Files
clean-architecture-frontend…/src/presentation/forms/form-components.tsx
T
donghyeon.kang e98d8ee9a9
frontend-quality-gates / merge / static checks (push) Successful in 1m12s
frontend-quality-gates / merge / tests (push) Failing after 10m10s
frontend-quality-gates / merge / browser tests (push) Successful in 6m1s
frontend-quality-gates / FE-GATE-017 / diagram-review (push) Skipped
frontend-quality-gates / FE-GATE-014 / config-compatibility (push) Skipped
frontend-quality-gates / FE-GATE-028 / manual-accessibility-review (push) Skipped
frontend-quality-gates / FE-GATE-026 / lab-performance (push) Skipped
frontend-quality-gates / FE-GATE-015 / immutable-release-candidate (push) Skipped
frontend-quality-gates / external-vulnerability-provider (push) Skipped
frontend-quality-gates / external-provenance-provider (push) Skipped
frontend-quality-gates / promote-verified-immutable-candidate (push) Skipped
frontend-quality-gates / deploy-promoted-release (push) Skipped
frontend-quality-gates / FE-GATE-019 / hosting-header (push) Skipped
frontend-quality-gates / FE-GATE-021 / runbook-boot-config (push) Skipped
frontend-quality-gates / FE-GATE-022 / runbook-chunk-mismatch (push) Skipped
frontend-quality-gates / FE-GATE-023 / runbook-api-degradation (push) Skipped
frontend-quality-gates / FE-GATE-024 / runbook-telemetry (push) Skipped
frontend-quality-gates / FE-GATE-025 / runbook-release-rollback (push) Skipped
frontend-quality-gates / FE-GATE-018 / field-web-vitals (push) Skipped
frontend-quality-gates / main / self-tests and removal drills (push) Failing after 2m3s
Merge pull request 'fix(design-system): 스타일·토큰·story·검사를 토큰 계약에 맞춘다' (#56) from donghyeon.kang/fix/r9-design-tokens-stories into main
2026-11-13 19:13:49 +00:00

207 lines
6.5 KiB
TypeScript

import { useId, type FormHTMLAttributes, type ReactNode } from "react";
import type { AsyncState } from "../../application/view-models/async-state.ts";
import type { AppFailure } from "../../contracts/errors.ts";
import { AsyncSurface, TerminalErrorSurface } from "../components/async-surface.tsx";
import type { HeadingLevel } from "../components/state-surfaces.tsx";
import { TextField } from "../components/ui/text-field.ts";
import { useLocale, type ParameterlessMessageKey } from "../i18n/index.ts";
import type {
FieldErrors,
FieldName,
FormResult,
FormResultState,
FormValues,
} from "./form-contracts.ts";
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;
/** 08-05. Below the heading of the card or section that holds it. */
headingLevel?: HeadingLevel | undefined;
}>) {
const { message } = useLocale();
const {
fieldErrors,
formErrors = [],
fieldLabels,
fieldId,
onFocusField,
headingLevel = 2,
} = props;
const headingId = useId();
const Heading = `h${headingLevel}` as const;
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}
>
<Heading id={headingId}>{message("form.errorSummary")}</Heading>
{entries.length > 0 ? (
<ul>
{entries.map(([name, error]) => (
<li key={name}>
<a
href={`#${fieldId(name)}`}
onClick={(event) => {
if (!onFocusField) return;
event.preventDefault();
onFocusField(name);
}}
>
{message("form.errorSummary.item", {
label: fieldLabels[name],
message: error,
})}
</a>
</li>
))}
</ul>
) : null}
{formErrors.map((message) => (
<p key={message}>{message}</p>
))}
</section>
);
}
/**
* 08-01. A save that failed for a reason other than the input (sign-in,
* permission, retry later, unavailable) is announced here with its own action, not in
* ErrorSummary. Pass `useAppForm().failure`.
*/
export function FormFailureStatus(props: Readonly<{
failure: AppFailure | null;
onAction?: () => void;
/** 08-05. Below the heading of the card or section that holds it. */
headingLevel?: HeadingLevel | undefined;
}>) {
const { message } = useLocale();
const { failure, onAction, headingLevel } = props;
if (!failure) return null;
return (
<TerminalErrorSurface
userMessageKey={failure.userMessageKey}
action={failure.action}
onAction={onAction}
// Signing in remounts the scope, so the entered values do not survive.
description={
failure.action === "reauth"
? message("form.reauthLosesInput")
: undefined
}
// 0929/08-04. The same support reference a failed query shows.
supportReference={failure.requestId}
headingLevel={headingLevel}
/>
);
}
export function FormActions(props: Readonly<{
children: ReactNode;
sticky?: boolean;
}>) {
return (
<div
className={`form-actions${props.sticky ? " form-actions--sticky" : ""}`}
>
{props.children}
</div>
);
}
/** What FormSaveFeedback reads of a `useAppForm` result given the `mutation` option. */
export type FormSaveFeedbackForm<Output> = Readonly<{
effectUnknown: boolean;
otherSaveRunning: boolean;
mutationState: AsyncState | undefined;
failure: AppFailure | null;
result: FormResultState;
notice: ParameterlessMessageKey | null;
supportReference: string | undefined;
submitForm(): Promise<unknown>;
confirmUnknownEffect(then?: () => void): Promise<void>;
resendUnknownEffect(): Promise<FormResult<Output> | null>;
}>;
/**
* 1112/01-01. The feedback of a form that saves through a mutation
* (`useAppForm` with `mutation`), in the order a page used to write out by
* hand: signing in again (D-2, whatever the effect), the unknown result
* (confirm it was applied, or resend it with the same key), then another
* save failure that is not an input error, then a conflict, then a save of
* the mutation this form did not start. Put it in the page template's
* feedback area (`FormPage` `feedback`, `feedbackId`). What a resend saved
* goes to the form's `onSaved`.
*/
export function FormSaveFeedback<Output>(props: Readonly<{
form: FormSaveFeedbackForm<Output>;
/**
* After "it was applied" has settled the request, while the form is
* mounted (a page opens the list).
*/
onConfirmed?: () => void;
/** The action of a failure that is not "try again" (sign in, for example). */
onFailureAction?: () => void;
}>) {
const { message } = useLocale();
const { form, onConfirmed, onFailureAction } = props;
const notice = form.notice ? message(form.notice) : undefined;
const failureStatus = form.failure ? (
<FormFailureStatus
failure={form.failure}
onAction={form.result === "retry-later" ? () => void form.submitForm() : onFailureAction}
/>
) : null;
if (form.failure?.action === "reauth") return failureStatus;
if (form.effectUnknown && form.mutationState) {
return (
<AsyncSurface
notice={notice}
onReconcileUnknownEffect={() => {
void form.confirmUnknownEffect(onConfirmed);
}}
onResendUnknownEffect={() => {
void form.resendUnknownEffect();
}}
state={form.mutationState}
supportReference={form.supportReference}
/>
);
}
if (failureStatus) return failureStatus;
if (form.result === "conflict" && notice) {
return <p role="alert">{notice}</p>;
}
if (form.otherSaveRunning && form.mutationState && form.result !== "effect-unknown") {
return <AsyncSurface state={form.mutationState} />;
}
return null;
}