Merge lane/H: presentation (07-01, 08-02, 08-04, 08-05, 08-07~08-13, 11-02, F-10)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

# Conflicts:
#	config/contracts/registry-change-evidence.json
This commit is contained in:
donghyeon-ka
2026-09-27 13:19:31 +09:00
50 changed files with 1140 additions and 160 deletions
+5
View File
@@ -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 {
@@ -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<{
@@ -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",
@@ -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);
@@ -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() {
</dd>
</dl>
) : (
<p>요약 정보를 준비하고 있습니다.</p>
<p>{message("reference.detail.summaryPending")}</p>
)
}
feedback={
@@ -51,11 +51,11 @@ export default function ReferenceResourceDetailPage() {
onRetry={query.retry}
>
{resource ? (
<p>이 영역에는 제품별 상세 section을 조립할 수 있습니다.</p>
<p>{message("reference.detail.sectionSlot")}</p>
) : null}
</AsyncSurface>
}
aside={<p>상세 페이지의 관련 정보 slot입니다.</p>}
aside={<p>{message("reference.detail.aside")}</p>}
/>
);
}
@@ -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<keyof ReferenceResourceFormValues, string>;
export default function ReferenceResourceFormPage() {
const navigate = useNavigate();
const { message } = useLocale();
const fieldLabels = {
name: message("reference.form.name"),
note: message("reference.form.note"),
} satisfies Record<keyof ReferenceResourceFormValues, string>;
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")}
</button>
}
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={
<ErrorSummary
fieldErrors={form.fieldErrors}
formErrors={form.formErrors}
fieldLabels={FIELD_LABELS}
fieldLabels={fieldLabels}
fieldId={form.fieldId}
onFocusField={form.focusField}
/>
@@ -94,15 +94,15 @@ export default function ReferenceResourceFormPage() {
<>
<FormField
{...form.field("name")}
label={FIELD_LABELS.name}
description="앞뒤 공백은 command mapper 전에 제거됩니다."
label={fieldLabels.name}
description={message("reference.form.nameDescription")}
autoComplete="off"
required
/>
<FormField
{...form.field("note")}
label={FIELD_LABELS.note}
description="선택 입력이며 비어 있으면 command에 포함되지 않습니다."
label={fieldLabels.note}
description={message("reference.form.noteDescription")}
autoComplete="off"
/>
</>
@@ -114,20 +114,22 @@ export default function ReferenceResourceFormPage() {
onClick={() => navigate("/examples/reference-resources")}
disabled={form.pending || mutationBlocked}
>
취소
{message("reference.form.cancel")}
</Button>
<Button
type="submit"
disabled={form.pending || mutationBlocked}
>
{form.pending ? "저장 중…" : "저장"}
{form.pending
? message("reference.form.saving")
: message("reference.form.save")}
</Button>
<Button
variant="ghost"
onClick={() => form.reset()}
disabled={!form.dirty || form.pending || mutationBlocked}
>
초기화
{message("reference.form.reset")}
</Button>
</FormActions>
}
@@ -163,21 +165,18 @@ export default function ReferenceResourceFormPage() {
.catch(() => {});
}}
>
목록을 새로 불러와 확인
{message("reference.form.reloadList")}
</Link>
</p>
</>
) : form.result === "success" ? (
<p role="status">저장했습니다.</p>
<p role="status">{message("reference.form.saved")}</p>
) : form.result === "conflict" ? (
<p role="status">충돌을 해결한 뒤 다시 제출할 수 있습니다.</p>
<p role="status">{message("reference.form.conflict")}</p>
) : null
}
aside={
<p>
form value는 URL, storage, telemetry에 저장되지 않고 submit 시에만
application command로 변환됩니다.
</p>
<p>{message("reference.form.privacy")}</p>
}
guard={<DirtyNavigationDialog guard={guard} />}
/>
@@ -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(""),
})
@@ -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 (
<CollectionPage
heading={{
eyebrow: "제거 가능한 수직 슬라이스",
eyebrow: message("reference.list.eyebrow"),
title: "Reference feature",
description:
"URL codec, application input, HTTP/schema/mapper와 query 상태를 한 경로로 검증합니다.",
description: message("reference.list.description"),
}}
actions={[
{
kind: "button",
label: "새 항목 만들기",
label: message("reference.list.create"),
onAction: () => navigate("/examples/reference-resources/new"),
},
]}
@@ -34,9 +38,20 @@ export default function ReferenceResourcePage() {
{filters.tags?.length ? ` · tags ${filters.tags.join(", ")}` : ""}
</p>
}
toolbar={<Button onClick={() => void query.retry()}>새로고침</Button>}
toolbar={
<Button onClick={() => void query.retry()}>
{message("reference.list.refresh")}
</Button>
}
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
}
>
<AsyncSurface
@@ -48,7 +63,7 @@ export default function ReferenceResourcePage() {
{(query.data ?? []).map((resource) => (
<li key={resource.resourceId}>
<Link
to={`/examples/reference-resources/${encodeURIComponent(resource.resourceId)}`}
to={`/examples/reference-resources/items/${encodeURIComponent(resource.resourceId)}`}
>
{resource.title}
</Link>
@@ -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 (
<StatusPage
variant="maintenance"
heading={{
eyebrow: "StatusPage · maintenance",
title: "잠시 사용할 수 없습니다.",
description:
"도메인 데이터나 raw 오류를 노출하지 않는 중립적인 상태 페이지 예시입니다.",
title: message("reference.status.title"),
description: message("reference.status.description"),
}}
primaryAction={{
kind: "button",
label: "목록으로 이동",
label: message("reference.status.back"),
onAction: () => navigate("/examples/reference-resources"),
}}
supportReference="REFERENCE-STATUS-DEMO"
@@ -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<RecoveryResult>;
/** 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<Props, State> {
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 <ChunkRecoverySurface recovery="checking" />;
@@ -83,7 +92,15 @@ export class ChunkRecoveryBoundary extends Component<Props, State> {
return <ChunkRecoverySurface recovery="reload-requested" />;
}
if (error && recovery === "support") {
return <ChunkRecoverySurface recovery="support" reason={reason} />;
return (
<ChunkRecoverySurface
recovery="support"
reason={reason}
supportReference={[this.props.buildId, incidentId]
.filter(Boolean)
.join(":")}
/>
);
}
return this.props.children;
}
@@ -92,9 +109,11 @@ export class ChunkRecoveryBoundary extends Component<Props, State> {
function ChunkRecoverySurface({
recovery,
reason,
supportReference,
}: Readonly<{
recovery: Exclude<State["recovery"], "idle">;
reason?: string;
supportReference?: string;
}>) {
const { message } = useLocale();
if (recovery === "checking") {
@@ -119,6 +138,13 @@ function ChunkRecoverySurface({
<Button onClick={() => window.location.reload()}>
{message("action.reloadOnce")}
</Button>
{supportReference ? (
<p>
{message("template.supportReference", {
reference: supportReference,
})}
</p>
) : null}
</section>
);
}
@@ -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 ?? <DefaultRenderFailure onRetry={this.reset} />
);
const { fallback } = this.props;
if (typeof fallback === "function") {
return fallback(this.state.incidentId ?? newIncidentId());
}
return fallback ?? <DefaultRenderFailure onRetry={this.reset} />;
}
return this.props.children;
}
@@ -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 && (
<Button onClick={onAction}>{actionLabels[action]}</Button>
)}
{supportReference ? (
<p>
{message("template.supportReference", {
reference: supportReference,
})}
</p>
) : null}
</section>
);
}
@@ -121,6 +136,23 @@ export function AsyncSurface({
if (state.base === "initial-loading") return <LoadingSurface />;
if (state.base === "empty") return <EmptySurface />;
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 (
<div role="alert" data-message-key={state.failure.userMessageKey}>
<AccessState onAction={onAction} />
{state.failure.requestId ? (
<p>
{message("template.supportReference", {
reference: state.failure.requestId,
})}
</p>
) : null}
</div>
);
}
return (
<TerminalErrorSurface
userMessageKey={state.failure.userMessageKey}
@@ -130,6 +162,7 @@ export function AsyncSurface({
? onRetry ?? onAction
: onAction
}
supportReference={state.failure.requestId}
/>
);
}
@@ -177,3 +210,16 @@ export function AsyncSurface({
</section>
);
}
const ACCESS_SURFACES: Readonly<
Partial<
Record<
AppFailure["kind"],
(props: Readonly<{ onAction?: () => void }>) => ReactNode
>
>
> = Object.freeze({
AUTH_REQUIRED: ({ onAction }) => <AuthRequiredSurface onSignIn={onAction} />,
FORBIDDEN: ({ onAction }) => <ForbiddenSurface onNavigate={onAction} />,
NOT_FOUND: ({ onAction }) => <NotFoundSurface onNavigate={onAction} />,
});
+18 -3
View File
@@ -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 (
@@ -23,7 +23,9 @@ function StateSurface({
<p className="state-surface__eyebrow">{eyebrow}</p>
<h2>{title}</h2>
<p>{description}</p>
{actionLabel ? <Button onClick={onAction}>{actionLabel}</Button> : null}
{actionLabel && onAction ? (
<Button onClick={onAction}>{actionLabel}</Button>
) : null}
</section>
);
}
@@ -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);
}}
+1 -1
View File
@@ -82,7 +82,7 @@ export function ErrorSummary<Values extends FormValues>(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<{
+37 -13
View File
@@ -43,7 +43,7 @@ export function useAppForm<
Command,
Output,
>(options: AppFormOptions<Values, Command, Output>) {
const { message } = useLocale();
const { resolve } = useLocale();
const {
schema,
defaultValues,
@@ -59,10 +59,28 @@ export function useAppForm<
const [touched, setTouched] = useState<ReadonlySet<FieldName<Values>>>(
() => new Set(),
);
const [fieldErrors, setFieldErrors] = useState<FieldErrors<Values>>(
// 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<FieldErrors<Values>>(
() => ({} as FieldErrors<Values>),
);
const [formErrors, setFormErrors] = useState<readonly string[]>([]);
const [formErrorKeys, setFormErrors] = useState<readonly string[]>([]);
const fieldErrors = useMemo(
() =>
Object.freeze(
Object.fromEntries(
Object.entries(fieldErrorKeys).map(([name, key]) => [
name,
resolve(String(key)),
]),
),
) as FieldErrors<Values>,
[fieldErrorKeys, resolve],
);
const formErrors = useMemo(
() => formErrorKeys.map((key) => resolve(key)),
[formErrorKeys, resolve],
);
const [pending, setPending] = useState(false);
const [result, setResult] = useState<FormResultState>("idle");
const [statusFailure, setStatusFailure] = useState<AppFailure | null>(null);
@@ -188,7 +206,7 @@ export function useAppForm<
const mapped = mapValidationFailureToFields<Values>(
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<Values>(
parsed.error.issues,
allowedServerFields,
message,
messageKey,
);
setFieldErrors(errors);
setFormErrors(
parsed.error.issues.some(
(issue) => !allowedServerFields.includes(issue.path[0] as FieldName<Values>),
)
? [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<FormResultState> = new Set([
"reauth-required",
"forbidden",
"retry-later",
"unavailable",
]);
function issuesToFieldErrors<Values extends FormValues>(
+94 -2
View File
@@ -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<keyof typeof PLATFORM_KO_MESSAGES, string>;
@@ -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<
+24 -31
View File
@@ -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<ReturnType<typeof runtime.getReleaseSummary>> | "failed" | null
>(null);
@@ -44,48 +37,48 @@ export default function HomePage() {
return (
<section className="ui-page">
<PageHeader
eyebrow="프로젝트 시작점"
title="Clean Architecture Frontend"
description="도메인을 추가하기 전에 실행 구조와 범용 사용자 경험을 확인할 수 있는 중립적인 스켈레톤입니다."
eyebrow={message("home.eyebrow")}
title={message("route.APP_HOME.title")}
description={message("home.description")}
/>
<div className="readiness-grid" aria-label="구현 준비 상태">
<div className="readiness-grid" aria-label={message("home.readiness")}>
{READINESS_ITEMS.map((item) => (
<article className="ui-panel" key={item.title}>
<h2>{item.title}</h2>
<p>{item.description}</p>
<article className="ui-panel" key={item}>
<h2>{message(`home.readiness.${item}.title`)}</h2>
<p>{message(`home.readiness.${item}.description`)}</p>
</article>
))}
</div>
<p className="ui-runtime-summary" aria-live="polite">
{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")}
</p>
<section className="ui-panel starter-actions" aria-labelledby="starter-title">
<div>
<h2 id="starter-title">준비된 화면 살펴보기</h2>
<p>
설치된 라우트와 계약, 런타임 능력은 플랫폼 구성 화면에서, 공통
구성요소와 비동기 화면 상태는 예제 라우트에서 확인하세요.
</p>
<h2 id="starter-title">{message("home.starter.title")}</h2>
<p>{message("home.starter.description")}</p>
</div>
<div className="button-row">
<Link className="ui-button" to={routePath("EXAMPLES_PLATFORM")}>
플랫폼 구성 보기
{message("home.starter.platform")}
</Link>
<Link
className="ui-button ui-button--secondary"
to={routePath("EXAMPLES_UI")}
>
UI 구성요소 보기
{message("home.starter.ui")}
</Link>
<Link
className="ui-button ui-button--secondary"
to={routePath("EXAMPLES_STATES")}
>
화면 상태 보기
{message("home.starter.states")}
</Link>
</div>
</section>
+52 -8
View File
@@ -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 <DisabledFeatureSurface featureId={owner ?? routeId} />;
const parsed = parseRouteInput(routeId, params, search);
if (!parsed.success) return <InvalidRouteSurface code={parsed.code} />;
const boundaryName =
definition.errorSurface === "feature-boundary" ? "feature" : "route";
const content = (
<RouteInputProvider input={parsed.data}>
@@ -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,
})
}
>
<runtime.Component />
</ChunkRecoveryBoundary>
@@ -356,10 +385,15 @@ function RouteSurface({
buildId,
resetKey: `${location.pathname}${location.search}`,
onRenderFailure: diagnostics.reportRenderFailure,
fallback: <RouteFailureSurface definition={definition} />,
fallback: (incidentId: string) => (
<RouteFailureSurface
definition={definition}
supportReference={`${buildId}:${incidentId}`}
/>
),
children: protectedContent,
};
return definition.errorSurface === "feature-boundary" ? (
return boundaryName === "feature" ? (
<FeatureBoundary {...boundaryProps} />
) : (
<RouteBoundary {...boundaryProps} />
@@ -404,6 +438,7 @@ function ContextRouteGateway({
}: Readonly<{ routeModule: ContextRouteModule; buildId: string }>) {
const location = useLocation();
const recovery = useApplicationRecovery();
const diagnostics = useApplicationDiagnostics();
const [routes, setRoutes] = useState<readonly RouteObject[] | null>(null);
const [failure, setFailure] = useState<Readonly<{ error: unknown }> | null>(
null,
@@ -431,7 +466,7 @@ function ContextRouteGateway({
<ContextErrorBoundary
contextId={routeModule.id}
resetKey={resetKey}
fallback={<RouteFailureSurface />}
fallback={<RouteFailureSurface supportReference={buildId} />}
>
{content}
</ContextErrorBoundary>
@@ -444,11 +479,20 @@ function ContextRouteGateway({
<ChunkRecoveryBoundary
chunkId={routeChunkId(location.pathname) ?? routeModule.id}
recover={recovery.recoverChunk}
buildId={buildId}
onUnrecovered={(incidentId) =>
diagnostics.reportRenderFailure({
routeId: routeModule.id,
buildId,
boundaryName: "route",
incidentId,
})
}
>
<Rethrow error={failure.error} />
</ChunkRecoveryBoundary>
) : (
<RouteFailureSurface />
<RouteFailureSurface supportReference={buildId} />
);
}
if (routes === null) return <RouteLoadingSurface />;
@@ -475,7 +519,7 @@ function ContextRouteGateway({
<FeatureErrorBoundary
featureId={featureId}
resetKey={resetKey}
fallback={<RouteFailureSurface />}
fallback={<RouteFailureSurface supportReference={buildId} />}
>
{route}
</FeatureErrorBoundary>
@@ -522,7 +566,7 @@ function createRegisteredRoutes(buildId: string): RouteObject[] {
id: "APP_SHELL",
path: "/",
element: <AppShell />,
errorElement: <RouteFailureSurface />,
errorElement: <RouteFailureSurface supportReference={buildId} />,
children: [...platformChildren, ...contextChildren],
},
];
+5
View File
@@ -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;