UNPKG

wcz-layout

Version:

183 lines (163 loc) • 6.93 kB
--- name: forms description: 'Use when building or changing a form in app: create and edit pages or dialogs, fields (text, number, autocomplete, date/time, switch, checkbox, radio, slider), Zod validation and messages, default values, submit, reset and failed saves, or splitting a long form; also when a form throws "Maximum update depth exceeded".' metadata: type: convention library: wcz-layout --- TanStack Form v1 ships no agent skill. `useLayoutForm` is its `useAppForm` and `withLayoutForm` its `withForm` (both `wcz-layout/hooks`), pre-bound to the MUI fields below; the rest is upstream API. ## Rules - A feature has one `-components/Form.tsx`, shared by create and edit: props `defaultValues: <Entity>` and `onSubmit: (value: <Entity>) => Promise<void>`. It validates with the entity schema (`validators: { onChange: <Entity>Schema }`) and resets once `onSubmit` resolves. - Fields come only from render props. `form.AppField` gives `field.TextField`, `NumberField`, `Autocomplete`, `Checkbox`, `Switch`, `RadioGroup`, `Slider`, `DatePicker`, `TimePicker`, `DateTimePicker`; `form.AppForm` gives `form.SubmitButton`, which submits and owns its loading/busy state. It disables while submitting, not merely because values are invalid; `handleSubmit()` validates. Never wire a raw MUI input to the form; a missing kind of field is a custom field (last rule). - Size every field for its expected content (`sx={{ width: 420 }}`); labels, helper texts and the submit text go through `t`; mark required fields `required`. - The page's `onSubmit` runs the optimistic action (client-db), awaits `when("settled")`, then navigates. On failure it alerts and rethrows: the rejection stops the reset, so the input survives a failed save. The current SubmitButton also propagates that rejection from its click handler; handle event-boundary reporting in the library, never hide failure by resolving the page callback. - A form that stays open after a create (dialog, "add another") resets with a fresh id, `formApi.reset({ ...defaultValues, id: uuidv7() })`; a reused id makes the next insert a silent no-op. - Standard Schema validators check but do not transform `value`; the server validator normalizes simple rows. Explicitly parse at the client submit boundary when converting form values or when optimistic UI depends on normalized values. - When a field holds what the entity type can't, give the form its own schema (example): pickers hold `Dayjs | null`; required pickers/autocompletes must allow `null` in their input type but reject it in validation. Type the form with `z.input` of it, map rows in (`dayjs(row.dueAt)`), and turn the value back into the entity with `<Entity>Schema.parse({ ...value, dueAt: value.dueAt?.toDate() })` before the action. - `Autocomplete` stores the chosen option: for a foreign key pass ids as `options` with `getOptionLabel`, so the value is the id. - Split a long form into `withLayoutForm({ defaultValues, render })` sections. A custom field reads `useFieldContext<T>()` from `wcz-layout/hooks`. ## Examples ```tsx // src/routes/<feature>s/-components/Form.tsx import type { FC } from "react"; import { useLayoutForm, useTranslation } from "wcz-layout/hooks"; import { FeatureSchema, type Feature } from "~/lib/schemas/feature"; interface FormProps { defaultValues: Feature; onSubmit: (value: Feature) => Promise<void>; } export const Form: FC<FormProps> = ({ defaultValues, onSubmit }) => { const { t } = useTranslation(); const form = useLayoutForm({ defaultValues, validators: { onChange: FeatureSchema }, onSubmit: async ({ value, formApi }) => { await onSubmit(value); formApi.reset(); }, }); return ( <form onSubmit={async (event) => { event.preventDefault(); event.stopPropagation(); await form.handleSubmit(); }} > <form.AppField name="name"> {(field) => <field.TextField label={t("Feature.Name")} required sx={{ width: 420 }} />} </form.AppField> <form.AppForm> <form.SubmitButton>{t("Submit")}</form.SubmitButton> </form.AppForm> </form> ); }; ``` ```tsx // src/routes/<feature>s/create.tsx. edit.$id.tsx: the detail route's options (routing), // defaultValues={data} after the RouterNotFound guard, update in onMutate, navigate to the detail export const Route = createFileRoute("/features/create")({ component: RouteComponent, beforeLoad: requireAuth("admin"), }); function RouteComponent() { const { alert } = useDialogs(); const navigate = useNavigate(); const features = useFeatureCollection(); const handleOnSubmit = createOptimisticAction<Feature>({ onMutate: (value) => { features.insert(value); }, mutationFn: async (value) => { await insertFeature({ data: value }); await features.utils.refetch({ throwOnError: true }); }, }); return ( <Form defaultValues={{ id: uuidv7(), name: "", quantity: 0, active: true }} onSubmit={async (value) => { try { await handleOnSubmit(value).when("settled"); await navigate({ to: "/features" }); } catch (error) { if (error instanceof Error) await alert(error.message); throw error; } }} /> ); } ``` ```tsx // src/lib/schemas/<feature>.ts, below FeatureSchema: a form with a library picker and a due date const required = { error: () => t("Validation.Required") }; export const FeatureFormSchema = FeatureSchema.extend({ libraryId: z .uuid(required) .nullable() .refine((id) => id !== null, required), dueAt: z .custom<Dayjs>((value) => dayjs.isDayjs(value) && value.isValid(), { error: () => t("Validation.InvalidDate"), }) .nullable() .refine((value) => value !== null, required), }); export type FeatureForm = z.input<typeof FeatureFormSchema>; ``` ```tsx // Inside Form.tsx: defaults typed FeatureForm, validators.onChange = FeatureFormSchema. const { data: libraries } = useLiveQuery(librariesQueryOptions); const pickerFields = ( <> <form.AppField name="libraryId"> {(field) => ( <field.Autocomplete options={libraries.map(({ id }) => id)} getOptionLabel={(id) => libraries.find((library) => library.id === id)?.name ?? ""} sx={{ width: 300 }} textFieldProps={{ label: t("Feature.Library"), required: true }} /> )} </form.AppField> <form.AppField name="dueAt"> {(field) => ( <field.DatePicker label={t("Feature.DueAt")} textFieldProps={{ required: true }} sx={{ width: 200 }} /> )} </form.AppField> </> ); // create defaults { …, libraryId: null, dueAt: null }; edit { ...data, dueAt: dayjs(data.dueAt) }; // submit: handleOnSubmit(FeatureSchema.parse({ ...value, dueAt: value.dueAt?.toDate() })) ```