wcz-layout 10.1.10 → 10.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/dist/Approval-D1TfISUL.mjs.map +1 -1
  2. package/dist/{LayoutTable-CxQNMuwo.d.mts → ChatLayout-BmLySLXy.d.mts} +11 -2
  3. package/dist/ChatLayout-Tpuwo8-b.mjs +1622 -0
  4. package/dist/ChatLayout-Tpuwo8-b.mjs.map +1 -0
  5. package/dist/DialogsContext-D23fJjYR.mjs.map +1 -1
  6. package/dist/Email-rnz3H0x3.mjs.map +1 -1
  7. package/dist/FileMeta-CPBWI_jA.mjs.map +1 -1
  8. package/dist/RouterListItemButton-CF-8w-08.mjs +62 -0
  9. package/dist/RouterListItemButton-CF-8w-08.mjs.map +1 -0
  10. package/dist/{approval-ByDIMRhe.mjs → approval-HB2w5jzc.mjs} +2 -2
  11. package/dist/approval-HB2w5jzc.mjs.map +1 -0
  12. package/dist/auth.mjs +4 -4
  13. package/dist/auth.mjs.map +1 -1
  14. package/dist/components.d.mts +3 -2
  15. package/dist/components.mjs +522 -627
  16. package/dist/components.mjs.map +1 -1
  17. package/dist/{createApi-L3ypB1gH.mjs → createApi-CKgFi53y.mjs} +3 -4
  18. package/dist/createApi-CKgFi53y.mjs.map +1 -0
  19. package/dist/data/client.mjs +3 -4
  20. package/dist/data/client.mjs.map +1 -1
  21. package/dist/data/server.mjs +4 -4
  22. package/dist/data/server.mjs.map +1 -1
  23. package/dist/env-BwFl7nWc.mjs +48 -0
  24. package/dist/env-BwFl7nWc.mjs.map +1 -0
  25. package/dist/{file-CwumKq_P.mjs → file-X1sK4ok6.mjs} +5 -4
  26. package/dist/file-X1sK4ok6.mjs.map +1 -0
  27. package/dist/{file-B4Q_bGLN.mjs → file-tkfsnk5F.mjs} +6 -5
  28. package/dist/file-tkfsnk5F.mjs.map +1 -0
  29. package/dist/generatedChart-k7NEdi5Z.mjs +211 -0
  30. package/dist/generatedChart-k7NEdi5Z.mjs.map +1 -0
  31. package/dist/hooks.d.mts +30 -2
  32. package/dist/hooks.mjs +1750 -1227
  33. package/dist/hooks.mjs.map +1 -1
  34. package/dist/index.d.mts +9 -2
  35. package/dist/index.mjs +1250 -1010
  36. package/dist/index.mjs.map +1 -1
  37. package/dist/middleware.mjs +2 -2
  38. package/dist/middleware.mjs.map +1 -1
  39. package/dist/models.d.mts +2 -2
  40. package/dist/models.mjs.map +1 -1
  41. package/dist/{peoplesoft-D1jPlXr9.mjs → peoplesoft-RnvfLbWH.mjs} +4 -23
  42. package/dist/peoplesoft-RnvfLbWH.mjs.map +1 -0
  43. package/dist/{providers-gKUqnVV5.mjs → providers-BfFg_3eo.mjs} +4 -20
  44. package/dist/providers-BfFg_3eo.mjs.map +1 -0
  45. package/dist/{tokens-DODxwvZ2.mjs → tokens-C4SErO-K.mjs} +10 -4
  46. package/dist/tokens-C4SErO-K.mjs.map +1 -0
  47. package/dist/{utils-obBGIuT3.mjs → utils-C2MZoH9U.mjs} +4 -31
  48. package/dist/utils-C2MZoH9U.mjs.map +1 -0
  49. package/dist/{utils-giYfiv39.d.mts → utils-CNYCSgip.d.mts} +2 -2
  50. package/dist/utils-DnMFybj3.mjs +27 -0
  51. package/dist/utils-DnMFybj3.mjs.map +1 -0
  52. package/dist/utils.d.mts +11 -2
  53. package/dist/utils.mjs +3 -5
  54. package/dist/vite.mjs.map +1 -1
  55. package/package.json +19 -21
  56. package/skills/ai/SKILL.md +156 -97
  57. package/skills/client-db/SKILL.md +104 -90
  58. package/skills/db-schema/SKILL.md +28 -20
  59. package/skills/dialogs/SKILL.md +26 -38
  60. package/skills/forms/SKILL.md +133 -73
  61. package/skills/general/SKILL.md +111 -126
  62. package/skills/general/references/auth.md +3 -7
  63. package/skills/routing/SKILL.md +60 -66
  64. package/skills/server-functions/SKILL.md +71 -26
  65. package/skills/services/SKILL.md +1 -1
  66. package/skills/services/docs/approval.md +4 -4
  67. package/skills/table/SKILL.md +113 -130
  68. package/dist/AggregatedCell-3CIdlmt6.mjs +0 -615
  69. package/dist/AggregatedCell-3CIdlmt6.mjs.map +0 -1
  70. package/dist/RouterListItemButton-B-cQ1XwU.mjs +0 -78
  71. package/dist/RouterListItemButton-B-cQ1XwU.mjs.map +0 -1
  72. package/dist/approval-ByDIMRhe.mjs.map +0 -1
  73. package/dist/createApi-L3ypB1gH.mjs.map +0 -1
  74. package/dist/file-B4Q_bGLN.mjs.map +0 -1
  75. package/dist/file-CwumKq_P.mjs.map +0 -1
  76. package/dist/peoplesoft-D1jPlXr9.mjs.map +0 -1
  77. package/dist/providers-gKUqnVV5.mjs.map +0 -1
  78. package/dist/tokens-DODxwvZ2.mjs.map +0 -1
  79. package/dist/utils-obBGIuT3.mjs.map +0 -1
  80. package/skills/general/references/exports.md +0 -117
@@ -1,27 +1,38 @@
1
1
  ---
2
2
  name: db-schema
3
- description: "Use when changing PostgreSQL tables, columns, constraints, indexes, enums, foreign keys, relations, migrations, or Drizzle-derived Zod schemas in a wcz-layout app."
3
+ description: "Use when adding or changing PostgreSQL tables, columns, constraints, indexes, enums, foreign keys or relations with Drizzle, the Zod schema and type derived from a table, validation messages, or when a migration is asked for."
4
4
  metadata:
5
5
  type: convention
6
6
  library: wcz-layout
7
7
  ---
8
8
 
9
- # Database schema patterns
9
+ Migration commands and drizzle-kit output: load `drizzle-kit#drizzle-migrations` and
10
+ `drizzle-kit#drizzle-generate`.
10
11
 
11
12
  ## Rules
12
13
 
13
- - One table per file, named after the table (e.g. `bookTable` lives in `book.ts`). Never put multiple tables in one file, even when they are related — a parent and its children each get their own file.
14
- - Use `uuid` for application-table primary keys and `snakeCase` for generating tables.
15
- - For `uuid` columns, do not generate random values in the schema. The client generates the id with `uuidv7()` from `wcz-layout/utils` when creating the record.
16
- - Always add `withTimezone: true` to timestamp columns.
17
- - Always declare `onDelete` explicitly on every foreign key — never rely on the default. Pick the behavior from the business rule: `"cascade"` when the child is meaningless without its parent, `"restrict"` when the parent must not be deleted while children exist, `"set null"` for optional references.
18
- - Index every foreign key column. Postgres does not create one for you.
19
- - Define relations in a central `relations.ts` file.
20
- - Declare enums with `pgEnum` in the table's own file, export them, and reference `enumValues` everywhere else — never re-declare the values.
21
- - Generate the full client record schema with `createSelectSchema` from `drizzle-orm/zod`. Use `createInsertSchema`; override fields with stricter rules (trim, min/max) where needed.
22
- - The second argument of `createSelectSchema` refines **existing columns only**. Adding a key
23
- that is not a column is a type error. Attach related data with `.extend()` after it.
24
- - Do not auto-generate migrations unless the user explicitly asks. When asked, run `npm run db:generate`; migrations apply automatically at app startup while `DATABASE_AUTO_MIGRATE=true`.
14
+ - One table per file in `src/server/db/schemas/`, named after it (`bookTable` in `book.ts`),
15
+ even for a parent and its children. Tables use `snakeCase.table("<plural>", …)`.
16
+ - Primary key `id: uuid().primaryKey()` with no default: the client creates the id with
17
+ `uuidv7()`.
18
+ - Timestamps: `timestamp({ withTimezone: true })`.
19
+ - Foreign keys declare `onDelete` from the business rule: `"cascade"` when the child is
20
+ meaningless without the parent, `"restrict"` when the parent must outlive its children,
21
+ `"set null"` for optional references. Index every foreign key column; Postgres does not.
22
+ - Enums: `pgEnum` in the table's file, exported; everything else reads `.enumValues`, never
23
+ a second list.
24
+ - Relations live in the one `relations.ts` (`defineRelations`), never in table files.
25
+ - The entity's Zod schema is `createSelectSchema(table, refinements)` from `drizzle-orm/zod`
26
+ in `src/lib/schemas/<entity>.ts`, with `export type <Entity> = z.infer<…>`. The client builds
27
+ whole rows, id included, so this one schema validates the form, the collection and the
28
+ server function input.
29
+ - Refinements tighten existing columns only (an unknown key is a type error): text gets
30
+ `.trim()`, `.min(1)` when required, `.max(n)`. Add related or derived fields with `.extend()`.
31
+ - Messages are lazy: `{ error: () => t("Validation.Required") }`. A plain `t(...)` runs once at
32
+ import, before the user's language is known, and never follows a language switch.
33
+ - Every table is audited: startup runs `attach_audit_triggers_all()` and `databaseMiddleware`
34
+ sets the acting user. Never add history tables or audit triggers.
35
+ - Migrations apply at startup.
25
36
 
26
37
  ## Examples
27
38
 
@@ -77,21 +88,18 @@ export const relations = defineRelations(
77
88
  ```
78
89
 
79
90
  ```ts
80
- // src/lib/schemas/<table>.ts
91
+ // src/lib/schemas/<entity>.ts
81
92
  import { createSelectSchema } from "drizzle-orm/zod";
82
93
  import { t } from "wcz-layout/utils";
83
94
  import type { z } from "zod";
84
95
  import { bookTable } from "~/server/db/schemas/book";
85
- import { PageSchema } from "./page";
86
96
 
87
97
  export const BookSchema = createSelectSchema(bookTable, {
88
98
  title: (schema) =>
89
99
  schema
90
100
  .trim()
91
- .min(1, t("Validation.Required"))
92
- .max(255, t("Validation.MaxLength", { length: 255 })),
93
- }).extend({
94
- pages: PageSchema.array().min(1, t("Validation.Required")),
101
+ .min(1, { error: () => t("Validation.Required") })
102
+ .max(255, { error: () => t("Validation.MaxLength", { length: 255 }) }),
95
103
  });
96
104
 
97
105
  export type Book = z.infer<typeof BookSchema>;
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: dialogs
3
- description: "Use for acknowledgement alerts, confirmation prompts, or custom MUI Dialogs opened through useDialogs."
3
+ description: "Use when app needs an alert, a confirmation before a destructive or irreversible action, an error message to acknowledge, or a custom MUI Dialog (create/edit dialog, picker, scanner) opened from code with useDialogs and awaited for its result."
4
4
  metadata:
5
5
  type: convention
6
6
  library: wcz-layout
@@ -8,51 +8,39 @@ metadata:
8
8
 
9
9
  ## Rules
10
10
 
11
- - Use `useDialogs()` instead of mounting another provider. It returns `{ alert, confirm, open, close }`.
12
- - Use `confirm()` for destructive or user-confirmed actions.
13
- - Use `alert()` for informational or error messages that require acknowledgement.
14
- - Use `open()` for feature-specific custom dialogs with typed payloads.
15
- - Custom dialogs receive `DialogProps<TPayload, TResult>`. `open()` resolves with
16
- whatever the dialog passes to `onClose(result)`, so a dialog that answers a
17
- question declares its result type and the caller awaits it. Leave `TResult` off
18
- only for dialogs that return nothing.
19
- - Use `close(dialog, result)` only to close outside the dialog component, passing the
20
- promise returned by `open()`. Custom dialogs normally call their injected `onClose(result)`.
21
- - Colocate feature-specific dialogs in `routes/<feature>s/-components`; put dialogs used by more than one route in `src/components`.
11
+ - `useDialogs()` from `wcz-layout/hooks` returns `{ alert, confirm, open, close }`;
12
+ `LayoutProvider` already mounts the provider.
13
+ - `confirm(message)` resolves `true`/`false`; ask it before every delete and other
14
+ irreversible action. Delete prompts use `t("DeleteConfirmation", { count })`.
15
+ - `alert(message)` for anything the user must acknowledge, first of all a failed action:
16
+ `if (error instanceof Error) await alert(error.message)`.
17
+ - `open(Component, payload)` renders a custom dialog and resolves with what it passes to
18
+ `onClose(result)`. Type it `DialogProps<TPayload, TResult>`; leave `TResult` off only for
19
+ dialogs that return nothing. Never keep dialog open-state in the caller.
20
+ - `close(dialogPromise, result)` closes a dialog from outside, with the promise `open()`
21
+ returned; inside, call the injected `onClose`.
22
+ - Save inside the dialog: await persistence, then `onClose(success)`. The optional
23
+ `open(..., { onClose })` callback is not a veto: the provider closes even if it rejects.
24
+ Do not put a fallible save there and expect the form to stay open.
25
+ - A feature's dialogs live in `routes/<entities>/-components`, shared ones in `src/components`.
22
26
 
23
27
  ## Examples
24
28
 
25
29
  ```tsx
26
- // confirmation dialog
27
- const { confirm } = useDialogs();
28
- const { t } = useTranslation();
29
-
30
- const confirmed = await confirm(t("DeleteConfirmation", { count: selectedIds.length }));
31
- if (confirmed) await deleteFeatures({ data: selectedIds });
32
- ```
33
-
34
- ```tsx
35
- // alert dialog
36
- const { alert } = useDialogs();
37
- const { t } = useTranslation();
38
-
39
- try {
40
- await saveFeature(values);
41
- } catch (error) {
42
- await alert(error instanceof Error ? error.message : t("UnknownError"));
30
+ const { confirm, alert, open } = useDialogs();
31
+
32
+ if (await confirm(t("DeleteConfirmation", { count: ids.length }))) {
33
+ try {
34
+ await handleOnDelete(ids).when("settled");
35
+ } catch (error) {
36
+ if (error instanceof Error) await alert(error.message);
37
+ }
43
38
  }
44
- ```
45
-
46
- ```tsx
47
- // custom dialog that returns a result
48
- const { open } = useDialogs();
49
39
 
50
40
  const saved = await open(EditFeatureDialog, { id });
51
- if (saved) await features.utils.refetch({ throwOnError: true });
52
41
  ```
53
42
 
54
43
  ```tsx
55
- // custom dialog component
56
44
  interface Payload {
57
45
  id: string;
58
46
  }
@@ -62,11 +50,11 @@ export const EditFeatureDialog = ({ payload, open, onClose }: DialogProps<Payloa
62
50
 
63
51
  return (
64
52
  <Dialog fullWidth open={open} onClose={() => onClose(false)}>
65
- <DialogTitle>{t("EditFeature")}</DialogTitle>
53
+ <DialogTitle>{t("Feature.Confirm")}</DialogTitle>
66
54
  <DialogContent>{payload.id}</DialogContent>
67
55
  <DialogActions>
68
56
  <Button onClick={() => onClose(false)}>{t("Cancel")}</Button>
69
- <Button onClick={() => onClose(true)}>{t("Save")}</Button>
57
+ <Button onClick={() => onClose(true)}>{t("Confirm")}</Button>
70
58
  </DialogActions>
71
59
  </Dialog>
72
60
  );
@@ -1,48 +1,58 @@
1
1
  ---
2
2
  name: forms
3
- description: "Use when building or changing forms, including fields, validation, submission, reset, date values, async initial values, or reusable subforms."
3
+ 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".'
4
4
  metadata:
5
5
  type: convention
6
6
  library: wcz-layout
7
7
  ---
8
8
 
9
- # Form patterns
10
-
11
- > Mechanics (`createFormHook`, `withForm`, field API, validation lifecycle) belong to
12
- > TanStack Form v1. `useLayoutForm` is its `useAppForm` and `withLayoutForm` its `withForm`,
13
- > pre-bound to the MUI field set below.
9
+ TanStack Form v1 ships no agent skill. `useLayoutForm` is its `useAppForm` and
10
+ `withLayoutForm` its `withForm` (both `wcz-layout/hooks`), pre-bound to the MUI fields below;
11
+ the rest is upstream API.
14
12
 
15
13
  ## Rules
16
14
 
17
- - Always use `useLayoutForm` with the pre-defined components.
18
- - Fields are not importable; reach them through render props. `form.AppField` yields
19
- `field.Autocomplete`, `field.Checkbox`, `field.DatePicker`, `field.DateTimePicker`,
20
- `field.NumberField`, `field.RadioGroup`, `field.Slider`, `field.Switch`, `field.TextField`
21
- and `field.TimePicker`. `form.AppForm` yields `form.SubmitButton`, and nothing else. Pick
22
- the field that matches the value.
23
- - Define `width` for all form fields based on the expected content length.
24
- - Reuse Zod schemas from `src/lib/schemas/`, derived from Drizzle tables with `createSelectSchema`.
25
- - `field.DatePicker`, `field.TimePicker` and `field.DateTimePicker` hold `Dayjs`, not `Date`.
26
- A Drizzle `timestamp` column gives you a `Date`, so convert at both boundaries:
27
- `dayjs(row.dueAt)` into `defaultValues`, `.toDate()` on the way out in `onSubmit`.
28
- - Use translation for labels, helper text, validation messages and submit.
29
- - Reset the form after a successful create, and let the submit handler reject on failure so
30
- a failed save keeps what the user typed: the route alerts, then rethrows (see the route
31
- example). A handler that only alerts resolves, and the form resets anyway.
32
- - `SubmitButton` calls `form.handleSubmit()` and owns its loading and disabled state.
33
- - `reset()` restores the `defaultValues` captured when the form was constructed. If those
34
- contain a generated `uuidv7()` id, pass a fresh one to `reset({ ...defaults, id: uuidv7() })`
35
- or the second create collides on the primary key.
36
- - `defaultValues` only re-syncs into a mounted form while it is still untouched. On edit
37
- routes, preload the query in the loader so the row is there before the form mounts.
38
- - When fetching data for a form, always use a suspense query.
39
- - Split a long form with `withLayoutForm`, which binds a sub-form to the same
40
- `defaultValues` shape as the parent. Custom field components read `useFieldContext<T>()`.
15
+ - A feature has one `-components/Form.tsx`, shared by create and edit: props
16
+ `defaultValues: <Entity>` and `onSubmit: (value: <Entity>) => Promise<void>`. It validates
17
+ with the entity schema (`validators: { onChange: <Entity>Schema }`) and resets once
18
+ `onSubmit` resolves.
19
+ - Fields come only from render props. `form.AppField` gives `field.TextField`, `NumberField`,
20
+ `Autocomplete`, `Checkbox`, `Switch`, `RadioGroup`, `Slider`, `DatePicker`, `TimePicker`,
21
+ `DateTimePicker`; `form.AppForm` gives `form.SubmitButton`, which submits and owns its
22
+ loading/busy state. It disables while submitting, not merely because values are invalid;
23
+ `handleSubmit()` validates. Never wire a raw MUI input to the form; a missing kind of field
24
+ is a custom field (last rule).
25
+ - Size every field for its expected content (`sx={{ width: 420 }}`); labels, helper texts and
26
+ the submit text go through `t`; mark required fields `required`.
27
+ - The page's `onSubmit` runs the optimistic action (client-db), awaits `when("settled")`, then
28
+ navigates. On failure it alerts and rethrows: the rejection stops the reset, so the input
29
+ survives a failed save.
30
+ The current SubmitButton also propagates that rejection from its click handler; handle
31
+ event-boundary reporting in the library, never hide failure by resolving the page callback.
32
+ - A form that stays open after a create (dialog, "add another") resets with a fresh id,
33
+ `formApi.reset({ ...defaultValues, id: uuidv7() })`; a reused id makes the next insert a
34
+ silent no-op.
35
+ - Standard Schema validators check but do not transform `value`; the server validator
36
+ normalizes simple rows. Explicitly parse at the client submit boundary when converting
37
+ form values or when optimistic UI depends on normalized values.
38
+ - When a field holds what the entity type can't, give the form its own schema (example):
39
+ pickers hold `Dayjs | null`; required pickers/autocompletes must allow `null` in their input
40
+ type but reject it in validation. Type the form
41
+ with `z.input` of it, map rows in (`dayjs(row.dueAt)`), and turn the value back into the
42
+ entity with `<Entity>Schema.parse({ ...value, dueAt: value.dueAt?.toDate() })` before the action.
43
+ - `Autocomplete` stores the chosen option: for a foreign key pass ids as `options` with
44
+ `getOptionLabel`, so the value is the id.
45
+ - Split a long form into `withLayoutForm({ defaultValues, render })` sections. A custom field
46
+ reads `useFieldContext<T>()` from `wcz-layout/hooks`.
41
47
 
42
48
  ## Examples
43
49
 
44
50
  ```tsx
45
- // Form component
51
+ // src/routes/<feature>s/-components/Form.tsx
52
+ import type { FC } from "react";
53
+ import { useLayoutForm, useTranslation } from "wcz-layout/hooks";
54
+ import { FeatureSchema, type Feature } from "~/lib/schemas/feature";
55
+
46
56
  interface FormProps {
47
57
  defaultValues: Feature;
48
58
  onSubmit: (value: Feature) => Promise<void>;
@@ -68,36 +78,11 @@ export const Form: FC<FormProps> = ({ defaultValues, onSubmit }) => {
68
78
  await form.handleSubmit();
69
79
  }}
70
80
  >
71
- <form.AppField name="property1">
72
- {(field) => <field.TextField label={t("Feature.Property1")} required sx={{ width: 420 }} />}
73
- </form.AppField>
74
-
75
- <form.AppField name="property2">
76
- {(field) => (
77
- <field.Autocomplete
78
- options={options}
79
- autoHighlight
80
- autoSelect
81
- autoComplete
82
- loading={isLoading}
83
- sx={{ width: 250 }}
84
- textFieldProps={{ label: t("Feature.Property2"), required: true }}
85
- />
86
- )}
87
- </form.AppField>
88
-
89
- <form.AppField name="property3">
90
- {(field) => (
91
- <field.NumberField label={t("Feature.Property3")} required sx={{ width: 120 }} />
92
- )}
93
- </form.AppField>
94
-
95
- <form.AppField name="property4">
96
- {(field) => <field.Switch label={t("Feature.Property4")} />}
81
+ <form.AppField name="name">
82
+ {(field) => <field.TextField label={t("Feature.Name")} required sx={{ width: 420 }} />}
97
83
  </form.AppField>
98
-
99
84
  <form.AppForm>
100
- <form.SubmitButton variant="contained">{t("Submit")}</form.SubmitButton>
85
+ <form.SubmitButton>{t("Submit")}</form.SubmitButton>
101
86
  </form.AppForm>
102
87
  </form>
103
88
  );
@@ -105,18 +90,93 @@ export const Form: FC<FormProps> = ({ defaultValues, onSubmit }) => {
105
90
  ```
106
91
 
107
92
  ```tsx
108
- // Route rendering the form: alert, then rethrow so a failed save keeps the input
109
- <Form
110
- defaultValues={{ id: uuidv7(), property1: "" }}
111
- onSubmit={async (value) => {
112
- try {
113
- const transaction = handleOnSubmit(value);
114
- await transaction.isPersisted.promise;
115
- await navigate({ to: "/features" });
116
- } catch (error) {
117
- if (error instanceof Error) await alert(error.message);
118
- throw error;
119
- }
120
- }}
121
- />
93
+ // src/routes/<feature>s/create.tsx. edit.$id.tsx: the detail route's options (routing),
94
+ // defaultValues={data} after the RouterNotFound guard, update in onMutate, navigate to the detail
95
+ export const Route = createFileRoute("/features/create")({
96
+ component: RouteComponent,
97
+ beforeLoad: requireAuth("admin"),
98
+ });
99
+
100
+ function RouteComponent() {
101
+ const { alert } = useDialogs();
102
+ const navigate = useNavigate();
103
+ const features = useFeatureCollection();
104
+
105
+ const handleOnSubmit = createOptimisticAction<Feature>({
106
+ onMutate: (value) => {
107
+ features.insert(value);
108
+ },
109
+ mutationFn: async (value) => {
110
+ await insertFeature({ data: value });
111
+ await features.utils.refetch({ throwOnError: true });
112
+ },
113
+ });
114
+
115
+ return (
116
+ <Form
117
+ defaultValues={{ id: uuidv7(), name: "", quantity: 0, active: true }}
118
+ onSubmit={async (value) => {
119
+ try {
120
+ await handleOnSubmit(value).when("settled");
121
+ await navigate({ to: "/features" });
122
+ } catch (error) {
123
+ if (error instanceof Error) await alert(error.message);
124
+ throw error;
125
+ }
126
+ }}
127
+ />
128
+ );
129
+ }
130
+ ```
131
+
132
+ ```tsx
133
+ // src/lib/schemas/<feature>.ts, below FeatureSchema: a form with a library picker and a due date
134
+ const required = { error: () => t("Validation.Required") };
135
+
136
+ export const FeatureFormSchema = FeatureSchema.extend({
137
+ libraryId: z
138
+ .uuid(required)
139
+ .nullable()
140
+ .refine((id) => id !== null, required),
141
+ dueAt: z
142
+ .custom<Dayjs>((value) => dayjs.isDayjs(value) && value.isValid(), {
143
+ error: () => t("Validation.InvalidDate"),
144
+ })
145
+ .nullable()
146
+ .refine((value) => value !== null, required),
147
+ });
148
+
149
+ export type FeatureForm = z.input<typeof FeatureFormSchema>;
150
+ ```
151
+
152
+ ```tsx
153
+ // Inside Form.tsx: defaults typed FeatureForm, validators.onChange = FeatureFormSchema.
154
+ const { data: libraries } = useLiveQuery(librariesQueryOptions);
155
+
156
+ const pickerFields = (
157
+ <>
158
+ <form.AppField name="libraryId">
159
+ {(field) => (
160
+ <field.Autocomplete
161
+ options={libraries.map(({ id }) => id)}
162
+ getOptionLabel={(id) => libraries.find((library) => library.id === id)?.name ?? ""}
163
+ sx={{ width: 300 }}
164
+ textFieldProps={{ label: t("Feature.Library"), required: true }}
165
+ />
166
+ )}
167
+ </form.AppField>
168
+ <form.AppField name="dueAt">
169
+ {(field) => (
170
+ <field.DatePicker
171
+ label={t("Feature.DueAt")}
172
+ textFieldProps={{ required: true }}
173
+ sx={{ width: 200 }}
174
+ />
175
+ )}
176
+ </form.AppField>
177
+ </>
178
+ );
179
+
180
+ // create defaults { …, libraryId: null, dueAt: null }; edit { ...data, dueAt: dayjs(data.dueAt) };
181
+ // submit: handleOnSubmit(FeatureSchema.parse({ ...value, dueAt: value.dueAt?.toDate() }))
122
182
  ```