@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
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { $ZodObject, $ZodShape
|
|
1
|
+
import { $ZodObject, $ZodShape } from "zod/v4/core";
|
|
2
2
|
/**
|
|
3
3
|
* The common ground between `zod` and `zod/mini`: both build on the shared core
|
|
4
4
|
* object and both expose `shape`. Accepting this instead of the classic
|
|
@@ -7,26 +7,4 @@ import { $ZodObject, $ZodShape, $ZodType } from "zod/v4/core";
|
|
|
7
7
|
*/
|
|
8
8
|
export type ObjectSchema<Shape extends $ZodShape = $ZodShape> = $ZodObject<Shape> & {
|
|
9
9
|
shape: Shape;
|
|
10
|
-
};
|
|
11
|
-
export type ProbeIssue = {
|
|
12
|
-
code: string;
|
|
13
|
-
/** Which string format rejected the value, on an `invalid_format` issue. */
|
|
14
|
-
format?: string;
|
|
15
|
-
message: string;
|
|
16
|
-
path: readonly PropertyKey[];
|
|
17
|
-
};
|
|
18
|
-
/** What probing needs, present on both entries but not on the core type. */
|
|
19
|
-
export type ProbeSchema = $ZodType & {
|
|
20
|
-
safeParse: (value: unknown) => {
|
|
21
|
-
success: true;
|
|
22
|
-
data: unknown;
|
|
23
|
-
error?: undefined;
|
|
24
|
-
} | {
|
|
25
|
-
success: false;
|
|
26
|
-
data?: undefined;
|
|
27
|
-
error: {
|
|
28
|
-
issues: readonly ProbeIssue[];
|
|
29
|
-
};
|
|
30
|
-
};
|
|
31
|
-
};
|
|
32
|
-
export declare const asProbe: (schema: $ZodType) => ProbeSchema;
|
|
10
|
+
};
|
package/dist/schema/walk.d.mts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { ControlKind, LeafSchema } from "../derive/attributes.mjs";
|
|
2
2
|
import { ObjectSchema } from "./object-schema.mjs";
|
|
3
3
|
import { $ZodType } from "zod/v4/core";
|
|
4
|
+
export type Api = 'formFields' | 'parseForm';
|
|
4
5
|
/** Placeholder an array item's name carries until a row index is known. */
|
|
5
6
|
export declare const INDEX = "{index}";
|
|
6
7
|
export type LeafNode = {
|
|
@@ -23,11 +24,13 @@ export type LeafNode = {
|
|
|
23
24
|
/**
|
|
24
25
|
* Present when several same-named controls submit together — a checkbox
|
|
25
26
|
* group, derived from an array of enums. Carries the bounds the group's
|
|
26
|
-
* array schema declared, which HTML has no attribute for
|
|
27
|
+
* array schema declared, which HTML has no attribute for, and that schema,
|
|
28
|
+
* whose own wording reports them.
|
|
27
29
|
*/
|
|
28
30
|
group?: {
|
|
29
31
|
minItems?: number;
|
|
30
32
|
maxItems?: number;
|
|
33
|
+
array: $ZodType;
|
|
31
34
|
};
|
|
32
35
|
};
|
|
33
36
|
export type ArrayNode = {
|
|
@@ -51,4 +54,4 @@ export declare const unwrap: ($schema: $ZodType) => $ZodType;
|
|
|
51
54
|
* that becomes a repeatable group. Both the derivation and the parse read this,
|
|
52
55
|
* so the two can never disagree about what the form contains.
|
|
53
56
|
*/
|
|
54
|
-
export declare const schemaMap: (schema: ObjectSchema) => SchemaMap;
|
|
57
|
+
export declare const schemaMap: (schema: ObjectSchema, api: Api) => SchemaMap;
|
package/dist/schema/walk.mjs
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
import { asProbe } from "./object-schema.mjs";
|
|
2
1
|
import { controlKindOf, emptySubmissionOf } from "../derive/attributes.mjs";
|
|
3
|
-
import { $ZodArray, $ZodCatch, $ZodDefault, $ZodNonOptional, $ZodNullable, $ZodObject, $ZodOptional, $ZodPrefault, $ZodReadonly, safeEncode, toJSONSchema } from "zod/v4/core";
|
|
2
|
+
import { $ZodArray, $ZodCatch, $ZodDefault, $ZodNonOptional, $ZodNullable, $ZodObject, $ZodOptional, $ZodPrefault, $ZodReadonly, safeEncode, safeParse, toJSONSchema } from "zod/v4/core";
|
|
4
3
|
// src/schema/walk.ts
|
|
5
4
|
/** Placeholder an array item's name carries until a row index is known. */
|
|
6
5
|
const INDEX = "{index}";
|
|
@@ -49,7 +48,7 @@ const checkedValueOf = ($schema) => {
|
|
|
49
48
|
* it does with that exact value, which is also what the parse will hand it, is
|
|
50
49
|
* what makes the attribute mean the same on both sides.
|
|
51
50
|
*/
|
|
52
|
-
const rejectsEmptySubmission = (kind, $schema) => !
|
|
51
|
+
const rejectsEmptySubmission = (kind, $schema) => !safeParse($schema, emptySubmissionOf(kind)).success;
|
|
53
52
|
/**
|
|
54
53
|
* Strings a text control could plausibly submit. One is never enough: a schema
|
|
55
54
|
* that coerces reads some strings and not others, and rejecting the one probe
|
|
@@ -61,8 +60,12 @@ const TEXT_PROBES = [
|
|
|
61
60
|
"2000-01-01",
|
|
62
61
|
"k8ordo-probe"
|
|
63
62
|
];
|
|
63
|
+
const COERCING = {
|
|
64
|
+
date: "z.coerce.date()",
|
|
65
|
+
bigint: "z.coerce.bigint()"
|
|
66
|
+
};
|
|
64
67
|
const rejectsAsWrongType = ($schema, value) => {
|
|
65
|
-
const probed =
|
|
68
|
+
const probed = safeParse($schema, value);
|
|
66
69
|
return !probed.success && probed.error.issues.some((issue) => issue.code === "invalid_type");
|
|
67
70
|
};
|
|
68
71
|
/**
|
|
@@ -78,28 +81,34 @@ const rejectsAsWrongType = ($schema, value) => {
|
|
|
78
81
|
* with `too_small`, which is the schema doing its job.
|
|
79
82
|
*/
|
|
80
83
|
const refusalOf = (json, $schema, kind) => {
|
|
81
|
-
if (kind === "string-checkbox") return
|
|
84
|
+
if (kind === "string-checkbox") return safeParse($schema, void 0).data === true ? "an unchecked box submits nothing, and this schema (.default(true) and the like) reads nothing as true, so the box can never submit false; word the field so that checking it means true" : void 0;
|
|
82
85
|
const control = controlKindOf(json);
|
|
83
86
|
if (control === "number") {
|
|
84
|
-
const asText =
|
|
87
|
+
const asText = safeParse($schema, "1");
|
|
85
88
|
if (asText.success) return;
|
|
86
|
-
return
|
|
89
|
+
return safeParse($schema, 1).success || asText.error.issues.some((issue) => issue.code === "invalid_type") ? "form values arrive as strings, so this schema fails on every submission; use z.coerce.number()" : void 0;
|
|
90
|
+
}
|
|
91
|
+
if (kind === "checkbox") return [true, false].every((value) => rejectsAsWrongType($schema, value)) ? "a checkbox is read as a boolean (z.boolean()) or as the string it submits (z.stringbool()), and this schema takes neither, so it fails on every submission" : void 0;
|
|
92
|
+
if (control === "text" && json.type !== "string") {
|
|
93
|
+
if (!TEXT_PROBES.every((probe) => rejectsAsWrongType($schema, probe))) return;
|
|
94
|
+
const { type } = unwrap($schema)._zod.def;
|
|
95
|
+
const coercing = COERCING[type];
|
|
96
|
+
return coercing === void 0 ? "this schema accepts no string, so nothing a form submits can satisfy it" : `this schema accepts no string, so nothing a form submits can satisfy it; use ${coercing} instead of z.${type}()`;
|
|
87
97
|
}
|
|
88
|
-
if (kind === "checkbox") return [true, false].every((value) => rejectsAsWrongType($schema, value)) ? "チェックボックスは真偽値(z.boolean())か、送信する文字列(z.stringbool())として読むため、どちらでもないこのスキーマはどんな入力でも失敗します" : void 0;
|
|
89
|
-
if (control === "text" && json.type !== "string") return TEXT_PROBES.every((probe) => rejectsAsWrongType($schema, probe)) ? "このスキーマは文字列を受け付けないため、フォームが送信できる値がありません(z.date() や z.bigint() などは表現できません)" : void 0;
|
|
90
98
|
};
|
|
91
|
-
const fail = (path, reason) => {
|
|
92
|
-
throw new Error(
|
|
99
|
+
const fail = (api, path, reason) => {
|
|
100
|
+
throw new Error(`${api}: '${path === "" ? "(schema)" : path}': ${reason}`);
|
|
93
101
|
};
|
|
94
102
|
const walkNode = (json, zod, path, name, context, out) => {
|
|
95
103
|
if (json.type === "object") {
|
|
96
104
|
const shape = shapeOf(zod);
|
|
97
|
-
if (json.properties === void 0 || shape === void 0) fail(path, "
|
|
105
|
+
if (json.properties === void 0 || shape === void 0) fail(context.api, path, "an object whose keys cannot be listed (z.record and the like) cannot be laid out as form fields");
|
|
98
106
|
for (const [key, child] of Object.entries(json.properties)) {
|
|
99
|
-
if (/[.[\]]/u.test(key)) fail(path === "" ? key : `${path}.${key}`, "
|
|
107
|
+
if (/[.[\]]/u.test(key)) fail(context.api, path === "" ? key : `${path}.${key}`, "a key containing '.', '[' or ']' collides with the separators of an input's name");
|
|
100
108
|
const childZod = shape[key];
|
|
101
|
-
if (childZod === void 0) fail(path === "" ? key : `${path}.${key}`, "JSON Schema
|
|
109
|
+
if (childZod === void 0) fail(context.api, path === "" ? key : `${path}.${key}`, "this key appears only in the JSON Schema, with no zod schema to pair it with, so it cannot be laid out as a form field");
|
|
102
110
|
walkNode(child, childZod, path === "" ? key : `${path}.${key}`, name === "" ? key : `${name}.${key}`, {
|
|
111
|
+
api: context.api,
|
|
103
112
|
arrayPath: context.arrayPath,
|
|
104
113
|
itemKey: context.arrayPath === null ? null : context.itemKey === null || context.itemKey === "" ? key : `${context.itemKey}.${key}`
|
|
105
114
|
}, out);
|
|
@@ -107,10 +116,10 @@ const walkNode = (json, zod, path, name, context, out) => {
|
|
|
107
116
|
return;
|
|
108
117
|
}
|
|
109
118
|
if (json.type === "array") {
|
|
110
|
-
if (json.items === void 0) fail(path, "
|
|
119
|
+
if (json.items === void 0) fail(context.api, path, "an array whose items differ (a tuple and the like) cannot be repeated rows");
|
|
111
120
|
if (json.items.enum !== void 0) {
|
|
112
121
|
const element = elementOf(zod);
|
|
113
|
-
if (element === void 0) fail(path, "
|
|
122
|
+
if (element === void 0) fail(context.api, path, "the array's element schema could not be read");
|
|
114
123
|
out.leaves.push({
|
|
115
124
|
path,
|
|
116
125
|
name,
|
|
@@ -122,14 +131,15 @@ const walkNode = (json, zod, path, name, context, out) => {
|
|
|
122
131
|
itemKey: context.itemKey,
|
|
123
132
|
group: {
|
|
124
133
|
minItems: json.minItems,
|
|
125
|
-
maxItems: json.maxItems
|
|
134
|
+
maxItems: json.maxItems,
|
|
135
|
+
array: zod
|
|
126
136
|
}
|
|
127
137
|
});
|
|
128
138
|
return;
|
|
129
139
|
}
|
|
130
|
-
if (context.arrayPath !== null) fail(path, "
|
|
140
|
+
if (context.arrayPath !== null) fail(context.api, path, "a repeat inside a repeat has no unambiguous index in an input's name");
|
|
131
141
|
const element = elementOf(zod);
|
|
132
|
-
if (element === void 0) fail(path, "
|
|
142
|
+
if (element === void 0) fail(context.api, path, "the array's element schema could not be read");
|
|
133
143
|
out.arrays.push({
|
|
134
144
|
path,
|
|
135
145
|
name,
|
|
@@ -137,18 +147,19 @@ const walkNode = (json, zod, path, name, context, out) => {
|
|
|
137
147
|
maxItems: json.maxItems
|
|
138
148
|
});
|
|
139
149
|
walkNode(json.items, element, path, `${name}[${INDEX}]`, {
|
|
150
|
+
api: context.api,
|
|
140
151
|
arrayPath: path,
|
|
141
152
|
itemKey: ""
|
|
142
153
|
}, out);
|
|
143
154
|
return;
|
|
144
155
|
}
|
|
145
156
|
if (json.anyOf !== void 0) {
|
|
146
|
-
for (const branch of json.anyOf) if (branch.type === "object" || branch.type === "array") fail(path, "nullable
|
|
157
|
+
for (const branch of json.anyOf) if (branch.type === "object" || branch.type === "array") fail(context.api, path, "a nullable or union object or array leaves no single branch to render");
|
|
147
158
|
}
|
|
148
159
|
const checkedValue = controlKindOf(json) === "checkbox" ? checkedValueOf(zod) : void 0;
|
|
149
160
|
const kind = checkedValue === void 0 ? kindOf(json, zod) : "string-checkbox";
|
|
150
161
|
const refusal = refusalOf(json, zod, kind);
|
|
151
|
-
if (refusal !== void 0) fail(path, refusal);
|
|
162
|
+
if (refusal !== void 0) fail(context.api, path, refusal);
|
|
152
163
|
out.leaves.push({
|
|
153
164
|
path,
|
|
154
165
|
name,
|
|
@@ -167,7 +178,7 @@ const cache = /* @__PURE__ */ new WeakMap();
|
|
|
167
178
|
* that becomes a repeatable group. Both the derivation and the parse read this,
|
|
168
179
|
* so the two can never disagree about what the form contains.
|
|
169
180
|
*/
|
|
170
|
-
const schemaMap = (schema) => {
|
|
181
|
+
const schemaMap = (schema, api) => {
|
|
171
182
|
const cached = cache.get(schema);
|
|
172
183
|
if (cached !== void 0) return cached;
|
|
173
184
|
const json = toJSONSchema(schema, {
|
|
@@ -180,6 +191,7 @@ const schemaMap = (schema) => {
|
|
|
180
191
|
arrays: []
|
|
181
192
|
};
|
|
182
193
|
walkNode(json, schema, "", "", {
|
|
194
|
+
api,
|
|
183
195
|
arrayPath: null,
|
|
184
196
|
itemKey: null
|
|
185
197
|
}, out);
|
package/dist/server.d.mts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import { DerivedRule, Rule, RuleMessage, minChecked, requiredWhen, sameAs } from "./rules/rules.mjs";
|
|
2
|
-
import { DerivedArray, DerivedField, DroppedCheck, FieldInput, FormFields, FormState, StringCheckboxInput, ValidityFlag } from "./types.mjs";
|
|
3
|
-
import { FormDefinition, defineForm } from "./rules/define-form.mjs";
|
|
4
1
|
import { formFields } from "./derive/form-fields.mjs";
|
|
5
2
|
import { ParseResult, parseForm } from "./parse/parse-form.mjs";
|
|
6
|
-
|
|
3
|
+
import { FormDefinition, defineForm } from "./rules/define-form.mjs";
|
|
4
|
+
import { DerivedRule, Rule, RuleMessage, requiredWhen, sameAs } from "./rules/rules.mjs";
|
|
5
|
+
import { ObjectSchema } from "./schema/object-schema.mjs";
|
|
6
|
+
import { CheckboxGroupInput, CheckboxInput, DerivedArray, DerivedField, DroppedCheck, FieldInput, FileInput, FormFields, FormState, NumberInput, StringCheckboxInput, ValidityFlag } from "./types.mjs";
|
|
7
|
+
export { type CheckboxGroupInput, type CheckboxInput, type DerivedArray, type DerivedField, type DerivedRule, type DroppedCheck, type FieldInput, type FileInput, type FormDefinition, type FormFields, type FormState, type NumberInput, type ObjectSchema, type ParseResult, type Rule, type RuleMessage, type StringCheckboxInput, type ValidityFlag, defineForm, formFields, parseForm, requiredWhen, sameAs };
|
package/dist/server.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { minChecked, requiredWhen, sameAs } from "./rules/rules.mjs";
|
|
2
|
-
import { defineForm } from "./rules/define-form.mjs";
|
|
3
1
|
import { formFields } from "./derive/form-fields.mjs";
|
|
4
2
|
import { parseForm } from "./parse/parse-form.mjs";
|
|
5
|
-
|
|
3
|
+
import { defineForm } from "./rules/define-form.mjs";
|
|
4
|
+
import { requiredWhen, sameAs } from "./rules/rules.mjs";
|
|
5
|
+
export { defineForm, formFields, parseForm, requiredWhen, sameAs };
|
package/dist/types.d.mts
CHANGED
|
@@ -1,7 +1,15 @@
|
|
|
1
|
+
import { ArrayInputsOf, FieldInputsOf } from "./paths.mjs";
|
|
2
|
+
import { FormDefinition } from "./rules/define-form.mjs";
|
|
1
3
|
import { DerivedRule } from "./rules/rules.mjs";
|
|
4
|
+
import { ObjectSchema } from "./schema/object-schema.mjs";
|
|
2
5
|
/** ValidityState flags a derived field can report a message for. */
|
|
3
6
|
export type ValidityFlag = 'badInput' | 'patternMismatch' | 'rangeOverflow' | 'rangeUnderflow' | 'stepMismatch' | 'tooLong' | 'tooShort' | 'typeMismatch' | 'valueMissing';
|
|
4
|
-
/**
|
|
7
|
+
/**
|
|
8
|
+
* Attributes spread onto the input element itself, for a field whose control
|
|
9
|
+
* the schema's type does not settle: a string (`type` is `email`, `date`,
|
|
10
|
+
* `password` and the like, and absent for plain text), an enum, and anything
|
|
11
|
+
* read through a union, a pipe or a literal.
|
|
12
|
+
*/
|
|
5
13
|
export type FieldInput = {
|
|
6
14
|
name: string;
|
|
7
15
|
type?: string;
|
|
@@ -11,55 +19,120 @@ export type FieldInput = {
|
|
|
11
19
|
pattern?: string;
|
|
12
20
|
/** Comma-separated mime types for a file control, from `.mime()`. */
|
|
13
21
|
accept?: string;
|
|
14
|
-
min?: number
|
|
15
|
-
max?: number
|
|
22
|
+
min?: number;
|
|
23
|
+
max?: number;
|
|
16
24
|
step?: number | 'any';
|
|
17
25
|
defaultValue?: string;
|
|
18
26
|
defaultChecked?: boolean;
|
|
19
27
|
};
|
|
28
|
+
/** The input of a `z.coerce.number()` field. */
|
|
29
|
+
export type NumberInput = {
|
|
30
|
+
name: string;
|
|
31
|
+
type: 'number';
|
|
32
|
+
required?: boolean;
|
|
33
|
+
min?: number;
|
|
34
|
+
max?: number;
|
|
35
|
+
/** From `.multipleOf()`; `1` after `.int()`, `'any'` otherwise. */
|
|
36
|
+
step: number | 'any';
|
|
37
|
+
/** The submitted text, echoed after a failed submission. */
|
|
38
|
+
defaultValue?: string;
|
|
39
|
+
};
|
|
40
|
+
/** The input of a checkbox read as checked or not (`z.boolean()`). */
|
|
41
|
+
export type CheckboxInput = {
|
|
42
|
+
name: string;
|
|
43
|
+
type: 'checkbox';
|
|
44
|
+
required?: boolean;
|
|
45
|
+
defaultChecked?: boolean;
|
|
46
|
+
};
|
|
20
47
|
/**
|
|
21
48
|
* The input of a checkbox whose schema reads the submitted string
|
|
22
49
|
* (`z.stringbool()`): it also carries what a checked box submits.
|
|
23
50
|
*/
|
|
24
|
-
export type StringCheckboxInput =
|
|
51
|
+
export type StringCheckboxInput = CheckboxInput & {
|
|
25
52
|
/** The schema's own spelling of `true`. */
|
|
53
|
+
value: string;
|
|
54
|
+
};
|
|
55
|
+
/**
|
|
56
|
+
* The input of a `z.file()` field. It has no `defaultValue`: no browser lets
|
|
57
|
+
* a value be put back into a file control.
|
|
58
|
+
*/
|
|
59
|
+
export type FileInput = {
|
|
60
|
+
name: string;
|
|
61
|
+
type: 'file';
|
|
62
|
+
required?: boolean;
|
|
63
|
+
/** Comma-separated mime types, from `.mime()`. */
|
|
64
|
+
accept?: string;
|
|
65
|
+
};
|
|
66
|
+
/**
|
|
67
|
+
* The input of a checkbox group (`z.array(z.enum([…]))`): the name every box
|
|
68
|
+
* shares, and after a submission the options that were checked.
|
|
69
|
+
*/
|
|
70
|
+
export type CheckboxGroupInput = {
|
|
71
|
+
name: string;
|
|
72
|
+
defaultValue?: string[];
|
|
73
|
+
};
|
|
74
|
+
export type AnyFieldInput = Omit<FieldInput, 'defaultValue'> & {
|
|
26
75
|
value?: string;
|
|
76
|
+
defaultValue?: string | string[];
|
|
27
77
|
};
|
|
28
78
|
/**
|
|
29
79
|
* One field as derived from the schema. Serializable on purpose: it crosses the
|
|
30
80
|
* RSC boundary as props, which is what keeps zod out of the client bundle.
|
|
31
81
|
*/
|
|
32
|
-
export type DerivedField<Input
|
|
82
|
+
export type DerivedField<Input = FieldInput> = {
|
|
33
83
|
input: Input;
|
|
34
84
|
/** Message per ValidityState flag, taken from zod itself. */
|
|
35
85
|
messages: Partial<Record<ValidityFlag, string>>;
|
|
36
86
|
/** True when the input must not be echoed back after a failed submit. */
|
|
37
87
|
secret: boolean;
|
|
88
|
+
/**
|
|
89
|
+
* Present on a checkbox group — one name shared by every box — with the
|
|
90
|
+
* bounds its array schema declared.
|
|
91
|
+
*/
|
|
92
|
+
group?: {
|
|
93
|
+
minItems?: number;
|
|
94
|
+
maxItems?: number;
|
|
95
|
+
};
|
|
38
96
|
};
|
|
39
97
|
/**
|
|
40
|
-
* A repeatable group
|
|
41
|
-
*
|
|
98
|
+
* A repeatable group as `formFields` derives it, named by the schema (or
|
|
99
|
+
* `defineForm` definition) and the array's path:
|
|
100
|
+
* `DerivedArray<typeof orderSchema, 'items'>`. The item is described once;
|
|
101
|
+
* the row index is filled into the name when a row renders, because rows do
|
|
102
|
+
* not exist until then.
|
|
42
103
|
*/
|
|
43
|
-
export type DerivedArray =
|
|
104
|
+
export type DerivedArray<Source extends ObjectSchema | FormDefinition, Path extends ArrayPathOf<Source>> = DerivedArrayBy<ItemInputsOf<Source, Path>>;
|
|
105
|
+
export type DerivedArrayBy<ItemInputs> = {
|
|
44
106
|
path: string;
|
|
45
107
|
minItems?: number;
|
|
46
108
|
maxItems?: number;
|
|
47
109
|
/** Keyed by the path within one item; '' when the array holds scalars. */
|
|
48
|
-
item:
|
|
110
|
+
item: { [Key in keyof ItemInputs]: DerivedField<ItemInputs[Key]>; };
|
|
111
|
+
};
|
|
112
|
+
export type AnyDerivedArray = Omit<DerivedArrayBy<Record<string, AnyFieldInput>>, 'item'> & {
|
|
113
|
+
item: Record<string, DerivedField<AnyFieldInput>>;
|
|
49
114
|
};
|
|
50
115
|
/** What a constraint-carrying check lost on its way to HTML. */
|
|
51
116
|
export type DroppedCheck = {
|
|
52
117
|
field: string;
|
|
53
118
|
reason: string;
|
|
54
119
|
};
|
|
120
|
+
export type SchemaOf<Source extends ObjectSchema | FormDefinition> = Source extends FormDefinition<infer Schema> ? Schema : Source;
|
|
121
|
+
export type ArrayPathOf<Source extends ObjectSchema | FormDefinition> = keyof ArrayInputsOf<SchemaOf<Source>> & string;
|
|
122
|
+
export type ItemInputsOf<Source extends ObjectSchema | FormDefinition, Path extends ArrayPathOf<Source>> = ArrayInputsOf<SchemaOf<Source>>[Path];
|
|
123
|
+
/**
|
|
124
|
+
* What `formFields` derives from a schema or a `defineForm` definition, typed
|
|
125
|
+
* from that schema: `FormFields<typeof talkSchema>` is what `formFields`
|
|
126
|
+
* returns for it. The import is type-only, so zod stays out of the bundle.
|
|
127
|
+
*/
|
|
128
|
+
export type FormFields<Source extends ObjectSchema | FormDefinition> = FieldsBy<FieldInputsOf<SchemaOf<Source>>, ArrayInputsOf<SchemaOf<Source>>>;
|
|
55
129
|
/**
|
|
56
|
-
* `
|
|
57
|
-
* `
|
|
58
|
-
* it out still takes the derived fields, and only hides `value` from `field()`.
|
|
130
|
+
* `FormFields` spelled out by what it holds rather than by the schema, so
|
|
131
|
+
* `useForm` can infer it from the structure of any value of that shape.
|
|
59
132
|
*/
|
|
60
|
-
export type
|
|
61
|
-
fields:
|
|
62
|
-
arrays:
|
|
133
|
+
export type FieldsBy<Inputs, Arrays> = {
|
|
134
|
+
fields: { [Path in keyof Inputs]: DerivedField<Inputs[Path]>; };
|
|
135
|
+
arrays: { [Path in keyof Arrays]: DerivedArrayBy<Arrays[Path]>; };
|
|
63
136
|
/**
|
|
64
137
|
* Checks HTML has no attribute for, each run by the same evaluator on both
|
|
65
138
|
* sides. A function message has already been called.
|
package/dist/use-form.d.mts
CHANGED
|
@@ -1,20 +1,38 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { ArrayInputsOf, FieldInputsOf } from "./paths.mjs";
|
|
2
|
+
import { FormDefinition } from "./rules/define-form.mjs";
|
|
3
|
+
import { ObjectSchema } from "./schema/object-schema.mjs";
|
|
4
|
+
import { ArrayPathOf, FieldInput, FieldsBy, FormState, ItemInputsOf, SchemaOf } from "./types.mjs";
|
|
2
5
|
import { FocusEvent, Ref, SubmitEvent, SyntheticEvent } from "react";
|
|
3
6
|
type Control = HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement;
|
|
4
|
-
export type FieldView<Input
|
|
7
|
+
export type FieldView<Input = FieldInput> = {
|
|
5
8
|
input: Input;
|
|
6
9
|
error: string | undefined;
|
|
7
10
|
invalid: boolean;
|
|
8
11
|
required: boolean;
|
|
9
12
|
};
|
|
10
|
-
|
|
13
|
+
/**
|
|
14
|
+
* One repeated row, named by the schema (or `defineForm` definition) and the
|
|
15
|
+
* array's path, for a component that takes a whole row:
|
|
16
|
+
* `{ row: RowView<typeof orderSchema, 'items'> }`.
|
|
17
|
+
*/
|
|
18
|
+
export type RowView<Source extends ObjectSchema | FormDefinition, Path extends ArrayPathOf<Source>> = RowViewBy<ItemInputsOf<Source, Path>>;
|
|
19
|
+
type RowViewBy<ItemInputs> = {
|
|
11
20
|
key: string;
|
|
12
21
|
index: number;
|
|
13
|
-
|
|
22
|
+
/**
|
|
23
|
+
* One field of the row, by its path within the item. A row of an array of
|
|
24
|
+
* scalars is a single field, under `''`, so its key can be left out.
|
|
25
|
+
*/
|
|
26
|
+
field: [keyof ItemInputs] extends [''] ? (itemKey?: '') => FieldView<ItemInputs[keyof ItemInputs]> : <Key extends keyof ItemInputs & string>(itemKey: Key) => FieldView<ItemInputs[Key]>;
|
|
14
27
|
remove: () => void;
|
|
15
28
|
};
|
|
16
|
-
|
|
17
|
-
|
|
29
|
+
/**
|
|
30
|
+
* What `form.array()` returns, named by the schema (or `defineForm`
|
|
31
|
+
* definition) and the array's path: `ArrayView<typeof orderSchema, 'items'>`.
|
|
32
|
+
*/
|
|
33
|
+
export type ArrayView<Source extends ObjectSchema | FormDefinition, Path extends ArrayPathOf<Source>> = ArrayViewBy<ItemInputsOf<Source, Path>>;
|
|
34
|
+
type ArrayViewBy<ItemInputs> = {
|
|
35
|
+
rows: Array<RowViewBy<ItemInputs>>;
|
|
18
36
|
add: () => void;
|
|
19
37
|
canAdd: boolean;
|
|
20
38
|
canRemove: boolean;
|
|
@@ -34,7 +52,12 @@ export type FormErrorView = {
|
|
|
34
52
|
tabIndex: -1;
|
|
35
53
|
};
|
|
36
54
|
};
|
|
37
|
-
|
|
55
|
+
/**
|
|
56
|
+
* What `useForm` returns for the fields `formFields` derived from a schema or
|
|
57
|
+
* a `defineForm` definition: `UseFormReturn<typeof talkSchema>`.
|
|
58
|
+
*/
|
|
59
|
+
export type UseFormReturn<Source extends ObjectSchema | FormDefinition> = UseFormReturnBy<FieldInputsOf<SchemaOf<Source>>, ArrayInputsOf<SchemaOf<Source>>>;
|
|
60
|
+
type UseFormReturnBy<Inputs, Arrays> = {
|
|
38
61
|
props: {
|
|
39
62
|
onBlur: (event: FocusEvent<HTMLFormElement>) => void;
|
|
40
63
|
onInput: (event: SyntheticEvent<HTMLFormElement>) => void;
|
|
@@ -42,11 +65,8 @@ export type UseFormReturn<FieldPath extends string = string, ArrayPath extends s
|
|
|
42
65
|
onSubmit: (event: SubmitEvent<HTMLFormElement>) => void;
|
|
43
66
|
ref: Ref<HTMLFormElement>;
|
|
44
67
|
};
|
|
45
|
-
field:
|
|
46
|
-
|
|
47
|
-
(path: FieldPath): FieldView;
|
|
48
|
-
};
|
|
49
|
-
array: (path: ArrayPath) => ArrayView;
|
|
68
|
+
field: <Path extends keyof Inputs & string>(path: Path) => FieldView<Inputs[Path]>;
|
|
69
|
+
array: <Path extends keyof Arrays & string>(path: Path) => ArrayViewBy<Arrays[Path]>;
|
|
50
70
|
formError: FormErrorView;
|
|
51
71
|
/** True once any field differs from the value it was rendered with. */
|
|
52
72
|
isDirty: boolean;
|
|
@@ -66,5 +86,5 @@ export type UseFormReturn<FieldPath extends string = string, ArrayPath extends s
|
|
|
66
86
|
* identity of each repeated row, one dirty flag, and the row counts adding or
|
|
67
87
|
* removing a row is measured against.
|
|
68
88
|
*/
|
|
69
|
-
export declare const useForm: <
|
|
89
|
+
export declare const useForm: <Inputs, Arrays>(fields: FieldsBy<Inputs, Arrays>, state?: FormState) => UseFormReturnBy<Inputs, Arrays>;
|
|
70
90
|
export {};
|
package/dist/use-form.mjs
CHANGED
|
@@ -216,14 +216,16 @@ const useForm = (fields, state = {}) => {
|
|
|
216
216
|
...field.input,
|
|
217
217
|
name
|
|
218
218
|
};
|
|
219
|
-
if (field.
|
|
219
|
+
if (field.group !== void 0) {
|
|
220
|
+
if (value !== void 0) input.defaultValue = [value].flat();
|
|
221
|
+
} else if (field.input.type === "checkbox") {
|
|
220
222
|
if (state.values !== void 0) input.defaultChecked = value !== void 0;
|
|
221
223
|
} else if (typeof value === "string") input.defaultValue = value;
|
|
222
224
|
return {
|
|
223
225
|
input,
|
|
224
226
|
error,
|
|
225
227
|
invalid: error !== void 0,
|
|
226
|
-
required: field.input.required ?? false
|
|
228
|
+
required: field.group === void 0 ? field.input.required ?? false : (field.group.minItems ?? 0) >= 1
|
|
227
229
|
};
|
|
228
230
|
}, [
|
|
229
231
|
clientErrors,
|
|
@@ -232,12 +234,12 @@ const useForm = (fields, state = {}) => {
|
|
|
232
234
|
]);
|
|
233
235
|
const field = useCallback((path) => {
|
|
234
236
|
const derived = lookup.fields[path];
|
|
235
|
-
if (derived === void 0) throw new Error(`
|
|
237
|
+
if (derived === void 0) throw new Error(`useForm: the schema has no field '${path}'; reach a field inside repeated rows through array()`);
|
|
236
238
|
return viewOf(derived, derived.input.name);
|
|
237
239
|
}, [lookup, viewOf]);
|
|
238
240
|
const array = useCallback((path) => {
|
|
239
241
|
const derived = lookup.arrays[path];
|
|
240
|
-
if (derived === void 0) throw new Error(`
|
|
242
|
+
if (derived === void 0) throw new Error(`useForm: the schema has no array '${path}'`);
|
|
241
243
|
const keys = rowKeys[path] ?? [];
|
|
242
244
|
const remove = (key) => {
|
|
243
245
|
const index = keys.indexOf(key);
|
|
@@ -258,7 +260,7 @@ const useForm = (fields, state = {}) => {
|
|
|
258
260
|
index,
|
|
259
261
|
field: (itemKey = "") => {
|
|
260
262
|
const item = derived.item[itemKey];
|
|
261
|
-
if (item === void 0) throw new Error(`
|
|
263
|
+
if (item === void 0) throw new Error(`useForm: array '${path}' has no field '${itemKey}' in its rows`);
|
|
262
264
|
return viewOf(item, item.input.name.replace(INDEX, String(index)));
|
|
263
265
|
},
|
|
264
266
|
remove: () => {
|