feat: add form and page platform

This commit is contained in:
donghyeon-ka
2026-07-26 15:22:52 +09:00
parent fdcf0de5bf
commit b327d7370b
54 changed files with 2036 additions and 122 deletions
+9
View File
@@ -4,6 +4,7 @@ import {
createFailure as failure,
kindForStatus as statusKind,
normalizeUnknownFailure,
safeValidationIssues,
} from "../../contracts/errors.js";
import { mapOperationPayload } from "./resource-mapper.js";
import { retryDelay, shouldRetry } from "./retry-policy.js";
@@ -415,6 +416,10 @@ async function parseResponse(
const kind = statusKind(response.status);
const retryAfter = response.headers.get("retry-after");
const backendError =
envelopeRecord.error && typeof envelopeRecord.error === "object"
? /** @type {Record<string, unknown>} */ (envelopeRecord.error)
: {};
return {
ok: false,
error: failure(kind, operation.operationId, attempt, {
@@ -426,6 +431,10 @@ async function parseResponse(
response.status === 429 && retryAfter
? parseRetryAfterHeader(retryAfter)
: undefined,
validationIssues:
response.status === 422
? safeValidationIssues(backendError.details)
: undefined,
}),
};
}
+58
View File
@@ -195,6 +195,7 @@ export const ERROR_REGISTRY = Object.freeze({
* requestId?: string,
* traceId?: string,
* retryAfterMs?: number,
* validationIssues?: readonly Readonly<{path: string, code: string}>[],
* userMessageKey: string,
* action: ErrorAction,
* causeClass?: string
@@ -211,6 +212,7 @@ export const ERROR_REGISTRY = Object.freeze({
* requestId?: string,
* traceId?: string,
* retryAfterMs?: number,
* validationIssues?: readonly Readonly<{path: string, code: string}>[],
* causeClass?: string
* }} [details]
* @returns {ApiFailure}
@@ -236,6 +238,24 @@ export function createFailure(kind, operationId, attempt, details = {}) {
...(typeof details.retryAfterMs === "number"
? { retryAfterMs: details.retryAfterMs }
: {}),
...(Array.isArray(details.validationIssues)
? {
validationIssues: Object.freeze(
details.validationIssues
.filter(
(issue) =>
issue &&
typeof issue === "object" &&
typeof issue.path === "string" &&
typeof issue.code === "string",
)
.slice(0, 50)
.map((issue) =>
Object.freeze({ path: issue.path, code: issue.code }),
),
),
}
: {}),
...(typeof details.causeClass === "string"
? { causeClass: details.causeClass }
: {}),
@@ -244,6 +264,44 @@ export function createFailure(kind, operationId, attempt, details = {}) {
});
}
/**
* Projects an untrusted 422 details payload into the only validation metadata
* allowed to cross the HTTP boundary. Backend copy and additional values are
* deliberately discarded.
*
* @param {unknown} value
* @returns {readonly Readonly<{path: string, code: string}>[]}
*/
export function safeValidationIssues(value) {
if (!value || typeof value !== "object") return Object.freeze([]);
const candidate =
/** @type {{issues?: unknown, fieldErrors?: unknown}} */ (value);
const issues = Array.isArray(candidate.issues)
? candidate.issues
: Array.isArray(candidate.fieldErrors)
? candidate.fieldErrors
: [];
return Object.freeze(
issues
.filter(
(issue) =>
issue &&
typeof issue === "object" &&
typeof issue.path === "string" &&
typeof issue.code === "string" &&
issue.path.length <= 120 &&
issue.code.length <= 80,
)
.slice(0, 50)
.map((issue) =>
Object.freeze({
path: issue.path,
code: issue.code,
}),
),
);
}
/** @param {number} status */
export function kindForStatus(status) {
if (status === 401) return "AUTH_REQUIRED";
+5 -5
View File
@@ -6,11 +6,11 @@ reference implementation이다.
## 소유 경계
- `domain`: 외부 DTO와 React를 모르는 불변 model
- `application`: UI가 호출하는 list/create input과 gateway 계약
- `application`: UI가 호출하는 list/get/create input과 gateway 계약
- `adapters`: HTTP executor를 gateway로 투영하는 outbound adapter
- `contracts`: route/API/query contribution, Zod DTO와 request schema, mapper
- `presentation`: route input을 query/mutation controller로 연결하는 inbound
adapter page
- `presentation`: route input을 query/form controller로 연결하는 inbound
adapter, 독립 form schema/command mapper와 list/detail/form/status page
generic application은 `features.get(featureId)` catalog만 제공한다. feature hook이
자신의 input shape를 확인하며 page는 HTTP client, storage, auth owner, output
@@ -33,7 +33,7 @@ corepack pnpm test:sample-removal
```
첫 명령은 URL filter와 query key/HTTP request의 동일성, schema/mapper, 모든
query/mutation 상태와 production composition을 검증한다. 두 번째 명령은 임시
query/mutation/form 상태와 production composition을 검증한다. 두 번째 명령은 임시
복제본에서 이 source/test 디렉터리를 제거하고 installed catalog를 빈 목록으로
재생성한 뒤 typecheck, architecture, registry, unit/integration, home smoke,
production build와 fixture ID 잔여 0개를 검사한다.
production build와 source/built fixture ID 잔여 0개를 검사한다.
@@ -14,6 +14,7 @@ type HttpExecutor = Readonly<{
request: Readonly<{
operationId: string;
routeId: string;
pathParams?: Record<string, string | number>;
searchParams?: unknown;
body?: unknown;
signal?: AbortSignal;
@@ -42,7 +43,7 @@ export function createReferenceHttpGateway(
}
: result;
},
async create(command: Readonly<{ name: string }>) {
async create(command: Readonly<{ name: string; note?: string }>) {
const result = await http.execute({
operationId: "CREATE_REFERENCE_RESOURCE",
routeId: "REFERENCE_RESOURCE_LIST",
@@ -52,5 +53,19 @@ export function createReferenceHttpGateway(
? { ok: true as const, value: result.value as ReferenceResource }
: result;
},
async get(
resourceId: string,
context?: Readonly<{ signal?: AbortSignal }>,
) {
const result = await http.execute({
operationId: "GET_REFERENCE_RESOURCE",
routeId: "REFERENCE_RESOURCE_DETAIL",
pathParams: { resourceId },
signal: context?.signal,
});
return result.ok
? { ok: true as const, value: result.value as ReferenceResource }
: result;
},
});
}
@@ -21,7 +21,11 @@ export type ReferenceFeatureInput = Readonly<{
context?: Readonly<{ signal?: AbortSignal }>,
): Promise<ReferenceResult<readonly ReferenceResourceView[]>>;
createResource(
command: Readonly<{ name: string }>,
command: Readonly<{ name: string; note?: string }>,
): Promise<ReferenceResult<ReferenceResourceView>>;
getResource(
resourceId: string,
context?: Readonly<{ signal?: AbortSignal }>,
): Promise<ReferenceResult<ReferenceResourceView>>;
}>;
@@ -31,7 +35,11 @@ export type ReferenceGateway = Readonly<{
context?: Readonly<{ signal?: AbortSignal }>,
): Promise<ReferenceResult<readonly ReferenceResource[]>>;
create(
command: Readonly<{ name: string }>,
command: Readonly<{ name: string; note?: string }>,
): Promise<ReferenceResult<ReferenceResource>>;
get(
resourceId: string,
context?: Readonly<{ signal?: AbortSignal }>,
): Promise<ReferenceResult<ReferenceResource>>;
}>;
@@ -54,5 +62,11 @@ export function createReferenceFeatureInput(
? { ok: true as const, value: toReferenceView(result.value) }
: result;
},
async getResource(resourceId, context) {
const result = await gateway.get(resourceId, context);
return result.ok
? { ok: true as const, value: toReferenceView(result.value) }
: result;
},
});
}
@@ -7,6 +7,9 @@ export const referenceQueryKeys = Object.freeze({
all: () => REFERENCE_NAMESPACE,
list: (filters = {}) =>
Object.freeze([...REFERENCE_NAMESPACE, "list", canonicalize(filters)]),
/** @param {string} resourceId */
detail: (resourceId) =>
Object.freeze([...REFERENCE_NAMESPACE, "detail", String(resourceId)]),
});
export const REFERENCE_FEATURE_CONTRACT = Object.freeze({
@@ -25,6 +28,45 @@ export const REFERENCE_FEATURE_CONTRACT = Object.freeze({
navigationLabel: "Reference feature",
navigationOrder: 50,
}),
REFERENCE_RESOURCE_DETAIL: Object.freeze({
routeId: "REFERENCE_RESOURCE_DETAIL",
path: "/examples/reference-resources/:resourceId",
paramsSchema: "ReferenceResourceParams",
searchSchema: null,
access: "integration-defined",
loadingSurface: "reference-resource-detail",
errorSurface: "feature-boundary",
chunkId: "route-reference-resource-detail",
title: "Reference detail",
navigationLabel: null,
navigationOrder: null,
}),
REFERENCE_RESOURCE_FORM: Object.freeze({
routeId: "REFERENCE_RESOURCE_FORM",
path: "/examples/reference-resources/new",
paramsSchema: null,
searchSchema: null,
access: "integration-defined",
loadingSurface: "reference-resource-form",
errorSurface: "feature-boundary",
chunkId: "route-reference-resource-form",
title: "Reference form",
navigationLabel: null,
navigationOrder: null,
}),
REFERENCE_RESOURCE_STATUS: Object.freeze({
routeId: "REFERENCE_RESOURCE_STATUS",
path: "/examples/reference-resources/status",
paramsSchema: null,
searchSchema: null,
access: "integration-defined",
loadingSurface: "reference-resource-status",
errorSurface: "feature-boundary",
chunkId: "route-reference-resource-status",
title: "Reference status",
navigationLabel: null,
navigationOrder: null,
}),
}),
routeRuntimeContracts: Object.freeze({
REFERENCE_RESOURCE_LIST: Object.freeze({
@@ -33,6 +75,24 @@ export const REFERENCE_FEATURE_CONTRACT = Object.freeze({
paramsCodec: "none",
searchCodec: "ReferenceResourceListQuery",
}),
REFERENCE_RESOURCE_DETAIL: Object.freeze({
routeId: "REFERENCE_RESOURCE_DETAIL",
moduleId: "reference-resource-detail-page",
paramsCodec: "ReferenceResourceParams",
searchCodec: "none",
}),
REFERENCE_RESOURCE_FORM: Object.freeze({
routeId: "REFERENCE_RESOURCE_FORM",
moduleId: "reference-resource-form-page",
paramsCodec: "none",
searchCodec: "none",
}),
REFERENCE_RESOURCE_STATUS: Object.freeze({
routeId: "REFERENCE_RESOURCE_STATUS",
moduleId: "reference-resource-status-page",
paramsCodec: "none",
searchCodec: "none",
}),
}),
apiOperations: Object.freeze({
LIST_REFERENCE_RESOURCES: Object.freeze({
@@ -61,6 +121,19 @@ export const REFERENCE_FEATURE_CONTRACT = Object.freeze({
responseSchema: "ReferenceResourcePayload",
owner: "feature-frontend-reference-feature-vertical-slice",
}),
GET_REFERENCE_RESOURCE: Object.freeze({
method: "GET",
path: "/api/reference-resources/{resourceId}",
operationId: "GET_REFERENCE_RESOURCE",
auth: "external-session",
timeoutMs: null,
idempotency: "safe",
retry: "runtime",
requestSource: "none",
requestSchema: "NoRequest",
responseSchema: "ReferenceResourcePayload",
owner: "feature-frontend-form-page-platform",
}),
}),
queryRegistry: Object.freeze({
REFERENCE_RESOURCE: Object.freeze({
@@ -33,7 +33,10 @@ export function mapReferenceOperation(
if (!Array.isArray(payload)) throw new TypeError("Expected a reference list");
return payload.map(mapReferenceDto);
}
if (operationId === "CREATE_REFERENCE_RESOURCE") {
if (
operationId === "CREATE_REFERENCE_RESOURCE" ||
operationId === "GET_REFERENCE_RESOURCE"
) {
return mapReferenceDto(payload);
}
throw new TypeError(`No reference mapper registered for ${operationId}`);
@@ -18,6 +18,12 @@ export const referenceResourceListQuerySchema = z
})
.strict();
export const referenceResourceParamsSchema = z
.object({
resourceId: z.string().trim().min(1).max(120),
})
.strict();
const referenceResourceDtoSchema = z
.object({
id: z.string().min(1),
@@ -36,6 +42,7 @@ const requestSchemas = {
CreateReferenceResourceCommand: z
.object({
name: z.string().trim().min(1).max(120),
note: z.string().trim().max(500).optional(),
})
.strict(),
} satisfies Record<string, z.ZodType>;
@@ -1,9 +1,13 @@
import { lazy } from "react";
import { referenceResourceListQuerySchema } from "../contracts/reference-schemas.js";
import {
referenceResourceListQuerySchema,
referenceResourceParamsSchema,
} from "../contracts/reference-schemas.js";
export const REFERENCE_FEATURE_ROUTE_CODECS = {
ReferenceResourceListQuery: referenceResourceListQuerySchema,
ReferenceResourceParams: referenceResourceParamsSchema,
} as const;
export const REFERENCE_FEATURE_ROUTE_RUNTIME = {
@@ -11,4 +15,16 @@ export const REFERENCE_FEATURE_ROUTE_RUNTIME = {
moduleId: "reference-resource-page",
Component: lazy(() => import("./reference-resource-page.js")),
}),
REFERENCE_RESOURCE_DETAIL: Object.freeze({
moduleId: "reference-resource-detail-page",
Component: lazy(() => import("./reference-resource-detail-page.js")),
}),
REFERENCE_RESOURCE_FORM: Object.freeze({
moduleId: "reference-resource-form-page",
Component: lazy(() => import("./reference-resource-form-page.js")),
}),
REFERENCE_RESOURCE_STATUS: Object.freeze({
moduleId: "reference-resource-status-page",
Component: lazy(() => import("./reference-resource-status-page.js")),
}),
} as const;
@@ -0,0 +1,47 @@
import { Link } from "react-router-dom";
import { AsyncSurface } from "../../../presentation/components/async-surface.jsx";
import { DetailPage } from "../../../presentation/templates/index.js";
import { useRouteInput } from "../../../presentation/routes/app-router.js";
import { useReferenceDetail } from "./use-reference-feature.js";
export default function ReferenceResourceDetailPage() {
const route = useRouteInput();
const resourceId = String(route.params.resourceId);
const { query } = useReferenceDetail(resourceId);
const resource = query.data;
return (
<DetailPage
key={resourceId}
breadcrumb={
<Link to="/examples/reference-resources">Reference resources</Link>
}
heading={{
eyebrow: "DetailPage",
title: resource?.title ?? "Reference detail",
description: "route param과 detail query의 reset 경계를 확인합니다.",
}}
metadata={
resource ? (
<dl>
<dt>Resource ID</dt>
<dd>{resource.resourceId}</dd>
<dt>Created</dt>
<dd>{resource.createdAtLabel ?? "표시 정보 없음"}</dd>
</dl>
) : (
<p> .</p>
)
}
feedback={
<AsyncSurface state={query.state} onRetry={query.retry}>
{resource ? (
<p> section을 .</p>
) : null}
</AsyncSurface>
}
aside={<p> slot입니다.</p>}
/>
);
}
@@ -0,0 +1,131 @@
import { useCallback } from "react";
import { useNavigate } from "react-router-dom";
import { Button } from "../../../presentation/components/ui/button.jsx";
import {
DirtyNavigationDialog,
ErrorSummary,
Form,
FormActions,
FormField,
useAppForm,
useDirtyNavigationGuard,
} from "../../../presentation/forms/index.js";
import { FormPage } from "../../../presentation/templates/index.js";
import {
REFERENCE_FORM_DEFAULTS,
referenceResourceFormSchema,
toCreateReferenceCommand,
type ReferenceResourceFormValues,
} from "./reference-resource-form.js";
import { useReferenceCreate } from "./use-reference-feature.js";
const FIELD_LABELS = Object.freeze({
name: "새 항목 이름",
note: "설명",
}) satisfies Record<keyof ReferenceResourceFormValues, string>;
export default function ReferenceResourceFormPage() {
const navigate = useNavigate();
const mutation = useReferenceCreate();
const submit = useCallback(
(command: ReturnType<typeof toCreateReferenceCommand>) =>
mutation.submit(command),
[mutation],
);
const form = useAppForm({
schema: referenceResourceFormSchema,
defaultValues: REFERENCE_FORM_DEFAULTS,
allowedServerFields: ["name", "note"],
mapToCommand: toCreateReferenceCommand,
submit,
});
const guard = useDirtyNavigationGuard(form.dirty && !form.pending);
return (
<Form
id={form.formId}
pending={form.pending}
onSubmit={(event) => void form.submitForm(event)}
>
<FormPage
breadcrumb={
<button
className="ui-button ui-button--ghost"
type="button"
onClick={() => navigate("/examples/reference-resources")}
>
</button>
}
heading={{
eyebrow: "FormPage",
title: "Reference resource 만들기",
description:
"presentation schema, command mapper, 422/conflict와 dirty navigation 정책을 실행합니다.",
}}
errorSummary={
<ErrorSummary
fieldErrors={form.fieldErrors}
formErrors={form.formErrors}
fieldLabels={FIELD_LABELS}
fieldId={form.fieldId}
onFocusField={form.focusField}
/>
}
fields={
<>
<FormField
{...form.field("name")}
label={FIELD_LABELS.name}
description="앞뒤 공백은 command mapper 전에 제거됩니다."
autoComplete="off"
required
/>
<FormField
{...form.field("note")}
label={FIELD_LABELS.note}
description="선택 입력이며 비어 있으면 command에 포함되지 않습니다."
autoComplete="off"
/>
</>
}
formActions={
<FormActions sticky>
<Button
variant="secondary"
onClick={() => navigate("/examples/reference-resources")}
disabled={form.pending}
>
</Button>
<Button type="submit" disabled={form.pending}>
{form.pending ? "저장 중…" : "저장"}
</Button>
<Button
variant="ghost"
onClick={() => form.reset()}
disabled={!form.dirty || form.pending}
>
</Button>
</FormActions>
}
feedback={
form.result === "success" ? (
<p role="status">.</p>
) : form.result === "conflict" ? (
<p role="status"> .</p>
) : null
}
aside={
<p>
form value는 URL, storage, telemetry에 submit
application command로 .
</p>
}
guard={<DirtyNavigationDialog guard={guard} />}
/>
</Form>
);
}
@@ -0,0 +1,29 @@
import { z } from "zod";
export const referenceResourceFormSchema = z
.object({
name: z
.string()
.trim()
.min(2, "이름은 두 글자 이상이어야 합니다.")
.max(120),
note: z.string().trim().max(500).default(""),
})
.strict();
export type ReferenceResourceFormValues = z.infer<
typeof referenceResourceFormSchema
>;
export const REFERENCE_FORM_DEFAULTS: ReferenceResourceFormValues =
Object.freeze({
name: "",
note: "",
});
export function toCreateReferenceCommand(values: ReferenceResourceFormValues) {
return Object.freeze({
name: values.name,
...(values.note ? { note: values.note } : {}),
});
}
@@ -1,60 +1,53 @@
import { useState, type FormEvent } from "react";
import { Link, useNavigate } from "react-router-dom";
import { AsyncSurface } from "../../../presentation/components/async-surface.jsx";
import { Button } from "../../../presentation/components/ui/button.jsx";
import { PageHeader } from "../../../presentation/components/page-header.jsx";
import { CollectionPage } from "../../../presentation/templates/index.js";
import { useReferenceFeature } from "./use-reference-feature.js";
export default function ReferenceResourcePage() {
const { filters, query, mutation } = useReferenceFeature();
const [name, setName] = useState("");
async function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
const result = await mutation.submit({ name });
if (result.ok) setName("");
}
const navigate = useNavigate();
const { filters, query } = useReferenceFeature();
return (
<section className="ui-page">
<PageHeader
eyebrow="제거 가능한 수직 슬라이스"
title="Reference feature"
description="URL codec, application input, HTTP/schema/mapper와 query/mutation 상태를 한 경로로 검증합니다."
/>
<p data-testid="reference-filter">
limit {filters.limit}
{filters.tags?.length ? ` · tags ${filters.tags.join(", ")}` : ""}
</p>
<CollectionPage
heading={{
eyebrow: "제거 가능한 수직 슬라이스",
title: "Reference feature",
description:
"URL codec, application input, HTTP/schema/mapper와 query 상태를 한 경로로 검증합니다.",
}}
actions={[
{
kind: "button",
label: "새 항목 만들기",
onAction: () => navigate("/examples/reference-resources/new"),
},
]}
activeFilters={
<p data-testid="reference-filter">
limit {filters.limit}
{filters.tags?.length ? ` · tags ${filters.tags.join(", ")}` : ""}
</p>
}
toolbar={<Button onClick={() => void query.retry()}></Button>}
resultCount={
query.data ? `${query.data.length}개 항목` : "결과 확인 중"
}
>
<AsyncSurface state={query.state} onRetry={query.retry}>
<ul aria-label="Reference resources">
{(query.data ?? []).map((resource) => (
<li
key={resource.resourceId}
data-optimistic={resource.optimistic || undefined}
>
{resource.title}
<li key={resource.resourceId}>
<Link
to={`/examples/reference-resources/${encodeURIComponent(resource.resourceId)}`}
>
{resource.title}
</Link>
</li>
))}
</ul>
</AsyncSurface>
<AsyncSurface
state={mutation.state}
onResolveConflict={mutation.resolveConflict}
>
<form onSubmit={(event) => void submit(event)}>
<label htmlFor="reference-resource-name"> </label>
<input
id="reference-resource-name"
value={name}
onChange={(event) => setName(event.currentTarget.value)}
required
/>
<Button type="submit" disabled={mutation.state.overlay.mutationPending}>
</Button>
</form>
</AsyncSurface>
</section>
</CollectionPage>
);
}
@@ -0,0 +1,25 @@
import { useNavigate } from "react-router-dom";
import { StatusPage } from "../../../presentation/templates/index.js";
export default function ReferenceResourceStatusPage() {
const navigate = useNavigate();
return (
<StatusPage
variant="maintenance"
heading={{
eyebrow: "StatusPage · maintenance",
title: "잠시 사용할 수 없습니다.",
description:
"도메인 데이터나 raw 오류를 노출하지 않는 중립적인 상태 페이지 예시입니다.",
}}
primaryAction={{
kind: "button",
label: "목록으로 이동",
onAction: () => navigate("/examples/reference-resources"),
}}
supportReference="REFERENCE-STATUS-DEMO"
/>
);
}
@@ -14,19 +14,38 @@ import type {
ReferenceListFilters,
} from "../application/reference-feature-api.js";
function useReferenceFeatureInput(): ReferenceFeatureInput {
export function useReferenceFeatureInput(): ReferenceFeatureInput {
const candidate = useApplication().features.get(REFERENCE_FEATURE_ID);
if (
!candidate ||
typeof candidate !== "object" ||
typeof (candidate as ReferenceFeatureInput).listResources !== "function" ||
typeof (candidate as ReferenceFeatureInput).createResource !== "function"
typeof (candidate as ReferenceFeatureInput).createResource !== "function" ||
typeof (candidate as ReferenceFeatureInput).getResource !== "function"
) {
throw new Error("Reference feature application input is invalid");
}
return candidate as ReferenceFeatureInput;
}
export function useReferenceDetail(resourceId: string) {
const input = useReferenceFeatureInput();
const query = useApplicationQuery({
queryKey: referenceQueryKeys.detail(resourceId),
execute: ({ signal }) => input.getResource(resourceId, { signal }),
});
return Object.freeze({ query });
}
export function useReferenceCreate() {
const input = useReferenceFeatureInput();
return useApplicationMutation({
execute: input.createResource,
invalidate: [referenceQueryKeys.all()],
currentData: true,
});
}
export function useReferenceFeature() {
const input = useReferenceFeatureInput();
const routeInput = useRouteInput();
@@ -0,0 +1,90 @@
import { useId, type FormHTMLAttributes, type ReactNode } from "react";
import { TextField } from "../components/ui/text-field.jsx";
import type {
FieldErrors,
FieldName,
FormValues,
} from "./form-contracts.js";
export function Form(
props: FormHTMLAttributes<HTMLFormElement> & Readonly<{ pending?: boolean }>,
) {
const { pending = false, children, ...formProps } = props;
return (
<form {...formProps} noValidate aria-busy={pending || undefined}>
{children}
</form>
);
}
export function FormField(
props: React.ComponentProps<typeof TextField>,
) {
return <TextField {...props} />;
}
export function ErrorSummary<Values extends FormValues>(props: Readonly<{
fieldErrors: FieldErrors<Values>;
formErrors?: readonly string[];
fieldLabels: Readonly<Record<FieldName<Values>, string>>;
fieldId(name: FieldName<Values>): string;
onFocusField?(name: FieldName<Values>): void;
}>) {
const {
fieldErrors,
formErrors = [],
fieldLabels,
fieldId,
onFocusField,
} = props;
const headingId = useId();
const entries = Object.entries(fieldErrors) as [
FieldName<Values>,
string,
][];
if (entries.length === 0 && formErrors.length === 0) return null;
return (
<section
className="form-error-summary"
role="alert"
aria-labelledby={headingId}
>
<h2 id={headingId}> .</h2>
{entries.length > 0 ? (
<ul>
{entries.map(([name, message]) => (
<li key={name}>
<a
href={`#${fieldId(name)}`}
onClick={(event) => {
if (!onFocusField) return;
event.preventDefault();
onFocusField(name);
}}
>
{fieldLabels[name]}: {message}
</a>
</li>
))}
</ul>
) : null}
{formErrors.map((message) => (
<p key={message}>{message}</p>
))}
</section>
);
}
export function FormActions(props: Readonly<{
children: ReactNode;
sticky?: boolean;
}>) {
return (
<div
className={`form-actions${props.sticky ? " form-actions--sticky" : ""}`}
>
{props.children}
</div>
);
}
+69
View File
@@ -0,0 +1,69 @@
import type { ApiFailure } from "../../contracts/errors.js";
export type FormValues = Readonly<Record<string, unknown>>;
export type FieldName<Values extends FormValues> = Extract<keyof Values, string>;
export type FieldErrors<Values extends FormValues> = Readonly<
Partial<Record<FieldName<Values>, string>>
>;
export type FormResult<Value> =
| Readonly<{ ok: true; value: Value }>
| Readonly<{ ok: false; error: ApiFailure }>;
export type FormResultState =
| "idle"
| "success"
| "validation-error"
| "conflict"
| "unavailable";
export type MappedValidationFailure<Values extends FormValues> = Readonly<{
fieldErrors: FieldErrors<Values>;
formErrors: readonly string[];
}>;
const VALIDATION_COPY = Object.freeze({
REQUIRED: "필수 입력값입니다.",
too_small: "입력값이 너무 짧습니다.",
too_big: "입력값이 너무 깁니다.",
invalid_type: "입력 형식을 확인해 주세요.",
invalid_format: "입력 형식을 확인해 주세요.",
invalid_value: "허용된 값을 선택해 주세요.",
});
export function validationMessage(code: string): string {
return (
VALIDATION_COPY[code as keyof typeof VALIDATION_COPY] ??
"입력값을 확인해 주세요."
);
}
export function mapValidationFailureToFields<Values extends FormValues>(
failure: ApiFailure,
allowedFields: readonly FieldName<Values>[],
): MappedValidationFailure<Values> {
if (failure.kind !== "VALIDATION_REJECTED") {
return Object.freeze({ fieldErrors: Object.freeze({}), formErrors: [] });
}
const allowed = new Set<string>(allowedFields);
const fieldErrors: Partial<Record<FieldName<Values>, string>> = {};
const formErrors: string[] = [];
const issues = failure.validationIssues ?? [];
if (issues.length === 0) {
formErrors.push("입력값을 다시 확인해 주세요.");
}
for (const issue of issues) {
const field = issue.path.split(".").at(0) ?? "";
if (allowed.has(field)) {
const name = field as FieldName<Values>;
fieldErrors[name] ??= validationMessage(issue.code);
} else {
formErrors.push("서버가 확인하지 못한 입력 항목이 있습니다.");
}
}
return Object.freeze({
fieldErrors: Object.freeze(fieldErrors),
formErrors: Object.freeze([...new Set(formErrors)]),
});
}
+4
View File
@@ -0,0 +1,4 @@
export * from "./form-components.js";
export * from "./form-contracts.js";
export * from "./use-app-form.js";
export * from "./use-dirty-navigation-guard.js";
+244
View File
@@ -0,0 +1,244 @@
import {
useCallback,
useId,
useMemo,
useRef,
useState,
type ChangeEvent,
type FormEvent,
} from "react";
import type { ZodType, ZodIssue } from "zod";
import {
mapValidationFailureToFields,
validationMessage,
type FieldErrors,
type FieldName,
type FormResult,
type FormResultState,
type FormValues,
} from "./form-contracts.js";
type AppFormOptions<
Values extends FormValues,
Command,
Output,
> = Readonly<{
schema: ZodType<Values>;
defaultValues: Values;
allowedServerFields: readonly FieldName<Values>[];
mapToCommand(values: Values): Command;
submit(command: Command): Promise<FormResult<Output>>;
resetOnSuccess?: boolean;
}>;
export function useAppForm<
Values extends FormValues,
Command,
Output,
>(options: AppFormOptions<Values, Command, Output>) {
const {
schema,
defaultValues,
allowedServerFields,
mapToCommand,
submit,
resetOnSuccess = true,
} = options;
const generatedId = useId().replaceAll(":", "");
const formId = `app-form-${generatedId}`;
const [values, setValues] = useState<Values>(defaultValues);
const [initialValues, setInitialValues] = useState<Values>(defaultValues);
const [touched, setTouched] = useState<ReadonlySet<FieldName<Values>>>(
() => new Set(),
);
const [fieldErrors, setFieldErrors] = useState<FieldErrors<Values>>(
() => ({} as FieldErrors<Values>),
);
const [formErrors, setFormErrors] = useState<readonly string[]>([]);
const [pending, setPending] = useState(false);
const [result, setResult] = useState<FormResultState>("idle");
const pendingRef = useRef<Promise<FormResult<Output>> | null>(null);
const dirty = useMemo(
() => JSON.stringify(values) !== JSON.stringify(initialValues),
[initialValues, values],
);
const fieldId = useCallback(
(name: FieldName<Values>) => `${formId}-${name}`,
[formId],
);
const focusField = useCallback(
(name: FieldName<Values>) => {
const field = document.getElementById(fieldId(name));
if (field instanceof HTMLElement) field.focus();
},
[fieldId],
);
const focusFirstError = useCallback(
(errors: FieldErrors<Values>) => {
const first = allowedServerFields.find((name) => Boolean(errors[name]));
if (first) focusField(first);
},
[allowedServerFields, focusField],
);
const setValue = useCallback(
(name: FieldName<Values>, value: Values[FieldName<Values>]) => {
setValues((current) => ({ ...current, [name]: value }) as Values);
setFieldErrors((current) => {
if (!current[name]) return current;
const next = { ...current };
delete next[name];
return next;
});
setFormErrors([]);
setResult("idle");
},
[],
);
const field = useCallback(
(name: FieldName<Values>) => ({
id: fieldId(name),
name,
value: String(values[name] ?? ""),
onChange(event: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) {
setValue(name, event.currentTarget.value as Values[FieldName<Values>]);
},
onBlur() {
setTouched((current) => new Set(current).add(name));
},
error: fieldErrors[name],
"aria-invalid": fieldErrors[name] ? ("true" as const) : undefined,
}),
[fieldErrors, fieldId, setValue, values],
);
const reset = useCallback(
(nextValues: Values = defaultValues) => {
setValues(nextValues);
setInitialValues(nextValues);
setTouched(new Set());
setFieldErrors({} as FieldErrors<Values>);
setFormErrors([]);
setResult("idle");
},
[defaultValues],
);
const submitForm = useCallback(
async (event?: FormEvent<HTMLFormElement>): Promise<FormResult<Output> | null> => {
event?.preventDefault();
if (pendingRef.current) return pendingRef.current;
setFieldErrors({} as FieldErrors<Values>);
setFormErrors([]);
const parsed = await schema.safeParseAsync(values);
if (!parsed.success) {
const errors = issuesToFieldErrors<Values>(
parsed.error.issues,
allowedServerFields,
);
setFieldErrors(errors);
setFormErrors(
parsed.error.issues.some(
(issue) => !allowedServerFields.includes(issue.path[0] as FieldName<Values>),
)
? ["입력 구성을 다시 확인해 주세요."]
: [],
);
setTouched(new Set(allowedServerFields));
setResult("validation-error");
focusFirstError(errors);
return null;
}
const command = mapToCommand(parsed.data);
setPending(true);
const execution = submit(command);
pendingRef.current = execution;
try {
const outcome = await execution;
if (outcome.ok) {
setResult("success");
if (resetOnSuccess) {
setValues(defaultValues);
setInitialValues(defaultValues);
setTouched(new Set());
} else {
setInitialValues(parsed.data);
}
return outcome;
}
if (outcome.error.kind === "VALIDATION_REJECTED") {
const mapped = mapValidationFailureToFields<Values>(
outcome.error,
allowedServerFields,
);
setFieldErrors(mapped.fieldErrors);
setFormErrors(mapped.formErrors);
setResult("validation-error");
focusFirstError(mapped.fieldErrors);
} else if (outcome.error.kind === "CONFLICT") {
setFormErrors([
"다른 변경과 충돌했습니다. 입력은 유지되었으니 최신 상태를 확인해 주세요.",
]);
setResult("conflict");
} else {
setFormErrors(["저장하지 못했습니다. 잠시 후 다시 시도해 주세요."]);
setResult("unavailable");
}
return outcome;
} finally {
pendingRef.current = null;
setPending(false);
}
},
[
allowedServerFields,
defaultValues,
focusFirstError,
mapToCommand,
resetOnSuccess,
schema,
submit,
values,
],
);
return Object.freeze({
formId,
values,
dirty,
touched,
fieldErrors,
formErrors,
pending,
result,
field,
fieldId,
focusField,
setValue,
submitForm,
reset,
});
}
function issuesToFieldErrors<Values extends FormValues>(
issues: readonly ZodIssue[],
allowedFields: readonly FieldName<Values>[],
): FieldErrors<Values> {
const allowed = new Set<PropertyKey>(allowedFields);
const errors: Partial<Record<FieldName<Values>, string>> = {};
for (const issue of issues) {
const field = issue.path[0];
if (!allowed.has(field)) continue;
const name = field as FieldName<Values>;
errors[name] ??= validationMessage(issue.code);
}
return Object.freeze(errors);
}
@@ -0,0 +1,54 @@
import { useCallback } from "react";
import { useBeforeUnload, useBlocker } from "react-router-dom";
import { Button } from "../components/ui/button.jsx";
import { Dialog } from "../components/ui/dialog.jsx";
export function useDirtyNavigationGuard(when: boolean) {
const blocker = useBlocker(when);
useBeforeUnload(
useCallback(
(event) => {
if (!when) return;
event.preventDefault();
event.returnValue = "";
},
[when],
),
{ capture: true },
);
return Object.freeze({
blocked: blocker.state === "blocked",
stay() {
blocker.reset?.();
},
leave() {
blocker.proceed?.();
},
});
}
export function DirtyNavigationDialog(props: Readonly<{
guard: ReturnType<typeof useDirtyNavigationGuard>;
}>) {
return (
<Dialog
open={props.guard.blocked}
onClose={props.guard.stay}
title="저장하지 않은 변경이 있습니다."
description="이 화면을 떠나면 입력한 내용이 사라집니다."
actions={
<>
<Button variant="secondary" onClick={props.guard.stay}>
</Button>
<Button variant="danger" onClick={props.guard.leave}>
</Button>
</>
}
/>
);
}
+153
View File
@@ -590,6 +590,141 @@
line-height: 1.7;
}
.page-template {
display: grid;
gap: 1.25rem;
min-width: 0;
}
.page-template__breadcrumb {
padding-block-start: 1rem;
color: var(--color-content-muted);
font-size: 0.9rem;
}
.page-template__heading {
display: grid;
min-width: 0;
grid-template-columns: minmax(0, 1fr) auto;
align-items: end;
gap: 1rem;
}
.page-template__heading .page-header {
grid-row: span 2;
min-width: 0;
}
.page-template__status,
.page-template__actions,
.status-page__actions,
.form-actions {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: flex-end;
gap: 0.75rem;
}
.page-template__layout {
display: grid;
min-width: 0;
gap: 1.5rem;
}
.page-template__layout[data-has-aside="true"] {
grid-template-columns: minmax(0, 1fr) minmax(14rem, 20rem);
}
.page-template__content,
.page-template__aside,
.collection-page__results,
.detail-page__sections,
.form-page__fields {
min-width: 0;
}
.page-template__aside,
.detail-page__metadata,
.collection-page__toolbar,
.form-error-summary {
border: 1px solid var(--color-border);
border-radius: var(--radius-surface);
padding: 1rem;
background: var(--color-panel);
}
.collection-page__toolbar,
.collection-page__active-filters,
.collection-page__bulk-actions {
display: flex;
flex-wrap: wrap;
align-items: end;
gap: 0.75rem;
}
.collection-page__result-count {
color: var(--color-content-muted);
}
.collection-page__results,
.detail-page__sections,
.form-page__fields,
.form-page__error-summary {
display: grid;
gap: 1rem;
}
.collection-page__pagination {
margin-block-start: 1.25rem;
}
.detail-page__danger {
margin-block-start: 2rem;
border-top: 1px solid var(--color-danger-border);
padding-block-start: 1rem;
}
.form-error-summary {
border-color: var(--color-danger-border);
background: var(--color-danger-surface);
}
.form-error-summary h2 {
font-size: 1.1rem;
}
.form-error-summary p,
.form-error-summary ul {
margin-block-end: 0;
}
.form-actions {
padding-block-start: 1rem;
border-top: 1px solid var(--color-border);
}
.form-actions--sticky {
position: sticky;
z-index: 10;
bottom: 0;
padding: 0.75rem;
background: color-mix(in oklch, var(--color-panel) 94%, transparent);
}
.status-page {
max-width: 48rem;
padding-block: 2rem;
}
.status-page__actions {
justify-content: flex-start;
}
.status-page__support {
color: var(--color-content-muted);
}
.readiness-grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
@@ -832,6 +967,24 @@
.component-grid--three {
grid-template-columns: minmax(0, 1fr);
}
.page-template__heading,
.page-template__layout[data-has-aside="true"] {
grid-template-columns: minmax(0, 1fr);
}
.page-template__heading .page-header {
grid-row: auto;
}
.page-template__actions,
.page-template__status {
justify-content: flex-start;
}
.form-actions--sticky {
margin-inline: calc(var(--spacing-page) * -1);
}
}
@media (prefers-reduced-motion: reduce) {
+1
View File
@@ -0,0 +1 @@
export * from "./page-templates.js";
@@ -0,0 +1,246 @@
import type { ReactNode } from "react";
import { PageHeader } from "../components/page-header.jsx";
import { Button } from "../components/ui/button.jsx";
export type PageHeading = Readonly<{
title: string;
description?: string;
eyebrow?: string;
}>;
export type PageActionDefinition =
| Readonly<{
kind: "button";
label: string;
onAction(): void;
disabled?: boolean;
variant?: "primary" | "secondary" | "danger" | "ghost";
}>
| Readonly<{
kind: "link";
label: string;
href: string;
variant?: "primary" | "secondary" | "danger" | "ghost";
}>;
export type PageTemplateSlots = Readonly<{
heading: PageHeading;
breadcrumb?: ReactNode;
status?: ReactNode;
actions?: readonly PageActionDefinition[];
notices?: ReactNode;
children?: ReactNode;
aside?: ReactNode;
feedback?: ReactNode;
}>;
export function StandardPage(props: PageTemplateSlots) {
return (
<article className="ui-page page-template page-template--standard">
{props.breadcrumb ? (
<nav className="page-template__breadcrumb" aria-label="현재 위치">
{props.breadcrumb}
</nav>
) : null}
<div className="page-template__heading">
<PageHeader {...props.heading} />
{props.status ? (
<div className="page-template__status">{props.status}</div>
) : null}
{props.actions?.length ? (
<PageActionBar actions={props.actions} />
) : null}
</div>
{props.notices ? (
<div className="page-template__notices">{props.notices}</div>
) : null}
{props.feedback ? (
<div className="page-template__feedback">{props.feedback}</div>
) : null}
<div
className="page-template__layout"
data-has-aside={props.aside ? "true" : "false"}
>
<div className="page-template__content">{props.children}</div>
{props.aside ? (
<aside className="page-template__aside" aria-label="관련 정보">
{props.aside}
</aside>
) : null}
</div>
</article>
);
}
export function CollectionPage(
props: PageTemplateSlots &
Readonly<{
toolbar?: ReactNode;
activeFilters?: ReactNode;
resultCount?: ReactNode;
bulkActions?: ReactNode;
pagination?: ReactNode;
}>,
) {
return (
<StandardPage
{...props}
notices={
<>
{props.notices}
{props.toolbar ? (
<section
className="collection-page__toolbar"
aria-label="검색과 필터"
>
{props.toolbar}
</section>
) : null}
{props.activeFilters ? (
<div className="collection-page__active-filters">
{props.activeFilters}
</div>
) : null}
{props.resultCount ? (
<div className="collection-page__result-count" role="status">
{props.resultCount}
</div>
) : null}
{props.bulkActions ? (
<div className="collection-page__bulk-actions">
{props.bulkActions}
</div>
) : null}
</>
}
>
<div className="collection-page__results">{props.children}</div>
{props.pagination ? (
<nav className="collection-page__pagination" aria-label="페이지 탐색">
{props.pagination}
</nav>
) : null}
</StandardPage>
);
}
export function DetailPage(
props: PageTemplateSlots &
Readonly<{
metadata?: ReactNode;
destructiveAction?: ReactNode;
}>,
) {
return (
<StandardPage {...props}>
{props.metadata ? (
<section className="detail-page__metadata" aria-label="요약 정보">
{props.metadata}
</section>
) : null}
<div className="detail-page__sections">{props.children}</div>
{props.destructiveAction ? (
<section className="detail-page__danger" aria-label="위험 작업">
{props.destructiveAction}
</section>
) : null}
</StandardPage>
);
}
export function FormPage(
props: PageTemplateSlots &
Readonly<{
errorSummary?: ReactNode;
fields?: ReactNode;
formActions?: ReactNode;
guard?: ReactNode;
}>,
) {
return (
<StandardPage {...props}>
{props.errorSummary ? (
<div className="form-page__error-summary">{props.errorSummary}</div>
) : null}
<div className="form-page__fields">{props.fields ?? props.children}</div>
{props.formActions ? (
<div className="form-page__actions">{props.formActions}</div>
) : null}
{props.guard}
</StandardPage>
);
}
export type StatusPageVariant =
| "unauthenticated"
| "forbidden"
| "not-found"
| "unavailable"
| "offline"
| "maintenance"
| "unexpected";
export function StatusPage(
props: Readonly<{
variant: StatusPageVariant;
heading: PageHeading;
primaryAction?: PageActionDefinition;
secondaryAction?: PageActionDefinition;
supportReference?: string;
}>,
) {
return (
<section
className={`ui-page page-template status-page status-page--${props.variant}`}
data-status-variant={props.variant}
>
<PageHeader {...props.heading} />
{props.primaryAction || props.secondaryAction ? (
<PageActionBar
className="status-page__actions"
actions={
[props.primaryAction, props.secondaryAction].filter(
Boolean,
) as PageActionDefinition[]
}
/>
) : null}
{props.supportReference ? (
<p className="status-page__support">
: <code>{props.supportReference}</code>
</p>
) : null}
</section>
);
}
function PageActionBar(props: Readonly<{
actions: readonly PageActionDefinition[];
className?: string;
}>) {
return (
<div className={props.className ?? "page-template__actions"}>
{props.actions.map((action) =>
action.kind === "link" ? (
<a
className={`ui-button ui-button--${action.variant ?? "primary"}`}
href={action.href}
key={`${action.kind}:${action.label}`}
>
{action.label}
</a>
) : (
<Button
disabled={action.disabled}
key={`${action.kind}:${action.label}`}
onClick={action.onAction}
variant={action.variant}
>
{action.label}
</Button>
),
)}
</div>
);
}