wcz-layout 10.1.2 → 10.1.7

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 (85) hide show
  1. package/dist/{AggregatedCell-C7nAQyMO.mjs → AggregatedCell-CqGptV6i.mjs} +199 -150
  2. package/dist/AggregatedCell-CqGptV6i.mjs.map +1 -0
  3. package/dist/Approval-DoD-GRRH.mjs.map +1 -1
  4. package/dist/DialogsContext-DLqA8RJ_.mjs.map +1 -1
  5. package/dist/Email-BzQQkbe9.mjs.map +1 -1
  6. package/dist/FileMeta-DDqUju1Y.mjs.map +1 -1
  7. package/dist/{LayoutTable-DX9IaO8V.d.mts → LayoutTable-CRo43iWr.d.mts} +7 -3
  8. package/dist/{RouterListItemButton-ULMlaQh6.mjs → RouterListItemButton-ke6iPKkL.mjs} +9 -9
  9. package/dist/RouterListItemButton-ke6iPKkL.mjs.map +1 -0
  10. package/dist/{approval-DiNOXd4B.mjs → approval-L09uPzTU.mjs} +2 -2
  11. package/dist/approval-L09uPzTU.mjs.map +1 -0
  12. package/dist/auth.d.mts +1 -0
  13. package/dist/auth.mjs +15 -12
  14. package/dist/auth.mjs.map +1 -1
  15. package/dist/components.d.mts +1 -1
  16. package/dist/components.mjs +594 -361
  17. package/dist/components.mjs.map +1 -1
  18. package/dist/{createApi-DGJJ4I_R.mjs → createApi-BhNkG4jz.mjs} +3 -3
  19. package/dist/createApi-BhNkG4jz.mjs.map +1 -0
  20. package/dist/data/client.mjs +3 -3
  21. package/dist/data/client.mjs.map +1 -1
  22. package/dist/data/server.mjs +4 -4
  23. package/dist/data/server.mjs.map +1 -1
  24. package/dist/{file-C14fhUeg.mjs → file-Chlljz3o.mjs} +4 -4
  25. package/dist/file-Chlljz3o.mjs.map +1 -0
  26. package/dist/{file-C5BOj1q8.mjs → file-Dl8JCcqy.mjs} +4 -4
  27. package/dist/file-Dl8JCcqy.mjs.map +1 -0
  28. package/dist/hooks.d.mts +2 -1
  29. package/dist/hooks.mjs +541 -591
  30. package/dist/hooks.mjs.map +1 -1
  31. package/dist/index.d.mts +9 -0
  32. package/dist/index.mjs +438 -428
  33. package/dist/index.mjs.map +1 -1
  34. package/dist/middleware.mjs +2 -2
  35. package/dist/middleware.mjs.map +1 -1
  36. package/dist/models.mjs.map +1 -1
  37. package/dist/{peoplesoft-BkJMCcHb.mjs → peoplesoft-BhintHQz.mjs} +3 -3
  38. package/dist/peoplesoft-BhintHQz.mjs.map +1 -0
  39. package/dist/{providers-DrairEO2.mjs → providers-BvuZWkpD.mjs} +2 -2
  40. package/dist/providers-BvuZWkpD.mjs.map +1 -0
  41. package/dist/{tokens-BLRreL1j.mjs → tokens-XuFhVbh5.mjs} +9 -6
  42. package/dist/tokens-XuFhVbh5.mjs.map +1 -0
  43. package/dist/{utils-BUpDoqme.mjs → utils-CaeVFWF-.mjs} +18 -7
  44. package/dist/utils-CaeVFWF-.mjs.map +1 -0
  45. package/dist/utils.mjs +1 -1
  46. package/dist/vite.mjs +11 -0
  47. package/dist/vite.mjs.map +1 -1
  48. package/package.json +131 -130
  49. package/skills/client-db/SKILL.md +136 -136
  50. package/skills/db-schema/SKILL.md +98 -98
  51. package/skills/dialogs/SKILL.md +74 -74
  52. package/skills/forms/SKILL.md +122 -122
  53. package/skills/general/SKILL.md +127 -127
  54. package/skills/general/references/exports.md +6 -1
  55. package/skills/migrations/SKILL.md +57 -57
  56. package/skills/migrations/versions/migrate-v10-to-v11.md +2 -1
  57. package/skills/migrations/versions/migrate-v9-to-v10.md +582 -582
  58. package/skills/routing/SKILL.md +87 -87
  59. package/skills/server-functions/SKILL.md +95 -95
  60. package/skills/services/SKILL.md +34 -34
  61. package/skills/services/docs/email.md +32 -32
  62. package/skills/services/docs/file.md +108 -108
  63. package/skills/services/docs/peoplesoft.md +114 -114
  64. package/skills/start/SKILL.md +52 -52
  65. package/skills/start/steps/01-git-setup.md +10 -10
  66. package/skills/start/steps/02-project-name-setup.md +19 -19
  67. package/skills/start/steps/03-apm-setup.md +97 -208
  68. package/skills/start/steps/04-wicop-setup.md +105 -105
  69. package/skills/start/steps/05-database-setup.md +52 -52
  70. package/skills/start/steps/06-entra-setup.md +96 -96
  71. package/skills/start/steps/07-vault-setup.md +115 -115
  72. package/skills/start/steps/08-generate-favicon.md +8 -8
  73. package/skills/start/steps/09-gitlab-ci.md +25 -25
  74. package/skills/start/steps/10-commit.md +15 -15
  75. package/skills/table/SKILL.md +266 -264
  76. package/dist/AggregatedCell-C7nAQyMO.mjs.map +0 -1
  77. package/dist/RouterListItemButton-ULMlaQh6.mjs.map +0 -1
  78. package/dist/approval-DiNOXd4B.mjs.map +0 -1
  79. package/dist/createApi-DGJJ4I_R.mjs.map +0 -1
  80. package/dist/file-C14fhUeg.mjs.map +0 -1
  81. package/dist/file-C5BOj1q8.mjs.map +0 -1
  82. package/dist/peoplesoft-BkJMCcHb.mjs.map +0 -1
  83. package/dist/providers-DrairEO2.mjs.map +0 -1
  84. package/dist/tokens-BLRreL1j.mjs.map +0 -1
  85. package/dist/utils-BUpDoqme.mjs.map +0 -1
@@ -1,98 +1,98 @@
1
- ---
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."
4
- metadata:
5
- type: convention
6
- library: wcz-layout
7
- ---
8
-
9
- # Database schema patterns
10
-
11
- ## Rules
12
-
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`.
25
-
26
- ## Examples
27
-
28
- ```ts
29
- // src/server/db/schemas/library.ts
30
- import { snakeCase, text, uuid } from "drizzle-orm/pg-core";
31
-
32
- export const libraryTable = snakeCase.table("libraries", {
33
- id: uuid().primaryKey(),
34
- name: text().notNull(),
35
- });
36
- ```
37
-
38
- ```ts
39
- // src/server/db/schemas/book.ts
40
- import { index, pgEnum, snakeCase, text, timestamp, uuid } from "drizzle-orm/pg-core";
41
- import { libraryTable } from "./library";
42
-
43
- export const bookStatusEnum = pgEnum("book_status", ["draft", "published"]);
44
-
45
- export const bookTable = snakeCase.table(
46
- "books",
47
- {
48
- id: uuid().primaryKey(),
49
- title: text().notNull(),
50
- status: bookStatusEnum().notNull().default("draft"),
51
- libraryId: uuid()
52
- .notNull()
53
- .references(() => libraryTable.id, { onDelete: "cascade" }),
54
- createdAt: timestamp({ withTimezone: true }).defaultNow().notNull(),
55
- },
56
- (table) => [index().on(table.libraryId)],
57
- );
58
- ```
59
-
60
- ```ts
61
- // src/server/db/schemas/relations.ts
62
- import { defineRelations } from "drizzle-orm";
63
- import { bookTable } from "./book";
64
- import { libraryTable } from "./library";
65
-
66
- export const relations = defineRelations(
67
- { libraryTable, bookTable },
68
- ({ one, many, libraryTable: library, bookTable: book }) => ({
69
- libraryTable: {
70
- books: many.bookTable(),
71
- },
72
- bookTable: {
73
- library: one.libraryTable({ from: book.libraryId, to: library.id }),
74
- },
75
- }),
76
- );
77
- ```
78
-
79
- ```ts
80
- // src/lib/schemas/<table>.ts
81
- import { createSelectSchema } from "drizzle-orm/zod";
82
- import { t } from "wcz-layout/utils";
83
- import type { z } from "zod";
84
- import { bookTable } from "~/server/db/schemas/book";
85
- import { PageSchema } from "./page";
86
-
87
- export const BookSchema = createSelectSchema(bookTable, {
88
- title: (schema) =>
89
- schema
90
- .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")),
95
- });
96
-
97
- export type Book = z.infer<typeof BookSchema>;
98
- ```
1
+ ---
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."
4
+ metadata:
5
+ type: convention
6
+ library: wcz-layout
7
+ ---
8
+
9
+ # Database schema patterns
10
+
11
+ ## Rules
12
+
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`.
25
+
26
+ ## Examples
27
+
28
+ ```ts
29
+ // src/server/db/schemas/library.ts
30
+ import { snakeCase, text, uuid } from "drizzle-orm/pg-core";
31
+
32
+ export const libraryTable = snakeCase.table("libraries", {
33
+ id: uuid().primaryKey(),
34
+ name: text().notNull(),
35
+ });
36
+ ```
37
+
38
+ ```ts
39
+ // src/server/db/schemas/book.ts
40
+ import { index, pgEnum, snakeCase, text, timestamp, uuid } from "drizzle-orm/pg-core";
41
+ import { libraryTable } from "./library";
42
+
43
+ export const bookStatusEnum = pgEnum("book_status", ["draft", "published"]);
44
+
45
+ export const bookTable = snakeCase.table(
46
+ "books",
47
+ {
48
+ id: uuid().primaryKey(),
49
+ title: text().notNull(),
50
+ status: bookStatusEnum().notNull().default("draft"),
51
+ libraryId: uuid()
52
+ .notNull()
53
+ .references(() => libraryTable.id, { onDelete: "cascade" }),
54
+ createdAt: timestamp({ withTimezone: true }).defaultNow().notNull(),
55
+ },
56
+ (table) => [index().on(table.libraryId)],
57
+ );
58
+ ```
59
+
60
+ ```ts
61
+ // src/server/db/schemas/relations.ts
62
+ import { defineRelations } from "drizzle-orm";
63
+ import { bookTable } from "./book";
64
+ import { libraryTable } from "./library";
65
+
66
+ export const relations = defineRelations(
67
+ { libraryTable, bookTable },
68
+ ({ one, many, libraryTable: library, bookTable: book }) => ({
69
+ libraryTable: {
70
+ books: many.bookTable(),
71
+ },
72
+ bookTable: {
73
+ library: one.libraryTable({ from: book.libraryId, to: library.id }),
74
+ },
75
+ }),
76
+ );
77
+ ```
78
+
79
+ ```ts
80
+ // src/lib/schemas/<table>.ts
81
+ import { createSelectSchema } from "drizzle-orm/zod";
82
+ import { t } from "wcz-layout/utils";
83
+ import type { z } from "zod";
84
+ import { bookTable } from "~/server/db/schemas/book";
85
+ import { PageSchema } from "./page";
86
+
87
+ export const BookSchema = createSelectSchema(bookTable, {
88
+ title: (schema) =>
89
+ schema
90
+ .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")),
95
+ });
96
+
97
+ export type Book = z.infer<typeof BookSchema>;
98
+ ```
@@ -1,74 +1,74 @@
1
- ---
2
- name: dialogs
3
- description: "Use for acknowledgement alerts, confirmation prompts, or custom MUI Dialogs opened through useDialogs."
4
- metadata:
5
- type: convention
6
- library: wcz-layout
7
- ---
8
-
9
- ## Rules
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`.
22
-
23
- ## Examples
24
-
25
- ```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"));
43
- }
44
- ```
45
-
46
- ```tsx
47
- // custom dialog that returns a result
48
- const { open } = useDialogs();
49
-
50
- const saved = await open(EditFeatureDialog, { id });
51
- if (saved) await features.utils.refetch({ throwOnError: true });
52
- ```
53
-
54
- ```tsx
55
- // custom dialog component
56
- interface Payload {
57
- id: string;
58
- }
59
-
60
- export const EditFeatureDialog = ({ payload, open, onClose }: DialogProps<Payload, boolean>) => {
61
- const { t } = useTranslation();
62
-
63
- return (
64
- <Dialog fullWidth open={open} onClose={() => onClose(false)}>
65
- <DialogTitle>{t("EditFeature")}</DialogTitle>
66
- <DialogContent>{payload.id}</DialogContent>
67
- <DialogActions>
68
- <Button onClick={() => onClose(false)}>{t("Cancel")}</Button>
69
- <Button onClick={() => onClose(true)}>{t("Save")}</Button>
70
- </DialogActions>
71
- </Dialog>
72
- );
73
- };
74
- ```
1
+ ---
2
+ name: dialogs
3
+ description: "Use for acknowledgement alerts, confirmation prompts, or custom MUI Dialogs opened through useDialogs."
4
+ metadata:
5
+ type: convention
6
+ library: wcz-layout
7
+ ---
8
+
9
+ ## Rules
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`.
22
+
23
+ ## Examples
24
+
25
+ ```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"));
43
+ }
44
+ ```
45
+
46
+ ```tsx
47
+ // custom dialog that returns a result
48
+ const { open } = useDialogs();
49
+
50
+ const saved = await open(EditFeatureDialog, { id });
51
+ if (saved) await features.utils.refetch({ throwOnError: true });
52
+ ```
53
+
54
+ ```tsx
55
+ // custom dialog component
56
+ interface Payload {
57
+ id: string;
58
+ }
59
+
60
+ export const EditFeatureDialog = ({ payload, open, onClose }: DialogProps<Payload, boolean>) => {
61
+ const { t } = useTranslation();
62
+
63
+ return (
64
+ <Dialog fullWidth open={open} onClose={() => onClose(false)}>
65
+ <DialogTitle>{t("EditFeature")}</DialogTitle>
66
+ <DialogContent>{payload.id}</DialogContent>
67
+ <DialogActions>
68
+ <Button onClick={() => onClose(false)}>{t("Cancel")}</Button>
69
+ <Button onClick={() => onClose(true)}>{t("Save")}</Button>
70
+ </DialogActions>
71
+ </Dialog>
72
+ );
73
+ };
74
+ ```
@@ -1,122 +1,122 @@
1
- ---
2
- name: forms
3
- description: "Use when building or changing forms, including fields, validation, submission, reset, date values, async initial values, or reusable subforms."
4
- metadata:
5
- type: convention
6
- library: wcz-layout
7
- ---
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.
14
-
15
- ## Rules
16
-
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>()`.
41
-
42
- ## Examples
43
-
44
- ```tsx
45
- // Form component
46
- interface FormProps {
47
- defaultValues: Feature;
48
- onSubmit: (value: Feature) => Promise<void>;
49
- }
50
-
51
- export const Form: FC<FormProps> = ({ defaultValues, onSubmit }) => {
52
- const { t } = useTranslation();
53
-
54
- const form = useLayoutForm({
55
- defaultValues,
56
- validators: { onChange: FeatureSchema },
57
- onSubmit: async ({ value, formApi }) => {
58
- await onSubmit(value);
59
- formApi.reset();
60
- },
61
- });
62
-
63
- return (
64
- <form
65
- onSubmit={async (event) => {
66
- event.preventDefault();
67
- event.stopPropagation();
68
- await form.handleSubmit();
69
- }}
70
- >
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")} />}
97
- </form.AppField>
98
-
99
- <form.AppForm>
100
- <form.SubmitButton variant="contained">{t("Submit")}</form.SubmitButton>
101
- </form.AppForm>
102
- </form>
103
- );
104
- };
105
- ```
106
-
107
- ```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
- />
122
- ```
1
+ ---
2
+ name: forms
3
+ description: "Use when building or changing forms, including fields, validation, submission, reset, date values, async initial values, or reusable subforms."
4
+ metadata:
5
+ type: convention
6
+ library: wcz-layout
7
+ ---
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.
14
+
15
+ ## Rules
16
+
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>()`.
41
+
42
+ ## Examples
43
+
44
+ ```tsx
45
+ // Form component
46
+ interface FormProps {
47
+ defaultValues: Feature;
48
+ onSubmit: (value: Feature) => Promise<void>;
49
+ }
50
+
51
+ export const Form: FC<FormProps> = ({ defaultValues, onSubmit }) => {
52
+ const { t } = useTranslation();
53
+
54
+ const form = useLayoutForm({
55
+ defaultValues,
56
+ validators: { onChange: FeatureSchema },
57
+ onSubmit: async ({ value, formApi }) => {
58
+ await onSubmit(value);
59
+ formApi.reset();
60
+ },
61
+ });
62
+
63
+ return (
64
+ <form
65
+ onSubmit={async (event) => {
66
+ event.preventDefault();
67
+ event.stopPropagation();
68
+ await form.handleSubmit();
69
+ }}
70
+ >
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")} />}
97
+ </form.AppField>
98
+
99
+ <form.AppForm>
100
+ <form.SubmitButton variant="contained">{t("Submit")}</form.SubmitButton>
101
+ </form.AppForm>
102
+ </form>
103
+ );
104
+ };
105
+ ```
106
+
107
+ ```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
+ />
122
+ ```