@k8ordo/form 2.3.1 → 4.0.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.
- package/README.md +10 -3
- package/dist/async-check.d.mts +2 -1
- package/dist/derive/attributes.mjs +14 -15
- package/dist/derive/form-fields.d.mts +8 -9
- package/dist/derive/form-fields.mjs +76 -21
- package/dist/derive/messages.d.mts +2 -2
- package/dist/derive/messages.mjs +2 -2
- package/dist/index.d.mts +5 -3
- package/dist/index.mjs +1 -1
- package/dist/parse/parse-form.d.mts +2 -2
- package/dist/parse/parse-form.mjs +9 -9
- package/dist/paths.d.mts +36 -21
- package/dist/rules/define-form.d.mts +1 -1
- package/dist/rules/rules.d.mts +15 -10
- package/dist/rules/rules.mjs +2 -9
- package/dist/schema/object-schema.d.mts +2 -24
- package/dist/schema/object-schema.mjs +1 -3
- package/dist/schema/walk.d.mts +5 -2
- package/dist/schema/walk.mjs +34 -22
- package/dist/server.d.mts +5 -4
- package/dist/server.mjs +3 -3
- package/dist/types.d.mts +88 -15
- package/dist/use-form.d.mts +33 -13
- package/dist/use-form.mjs +7 -5
- package/docs/GUIDE.md +261 -93
- package/docs/llms.txt +26 -9
- package/package.json +7 -7
package/docs/GUIDE.md
CHANGED
|
@@ -33,12 +33,16 @@ client useForm(fields, state) → attributes to spread, message to show
|
|
|
33
33
|
server parseForm(schema, formData) → typed data, or per-field errors
|
|
34
34
|
```
|
|
35
35
|
|
|
36
|
-
`formFields` runs on the server
|
|
37
|
-
result is JSON, so it crosses the RSC
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
36
|
+
`formFields` runs on the server, in the render of the Server Component that
|
|
37
|
+
hands its result to the form. Its result is JSON, so it crosses the RSC
|
|
38
|
+
boundary as props and zod never enters the client bundle. The messages are
|
|
39
|
+
read when it runs — zod's, and a rule's
|
|
40
|
+
[function message](#a-message-that-follows-the-request) — so a call in the
|
|
41
|
+
render words them for the request being answered (its locale, say, with
|
|
42
|
+
`@k8ordo/i18n`). Do not hoist it to module scope: that runs once, before any
|
|
43
|
+
request, and every visitor would get the messages of whichever locale was
|
|
44
|
+
current then. Deriving is a walk over the schema, cheap enough to repeat on
|
|
45
|
+
every render.
|
|
42
46
|
|
|
43
47
|
## Writing a form
|
|
44
48
|
|
|
@@ -74,7 +78,7 @@ Each leaf derives the control that submits what it validates:
|
|
|
74
78
|
|
|
75
79
|
| Schema | `input` |
|
|
76
80
|
| ------------------------------------------------ | ------------------------------------------------------------------------------------------------------ |
|
|
77
|
-
| `z.string()` | `type
|
|
81
|
+
| `z.string()` | no `type`: a plain text input, the browser's default |
|
|
78
82
|
| `z.email()` / `z.url()` | `type="email"` / `type="url"` |
|
|
79
83
|
| `z.iso.date()` / `z.iso.time()` | `type="date"` / `type="time"` |
|
|
80
84
|
| `z.iso.datetime({ local: true })` | `type="datetime-local"` |
|
|
@@ -85,14 +89,31 @@ Each leaf derives the control that submits what it validates:
|
|
|
85
89
|
| a password ([below](#what-it-guarantees)) | `type="password"` |
|
|
86
90
|
| `z.enum([…])` | no `type`: spread it onto a `<select>`, not a radio ([Radio groups](#radio-groups)) |
|
|
87
91
|
| `z.array(z.enum([…]))` | no `type`: one checkbox per option ([Checkbox groups](#checkbox-groups)) |
|
|
88
|
-
| anything else (`z.uuid()`, `z.coerce.date()`, …) | `type
|
|
92
|
+
| anything else (`z.uuid()`, `z.coerce.date()`, …) | no `type` |
|
|
93
|
+
|
|
94
|
+
`form.field()` types each `input` by the control its schema derives, so a
|
|
95
|
+
spread reaches a component that takes only what that control has:
|
|
96
|
+
|
|
97
|
+
| Schema | `input` type |
|
|
98
|
+
| --------------------------------------------------------------------------- | --------------------- |
|
|
99
|
+
| `z.coerce.number()` | `NumberInput` |
|
|
100
|
+
| `z.boolean()` | `CheckboxInput` |
|
|
101
|
+
| `z.stringbool()` | `StringCheckboxInput` |
|
|
102
|
+
| `z.file()` | `FileInput` |
|
|
103
|
+
| `z.array(z.enum([…]))` | `CheckboxGroupInput` |
|
|
104
|
+
| a string, `z.enum([…])`, and anything behind `.nullable()`, a union, a pipe | `FieldInput` |
|
|
105
|
+
|
|
106
|
+
`NumberInput` has numeric `min` and `max` and always a `step`; `FileInput` has
|
|
107
|
+
no `defaultValue`, since no browser lets a value be put back into a file
|
|
108
|
+
control. `.optional()`, `.default()` and the other wrappers keep the leaf's
|
|
109
|
+
control and its type; `.nullable()` does not — it turns the leaf into a union,
|
|
110
|
+
which derives a bare text input — so it falls to `FieldInput`, the type that
|
|
111
|
+
covers every control.
|
|
89
112
|
|
|
90
113
|
```tsx
|
|
91
114
|
// src/routes/talks/new/page.tsx — Server Component
|
|
92
|
-
const talkFields = formFields(talkSchema); // module scope: derived once
|
|
93
|
-
|
|
94
115
|
export default function Page() {
|
|
95
|
-
return <TalkForm action={createTalk} fields={
|
|
116
|
+
return <TalkForm action={createTalk} fields={formFields(talkSchema)} />;
|
|
96
117
|
}
|
|
97
118
|
```
|
|
98
119
|
|
|
@@ -103,6 +124,15 @@ report travel together.
|
|
|
103
124
|
// src/components/talk-form.tsx
|
|
104
125
|
'use client';
|
|
105
126
|
|
|
127
|
+
import type { FormFields, FormState } from '@k8ordo/form';
|
|
128
|
+
|
|
129
|
+
import type { talkSchema } from '../lib/schema';
|
|
130
|
+
|
|
131
|
+
type TalkFormProps = {
|
|
132
|
+
action: (state: FormState, formData: FormData) => Promise<FormState>;
|
|
133
|
+
fields: FormFields<typeof talkSchema>;
|
|
134
|
+
};
|
|
135
|
+
|
|
106
136
|
export const TalkForm = ({ action, fields }: TalkFormProps) => {
|
|
107
137
|
const [state, formAction] = useActionState(action, {});
|
|
108
138
|
const form = useForm(fields, state);
|
|
@@ -117,6 +147,27 @@ export const TalkForm = ({ action, fields }: TalkFormProps) => {
|
|
|
117
147
|
};
|
|
118
148
|
```
|
|
119
149
|
|
|
150
|
+
`FormFields<typeof talkSchema>` is the type `formFields(talkSchema)` returns,
|
|
151
|
+
so the prop is typed from the schema itself: the paths `form.field()` accepts
|
|
152
|
+
and the type of each field's `input` follow it. The import is type-only, so
|
|
153
|
+
zod stays out of the client bundle. A `defineForm` definition is named the
|
|
154
|
+
same way — `FormFields<typeof signup>` — and `UseFormReturn<typeof
|
|
155
|
+
talkSchema>` names what `useForm` returns, for a hook that takes the whole
|
|
156
|
+
form. A component that draws one field takes that field's `FieldView`:
|
|
157
|
+
|
|
158
|
+
```tsx
|
|
159
|
+
const TitleInput = ({ field }: { field: FieldView }) => (
|
|
160
|
+
<input {...field.input} />
|
|
161
|
+
);
|
|
162
|
+
|
|
163
|
+
<TitleInput field={form.field('title')} />;
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
Code generic over the form — a wrapper that owns the `<form>` element, say —
|
|
167
|
+
takes the schema as a type parameter: `<Source extends ObjectSchema |
|
|
168
|
+
FormDefinition>`, then `FormFields<Source>` and `UseFormReturn<Source>`. Both
|
|
169
|
+
constraint types are exported from either entry.
|
|
170
|
+
|
|
120
171
|
`form.props` attaches to the `<form>` and nowhere else. There is no per-field
|
|
121
172
|
registration to forget. Its `onSubmit` checks the form
|
|
122
173
|
([below](#what-it-guarantees)) — an `onSubmit` of your own written after the
|
|
@@ -182,13 +233,74 @@ Focus carries the message rather than a live region because focus moves on
|
|
|
182
233
|
every response: a live region already holding the same text announces nothing
|
|
183
234
|
when the same failure comes back.
|
|
184
235
|
|
|
236
|
+
## Telling the person it worked
|
|
237
|
+
|
|
238
|
+
When the action does not redirect, say so on the page, from the state the
|
|
239
|
+
action returns. `FormState` has no success flag of its own; extend it with
|
|
240
|
+
one, and keep handing the Server Action to `useActionState` as it is:
|
|
241
|
+
|
|
242
|
+
```ts
|
|
243
|
+
// src/lib/actions.ts
|
|
244
|
+
'use server';
|
|
245
|
+
|
|
246
|
+
export type ContactState = FormState & { accepted?: true };
|
|
247
|
+
|
|
248
|
+
export async function sendContact(
|
|
249
|
+
_prev: ContactState,
|
|
250
|
+
formData: FormData,
|
|
251
|
+
): Promise<ContactState> {
|
|
252
|
+
const parsed = parseForm(contactSchema, formData);
|
|
253
|
+
if (!parsed.success) return parsed.state;
|
|
254
|
+
|
|
255
|
+
const delivered = await deliver(parsed.data);
|
|
256
|
+
if (!delivered) {
|
|
257
|
+
return { ...parsed.state, formError: '送信できませんでした' };
|
|
258
|
+
}
|
|
259
|
+
return { accepted: true };
|
|
260
|
+
}
|
|
261
|
+
```
|
|
262
|
+
|
|
263
|
+
```tsx
|
|
264
|
+
const [state, formAction] = useActionState(sendContact, {});
|
|
265
|
+
const form = useForm(fields, state);
|
|
266
|
+
|
|
267
|
+
<form {...form.props} action={formAction}>
|
|
268
|
+
{state.accepted === true && <p role="status">送信しました</p>}
|
|
269
|
+
{/* … */}
|
|
270
|
+
</form>;
|
|
271
|
+
```
|
|
272
|
+
|
|
273
|
+
The message is part of the page the action's result renders, so it shows
|
|
274
|
+
without JavaScript too, and React's reset after the action empties the
|
|
275
|
+
fields. A failure found after the schema passed — the mail server is down,
|
|
276
|
+
the slot was taken — goes back as `{ ...parsed.state, formError }`: the
|
|
277
|
+
submitted values and the `token` stay, so the fields keep what was typed and
|
|
278
|
+
focus moves to the form-level message. With `@k8ordo/ui`, an inline
|
|
279
|
+
`<Alert message="…" tone="success" />` draws the success the same way.
|
|
280
|
+
|
|
281
|
+
A toast is the other choice, and it needs JavaScript: it is opened from a
|
|
282
|
+
client function that wraps the action and reads its result. Handing that
|
|
283
|
+
wrapper to `useActionState` makes the form's action a client function, so
|
|
284
|
+
without JavaScript the form has nothing to submit to. Choose it only when the
|
|
285
|
+
page already needs JavaScript to work.
|
|
286
|
+
|
|
287
|
+
```tsx
|
|
288
|
+
const { open } = useToast(); // @k8ordo/ui
|
|
289
|
+
const [state, formAction] = useActionState(
|
|
290
|
+
async (previous: ContactState, formData: FormData) => {
|
|
291
|
+
const next = await sendContact(previous, formData);
|
|
292
|
+
if (next.accepted === true) open('success', '送信しました');
|
|
293
|
+
return next;
|
|
294
|
+
},
|
|
295
|
+
{},
|
|
296
|
+
);
|
|
297
|
+
```
|
|
298
|
+
|
|
185
299
|
## What it guarantees
|
|
186
300
|
|
|
187
301
|
**The wording cannot drift.** Client messages are obtained by running the
|
|
188
302
|
schema against a probe value, so the text shown next to the input is the text
|
|
189
|
-
zod itself produces. A custom `min(1, '…')` reaches both sides.
|
|
190
|
-
exception is a range message from `@k8ordo/ui`'s `NumberField` (see
|
|
191
|
-
[Working with @k8ordo/ui](#working-with-k8ordoui)).
|
|
303
|
+
zod itself produces. A custom `min(1, '…')` reaches both sides.
|
|
192
304
|
|
|
193
305
|
**`required` means the same thing on both sides.** JSON Schema's `required`
|
|
194
306
|
means "the key is present", but a form always submits something for every
|
|
@@ -211,8 +323,8 @@ float, a regex whose flags or anchoring the `pattern` attribute would silently
|
|
|
211
323
|
reinterpret, several regexes on one string (the attribute holds one), a regex on
|
|
212
324
|
a control that ignores `pattern` such as `type="date"`, a `.mime()` that
|
|
213
325
|
`accept` only suggests to the file picker, a `z.iso.datetime()` no
|
|
214
|
-
`datetime-local` control can ever satisfy,
|
|
215
|
-
a leaf whose constraints could not be read at all because a `.transform()` or a
|
|
326
|
+
`datetime-local` control can ever satisfy, the count of a checkbox group inside
|
|
327
|
+
repeated rows, a leaf whose constraints could not be read at all because a `.transform()` or a
|
|
216
328
|
`z.custom()` left nothing to read — are returned in `dropped`. They still run
|
|
217
329
|
on the server; you are told they do not run on the client. Outside production
|
|
218
330
|
`formFields` also logs the list once per schema with `console.warn`, so it is
|
|
@@ -403,15 +515,12 @@ accepts it, and a bare `z.stringbool()` makes the box `required`.
|
|
|
403
515
|
`.default(true)` is refused at derive time — nothing would read as `true`, so
|
|
404
516
|
unchecking the box could never submit `false`.
|
|
405
517
|
|
|
406
|
-
Only these fields carry `value` in their type. `
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
takes the derived fields, and the box still submits its `value`, but
|
|
413
|
-
`input.value` no longer compiles. The same holds for a box inside repeated
|
|
414
|
-
rows, which `row.field()` never types with `value`.
|
|
518
|
+
Only these fields carry `value` in their type. `field()` reads which ones they
|
|
519
|
+
are from the schema's type, and types `input` by the control each field
|
|
520
|
+
derives ([the table above](#writing-a-form)): `StringCheckboxInput` is the one
|
|
521
|
+
input type with a `value`, so every other field spreads onto a component that
|
|
522
|
+
takes `value` only when it is controlled. A box inside repeated rows is typed
|
|
523
|
+
the same way by `row.field(key)`.
|
|
415
524
|
|
|
416
525
|
## Checkbox groups
|
|
417
526
|
|
|
@@ -426,9 +535,7 @@ const tags = form.field('tags');
|
|
|
426
535
|
{
|
|
427
536
|
['a', 'b', 'c'].map((option) => (
|
|
428
537
|
<input
|
|
429
|
-
defaultChecked={
|
|
430
|
-
Array.isArray(state.values?.tags) && state.values.tags.includes(option)
|
|
431
|
-
}
|
|
538
|
+
defaultChecked={tags.input.defaultValue?.includes(option)}
|
|
432
539
|
key={option}
|
|
433
540
|
name={tags.input.name}
|
|
434
541
|
type="checkbox"
|
|
@@ -440,11 +547,27 @@ const tags = form.field('tags');
|
|
|
440
547
|
|
|
441
548
|
`parseForm` reads every checked box under the shared name — none checked is
|
|
442
549
|
`[]`, never a wiring error. The `.min(2)` cannot become an HTML attribute (on
|
|
443
|
-
a group, `required` would mean "check every box"), so
|
|
444
|
-
|
|
445
|
-
browser
|
|
446
|
-
|
|
447
|
-
`
|
|
550
|
+
a group, `required` would mean "check every box"), so `formFields` derives
|
|
551
|
+
the array's `.min()` and `.max()` as [rules](#checks-html-has-no-attribute-for)
|
|
552
|
+
the browser runs on the group, worded by zod — read on every call, so the
|
|
553
|
+
wording follows the locale like the rest of zod's. A bound zod gives no
|
|
554
|
+
message for (a `.refine()` with `abort` ahead of it, say) is listed in
|
|
555
|
+
`dropped` instead, and a `.max()` no selection can exceed derives no rule.
|
|
556
|
+
`tags.required` is `true`
|
|
557
|
+
while `.min()` asks for at least one box, for the label's required marker;
|
|
558
|
+
`tags.input` carries no `required`. Inside repeated rows a group has no
|
|
559
|
+
fixed name for a rule to target, so its count runs on the server only and is
|
|
560
|
+
listed in `dropped`.
|
|
561
|
+
|
|
562
|
+
After a submission `tags.input.defaultValue` holds what was checked as an
|
|
563
|
+
array — `['a']` for one box, `[]` for none — typed `string[]`
|
|
564
|
+
(`CheckboxGroupInput`). A component that takes the checked options as its
|
|
565
|
+
`defaultValue` — a `<select multiple>`, or `@k8ordo/ui`'s `CheckboxGroup`,
|
|
566
|
+
`CheckboxCard` and `Autocomplete` — takes the spread as it is. A hand-written
|
|
567
|
+
box takes the `name` and reads `defaultChecked` from the array, as above: a
|
|
568
|
+
spread would put the whole array on every box. The same holds for a group
|
|
569
|
+
inside repeated rows, which `row.field(key)` types as `CheckboxGroupInput`
|
|
570
|
+
too.
|
|
448
571
|
|
|
449
572
|
## Files
|
|
450
573
|
|
|
@@ -471,16 +594,40 @@ form.field('titel'); // error: not a field in the schema
|
|
|
471
594
|
form.field('items'); // error: an array of objects, reached through array()
|
|
472
595
|
form.array('user'); // error: an object, not an array
|
|
473
596
|
form.array('tags'); // error: a checkbox group is a field
|
|
597
|
+
row.field('nmae'); // error: not a field of the row
|
|
474
598
|
defineForm(schema, [sameAs('confrim', 'password', '…')]); // error: typo
|
|
475
599
|
```
|
|
476
600
|
|
|
477
|
-
A row's `row.field(key)`
|
|
478
|
-
|
|
601
|
+
A row's `row.field(key)` takes the path within one item and types its `input`
|
|
602
|
+
by that key, the way `form.field()` does by path: in a row of a string and a
|
|
603
|
+
number, `row.field('name').input` is a `FieldInput` and
|
|
604
|
+
`row.field('quantity').input` a `NumberInput`. The row of an array of scalars
|
|
605
|
+
is a single field under `''`, so its key is left out: `row.field()`.
|
|
606
|
+
|
|
607
|
+
A component that draws a whole row takes its `RowView`, named by the schema
|
|
608
|
+
(or the `defineForm` definition) and the array's path, the way `FormFields`
|
|
609
|
+
is named by the schema. The keys `row.field()` accepts follow from those two,
|
|
610
|
+
so `RowView` without them is a type error. `ArrayView` and `DerivedArray`
|
|
611
|
+
are named the same way.
|
|
612
|
+
|
|
613
|
+
```tsx
|
|
614
|
+
import type { RowView } from '@k8ordo/form';
|
|
615
|
+
|
|
616
|
+
import type { orderSchema } from '../lib/schema';
|
|
617
|
+
|
|
618
|
+
const ItemRow = ({ row }: { row: RowView<typeof orderSchema, 'items'> }) => (
|
|
619
|
+
<input {...row.field('quantity').input} />
|
|
620
|
+
);
|
|
621
|
+
|
|
622
|
+
{
|
|
623
|
+
form.array('items').rows.map((row) => <ItemRow key={row.key} row={row} />);
|
|
624
|
+
}
|
|
625
|
+
```
|
|
479
626
|
|
|
480
627
|
## Checks HTML has no attribute for
|
|
481
628
|
|
|
482
|
-
Password confirmation, "
|
|
483
|
-
|
|
629
|
+
Password confirmation, "required only when rejected" — neither maps to a
|
|
630
|
+
constraint attribute, and a `.refine()` cannot cross to
|
|
484
631
|
the client because it is a function. Declare them next to the schema instead:
|
|
485
632
|
|
|
486
633
|
```ts
|
|
@@ -504,10 +651,13 @@ indistinguishable from a built-in check — `:user-invalid` matches and the
|
|
|
504
651
|
message arrives through the same path as every other one. When several rules
|
|
505
652
|
break the same field, both sides show the one declared first.
|
|
506
653
|
|
|
507
|
-
Available: `sameAs(field, other, message)
|
|
508
|
-
|
|
654
|
+
Available: `sameAs(field, other, message)` and
|
|
655
|
+
`requiredWhen(field, when, equals, message)` —
|
|
509
656
|
`requiredWhen('reason', 'status', 'rejected', '…')` requires `reason` while
|
|
510
|
-
`status` is `'rejected'`.
|
|
657
|
+
`status` is `'rejected'`. How many boxes of a checkbox group may be checked
|
|
658
|
+
is not a rule to declare: it is the array's `.min()` / `.max()`, which
|
|
659
|
+
`formFields` turns into rules of its own, after the declared ones
|
|
660
|
+
([Checkbox groups](#checkbox-groups)). Anything else stays a `.refine()` and runs on the
|
|
511
661
|
server only. A `refine` on the schema as a whole is listed in `dropped`; one on
|
|
512
662
|
a single field, a nested object, or a row is not yet.
|
|
513
663
|
|
|
@@ -523,16 +673,20 @@ reads it:
|
|
|
523
673
|
|
|
524
674
|
```ts
|
|
525
675
|
// src/lib/signup-form.ts
|
|
526
|
-
import {
|
|
676
|
+
import { companyRequired, mismatch } from '../messages/signup'; // @k8ordo/i18n
|
|
527
677
|
|
|
528
678
|
export const signup = defineForm(schema, [
|
|
529
679
|
sameAs('confirm', 'password', mismatch),
|
|
530
|
-
|
|
680
|
+
requiredWhen('company', 'plan', 'business', companyRequired),
|
|
531
681
|
]);
|
|
532
682
|
```
|
|
533
683
|
|
|
534
|
-
|
|
535
|
-
|
|
684
|
+
The definition stays at module scope; `formFields(signup)` is called in the
|
|
685
|
+
render, as everywhere, so the rules come out worded for that request. zod's
|
|
686
|
+
own wording, for a check written without a message, follows the request once
|
|
687
|
+
its configuration reads the locale; `@k8ordo/i18n`'s guide
|
|
688
|
+
(`node_modules/@k8ordo/i18n/docs/GUIDE.md`, the `@k8ordo/form` item of
|
|
689
|
+
"Alongside the rest of k8ordo") shows the module that does it.
|
|
536
690
|
|
|
537
691
|
## Asking the server about one field
|
|
538
692
|
|
|
@@ -650,96 +804,110 @@ request — which is the correct behaviour, not a broken one.
|
|
|
650
804
|
`@k8ordo/form` does not depend on `@k8ordo/ui`; the fields in `@k8ordo/ui`
|
|
651
805
|
take what `formFields` derives as it is. Spread `input` onto the field after
|
|
652
806
|
`FormControl`'s props. `FormControl` gets only what it uses — the label, the
|
|
653
|
-
error, `
|
|
654
|
-
|
|
807
|
+
error, `required` — and generates the `id` and `aria-*` links itself. A
|
|
808
|
+
non-empty `error` is what marks the field invalid, so `invalid` is not passed.
|
|
655
809
|
|
|
656
810
|
```tsx
|
|
657
811
|
const title = form.field('title');
|
|
658
812
|
|
|
659
813
|
<FormControl
|
|
660
814
|
errorText={title.error}
|
|
661
|
-
invalid={title.invalid}
|
|
662
815
|
label="タイトル"
|
|
663
816
|
required={title.required}
|
|
664
817
|
renderInput={(props) => <TextField {...props} {...title.input} />}
|
|
665
818
|
/>;
|
|
666
819
|
```
|
|
667
820
|
|
|
668
|
-
Nothing in `input` has to be taken out first
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
821
|
+
Nothing in `input` has to be taken out first. `formFields` writes only
|
|
822
|
+
attributes the native element takes — no `type` for a plain text input, `min`
|
|
823
|
+
and `max` as numbers — so `TextField` renders the date and time types as well
|
|
824
|
+
as the text ones, `PasswordInput` keeps its show/hide toggle under a spread
|
|
825
|
+
`type`, a plain string spreads onto `Textarea` as it is, and `NumberField` and
|
|
826
|
+
`Slider` take `step="any"` and the echoed `defaultValue`, which is a string
|
|
827
|
+
whichever field it belongs to.
|
|
673
828
|
Uncontrolled fields keep their value in the DOM, so a reset — React's after
|
|
674
829
|
each action included — restores the echo, `isDirty` reads them, and a value a
|
|
675
830
|
component changes in code — a stepper, a chosen option, a removed file —
|
|
676
831
|
arrives as an `input` event, the way typing does.
|
|
677
832
|
|
|
678
|
-
| Schema
|
|
679
|
-
|
|
|
680
|
-
| `z.string()
|
|
681
|
-
|
|
|
682
|
-
|
|
|
683
|
-
| `z.
|
|
684
|
-
| `z.
|
|
685
|
-
| `z.
|
|
686
|
-
| `z.
|
|
833
|
+
| Schema | Component | What to pass besides `{...props} {...input}` |
|
|
834
|
+
| -------------------------------------------------- | ----------------------------------------------- | ---------------------------------------------------------------------------------- |
|
|
835
|
+
| `z.string()` | `TextField`, `Textarea` | — |
|
|
836
|
+
| `z.email()`, `z.url()`, `z.iso.*()` | `TextField` | — |
|
|
837
|
+
| a password | `PasswordInput` | — |
|
|
838
|
+
| `z.coerce.number()` | `NumberField`, `Slider` | — |
|
|
839
|
+
| `z.enum([…])` | `Select`, `Radio`, `RadioCard` | `options`; `labelAs="group"` on `FormControl` for radios |
|
|
840
|
+
| `z.boolean()`, `z.literal(true)`, `z.stringbool()` | `Checkbox`, `Switch` | `label` and `errorText`; no `FormControl`, so no `{...props}` |
|
|
841
|
+
| `z.array(z.enum([…]))` | `CheckboxGroup`, `CheckboxCard`, `Autocomplete` | `options`; `labelAs="group"` on `FormControl` for boxes |
|
|
842
|
+
| `z.file()` | `FileField.Root` | a `FileField.Trigger` and `FileField.ItemList`; `labelAs="group"` on `FormControl` |
|
|
843
|
+
|
|
844
|
+
**A group takes its name from `FormControl`.** `Radio`, `RadioCard`,
|
|
845
|
+
`CheckboxGroup` and `CheckboxCard` are a group each, so `labelAs="group"`
|
|
846
|
+
draws the label as the heading the group reads its name from, the required
|
|
847
|
+
mark included. On a checkbox group, `required={tags.required}` shows only as
|
|
848
|
+
that mark: `FormControl` passes it on, and `CheckboxGroup` and `CheckboxCard`
|
|
849
|
+
write it to no element — a `<fieldset>` takes no `required`, and a box with
|
|
850
|
+
one would have to be checked itself — while the count rule does the checking.
|
|
851
|
+
`FileField` takes `'group'` as well: what a person presses is its trigger, a
|
|
852
|
+
button that reads its name from the heading and cannot take `required`, so
|
|
853
|
+
the mark there is what says a file is required. `Autocomplete` keeps the
|
|
854
|
+
default, a `<label>` for its text input.
|
|
687
855
|
|
|
688
856
|
**Radios take the spread.** The advice under [Radio groups](#radio-groups) is
|
|
689
857
|
about a hand-written `<input type="radio">`. `Radio` and `RadioCard` read an
|
|
690
858
|
enum's `input` the other way round: `defaultValue` is the selected option and
|
|
691
859
|
`required` reaches every radio.
|
|
692
860
|
|
|
693
|
-
**A
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
custom `truthy`, and the URL state writes, do not share. Render a plain
|
|
697
|
-
`<input {...field.input} />` there.
|
|
861
|
+
**A single box draws its own message.** `Checkbox` and `Switch` carry their
|
|
862
|
+
own label, so they are not wrapped in `FormControl`. `errorText` draws the
|
|
863
|
+
field's error under the box and describes the input with it:
|
|
698
864
|
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
865
|
+
```tsx
|
|
866
|
+
const agree = form.field('agree');
|
|
867
|
+
|
|
868
|
+
<Checkbox {...agree.input} errorText={agree.error} label="規約に同意する" />;
|
|
869
|
+
```
|
|
702
870
|
|
|
703
|
-
|
|
704
|
-
|
|
871
|
+
The spread `value` of a `z.stringbool()` box lands on `Checkbox`'s and
|
|
872
|
+
`Switch`'s `value`, the string a checked box submits, so the box submits the
|
|
873
|
+
schema's own `true` ([Checkboxes that submit a string](#checkboxes-that-submit-a-string)).
|
|
874
|
+
|
|
875
|
+
**A `Select` needs a `placeholder` for `required` to mean anything.** A
|
|
876
|
+
`<select>` without an empty option always has a choice selected; `placeholder`
|
|
877
|
+
puts one first, with the value `''`, which `parseForm` reads as no choice — a
|
|
878
|
+
required enum reports it as missing, an optional one parses to `undefined`.
|
|
879
|
+
|
|
880
|
+
**A checkbox group echoes as an array.** `input.defaultValue` is what was
|
|
881
|
+
checked, so the group components take the spread with nothing added:
|
|
705
882
|
|
|
706
883
|
```tsx
|
|
707
884
|
const tags = form.field('tags');
|
|
708
|
-
const checked = state.values?.tags;
|
|
709
885
|
|
|
710
886
|
<FormControl
|
|
711
887
|
errorText={tags.error}
|
|
712
|
-
invalid={tags.invalid}
|
|
713
888
|
label="タグ"
|
|
714
|
-
labelAs="
|
|
889
|
+
labelAs="group"
|
|
715
890
|
renderInput={(props) => (
|
|
716
|
-
<CheckboxCard
|
|
717
|
-
{...props}
|
|
718
|
-
{...tags.input}
|
|
719
|
-
defaultValue={Array.isArray(checked) ? checked : []}
|
|
720
|
-
options={options}
|
|
721
|
-
/>
|
|
891
|
+
<CheckboxCard {...props} {...tags.input} options={options} />
|
|
722
892
|
)}
|
|
723
893
|
/>;
|
|
724
894
|
```
|
|
725
895
|
|
|
726
|
-
|
|
896
|
+
A group's count reaches `Autocomplete` as well as the checkboxes: it submits
|
|
727
897
|
through a hidden `<select multiple>` that is present even with nothing
|
|
728
898
|
selected, so the rule has an element to mark, and focus sent to it after a
|
|
729
899
|
failure goes on to the text input.
|
|
730
900
|
|
|
731
|
-
**`NumberField`
|
|
732
|
-
format and step the value, and the browser does not check `min` and `max`
|
|
733
|
-
a text input. `NumberField`
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
`
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
a `TextField` given the derived `type="number"` keeps the browser's own
|
|
742
|
-
check, and its wording.
|
|
901
|
+
**`NumberField` keeps the value in range.** It renders `type="text"` so it
|
|
902
|
+
can format and step the value, and the browser does not check `min` and `max`
|
|
903
|
+
on a text input. `NumberField` clamps the value into range instead, when the
|
|
904
|
+
field is left and when Enter is pressed in it, so a form submitted with Enter
|
|
905
|
+
sends the clamped value and no range message is ever shown. `.int()` and
|
|
906
|
+
`.multipleOf()` set the precision the field rounds to; a plain
|
|
907
|
+
`z.coerce.number()` derives `step="any"`, which is not rounded. Without
|
|
908
|
+
JavaScript nothing checks the range before the server does, and the server
|
|
909
|
+
answers with zod's message; a `TextField` given the derived `type="number"`
|
|
910
|
+
keeps the browser's own check, and its wording.
|
|
743
911
|
|
|
744
912
|
**A `Textarea` has no `pattern`.** A regex on a field drawn as a `Textarea`
|
|
745
913
|
reaches the markup, but a `<textarea>` ignores it: the check runs on the server
|
package/docs/llms.txt
CHANGED
|
@@ -13,7 +13,8 @@ When installed via npm, these docs live under `node_modules/@k8ordo/form/docs/`.
|
|
|
13
13
|
## Guide
|
|
14
14
|
|
|
15
15
|
- [Design Guide](GUIDE.md): the server/client split, writing a form end to end,
|
|
16
|
-
|
|
16
|
+
telling the person a submission worked (an inline message that works
|
|
17
|
+
without JavaScript, or a toast that needs it), what the package guarantees, what it does not do yet, and how it pairs with
|
|
17
18
|
`@k8ordo/ui` without depending on it.
|
|
18
19
|
|
|
19
20
|
## Not supported
|
|
@@ -52,11 +53,22 @@ row. Rules cannot target fields inside repeated rows.
|
|
|
52
53
|
per-field checks and `HiddenValue` for components that render no input of
|
|
53
54
|
their own. The types
|
|
54
55
|
of the `formFields` result (`FormFields`, `DerivedField`, `DerivedArray`,
|
|
55
|
-
`DroppedCheck`, `
|
|
56
|
-
|
|
56
|
+
`DroppedCheck`, `ValidityFlag`, `Rule`, `DerivedRule`, `RuleMessage`, and
|
|
57
|
+
the input types `field()` gives per control: `NumberInput`, `CheckboxInput`,
|
|
58
|
+
`StringCheckboxInput`, `FileInput`, `CheckboxGroupInput` — whose
|
|
59
|
+
`defaultValue` is the echoed array of checked options — and `FieldInput`
|
|
60
|
+
for the rest) are
|
|
61
|
+
exported here as
|
|
57
62
|
well, since the result crosses to the client as a prop, and so are
|
|
58
63
|
`FormState` and the return types (`UseFormReturn`, `FieldView`, `ArrayView`,
|
|
59
|
-
`RowView`, `FormErrorView`, `AsyncCheck`).
|
|
64
|
+
`RowView`, `FormErrorView`, `AsyncCheck`). `FormFields` and `UseFormReturn`
|
|
65
|
+
take one type argument, the schema or the `defineForm` definition
|
|
66
|
+
(`fields: FormFields<typeof talkSchema>`, with the schema imported as a
|
|
67
|
+
type), and the paths and each field's `input` type follow it; `ArrayView`,
|
|
68
|
+
`RowView` and `DerivedArray` take the same plus the array's path
|
|
69
|
+
(`row: RowView<typeof orderSchema, 'items'>` in a component that draws a
|
|
70
|
+
whole row); `ObjectSchema` and `FormDefinition` are exported for code
|
|
71
|
+
generic over the form.
|
|
60
72
|
- `@k8ordo/form/server` — server. `formFields(schemaOrDefinition)` derives
|
|
61
73
|
serializable fields plus a `dropped` list of checks HTML cannot express
|
|
62
74
|
(outside production the list is also logged once per schema with
|
|
@@ -71,14 +83,19 @@ row. Rules cannot target fields inside repeated rows.
|
|
|
71
83
|
which, checked, submits the `value` derived from the schema's own spelling of
|
|
72
84
|
`true`, the same string `@k8ordo/state` writes into a URL — so `z.coerce.number()` cannot read a
|
|
73
85
|
blank field as 0 and `z.enum([…]).optional()` can be left empty. A checkbox
|
|
74
|
-
group always echoes as an array
|
|
86
|
+
group always echoes as an array, which `field()` puts on the group's
|
|
87
|
+
`input.defaultValue`.
|
|
75
88
|
`defineForm(schema, rules)` attaches cross-field rules (`sameAs`,
|
|
76
|
-
`
|
|
89
|
+
`requiredWhen`) typed against the schema's paths, and `formFields` derives a
|
|
90
|
+
checkbox group's `.min()` / `.max()` as rules of its own, in zod's wording;
|
|
91
|
+
a rule's
|
|
77
92
|
message is a string or a function called when the rule is reported
|
|
78
93
|
(`formFields` calls it while deriving, so a rule crosses to the client as a
|
|
79
94
|
`DerivedRule` with the text in it; `parseForm` calls it when the rule
|
|
80
95
|
breaks), which keeps a localized definition at module scope. Types:
|
|
81
|
-
`ParseResult`, `FormDefinition`, `
|
|
96
|
+
`ParseResult`, `FormDefinition`, `ObjectSchema`, `Rule`, `RuleMessage`,
|
|
97
|
+
`FormState`, and the
|
|
82
98
|
`formFields` result's `FormFields`, `DerivedField`, `DerivedArray`,
|
|
83
|
-
`DerivedRule`, `DroppedCheck`, `
|
|
84
|
-
`
|
|
99
|
+
`DerivedRule`, `DroppedCheck`, `ValidityFlag`, and the input types
|
|
100
|
+
(`FieldInput`, `NumberInput`, `CheckboxInput`, `StringCheckboxInput`,
|
|
101
|
+
`FileInput`, `CheckboxGroupInput`).
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@k8ordo/form",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "4.0.0",
|
|
4
4
|
"description": "Derive HTML constraint attributes and per-field errors from one zod schema. Works without JavaScript.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"constraint-validation",
|
|
@@ -43,17 +43,17 @@
|
|
|
43
43
|
},
|
|
44
44
|
"devDependencies": {
|
|
45
45
|
"@arethetypeswrong/cli": "0.18.5",
|
|
46
|
-
"@k8ordo/state": "^
|
|
46
|
+
"@k8ordo/state": "^4.0.0",
|
|
47
47
|
"@types/react": "19.3.0",
|
|
48
|
-
"@vitejs/plugin-react": "6.
|
|
49
|
-
"@vitest/browser-playwright": "5.
|
|
48
|
+
"@vitejs/plugin-react": "6.3.0",
|
|
49
|
+
"@vitest/browser-playwright": "5.1.1",
|
|
50
50
|
"publint": "0.3.25",
|
|
51
51
|
"react": "19.3.1",
|
|
52
52
|
"react-dom": "19.3.1",
|
|
53
53
|
"typescript": "7.0.2",
|
|
54
|
-
"vite": "npm:@voidzero-dev/vite-plus-core@
|
|
55
|
-
"vite-plus": "1.
|
|
56
|
-
"vitest": "5.
|
|
54
|
+
"vite": "npm:@voidzero-dev/vite-plus-core@8.3.8000",
|
|
55
|
+
"vite-plus": "1.7.0",
|
|
56
|
+
"vitest": "5.1.1",
|
|
57
57
|
"vitest-browser-react": "2.3.0",
|
|
58
58
|
"zod": "4.6.7"
|
|
59
59
|
},
|