diff --git a/config/contracts/registry-change-evidence.json b/config/contracts/registry-change-evidence.json index 5aa12b9c..3c90d861 100644 --- a/config/contracts/registry-change-evidence.json +++ b/config/contracts/registry-change-evidence.json @@ -112,6 +112,14 @@ "compatibilityWindow": "No runtime document or wire format changes: BUILD_ID was already local-build whenever VITE_BUILD_ID was unset.", "rollback": "Restore defaultValue null on VITE_BUILD_ID in src/contracts/env.ts and drop the public-target check in scripts/generate-runtime-config.ts.", "owner": "frontend-platform" + }, + { + "changeId": "FE-REG-ROUTE:REFERENCE_RESOURCE_DETAIL:path:field-changed", + "versionBump": "The reference detail route moves from /examples/reference-resources/:resourceId to /examples/reference-resources/items/:resourceId (maturity review 08-13), so a server id equal to the static segments new or status opens its detail instead of the form or status screen.", + "migration": "The only in-app link (reference-resource-page.tsx) builds the new path from the contract route. The reference feature is a sample; downstream features that copied it keep their own paths.", + "compatibilityWindow": "None for bookmarked sample detail URLs: an old /examples/reference-resources/ URL no longer matches the detail route; new and status keep opening the form and status screens.", + "rollback": "Restore the previous path in src/features/reference-feature/contracts/reference-feature-contract.ts and the link in reference-resource-page.tsx, then drop this entry.", + "owner": "frontend-platform" } ] } diff --git a/docs/accessibility/manual-checklist.md b/docs/accessibility/manual-checklist.md index 7e556367..77b804f7 100644 --- a/docs/accessibility/manual-checklist.md +++ b/docs/accessibility/manual-checklist.md @@ -63,3 +63,16 @@ The reviewer must verify: not be marked not-applicable on that route. Passing automated evidence means only that tested pages had no critical or serious axe findings under the recorded Chromium, Firefox, and WebKit runs. + +What the automated run scans: + +- Every registered route, after the route's own `h1` is on screen, so the scan + never lands on the app shell's loading surface + (`tests/e2e/accessibility.spec.ts`). A public route's `h1` must equal its + catalog title. +- Protected routes after the demo sign-in, never the sign-in prompt. Their API + calls answer an empty list there. +- The reference sample's list in its success, empty and error states, its + detail, its form with submit errors and its status page, each after that + state is on screen (`tests/e2e/reference-form.spec.ts`, removed with the + sample). diff --git a/docs/architecture/decisions/VD-04-native-form-facade.md b/docs/architecture/decisions/VD-04-native-form-facade.md index 958581c6..a27fa86e 100644 --- a/docs/architecture/decisions/VD-04-native-form-facade.md +++ b/docs/architecture/decisions/VD-04-native-form-facade.md @@ -30,7 +30,8 @@ field orchestration까지 플랫폼 기본값으로 고정하게 된다. layout과 state slot만 소유하며 application/query/HTTP를 import하지 않는다. 8. (2026-09-25, 08-01) 입력 오류가 아닌 저장 실패는 ErrorSummary에 넣지 않는다. `useAppForm`은 `action: "reauth"`를 `reauth-required`, `FORBIDDEN`을 `forbidden`, - `action: "retry"`를 `retry-later`로 구분하고 그 실패를 `failure`로 낸다. 화면은 + `action: "retry"`를 `retry-later`로, 나머지 입력 외 실패를 `unavailable`로 구분하고 + 그 실패를 `failure`로 낸다(F-10). 화면은 `FormFailureStatus`로 문구와 행동(로그인·이동·다시 시도)을 보여 준다. 재로그인은 입력을 지운다는 안내를 버튼 앞에 둔다(`src/presentation/forms/use-app-form.ts`, `form-components.tsx`). diff --git a/docs/architecture/decisions/VD-06-intl-typed-message-catalog.md b/docs/architecture/decisions/VD-06-intl-typed-message-catalog.md index 0204c94c..2b994271 100644 --- a/docs/architecture/decisions/VD-06-intl-typed-message-catalog.md +++ b/docs/architecture/decisions/VD-06-intl-typed-message-catalog.md @@ -66,9 +66,15 @@ route/form/failure 의미 값 ## 검증 -- `check:i18n`은 catalog key와 placeholder parity, common UI의 한국어 literal, - backend message JSX 렌더링과 raw HTML 사용을 검사한다. -- `check:i18n:fixture`는 세 금지 사례를 실제로 거절해야 성공으로 인정된다. +- `check:i18n`은 catalog key와 placeholder parity, 화면 코드의 한국어 literal, + backend message JSX 렌더링과 raw HTML 사용을 검사한다. 검사 범위는 공통 UI + 디렉터리, `src/presentation/pages`, 모든 `src/features/*/presentation`이다. + 컴포넌트 갤러리 `src/presentation/examples`는 일부러 뺐다 + (`scripts/check-i18n.ts`의 `commonDirectories`, `featurePresentationDirectories`). +- `check:i18n:fixture`는 같은 탐색 규칙을 `tests/fixtures/i18n/forbidden` 트리에 + 돌린다. fixture 파일 하나라도 거절되지 않으면 종료 코드 2로 실패한다. +- `tests/unit/i18n-contract.test.ts`는 `ERROR_REGISTRY`의 모든 `userMessageKey`가 + ko-KR·en-US catalog에 있는지 확인한다. - type negative fixture는 unknown key와 잘못된 parameter shape를 거절한다. - unit test는 fallback, alias, pseudo 확장, direction과 timezone/number/relative/ list/plural/select의 결정성을 검증한다. diff --git a/docs/architecture/routing-pages-and-patterns.md b/docs/architecture/routing-pages-and-patterns.md index 98d214c4..89515500 100644 --- a/docs/architecture/routing-pages-and-patterns.md +++ b/docs/architecture/routing-pages-and-patterns.md @@ -280,6 +280,18 @@ chunk recovery 순서: 4. 안전한 support surface와 trace/build ID를 표시한다. 5. recovery 결과를 redacted diagnostics에 기록한다. +지원 참조는 사용자가 문의할 때 말하는 값이고, 진단 이벤트에서 같은 값을 찾을 +수 있다. + +- 라우트 렌더 실패: `buildId:incidentId`. 같은 incident ID가 `ui.render.failed` + 진단의 `correlation_id`에 남는다(`render-error-boundary.tsx`의 + `newIncidentId`, `create-application.ts`의 `reportRenderFailure`). 화면에는 + "한 번 새로고침" 버튼이 있다(`app-router.tsx`의 `RouteFailureSurface`). +- 복구하지 못한 청크 실패: 같은 형식이다. `ChunkRecoveryBoundary`의 + `onUnrecovered`가 같은 ID로 `ui.render.failed`를 기록한다. +- 조회 실패: `AppFailure.requestId`. HTTP 진단의 `correlation_id`와 같은 값이다 + (`async-surface.tsx`의 `TerminalErrorSurface`). + custom fallback을 넘겨 retry/reset 기능을 잃지 않게 한다. boundary는 `location.key` 또는 route ID가 바뀌면 적절히 reset된다. @@ -289,9 +301,15 @@ custom fallback을 넘겨 retry/reset 기능을 잃지 않게 한다. boundary - mouse 사용자가 불필요한 focus ring을 보지 않게 할 수는 있지만 keyboard focus indication을 전역으로 제거하지 않음 - modal/drawer가 닫히면 opener에 focus 복원 -- backward/forward navigation은 저장한 scroll 복원 +- backward/forward navigation은 저장한 scroll 복원. 복원은 브라우저가 하고, + `RouteLifecycle`은 POP이 아닐 때만 top으로 보낸다(`app-router.tsx`). + `PageHeader`의 heading focus는 `preventScroll`이라 복원된 위치를 옮기지 않는다 - 새 primary route는 top으로 이동 -- hash target은 fixed header offset과 focus 가능 여부를 처리 +- hash target은 fixed header offset과 focus 가능 여부를 처리. 페이지가 그려진 뒤 + `PageHeader`가 대상으로 스크롤하고, 대상이 focus 가능하면 대상에, 아니면 + heading에 focus한다(`page-header.tsx`). header 높이는 `html`의 + `scroll-padding-top`으로 뺀다(`shell.css`). 브라우저 검증은 + `tests/e2e/scroll-restoration.spec.ts` - screen reader용 route title/live announcement는 중복 발표를 피함 ### 6.4 취소와 dirty form diff --git a/docs/architecture/typescript-state-and-data-flow.md b/docs/architecture/typescript-state-and-data-flow.md index 3c60cddf..9e77d838 100644 --- a/docs/architecture/typescript-state-and-data-flow.md +++ b/docs/architecture/typescript-state-and-data-flow.md @@ -599,7 +599,7 @@ Form 또는 TanStack Form adapter를 평가한다. - `Description` - `FieldError` - `ErrorSummary` -- `FormFailureStatus` (재로그인·권한 없음·잠시 후 재시도 저장 실패) +- `FormFailureStatus` (재로그인·권한 없음·잠시 후 재시도·그 밖의 저장 불가 실패) - `useAppForm` - `mapValidationFailureToFields` - `useDirtyNavigationGuard` @@ -623,7 +623,7 @@ backend message와 알 수 없는 path는 field copy로 사용하지 않는다. 3. submitting 중 중복 제출 방지 4. 422 응답의 알려진 field만 표시하고 나머지는 form-level failure로 처리 5. 409 conflict는 validation error로 위장하지 않음 -5a. 401·403·429 같은 입력 외 실패는 ErrorSummary가 아니라 `FormFailureStatus`로 표시 +5a. 401·403·429와 404 같은 입력 외 실패는 ErrorSummary가 아니라 `FormFailureStatus`로 표시(`use-app-form.ts`의 `STATUS_RESULTS`) 6. 취소와 route 이탈 시 dirty policy 적용 7. form value → application command mapper를 별도 함수로 둠 8. browser autofill, IME composition, paste, password manager를 방해하지 않음 diff --git a/docs/styling/design-system-platform.md b/docs/styling/design-system-platform.md index 48f16cfd..0f25b452 100644 --- a/docs/styling/design-system-platform.md +++ b/docs/styling/design-system-platform.md @@ -306,8 +306,8 @@ Pattern은 여러 primitive를 조합해 반복되는 사용자 문제를 해결 | Pattern | 필수 내용 | | --- | --- | -| `AsyncSurface` | loading, success, empty, terminal error, stale, refresh | -| `AccessSurface` | auth required, forbidden, not found | +| `AsyncSurface` | loading, success, empty, terminal error, stale, refresh. 조회 실패가 `AUTH_REQUIRED`·`FORBIDDEN`·`NOT_FOUND`이면 `AccessSurface`와 같은 화면(`state-surfaces.tsx`)을 그린다(`async-surface.tsx`의 `ACCESS_SURFACES`) | +| `AccessSurface` | auth required, forbidden, not found. 조회 실패와 갤러리가 이 한 벌을 쓴다 | | `Form` | submit, error summary, first-invalid focus, pending | | `ConfirmationDialog` | destructive action 설명과 명시적 확인 | | `ToastRegion` | queue, announcement, dismiss, focus policy | diff --git a/scripts/check-i18n.ts b/scripts/check-i18n.ts index ae62611e..e1a58c88 100644 --- a/scripts/check-i18n.ts +++ b/scripts/check-i18n.ts @@ -52,20 +52,45 @@ if (!fixtureMode) { } } +// 08-04. Screen code under these directories must take its words from the +// catalog. `src/presentation/examples` is the component gallery and stays out +// of scope on purpose. Fixture mode runs the same discovery on a fixture tree. +const sourceRoot = fixtureMode ? "tests/fixtures/i18n/forbidden" : "."; const commonDirectories = [ "src/presentation/boundaries", "src/presentation/components", "src/presentation/design-system", "src/presentation/forms", "src/presentation/layouts", + "src/presentation/pages", "src/presentation/routes", "src/presentation/templates", ]; -const sources = fixtureMode - ? await listSourceFiles("tests/fixtures/i18n/forbidden") - : ( - await Promise.all(commonDirectories.map((directory) => listSourceFiles(directory))) - ).flat(); + +async function featurePresentationDirectories(root: string): Promise { + const features = path.join(root, "src/features"); + const entries = await readdir(features, { withFileTypes: true }).catch( + () => [], + ); + return entries + .filter((entry) => entry.isDirectory()) + .map((entry) => path.join("src/features", entry.name, "presentation")); +} + +async function existingSourceFiles(directory: string): Promise { + return listSourceFiles(directory).catch((error: NodeJS.ErrnoException) => { + if (error.code === "ENOENT") return []; + throw error; + }); +} + +const sourceDirectories = [ + ...commonDirectories, + ...(await featurePresentationDirectories(sourceRoot)), +].map((directory) => path.join(sourceRoot, directory)); +const sources = ( + await Promise.all(sourceDirectories.map(existingSourceFiles)) +).flat(); for (const file of sources) { const source = await readFile(file, "utf8"); @@ -98,6 +123,19 @@ await writeValidatedJsonArtifact({ value: report, }); +// Every fixture file must be rejected on its own; one rejected file must not +// hide a directory the discovery above stopped reaching. +const fixtureFiles = fixtureMode ? await listSourceFiles(sourceRoot) : []; +const unrejectedFixtures = fixtureFiles.filter( + (file) => !failures.some((failure) => failure.endsWith(file)), +); +if (fixtureMode && (fixtureFiles.length === 0 || unrejectedFixtures.length > 0)) { + process.stderr.write( + `I18n fixture was not rejected:\n${unrejectedFixtures.join("\n") || "(no fixture files found)"}\n`, + ); + process.exit(2); +} + if (failures.length > 0) { process.stderr.write(`I18n contract failed:\n${failures.join("\n")}\n`); process.exit(1); diff --git a/src/application/create-application.ts b/src/application/create-application.ts index fccb38da..5625e5de 100644 --- a/src/application/create-application.ts +++ b/src/application/create-application.ts @@ -62,6 +62,11 @@ export function createApplication( route_id: report.routeId, build_id: report.buildId, component_boundary: report.boundaryName, + // Incident-scoped like a request id: diagnostics only, never + // telemetry. + ...(report.incidentId === undefined + ? {} + : { correlation_id: report.incidentId }), }, }); } catch { diff --git a/src/application/ports/in/application-api.ts b/src/application/ports/in/application-api.ts index f4f7f2bb..fbf7564c 100644 --- a/src/application/ports/in/application-api.ts +++ b/src/application/ports/in/application-api.ts @@ -24,6 +24,8 @@ export type RenderFailureReport = Readonly<{ routeId: string; buildId: string; boundaryName: "route" | "feature"; + /** 08-07. The id the failure page shows as its support reference. */ + incidentId?: string; }>; export type RouteChangedReport = Readonly<{ diff --git a/src/features/reference-feature/contracts/reference-feature-contract.ts b/src/features/reference-feature/contracts/reference-feature-contract.ts index 3bac006e..fb06ea59 100644 --- a/src/features/reference-feature/contracts/reference-feature-contract.ts +++ b/src/features/reference-feature/contracts/reference-feature-contract.ts @@ -88,7 +88,8 @@ export const REFERENCE_FEATURE_CONTRACT = Object.freeze({ }), REFERENCE_RESOURCE_DETAIL: Object.freeze({ routeId: "REFERENCE_RESOURCE_DETAIL", - path: "/examples/reference-resources/:resourceId", + // 08-13. `items/` keeps an id such as `new` or `status` off the static routes. + path: "/examples/reference-resources/items/:resourceId", paramsSchema: "ReferenceResourceParams", searchSchema: null, access: "session-required", diff --git a/src/features/reference-feature/contracts/reference-message-catalog.ts b/src/features/reference-feature/contracts/reference-message-catalog.ts index a7880c98..e080dcb1 100644 --- a/src/features/reference-feature/contracts/reference-message-catalog.ts +++ b/src/features/reference-feature/contracts/reference-message-catalog.ts @@ -8,6 +8,41 @@ export const REFERENCE_MESSAGE_CATALOGS = Object.freeze({ "route.REFERENCE_RESOURCE_FORM.title": "Create reference resource", "route.REFERENCE_RESOURCE_STATUS.navigation": "Reference status", "route.REFERENCE_RESOURCE_STATUS.title": "Reference resource status", + "reference.list.eyebrow": "제거 가능한 수직 슬라이스", + "reference.list.description": + "URL codec, application input, HTTP/schema/mapper와 query 상태를 한 경로로 검증합니다.", + "reference.list.create": "새 항목 만들기", + "reference.list.refresh": "새로고침", + "reference.list.resultCount": "총 {count}개 항목", + "reference.form.back": "목록으로 돌아가기", + "reference.form.title": "Reference resource 만들기", + "reference.form.description": + "presentation schema, command mapper, 422/conflict와 dirty navigation 정책을 실행합니다.", + "reference.form.name": "새 항목 이름", + "reference.form.nameDescription": + "앞뒤 공백은 command mapper 전에 제거됩니다.", + "reference.form.note": "설명", + "reference.form.noteDescription": + "선택 입력이며 비어 있으면 command에 포함되지 않습니다.", + "reference.form.cancel": "취소", + "reference.form.save": "저장", + "reference.form.saving": "저장 중…", + "reference.form.reset": "초기화", + "reference.form.reloadList": "목록을 새로 불러와 확인", + "reference.form.saved": "저장했습니다.", + "reference.form.conflict": "충돌을 해결한 뒤 다시 제출할 수 있습니다.", + "reference.form.privacy": + "form value는 URL, storage, telemetry에 저장되지 않고 submit 시에만 application command로 변환됩니다.", + "reference.detail.description": + "route param과 detail query의 reset 경계를 확인합니다.", + "reference.detail.summaryPending": "요약 정보를 준비하고 있습니다.", + "reference.detail.sectionSlot": + "이 영역에는 제품별 상세 section을 조립할 수 있습니다.", + "reference.detail.aside": "상세 페이지의 관련 정보 slot입니다.", + "reference.status.title": "잠시 사용할 수 없습니다.", + "reference.status.description": + "도메인 데이터나 raw 오류를 노출하지 않는 중립적인 상태 페이지 예시입니다.", + "reference.status.back": "목록으로 이동", }), "en-US": Object.freeze({ "route.REFERENCE_RESOURCE_LIST.navigation": "Reference feature", @@ -18,5 +53,40 @@ export const REFERENCE_MESSAGE_CATALOGS = Object.freeze({ "route.REFERENCE_RESOURCE_FORM.title": "Create reference resource", "route.REFERENCE_RESOURCE_STATUS.navigation": "Reference status", "route.REFERENCE_RESOURCE_STATUS.title": "Reference resource status", + "reference.list.eyebrow": "Removable vertical slice", + "reference.list.description": + "Checks the URL codec, application input, HTTP/schema/mapper and query state along one path.", + "reference.list.create": "Create item", + "reference.list.refresh": "Refresh", + "reference.list.resultCount": "Total items: {count}", + "reference.form.back": "Back to the list", + "reference.form.title": "Create a reference resource", + "reference.form.description": + "Runs the presentation schema, command mapper, 422/conflict and dirty navigation policies.", + "reference.form.name": "New item name", + "reference.form.nameDescription": + "Leading and trailing spaces are removed before the command mapper.", + "reference.form.note": "Description", + "reference.form.noteDescription": + "Optional. An empty value is left out of the command.", + "reference.form.cancel": "Cancel", + "reference.form.save": "Save", + "reference.form.saving": "Saving…", + "reference.form.reset": "Reset", + "reference.form.reloadList": "Reload the list to check", + "reference.form.saved": "Saved.", + "reference.form.conflict": "Resolve the conflict, then submit again.", + "reference.form.privacy": + "Form values are never written to the URL, storage or telemetry; they become an application command only on submit.", + "reference.detail.description": + "Checks the reset boundary between the route parameter and the detail query.", + "reference.detail.summaryPending": "Preparing the summary.", + "reference.detail.sectionSlot": + "Product-specific detail sections can be assembled here.", + "reference.detail.aside": "Related information slot of the detail page.", + "reference.status.title": "Temporarily unavailable.", + "reference.status.description": + "An example of a neutral status page that exposes no domain data or raw errors.", + "reference.status.back": "Go to the list", }), } as const); diff --git a/src/features/reference-feature/presentation/reference-resource-detail-page.tsx b/src/features/reference-feature/presentation/reference-resource-detail-page.tsx index 008bd259..447a091a 100644 --- a/src/features/reference-feature/presentation/reference-resource-detail-page.tsx +++ b/src/features/reference-feature/presentation/reference-resource-detail-page.tsx @@ -26,7 +26,7 @@ export default function ReferenceResourceDetailPage() { heading={{ eyebrow: "DetailPage", title: resource?.title ?? "Reference detail", - description: "route param과 detail query의 reset 경계를 확인합니다.", + description: message("reference.detail.description"), }} metadata={ resource ? ( @@ -41,7 +41,7 @@ export default function ReferenceResourceDetailPage() { ) : ( -

요약 정보를 준비하고 있습니다.

+

{message("reference.detail.summaryPending")}

) } feedback={ @@ -51,11 +51,11 @@ export default function ReferenceResourceDetailPage() { onRetry={query.retry} > {resource ? ( -

이 영역에는 제품별 상세 section을 조립할 수 있습니다.

+

{message("reference.detail.sectionSlot")}

) : null} } - aside={

상세 페이지의 관련 정보 slot입니다.

} + aside={

{message("reference.detail.aside")}

} /> ); } diff --git a/src/features/reference-feature/presentation/reference-resource-form-page.tsx b/src/features/reference-feature/presentation/reference-resource-form-page.tsx index 80bec0f4..d884853c 100644 --- a/src/features/reference-feature/presentation/reference-resource-form-page.tsx +++ b/src/features/reference-feature/presentation/reference-resource-form-page.tsx @@ -14,6 +14,7 @@ import { useAppForm, useDirtyNavigationGuard, } from "../../../presentation/design-system/index.ts"; +import { useLocale } from "../../../presentation/i18n/index.ts"; import { useQueryInvalidationCoordinator } from "../../../presentation/adapters/query/query-invalidation-provider.tsx"; import { REFERENCE_RESOURCE_INVALIDATION_TOPIC } from "../contracts/reference-feature-contract.ts"; import { @@ -25,13 +26,13 @@ import { import { useReferenceFailureAction } from "./use-reference-failure-action.ts"; import { useReferenceCreate } from "./use-reference-feature.ts"; -const FIELD_LABELS = Object.freeze({ - name: "새 항목 이름", - note: "설명", -}) satisfies Record; - export default function ReferenceResourceFormPage() { const navigate = useNavigate(); + const { message } = useLocale(); + const fieldLabels = { + name: message("reference.form.name"), + note: message("reference.form.note"), + } satisfies Record; const mutation = useReferenceCreate(); const invalidation = useQueryInvalidationCoordinator(); const submit = useCallback( @@ -72,20 +73,19 @@ export default function ReferenceResourceFormPage() { type="button" onClick={() => navigate("/examples/reference-resources")} > - 목록으로 돌아가기 + {message("reference.form.back")} } heading={{ eyebrow: "FormPage", - title: "Reference resource 만들기", - description: - "presentation schema, command mapper, 422/conflict와 dirty navigation 정책을 실행합니다.", + title: message("reference.form.title"), + description: message("reference.form.description"), }} errorSummary={ @@ -94,15 +94,15 @@ export default function ReferenceResourceFormPage() { <> @@ -114,20 +114,22 @@ export default function ReferenceResourceFormPage() { onClick={() => navigate("/examples/reference-resources")} disabled={form.pending || mutationBlocked} > - 취소 + {message("reference.form.cancel")} } @@ -163,21 +165,18 @@ export default function ReferenceResourceFormPage() { .catch(() => {}); }} > - 목록을 새로 불러와 확인 + {message("reference.form.reloadList")}

) : form.result === "success" ? ( -

저장했습니다.

+

{message("reference.form.saved")}

) : form.result === "conflict" ? ( -

충돌을 해결한 뒤 다시 제출할 수 있습니다.

+

{message("reference.form.conflict")}

) : null } aside={ -

- form value는 URL, storage, telemetry에 저장되지 않고 submit 시에만 - application command로 변환됩니다. -

+

{message("reference.form.privacy")}

} guard={} /> diff --git a/src/features/reference-feature/presentation/reference-resource-form.ts b/src/features/reference-feature/presentation/reference-resource-form.ts index 27af8f7b..39a2ebaa 100644 --- a/src/features/reference-feature/presentation/reference-resource-form.ts +++ b/src/features/reference-feature/presentation/reference-resource-form.ts @@ -5,7 +5,7 @@ export const referenceResourceFormSchema = z name: z .string() .trim() - .min(2, "이름은 두 글자 이상이어야 합니다.") + .min(2) .max(120), note: z.string().trim().max(500).default(""), }) diff --git a/src/features/reference-feature/presentation/reference-resource-page.tsx b/src/features/reference-feature/presentation/reference-resource-page.tsx index d3ac3634..16b04572 100644 --- a/src/features/reference-feature/presentation/reference-resource-page.tsx +++ b/src/features/reference-feature/presentation/reference-resource-page.tsx @@ -5,26 +5,30 @@ import { Button, CollectionPage, } from "../../../presentation/design-system/index.ts"; +import { + resolveMessage, + useLocale, +} from "../../../presentation/i18n/index.ts"; import { useReferenceFailureAction } from "./use-reference-failure-action.ts"; import { useReferenceFeature } from "./use-reference-feature.ts"; export default function ReferenceResourcePage() { const navigate = useNavigate(); + const { locale, message } = useLocale(); const { filters, query } = useReferenceFeature(); const failureAction = useReferenceFailureAction(query.state.failure); return ( navigate("/examples/reference-resources/new"), }, ]} @@ -34,9 +38,20 @@ export default function ReferenceResourcePage() { {filters.tags?.length ? ` · tags ${filters.tags.join(", ")}` : ""}

} - toolbar={} + toolbar={ + + } resultCount={ - query.data ? `총 ${query.data.length}개 항목` : "결과 확인 중" + // 08-09. Counted only from a settled result: a loading, idle or + // failed list has nothing to count. Feature keys carry no parameter + // types, so the count goes through the untyped resolver. + query.state.base === "success" || query.state.base === "empty" + ? resolveMessage(locale, "reference.list.resultCount", { + count: query.data?.length ?? 0, + }) + : null } > (
  • {resource.title} diff --git a/src/features/reference-feature/presentation/reference-resource-status-page.tsx b/src/features/reference-feature/presentation/reference-resource-status-page.tsx index b98764af..28ad01a5 100644 --- a/src/features/reference-feature/presentation/reference-resource-status-page.tsx +++ b/src/features/reference-feature/presentation/reference-resource-status-page.tsx @@ -1,22 +1,23 @@ import { useNavigate } from "react-router-dom"; import { StatusPage } from "../../../presentation/design-system/index.ts"; +import { useLocale } from "../../../presentation/i18n/index.ts"; export default function ReferenceResourceStatusPage() { const navigate = useNavigate(); + const { message } = useLocale(); return ( navigate("/examples/reference-resources"), }} supportReference="REFERENCE-STATUS-DEMO" diff --git a/src/presentation/boundaries/chunk-recovery-boundary.tsx b/src/presentation/boundaries/chunk-recovery-boundary.tsx index 8cc8e375..cca4ca6d 100644 --- a/src/presentation/boundaries/chunk-recovery-boundary.tsx +++ b/src/presentation/boundaries/chunk-recovery-boundary.tsx @@ -5,6 +5,7 @@ import { } from "react"; import { Button, LoadingSurface } from "../design-system/index.ts"; import { useLocale } from "../i18n/index.ts"; +import { newIncidentId } from "./render-error-boundary.tsx"; type RecoveryResult = | Readonly<{ action: "reload-once"; releasePair: string }> @@ -17,12 +18,17 @@ type Props = Readonly<{ chunkId: string; failureKind: "CHUNK_LOAD_FAILURE"; }>): Promise; + /** 08-07. Shown with the incident id as the support reference. */ + buildId?: string; + /** 08-07. Records the incident id the support surface shows. */ + onUnrecovered?: (incidentId: string) => void; }>; type State = Readonly<{ error: unknown | null; recovery: "idle" | "checking" | "reload-requested" | "support"; reason?: string; + incidentId?: string; }>; export function isChunkLoadFailure(error: unknown): boolean { @@ -55,26 +61,29 @@ export class ChunkRecoveryBoundary extends Component { failureKind: "CHUNK_LOAD_FAILURE", }) .then((result) => { - this.setState({ - error, - recovery: - result.action === "reload-once" - ? "reload-requested" - : "support", - ...(result.action === "support" ? { reason: result.reason } : {}), - }); + if (result.action === "support") { + this.showSupport(error, result.reason); + } else { + this.setState({ error, recovery: "reload-requested" }); + } }) .catch(() => { - this.setState({ - error, - recovery: "support", - reason: "recovery-controller-failed", - }); + this.showSupport(error, "recovery-controller-failed"); }); } + private showSupport(error: unknown, reason: string) { + const incidentId = newIncidentId(); + this.setState({ error, recovery: "support", reason, incidentId }); + try { + this.props.onUnrecovered?.(incidentId); + } catch { + // Diagnostics must never hide the recovery surface. + } + } + render() { - const { error, recovery, reason } = this.state; + const { error, recovery, reason, incidentId } = this.state; if (error && !isChunkLoadFailure(error)) throw error; if (error && recovery === "checking") { return ; @@ -83,7 +92,15 @@ export class ChunkRecoveryBoundary extends Component { return ; } if (error && recovery === "support") { - return ; + return ( + + ); } return this.props.children; } @@ -92,9 +109,11 @@ export class ChunkRecoveryBoundary extends Component { function ChunkRecoverySurface({ recovery, reason, + supportReference, }: Readonly<{ recovery: Exclude; reason?: string; + supportReference?: string; }>) { const { message } = useLocale(); if (recovery === "checking") { @@ -119,6 +138,13 @@ function ChunkRecoverySurface({ + {supportReference ? ( +

    + {message("template.supportReference", { + reference: supportReference, + })} +

    + ) : null} ); } diff --git a/src/presentation/boundaries/render-error-boundary.tsx b/src/presentation/boundaries/render-error-boundary.tsx index 36e69ad8..6d4f39b9 100644 --- a/src/presentation/boundaries/render-error-boundary.tsx +++ b/src/presentation/boundaries/render-error-boundary.tsx @@ -10,10 +10,24 @@ export type RenderBoundaryProps = Readonly<{ buildId: string; resetKey?: string; onRenderFailure?: (report: RenderFailureReport) => void; - fallback?: ReactNode; + /** A function receives the incident id the failure was reported with. */ + fallback?: ReactNode | ((incidentId: string) => ReactNode); }>; -type RenderBoundaryState = Readonly<{ hasError: boolean }>; +type RenderBoundaryState = Readonly<{ + hasError: boolean; + incidentId?: string; +}>; + +/** + * 08-07. A short id a failure page shows as its support reference and the + * render diagnostic records, so a user's report finds the event. + * `getRandomValues` also works outside secure contexts, unlike `randomUUID`. + */ +export function newIncidentId(): string { + const [value = 0] = crypto.getRandomValues(new Uint32Array(1)); + return value.toString(16).padStart(8, "0"); +} export class RenderErrorBoundary extends Component< RenderBoundaryProps, @@ -22,7 +36,7 @@ export class RenderErrorBoundary extends Component< state: RenderBoundaryState = { hasError: false }; static getDerivedStateFromError(): RenderBoundaryState { - return { hasError: true }; + return { hasError: true, incidentId: newIncidentId() }; } componentDidCatch(): void { @@ -31,6 +45,9 @@ export class RenderErrorBoundary extends Component< routeId: this.props.routeId, buildId: this.props.buildId, boundaryName: this.props.boundaryName, + ...(this.state.incidentId === undefined + ? {} + : { incidentId: this.state.incidentId }), }); } catch { // Diagnostics must never recurse into another render failure. @@ -49,9 +66,11 @@ export class RenderErrorBoundary extends Component< render(): ReactNode { if (this.state.hasError) { - return ( - this.props.fallback ?? - ); + const { fallback } = this.props; + if (typeof fallback === "function") { + return fallback(this.state.incidentId ?? newIncidentId()); + } + return fallback ?? ; } return this.props.children; } diff --git a/src/presentation/components/async-surface.tsx b/src/presentation/components/async-surface.tsx index e551e43b..834fd8a9 100644 --- a/src/presentation/components/async-surface.tsx +++ b/src/presentation/components/async-surface.tsx @@ -4,6 +4,11 @@ import type { AsyncState } from "../../application/view-models/async-state.ts"; import type { AppFailure } from "../../contracts/errors.ts"; import { useLocale } from "../i18n/index.ts"; import { errorMessage } from "./error-copy.ts"; +import { + AuthRequiredSurface, + ForbiddenSurface, + NotFoundSurface, +} from "./state-surfaces.tsx"; import { Button } from "./ui/button.ts"; export function LoadingSurface({ @@ -57,6 +62,8 @@ export type TerminalErrorSurfaceProps = Readonly<{ onAction?: () => void; /** Read before the action, inside the same alert. */ description?: string; + /** 08-07. The id a user quotes to support, e.g. `AppFailure.requestId`. */ + supportReference?: string; }>; export function TerminalErrorSurface({ @@ -64,6 +71,7 @@ export function TerminalErrorSurface({ action, onAction, description, + supportReference, }: TerminalErrorSurfaceProps) { const { locale, message } = useLocale(); const messageId = useId(); @@ -88,6 +96,13 @@ export function TerminalErrorSurface({ {action !== "none" && onAction && ( )} + {supportReference ? ( +

    + {message("template.supportReference", { + reference: supportReference, + })} +

    + ) : null} ); } @@ -121,6 +136,23 @@ export function AsyncSurface({ if (state.base === "initial-loading") return ; if (state.base === "empty") return ; if (state.base === "terminal-error" && state.failure) { + const AccessState = ACCESS_SURFACES[state.failure.kind]; + if (AccessState) { + // 08-11. Access failures use the same surfaces as the design system's + // AccessSurface, so a query and the gallery show one copy. + return ( +
    + + {state.failure.requestId ? ( +

    + {message("template.supportReference", { + reference: state.failure.requestId, + })} +

    + ) : null} +
    + ); + } return ( ); } @@ -177,3 +210,16 @@ export function AsyncSurface({ ); } + +const ACCESS_SURFACES: Readonly< + Partial< + Record< + AppFailure["kind"], + (props: Readonly<{ onAction?: () => void }>) => ReactNode + > + > +> = Object.freeze({ + AUTH_REQUIRED: ({ onAction }) => , + FORBIDDEN: ({ onAction }) => , + NOT_FOUND: ({ onAction }) => , +}); diff --git a/src/presentation/components/page-header.tsx b/src/presentation/components/page-header.tsx index 1eb3addd..870d02de 100644 --- a/src/presentation/components/page-header.tsx +++ b/src/presentation/components/page-header.tsx @@ -6,6 +6,15 @@ export type PageHeaderProps = Readonly<{ eyebrow?: string; }>; +function hashTarget(): HTMLElement | null { + try { + const id = decodeURIComponent(window.location.hash.slice(1)); + return id ? document.getElementById(id) : null; + } catch { + return null; + } +} + export function PageHeader({ title, description, @@ -21,9 +30,15 @@ export function PageHeader({ activeElement === document.body || activeElement === document.documentElement || activeElement === main; - if (routeOwnsFocus) { - headingRef.current?.focus(); - } + if (!routeOwnsFocus) return; + // 08-08. A hash names a target in this page, which exists only once the + // page has rendered. Focus never scrolls: back navigation keeps the + // position the browser restored. + const target = hashTarget(); + target?.scrollIntoView?.(); + (target && target.tabIndex >= 0 ? target : headingRef.current)?.focus({ + preventScroll: true, + }); }, [title]); return ( diff --git a/src/presentation/components/state-surfaces.tsx b/src/presentation/components/state-surfaces.tsx index d48c546a..c7400d5d 100644 --- a/src/presentation/components/state-surfaces.tsx +++ b/src/presentation/components/state-surfaces.tsx @@ -23,7 +23,9 @@ function StateSurface({

    {eyebrow}

    {title}

    {description}

    - {actionLabel ? : null} + {actionLabel && onAction ? ( + + ) : null} ); } diff --git a/src/presentation/design-system/primitives/navigation.tsx b/src/presentation/design-system/primitives/navigation.tsx index d19b6074..1fac75dc 100644 --- a/src/presentation/design-system/primitives/navigation.tsx +++ b/src/presentation/design-system/primitives/navigation.tsx @@ -267,7 +267,17 @@ function PageLinks({ key={candidate} onClick={(event) => { // The owner decides how a page change is applied; the href is for - // open-in-new-tab and copy-link. + // open-in-new-tab and copy-link, so a modified or non-primary + // click stays with the browser (08-12). + if ( + event.button !== 0 || + event.metaKey || + event.altKey || + event.ctrlKey || + event.shiftKey + ) { + return; + } event.preventDefault(); onChange(candidate); }} diff --git a/src/presentation/forms/form-components.tsx b/src/presentation/forms/form-components.tsx index f87d771f..4b91fc2f 100644 --- a/src/presentation/forms/form-components.tsx +++ b/src/presentation/forms/form-components.tsx @@ -82,7 +82,7 @@ export function ErrorSummary(props: Readonly<{ /** * 08-01. A save that failed for a reason other than the input (sign-in, - * permission, retry later) is announced here with its own action, not in + * permission, retry later, unavailable) is announced here with its own action, not in * ErrorSummary. Pass `useAppForm().failure`. */ export function FormFailureStatus(props: Readonly<{ diff --git a/src/presentation/forms/use-app-form.ts b/src/presentation/forms/use-app-form.ts index 80556329..e39d3877 100644 --- a/src/presentation/forms/use-app-form.ts +++ b/src/presentation/forms/use-app-form.ts @@ -43,7 +43,7 @@ export function useAppForm< Command, Output, >(options: AppFormOptions) { - const { message } = useLocale(); + const { resolve } = useLocale(); const { schema, defaultValues, @@ -59,10 +59,28 @@ export function useAppForm< const [touched, setTouched] = useState>>( () => new Set(), ); - const [fieldErrors, setFieldErrors] = useState>( + // 08-10. Errors are held as message keys and translated on render, so a + // locale change re-translates the ones already on screen. + const [fieldErrorKeys, setFieldErrors] = useState>( () => ({} as FieldErrors), ); - const [formErrors, setFormErrors] = useState([]); + const [formErrorKeys, setFormErrors] = useState([]); + const fieldErrors = useMemo( + () => + Object.freeze( + Object.fromEntries( + Object.entries(fieldErrorKeys).map(([name, key]) => [ + name, + resolve(String(key)), + ]), + ), + ) as FieldErrors, + [fieldErrorKeys, resolve], + ); + const formErrors = useMemo( + () => formErrorKeys.map((key) => resolve(key)), + [formErrorKeys, resolve], + ); const [pending, setPending] = useState(false); const [result, setResult] = useState("idle"); const [statusFailure, setStatusFailure] = useState(null); @@ -188,7 +206,7 @@ export function useAppForm< const mapped = mapValidationFailureToFields( outcome.error, allowedServerFields, - message, + messageKey, ); setFieldErrors(mapped.fieldErrors); setFormErrors(mapped.formErrors); @@ -208,9 +226,7 @@ export function useAppForm< settleSuccessfulValues(submittedValues); } else if (outcome.error.kind === "CONFLICT") { unknownSubmissionRef.current = null; - setFormErrors([ - message("form.conflict"), - ]); + setFormErrors(["form.conflict"]); setResult("conflict"); } else if ( outcome.error.kind === "FORBIDDEN" || @@ -223,12 +239,14 @@ export function useAppForm< outcome.error.kind === "FORBIDDEN" ? "forbidden" : "retry-later", ); } else { + // F-10. Not an input error either: shown by FormFailureStatus. unknownSubmissionRef.current = null; - setFormErrors([message("form.unavailable")]); + setFormErrors([]); + setStatusFailure(outcome.error); setResult("unavailable"); } }, - [allowedServerFields, focusFirstError, message, settleSuccessfulValues], + [allowedServerFields, focusFirstError, settleSuccessfulValues], ); const validateAndSubmit = useCallback( @@ -241,14 +259,14 @@ export function useAppForm< const errors = issuesToFieldErrors( parsed.error.issues, allowedServerFields, - message, + messageKey, ); setFieldErrors(errors); setFormErrors( parsed.error.issues.some( (issue) => !allowedServerFields.includes(issue.path[0] as FieldName), ) - ? [message("form.validation.configuration")] + ? ["form.validation.configuration"] : [], ); setTouched(new Set(allowedServerFields)); @@ -272,7 +290,6 @@ export function useAppForm< applyOutcome, focusFirstError, mapToCommand, - message, schema, submit, values, @@ -335,7 +352,10 @@ export function useAppForm< formErrors, pending, result, - /** The save failure behind `reauth-required`, `forbidden` or `retry-later`. */ + /** + * The save failure behind `reauth-required`, `forbidden`, `retry-later` + * or `unavailable`. + */ failure: STATUS_RESULTS.has(result) ? statusFailure : null, field, fieldId, @@ -349,10 +369,14 @@ export function useAppForm< }); } +/** Keeps the key: the form translates at render time. */ +const messageKey = (key: ParameterlessMessageKey): string => key; + const STATUS_RESULTS: ReadonlySet = new Set([ "reauth-required", "forbidden", "retry-later", + "unavailable", ]); function issuesToFieldErrors( diff --git a/src/presentation/i18n/catalog.ts b/src/presentation/i18n/catalog.ts index f5276223..03a0f202 100644 --- a/src/presentation/i18n/catalog.ts +++ b/src/presentation/i18n/catalog.ts @@ -99,6 +99,28 @@ const PLATFORM_KO_MESSAGES = { "chunk.failure.title": "화면 자산을 복구하지 못했습니다.", "chunk.failure.description": "문제가 계속되면 배포 상태와 지원 참조 정보를 확인해 주세요.", + "home.eyebrow": "프로젝트 시작점", + "home.description": + "도메인을 추가하기 전에 실행 구조와 범용 사용자 경험을 확인할 수 있는 중립적인 스켈레톤입니다.", + "home.readiness": "구현 준비 상태", + "home.readiness.contract.title": "실행 계약", + "home.readiness.contract.description": + "런타임 설정, 릴리스 정합성, 오류 경계가 마운트 전에 검증됩니다.", + "home.readiness.adapters.title": "교체 가능한 연동", + "home.readiness.adapters.description": + "인증, HTTP, 캐시, 저장소, 텔레메트리가 포트 뒤에 분리되어 있습니다.", + "home.readiness.accessibility.title": "접근 가능한 화면", + "home.readiness.accessibility.description": + "키보드 탐색, 포커스 이동, 반응형 앱 셸의 기본 동작이 준비되어 있습니다.", + "home.runtime.checking": "검증된 런타임 정보를 확인하고 있습니다.", + "home.runtime.failed": "런타임 정보를 확인하지 못했습니다.", + "home.runtime.summary": "빌드 {buildId} · 릴리스 {releaseId}", + "home.starter.title": "준비된 화면 살펴보기", + "home.starter.description": + "설치된 라우트와 계약, 런타임 능력은 플랫폼 구성 화면에서, 공통 구성요소와 비동기 화면 상태는 예제 라우트에서 확인하세요.", + "home.starter.platform": "플랫폼 구성 보기", + "home.starter.ui": "UI 구성요소 보기", + "home.starter.states": "화면 상태 보기", "page.notFound.title": "페이지를 찾을 수 없습니다.", "page.notFound.description": "주소를 확인하거나 준비된 시작 화면으로 돌아가세요.", @@ -125,7 +147,6 @@ const PLATFORM_KO_MESSAGES = { "form.validation.configuration": "입력 구성을 다시 확인해 주세요.", "form.conflict": "다른 변경과 충돌했습니다. 입력은 유지되었으니 최신 상태를 확인해 주세요.", - "form.unavailable": "저장하지 못했습니다. 잠시 후 다시 시도해 주세요.", "form.reauthLosesInput": "다시 로그인하면 이 화면에 입력한 내용은 사라집니다. 필요하면 먼저 복사해 두세요.", "form.remaining": "{count}자 남음", @@ -146,6 +167,30 @@ const PLATFORM_KO_MESSAGES = { "error.asset_mismatch": "화면 자산 구성이 현재 릴리스와 일치하지 않습니다.", "error.render_failure": "화면을 표시하지 못했습니다.", "error.unknown_failure": "예상하지 못한 문제가 발생했습니다.", + "error.request_aborted": "요청이 취소되었습니다.", + "error.content_type_mismatch": "서버 응답 형식을 해석할 수 없습니다.", + "error.malformed_json": "서버 응답을 읽을 수 없습니다.", + "error.response_body_limit": "서버 응답이 허용된 크기를 넘었습니다.", + "error.envelope_mismatch": "서버 응답 구조가 예상과 다릅니다.", + "error.schema_mismatch": "서버 응답 데이터가 현재 화면과 맞지 않습니다.", + "error.mapping_contract_violation": + "서버 응답을 화면 데이터로 바꾸지 못했습니다.", + "error.result_limit_exceeded": "결과가 너무 많아 표시할 수 없습니다.", + "error.scope_generation_changed": "세션이 바뀌어 이전 요청을 중단했습니다.", + "error.identity_intern_limit_exceeded": + "처리할 항목이 너무 많습니다. 잠시 후 다시 시도해 주세요.", + "error.duplicate_in_flight": "같은 요청을 이미 처리하고 있습니다.", + "error.pagination_contract_violation": "페이지 정보를 확인할 수 없습니다.", + "error.conflict": "다른 변경과 충돌했습니다.", + "error.validation_rejected": "서버가 입력값을 받아들이지 않았습니다.", + "error.unknown_client_failure": "요청을 처리할 수 없습니다.", + "error.boot_config_failure": "실행 설정을 불러오지 못했습니다.", + "error.release_manifest_failure": "릴리스 정보를 불러오지 못했습니다.", + "error.deploy_mismatch": "배포 구성이 현재 화면과 일치하지 않습니다.", + "error.storage_unavailable": "브라우저 저장소를 사용할 수 없습니다.", + "error.storage_quota_exceeded": "브라우저 저장 공간이 부족합니다.", + "error.telemetry_failure": "진단 정보를 보내지 못했습니다.", + "error.query_cache_failure": "저장된 조회 결과를 사용할 수 없습니다.", ...BOOT_MESSAGES["ko-KR"], } as const; @@ -253,6 +298,28 @@ const PLATFORM_EN_MESSAGES = { "chunk.failure.title": "The page assets could not be recovered.", "chunk.failure.description": "If the problem continues, check deployment status and support information.", + "home.eyebrow": "Project starting point", + "home.description": + "A neutral skeleton for checking the runtime structure and common user experience before adding a domain.", + "home.readiness": "Implementation readiness", + "home.readiness.contract.title": "Runtime contract", + "home.readiness.contract.description": + "Runtime configuration, release consistency and error boundaries are checked before mounting.", + "home.readiness.adapters.title": "Replaceable integrations", + "home.readiness.adapters.description": + "Authentication, HTTP, cache, storage and telemetry sit behind ports.", + "home.readiness.accessibility.title": "Accessible screens", + "home.readiness.accessibility.description": + "Keyboard navigation, focus movement and the responsive app shell work out of the box.", + "home.runtime.checking": "Checking the verified runtime information.", + "home.runtime.failed": "The runtime information could not be checked.", + "home.runtime.summary": "Build {buildId} · Release {releaseId}", + "home.starter.title": "Explore the prepared screens", + "home.starter.description": + "See installed routes, contracts and runtime capabilities on the platform composition page, and common components and async screen states on the example routes.", + "home.starter.platform": "View platform composition", + "home.starter.ui": "View UI components", + "home.starter.states": "View screen states", "page.notFound.title": "Page not found.", "page.notFound.description": "Check the address or return to the start page.", "template.breadcrumb": "Current location", @@ -279,7 +346,6 @@ const PLATFORM_EN_MESSAGES = { "form.validation.configuration": "Review the input configuration.", "form.conflict": "Another update conflicts with this change. Your input has been preserved.", - "form.unavailable": "The change could not be saved. Try again shortly.", "form.reauthLosesInput": "Signing in again clears what you entered on this page. Copy it first if you need it.", "form.remaining": "{count} characters remaining", @@ -300,6 +366,32 @@ const PLATFORM_EN_MESSAGES = { "error.asset_mismatch": "The page assets do not match this release.", "error.render_failure": "The page could not be displayed.", "error.unknown_failure": "An unexpected problem occurred.", + "error.request_aborted": "The request was cancelled.", + "error.content_type_mismatch": "The server response format is not supported.", + "error.malformed_json": "The server response could not be read.", + "error.response_body_limit": "The server response exceeded the allowed size.", + "error.envelope_mismatch": "The server response structure is unexpected.", + "error.schema_mismatch": "The server response data does not match this page.", + "error.mapping_contract_violation": + "The server response could not be converted for this page.", + "error.result_limit_exceeded": "There are too many results to display.", + "error.scope_generation_changed": + "The session changed, so the earlier request was stopped.", + "error.identity_intern_limit_exceeded": + "There are too many items to process. Try again shortly.", + "error.duplicate_in_flight": "The same request is already in progress.", + "error.pagination_contract_violation": + "The page information could not be verified.", + "error.conflict": "The change conflicts with another update.", + "error.validation_rejected": "The server did not accept the entered values.", + "error.unknown_client_failure": "The request could not be processed.", + "error.boot_config_failure": "The runtime configuration could not be loaded.", + "error.release_manifest_failure": "The release information could not be loaded.", + "error.deploy_mismatch": "The deployment does not match this page.", + "error.storage_unavailable": "Browser storage is unavailable.", + "error.storage_quota_exceeded": "Browser storage is full.", + "error.telemetry_failure": "The diagnostic information could not be sent.", + "error.query_cache_failure": "The stored query results are unavailable.", ...BOOT_MESSAGES["en-US"], } as const satisfies Record; diff --git a/src/presentation/i18n/message-contract.ts b/src/presentation/i18n/message-contract.ts index ac193b51..fe0b9c18 100644 --- a/src/presentation/i18n/message-contract.ts +++ b/src/presentation/i18n/message-contract.ts @@ -21,6 +21,7 @@ export type MessageParameters = Readonly<{ "route.documentTitle": { title: string; appName: string }; "template.supportReference": { reference: string }; "form.remaining": { count: number }; + "home.runtime.summary": { buildId: string; releaseId: string }; "boot.supportReference": { reference: string }; }>; export type ParameterlessMessageKey = Exclude< diff --git a/src/presentation/pages/home-page.tsx b/src/presentation/pages/home-page.tsx index 3412ffa2..b773916e 100644 --- a/src/presentation/pages/home-page.tsx +++ b/src/presentation/pages/home-page.tsx @@ -3,25 +3,18 @@ import { Link } from "react-router-dom"; import { routePath } from "../../features/installed-feature-contracts.ts"; import { PageHeader } from "../design-system/index.ts"; +import { useLocale } from "../i18n/index.ts"; import { useApplicationRuntime } from "../providers/application-provider.tsx"; const READINESS_ITEMS = Object.freeze([ - { - title: "실행 계약", - description: "런타임 설정, 릴리스 정합성, 오류 경계가 마운트 전에 검증됩니다.", - }, - { - title: "교체 가능한 연동", - description: "인증, HTTP, 캐시, 저장소, 텔레메트리가 포트 뒤에 분리되어 있습니다.", - }, - { - title: "접근 가능한 화면", - description: "키보드 탐색, 포커스 이동, 반응형 앱 셸의 기본 동작이 준비되어 있습니다.", - }, -]); + "contract", + "adapters", + "accessibility", +] as const); export default function HomePage() { const runtime = useApplicationRuntime(); + const { message } = useLocale(); const [release, setRelease] = useState< Awaited> | "failed" | null >(null); @@ -44,48 +37,48 @@ export default function HomePage() { return (
    -
    +
    {READINESS_ITEMS.map((item) => ( -
    -

    {item.title}

    -

    {item.description}

    +
    +

    {message(`home.readiness.${item}.title`)}

    +

    {message(`home.readiness.${item}.description`)}

    ))}

    {release === "failed" - ? "런타임 정보를 확인하지 못했습니다." + ? message("home.runtime.failed") : release - ? `빌드 ${release.buildId} · 릴리스 ${release.releaseId}` - : "검증된 런타임 정보를 확인하고 있습니다."} + ? message("home.runtime.summary", { + buildId: release.buildId, + releaseId: release.releaseId, + }) + : message("home.runtime.checking")}

    -

    준비된 화면 살펴보기

    -

    - 설치된 라우트와 계약, 런타임 능력은 플랫폼 구성 화면에서, 공통 - 구성요소와 비동기 화면 상태는 예제 라우트에서 확인하세요. -

    +

    {message("home.starter.title")}

    +

    {message("home.starter.description")}

    - 플랫폼 구성 보기 + {message("home.starter.platform")} - UI 구성요소 보기 + {message("home.starter.ui")} - 화면 상태 보기 + {message("home.starter.states")}
    diff --git a/src/presentation/routes/app-router.tsx b/src/presentation/routes/app-router.tsx index f29122e6..9b3236f7 100644 --- a/src/presentation/routes/app-router.tsx +++ b/src/presentation/routes/app-router.tsx @@ -13,6 +13,7 @@ import { type RouteObject, useLocation, useNavigate, + useNavigationType, useParams, useSearchParams, } from "react-router-dom"; @@ -91,8 +92,11 @@ function RouteLoadingSurface({ function RouteFailureSurface({ definition, + supportReference, }: { definition?: RouteDefinition; + /** 08-07. The build and, when reported, the incident id. */ + supportReference: string; }) { const { message } = useLocale(); return ( @@ -101,6 +105,14 @@ function RouteFailureSurface({ title: message("route.failure.title"), description: message("route.failure.description"), }} + // RENDER_FAILURE's registry action: a render defect stays until the + // URL changes, so the page offers the reload itself. + primaryAction={{ + kind: "button", + label: message("action.reloadOnce"), + onAction: () => window.location.reload(), + }} + supportReference={supportReference} surface={definition?.errorSurface ?? "route-boundary"} variant="unexpected" /> @@ -154,6 +166,7 @@ function RouteLifecycle({ buildId: string; }) { const { pathname, search } = useLocation(); + const navigationType = useNavigationType(); const { message, resolve } = useLocale(); const diagnostics = useApplicationDiagnostics(); // A locale change re-renders the title only; it is not a route change. @@ -167,7 +180,12 @@ function RouteLifecycle({ const main = document.getElementById("main-content"); main?.focus({ preventScroll: true }); try { - if (!navigator.userAgent.toLowerCase().includes("jsdom")) { + // 08-08. Back and forward leave the scroll to the browser, which + // restores the position it saved for that entry. + if ( + navigationType !== "POP" && + !navigator.userAgent.toLowerCase().includes("jsdom") + ) { window.scrollTo({ top: 0, left: 0, behavior: "auto" }); } } catch { @@ -177,7 +195,7 @@ function RouteLifecycle({ routeId: definition.routeId, buildId, }); - }, [buildId, definition, diagnostics, pathname, search]); + }, [buildId, definition, diagnostics, navigationType, pathname, search]); return null; } @@ -328,6 +346,8 @@ function RouteSurface({ if (!runtime) return ; const parsed = parseRouteInput(routeId, params, search); if (!parsed.success) return ; + const boundaryName = + definition.errorSurface === "feature-boundary" ? "feature" : "route"; const content = ( @@ -339,6 +359,15 @@ function RouteSurface({ key={definition.routeId} chunkId={definition.chunkId} recover={recovery.recoverChunk} + buildId={buildId} + onUnrecovered={(incidentId) => + diagnostics.reportRenderFailure({ + routeId, + buildId, + boundaryName, + incidentId, + }) + } > @@ -356,10 +385,15 @@ function RouteSurface({ buildId, resetKey: `${location.pathname}${location.search}`, onRenderFailure: diagnostics.reportRenderFailure, - fallback: , + fallback: (incidentId: string) => ( + + ), children: protectedContent, }; - return definition.errorSurface === "feature-boundary" ? ( + return boundaryName === "feature" ? ( ) : ( @@ -404,6 +438,7 @@ function ContextRouteGateway({ }: Readonly<{ routeModule: ContextRouteModule; buildId: string }>) { const location = useLocation(); const recovery = useApplicationRecovery(); + const diagnostics = useApplicationDiagnostics(); const [routes, setRoutes] = useState(null); const [failure, setFailure] = useState | null>( null, @@ -431,7 +466,7 @@ function ContextRouteGateway({ } + fallback={} > {content} @@ -444,11 +479,20 @@ function ContextRouteGateway({ + diagnostics.reportRenderFailure({ + routeId: routeModule.id, + buildId, + boundaryName: "route", + incidentId, + }) + } > ) : ( - + ); } if (routes === null) return ; @@ -475,7 +519,7 @@ function ContextRouteGateway({ } + fallback={} > {route} @@ -522,7 +566,7 @@ function createRegisteredRoutes(buildId: string): RouteObject[] { id: "APP_SHELL", path: "/", element: , - errorElement: , + errorElement: , children: [...platformChildren, ...contextChildren], }, ]; diff --git a/src/presentation/styles/theme/shell.css b/src/presentation/styles/theme/shell.css index 2d2afee3..c3398a66 100644 --- a/src/presentation/styles/theme/shell.css +++ b/src/presentation/styles/theme/shell.css @@ -27,6 +27,11 @@ transform: translateY(0); } + /* 08-08. Hash targets land below the sticky 4.5rem header. */ + html { + scroll-padding-top: 4.5rem; + } + .app-shell { display: grid; min-height: 100vh; diff --git a/tests/component/async-surface.test.tsx b/tests/component/async-surface.test.tsx index 7cb44269..558cb74c 100644 --- a/tests/component/async-surface.test.tsx +++ b/tests/component/async-surface.test.tsx @@ -7,6 +7,7 @@ import { describe, expect, it, vi } from "vitest"; import { deriveAsyncState } from "../../src/application/view-models/async-state.ts"; import { AsyncSurface } from "../../src/presentation/components/async-surface.tsx"; import { createFailure } from "../../src/contracts/errors.ts"; +import { AccessSurface } from "../../src/presentation/design-system/index.ts"; describe("async UI state matrix", () => { it.each([ @@ -138,6 +139,17 @@ describe("async UI state matrix", () => { expect(resolveConflict).toHaveBeenCalledOnce(); }); + // 08-07. The id a user quotes when asking for help is the one the request + // diagnostics carry as `correlation_id`. + it("shows the failure's request id as its support reference", () => { + const failure = { + ...createFailure("SERVER_FAILURE", "LIST", 1), + requestId: "req-7f3a", + }; + render(); + expect(screen.getByRole("alert")).toHaveTextContent("지원 참조: req-7f3a"); + }); + it("renders only safe error vocabulary", () => { const failure = createFailure("SERVER_FAILURE", "LIST", 0, { code: "SERVER_FAILURE", @@ -222,6 +234,41 @@ describe("async UI state matrix", () => { expect(screen.getByText("표시할 항목이 없습니다.")).toBeVisible(); }); + // 08-11. A query failure and the gallery draw one access set, not two. + it.each([ + ["AUTH_REQUIRED", "auth-required"], + ["FORBIDDEN", "forbidden"], + ["NOT_FOUND", "not-found"], + ] as const)( + "renders a %s query failure with the gallery's access surface", + async (kind, accessKind) => { + const user = userEvent.setup(); + const action = vi.fn(); + const failure = createFailure(kind, "LIST", 0); + const gallery = render( + {}} />, + ); + const expected = gallery.container.querySelector(".state-surface"); + expect(expected).not.toBeNull(); + const expectedText = expected?.textContent; + gallery.unmount(); + + render( + , + ); + const alert = screen.getByRole("alert"); + expect(alert).toHaveAttribute("data-message-key", failure.userMessageKey); + expect(alert.querySelector(".state-surface")?.textContent).toBe( + expectedText, + ); + await user.click(screen.getByRole("button")); + expect(action).toHaveBeenCalledOnce(); + }, + ); + it("does not retain a terminal error after usable data is restored", () => { const failed = deriveAsyncState({ failure: createFailure("SERVER_FAILURE", "LIST", 0), diff --git a/tests/component/chunk-recovery-boundary.test.tsx b/tests/component/chunk-recovery-boundary.test.tsx index 8efd76f5..98efa952 100644 --- a/tests/component/chunk-recovery-boundary.test.tsx +++ b/tests/component/chunk-recovery-boundary.test.tsx @@ -141,6 +141,34 @@ describe("chunk recovery boundary classification", () => { ).toBeVisible(); }); + // 08-07. An unrecovered chunk failure shows a reference the render + // diagnostic also records. + it("shows an unrecovered chunk failure's support reference and records it", async () => { + const record = vi.fn(); + window.history.pushState({}, "", "/examples/states"); + render( + + + + + , + ); + + const reference = await screen.findByText(/^지원 참조: build-a:[0-9a-f]{8}$/); + const incidentId = reference.textContent?.split(":").at(-1); + expect(record).toHaveBeenCalledWith({ + level: "error", + eventId: "ui.render.failed", + context: expect.objectContaining({ + route_id: "EXAMPLES_STATES", + build_id: "build-a", + correlation_id: incidentId, + }), + }); + }); + it("clears a failed route chunk when the user moves to a sibling route", async () => { // React Router reuses the rendered-route instance between sibling routes, // so a failure latched in one route's boundary would otherwise follow the diff --git a/tests/component/form-foundation.test.tsx b/tests/component/form-foundation.test.tsx index a91113f8..91000a81 100644 --- a/tests/component/form-foundation.test.tsx +++ b/tests/component/form-foundation.test.tsx @@ -202,6 +202,40 @@ describe("local form facade", () => { }, ); + // F-10 (08-01). A save that failed for a reason the user cannot fix in the + // input is a status with its own action, never an input error summary. + it.each([ + ["NOT_FOUND", "요청한 항목을 찾을 수 없습니다.", "안전한 화면으로 이동"], + ["UNKNOWN_CLIENT_FAILURE", "요청을 처리할 수 없습니다.", "지원 정보 확인"], + ] as const)( + "shows an unavailable %s save as a status, not an input error", + async (kind, copy, action) => { + const user = userEvent.setup(); + const onFailureAction = vi.fn(); + render( + ({ + ok: false, + error: createFailure(kind, "CREATE_ENTITY", 0, { + effect: "NOT_APPLIED", + }), + })} + onFailureAction={onFailureAction} + />, + ); + await user.type(screen.getByRole("textbox", { name: /Name/ }), "Valid"); + await user.click(screen.getByRole("button", { name: "Submit" })); + + expect(await screen.findByTestId("result")).toHaveTextContent( + "unavailable", + ); + expect(screen.getByRole("alert")).toHaveTextContent(copy); + expect(document.body).not.toHaveTextContent("입력 내용을 확인해 주세요."); + await user.click(screen.getByRole("button", { name: action })); + expect(onFailureAction).toHaveBeenCalledOnce(); + }, + ); + it("keeps conflict input out of URL and storage", async () => { const user = userEvent.setup(); localStorage.clear(); diff --git a/tests/component/locale-platform.test.tsx b/tests/component/locale-platform.test.tsx index f2733277..ea80c3c3 100644 --- a/tests/component/locale-platform.test.tsx +++ b/tests/component/locale-platform.test.tsx @@ -4,6 +4,7 @@ import { render, screen } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { useState } from "react"; import { describe, expect, it } from "vitest"; +import { z } from "zod"; import { Button, @@ -16,6 +17,12 @@ import { useLocale, type SupportedLocale, } from "../../src/presentation/i18n/index.ts"; +import { + ErrorSummary, + Form, + FormField, + useAppForm, +} from "../../src/presentation/forms/index.ts"; import { ApplicationProvider } from "../../src/presentation/providers/application-provider.tsx"; import { PreferenceProviders } from "../../src/presentation/providers/preference-providers.tsx"; import { AppRouter } from "../../src/presentation/routes/app-router.tsx"; @@ -54,7 +61,71 @@ function LocaleHarness() { ); } +function LocaleSelect() { + const { locale, message, setLocale } = useLocale(); + return ( + <> + + + + ); +} + +function ValidatedForm() { + const form = useAppForm({ + schema: z.object({ name: z.string().min(2) }).strict(), + defaultValues: { name: "" }, + allowedServerFields: ["name"], + mapToCommand: (values) => values, + submit: async () => ({ ok: true as const, value: null }), + }); + return ( +
    void form.submitForm(event)}> + + + + + ); +} + describe("locale provider runtime", () => { + // 08-10. A shown error is kept as a message key, not a translated string. + it("re-translates displayed form errors when the locale changes", async () => { + const user = userEvent.setup(); + render( + + + + , + ); + await user.click(screen.getByRole("button", { name: "Submit" })); + expect(screen.getByRole("alert")).toHaveTextContent( + "입력 내용을 확인해 주세요.Name: 입력값이 너무 짧습니다.", + ); + + await user.selectOptions(screen.getByLabelText("언어"), "en-US"); + expect(screen.getByRole("alert")).toHaveTextContent( + "Review the entered information.Name: This value is too short.", + ); + expect(screen.getByRole("textbox", { name: "Name" })).toHaveAccessibleDescription( + "This value is too short.", + ); + }); + it("switches copy and synchronizes the document language and direction", async () => { const user = userEvent.setup(); render( diff --git a/tests/component/pagination.test.tsx b/tests/component/pagination.test.tsx index a6bdc5b0..e4ee9730 100644 --- a/tests/component/pagination.test.tsx +++ b/tests/component/pagination.test.tsx @@ -1,7 +1,7 @@ // @vitest-environment jsdom -import { render, screen, within } from "@testing-library/react"; -import { describe, expect, it } from "vitest"; +import { fireEvent, render, screen, within } from "@testing-library/react"; +import { describe, expect, it, vi } from "vitest"; import { Pagination } from "../../src/presentation/design-system/index.ts"; import { CollectionPage } from "../../src/presentation/templates/index.ts"; @@ -78,3 +78,41 @@ describe("Pagination landmarks", () => { expect(within(slot).getByRole("group", { name: "Pages" })).toBeVisible(); }); }); + +// 08-12. A modified click is the browser's (new tab/window), not a page change. +describe("Pagination modified clicks", () => { + function renderWith(onChange: (page: number) => void) { + render( + `Page ${candidate}`} + previousLabel="Previous" + />, + ); + return screen.getByRole("link", { name: "Page 2" }); + } + + it.each([ + ["Ctrl", { ctrlKey: true }], + ["Cmd", { metaKey: true }], + ["Shift", { shiftKey: true }], + ["Alt", { altKey: true }], + ])("leaves a %s click to the browser", (_, modifier) => { + const onChange = vi.fn(); + const link = renderWith(onChange); + const notPrevented = fireEvent.click(link, { button: 0, ...modifier }); + expect(notPrevented).toBe(true); + expect(onChange).not.toHaveBeenCalled(); + }); + + it("changes the page on a plain primary click", () => { + const onChange = vi.fn(); + const link = renderWith(onChange); + expect(fireEvent.click(link, { button: 0 })).toBe(false); + expect(onChange).toHaveBeenCalledWith(2); + }); +}); diff --git a/tests/component/render-boundary.test.tsx b/tests/component/render-boundary.test.tsx index 812d520f..4de85108 100644 --- a/tests/component/render-boundary.test.tsx +++ b/tests/component/render-boundary.test.tsx @@ -11,6 +11,17 @@ import { AsyncSurface } from "../../src/presentation/components/async-surface.ts import { BootErrorShell } from "../../src/presentation/boundaries/boot-error-shell.tsx"; import { FeatureBoundary } from "../../src/presentation/boundaries/render-error-boundary.tsx"; import { LocaleProvider } from "../../src/presentation/i18n/index.ts"; +import { ApplicationProvider } from "../../src/presentation/providers/application-provider.tsx"; +import { PreferenceProviders } from "../../src/presentation/providers/preference-providers.tsx"; +import { AppRouter } from "../../src/presentation/routes/app-router.tsx"; +import { createTestApplication } from "../helpers/create-test-application.ts"; + +// The states page stands in for any route page with a programmer defect. +vi.mock("../../src/presentation/examples/state-gallery-page.tsx", () => ({ + default: function BrokenPage(): never { + throw new Error("ordinary render defect"); + }, +})); function Defect(): ReactNode { throw new Error("raw render stack"); @@ -36,9 +47,39 @@ describe("render recovery boundaries", () => { routeId: "APP_HOME", buildId: "build-a", boundaryName: "feature", + incidentId: expect.stringMatching(/^[0-9a-f]{8}$/), }); }); + // 08-07. The route failure page shows the reference the user quotes, the + // same id the render diagnostic records, and a way out besides the URL. + it("shows a route render failure's support reference and records it", async () => { + const record = vi.fn(); + window.history.pushState({}, "", "/examples/states"); + render( + + + + + , + ); + + const reference = await screen.findByText(/^지원 참조: build-a:[0-9a-f]{8}$/); + const incidentId = reference.textContent?.split(":").at(-1); + expect(record).toHaveBeenCalledWith({ + level: "error", + eventId: "ui.render.failed", + context: expect.objectContaining({ + route_id: "EXAMPLES_STATES", + build_id: "build-a", + correlation_id: incidentId, + }), + }); + expect(screen.getByRole("button", { name: "한 번 새로고침" })).toBeVisible(); + }); + it("keeps normalized operational failures in normal async state", () => { const state = deriveAsyncState({ failure: createFailure("SERVER_FAILURE", "LIST", 0), diff --git a/tests/e2e/accessibility.spec.ts b/tests/e2e/accessibility.spec.ts index a30a541d..f2aca7e9 100644 --- a/tests/e2e/accessibility.spec.ts +++ b/tests/e2e/accessibility.spec.ts @@ -1,23 +1,52 @@ import AxeBuilder from "@axe-core/playwright"; -import { expect, test } from "../support/browser/strict-browser-test.ts"; +import { expect, test, type Page } from "../support/browser/strict-browser-test.ts"; import { ROUTE_REGISTRY } from "../../src/features/installed-feature-contracts.ts"; +import type { RouteDefinition } from "../../src/contracts/routes.ts"; +import { KO_MESSAGES } from "../../src/presentation/i18n/catalog.ts"; -for (const route of Object.values(ROUTE_REGISTRY).map((definition) => { - if (definition.path === "*") return "/not-found"; - return definition.path.replace(":resourceId", "reference-1"); -})) { +const WCAG_TAGS = ["wcag2a", "wcag2aa", "wcag21a", "wcag21aa"]; +const SIGN_IN_TITLE = KO_MESSAGES["route.auth.required.title"]; +const CATALOG = KO_MESSAGES as Readonly>; + +async function blockingViolations(page: Page) { + const results = await new AxeBuilder({ page }).withTags(WCAG_TAGS).analyze(); + return results.violations.filter((violation) => + ["critical", "serious"].includes(violation.impact ?? ""), + ); +} + +// 08-05/11-02. The app shell draws `main` before the route chunk arrives, so +// axe waits for the route's own h1. A public route's h1 is its catalog title. +// A protected route is scanned after the demo sign-in, never on the sign-in +// prompt; the feature's own spec pins its exact headings and states. +// Widened: without an installed feature every route is public, and the +// `session-required` branch must still typecheck (sample removal). +const ROUTES: readonly RouteDefinition[] = Object.values(ROUTE_REGISTRY); +for (const definition of ROUTES) { + const route = + definition.path === "*" + ? "/not-found" + : definition.path.replace(":resourceId", "reference-1"); test(`@a11y ${route} has no critical or serious axe violations`, async ({ page, }) => { - await page.goto(route); - await expect(page.getByRole("main")).toBeVisible(); - const results = await new AxeBuilder({ page }) - .withTags(["wcag2a", "wcag2aa", "wcag21a", "wcag21aa"]) - .analyze(); - const blocking = results.violations.filter((violation) => - ["critical", "serious"].includes(violation.impact ?? ""), - ); - expect(blocking).toEqual([]); + const heading = page.getByRole("heading", { level: 1 }); + if (definition.access === "session-required") { + // Feature data is not this spec's subject: any API answers an empty list. + await page.route("http://localhost:8080/api/**", (request) => + request.fulfill({ json: [] }), + ); + await page.goto(route); + await expect(heading).toHaveText(SIGN_IN_TITLE); + await page.getByRole("button", { name: "로그인 시작" }).click(); + await expect(heading).toBeVisible(); + await expect(heading).not.toHaveText(SIGN_IN_TITLE); + } else { + await page.goto(route); + const title = CATALOG[`route.${definition.routeId}.title`]; + await expect(heading).toHaveText(title ?? definition.title); + } + expect(await blockingViolations(page)).toEqual([]); }); } @@ -48,7 +77,7 @@ test("@a11y opened design-system dialog has no blocking violations", async ({ await page.getByRole("button", { name: "모달 열기" }).click(); const results = await new AxeBuilder({ page }) .include(".ui-dialog") - .withTags(["wcag2a", "wcag2aa", "wcag21a", "wcag21aa"]) + .withTags(WCAG_TAGS) .analyze(); expect( results.violations.filter((violation) => diff --git a/tests/e2e/reference-form.spec.ts b/tests/e2e/reference-form.spec.ts index 7c4e84b5..e895a83d 100644 --- a/tests/e2e/reference-form.spec.ts +++ b/tests/e2e/reference-form.spec.ts @@ -1,3 +1,4 @@ +import AxeBuilder from "@axe-core/playwright"; import type { Page } from "@playwright/test"; import { expect, test } from "../support/browser/strict-browser-test.ts"; @@ -48,3 +49,102 @@ test("keeps the form template within a 320px viewport", async ({ page }) => { })); expect(viewport.scrollWidth).toBeLessThanOrEqual(viewport.clientWidth); }); + +// 08-04. Feature screens take their words from the catalog. This lives with +// the sample's specs so removing the sample removes it too. +test("renders the reference screens without Korean copy in en-US", async ({ + page, +}) => { + await page.route("http://localhost:8080/api/reference-resources?*", (route) => + route.fulfill({ + json: [ + { + id: "browser-reference", + name: "Browser reference", + createdAt: "2026-07-26T00:00:00.000Z", + }, + ], + }), + ); + await page.goto("/examples/reference-resources"); + await page.getByRole("button", { name: "로그인 시작" }).click(); + await expect(page.getByRole("link", { name: "Browser reference" })).toBeVisible(); + await page.getByRole("combobox", { name: "언어" }).selectOption("en-US"); + + const main = page.getByRole("main"); + await expect(main.getByRole("status")).toHaveText("Total items: 1"); + await expect(main).not.toContainText(/[가-힣]/); + + await main.getByRole("button", { name: "Create item" }).click(); + await expect(main.getByRole("button", { name: "Save" })).toBeVisible(); + await expect(main).not.toContainText(/[가-힣]/); +}); + +const LIST_PATH = "/examples/reference-resources"; +const LIST_API = "http://localhost:8080/api/reference-resources?*"; +const BROWSER_REFERENCE = { + id: "browser-reference", + name: "Browser reference", + createdAt: "2026-07-26T00:00:00.000Z", +}; + +async function signInAt(page: Page, path: string, heading: string) { + await page.goto(path); + await page.getByRole("button", { name: "로그인 시작" }).click(); + await expect(page.getByRole("heading", { level: 1 })).toHaveText(heading); +} + +async function expectNoBlockingViolations(page: Page) { + const results = await new AxeBuilder({ page }) + .withTags(["wcag2a", "wcag2aa", "wcag21a", "wcag21aa"]) + .analyze(); + expect( + results.violations.filter((violation) => + ["critical", "serious"].includes(violation.impact ?? ""), + ), + ).toEqual([]); +} + +// 08-05. The protected reference screens are scanned signed in and in each +// state they can show. The state must be on screen before axe runs. +for (const [state, payload, visible] of [ + ["success", [BROWSER_REFERENCE], "Browser reference"], + ["empty", [], "표시할 항목이 없습니다."], + // A 200 that breaks the response schema: a 5xx would also log a console + // error, which the strict fixture rejects on its own. + ["error", [{ wrong: true }], "서버 응답 데이터가 현재 화면과 맞지 않습니다."], +] as const) { + test(`@a11y reference list ${state} state has no blocking violations`, async ({ + page, + }) => { + await page.route(LIST_API, (route) => route.fulfill({ json: payload })); + await signInAt(page, LIST_PATH, "Reference feature"); + await expect(page.getByRole("main")).toContainText(visible); + await expectNoBlockingViolations(page); + }); +} + +test("@a11y reference detail has no blocking violations", async ({ page }) => { + await page.route( + "http://localhost:8080/api/reference-resources/browser-reference", + (route) => route.fulfill({ json: BROWSER_REFERENCE }), + ); + await signInAt(page, `${LIST_PATH}/browser-reference`, "Browser reference"); + await expectNoBlockingViolations(page); +}); + +test("@a11y reference form with submit errors has no blocking violations", async ({ + page, +}) => { + await signInAt(page, `${LIST_PATH}/new`, "Reference resource 만들기"); + await page.getByRole("button", { name: "저장" }).click(); + await expect(page.getByRole("alert")).toContainText("입력 내용을 확인해 주세요."); + await expectNoBlockingViolations(page); +}); + +test("@a11y reference status page has no blocking violations", async ({ + page, +}) => { + await signInAt(page, `${LIST_PATH}/status`, "잠시 사용할 수 없습니다."); + await expectNoBlockingViolations(page); +}); diff --git a/tests/e2e/scroll-restoration.spec.ts b/tests/e2e/scroll-restoration.spec.ts new file mode 100644 index 00000000..f4f99d81 --- /dev/null +++ b/tests/e2e/scroll-restoration.spec.ts @@ -0,0 +1,39 @@ +import { expect, test, type Page } from "../support/browser/strict-browser-test.ts"; + +const scrollY = (page: Page) => page.evaluate(() => Math.round(window.scrollY)); + +// 08-08. Back restores where the user was; a new route starts at the top. +test("restores the scroll position when navigating back", async ({ page }) => { + const heading = page.getByRole("heading", { level: 1 }); + await page.goto("/examples/ui"); + await expect(heading).toHaveText("UI 구성요소"); + await page.evaluate(() => window.scrollTo(0, 900)); + await expect.poll(() => scrollY(page)).toBe(900); + + await page + .getByRole("navigation", { name: "주요 탐색" }) + .getByRole("link", { name: "화면 상태" }) + .click(); + await expect(heading).toHaveText("화면 상태"); + await expect.poll(() => scrollY(page)).toBe(0); + + await page.goBack(); + await expect(heading).toHaveText("UI 구성요소"); + await expect.poll(() => scrollY(page)).toBe(900); +}); + +test("opens a hash link at its target below the sticky header", async ({ + page, +}) => { + await page.goto("/examples/ui#tokens-title"); + const target = page.locator("#tokens-title"); + await expect(target).toBeInViewport(); + const top = await target.evaluate((element) => + Math.round(element.getBoundingClientRect().top), + ); + const headerBottom = await page + .locator(".app-shell__header") + .evaluate((element) => Math.round(element.getBoundingClientRect().bottom)); + expect(top).toBeGreaterThanOrEqual(headerBottom); + expect(await scrollY(page)).toBeGreaterThan(0); +}); diff --git a/tests/features/reference-feature/installed-context-routing.test.ts b/tests/features/reference-feature/installed-context-routing.test.ts index 64b98ec1..ac16c22f 100644 --- a/tests/features/reference-feature/installed-context-routing.test.ts +++ b/tests/features/reference-feature/installed-context-routing.test.ts @@ -16,7 +16,7 @@ describe("installed context routing", () => { const routes = await context!.loadRoutes(); expect(routes.map((route) => [route.id, route.path])).toEqual([ ["REFERENCE_RESOURCE_LIST", "/examples/reference-resources"], - ["REFERENCE_RESOURCE_DETAIL", "/examples/reference-resources/:resourceId"], + ["REFERENCE_RESOURCE_DETAIL", "/examples/reference-resources/items/:resourceId"], ["REFERENCE_RESOURCE_FORM", "/examples/reference-resources/new"], ["REFERENCE_RESOURCE_STATUS", "/examples/reference-resources/status"], ]); diff --git a/tests/features/reference-feature/reference-page.test.tsx b/tests/features/reference-feature/reference-page.test.tsx index 43fe742c..a9e69d67 100644 --- a/tests/features/reference-feature/reference-page.test.tsx +++ b/tests/features/reference-feature/reference-page.test.tsx @@ -147,7 +147,7 @@ describe("reference feature page states", () => { const detail = renderReference( inputWith(), - "/examples/reference-resources/reference-1", + "/examples/reference-resources/items/reference-1", ); await screen.findByText("Detail"); const detailKey = detail.client.getQueryCache().getAll()[0]?.queryKey; @@ -208,6 +208,75 @@ describe("reference feature page states", () => { expect(listResources).not.toHaveBeenCalled(); }); + // 08-09. The count is a status only once there is a result to count. + it("shows the result count only for a loaded list", async () => { + const resultCount = () => + document.querySelector(".collection-page__result-count"); + let resolveList: + | ((result: ReferenceResult) => void) + | undefined; + const loading = renderReference( + inputWith({ + listResources: () => + new Promise((resolve) => { + resolveList = resolve; + }), + }), + ); + expect(await screen.findByLabelText("불러오는 중")).toBeVisible(); + expect(resultCount()).toBeNull(); + resolveList?.({ + ok: true, + value: [{ resourceId: "reference-1", title: "Loaded", createdAt: null }], + }); + expect(await screen.findByText("Loaded")).toBeVisible(); + expect(resultCount()).toHaveTextContent("총 1개 항목"); + loading.unmount(); + + renderReference( + inputWith({ + listResources: async () => ({ + ok: false, + error: createFailure("SERVER_FAILURE", "LIST_REFERENCE_RESOURCES", 0), + }), + }), + ); + expect(await screen.findByRole("alert")).toHaveTextContent( + "요청을 완료하지 못했습니다.", + ); + expect(resultCount()).toBeNull(); + }); + + // 08-13. A server id equal to a static segment still opens its detail. + it.each(["new", "status"])( + "opens the detail screen for an item whose id is %s", + async (resourceId) => { + const user = userEvent.setup(); + const getResource = vi.fn(async (id: string) => ({ + ok: true as const, + value: { resourceId: id, title: "Detail", createdAt: null }, + })); + renderReference( + inputWith({ + listResources: async () => ({ + ok: true, + value: [ + { resourceId, title: `Item ${resourceId}`, createdAt: null }, + ], + }), + getResource, + }), + ); + await user.click( + await screen.findByRole("link", { name: `Item ${resourceId}` }), + ); + expect( + await screen.findByRole("heading", { level: 1, name: "Detail" }), + ).toBeVisible(); + expect(getResource.mock.calls[0]?.[0]).toBe(resourceId); + }, + ); + it("renders backend forbidden even when the client access hint allowed entry", async () => { const user = userEvent.setup(); renderReference( @@ -223,7 +292,7 @@ describe("reference feature page states", () => { }), ); expect(await screen.findByRole("alert")).toHaveTextContent( - "이 작업을 수행할 권한이 없습니다.", + "접근할 수 없습니다.", ); await user.click( screen.getByRole("button", { name: "안전한 화면으로 이동" }), @@ -256,7 +325,7 @@ describe("reference feature page states", () => { session, ); - await user.click(await screen.findByRole("button", { name: "로그인" })); + await user.click(await screen.findByRole("button", { name: "로그인 시작" })); expect(beginSignIn).toHaveBeenCalledWith( "/examples/reference-resources?limit=5", ); @@ -283,7 +352,7 @@ describe("reference feature page states", () => { { ...demoSession, beginSignIn }, ); - await user.click(await screen.findByRole("button", { name: "로그인" })); + await user.click(await screen.findByRole("button", { name: "로그인 시작" })); expect( await screen.findByRole("heading", { level: 1, diff --git a/tests/fixtures/i18n/forbidden/src/features/sample-feature/presentation/sample-feature-page.tsx b/tests/fixtures/i18n/forbidden/src/features/sample-feature/presentation/sample-feature-page.tsx new file mode 100644 index 00000000..51f1c9dd --- /dev/null +++ b/tests/fixtures/i18n/forbidden/src/features/sample-feature/presentation/sample-feature-page.tsx @@ -0,0 +1,3 @@ +export default function SampleFeaturePage() { + return ; +} diff --git a/tests/fixtures/i18n/forbidden/backend-message.tsx b/tests/fixtures/i18n/forbidden/src/presentation/components/backend-message.tsx similarity index 100% rename from tests/fixtures/i18n/forbidden/backend-message.tsx rename to tests/fixtures/i18n/forbidden/src/presentation/components/backend-message.tsx diff --git a/tests/fixtures/i18n/forbidden/hardcoded-common.tsx b/tests/fixtures/i18n/forbidden/src/presentation/components/hardcoded-common.tsx similarity index 100% rename from tests/fixtures/i18n/forbidden/hardcoded-common.tsx rename to tests/fixtures/i18n/forbidden/src/presentation/components/hardcoded-common.tsx diff --git a/tests/fixtures/i18n/forbidden/unsafe-html.tsx b/tests/fixtures/i18n/forbidden/src/presentation/components/unsafe-html.tsx similarity index 100% rename from tests/fixtures/i18n/forbidden/unsafe-html.tsx rename to tests/fixtures/i18n/forbidden/src/presentation/components/unsafe-html.tsx diff --git a/tests/fixtures/i18n/forbidden/src/presentation/pages/sample-page.tsx b/tests/fixtures/i18n/forbidden/src/presentation/pages/sample-page.tsx new file mode 100644 index 00000000..270e598d --- /dev/null +++ b/tests/fixtures/i18n/forbidden/src/presentation/pages/sample-page.tsx @@ -0,0 +1,3 @@ +export default function SamplePage() { + return

    프로젝트 시작점

    ; +} diff --git a/tests/unit/i18n-contract.test.ts b/tests/unit/i18n-contract.test.ts index 42513ebd..ebcaf9b0 100644 --- a/tests/unit/i18n-contract.test.ts +++ b/tests/unit/i18n-contract.test.ts @@ -1,5 +1,7 @@ import { describe, expect, it } from "vitest"; +import { ERROR_REGISTRY } from "../../src/contracts/errors.ts"; + import { catalogKeys, FORMAT_FALLBACK, @@ -34,6 +36,17 @@ describe("internationalization message contract", () => { expect(MESSAGE_CATALOGS["ar-EG"]).toBe(EN_MESSAGES); }); + // 07-01/08-02. A kind without copy renders "This message is unavailable." + // as the failure title, so every registry row must resolve in both locales. + it("gives every error registry kind its own message in every locale", () => { + const missing = Object.values(ERROR_REGISTRY).flatMap((definition) => + [KO_MESSAGES, EN_MESSAGES] + .filter((catalog) => !Object.hasOwn(catalog, definition.userMessageKey)) + .map(() => definition.userMessageKey), + ); + expect(missing).toEqual([]); + }); + it("formats typed parameters and expands the pseudo locale", () => { expect( formatMessage("en-US", "route.documentTitle", { diff --git a/tests/visual/__snapshots__/platform.visual.spec.ts-snapshots/app-shell-compact-pseudo-drawer-chromium-visual-linux.png b/tests/visual/__snapshots__/platform.visual.spec.ts-snapshots/app-shell-compact-pseudo-drawer-chromium-visual-linux.png index c5065a93..9d5a75a5 100644 Binary files a/tests/visual/__snapshots__/platform.visual.spec.ts-snapshots/app-shell-compact-pseudo-drawer-chromium-visual-linux.png and b/tests/visual/__snapshots__/platform.visual.spec.ts-snapshots/app-shell-compact-pseudo-drawer-chromium-visual-linux.png differ diff --git a/tests/visual/__snapshots__/platform.visual.spec.ts-snapshots/state-surfaces-light-chromium-visual-linux.png b/tests/visual/__snapshots__/platform.visual.spec.ts-snapshots/state-surfaces-light-chromium-visual-linux.png index 45c28c65..69721583 100644 Binary files a/tests/visual/__snapshots__/platform.visual.spec.ts-snapshots/state-surfaces-light-chromium-visual-linux.png and b/tests/visual/__snapshots__/platform.visual.spec.ts-snapshots/state-surfaces-light-chromium-visual-linux.png differ diff --git a/tests/visual/platform.visual.spec.ts b/tests/visual/platform.visual.spec.ts index f488dbb3..2ef4aad5 100644 --- a/tests/visual/platform.visual.spec.ts +++ b/tests/visual/platform.visual.spec.ts @@ -1,12 +1,19 @@ import { expect, test, + type Page, } from "../support/browser/strict-browser-test.ts"; +// 11-02. `main` is drawn before the route chunk arrives; a screenshot taken +// then pins the loading surface instead of the page. +async function expectRouteHeading(page: Page, title: string) { + await expect(page.getByRole("heading", { level: 1 })).toHaveText(title); +} + test("wide application shell visual contract", async ({ page }) => { await page.setViewportSize({ width: 1440, height: 900 }); await page.goto("/"); - await expect(page.getByRole("main")).toBeVisible(); + await expectRouteHeading(page, "Clean Architecture Frontend"); await expect(page).toHaveScreenshot("app-shell-wide-light.png", { fullPage: true, }); @@ -15,6 +22,7 @@ test("wide application shell visual contract", async ({ page }) => { test("compact drawer and pseudo-locale visual contract", async ({ page }) => { await page.setViewportSize({ width: 390, height: 844 }); await page.goto("/"); + await expectRouteHeading(page, "Clean Architecture Frontend"); await page.locator("#locale-preference").selectOption("en-XA"); await page.locator(".app-shell__menu-button").click(); await expect(page.locator(".ui-drawer")).toHaveJSProperty("open", true); @@ -26,6 +34,7 @@ test("compact drawer and pseudo-locale visual contract", async ({ page }) => { test("design-system gallery dark visual contract", async ({ page }) => { await page.setViewportSize({ width: 1280, height: 900 }); await page.goto("/examples/ui"); + await expectRouteHeading(page, "UI 구성요소"); await page.locator("#theme-preference").selectOption("dark"); await expect(page.getByRole("main")).toHaveScreenshot( "design-system-gallery-dark.png", @@ -37,6 +46,7 @@ test("loading empty error and access surfaces visual contract", async ({ }) => { await page.setViewportSize({ width: 1280, height: 1100 }); await page.goto("/examples/states"); + await expectRouteHeading(page, "화면 상태"); await expect(page.getByRole("main")).toHaveScreenshot( "state-surfaces-light.png", ); @@ -45,6 +55,7 @@ test("loading empty error and access surfaces visual contract", async ({ test("platform composition overview visual contract", async ({ page }) => { await page.setViewportSize({ width: 1280, height: 1100 }); await page.goto("/examples/platform"); + await expectRouteHeading(page, "플랫폼 구성"); await expect( page.locator("section[aria-labelledby='platform-capabilities-title']"), ).toBeVisible();