Merge remote-tracking branch 'origin/main' into fix/r9-precache-bound-diagnostics
frontend-quality-gates / merge / static checks (pull_request) Successful in 1m44s
frontend-quality-gates / merge / tests (pull_request) Successful in 17m15s
frontend-quality-gates / merge / browser tests (pull_request) Successful in 6m19s
frontend-quality-gates / FE-GATE-017 / diagram-review (pull_request) Skipped
frontend-quality-gates / main / self-tests and removal drills (pull_request) Skipped
frontend-quality-gates / FE-GATE-014 / config-compatibility (pull_request) Skipped
frontend-quality-gates / FE-GATE-028 / manual-accessibility-review (pull_request) Skipped
frontend-quality-gates / FE-GATE-026 / lab-performance (pull_request) Skipped
frontend-quality-gates / FE-GATE-015 / immutable-release-candidate (pull_request) Skipped
frontend-quality-gates / external-vulnerability-provider (pull_request) Skipped
frontend-quality-gates / external-provenance-provider (pull_request) Skipped
frontend-quality-gates / promote-verified-immutable-candidate (pull_request) Skipped
frontend-quality-gates / deploy-promoted-release (pull_request) Skipped
frontend-quality-gates / FE-GATE-019 / hosting-header (pull_request) Skipped
frontend-quality-gates / FE-GATE-021 / runbook-boot-config (pull_request) Skipped
frontend-quality-gates / FE-GATE-022 / runbook-chunk-mismatch (pull_request) Skipped
frontend-quality-gates / FE-GATE-023 / runbook-api-degradation (pull_request) Skipped
frontend-quality-gates / FE-GATE-024 / runbook-telemetry (pull_request) Skipped
frontend-quality-gates / FE-GATE-025 / runbook-release-rollback (pull_request) Skipped
frontend-quality-gates / FE-GATE-018 / field-web-vitals (pull_request) Skipped

This commit is contained in:
DongHyeonka
2026-11-13 15:04:13 +09:00
47 changed files with 1825 additions and 217 deletions
+1 -1
View File
@@ -51,7 +51,7 @@ paths:
폼
- [ ] label·설명·오류가 같은 ID 체계와 `aria-describedby`로 연결된다(M5). required는 기호와 programmatic 상태를 함께 가진다. 제출 실패 시 오류 요약으로 포커스가 간다. — DS 8.3절
- [ ] label·설명·오류가 같은 ID 체계와 `aria-describedby`로 연결된다(M5). required는 기호와 programmatic 상태를 함께 가진다. 입력 오류로 제출이 실패하면 첫 오류 필드로 포커스가 가고, 오류 요약은 그 필드들로 가는 링크다(`src/presentation/forms/use-app-form.ts` `focusFirstError`). 입력 오류가 아닌 실패는 feedback 자리가 포커스를 받는다. — DS 8.3절
- [ ] IME 조합 중에 검증하거나 제출하지 않는다. — DS 8.1절
시각
+1 -1
View File
@@ -58,7 +58,7 @@ paths:
폼
- [ ] label·설명·오류가 연결되고, 제출 실패 시 오류 요약으로 포커스가 가며, 요약 항목은 그 필드로 간다. — `docs/design/2026-07-26-design-system-platform-design.md` 8.3절
- [ ] label·설명·오류가 연결되고, 입력 오류로 제출이 실패하면 첫 오류 필드로 포커스가 가며, 오류 요약 항목은 그 필드로 간다(`src/presentation/forms/use-app-form.ts` `focusFirstError`). — `docs/design/2026-07-26-design-system-platform-design.md` 8.3절
- [ ] 409를 검증 오류로 위장하지 않는다. 이탈 확인(`useDirtyNavigationGuard`)은 성공 저장 뒤 풀고 이동한다. — `docs/design/2026-07-26-typescript-state-and-data-flow-design.md` 8절, `docs/design/2026-07-26-routing-pages-and-patterns-design.md` 6.4절
- [ ] 자동 완성·IME·붙여넣기·비밀번호 관리자를 막지 않는다. 입력을 loading skeleton으로 덮지 않는다. — data-flow 8절
+73
View File
@@ -41,10 +41,34 @@ jobs:
if: ${{ gitea.event_name != 'workflow_dispatch' || (inputs.stage != 'documentation' && inputs.stage != 'main') }}
runs-on: ubuntu-latest
timeout-minutes: 45
env:
COREPACK_HOME: /tmp/fe-dependency-cache/corepack
PNPM_CONFIG_STORE_DIR: /tmp/fe-dependency-cache/pnpm-store
PNPM_CONFIG_CACHE_DIR: /tmp/fe-dependency-cache/pnpm-cache
steps:
- uses: https://github.com/actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5
with:
persist-credentials: false
- name: Restore and save the dependency cache
if: ${{ gitea.ref == 'refs/heads/main' }}
uses: https://github.com/actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830
with:
path: |
/opt/hostedtoolcache/node
/tmp/fe-dependency-cache
key: fe-dependencies-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('.nvmrc', 'pnpm-lock.yaml') }}
restore-keys: |
fe-dependencies-${{ runner.os }}-${{ runner.arch }}-
- name: Restore the dependency cache
if: ${{ gitea.ref != 'refs/heads/main' }}
uses: https://github.com/actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830
with:
path: |
/opt/hostedtoolcache/node
/tmp/fe-dependency-cache
key: fe-dependencies-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('.nvmrc', 'pnpm-lock.yaml') }}
restore-keys: |
fe-dependencies-${{ runner.os }}-${{ runner.arch }}-
- uses: https://github.com/actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020
with:
node-version-file: .nvmrc
@@ -85,10 +109,34 @@ jobs:
# FE-GATE-013 runner requirement: unprivileged user and network namespaces for bwrap (the provider sandbox runs bwrap --unshare-pid --unshare-ipc --unshare-uts --unshare-net); Ubuntu 23.10 and later refuse them while kernel.apparmor_restrict_unprivileged_userns=1 unless /usr/bin/bwrap has an AppArmor profile that allows userns; scripts/check-system-test-prerequisites.ts probes this before test:system runs and scripts/run-and-validate-provider.ts before a provider runs
runs-on: ubuntu-latest
timeout-minutes: 45
env:
COREPACK_HOME: /tmp/fe-dependency-cache/corepack
PNPM_CONFIG_STORE_DIR: /tmp/fe-dependency-cache/pnpm-store
PNPM_CONFIG_CACHE_DIR: /tmp/fe-dependency-cache/pnpm-cache
steps:
- uses: https://github.com/actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5
with:
persist-credentials: false
- name: Restore and save the dependency cache
if: ${{ gitea.ref == 'refs/heads/main' }}
uses: https://github.com/actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830
with:
path: |
/opt/hostedtoolcache/node
/tmp/fe-dependency-cache
key: fe-dependencies-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('.nvmrc', 'pnpm-lock.yaml') }}
restore-keys: |
fe-dependencies-${{ runner.os }}-${{ runner.arch }}-
- name: Restore the dependency cache
if: ${{ gitea.ref != 'refs/heads/main' }}
uses: https://github.com/actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830
with:
path: |
/opt/hostedtoolcache/node
/tmp/fe-dependency-cache
key: fe-dependencies-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('.nvmrc', 'pnpm-lock.yaml') }}
restore-keys: |
fe-dependencies-${{ runner.os }}-${{ runner.arch }}-
- uses: https://github.com/actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020
with:
node-version-file: .nvmrc
@@ -131,10 +179,33 @@ jobs:
image: "mcr.microsoft.com/playwright:v1.62.0-noble@sha256:baed2032d533817f3dbe6425de795788430ba345e819a1201337009ba17c9d07"
env:
CI_RUNNER_IMAGE: "mcr.microsoft.com/playwright:v1.62.0-noble@sha256:baed2032d533817f3dbe6425de795788430ba345e819a1201337009ba17c9d07"
COREPACK_HOME: /tmp/fe-dependency-cache/corepack
PNPM_CONFIG_STORE_DIR: /tmp/fe-dependency-cache/pnpm-store
PNPM_CONFIG_CACHE_DIR: /tmp/fe-dependency-cache/pnpm-cache
steps:
- uses: https://github.com/actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5
with:
persist-credentials: false
- name: Restore and save the dependency cache
if: ${{ gitea.ref == 'refs/heads/main' }}
uses: https://github.com/actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830
with:
path: |
/opt/hostedtoolcache/node
/tmp/fe-dependency-cache
key: fe-dependencies-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('.nvmrc', 'pnpm-lock.yaml') }}
restore-keys: |
fe-dependencies-${{ runner.os }}-${{ runner.arch }}-
- name: Restore the dependency cache
if: ${{ gitea.ref != 'refs/heads/main' }}
uses: https://github.com/actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830
with:
path: |
/opt/hostedtoolcache/node
/tmp/fe-dependency-cache
key: fe-dependencies-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('.nvmrc', 'pnpm-lock.yaml') }}
restore-keys: |
fe-dependencies-${{ runner.os }}-${{ runner.arch }}-
- uses: https://github.com/actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020
with:
node-version-file: .nvmrc
@@ -166,6 +237,8 @@ jobs:
if: ${{ startsWith(gitea.ref, 'refs/tags/v') || (gitea.event_name == 'workflow_dispatch' && (inputs.stage == 'release' || inputs.stage == 'production' || inputs.stage == 'field')) }}
runs-on: ubuntu-latest
timeout-minutes: 45
env:
RELEASE_TAG: "${{ startsWith(gitea.ref, 'refs/tags/v') && gitea.ref_name || '' }}"
strategy:
fail-fast: false
matrix:
+3 -1
View File
@@ -21,14 +21,16 @@ Gitea runner에서 merge 단계를 초록으로 만들고, worker를 늘리지
- merge / browser tests job이 Playwright 공식 이미지(`config/ci/gates.json`의 `browser-install.image`, digest 고정)에서 돈다. `@playwright/test`를 올릴 때 이 digest도 같은 버전으로 바꾼다(`tests/unit/ci-browser-image.test.ts`가 막는다).
- devDependencies에서 `dependency-cruiser`가 빠진다. 그 CLI를 따로 쓰고 있었으면 다시 더한다.
- 선택 runtime 제거 드릴 셋이 merge의 FE-GATE-020에서 main 단계의 새 게이트 FE-GATE-030으로 옮는다. main job 이름이 `main / self-tests and removal drills`로 바뀐다. 그 이름을 필수 검사로 걸었으면 바꾼다. 선택 runtime을 바꾸는 PR은 `scripts/verify.sh gate FE-GATE-030`을 직접 돌린다.
- merge job 셋이 runner의 actions/cache 저장소에서 Node·corepack·pnpm store와 메타데이터 캐시를 복원하고, main run만 저장한다. runner에 캐시 서버가 없으면 복원 단계가 경고만 내고 설치가 그대로 돈다. 자기 runner의 캐시 크기 상한을 확인한다(항목 하나가 압축 전 약 0.7GB, lockfile이 바뀔 때마다 새 항목).
### 보안·계약 변경
| 표시 | 변경 | 영향 경로 | 커밋 |
| --- | --- | --- | --- |
| [계약] | 게이트 필드 `hostEnvironment`(`"system-container"`)를 더한다. 생성기와 `scripts/verify.sh`가 그 게이트를 `scripts/run-in-system-container.sh`로 감싸고, 실행 검사는 계약이 정한 접두어로 돈 줄만 센다. FE-GATE-013에 준다 | `config/ci/gates.json`, `scripts/contracts/ci-gates.ts`, `scripts/generate-ci-workflow.ts`, `scripts/verify.sh`, `scripts/run-in-system-container.sh`, `config/ci/system-container.Dockerfile` | `1d3eb901` |
| [계약] | 게이트 FE-GATE-030 `optional-removability`(main 단계)를 더하고 FE-GATE-020에서 선택 runtime 제거 드릴 셋을 옮긴다. 정규 게이트 ID는 001..030, MAIN_READY는 029·030, 계약 보고서 `gateCount`는 29다(소유자 결정 2026-11-12) | `config/ci/gates.json`, `scripts/contracts/ci-gates.ts`, `scripts/lib/promotion-readiness.ts`, `scripts/lib/ci-contract-report.ts`, `scripts/lib/feature-scaffold-drill.ts` | `8de1403b` |
| [계약] | 게이트 FE-GATE-030 `optional-removability`(main 단계)를 더하고 FE-GATE-020에서 선택 runtime 제거 드릴 셋을 옮긴다. 정규 게이트 ID는 001..030, MAIN_READY는 029·030, 계약 보고서 `gateCount`는 29다(권하는 안으로 정함 2026-11-12, 총괄) | `config/ci/gates.json`, `scripts/contracts/ci-gates.ts`, `scripts/lib/promotion-readiness.ts`, `scripts/lib/ci-contract-report.ts`, `scripts/lib/feature-scaffold-drill.ts` | `8de1403b` |
| [계약] | `browser-install` 단계에 `image`(Playwright 레지스트리 noble 태그 + digest)를 더한다. 생성기는 그 job의 container와 job env `CI_RUNNER_IMAGE`로 그리고, 단계는 글꼴만 설치한다. gate-sequence job에만 둔다 | 같은 파일, `tests/unit/ci-browser-image.test.ts` | `92abfd20` |
| [계약] | job 단계 `dependency-cache`와 CI action `cache`(actions/cache v4.3.0, 짝 백엔드와 같은 pin)를 더한다. merge job 셋에만 두고(계약이 다른 job을 거절), 생성기가 main 복원·저장과 그 밖 복원만 두 단계, job env `COREPACK_HOME`·`PNPM_CONFIG_STORE_DIR`·`PNPM_CONFIG_CACHE_DIR`로 그린다. `scripts/run-in-system-container.sh`가 그 store와 메타데이터 캐시를 컨테이너에 넘긴다(권하는 안으로 정함 2026-11-13, 총괄) | `config/ci/gates.json`, `scripts/contracts/ci-gates.ts`, `scripts/generate-ci-workflow.ts`, `scripts/run-in-system-container.sh`, `.gitea/workflows/quality-gates.yml` | `7ed0af3d` |
### 그 밖의 변경
+18 -1
View File
@@ -1993,6 +1993,9 @@
"commandIds": [
"review-a11y-manual"
],
"requiresEnvironment": [
"RELEASE_TAG"
],
"logArtifactId": "artifact-artifacts-quality-gates-FE-GATE-028-txt",
"evidenceArtifactIds": [
"artifact-docs-accessibility-route-reviews-APP-HOME-md",
@@ -2158,6 +2161,9 @@
{
"kind": "checkout"
},
{
"kind": "dependency-cache"
},
{
"kind": "setup-node"
},
@@ -2199,6 +2205,9 @@
{
"kind": "checkout"
},
{
"kind": "dependency-cache"
},
{
"kind": "setup-node"
},
@@ -2239,6 +2248,9 @@
{
"kind": "checkout"
},
{
"kind": "dependency-cache"
},
{
"kind": "setup-node"
},
@@ -2282,7 +2294,12 @@
"browserGateIds": [
"FE-GATE-026"
],
"environment": [],
"environment": [
{
"name": "RELEASE_TAG",
"value": "${{ startsWith(gitea.ref, 'refs/tags/v') && gitea.ref_name || '' }}"
}
],
"steps": [
{
"kind": "checkout"
+4 -3
View File
@@ -28,7 +28,8 @@
"agent-harness": "에이전트 하네스 파일(tests/unit/template-contract-documents.test.ts)",
"feature-typecheck": "기능 코드와 기능 시험을 타입 검사하는 tsconfig(tests/unit/manual-code-blocks.test.ts)",
"product-typecheck": "제품 사본을 타입 검사하는 tsconfig(tests/unit/product-extension-typecheck.test.ts)",
"app-typecheck": "앱 프로그램 tsconfig와 그 기반 설정(tests/unit/two-feature-install-typecheck.test.ts)"
"app-typecheck": "앱 프로그램 tsconfig와 그 기반 설정(tests/unit/two-feature-install-typecheck.test.ts)",
"dependency-cache-key": "merge job 의존성 캐시의 키를 정하는 입력(scripts/contracts/ci-gates.ts의 DEPENDENCY_CACHE)"
},
"entries": [
{
@@ -105,7 +106,7 @@
"kind": "tool-convention",
"role": "Node 버전",
"readBy": "nvm, CI",
"sets": ["fixture-copy", "secret-scan"]
"sets": ["fixture-copy", "secret-scan", "dependency-cache-key"]
},
{
"path": ".release",
@@ -285,7 +286,7 @@
"kind": "tool-convention",
"role": "잠금 파일",
"readBy": "pnpm, 공급망 생성",
"sets": ["fixture-copy", "secret-scan", "scale-source", "package-manifest"]
"sets": ["fixture-copy", "secret-scan", "scale-source", "package-manifest", "dependency-cache-key"]
},
{
"path": "pnpm-workspace.yaml",
+4
View File
@@ -73,3 +73,7 @@ React Hook Form과 Zod resolver를 평가한다.
rollback 시 reference page는 이전 직접 form/layout으로 돌아갈 수 있다.
application input과 outbound gateway 계약은 유지되며, form facade와 template
commit은 독립적으로 되돌릴 수 있다.
## 보완
- 2026-11-12: 결정 5(409 conflict는 validation으로 바꾸지 않는다)는 기능이 선언하지 않은 409에 적용된다. 기능이 `useAppForm`의 `refusalMessages`로 선언한 쓰기 전 거절은 409라도 기능의 문구로 필드나 오류 요약에 보이고, 폼은 다음 저장을 받는다(1103/03-01, 매뉴얼 02 결정표 4절). 그 밖의 409는 그대로 충돌이고, `mutation` 옵션을 준 폼은 그 안내를 입력 오류 요약이 아니라 `FormSaveFeedback`에 보인다(1112/04-02).
+1
View File
@@ -579,6 +579,7 @@ export function useInvoiceListFilters(): InvoiceListSearch {
- 페이지 템플릿. [02 결정표 6절](02-decision-tables.md#6-페이지-템플릿)
- 쓰기가 있으면 결과 불명 화면. `AsyncSurface`의 `onReconcileUnknownEffect`(확인), `onResendUnknownEffect`(같은 키로 다시 보내기). 다시 보내기 버튼은 다시 보내도 되는 요청(`KEYED`, `IDEMPOTENT`. 뮤테이션 정책의 `resendSafe`)에만 그려진다. `NEVER` 쓰기는 확인만 남는다. 폼 밖에서 `mutation.submit`을 부르는 화면도 `NEVER` 쓰기의 같은 입력을 다시 보낼 수 없다. 훅이 `DUPLICATE_IN_FLIGHT`(code `UNKNOWN_EFFECT_PENDING`)로 거절한다. `AsyncSurface`에 손으로 만든 상태를 넘기면 재전송 버튼은 그려지지 않는다(코디네이터의 `state`를 넘긴다).
- 폼으로 저장하면 결과 불명 화면을 직접 잇지 않는다. `useAppForm`에 `mutation`과 저장 뒤 할 일(`onSaved`)을 주고 피드백 자리에 `FormSaveFeedback`을 둔다. 확인·재전송, 결과 불명 동안 새 저장 막기, 페이지를 떠난 뒤 끝난 저장이 아무 데도 옮기지 않는 것을 폼이 맡는다.
- 폼이면 서버 필드 오류를 받을 필드(`useAppForm`의 `allowedServerFields`). 짝 백엔드는 필드 검증 거절을 400 `VALIDATION_FAILED`와 `details[{field, code}]`로 보낸다(422가 아니다). 공유 MSW 시나리오에는 짝 백엔드가 보내지 않는 `validation-422`만 있고, Envelope operation에서 그 답은 결과 불명이다. 짝 백엔드 모양의 필드 오류 테스트는 생성된 작성 폼 테스트(`<base>-create-page.test.tsx`)처럼 400 본문을 손으로 적는다.
② **기준**
+1 -1
View File
@@ -185,7 +185,7 @@ context는 URL 앞부분 하나(라우트 루트)를 가진다. 그 아래 기
- 적을 수 없는 code: `IDEMPOTENT_*`, `IDEMPOTENCY_*`. 멱등성 응답은 백엔드 표가 정한다. 적으면 계약 조립이 `refusedBeforeWrite cannot declare ...`로 거부한다. `responseEnvelope: "ENVELOPE_V1"`가 아닌 operation에 적어도 거부한다(`refusedBeforeWrite needs responseEnvelope ENVELOPE_V1 ...`).
- 계약 문서 6.1절이 "쓰기 뒤 가능"으로 둔 플랫폼 code(`BAD_PARAMETER`, `MAPPING_FAILED`, `DB_UNIQUE_VIOLATION` 등 `DB_*`, `LOCK_ACQUISITION_TIMEOUT`, fileserver code)도 적을 수 없다. 폼을 막는 400 `BAD_PARAMETER`나 409 `DB_UNIQUE_VIOLATION`은 어느 층에서든, 트랜잭션 안에서도 나온다. 적으면 계약 조립이 `refusedBeforeWrite cannot declare ...; contract 6.1 reads this platform code as possibly raised after the write`로 거부한다.
- 거절 이유를 필드 옆에 보이려면 `mapProblem`이 그 code를 `VALIDATION_REJECTED`와 필드 목록으로 돌려준다. 선언 없이 `mapProblem`만 두면 필드 오류는 보이지만 저장 버튼은 꺼진 채다.
- 거절 이유를 기능의 말로 보이려면 `useAppForm`의 `refusalMessages`에 code별로 기능 catalog의 메시지 키와 필드를 적는다(예: `{ POSTER_ALREADY_EXISTS: { field: "name", message: "poster.form.nameTaken" } }`). 적용 안 됨(`NOT_APPLIED`)으로 끝난 실패만 읽는다. 그 code는 필드 오류(필드가 없으면 오류 요약)가 되고, 결과는 `validation-error`다. 적지 않으면 선언한 400은 "요청을 처리할 수 없습니다" + 지원 안내, 409는 충돌 문구가 보인다. 결과 불명은 code와 상관없이 결과 불명으로 남는다.
- 거절 이유를 기능의 말로 보이려면 `useAppForm`의 `refusalMessages`에 code별로 기능 catalog의 메시지 키와 필드를 적는다(예: `{ POSTER_ALREADY_EXISTS: { field: "name", message: "poster.form.nameTaken" } }`). 적용 안 됨(`NOT_APPLIED`)으로 끝난 실패만 읽는다. 그 code는 필드 오류(필드가 없으면 오류 요약)가 되고, 결과는 `validation-error`다. 적지 않으면 선언한 400은 "요청을 처리할 수 없습니다" + 지원 안내, 409는 충돌 문구가 보인다. 결과 불명은 code와 상관없이 결과 불명으로 남는다. 필드 이름이 붙은 실패라도 결과 불명(`MAYBE_APPLIED`)이면 필드 오류가 아니라 결과 불명으로 보인다. 같은 키 재전송이 쓰기 전에 거절되면, `mutation`을 준 폼은 그 안내를 입력 오류 요약이 아니라 결과 불명 표면(`FormSaveFeedback`)에 보인다.
**503 `IDEMPOTENCY_UNAVAILABLE`는 `NOT_APPLIED`로 분류하지 않는다.**
+2 -2
View File
@@ -96,7 +96,7 @@ const search = (q: string) =>
| 쿼리 바인딩 | `src/contracts/server-state.ts`의 `bindQuery`, `src/presentation/adapters/query/application-query.ts` | 생성 뼈대 `presentation/use-<base>-items.ts` | profile ID (실행 때). `owner`·`operationId`는 읽는 곳이 없는 `@deprecated` 칸이라 적지 않는다 |
| 무효화 topic | `src/contracts/query-invalidation.ts` | 생성 뼈대 계약 `invalidation` | 조립(중복, 고아 topic) |
| 멱등 키 쓰기 | V3 `retrySemantics: "KEYED"`, `commandRecovery`, 뮤테이션 정책(`src/contracts/server-state.ts`의 `commandMutationIdentity`로 operation ID와 키 여부를 descriptor에서 받는다) | 쓰기 slice `--keyed`(`contracts/<base>-contract-contribution.ts`, `presentation/use-<base>-create.ts`) | 계약 조립(복구 descriptor 필수), 타입(descriptor 상수 이름, 손으로 적은 operation ID는 `MutationOperationId`가 아니다), 기능 테스트 |
| 결과 불명 화면 | `src/presentation/components/async-surface.tsx`의 `onReconcileUnknownEffect`, `onResendUnknownEffect` | 쓰기 slice `presentation/<base>-create-page.tsx` | 기능 테스트만(쓰기 slice는 `<base>-create-page.test.tsx`) |
| 결과 불명 화면 | `src/presentation/components/async-surface.tsx`의 `onReconcileUnknownEffect`, `onResendUnknownEffect`. 폼으로 저장하면 아래 「폼」 행의 `FormSaveFeedback`이 이 둘을 잇는다 | 쓰기 slice `presentation/<base>-create-page.tsx` | 기능 테스트(쓰기 slice는 `<base>-create-page.test.tsx`), `tests/component/form-foundation.test.tsx` |
| 수정·삭제 명령 | 같은 V3 계약 (`PUT`, `PATCH`, `DELETE`) | 없음 (쓰기 slice는 작성 명령만 만든다) | — |
| 낙관적 갱신 | `useApplicationMutation`의 `optimistic` 옵션 (`application-query.ts`) | 없음 | 런타임 테스트만 |
| 페이지 넘김 | `src/adapters/query-cache/index.ts`의 `createCursorPaginationRuntime` | 없음 (생성 뼈대 목록은 첫 페이지와 `meta.page.total`만 읽는다) | 런타임 테스트만 |
@@ -108,7 +108,7 @@ const search = (q: string) =>
|---|---|---|---|
| 페이지 템플릿 | `src/presentation/templates/page-templates.tsx` | 생성 뼈대 `CollectionPage`, 쓰기 slice `DetailPage`·`FormPage` | `page-templates-own-layout-only` |
| 비동기 상태 화면 | `src/presentation/components/async-surface.tsx`의 `AsyncSurface` | 생성 뼈대 목록 페이지 | 페이지 테스트 |
| 폼 | `src/presentation/forms/use-app-form.ts`의 `useAppForm` | 쓰기 slice `presentation/<base>-form.ts`와 `<base>-create-page.tsx` | 페이지 테스트(서버 필드 오류, 이탈 확인) |
| 폼 | `src/presentation/forms/use-app-form.ts`의 `useAppForm`. mutation으로 저장하는 폼은 `mutation` 옵션을 주고 피드백 자리에 `FormSaveFeedback`(`src/presentation/forms/form-components.tsx`)을 둔다. 결과 불명 동안 새 저장 막기, 「변경됨으로 확인」, 같은 키 재전송, 다른 저장이 도는 동안의 표시, 마운트된 동안만 저장 뒤 이동(`onSaved`, `FormSaveFeedback`의 `onConfirmed`)을 폼이 맡는다 | 쓰기 slice `presentation/<base>-form.ts`와 `<base>-create-page.tsx` | 페이지 테스트(서버 필드 오류, 이탈 확인), `tests/component/form-foundation.test.tsx` |
| 화면 문구 | `src/presentation/i18n/index.ts`, 기능 문구 catalog | 생성 뼈대 `contracts/<base>-message-catalog.ts` | `lint`(문구 literal), `check:i18n`(ko-KR·en-US 키) |
| 권한 분기 | 라우트 `access`, 서버 403 → 실패 | 코드 조각: [01 문서 10단계](../01-add-a-feature.md#10단계-테스트)의 403 페이지 테스트 `tests/features/<id>/<base>-forbidden.test.tsx` | 가드 테스트. 역할·권한 힌트 예제는 없음 |
+17 -2
View File
@@ -8,10 +8,21 @@
출력을 거절한다. `corepack pnpm check:ci`는 산출물 schema 검사, 타입이 있는 계약 검사기,
이 workflow drift 검사를 돈다. merge 단계는 job 셋(`merge_static`, `merge_test`,
`merge_browser`)으로 돌고 job마다 설치를 한 번 한다. 게이트마다 ID 이름의 step이 하나씩
있고, 실패한 게이트가 다음 게이트를 건너뛰게 하지 않는다. 검사기 자신의 음성 fixture와
있고, 실패한 게이트가 다음 게이트를 건너뛰게 하지 않는다.
merge job 셋만 의존성 캐시를 쓴다(권하는 안으로 정함 2026-11-13, 총괄). setup-node 앞에서
Node toolcache, corepack이 받은 pnpm, pnpm store와 메타데이터 캐시를 `.nvmrc`와
`pnpm-lock.yaml` 해시 키로 복원한다. 저장은 main run만 한다. 캐시 항목은 다음 run이 믿는
입력이다. pnpm은 같은 lockfile의 공급망 검증 기록이 캐시에 있으면 검증을 다시 하지 않는다.
그래서 브랜치 run은 복원만 한다. frozen install은 캐시가 맞든 없든 늘 돈다. 항목이 없거나
깨지면 pnpm이 모자란 패키지만 내려받고 node_modules는 같다. FE-GATE-013의 시스템 컨테이너도
같은 store와 메타데이터 캐시를 받는다. release·promotion·provider job은 공급망 증거를
만들므로 매번 새로 설치한다. 이 규칙은 `scripts/contracts/ci-gates.ts`의 `DEPENDENCY_CACHE`와
계약 검사가 지킨다. runner의 캐시 저장소는 짝 백엔드와 함께 쓰고 크기 상한이 있다(platform-core
`infrastructure/ci/gitea-runner/config.yaml`). 검사기 자신의 음성 fixture와
gating 검사는 branch에 push한 뒤 main 단계(`main_gate`, FE-GATE-029)에서 돈다. 선택 runtime
제거 드릴 셋(FE-GATE-030)도 main 단계에서 돈다. PR runner 시간 약 30분 가운데 7분쯤이라
merge에서 뺐고, 실패하면 main이 빨강이 되어 다음 PR이 고친다(소유자 결정 2026-11-12). release와
merge에서 뺐고, 실패하면 main이 빨강이 되어 다음 PR이 고친다(권하는 안으로 정함 2026-11-12, 총괄). release와
production 게이트는 matrix check로 남는다. 실패를 무시하는(soft-fail) 연결은 없다.
같은 PR이나 같은 브랜치에 새 push가 오면 workflow `concurrency`가 앞 run을 취소한다. Gitea는
앞 run의 대기 중인 job은 언제나, 돌고 있는 job은 `cancel-in-progress`가 참일 때 취소한다.
@@ -137,6 +148,10 @@ full commit ID와 commit timestamp를 한 번 읽어 `SOURCE_DATE_EPOCH`를 유
release manifest도 같은 build ID, commit SHA, release ID와 timestamp를 가져야
한다.
`release_gate` job은 tag run이면 그 tag 이름(예 `v1.4.0`)을 `RELEASE_TAG`로 준다.
FE-GATE-028이 이 값을 요구한다(`requiresEnvironment`). tag run이 아니면(브랜치에서 수동으로
돌린 release 단계) 값이 비어 게이트가 `missing required environment: RELEASE_TAG`로 실패한다.
Release tier의 `immutable_build`는 `dist`의 hidden `.vite` entries, raw
`pnpm-lock.yaml`, build/module inventory와 local release/security evidence를 한
번 생성해 run ID/attempt로 구분된 archive로 게시한다. Raw lock bytes의 SHA-256은
+2 -1
View File
@@ -70,7 +70,8 @@
| round9 R9-D10 예산과 advisory | 2026-11-12 | 권하는 안으로 정함(2026-11-12, 총괄). D1을 먼저 정한다: zod·react-router 갱신이 지금 초기 JS 예산 안에 들어가므로 갱신하고, 드릴을 다시 재서 D9 규칙으로 예산을 정한다. 버린 안: 예산만 먼저 내림 | 같음, 1106/15-01, 1103/13-03 |
| round9 R9-D11 `@a11y` 두 번 실행 | 2026-11-12 | 권하는 안으로 정함(2026-11-12, 총괄). 그대로 둔다. 게이트마다 증거를 새로 만드는 계약이다. 결함 아님으로 닫는다. 버린 안: FE-GATE-009가 FE-GATE-008 결과를 쓰기 | 같음, 1112/03-10 |
| round9 R9-D12 CSS·라우트 lazy 합 예산 | 2026-11-12 | 권하는 안으로 정함(2026-11-12, 총괄). 지금 값을 기록만 하고 예산은 두지 않는다. 다시 볼 때: 첫 공개 기능 라우트 lab. 버린 안: 예산 신설 | 같음, 1101/15-03 |
| 결정 p 선택 runtime 제거 드릴을 main 단계로 | 2026-11-12 | FE-GATE-020의 선택 runtime 제거 드릴 셋(optional recipe, browser file/storage, realtime)을 새 게이트 FE-GATE-030으로 떼어 main 단계(`main_gate`)에서 돌린다. 기능 드릴(샘플 제거, scaffold)은 merge에 남는다. 이유: runner PR 1회 약 30분 가운데 7분쯤이고, worker를 늘리지 않고 merge 25분 목표에 닿는 길이 이것뿐이었다. 대가: 그 셋의 회귀를 병합 뒤 main run에서 본다. main이 빨강이면 다음 PR이 고친다. 짝 백엔드가 무거운 lane을 nightly로 옮긴 것과 같은 모양이다. 재검토: runner가 늘거나 드릴이 빨라져 merge에 다시 넣어도 25분 안이면 되돌린다 | 소유자 결정 p(2026-11-12, design-docs `template-program/README.md` 5절, W2-FE의 O1 권하는 안 채택) |
| 결정 p 선택 runtime 제거 드릴을 main 단계로 | 2026-11-12 | FE-GATE-020의 선택 runtime 제거 드릴 셋(optional recipe, browser file/storage, realtime)을 새 게이트 FE-GATE-030으로 떼어 main 단계(`main_gate`)에서 돌린다. 기능 드릴(샘플 제거, scaffold)은 merge에 남는다. 이유: runner PR 1회 약 30분 가운데 7분쯤이고, worker를 늘리지 않고 merge 25분 목표에 닿는 길이 이것뿐이었다. 대가: 그 셋의 회귀를 병합 뒤 main run에서 본다. main이 빨강이면 다음 PR이 고친다. 짝 백엔드가 무거운 lane을 nightly로 옮긴 것과 같은 모양이다. 재검토: runner가 늘거나 드릴이 빨라져 merge에 다시 넣어도 25분 안이면 되돌린다 | 권하는 안으로 정함(2026-11-12, 총괄): 백엔드 nightly lane과 같은 모양(design-docs `template-program/README.md` 5절 p, w2-fe-2가 올린 O1) |
| 의존성 캐시는 merge job만 | 2026-11-13 | merge job 셋(`merge_static`·`merge_test`·`merge_browser`)만 Node toolcache·corepack·pnpm store와 메타데이터 캐시를 `.nvmrc`·`pnpm-lock.yaml` 해시 키로 복원하고, 저장은 main run만 한다. release·promotion·provider job은 공급망 증거를 만들므로 매번 새로 설치한다. 이유: worker를 늘리지 않고 job마다 되풀이하던 내려받기와 공급망 검증 요청을 없앤다. 캐시가 없거나 깨져도 frozen install이 같은 node_modules를 만든다. 짝 백엔드의 JDK·Gradle·Trivy 캐시와 같은 저장 규칙이다. 버린 안: CI 이미지에 의존성을 굽기(레지스트리 쓰기 토큰이 든다). 규칙의 정본은 `scripts/contracts/ci-gates.ts`의 `DEPENDENCY_CACHE` | 권하는 안으로 정함(2026-11-13, 총괄): 의존성 캐시는 merge job만, 공급망 증거 job은 매번 새로 설치 |
| 구조·기술 결정 기록 | 2026-07-26~ | `VD-01`~(빈 번호 있음) | `docs/adr/` |
## 3. 결정 대기 쓰는 법
+1 -1
View File
@@ -114,7 +114,7 @@ src/ 최상위 폴더 ── 역할: docs/architecture/layers.md 표
## 12. 제거 가능성
지울 수 있는 단위는 드릴이 지킨다. 기능 드릴(샘플 제거, 생성 기능의 scaffold·제거)은 merge 게이트 FE-GATE-020, 선택 runtime 제거 드릴 셋(optional recipe, browser file/storage, realtime)은 main 단계 FE-GATE-030이다(소유자 결정 2026-11-12). 드릴 목록은 `config/ci/gates.json`의 두 게이트 `commandIds`다. 선택 runtime을 바꾼 PR은 merge에서 FE-GATE-030이 돌지 않으니 `scripts/verify.sh gate FE-GATE-030`을 직접 돌린다.
지울 수 있는 단위는 드릴이 지킨다. 기능 드릴(샘플 제거, 생성 기능의 scaffold·제거)은 merge 게이트 FE-GATE-020, 선택 runtime 제거 드릴 셋(optional recipe, browser file/storage, realtime)은 main 단계 FE-GATE-030이다(권하는 안으로 정함 2026-11-12, 총괄). 드릴 목록은 `config/ci/gates.json`의 두 게이트 `commandIds`다. 선택 runtime을 바꾼 PR은 merge에서 FE-GATE-030이 돌지 않으니 `scripts/verify.sh gate FE-GATE-030`을 직접 돌린다.
- 구조를 바꾸면 드릴을 돌린다. 드릴 fixture가 복사하는 목록(`scripts/lib/removal-fixture.ts`, 이 목록 하나만 쓴다)이 바뀐 구조를 아는지 본다. 그 목록에 `README.md`·`CHANGELOG.md`가 없어 드릴 넷 중 셋이 항상 실패한 일이 있다(결함 패턴 G11).
- 드릴은 오래 걸린다(desktop 2026-11-13 실측: FE-GATE-020과 FE-GATE-030 합쳐 약 10분 30초). desktop에서 잠금 아래 돌린다.
+68 -5
View File
@@ -4,6 +4,7 @@ import path from "node:path";
import { z } from "zod";
import { DEPENDENCY_ADVISORIES_RECORD_PATH } from "../lib/dependency-advisories.ts";
import { selectRepositoryPaths } from "../lib/repository-layout.ts";
import { PROMOTION_FORMULA } from "../lib/promotion-readiness.ts";
import {
RELEASE_CANDIDATE_EVIDENCE_PATHS,
@@ -39,6 +40,7 @@ const ciActionRegistrySchema = z
setupNode: ciActionRegistrationSchema,
uploadArtifact: ciActionRegistrationSchema,
downloadArtifact: ciActionRegistrationSchema,
cache: ciActionRegistrationSchema,
})
.strict()
.readonly();
@@ -78,6 +80,12 @@ export const CI_ACTION_REGISTRY = parseCiActionRegistry({
revision: "75635f32b4c1c41c4b3d64e8f85210112ed4c9c7",
version: "v4 branch",
},
// The same pin as the paired backend's JDK, Gradle and Trivy caches.
cache: {
repository: "https://github.com/actions/cache",
revision: "0057852bfaa89a56745cba8c7296529d2fc39830",
version: "v4.3.0",
},
});
const actionIdByStepKind = Object.freeze({
@@ -85,6 +93,7 @@ const actionIdByStepKind = Object.freeze({
"setup-node": "setupNode",
upload: "uploadArtifact",
download: "downloadArtifact",
"dependency-cache": "cache",
} as const satisfies Readonly<Record<string, CiActionId>>);
export function resolveCiActionUses(actionId: CiActionId): string {
@@ -93,6 +102,42 @@ export function resolveCiActionUses(actionId: CiActionId): string {
return `${action.repository}@${action.revision}`;
}
/** An action a registered repository holds below its root (`actions/cache/restore`), at the same pin. */
export function resolveCiSubActionUses(actionId: CiActionId, subpath: "restore"): string {
const action = CI_ACTION_REGISTRY[actionId];
if (!action) throw new TypeError(`unknown CI action: ${String(actionId)}`);
return `${action.repository}/${subpath}@${action.revision}`;
}
/**
* Decision (2026-11-13, lead): the dependency cache is for the merge jobs
* only; the jobs that produce supply-chain evidence install fresh every time
* (docs/work/reference/decisions.md). A merge job restores the Node toolcache, the corepack
* download and pnpm's store and metadata cache (with its record of the
* lockfile's supply-chain verification) before setup-node, keyed by
* `.nvmrc` and the lockfile. Only a run on main saves an entry, the paired
* backend's rule for its caches: an entry is trusted input to the next run
* (the verification record lets pnpm skip the check), so a branch must not
* write one. The frozen install always runs after it: a missing or damaged
* entry only makes pnpm download what it lacks, and node_modules is the same
* (desktop, 2026-11-13: cold 13.9 s, warm 1.6 s, 40 broken store and 40
* broken metadata files 3.6 s with 27 packages fetched again; the same tree
* hash in all five installs).
*/
export const DEPENDENCY_CACHE = Object.freeze({
keyPrefix: "fe-dependencies-${{ runner.os }}-${{ runner.arch }}-",
// `.nvmrc` and `pnpm-lock.yaml` (config/repository-layout.json).
keyInputs: selectRepositoryPaths("dependency-cache-key"),
paths: Object.freeze(["/opt/hostedtoolcache/node", "/tmp/fe-dependency-cache"] as const),
environment: Object.freeze([
Object.freeze({ name: "COREPACK_HOME", value: "/tmp/fe-dependency-cache/corepack" }),
Object.freeze({ name: "PNPM_CONFIG_STORE_DIR", value: "/tmp/fe-dependency-cache/pnpm-store" }),
Object.freeze({ name: "PNPM_CONFIG_CACHE_DIR", value: "/tmp/fe-dependency-cache/pnpm-cache" }),
]),
/** The jobs that may hold the step: the three merge jobs. */
jobIds: Object.freeze(["merge_static", "merge_test", "merge_browser"] as const),
});
export function resolveCiStepActionUses(stepKind: string): string | null {
const actionId = actionIdByStepKind[stepKind as keyof typeof actionIdByStepKind];
return actionId ? resolveCiActionUses(actionId) : null;
@@ -333,6 +378,7 @@ const environmentBindingSchema = z
const checkoutStep = z.object({ kind: z.literal("checkout") }).strict();
const setupNodeStep = z.object({ kind: z.literal("setup-node") }).strict();
const frozenInstallStep = z.object({ kind: z.literal("frozen-install") }).strict();
const dependencyCacheStep = z.object({ kind: z.literal("dependency-cache") }).strict();
/**
* `image`: the job runs in Playwright's own image for the pinned
* @playwright/test version, which already holds the browsers and their OS
@@ -405,6 +451,7 @@ const deployStep = z
const jobStepSchema = z.discriminatedUnion("kind", [
checkoutStep,
dependencyCacheStep,
setupNodeStep,
frozenInstallStep,
browserInstallStep,
@@ -817,6 +864,16 @@ function validateContractSemantics(
}
}
validateJobStepKinds(job, issue);
if (job.steps.some(({ kind }) => kind === "dependency-cache")) {
if (!(DEPENDENCY_CACHE.jobIds as readonly string[]).includes(job.id)) {
issue(`the dependency cache is for the merge jobs only: ${job.id}`);
}
for (const { name } of DEPENDENCY_CACHE.environment) {
if (job.environment.some((binding) => binding.name === name)) {
issue(`job ${job.id} binds ${name}, which its dependency cache sets`);
}
}
}
for (const step of job.steps) {
const uses = resolveCiStepActionUses(step.kind);
if (uses && !/^https:\/\/github\.com\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+@[0-9a-f]{40}$/u.test(uses)) {
@@ -910,9 +967,9 @@ function validateContractSemantics(
}
}
const expectedStepKinds: Readonly<Record<string, readonly CiWorkflowStep["kind"][]>> = {
merge_static: ["checkout", "setup-node", "frozen-install", "run-gate", "upload"],
merge_test: ["checkout", "setup-node", "frozen-install", "run-gate", "upload"],
merge_browser: ["checkout", "setup-node", "frozen-install", "browser-install", "run-gate", "upload"],
merge_static: ["checkout", "dependency-cache", "setup-node", "frozen-install", "run-gate", "upload"],
merge_test: ["checkout", "dependency-cache", "setup-node", "frozen-install", "run-gate", "upload"],
merge_browser: ["checkout", "dependency-cache", "setup-node", "frozen-install", "browser-install", "run-gate", "upload"],
release_gate: ["checkout", "setup-node", "frozen-install", "browser-install", "run-gate", "upload"],
immutable_build: ["checkout", "setup-node", "frozen-install", "run-gate", "archive-candidate", "upload", "upload"],
vulnerability_provider: ["checkout", "setup-node", "frozen-install", "download", "run-provider", "validate-provider-evidence", "upload"],
@@ -934,7 +991,13 @@ function validateContractSemantics(
merge_static: [],
merge_test: [],
merge_browser: [],
release_gate: [],
release_gate: [
// 1112/05-01 (R9-D7, release tag). FE-GATE-028 compares each signed
// record's Release ID with the tag being released. A run that is not a
// tag run (a release stage dispatched on a branch) gets an empty value,
// and run-ci-gate.ts fails the gate on it.
{ name: "RELEASE_TAG", value: "${{ startsWith(gitea.ref, 'refs/tags/v') && gitea.ref_name || '' }}" },
],
immutable_build: [
// FE-GATE-027 admits the built artifact to a named environment, so both
// the profile it was built from and the destination it is claimed for are
@@ -1324,7 +1387,7 @@ function validateJobStepKinds(
): void {
const allowed: Readonly<Record<z.infer<typeof jobSchema>["kind"], ReadonlySet<string>>> = {
"gate-matrix": new Set(["checkout", "setup-node", "frozen-install", "browser-install", "download", "extract", "run-gate", "upload"]),
"gate-sequence": new Set(["checkout", "setup-node", "frozen-install", "browser-install", "run-gate", "upload"]),
"gate-sequence": new Set(["checkout", "dependency-cache", "setup-node", "frozen-install", "browser-install", "run-gate", "upload"]),
"gate-single": new Set(["checkout", "setup-node", "frozen-install", "run-gate", "upload"]),
immutable: new Set(["checkout", "setup-node", "frozen-install", "run-gate", "archive-candidate", "upload"]),
provider: new Set(["checkout", "setup-node", "frozen-install", "download", "extract", "run-provider", "validate-provider-evidence", "upload"]),
+25 -81
View File
@@ -589,26 +589,21 @@ export default function ${pascal}DetailPage() {
export function renderCreatePage({ names, routeId, write }: SliceShape): string {
const { base, camel, pascal, upper } = names;
return `import { useCallback, useEffect, useRef } from "react";
import { Link, useNavigate } from "react-router-dom";
return `import { Link, useNavigate } from "react-router-dom";
import type { Result } from "../../../contracts/result.ts";
import {
AsyncSurface,
Button,
DirtyNavigationDialog,
ErrorSummary,
Form,
FormActions,
FormFailureStatus,
FormField,
FormPage,
FormSaveFeedback,
useAppForm,
useDirtyNavigationGuard,
} from "../../../presentation/design-system/index.ts";
import { useLocale } from "../../../presentation/i18n/index.ts";
import type { ${pascal}CreateCommand } from "../application/${base}-feature-api.ts";
import type { ${pascal}ItemView } from "../contracts/${base}-mapper.ts";
import {
${upper}_FORM_DEFAULTS,
${camel}FormSchema,
@@ -634,63 +629,29 @@ export default function ${pascal}CreatePage() {
name: message("${camel}.form.name"),
} satisfies Record<keyof ${pascal}FormValues, string>;
const mutation = use${pascal}Create();
// A save outlives this page when the user leaves while it runs. Ending
// then, it does not take them to its item or the list (1106/08-02).
const mounted = useRef(false);
useEffect(() => {
mounted.current = true;
return () => {
mounted.current = false;
};
}, []);
const openSaved = useCallback(
(outcome: Result<${pascal}ItemView> | null) => {
if (outcome?.ok && mounted.current) {
void navigate(
${camel}RouteUrl("${write.detail.routeId}", {
params: { ${write.idParam}: outcome.value.itemId },
}),
);
}
return outcome;
},
[navigate],
);
const submit = useCallback(
async (command: ${pascal}CreateCommand) => {
const outcome = await mutation.submit(command);
openSaved(outcome);
return outcome;
},
[mutation, openSaved],
);
// The form holds the rules of a save through the mutation: no new save
// while one is unknown or another runs, confirm and resend of an unknown
// one, and what the page does after a save only while it is still open
// (useAppForm \`mutation\` and \`onSaved\`, FormSaveFeedback).
const form = useAppForm({
schema: ${camel}FormSchema,
defaultValues: ${upper}_FORM_DEFAULTS,
allowedServerFields: ["name"],
mapToCommand: to${pascal}CreateCommand,
submit,
submit: mutation.submit,
mutation,
onSaved: (item) => {
void navigate(
${camel}RouteUrl("${write.detail.routeId}", {
params: { ${write.idParam}: item.itemId },
}),
);
},
});
const effectUnknown = mutation.state.indicator === "mutation-effect-unknown";
const blocked = effectUnknown || mutation.state.indicator === "mutation-pending";
// A save this form did not start holds the coordinator (one left running
// when the user came back, or the check behind "confirm applied"): the save
// is off and the feedback says a save is running (1105/08-04).
const otherSaveRunning = mutation.state.indicator === "mutation-pending" && !form.pending;
const guard = useDirtyNavigationGuard(form.dirty && !form.pending);
return (
<Form
id={form.formId}
pending={form.pending}
onSubmit={(event) => {
if (blocked) {
event.preventDefault();
return;
}
void form.submitForm(event);
}}
>
<Form id={form.formId} pending={form.pending} onSubmit={(event) => void form.submitForm(event)}>
<FormPage
feedbackId={form.feedbackId}
breadcrumb={<Link to={${camel}RouteUrl("${routeId}")}>{message("${camel}.list.title")}</Link>}
@@ -715,38 +676,21 @@ export default function ${pascal}CreatePage() {
type="submit"
pending={form.pending}
pendingLabel={message("${camel}.form.saving")}
disabled={effectUnknown || otherSaveRunning}
disabled={form.effectUnknown || form.otherSaveRunning}
>
{message("${camel}.form.save")}
</Button>
</FormActions>
}
feedback={
form.failure ? (
<FormFailureStatus
failure={form.failure}
onAction={form.result === "retry-later" ? () => void form.submitForm() : undefined}
/>
) : effectUnknown ? (
<AsyncSurface
state={mutation.state}
supportReference={form.supportReference}
// The list shows whether the item is there; the form alone
// would show nothing but an emptied input (1105/08-02).
onReconcileUnknownEffect={(resolution) => {
void mutation.reconcileUnknownEffect(resolution).then(() => {
form.settleApplied();
if (mounted.current) void navigate(${camel}RouteUrl("${routeId}"));
});
}}
// Drawn only for a request with a key (a KEYED command).
onResendUnknownEffect={() => {
void form.resendUnknown(async () => openSaved(await mutation.resendUnknownEffect()));
}}
/>
) : otherSaveRunning && form.result !== "effect-unknown" ? (
<AsyncSurface state={mutation.state} />
) : null
<FormSaveFeedback
form={form}
// The list shows whether the item is there; the form alone
// would show nothing but an emptied input (1105/08-02).
onConfirmed={() => {
void navigate(${camel}RouteUrl("${routeId}"));
}}
/>
}
guard={<DirtyNavigationDialog guard={guard} />}
/>
+33 -1
View File
@@ -11,9 +11,11 @@ import { fileURLToPath } from "node:url";
import path from "node:path";
import {
DEPENDENCY_CACHE,
indexCiGateContract,
loadCiGateContract,
resolveCiStepActionUses,
resolveCiSubActionUses,
type CiGateContract,
type CiWorkflowJob,
type CiWorkflowStep,
@@ -234,9 +236,16 @@ function renderJob(
const jobEnvironment = job.environment.filter((binding) => !isStepScopedSecret(job, binding));
// The build records the image it ran in (scripts/lib/build-environment.ts):
// a job in its own image names that one, not the runner label's.
// Every pnpm and corepack call of the job reads the cached directories, the
// install and the system container's own install alike.
const cacheEnvironment = job.steps.some(({ kind }) => kind === "dependency-cache")
? DEPENDENCY_CACHE.environment
: [];
const environmentLines = [
...(image ? [` CI_RUNNER_IMAGE: ${yamlScalar(image)}`] : []),
...jobEnvironment.map((binding) => ` ${binding.name}: ${yamlScalar(binding.value)}`),
...[...cacheEnvironment, ...jobEnvironment].map(
(binding) => ` ${binding.name}: ${yamlScalar(binding.value)}`,
),
];
if (environmentLines.length > 0) lines.push(" env:", ...environmentLines);
if (job.kind === "gate-matrix") {
@@ -316,6 +325,29 @@ function renderStep(
" with:",
" node-version-file: .nvmrc",
];
case "dependency-cache": {
// DEPENDENCY_CACHE: main restores and saves, every other ref restores.
// The frozen install after it runs either way.
const inputs = DEPENDENCY_CACHE.keyInputs.map((file) => `'${file}'`).join(", ");
const cache = [
" with:",
" path: |",
...DEPENDENCY_CACHE.paths.map((cachePath) => ` ${cachePath}`),
` key: ${DEPENDENCY_CACHE.keyPrefix}\${{ hashFiles(${inputs}) }}`,
" restore-keys: |",
` ${DEPENDENCY_CACHE.keyPrefix}`,
];
return [
" - name: Restore and save the dependency cache",
" if: ${{ gitea.ref == 'refs/heads/main' }}",
` uses: ${requiredStepActionUses(step.kind)}`,
...cache,
" - name: Restore the dependency cache",
" if: ${{ gitea.ref != 'refs/heads/main' }}",
` uses: ${resolveCiSubActionUses("cache", "restore")}`,
...cache,
];
}
case "frozen-install":
return [
" - name: Frozen install",
+1
View File
@@ -32,6 +32,7 @@ export const REPOSITORY_LAYOUT_SETS = Object.freeze([
"feature-typecheck",
"product-typecheck",
"app-typecheck",
"dependency-cache-key",
] as const);
export type RepositoryLayoutSet = (typeof REPOSITORY_LAYOUT_SETS)[number];
+13
View File
@@ -25,6 +25,15 @@ node_root=$(dirname "$(dirname "$(command -v node)")")
corepack_home=${COREPACK_HOME:-$HOME/.cache/node/corepack}
# The environment the gate reads (scripts/verify.sh ci_env, the workflow's global env).
pass_env=(CI VITE_BUILD_ID VITE_COMMIT_SHA RELEASE_ID CI_RUNNER_IMAGE SOURCE_DATE_EPOCH APP_PROFILE RELEASE_TARGET)
# A merge job's dependency cache (scripts/contracts/ci-gates.ts DEPENDENCY_CACHE): pnpm's store and metadata
# cache go in at the same paths, so the install in here reuses what the job's install fetched.
pnpm_dirs=()
for name in PNPM_CONFIG_STORE_DIR PNPM_CONFIG_CACHE_DIR; do
if [ -n "${!name:-}" ] && [ -d "${!name}" ]; then
pass_env+=("$name")
pnpm_dirs+=("${!name}")
fi
done
say() { echo "system-container: $*" >&2; }
fail() { say "$*"; exit 3; }
@@ -68,6 +77,10 @@ else
fi
tar -C "$node_root" -cf - . | $docker exec -i "$cid" sh -c 'mkdir -p /opt/node && tar -C /opt/node --no-same-owner -xf -' \
|| fail "copying node failed"
for dir in "${pnpm_dirs[@]}"; do
tar -C "$dir" -cf - . | $docker exec -i "$cid" sh -c "mkdir -p '$dir' && tar -C '$dir' --no-same-owner -xf -" \
|| fail "copying $dir failed"
done
if [ -d "$corepack_home" ]; then
tar -C "$corepack_home" -cf - . | $docker exec -i "$cid" sh -c 'mkdir -p /opt/corepack && tar -C /opt/corepack --no-same-owner -xf -' \
|| fail "copying the corepack cache failed"
@@ -282,6 +282,13 @@ type ApplicationMutationController<Input, Value> = Readonly<{
* `state.unknownEffectResendable` carries the same answer to `AsyncSurface`.
*/
canResendUnknownEffect: boolean;
/**
* 1112/01-01. Whether the oldest request is unknown now, read at the
* call, not from the last render: a form asks it when a resend has ended
* (`useAppForm` `mutation`). `state.indicator` says the same once the
* hook renders again.
*/
holdsUnknownEffect(): boolean;
}>;
type MutationExecution<Input> =
@@ -878,6 +885,11 @@ export function useApplicationMutation<Input, Value>(
return submit(head.input as Input);
}, [submit, unknownEffectChannel]);
const holdsUnknownEffect = useCallback(
() => unknownEffectChannel?.admissions[0]?.state === "UNKNOWN",
[unknownEffectChannel],
);
const unknownEffectHead = unknownEffectChannel?.admissions[0];
const canResendUnknownEffect =
unknownEffectChannel !== null &&
@@ -900,6 +912,7 @@ export function useApplicationMutation<Input, Value>(
reconcileUnknownEffect,
resendUnknownEffect,
canResendUnknownEffect,
holdsUnknownEffect,
});
}
@@ -142,6 +142,12 @@ export type AsyncSurfaceProps = Readonly<{
* terminal error shows its own `failure.requestId`.
*/
supportReference?: string | undefined;
/**
* 1112/04-02. Words about the unknown save shown with it (a resend the
* server refused before the write: `form.resendLater`), not under the input
* error summary.
*/
notice?: ReactNode;
}>;
export function AsyncSurface({
@@ -155,6 +161,7 @@ export function AsyncSurface({
onResendUnknownEffect,
headingLevel,
supportReference,
notice,
}: AsyncSurfaceProps) {
const { message } = useLocale();
if (state.base === "idle") return idle ?? null;
@@ -231,6 +238,7 @@ export function AsyncSurface({
{message("action.resendMutation")}
</Button>
) : null}
{state.indicator === "mutation-effect-unknown" && notice ? <p>{notice}</p> : null}
{state.indicator === "mutation-effect-unknown" && supportReference ? (
<p>
{message("template.supportReference", {
+1
View File
@@ -123,6 +123,7 @@ export {
FormActions,
FormFailureStatus,
FormField,
FormSaveFeedback,
useAppForm,
useDirtyNavigationGuard,
} from "../forms/index.ts";
@@ -42,7 +42,11 @@ export const Checkbox = forwardRef<HTMLInputElement, CheckboxProps>(
}}
type="checkbox"
/>
<span>{label}</span>
<span>
{label}
{/* 1112/05-13. The symbol as Field draws it; the state is on the input. */}
{props.required ? <span aria-hidden="true"> *</span> : null}
</span>
</label>
{description ? (
<p className="ui-field__description" id={descriptionId}>
@@ -41,6 +41,7 @@ export const Dialog = forwardRef<HTMLDialogElement, DialogProps>(
const dialogRef = useRef<HTMLDialogElement | null>(null);
const previousFocusRef = useRef<HTMLElement | null>(null);
const focusRestoreGenerationRef = useRef(0);
const innerEscapeRef = useRef(false);
const titleId = useId();
const descriptionId = useId();
useImperativeHandle(forwardedRef, () => dialogRef.current!, []);
@@ -103,16 +104,26 @@ export const Dialog = forwardRef<HTMLDialogElement, DialogProps>(
className={`ui-dialog ${className}`.trim()}
onCancel={(event) => {
event.preventDefault();
// The Escape that fired this cancel closed an inner layer.
if (innerEscapeRef.current) return;
onClose();
}}
onClick={(event) => {
if (event.target === event.currentTarget) onClose();
}}
onKeyDown={(event) => {
if (event.key === "Escape") {
event.preventDefault();
onClose();
if (event.key !== "Escape") return;
// 1112/05-11. A Menu, Popover or Tooltip inside handled this Escape
// (it prevented the default): it closes that layer, not the Dialog.
if (event.defaultPrevented) {
innerEscapeRef.current = true;
globalThis.setTimeout(() => {
innerEscapeRef.current = false;
}, 0);
return;
}
event.preventDefault();
onClose();
}}
ref={dialogRef}
>
@@ -0,0 +1,15 @@
/**
* 1112/05-11. Whether an Escape is for a layer drawn over the page (a
* Popover or a shown Tooltip) whose root is `root`. Not when it was pressed
* inside a dialog that does not hold the layer: that Escape is the dialog's.
* An Escape from the layer, from a dialog around it, or from no element
* (focus on the body, as after a click in WebKit) is the layer's.
*/
export function escapeIsForLayer(event: KeyboardEvent, root: Element | null): boolean {
const target = event.target;
if (root === null || !(target instanceof Element) || root.contains(target)) {
return true;
}
const dialog = target.closest("dialog");
return dialog === null || dialog.contains(root);
}
@@ -1,6 +1,7 @@
import { useEffect, useId, useRef, useState } from "react";
import { Button } from "./button.tsx";
import { escapeIsForLayer } from "./escape-layer.ts";
export type PopoverProps = Readonly<{
triggerLabel: string;
@@ -12,6 +13,7 @@ export function Popover({ triggerLabel, children }: PopoverProps) {
const rootRef = useRef<HTMLDivElement | null>(null);
const triggerRef = useRef<HTMLButtonElement | null>(null);
const contentId = useId();
const triggerId = useId();
useEffect(() => {
if (!open) return;
@@ -24,17 +26,25 @@ export function Popover({ triggerLabel, children }: PopoverProps) {
triggerRef.current?.focus();
}
}
// Capture phase, and the default prevented: the Escape closes this
// layer only, not a Dialog around it (1112/05-11). An Escape pressed in
// a Dialog this popover is not in is the Dialog's.
function closeOnEscape(event: KeyboardEvent) {
if (event.key === "Escape") {
if (
event.key === "Escape" &&
!event.defaultPrevented &&
escapeIsForLayer(event, rootRef.current)
) {
event.preventDefault();
setOpen(false);
triggerRef.current?.focus();
}
}
document.addEventListener("pointerdown", closeOutside);
document.addEventListener("keydown", closeOnEscape);
document.addEventListener("keydown", closeOnEscape, true);
return () => {
document.removeEventListener("pointerdown", closeOutside);
document.removeEventListener("keydown", closeOnEscape);
document.removeEventListener("keydown", closeOnEscape, true);
};
}, [open]);
@@ -43,6 +53,7 @@ export function Popover({ triggerLabel, children }: PopoverProps) {
<Button
aria-controls={contentId}
aria-expanded={open}
id={triggerId}
onClick={() => setOpen((current) => !current)}
ref={triggerRef}
variant="secondary"
@@ -50,7 +61,12 @@ export function Popover({ triggerLabel, children }: PopoverProps) {
{triggerLabel}
</Button>
{open ? (
<div className="ui-popover__content" id={contentId} role="dialog">
<div
aria-labelledby={triggerId}
className="ui-popover__content"
id={contentId}
role="dialog"
>
{children}
</div>
) : null}
@@ -47,6 +47,9 @@ export const SearchField = forwardRef<HTMLInputElement, SearchFieldProps>(
className="ui-field__input"
id={controlId}
ref={inputRef}
// 1112/05-13. Required both ways, as TextField: the symbol
// Field draws and the state on the input.
required={required}
type="search"
value={value}
/>
@@ -45,33 +45,52 @@ export const TextArea = forwardRef<HTMLTextAreaElement, TextAreaProps>(
label={label}
required={required}
>
{({ controlId, describedBy, invalid }) => (
<>
<textarea
{...props}
aria-describedby={describedBy}
aria-invalid={invalid || undefined}
className="ui-field__input ui-field__textarea"
defaultValue={value === undefined ? defaultValue : undefined}
id={controlId}
maxLength={maxLength}
onChange={(event) => {
if (value === undefined) setUncontrolledValue(event.currentTarget.value);
props.onChange?.(event);
}}
ref={ref}
required={required}
value={value}
/>
{remaining !== null ? (
<output className="ui-field__counter">
{maxLengthMessage
? maxLengthMessage(remaining)
: message("form.remaining", { count: remaining })}
</output>
) : null}
</>
)}
{({ controlId, describedBy, invalid }) => {
// 1112/05-17. The count describes the field; it is read when the
// field is reached, not announced on every key. Reaching the limit
// is announced once.
const counterId = `${controlId}-counter`;
const counterText =
remaining === null
? null
: maxLengthMessage
? maxLengthMessage(remaining)
: message("form.remaining", { count: remaining });
return (
<>
<textarea
{...props}
aria-describedby={
[describedBy, counterText === null ? undefined : counterId]
.filter(Boolean)
.join(" ") || undefined
}
aria-invalid={invalid || undefined}
className="ui-field__input ui-field__textarea"
defaultValue={value === undefined ? defaultValue : undefined}
id={controlId}
maxLength={maxLength}
onChange={(event) => {
if (value === undefined) setUncontrolledValue(event.currentTarget.value);
props.onChange?.(event);
}}
ref={ref}
required={required}
value={value}
/>
{counterText !== null ? (
<>
<span className="ui-field__counter" id={counterId}>
{counterText}
</span>
<span aria-live="polite" className="visually-hidden">
{remaining === 0 ? counterText : ""}
</span>
</>
) : null}
</>
);
}}
</Field>
);
},
@@ -4,6 +4,7 @@ import {
useContext,
useEffect,
useMemo,
useRef,
useState,
} from "react";
@@ -79,14 +80,28 @@ function ToastRegion({
dismiss(id: string): void;
}>) {
const { message } = useLocale();
// 1112/05-14. Where focus was before it came into the toasts: closing the
// last toast with its button gives focus back there, not to the body.
const returnFocusRef = useRef<HTMLElement | null>(null);
return (
<section
aria-label={message("toast.region")}
aria-live="polite"
className="ui-toast-region"
onFocus={(event) => {
const from = event.relatedTarget;
if (from instanceof HTMLElement && !event.currentTarget.contains(from)) {
returnFocusRef.current = from;
}
}}
>
{toasts.map((toast) => (
<ToastItem dismiss={dismiss} key={toast.id} toast={toast} />
<ToastItem
dismiss={dismiss}
key={toast.id}
returnFocus={() => returnFocusRef.current}
toast={toast}
/>
))}
</section>
);
@@ -95,9 +110,11 @@ function ToastRegion({
function ToastItem({
toast,
dismiss,
returnFocus,
}: Readonly<{
toast: ToastEntry;
dismiss(id: string): void;
returnFocus(): HTMLElement | null;
}>) {
const { message } = useLocale();
const [paused, setPaused] = useState(false);
@@ -129,7 +146,21 @@ function ToastItem({
</div>
<IconButton
accessibleName={message("action.closeNamed", { title: toast.title })}
onClick={() => dismiss(toast.id)}
onClick={(event) => {
// The button goes away with its toast. Focus moves to the next
// toast's close button, or back to where it came from.
const item = event.currentTarget.closest("article");
const items = item?.parentElement
? [...item.parentElement.querySelectorAll(":scope > article")]
: [];
const index = item ? items.indexOf(item) : -1;
const neighbour = items[index + 1] ?? items[index - 1];
const next =
neighbour?.querySelector("button") ??
(returnFocus()?.isConnected ? returnFocus() : null);
dismiss(toast.id);
next?.focus();
}}
variant="ghost"
>
<CloseIcon />
@@ -1,4 +1,6 @@
import { cloneElement, useEffect, useId, useState } from "react";
import { cloneElement, useEffect, useId, useRef, useState } from "react";
import { escapeIsForLayer } from "./escape-layer.ts";
export type TooltipProps = Readonly<{
content: string;
@@ -7,29 +9,55 @@ export type TooltipProps = Readonly<{
/**
* Describes its focusable child (WCAG 1.4.13): the child carries
* `aria-describedby`, and Escape hides the tooltip until the next hover or
* focus.
* `aria-describedby`, Escape hides the tooltip until the next hover or
* focus, and the pointer can move onto the tooltip (primitives.css).
*/
export function Tooltip({ content, children }: TooltipProps) {
const tooltipId = useId();
const [dismissed, setDismissed] = useState(false);
const [hovered, setHovered] = useState(false);
const [focused, setFocused] = useState(false);
const rootRef = useRef<HTMLSpanElement | null>(null);
const shown = (hovered || focused) && !dismissed;
useEffect(() => {
if (dismissed) return;
// Document level: a hovered trigger does not have keyboard focus.
if (!shown) return;
// Document level: a hovered trigger does not have keyboard focus. Capture
// phase, and the default prevented: this Escape hides the tooltip only,
// not a Dialog around it (1112/05-11). A tooltip that is not shown, or
// one outside the Dialog the Escape was pressed in, leaves it alone.
function dismissOnEscape(event: KeyboardEvent) {
if (event.key === "Escape") setDismissed(true);
if (
event.key !== "Escape" ||
event.defaultPrevented ||
!escapeIsForLayer(event, rootRef.current)
) {
return;
}
event.preventDefault();
setDismissed(true);
}
document.addEventListener("keydown", dismissOnEscape);
return () => document.removeEventListener("keydown", dismissOnEscape);
}, [dismissed]);
document.addEventListener("keydown", dismissOnEscape, true);
return () => document.removeEventListener("keydown", dismissOnEscape, true);
}, [shown]);
const describedBy = [children.props["aria-describedby"], tooltipId]
.filter(Boolean)
.join(" ");
return (
<span
className="ui-tooltip"
onFocus={() => setDismissed(false)}
onMouseEnter={() => setDismissed(false)}
ref={rootRef}
onBlur={(event) => {
if (!event.currentTarget.contains(event.relatedTarget)) setFocused(false);
}}
onFocus={() => {
setFocused(true);
setDismissed(false);
}}
onMouseEnter={() => {
setHovered(true);
setDismissed(false);
}}
onMouseLeave={() => setHovered(false)}
>
{cloneElement(children, { "aria-describedby": describedBy })}
<span
+74 -2
View File
@@ -1,13 +1,16 @@
import { useId, type FormHTMLAttributes, type ReactNode } from "react";
import type { AsyncState } from "../../application/view-models/async-state.ts";
import type { AppFailure } from "../../contracts/errors.ts";
import { TerminalErrorSurface } from "../components/async-surface.tsx";
import { AsyncSurface, TerminalErrorSurface } from "../components/async-surface.tsx";
import type { HeadingLevel } from "../components/state-surfaces.tsx";
import { TextField } from "../components/ui/text-field.ts";
import { useLocale } from "../i18n/index.ts";
import { useLocale, type ParameterlessMessageKey } from "../i18n/index.ts";
import type {
FieldErrors,
FieldName,
FormResult,
FormResultState,
FormValues,
} from "./form-contracts.ts";
@@ -126,3 +129,72 @@ export function FormActions(props: Readonly<{
</div>
);
}
/** What FormSaveFeedback reads of a `useAppForm` result given the `mutation` option. */
export type FormSaveFeedbackForm<Output> = Readonly<{
effectUnknown: boolean;
otherSaveRunning: boolean;
mutationState: AsyncState | undefined;
failure: AppFailure | null;
result: FormResultState;
notice: ParameterlessMessageKey | null;
supportReference: string | undefined;
submitForm(): Promise<unknown>;
confirmUnknownEffect(then?: () => void): Promise<void>;
resendUnknownEffect(): Promise<FormResult<Output> | null>;
}>;
/**
* 1112/01-01. The feedback of a form that saves through a mutation
* (`useAppForm` with `mutation`), in the order a page used to write out by
* hand: signing in again (D-2, whatever the effect), the unknown result
* (confirm it was applied, or resend it with the same key), then another
* save failure that is not an input error, then a conflict, then a save of
* the mutation this form did not start. Put it in the page template's
* feedback area (`FormPage` `feedback`, `feedbackId`). What a resend saved
* goes to the form's `onSaved`.
*/
export function FormSaveFeedback<Output>(props: Readonly<{
form: FormSaveFeedbackForm<Output>;
/**
* After "it was applied" has settled the request, while the form is
* mounted (a page opens the list).
*/
onConfirmed?: () => void;
/** The action of a failure that is not "try again" (sign in, for example). */
onFailureAction?: () => void;
}>) {
const { message } = useLocale();
const { form, onConfirmed, onFailureAction } = props;
const notice = form.notice ? message(form.notice) : undefined;
const failureStatus = form.failure ? (
<FormFailureStatus
failure={form.failure}
onAction={form.result === "retry-later" ? () => void form.submitForm() : onFailureAction}
/>
) : null;
if (form.failure?.action === "reauth") return failureStatus;
if (form.effectUnknown && form.mutationState) {
return (
<AsyncSurface
notice={notice}
onReconcileUnknownEffect={() => {
void form.confirmUnknownEffect(onConfirmed);
}}
onResendUnknownEffect={() => {
void form.resendUnknownEffect();
}}
state={form.mutationState}
supportReference={form.supportReference}
/>
);
}
if (failureStatus) return failureStatus;
if (form.result === "conflict" && notice) {
return <p role="alert">{notice}</p>;
}
if (form.otherSaveRunning && form.mutationState && form.result !== "effect-unknown") {
return <AsyncSurface state={form.mutationState} />;
}
return null;
}
+227 -49
View File
@@ -9,6 +9,7 @@ import {
type FormEvent,
} from "react";
import { flushSync } from "react-dom";
import type { AsyncState } from "../../application/view-models/async-state.ts";
import type { ZodIssue, ZodType } from "../../contracts/zod.ts";
import {
isRefusedOnEveryAttempt,
@@ -39,6 +40,21 @@ export type FormRefusalMessage<Values extends FormValues> = Readonly<{
field?: FieldName<Values>;
}>;
/**
* 1112/01-01. What `useAppForm` needs of the mutation it saves through
* (`useApplicationMutation`). A `BoundMutation` is one.
*/
export type FormSaveMutation<Output> = Readonly<{
state: AsyncState;
reconcileUnknownEffect(resolution: "APPLIED"): Promise<void>;
resendUnknownEffect(): Promise<FormResult<Output> | null>;
/**
* Whether the mutation holds an unknown result now. The form reads it
* when a resend has ended instead of judging the outcome itself.
*/
holdsUnknownEffect(): boolean;
}>;
type AppFormOptions<
Values extends FormValues,
Command,
@@ -60,6 +76,24 @@ type AppFormOptions<
* unknown whatever its code.
*/
refusalMessages?: Readonly<Record<string, FormRefusalMessage<Values>>>;
/**
* 1112/01-01. The mutation `submit` goes through. Given, the form owns the
* rules a page used to copy: it refuses a save while the mutation holds an
* unknown result or runs one this form did not start (`saveBlocked`), the
* unknown result's confirm and resend go through it
* (`confirmUnknownEffect`, `resendUnknownEffect`), and what it says about
* a save that is not an input error goes to `notice` for
* `FormSaveFeedback`, not to the input error summary.
*/
mutation?: FormSaveMutation<Output>;
/**
* 1106/08-02, 1112/01-01. A save this form shows ended with a value (a
* submit or a resend): a page opens what was saved here. Called while the
* form is mounted only, after the form shows the outcome and is no longer
* pending, so a leave guard reads the values left on screen (values a
* remounted form never sent stay guarded).
*/
onSaved?(value: Output): void;
}>;
export function useAppForm<
@@ -76,6 +110,8 @@ export function useAppForm<
submit,
resetOnSuccess = true,
refusalMessages,
mutation,
onSaved,
} = options;
const generatedId = useId().replaceAll(":", "");
const formId = `app-form-${generatedId}`;
@@ -108,15 +144,37 @@ export function useAppForm<
[formErrorKeys, resolve],
);
const [pending, setPending] = useState(false);
// 1112/04-02. With a mutation: the status line FormSaveFeedback shows.
const [notice, setNotice] = useState<ParameterlessMessageKey | null>(null);
const indicator = mutation?.state.indicator;
const effectUnknown = indicator === "mutation-effect-unknown";
// A save of this mutation the form did not start: one left running when
// the user came back, or the check behind "confirm applied" (1105/08-04).
const otherSaveRunning = indicator === "mutation-pending" && !pending;
const saveBlocked = effectUnknown || indicator === "mutation-pending";
const saveBlockedRef = useRef(saveBlocked);
saveBlockedRef.current = saveBlocked;
const [result, setResult] = useState<FormResultState>("idle");
const [statusFailure, setStatusFailure] = useState<AppFailure | null>(null);
const pendingRef = useRef<Promise<FormResult<Output> | null> | null>(null);
const unknownSubmissionRef = useRef<Values | null>(null);
// The save whose effect is unknown: what it sent, or `values: null` when
// an earlier mount sent it (a resend from a remounted form). Held, it keeps
// a new save from going out as a new request.
const unknownSubmissionRef = useRef<Readonly<{ values: Values | null }> | null>(null);
// 1103/08-02. A save that ends in neither a field error nor success shows
// its status above the form while the page disables the button that had
// focus, so the browser drops focus to the body. The status takes focus
// once it has rendered (`feedbackId`).
const focusFeedbackRef = useRef(false);
// 1106/08-02. A save outlives the form when the user leaves while it runs.
// Ending then, it opens nothing and changes no state.
const mountedRef = useRef(false);
useEffect(() => {
mountedRef.current = true;
return () => {
mountedRef.current = false;
};
}, []);
// 1105/08-01. The recovery actions (confirm applied, resend, retry) sit in
// that status and go away with it once they have done their work, so the
// browser drops focus to the body again. A success that replaces a status
@@ -173,6 +231,8 @@ export function useAppForm<
return next;
});
setFormErrors([]);
// The notice of a save still unknown stays; a conflict's goes with it.
setNotice((current) => (unknownSubmissionRef.current ? current : null));
setResult((current) =>
unknownSubmissionRef.current ? current : "idle",
);
@@ -205,6 +265,7 @@ export function useAppForm<
setTouched(new Set());
setFieldErrors({} as FieldErrors<Values>);
setFormErrors([]);
setNotice(null);
setResult("idle");
},
[defaultValues],
@@ -218,6 +279,7 @@ export function useAppForm<
flushSync(() => {
setFieldErrors({} as FieldErrors<Values>);
setFormErrors([]);
setNotice(null);
setResult("success");
if (resetOnSuccess) {
setValues(defaultValues);
@@ -231,35 +293,54 @@ export function useAppForm<
[defaultValues, resetOnSuccess],
);
/**
* The save went through, with values this form did not send: an earlier
* mount sent them. 1106/08-01. The confirmed save is shown, and focus,
* lost with the button that confirmed it, goes to the feedback area that
* shows it. The values on screen were never sent, so they and the dirty
* state stay as they are (diff review of 1106/08-01).
*/
const settleUnsentValues = useCallback(() => {
unknownSubmissionRef.current = null;
focusFeedbackRef.current = focusIsLost();
setFieldErrors({} as FieldErrors<Values>);
setFormErrors([]);
setNotice(null);
setResult("success");
}, []);
const settleApplied = useCallback(() => {
const submittedValues = unknownSubmissionRef.current;
if (!submittedValues) {
// 1106/08-01. After a remount the form no longer holds the submitted
// values. The confirmed save is shown, and focus, lost with the
// confirm button, goes to the feedback area that shows it. The values
// on screen were never sent, so they and the dirty state stay as they
// are (diff review of 1106/08-01).
focusFeedbackRef.current = focusIsLost();
setFieldErrors({} as FieldErrors<Values>);
setFormErrors([]);
setResult("success");
const submittedValues = unknownSubmissionRef.current?.values ?? null;
if (submittedValues === null) {
// After a remount the form no longer holds the submitted values.
settleUnsentValues();
return;
}
settleSuccessfulValues(submittedValues);
}, [settleSuccessfulValues]);
}, [settleSuccessfulValues, settleUnsentValues]);
const settleNotApplied = useCallback(() => {
if (!unknownSubmissionRef.current) return;
unknownSubmissionRef.current = null;
setFieldErrors({} as FieldErrors<Values>);
setFormErrors([]);
setNotice(null);
setResult("idle");
}, []);
/**
* `submittedValues` is null when this form did not send the request the
* outcome answers (a resend after a remount): a success then keeps the
* values on screen, and a result left unknown holds no values either.
*/
const applyOutcome = useCallback(
(outcome: FormResult<Output>, submittedValues: Values) => {
(outcome: FormResult<Output>, submittedValues: Values | null) => {
const settleSaved = () =>
submittedValues === null
? settleUnsentValues()
: settleSuccessfulValues(submittedValues);
if (outcome.ok) {
settleSuccessfulValues(submittedValues);
settleSaved();
return;
}
const refusal = refusalFor(refusalMessages, outcome.error);
@@ -283,7 +364,20 @@ export function useAppForm<
if (onField !== undefined) focusField(onField);
return;
}
if (outcome.error.kind === "VALIDATION_REJECTED") {
if (
outcome.error.effect === "MAYBE_APPLIED" &&
outcome.error.action !== "reauth"
) {
// 1101/03-04. Before an input error: a save that may have applied is
// not corrected and sent again, whatever field its failure names.
focusFeedbackRef.current = true;
unknownSubmissionRef.current = { values: submittedValues };
setFieldErrors({} as FieldErrors<Values>);
setFormErrors([]);
// 0929/08-04. Kept for its request id, not shown as a status.
setStatusFailure(outcome.error);
setResult("effect-unknown");
} else if (outcome.error.kind === "VALIDATION_REJECTED") {
unknownSubmissionRef.current = null;
const mapped = mapValidationFailureToFields<Values>(
outcome.error,
@@ -301,19 +395,19 @@ export function useAppForm<
setFormErrors([]);
setStatusFailure(outcome.error);
setResult("reauth-required");
} else if (outcome.error.effect === "MAYBE_APPLIED") {
focusFeedbackRef.current = true;
unknownSubmissionRef.current = submittedValues;
setFormErrors([]);
// 0929/08-04. Kept for its request id, not shown as a status.
setStatusFailure(outcome.error);
setResult("effect-unknown");
} else if (outcome.error.effect === "APPLIED_CONFIRMED") {
settleSuccessfulValues(submittedValues);
settleSaved();
} else if (outcome.error.kind === "CONFLICT") {
focusFeedbackRef.current = true;
unknownSubmissionRef.current = null;
setFormErrors(["form.conflict"]);
// 1112/04-02. Not an input error: with a mutation, FormSaveFeedback
// says it; without one the page reads it from formErrors as before.
if (mutation) {
setFormErrors([]);
setNotice("form.conflict");
} else {
setFormErrors(["form.conflict"]);
}
setResult("conflict");
} else if (
outcome.error.kind === "FORBIDDEN" ||
@@ -339,15 +433,32 @@ export function useAppForm<
allowedServerFields,
focusField,
focusFirstError,
mutation,
refusalMessages,
settleSuccessfulValues,
settleUnsentValues,
],
);
/**
* The end of a save the form shows: no longer pending, committed before
* `onSaved` runs, so a page that navigates there meets the form's own leave
* guard. Nothing runs once the form is gone.
*/
const finishSave = useCallback(
(outcome: FormResult<Output> | null) => {
if (!mountedRef.current) return;
flushSync(() => setPending(false));
if (outcome?.ok) onSaved?.(outcome.value);
},
[onSaved],
);
const validateAndSubmit = useCallback(
async (): Promise<FormResult<Output> | null> => {
setFieldErrors({} as FieldErrors<Values>);
setFormErrors([]);
setNotice(null);
const parsed = await schema.safeParseAsync(values);
if (!parsed.success) {
@@ -372,17 +483,19 @@ export function useAppForm<
const command = mapToCommand(parsed.data);
setPending(true);
let outcome: FormResult<Output> | null = null;
try {
const outcome = await submit(command);
outcome = await submit(command);
applyOutcome(outcome, parsed.data);
return outcome;
} finally {
setPending(false);
finishSave(outcome);
}
},
[
allowedServerFields,
applyOutcome,
finishSave,
focusFirstError,
mapToCommand,
schema,
@@ -398,6 +511,9 @@ export function useAppForm<
// let a second submit through before the command starts.
if (pendingRef.current) return pendingRef.current;
if (unknownSubmissionRef.current) return Promise.resolve(null);
// 1112/01-01. The mutation holds an unknown result or runs a save this
// form did not start: a new save would go out as a second request.
if (saveBlockedRef.current) return Promise.resolve(null);
const submission = validateAndSubmit().finally(() => {
pendingRef.current = null;
});
@@ -421,24 +537,34 @@ export function useAppForm<
send: () => Promise<FormResult<Output> | null>,
): Promise<FormResult<Output> | null> => {
if (pendingRef.current) return pendingRef.current;
// After a remount the form no longer holds the submitted values.
const submittedValues = unknownSubmissionRef.current ?? values;
// After a remount the form no longer holds the submitted values, and
// the values on screen were never sent (1106/03-01 diff review FR-03).
const submittedValues = unknownSubmissionRef.current?.values ?? null;
const resend = (async () => {
setPending(true);
let outcome: FormResult<Output> | null = null;
try {
const outcome = await send();
if (outcome && resendLeftUnknown(outcome)) {
outcome = await send();
if (outcome && resendLeftUnknown(outcome, mutation)) {
focusFeedbackRef.current = true;
unknownSubmissionRef.current = submittedValues;
unknownSubmissionRef.current = { values: submittedValues };
setFieldErrors({} as FieldErrors<Values>);
setFormErrors(["form.resendLater"]);
// 1112/04-02. With a mutation the words go to the unknown
// result's own surface (FormSaveFeedback), not under the input
// error summary.
if (mutation) {
setFormErrors([]);
setNotice("form.resendLater");
} else {
setFormErrors(["form.resendLater"]);
}
setResult("effect-unknown");
} else if (outcome) {
applyOutcome(outcome, submittedValues);
}
return outcome;
} finally {
setPending(false);
finishSave(outcome);
}
})().finally(() => {
pendingRef.current = null;
@@ -446,9 +572,40 @@ export function useAppForm<
pendingRef.current = resend;
return resend;
},
[applyOutcome, values],
[applyOutcome, finishSave, mutation],
);
/**
* 1112/01-01. The unknown result's "it was applied": the mutation settles
* its request, then the form shows the save (`settleApplied`), then `then`
* runs while the form is mounted (1105/08-02: a page opens the list, which
* shows whether the item is there). Without a mutation it rejects.
*/
const confirmUnknownEffect = useCallback(
async (then?: () => void): Promise<void> => {
if (!mutation) throw new TypeError("useAppForm: confirmUnknownEffect needs the mutation option");
await mutation.reconcileUnknownEffect("APPLIED");
if (!mountedRef.current) return;
settleApplied();
then?.();
},
[mutation, settleApplied],
);
/**
* 1112/01-01. The unknown result's "send the same request again":
* `resendUnknown` with the mutation's own resend. What it saved goes to
* `onSaved` like a submit's.
*/
const resendUnknownEffect = useCallback((): Promise<FormResult<Output> | null> => {
if (!mutation) {
return Promise.reject(
new TypeError("useAppForm: resendUnknownEffect needs the mutation option"),
);
}
return resendUnknown(() => mutation.resendUnknownEffect());
}, [mutation, resendUnknown]);
return Object.freeze({
formId,
/**
@@ -488,6 +645,21 @@ export function useAppForm<
reset,
settleApplied,
settleNotApplied,
/**
* 1112/01-01. With the `mutation` option: the mutation holds an unknown
* result or runs a save; `submitForm` sends nothing. Without it, false.
*/
saveBlocked,
/** The mutation's request is unknown: FormSaveFeedback shows its surface. */
effectUnknown,
/** A save of the mutation this form did not start is running. */
otherSaveRunning,
/** The mutation's state, for FormSaveFeedback's surfaces. */
mutationState: mutation?.state,
/** 1112/04-02. What the save feedback says besides a failure (a key). */
notice,
confirmUnknownEffect,
resendUnknownEffect,
});
}
@@ -512,21 +684,27 @@ function refusalFor<Values extends FormValues>(
}
/**
* 1106/03-01. The resend did not reach the write: the request it repeats is
* still unknown, and the mutation coordinator keeps its key. Signing in again
* still comes first (D-2). A refusal every attempt gets
* (`isRefusedOnEveryAttempt`, the coordinator's own test) settles the request
* instead, and the form shows it as for a first save (field errors, a save
* it takes again).
* 1106/03-01. The resend did not reach the write (`NOT_APPLIED`,
* `NOT_STARTED`) and the request it repeats is still unknown, its key kept.
* Signing in again still comes first (D-2). Otherwise the form shows the
* outcome as for a first save (field errors, a save it takes again).
* 1112/01-01. Whether the request is still unknown is the mutation's own
* answer, read now. A form given no mutation (a page generated before it)
* cannot ask: it reads the refusals every attempt gets
* (`isRefusedOnEveryAttempt`), the same rule the mutation applies.
*/
function resendLeftUnknown(outcome: FormResult<unknown>): boolean {
return (
!outcome.ok &&
(outcome.error.effect === "NOT_APPLIED" ||
outcome.error.effect === "NOT_STARTED") &&
outcome.error.action !== "reauth" &&
!isRefusedOnEveryAttempt(outcome.error)
);
function resendLeftUnknown(
outcome: FormResult<unknown>,
mutation: FormSaveMutation<unknown> | undefined,
): boolean {
if (outcome.ok) return false;
const { effect, action } = outcome.error;
if ((effect !== "NOT_APPLIED" && effect !== "NOT_STARTED") || action === "reauth") {
return false;
}
return mutation
? mutation.holdsUnknownEffect()
: !isRefusedOnEveryAttempt(outcome.error);
}
/** 1105/08-01. Nothing has focus: the focused element left the document. */
+1 -1
View File
@@ -53,7 +53,7 @@ export default function HomePage() {
title={message("route.APP_HOME.title")}
description={message("home.description")}
/>
<div className="readiness-grid" aria-label={message("home.readiness")}>
<div className="readiness-grid" role="group" aria-label={message("home.readiness")}>
{READINESS_ITEMS.map((item) => (
<article className="ui-panel" key={item}>
<h2>{message(`home.readiness.${item}.title`)}</h2>
@@ -516,9 +516,21 @@
transition: opacity var(--duration-fast) var(--easing-standard);
}
/* 1112/05-06. WCAG 1.4.13 hoverable: a shown tooltip takes the pointer,
and the bridge below it covers the gap to the trigger, so moving onto it
keeps .ui-tooltip hovered. A hidden one stays out of the pointer's way. */
.ui-tooltip__content::before {
position: absolute;
inset-inline: 0;
inset-block-start: 100%;
block-size: var(--space-2);
content: "";
}
.ui-tooltip:focus-within .ui-tooltip__content,
.ui-tooltip:hover .ui-tooltip__content {
opacity: 1;
pointer-events: auto;
}
.ui-progress,
+9 -1
View File
@@ -4,7 +4,9 @@
padding-block: clamp(1rem, 5vw, 3.5rem) 0.5rem;
}
[data-route-heading]:focus {
/* 1112/05-02. Pointer navigation only: a keyboard user keeps the
:focus-visible ring (base.css) on the heading each route move focuses. */
[data-route-heading]:focus:not(:focus-visible) {
outline: none;
}
@@ -30,6 +32,12 @@
min-width: 0;
}
/* A form page always holds its save feedback (FormSaveFeedback); with
nothing to say it takes no row, so it adds no gap. */
.page-template__feedback:empty {
display: none;
}
.page-template__breadcrumb {
padding-block-start: 1rem;
color: var(--color-content-muted);
+270
View File
@@ -0,0 +1,270 @@
// @vitest-environment jsdom
import { render, screen, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { useState } from "react";
import { describe, expect, it, vi } from "vitest";
import {
Button,
Checkbox,
Dialog,
Menu,
Popover,
SearchField,
TextArea,
ToastProvider,
Tooltip,
useToast,
} from "../../src/presentation/design-system/index.ts";
/**
* 1112/05-10, 05-11, 05-13, 05-14, 05-17. What the shared primitives promise
* a keyboard and screen reader user (docs/design/2026-07-26-design-system-platform-design.md
* 8.1·8.2절, WCAG 2.2 AA): a named dialog, Escape that closes the innermost
* layer only, required shown both ways, focus that does not fall to the body,
* and a counter that is not announced on every key.
*/
function DialogWith({ onClose, children }: Readonly<{ onClose(): void; children: React.ReactNode }>) {
return (
<Dialog open onClose={onClose} title="설정">
{children}
</Dialog>
);
}
describe("Popover", () => {
it("names its dialog after the trigger", async () => {
const user = userEvent.setup();
render(
<Popover triggerLabel="설명 열기">
<Button>내부 작업</Button>
</Popover>,
);
await user.click(screen.getByRole("button", { name: "설명 열기" }));
expect(screen.getByRole("dialog", { name: "설명 열기" })).toBeVisible();
});
});
describe("Escape inside a Dialog", () => {
it("closes an open Popover and keeps the Dialog", async () => {
const user = userEvent.setup();
const onClose = vi.fn();
render(
<DialogWith onClose={onClose}>
<Popover triggerLabel="설명 열기">
<Button>내부 작업</Button>
</Popover>
</DialogWith>,
);
await user.click(screen.getByRole("button", { name: "설명 열기" }));
await user.click(screen.getByRole("button", { name: "내부 작업" }));
await user.keyboard("{Escape}");
expect(screen.queryByRole("button", { name: "내부 작업" })).not.toBeInTheDocument();
expect(screen.getByRole("button", { name: "설명 열기" })).toHaveFocus();
expect(onClose).not.toHaveBeenCalled();
});
it("closes an open Menu and keeps the Dialog", async () => {
const user = userEvent.setup();
const onClose = vi.fn();
render(
<DialogWith onClose={onClose}>
<Menu triggerLabel="더 보기" items={[{ id: "copy", label: "복사", onSelect: () => {} }]} />
</DialogWith>,
);
await user.click(screen.getByRole("button", { name: "더 보기" }));
expect(screen.getByRole("menu")).toBeVisible();
await user.keyboard("{Escape}");
expect(screen.queryByRole("menu")).not.toBeInTheDocument();
expect(onClose).not.toHaveBeenCalled();
});
it("hides a shown Tooltip and keeps the Dialog", async () => {
const user = userEvent.setup();
const onClose = vi.fn();
render(
<DialogWith onClose={onClose}>
<Tooltip content="자세한 설명">
<Button>도움말</Button>
</Tooltip>
</DialogWith>,
);
await user.hover(screen.getByRole("button", { name: "도움말" }));
await user.keyboard("{Escape}");
expect(screen.getByRole("tooltip", { hidden: true })).not.toBeVisible();
expect(onClose).not.toHaveBeenCalled();
});
// round9 confirm review. A popover or tooltip left open outside a Dialog
// does not take the Dialog's Escape: the Escape belongs to the Dialog it
// was pressed in.
it.each([
[
"a Popover",
(
<Popover key="layer" triggerLabel="설명 열기">
<Button>내부 작업</Button>
</Popover>
),
(user: ReturnType<typeof userEvent.setup>) => user.click(screen.getByRole("button", { name: "설명 열기" })),
],
[
"a Tooltip",
(
<Tooltip key="layer" content="자세한 설명">
<Button>도움말</Button>
</Tooltip>
),
(user: ReturnType<typeof userEvent.setup>) => user.hover(screen.getByRole("button", { name: "도움말" })),
],
])("closes the Dialog when %s outside it is open", async (_label, layer, openLayer) => {
const user = userEvent.setup();
const onClose = vi.fn();
render(
<>
{layer}
<DialogWith onClose={onClose}>
<Button>안쪽 버튼</Button>
</DialogWith>
</>,
);
await openLayer(user);
screen.getByRole("button", { name: "안쪽 버튼" }).focus();
await user.keyboard("{Escape}");
expect(onClose).toHaveBeenCalledTimes(1);
});
// WebKit does not focus a clicked button: an Escape with focus on the body
// still closes the open Popover.
it("closes an open Popover on an Escape from the body", async () => {
const user = userEvent.setup();
render(
<Popover triggerLabel="설명 열기">
<Button>내부 작업</Button>
</Popover>,
);
await user.click(screen.getByRole("button", { name: "설명 열기" }));
(document.activeElement as HTMLElement | null)?.blur();
await user.keyboard("{Escape}");
expect(screen.queryByRole("button", { name: "내부 작업" })).not.toBeInTheDocument();
});
it("closes the Dialog when no inner layer is open", async () => {
const user = userEvent.setup();
const onClose = vi.fn();
render(
<DialogWith onClose={onClose}>
<Button>안쪽 버튼</Button>
</DialogWith>,
);
screen.getByRole("button", { name: "안쪽 버튼" }).focus();
await user.keyboard("{Escape}");
expect(onClose).toHaveBeenCalledTimes(1);
});
});
describe("required fields", () => {
it("marks a required SearchField both on the input and with the symbol", () => {
render(<SearchField label="검색" required value="" onChange={() => {}} clearLabel="지우기" onClear={() => {}} />);
expect(screen.getByRole("searchbox", { name: /검색/u })).toBeRequired();
expect(screen.getByText("*", { exact: false })).toHaveAttribute("aria-hidden", "true");
});
it("marks a required Checkbox both on the input and with the symbol", () => {
render(<Checkbox label="약관에 동의" required />);
const checkbox = screen.getByRole("checkbox", { name: /약관에 동의/u });
expect(checkbox).toBeRequired();
const label = checkbox.closest("label");
if (!label) throw new Error("expected the checkbox label");
expect(within(label).getByText("*", { exact: false })).toHaveAttribute("aria-hidden", "true");
});
});
describe("Toast focus when it is closed", () => {
function Harness({ count }: Readonly<{ count: number }>) {
const toast = useToast();
return (
<Button
onClick={() => {
for (let index = 0; index < count; index += 1) {
toast.push({ id: `toast-${index}`, title: `알림 ${index}`, durationMs: 60_000 });
}
}}
>
알림 보이기
</Button>
);
}
it("moves focus to the next toast's close button", async () => {
const user = userEvent.setup();
render(
<ToastProvider>
<Harness count={2} />
</ToastProvider>,
);
await user.click(screen.getByRole("button", { name: "알림 보이기" }));
const [first] = screen.getAllByRole("button", { name: /닫기/u });
if (!first) throw new Error("expected two close buttons");
first.focus();
await user.click(first);
expect(document.activeElement).not.toBe(document.body);
expect(document.activeElement).toBe(screen.getByRole("button", { name: /닫기/u }));
});
it("returns focus to where it was before the last toast took it", async () => {
const user = userEvent.setup();
render(
<ToastProvider>
<Harness count={1} />
</ToastProvider>,
);
const trigger = screen.getByRole("button", { name: "알림 보이기" });
await user.click(trigger);
await user.tab();
const close = screen.getByRole("button", { name: /닫기/u });
expect(close).toHaveFocus();
await user.keyboard("{Enter}");
expect(screen.queryByRole("article")).not.toBeInTheDocument();
expect(trigger).toHaveFocus();
});
});
describe("TextArea counter", () => {
it("describes the field without announcing every key", async () => {
const user = userEvent.setup();
function Controlled() {
const [value, setValue] = useState("");
return <TextArea label="메모" maxLength={30} value={value} onChange={(event) => setValue(event.currentTarget.value)} />;
}
render(<Controlled />);
const field = screen.getByRole("textbox", { name: "메모" });
await user.type(field, "가나다");
expect(screen.queryByRole("status")).not.toBeInTheDocument();
expect(field).toHaveAccessibleDescription(/27/u);
});
});
+444 -2
View File
@@ -26,6 +26,7 @@ import {
Form,
FormFailureStatus,
FormField,
FormSaveFeedback,
useAppForm,
useDirtyNavigationGuard,
validationMessage,
@@ -165,6 +166,11 @@ function FormHarness(props: Readonly<{
>;
resetOnSuccess?: boolean;
onFailureAction?(): void;
/** Resends the save an earlier mount left unknown (`resendUnknown`). */
resend?(): Promise<
| Readonly<{ ok: true; value: string }>
| Readonly<{ ok: false; error: ReturnType<typeof createFailure> }>
>;
}>) {
const form = useAppForm({
schema,
@@ -179,6 +185,7 @@ function FormHarness(props: Readonly<{
submit: props.submit,
resetOnSuccess: props.resetOnSuccess,
});
const resend = props.resend;
return (
<Form pending={form.pending} onSubmit={(event) => void form.submitForm(event)}>
<ErrorSummary
@@ -205,6 +212,9 @@ function FormHarness(props: Readonly<{
Reset
</Button>
<Button onClick={() => form.settleApplied()}>Confirm applied</Button>
{resend ? (
<Button onClick={() => void form.resendUnknown(resend)}>Resend</Button>
) : null}
<Button onClick={() => form.settleNotApplied()}>
Confirm not applied
</Button>
@@ -632,6 +642,70 @@ describe("local form facade", () => {
});
});
// 1106/08-01, 1106/03-01 (diff review FR-03), 1112/10-01. A page left while
// its save was unknown comes back with a new form: the coordinator still
// holds the unknown save, the form no longer knows the values it sent. The
// values on screen were typed after the save and never sent, so no way out
// of the unknown result may take them as the saved values: they and the
// dirty state stay as they are, and the leave guard still protects them.
describe("a form mounted again while its save is unknown", () => {
const leftUnknown = () =>
Promise.resolve({
ok: false as const,
error: createFailure("RATE_LIMITED", "CREATE_ENTITY", 0, {
effect: "NOT_APPLIED",
httpStatus: 429,
code: "RATE_LIMIT_EXCEEDED",
}),
});
it("keeps the values on screen when the earlier save is confirmed applied", async () => {
const user = userEvent.setup();
const submit = vi.fn();
render(<FormHarness submit={submit} />);
await user.type(screen.getByRole("textbox", { name: /Name/ }), "Beta");
await user.click(screen.getByRole("button", { name: "Confirm applied" }));
expect(screen.getByTestId("result")).toHaveTextContent("success");
expect(screen.getByRole("textbox", { name: /Name/ })).toHaveValue("Beta");
expect(screen.getByTestId("dirty")).toHaveTextContent("true");
expect(submit).not.toHaveBeenCalled();
});
it("keeps the values on screen when the resend succeeds", async () => {
const user = userEvent.setup();
const resend = vi.fn(async () => ({ ok: true as const, value: "saved" }));
render(<FormHarness submit={vi.fn()} resend={resend} />);
await user.type(screen.getByRole("textbox", { name: /Name/ }), "Beta");
await user.click(screen.getByRole("button", { name: "Resend" }));
await waitFor(() =>
expect(screen.getByTestId("result")).toHaveTextContent("success"),
);
expect(resend).toHaveBeenCalledTimes(1);
expect(screen.getByRole("textbox", { name: /Name/ })).toHaveValue("Beta");
expect(screen.getByTestId("dirty")).toHaveTextContent("true");
});
it("keeps the values on screen when a resend left unknown is then confirmed applied", async () => {
const user = userEvent.setup();
render(<FormHarness submit={vi.fn()} resend={leftUnknown} />);
await user.type(screen.getByRole("textbox", { name: /Name/ }), "Beta");
await user.click(screen.getByRole("button", { name: "Resend" }));
await waitFor(() =>
expect(screen.getByTestId("result")).toHaveTextContent("effect-unknown"),
);
await user.click(screen.getByRole("button", { name: "Confirm applied" }));
expect(screen.getByTestId("result")).toHaveTextContent("success");
expect(screen.getByRole("textbox", { name: /Name/ })).toHaveValue("Beta");
expect(screen.getByTestId("dirty")).toHaveTextContent("true");
});
});
// 1101/14.4. Every code the paired backend can put in a field error's
// details[].code: clean-architecture-backend-template 5786126c,
// ClientSafeValidationDetails.java RULES (18-42) and its INVALID fallback.
@@ -1127,7 +1201,8 @@ describe("correcting a field after a server validation refusal", () => {
// 1101/14.4. Outside IDEMPOTENT_REQUEST_MISMATCH a 422 may come after a
// write (fileserver INTEGRITY_MISMATCH), so the coordinator holds it as an
// unknown result even though the form shows the field.
// unknown result. 1101/03-04. The form shows that result, not the field it
// names: correcting the field would send a second save.
it("keeps the save off after a 422 the backend may have applied", async () => {
const user = userEvent.setup();
const fetcher = answerFirst(422, {
@@ -1141,8 +1216,11 @@ describe("correcting a field after a server validation refusal", () => {
await user.type(name, "Rejected");
await user.click(screen.getByRole("button", { name: "Submit" }));
await waitFor(() => expect(name).toHaveAttribute("aria-invalid", "true"));
await waitFor(() =>
expect(screen.getByTestId("result")).toHaveTextContent("effect-unknown"),
);
expect(name).not.toHaveAttribute("aria-invalid");
expect(screen.getByRole("button", { name: "Submit" })).toBeDisabled();
expect(fetcher).toHaveBeenCalledTimes(1);
});
@@ -1273,3 +1351,367 @@ describe("correcting a field after a server validation refusal", () => {
expect(sentKeys(fetcher)).toEqual(["key-1", "key-1", "key-2"]);
});
});
// 1112/01-01. The page used to hold the rules of a save through a mutation:
// it refused a new save while the coordinator held one unknown or running,
// and it wired the unknown-result surface's confirm and resend to the form.
// A generated page kept its own copy, so a platform fix never reached it.
// Now the form takes the mutation and FormSaveFeedback draws the feedback.
describe("a form bound to its mutation", () => {
let token = 0;
const scope = {
...scopeSnapshot(),
identities: createRuntimeIdentityRegistry({
tokenFactory: () => `bound-identity-token-${String(++token).padStart(4, "0")}`,
}),
};
const meta = { requestId: "request-1", traceId: "trace-1" };
function BoundForm(
props: Readonly<{
fetcher: typeof fetch;
operations?: typeof FORM_DECLARING_OPERATIONS;
onSaved?: (value: unknown) => void;
onConfirmed?: () => void;
/** Counts the saves the form hands to the mutation. */
onSubmit?: () => void;
}>,
) {
const [http] = useState(() => formBinding(props.fetcher, props.operations));
const mutation = useApplicationMutation<Readonly<{ name: string; note?: string }>, unknown>({
definitionId: "form-bound-create-v1",
definitionVersion: 1,
operationId: commandMutationIdentity(FORM_CREATE_CONTRACT).operationId,
requiresIdempotencyKey: true,
owner: "platform-test",
duplicatePolicy: "REJECT_WHILE_ACTIVE",
scope,
invalidate: [],
execute: (command, { intent }) =>
http.execute("FORM_CREATE_ENTITY", { name: command.name }, { intent }),
});
const form = useAppForm({
schema,
defaultValues: defaults,
allowedServerFields: ["name", "note"],
mapToCommand: (values) => ({ name: values.name }),
submit: (command) => {
props.onSubmit?.();
return mutation.submit(command);
},
mutation,
...(props.onSaved === undefined ? {} : { onSaved: props.onSaved }),
});
return (
<Form pending={form.pending} onSubmit={(event) => void form.submitForm(event)}>
<ErrorSummary
fieldErrors={form.fieldErrors}
formErrors={form.formErrors}
fieldLabels={{ name: "Name", note: "Note" }}
fieldId={form.fieldId}
onFocusField={form.focusField}
/>
<FormField {...form.field("name")} label="Name" required />
<Button type="submit" pending={form.pending} disabled={form.saveBlocked}>
Submit
</Button>
<div id={form.feedbackId} tabIndex={-1}>
<FormSaveFeedback
form={form}
{...(props.onConfirmed === undefined ? {} : { onConfirmed: props.onConfirmed })}
/>
</div>
<output data-testid="result">{form.result}</output>
<output data-testid="indicator">{mutation.state.indicator ?? "none"}</output>
<output data-testid="pending">{String(form.pending)}</output>
<output data-testid="dirty">{String(form.dirty)}</output>
</Form>
);
}
function lostThen(...answers: Response[]) {
const fetcher = vi.fn<typeof fetch>().mockRejectedValueOnce(new TypeError("Failed to fetch"));
for (const answer of answers) fetcher.mockResolvedValueOnce(answer);
return fetcher.mockImplementation(async () =>
Response.json({ success: true, data: { id: "entity-1", name: "Saved" }, meta }),
);
}
async function loseFirstSave(
fetcher: typeof fetch,
props: Omit<Parameters<typeof BoundForm>[0], "fetcher"> = {},
) {
const user = userEvent.setup();
const client = queryClient();
const view = render(<BoundForm fetcher={fetcher} {...props} />, { wrapper: wrapper(client) });
await user.type(screen.getByRole("textbox", { name: /Name/ }), "Saved");
await user.click(screen.getByRole("button", { name: "Submit" }));
await screen.findByText(formatMessage("ko-KR", "async.mutationEffectUnknown"));
return { user, view, client };
}
/** The user leaves the page and comes back: a new form, the same mutation. */
function mountAgain(
view: ReturnType<typeof render>,
client: ReturnType<typeof queryClient>,
props: Parameters<typeof BoundForm>[0],
) {
view.unmount();
return render(<BoundForm {...props} />, { wrapper: wrapper(client) });
}
/** A save the server answers only when the test says so. */
function heldSave() {
let answer: ((response: Response) => void) | undefined;
const fetcher = vi.fn<typeof fetch>(
() =>
new Promise<Response>((resolve) => {
answer = resolve;
}),
);
return {
fetcher,
answer: async () => {
await waitFor(() => expect(answer).toBeDefined());
answer?.(Response.json({ success: true, data: { id: "entity-1", name: "Saved" }, meta }));
},
};
}
// fe-testing (round9 confirm review). A form mounted again holds no
// submission of its own: only the coordinator's unknown result stops it.
it("refuses a new save in a form mounted again while the coordinator holds one unknown", async () => {
const fetcher = lostThen();
const { view, client } = await loseFirstSave(fetcher);
const submits = vi.fn();
const again = mountAgain(view, client, { fetcher, onSubmit: submits });
await screen.findByText(formatMessage("ko-KR", "async.mutationEffectUnknown"));
const form = again.container.querySelector("form");
if (!form) throw new Error("expected the form");
// A valid value of its own, so only the block stops the save.
fireEvent.change(screen.getByRole("textbox", { name: /Name/ }), {
target: { value: "Typed after coming back" },
});
fireEvent.submit(form);
// The form's own rule: it does not hand the save to the mutation at all.
await new Promise((resolve) => setTimeout(resolve, 0));
expect(submits).not.toHaveBeenCalled();
expect(fetcher).toHaveBeenCalledTimes(1);
expect(screen.getByRole("button", { name: "Submit" })).toBeDisabled();
});
// 1105/08-04, moved here from the generated create page test (1112/01-01).
// The user comes back while the save they started still runs: the form
// shows it and sends nothing new.
it("shows a save it did not start and refuses a new one", async () => {
const user = userEvent.setup();
const held = heldSave();
const client = queryClient();
const view = render(<BoundForm fetcher={held.fetcher} />, { wrapper: wrapper(client) });
await user.type(screen.getByRole("textbox", { name: /Name/ }), "Saved");
await user.click(screen.getByRole("button", { name: "Submit" }));
await waitFor(() => expect(held.fetcher).toHaveBeenCalledTimes(1));
const again = mountAgain(view, client, { fetcher: held.fetcher });
const form = again.container.querySelector("form");
if (!form) throw new Error("expected the form");
fireEvent.submit(form);
expect(await screen.findByText(formatMessage("ko-KR", "async.mutationPending"))).toBeVisible();
expect(screen.getByRole("button", { name: "Submit" })).toBeDisabled();
expect(held.fetcher).toHaveBeenCalledTimes(1);
await held.answer();
});
// 1106/08-02, moved here from the generated create page test. A save that
// ends after the user left does not take them to what it saved.
it.each([
["while the form is there", false, 1],
["once the user left the form", true, 0],
] as const)("opens what was saved only %s", async (_label, leave, opened) => {
const user = userEvent.setup();
const held = heldSave();
const onSaved = vi.fn();
const view = render(<BoundForm fetcher={held.fetcher} onSaved={onSaved} />, {
wrapper: wrapper(queryClient()),
});
await user.type(screen.getByRole("textbox", { name: /Name/ }), "Saved");
await user.click(screen.getByRole("button", { name: "Submit" }));
if (leave) view.unmount();
await held.answer();
await waitFor(() => expect(held.fetcher).toHaveBeenCalledTimes(1));
if (opened) await waitFor(() => expect(onSaved).toHaveBeenCalledTimes(1));
await new Promise((resolve) => setTimeout(resolve, 0));
expect(onSaved).toHaveBeenCalledTimes(opened);
});
// 1105/08-02, moved here from the generated create page test. Confirming
// the unknown result hands over to the page (which opens the list).
it("hands over to the page once the user confirms the save applied", async () => {
const onConfirmed = vi.fn();
const { user } = await loseFirstSave(lostThen(), { onConfirmed });
await user.click(
screen.getByRole("button", { name: formatMessage("ko-KR", "action.confirmMutationApplied") }),
);
await waitFor(() => expect(onConfirmed).toHaveBeenCalledTimes(1));
expect(screen.getByTestId("indicator")).toHaveTextContent("none");
});
// 1112/01-02 영향 (round9 confirm review). Back on the page, the user typed
// a value the first save never had; the resend saves the first one. The
// page opens what was saved with the leave guard on: the typed value is
// still there and unsaved.
it("opens what a resend saved with the values it never sent still guarded", async () => {
const fetcher = lostThen();
const seen: string[] = [];
const onSaved = vi.fn(() => {
seen.push(
`pending=${screen.getByTestId("pending").textContent} dirty=${screen.getByTestId("dirty").textContent}`,
);
});
const { user, view, client } = await loseFirstSave(fetcher);
mountAgain(view, client, { fetcher, onSaved });
await user.type(screen.getByRole("textbox", { name: /Name/ }), "Never sent");
await user.click(
await screen.findByRole("button", { name: formatMessage("ko-KR", "action.resendMutation") }),
);
await waitFor(() => expect(onSaved).toHaveBeenCalledTimes(1));
expect(seen).toEqual(["pending=false dirty=true"]);
expect(screen.getByRole("textbox", { name: /Name/ })).toHaveValue("Never sent");
});
// D-2 (round9 confirm review). The resend meets a sign-in: signing in
// again comes first, before the unknown result that is still held.
it("asks to sign in again before it shows the unknown result", async () => {
const fetcher = lostThen(
Response.json(
{ success: false, error: { code: "UNAUTHENTICATED", category: "AUTH", retryable: false }, meta },
{ status: 401 },
),
);
const { user } = await loseFirstSave(fetcher);
await user.click(
screen.getByRole("button", { name: formatMessage("ko-KR", "action.resendMutation") }),
);
expect(await screen.findByText("계속하려면 로그인이 필요합니다.")).toBeVisible();
expect(
screen.queryByRole("button", { name: formatMessage("ko-KR", "action.resendMutation") }),
).not.toBeInTheDocument();
});
// 1112/04-02, the declared 409. Not an input error: the feedback says it,
// and the "check what you entered" summary does not appear.
it("says a declared conflict in the feedback, not as an input error", async () => {
const user = userEvent.setup();
const fetcher = vi
.fn<typeof fetch>()
.mockResolvedValueOnce(
Response.json(
{ success: false, error: { code: "POSTER_ALREADY_EXISTS", category: "CONFLICT", retryable: false }, meta },
{ status: 409 },
),
);
render(<BoundForm fetcher={fetcher} operations={FORM_DECLARING_OPERATIONS} />, {
wrapper: wrapper(queryClient()),
});
await user.type(screen.getByRole("textbox", { name: /Name/ }), "Taken");
await user.click(screen.getByRole("button", { name: "Submit" }));
await waitFor(() => expect(screen.getByTestId("result")).toHaveTextContent("conflict"));
expect(screen.getByText(formatMessage("ko-KR", "form.conflict"))).toBeVisible();
expect(
screen.queryByRole("heading", { name: formatMessage("ko-KR", "form.errorSummary") }),
).not.toBeInTheDocument();
});
it("refuses a new save while the coordinator holds one unknown", async () => {
const fetcher = lostThen();
const { view } = await loseFirstSave(fetcher);
const form = view.container.querySelector("form");
if (!form) throw new Error("expected the form");
fireEvent.submit(form);
expect(fetcher).toHaveBeenCalledTimes(1);
expect(screen.getByRole("button", { name: "Submit" })).toBeDisabled();
});
it("confirms the save applied through the form, which settles both", async () => {
const { user } = await loseFirstSave(lostThen());
await user.click(
screen.getByRole("button", { name: formatMessage("ko-KR", "action.confirmMutationApplied") }),
);
await waitFor(() => expect(screen.getByTestId("result")).toHaveTextContent("success"));
expect(screen.getByTestId("indicator")).toHaveTextContent("none");
});
// UX-02 (1112/04-02). The same-key resend was refused before the write: the
// save is still unknown, and the words say so where the unknown result is,
// not under the "check what you entered" summary.
it("says a resend refused before the write in the feedback, not as an input error", async () => {
const fetcher = lostThen(
Response.json(
{
success: false,
error: { code: "RATE_LIMIT_UNAVAILABLE", category: "TRANSIENT_DEPENDENCY", retryable: true },
meta,
},
{ status: 503 },
),
);
const { user } = await loseFirstSave(fetcher);
await user.click(
screen.getByRole("button", { name: formatMessage("ko-KR", "action.resendMutation") }),
);
await waitFor(() => expect(fetcher).toHaveBeenCalledTimes(2));
// The harness's <output> elements are statuses too: find the words, then
// the unknown result's status around them.
const notice = await screen.findByText(formatMessage("ko-KR", "form.resendLater"));
expect(notice.closest('[role="status"]')).toHaveTextContent(
formatMessage("ko-KR", "async.mutationEffectUnknown"),
);
expect(
screen.queryByRole("heading", { name: formatMessage("ko-KR", "form.errorSummary") }),
).not.toBeInTheDocument();
expect(screen.getByTestId("result")).toHaveTextContent("effect-unknown");
});
});
// 1101/03-04. A failure that is both a field refusal and possibly applied
// (a feature's mapProblem says VALIDATION_REJECTED, the classifier
// MAYBE_APPLIED) shows the unknown result only: correcting the field would
// send a second save of something that may already be saved.
describe("a possibly applied failure that names a field", () => {
it("shows the unknown result, not a field error", async () => {
const user = userEvent.setup();
const submit = vi.fn(async () => ({
ok: false as const,
error: createFailure("VALIDATION_REJECTED", "CREATE_ENTITY", 0, {
effect: "MAYBE_APPLIED",
validationIssues: [{ path: "name", code: "SIZE" }],
}),
}));
render(<FormHarness submit={submit} />);
await user.type(screen.getByRole("textbox", { name: /Name/ }), "Alpha");
await user.click(screen.getByRole("button", { name: "Submit" }));
await waitFor(() => expect(screen.getByTestId("result")).toHaveTextContent("effect-unknown"));
expect(screen.getByRole("textbox", { name: /Name/ })).not.toHaveAccessibleDescription(/./u);
});
});
+11 -1
View File
@@ -5,7 +5,7 @@ import userEvent from "@testing-library/user-event";
import { MemoryRouter } from "react-router-dom";
import { describe, expect, it } from "vitest";
import { LocaleProvider } from "../../src/presentation/i18n/index.ts";
import { formatMessage, LocaleProvider } from "../../src/presentation/i18n/index.ts";
import HomePage from "../../src/presentation/pages/home-page.tsx";
import { ApplicationProvider } from "../../src/presentation/providers/application-provider.tsx";
import { PreferenceProviders } from "../../src/presentation/providers/preference-providers.tsx";
@@ -35,6 +35,16 @@ function renderApp(
}
describe("starter home page", () => {
// 1112/05-15. A generic div's aria-label is dropped by assistive technology;
// the readiness list is a named group.
it("names the readiness list as a group", async () => {
renderApp("/");
expect(
await screen.findByRole("group", { name: formatMessage("ko-KR", "home.readiness") }),
).toBeVisible();
});
it("reaches the platform overview from the starter actions", async () => {
const user = userEvent.setup();
renderApp("/");
+28
View File
@@ -24,6 +24,34 @@ test("navigates to a registry-backed example without a page reload", async ({
).toBeFocused();
});
// 1112/05-02. The route heading takes focus on every navigation. A keyboard
// user must see it (M2); a pointer user may not need the ring.
test("shows the focus ring on the route heading after keyboard navigation only", async ({
page,
}) => {
await page.goto("/");
// The home route renders after the shell: focus given before it is there
// goes with the node it lands on, and Enter then does nothing (WebKit).
await expect(page.getByRole("heading", { level: 1 })).toHaveText("Clean Architecture Frontend");
const link = page
.getByRole("navigation", { name: "주요 탐색" })
.getByRole("link", { name: "플랫폼 구성" });
await link.focus();
await expect(link).toBeFocused();
await page.keyboard.press("Enter");
const heading = page.getByRole("heading", { level: 1, name: "플랫폼 구성" });
await expect(heading).toBeFocused();
expect(await heading.evaluate((element) => getComputedStyle(element).outlineStyle)).not.toBe("none");
await page
.getByRole("navigation", { name: "주요 탐색" })
.getByRole("link", { name: "홈" })
.click();
const home = page.getByRole("heading", { level: 1 });
await expect(home).toBeFocused();
expect(await home.evaluate((element) => getComputedStyle(element).outlineStyle)).toBe("none");
});
test("provides an escape-dismissible mobile navigation", async ({ page }) => {
await page.setViewportSize({ width: 390, height: 844 });
await page.goto("/");
+18
View File
@@ -225,6 +225,24 @@ test.describe("the form", () => {
}));
expect(viewport.scrollWidth).toBeLessThanOrEqual(viewport.clientWidth);
});
// round9 confirm review. The page always hands FormSaveFeedback to the
// template's feedback area; with nothing to say it takes no row, so the
// heading and the fields stay one gap apart.
test("leaves no room for a save feedback area with nothing to say", async ({ page }) => {
await openForm(page);
const spacing = await page.evaluate(() => {
const box = (selector: string) => document.querySelector(selector)?.getBoundingClientRect();
const heading = box(".page-template__heading");
const layout = box(".page-template__layout");
const template = document.querySelector(".page-template");
return heading && layout && template
? { between: layout.top - heading.bottom, rowGap: parseFloat(getComputedStyle(template).rowGap) }
: null;
});
expect(spacing).not.toBeNull();
expect(spacing?.between).toBeCloseTo(spacing?.rowGap ?? 0, 0);
});
});
test.describe("the save", () => {
+23
View File
@@ -23,6 +23,29 @@ async function openDesignSystemGallery(page: Page) {
).toBeVisible();
}
// 1112/05-06. WCAG 1.4.13 hoverable: the pointer can move from the trigger
// onto the tooltip, across the gap between them, and the tooltip stays.
test("keeps a tooltip shown while the pointer moves onto it", async ({ page }) => {
await openDesignSystemGallery(page);
await page.getByRole("button", { name: "도움말" }).hover();
const tooltip = page.getByRole("tooltip", { name: "이 설명은 필수 정보가 아닙니다." });
await expect.poll(() => tooltip.evaluate((element) => getComputedStyle(element).opacity)).toBe("1");
const box = await tooltip.boundingBox();
if (!box) throw new Error("expected the tooltip box");
// The hover that shows it holds in the gap and over the tooltip itself:
// read where it is decided, not only the opacity, which fades over 100 ms
// and still reads 1 the moment the hover is lost.
const stillHovered = () =>
tooltip.evaluate((element) => element.closest(".ui-tooltip")?.matches(":hover") ?? false);
await page.mouse.move(box.x + box.width / 2, box.y + box.height + 2, { steps: 4 });
expect(await stillHovered()).toBe(true);
await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2, { steps: 4 });
expect(await stillHovered()).toBe(true);
await expect.poll(() => tooltip.evaluate((element) => getComputedStyle(element).opacity)).toBe("1");
});
test("validates and reports the common text-field flow", async ({ page }) => {
await openDesignSystemGallery(page);
await page.getByRole("button", { name: "입력 확인" }).click();
@@ -44,10 +44,34 @@ jobs:
if: \${{ gitea.event_name != 'workflow_dispatch' || (inputs.stage != 'documentation' && inputs.stage != 'main') }}
runs-on: ubuntu-latest
timeout-minutes: 45
env:
COREPACK_HOME: /tmp/fe-dependency-cache/corepack
PNPM_CONFIG_STORE_DIR: /tmp/fe-dependency-cache/pnpm-store
PNPM_CONFIG_CACHE_DIR: /tmp/fe-dependency-cache/pnpm-cache
steps:
- uses: https://github.com/actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5
with:
persist-credentials: false
- name: Restore and save the dependency cache
if: \${{ gitea.ref == 'refs/heads/main' }}
uses: https://github.com/actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830
with:
path: |
/opt/hostedtoolcache/node
/tmp/fe-dependency-cache
key: fe-dependencies-\${{ runner.os }}-\${{ runner.arch }}-\${{ hashFiles('.nvmrc', 'pnpm-lock.yaml') }}
restore-keys: |
fe-dependencies-\${{ runner.os }}-\${{ runner.arch }}-
- name: Restore the dependency cache
if: \${{ gitea.ref != 'refs/heads/main' }}
uses: https://github.com/actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830
with:
path: |
/opt/hostedtoolcache/node
/tmp/fe-dependency-cache
key: fe-dependencies-\${{ runner.os }}-\${{ runner.arch }}-\${{ hashFiles('.nvmrc', 'pnpm-lock.yaml') }}
restore-keys: |
fe-dependencies-\${{ runner.os }}-\${{ runner.arch }}-
- uses: https://github.com/actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020
with:
node-version-file: .nvmrc
@@ -88,10 +112,34 @@ jobs:
# FE-GATE-013 runner requirement: unprivileged user and network namespaces for bwrap (the provider sandbox runs bwrap --unshare-pid --unshare-ipc --unshare-uts --unshare-net); Ubuntu 23.10 and later refuse them while kernel.apparmor_restrict_unprivileged_userns=1 unless /usr/bin/bwrap has an AppArmor profile that allows userns; scripts/check-system-test-prerequisites.ts probes this before test:system runs and scripts/run-and-validate-provider.ts before a provider runs
runs-on: ubuntu-latest
timeout-minutes: 45
env:
COREPACK_HOME: /tmp/fe-dependency-cache/corepack
PNPM_CONFIG_STORE_DIR: /tmp/fe-dependency-cache/pnpm-store
PNPM_CONFIG_CACHE_DIR: /tmp/fe-dependency-cache/pnpm-cache
steps:
- uses: https://github.com/actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5
with:
persist-credentials: false
- name: Restore and save the dependency cache
if: \${{ gitea.ref == 'refs/heads/main' }}
uses: https://github.com/actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830
with:
path: |
/opt/hostedtoolcache/node
/tmp/fe-dependency-cache
key: fe-dependencies-\${{ runner.os }}-\${{ runner.arch }}-\${{ hashFiles('.nvmrc', 'pnpm-lock.yaml') }}
restore-keys: |
fe-dependencies-\${{ runner.os }}-\${{ runner.arch }}-
- name: Restore the dependency cache
if: \${{ gitea.ref != 'refs/heads/main' }}
uses: https://github.com/actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830
with:
path: |
/opt/hostedtoolcache/node
/tmp/fe-dependency-cache
key: fe-dependencies-\${{ runner.os }}-\${{ runner.arch }}-\${{ hashFiles('.nvmrc', 'pnpm-lock.yaml') }}
restore-keys: |
fe-dependencies-\${{ runner.os }}-\${{ runner.arch }}-
- uses: https://github.com/actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020
with:
node-version-file: .nvmrc
@@ -134,10 +182,33 @@ jobs:
image: "mcr.microsoft.com/playwright:v1.62.0-noble@sha256:baed2032d533817f3dbe6425de795788430ba345e819a1201337009ba17c9d07"
env:
CI_RUNNER_IMAGE: "mcr.microsoft.com/playwright:v1.62.0-noble@sha256:baed2032d533817f3dbe6425de795788430ba345e819a1201337009ba17c9d07"
COREPACK_HOME: /tmp/fe-dependency-cache/corepack
PNPM_CONFIG_STORE_DIR: /tmp/fe-dependency-cache/pnpm-store
PNPM_CONFIG_CACHE_DIR: /tmp/fe-dependency-cache/pnpm-cache
steps:
- uses: https://github.com/actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5
with:
persist-credentials: false
- name: Restore and save the dependency cache
if: \${{ gitea.ref == 'refs/heads/main' }}
uses: https://github.com/actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830
with:
path: |
/opt/hostedtoolcache/node
/tmp/fe-dependency-cache
key: fe-dependencies-\${{ runner.os }}-\${{ runner.arch }}-\${{ hashFiles('.nvmrc', 'pnpm-lock.yaml') }}
restore-keys: |
fe-dependencies-\${{ runner.os }}-\${{ runner.arch }}-
- name: Restore the dependency cache
if: \${{ gitea.ref != 'refs/heads/main' }}
uses: https://github.com/actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830
with:
path: |
/opt/hostedtoolcache/node
/tmp/fe-dependency-cache
key: fe-dependencies-\${{ runner.os }}-\${{ runner.arch }}-\${{ hashFiles('.nvmrc', 'pnpm-lock.yaml') }}
restore-keys: |
fe-dependencies-\${{ runner.os }}-\${{ runner.arch }}-
- uses: https://github.com/actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020
with:
node-version-file: .nvmrc
@@ -169,6 +240,8 @@ jobs:
if: \${{ startsWith(gitea.ref, 'refs/tags/v') || (gitea.event_name == 'workflow_dispatch' && (inputs.stage == 'release' || inputs.stage == 'production' || inputs.stage == 'field')) }}
runs-on: ubuntu-latest
timeout-minutes: 45
env:
RELEASE_TAG: "\${{ startsWith(gitea.ref, 'refs/tags/v') && gitea.ref_name || '' }}"
strategy:
fail-fast: false
matrix:
+131 -2
View File
@@ -9,6 +9,7 @@ import { afterEach, describe, expect, it } from "vitest";
import {
CI_ACTION_REGISTRY,
DEPENDENCY_CACHE,
indexCiGateContract,
loadCiGateContract,
parseCiActionRegistry,
@@ -241,6 +242,27 @@ describe("CI gate contract", () => {
expect(stageOf("FE-GATE-028")).toBe("release");
});
// 1112/05-01 (R9-D7). The signed review names the release tag it covers;
// the release job hands FE-GATE-028 that tag, and nothing on a run that is
// not a tag run, so the gate fails closed there (run-ci-gate.ts refuses an
// empty required variable).
it("gives FE-GATE-028 the release tag of a tag run and nothing otherwise (1112/05-01)", async () => {
const contract = await loadCiGateContract(process.cwd());
const tag = "${{ startsWith(gitea.ref, 'refs/tags/v') && gitea.ref_name || '' }}";
expect(contract.gates.find(({ id }) => id === "FE-GATE-028")?.requiresEnvironment).toEqual(["RELEASE_TAG"]);
expect(contract.jobs.find(({ id }) => id === "release_gate")?.environment).toEqual([
{ name: "RELEASE_TAG", value: tag },
]);
const workflow = renderCiWorkflow(contract);
const release = workflow.slice(workflow.indexOf("\n release_gate:\n"), workflow.indexOf("\n immutable_build:\n"));
expect(release).toContain(` env:\n RELEASE_TAG: ${JSON.stringify(tag)}\n`);
expect(workflow.match(/RELEASE_TAG:/gu)).toHaveLength(1);
const unbound = JSON.parse(JSON.stringify(contract)) as Record<string, any>;
unbound.jobs.find((job: Record<string, any>) => job.id === "release_gate").environment = [];
expect(() => parseCiGateContract(unbound)).toThrow(/job release_gate lacks environment RELEASE_TAG for FE-GATE-028/u);
});
it("keeps every platform route's signed review record as FE-GATE-028 evidence (1112/05-18)", async () => {
// The evidence list is written by hand. EXAMPLES_PLATFORM's record was
// missing from it while the review covers every registered route. A
@@ -1674,16 +1696,18 @@ describe("CI workflow generation", () => {
'if [ -n "$PROMOTION_STAGING_ROOT" ] && [ -n "$PROMOTION_CLEANUP_TOKEN" ] && [ -n "$PROMOTION_RUNNER_TEMP_DEV" ] && [ -n "$PROMOTION_RUNNER_TEMP_INO" ] && [ -n "$PROMOTION_STAGING_DEV" ] && [ -n "$PROMOTION_STAGING_INO" ]; then',
);
const actionUses = [...first.matchAll(/^\s+-?\s*uses: (.+)$/gmu)].map((match) => match[1]);
expect(actionUses).toHaveLength(43);
expect(actionUses).toHaveLength(49);
expect(new Set(actionUses)).toEqual(
new Set([
"https://github.com/actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5",
"https://github.com/actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020",
"https://github.com/ChristopherHX/gitea-upload-artifact@81f940d004763f986ba3582c007fd842dd5cb0d7",
"https://github.com/ChristopherHX/gitea-download-artifact@75635f32b4c1c41c4b3d64e8f85210112ed4c9c7",
"https://github.com/actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830",
"https://github.com/actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830",
]),
);
expect(actionUses.every((uses) => /^https:\/\/github\.com\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+@[0-9a-f]{40}$/u.test(uses!))).toBe(true);
expect(actionUses.every((uses) => /^https:\/\/github\.com\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+(?:\/restore)?@[0-9a-f]{40}$/u.test(uses!))).toBe(true);
});
// 1103/11-02. tests/visual/fonts.conf reads the goldens' faces from OS
@@ -1783,6 +1807,111 @@ describe("CI workflow generation", () => {
);
});
// Decision 2026-11-13 (lead): the dependency cache is for the merge jobs
// only, and the jobs that produce supply-chain evidence install fresh.
describe("dependency cache", () => {
const jobSection = (workflow: string, jobId: string) => {
const start = workflow.indexOf(`\n ${jobId}:\n`);
expect(start, jobId).toBeGreaterThan(0);
const next = workflow.slice(start + 1).search(/\n {2}[a-z_]+:\n/u);
return workflow.slice(start + 1, next < 0 ? undefined : start + 1 + next + 1);
};
const save = "https://github.com/actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830";
const restore = "https://github.com/actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830";
it("restores it in each merge job before setup-node, saves it only on main, and installs either way", async () => {
const workflow = renderCiWorkflow(await loadCiGateContract(process.cwd()));
for (const jobId of DEPENDENCY_CACHE.jobIds) {
const job = jobSection(workflow, jobId);
const steps = job.split("\n - ");
const saveIndex = steps.findIndex((step) => step.includes(`uses: ${save}`));
const restoreIndex = steps.findIndex((step) => step.includes(`uses: ${restore}`));
const setupIndex = steps.findIndex((step) => step.startsWith("uses: https://github.com/actions/setup-node@"));
const installIndex = steps.findIndex((step) => step.startsWith("name: Frozen install"));
expect([saveIndex, restoreIndex].every((index) => index > 0 && index < setupIndex), jobId).toBe(true);
expect(setupIndex).toBeLessThan(installIndex);
expect(steps[saveIndex]).toContain("if: ${{ gitea.ref == 'refs/heads/main' }}");
expect(steps[restoreIndex]).toContain("if: ${{ gitea.ref != 'refs/heads/main' }}");
for (const step of [steps[saveIndex]!, steps[restoreIndex]!]) {
expect(step).toContain(
"key: fe-dependencies-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('.nvmrc', 'pnpm-lock.yaml') }}",
);
expect(step).toContain(" /opt/hostedtoolcache/node\n /tmp/fe-dependency-cache\n");
}
// The install does not depend on a hit: a missing or damaged entry
// only makes pnpm fetch what it lacks.
expect(steps[installIndex]).toBe(
"name: Frozen install\n run: |\n corepack enable\n corepack pnpm install --frozen-lockfile --ignore-scripts",
);
for (const { name, value } of DEPENDENCY_CACHE.environment) {
expect(job).toContain(` ${name}: ${value}\n`);
expect(value.startsWith("/tmp/fe-dependency-cache/")).toBe(true);
}
}
});
// A pull request run (`refs/pull/<n>/head`) restores what main saved and
// cannot change it: only actions/cache saves (in its post step), and only
// the step a main run takes uses it.
it("gives a pull request run main's entry read-only, under the same key", async () => {
const workflow = renderCiWorkflow(await loadCiGateContract(process.cwd()));
const steps = workflow.split("\n - ");
const saving = steps.filter((step) => step.includes(`uses: ${save}`));
const restoring = steps.filter((step) => step.includes(`uses: ${restore}`));
expect(saving).toHaveLength(DEPENDENCY_CACHE.jobIds.length);
expect(restoring).toHaveLength(DEPENDENCY_CACHE.jobIds.length);
const condition = (step: string) => /\n {8}if: (.+)\n/u.exec(step)?.[1];
expect(new Set(saving.map(condition))).toEqual(new Set(["${{ gitea.ref == 'refs/heads/main' }}"]));
expect(new Set(restoring.map(condition))).toEqual(new Set(["${{ gitea.ref != 'refs/heads/main' }}"]));
// The restore-only action has no post step, so nothing it runs writes the cache.
expect(restore).toMatch(/^https:\/\/github\.com\/actions\/cache\/restore@[0-9a-f]{40}$/u);
const withBlock = (step: string) => step.slice(step.indexOf(" with:\n"));
for (let index = 0; index < saving.length; index += 1) {
expect(withBlock(restoring[index]!)).toBe(withBlock(saving[index]!));
}
});
it("leaves every other job on a fresh install", async () => {
const contract = await loadCiGateContract(process.cwd());
const workflow = renderCiWorkflow(contract);
const others = contract.jobs.map(({ id }) => id).filter(
(id) => !(DEPENDENCY_CACHE.jobIds as readonly string[]).includes(id),
);
expect(others).toEqual(expect.arrayContaining([
"release_gate", "immutable_build", "vulnerability_provider", "provenance_provider", "promotion", "main_gate",
]));
for (const jobId of others) {
const job = jobSection(workflow, jobId);
expect(job, jobId).not.toContain("actions/cache");
expect(job, jobId).not.toMatch(/PNPM_CONFIG_|COREPACK_HOME|fe-dependency-cache/u);
}
expect(workflow.match(/uses: https:\/\/github\.com\/actions\/cache/gu)).toHaveLength(2 * DEPENDENCY_CACHE.jobIds.length);
});
it.each([
["a release job", "release_gate", 1, /step kind dependency-cache is forbidden for gate-matrix job release_gate/u],
["the main job", "main_gate", 1, /the dependency cache is for the merge jobs only: main_gate/u],
["a provider job", "vulnerability_provider", 1, /step kind dependency-cache is forbidden for provider job vulnerability_provider/u],
])("refuses the cache in %s", async (_name, jobId, at, diagnostic) => {
const contract = JSON.parse(JSON.stringify(await loadCiGateContract(process.cwd()))) as Record<string, any>;
contract.jobs.find((job: Record<string, any>) => job.id === jobId).steps.splice(at, 0, { kind: "dependency-cache" });
expect(() => parseCiGateContract(contract)).toThrow(diagnostic);
});
it("refuses a merge job that drops the cache or binds its directories itself", async () => {
const dropped = JSON.parse(JSON.stringify(await loadCiGateContract(process.cwd()))) as Record<string, any>;
const test = dropped.jobs.find((job: Record<string, any>) => job.id === "merge_test");
test.steps = test.steps.filter((step: Record<string, any>) => step.kind !== "dependency-cache");
expect(() => parseCiGateContract(dropped)).toThrow(/canonical job step sequence drift: merge_test/u);
const bound = JSON.parse(JSON.stringify(await loadCiGateContract(process.cwd()))) as Record<string, any>;
bound.jobs.find((job: Record<string, any>) => job.id === "merge_static").environment.push(
{ name: "COREPACK_HOME", value: "/somewhere" },
);
expect(() => parseCiGateContract(bound)).toThrow(/job merge_static binds COREPACK_HOME, which its dependency cache sets/u);
});
});
// The job container has neither systemd nor bubblewrap, so FE-GATE-013 runs
// in the system container its contract names (hostEnvironment).
it("runs a gate with a host environment through it, and counts only that run", async () => {
+39 -10
View File
@@ -268,18 +268,18 @@ describe("create:feature --with-create", () => {
// 1105/08-04. Like the reference form: while a save this page did not
// start holds the coordinator, the save is off and the feedback says a
// save is running, instead of a save button that does nothing.
// 1112/01-01. The rule is the platform form's (useAppForm `mutation`,
// FormSaveFeedback; tests/component/form-foundation.test.tsx walks it):
// the page turns the button off from the form's state.
it("keeps the create's save off and says so while another save of it runs", () => {
const page =
plan({ id: "invoice-feature", write: "NEVER" }).files.get(
"src/features/invoice-feature/presentation/invoice-create-page.tsx",
) ?? "";
expect(page).toContain(
'const otherSaveRunning = mutation.state.indicator === "mutation-pending" && !form.pending;',
);
expect(page).toContain("disabled={effectUnknown || otherSaveRunning}");
expect(page).toContain('otherSaveRunning && form.result !== "effect-unknown" ? (');
expect(page).toContain("<AsyncSurface state={mutation.state} />");
expect(page).toContain("disabled={form.effectUnknown || form.otherSaveRunning}");
expect(page).toContain("<FormSaveFeedback");
expect(page).not.toContain("mutation.state.indicator");
});
// 1105/08-02. Confirming an unknown create used to leave an emptied form
@@ -302,6 +302,9 @@ describe("create:feature --with-create", () => {
// 1106/08-02. A save that ended after the user left the form took them to
// the item anyway. The page opens the item or the list only while it is
// still mounted, and the generated page test walks that path.
// 1112/01-01. "While mounted" is the platform form's rule: the page opens
// the item in `onSaved` and the list in FormSaveFeedback's `onConfirmed`,
// which the form calls only while it is mounted.
it.each(["NEVER", "KEYED"] as const)(
"does not open the item when the user left during a %s create",
(write) => {
@@ -309,10 +312,9 @@ describe("create:feature --with-create", () => {
const page =
files.get("src/features/invoice-feature/presentation/invoice-create-page.tsx") ?? "";
expect(page).toContain("if (outcome?.ok && mounted.current) {");
expect(page).toContain(
'if (mounted.current) void navigate(invoiceRouteUrl("INVOICE_LIST"));',
);
expect(page).toContain("onSaved: (item) => {");
expect(page).toContain("onConfirmed={() => {");
expect(page).not.toContain("mounted");
expect(
files.get("tests/features/invoice-feature/invoice-create-page.test.tsx"),
).toContain('it("stays on the list the user went to while the create was saving"');
@@ -569,3 +571,30 @@ describe("create:feature writing", () => {
await expect(access(path.join(root, "src"))).rejects.toThrow();
});
});
// 1112/01-01. The generated create page leaves the rules of a save through
// its mutation to the platform form: it gives useAppForm the mutation and
// draws FormSaveFeedback, so a platform fix to those rules reaches it.
describe("generated create page", () => {
it("hands the save rules to the platform form", () => {
const { files } = plan({ id: "invoice-feature", write: "KEYED" });
const page = files.get("src/features/invoice-feature/presentation/invoice-create-page.tsx") ?? "";
expect(page).toContain(" mutation,\n");
expect(page).toContain("<FormSaveFeedback");
expect(page).not.toContain("mutation.state.indicator");
expect(page).not.toContain("reconcileUnknownEffect");
});
// R-01 완료 기준 (round9 confirm review). Opening what was saved only while
// the page is open is the form's rule too (onSaved), not a mount flag the
// page keeps, and the page calls no resend or settle of its own.
it("keeps no save rule of its own", () => {
const { files } = plan({ id: "invoice-feature", write: "KEYED" });
const page = files.get("src/features/invoice-feature/presentation/invoice-create-page.tsx") ?? "";
expect(page).toContain("onSaved:");
expect(page).not.toMatch(/useRef|useEffect|mounted/u);
expect(page).not.toMatch(/resendUnknown|settleApplied|onResent/u);
});
});
Binary file not shown.

Before

Width:  |  Height:  |  Size: 90 KiB

After

Width:  |  Height:  |  Size: 90 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 189 KiB

After

Width:  |  Height:  |  Size: 189 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 190 KiB

After

Width:  |  Height:  |  Size: 189 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 123 KiB

After

Width:  |  Height:  |  Size: 123 KiB