feat: add form and page platform
This commit is contained in:
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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)]),
|
||||
});
|
||||
}
|
||||
@@ -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";
|
||||
@@ -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>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user