@k8ordo/form 1.4.3 → 2.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.
@@ -1,3 +1,4 @@
1
+ import { UseFormReturn } from "./use-form.mjs";
1
2
  /**
2
3
  * Ask the server about one field while the person is still filling the form.
3
4
  *
@@ -16,4 +17,4 @@ export type AsyncCheck = {
16
17
  /** True while an answer is outstanding, for disabling submit. */
17
18
  isChecking: boolean;
18
19
  };
19
- export declare const useAsyncCheck: (check: (value: string) => Promise<string | undefined>) => AsyncCheck;
20
+ export declare const useAsyncCheck: (check: (value: string) => Promise<string | undefined>, revalidate: UseFormReturn['revalidate']) => AsyncCheck;
@@ -1,7 +1,7 @@
1
1
  "use client";
2
2
  import { useCallback, useEffect, useRef, useState } from "react";
3
3
  // src/async-check.ts
4
- const useAsyncCheck = (check) => {
4
+ const useAsyncCheck = (check, revalidate) => {
5
5
  const control = useRef(null);
6
6
  const latest = useRef(0);
7
7
  const answered = useRef(null);
@@ -13,8 +13,7 @@ const useAsyncCheck = (check) => {
13
13
  props: {
14
14
  onBlur: useCallback(() => {
15
15
  const node = control.current;
16
- if (node === null) return;
17
- if (node.value === answered.current) return;
16
+ if (node === null || node.value === answered.current) return;
18
17
  latest.current += 1;
19
18
  if (node.value === "") {
20
19
  answered.current = null;
@@ -32,12 +31,12 @@ const useAsyncCheck = (check) => {
32
31
  if (current === null || current.value !== issuedFor) return;
33
32
  answered.current = issuedFor;
34
33
  current.setCustomValidity(message ?? "");
35
- current.dispatchEvent(new FocusEvent("focusout", { bubbles: true }));
36
- } catch {} finally {
34
+ revalidate(current);
35
+ } finally {
37
36
  if (ticket === latest.current) setIsChecking(false);
38
37
  }
39
- })();
40
- }, [check]),
38
+ })().catch(reportError);
39
+ }, [check, revalidate]),
41
40
  ref: useCallback((node) => {
42
41
  control.current = node;
43
42
  }, [])
@@ -4,8 +4,15 @@ import { asProbe } from "../schema/object-schema.mjs";
4
4
  import { attributesFor, emptySubmissionOf, namesAControl } from "./attributes.mjs";
5
5
  import { schemaMap, unwrap } from "../schema/walk.mjs";
6
6
  import { messagesFor } from "./messages.mjs";
7
+ import { $ZodCheckStringFormat } from "zod/v4/core";
7
8
  // src/derive/form-fields.ts
8
- const objectLevelCheckCount = (schema) => schema._zod?.def?.checks?.length ?? 0;
9
+ /**
10
+ * Object-level checks — `.refine()` and friends — vanish from the JSON Schema
11
+ * without a trace, so the conversion cannot tell us they existed. Only the
12
+ * schema's check list can, and knowing is the whole point: a check the client
13
+ * never runs has to be reported, not silently skipped.
14
+ */
15
+ const objectLevelCheckCount = (schema) => schema._zod.def.checks?.length ?? 0;
9
16
  /**
10
17
  * The string formats a leaf declares — its own (`z.email()`) first, then the
11
18
  * ones its checks add (`.regex()`, `.lowercase()`) — each with the RegExp
@@ -15,8 +22,8 @@ const objectLevelCheckCount = (schema) => schema._zod?.def?.checks?.length ?? 0;
15
22
  * (`.regex()`).
16
23
  */
17
24
  const stringFormatsOf = (schema) => {
18
- const def = unwrap(schema)._zod?.def;
19
- return [def, ...(def?.checks ?? []).map((check) => check._zod?.def)].filter((entry) => entry?.format !== void 0);
25
+ const leaf = unwrap(schema);
26
+ return [leaf, ...leaf._zod.def.checks ?? []].filter((entry) => entry instanceof $ZodCheckStringFormat).map((entry) => entry._zod.def);
20
27
  };
21
28
  /** zod's own name for a format is not always the JSON Schema one. */
22
29
  const ZOD_FORMAT_TO_JSON_FORMAT = {
package/dist/index.d.mts CHANGED
@@ -1,6 +1,6 @@
1
- import { AsyncCheck, useAsyncCheck } from "./async-check.mjs";
2
1
  import { DerivedRule, Rule, RuleMessage } from "./rules/rules.mjs";
3
2
  import { DerivedArray, DerivedField, DroppedCheck, FieldInput, FormFields, FormState, StringCheckboxInput, ValidityFlag } from "./types.mjs";
4
- import { HiddenValue } from "./hidden-value.mjs";
5
3
  import { ArrayView, FieldView, FormErrorView, RowView, UseFormReturn, useForm } from "./use-form.mjs";
4
+ import { AsyncCheck, useAsyncCheck } from "./async-check.mjs";
5
+ import { HiddenValue } from "./hidden-value.mjs";
6
6
  export { type ArrayView, type AsyncCheck, type DerivedArray, type DerivedField, type DerivedRule, type DroppedCheck, type FieldInput, type FieldView, type FormErrorView, type FormFields, type FormState, HiddenValue, type RowView, type Rule, type RuleMessage, type StringCheckboxInput, type UseFormReturn, type ValidityFlag, useAsyncCheck, useForm };
@@ -1,6 +1,6 @@
1
1
  import { asProbe } from "./object-schema.mjs";
2
2
  import { controlKindOf, emptySubmissionOf } from "../derive/attributes.mjs";
3
- import { safeEncode, toJSONSchema } from "zod/v4/core";
3
+ import { $ZodArray, $ZodCatch, $ZodDefault, $ZodNonOptional, $ZodNullable, $ZodObject, $ZodOptional, $ZodPrefault, $ZodReadonly, safeEncode, toJSONSchema } from "zod/v4/core";
4
4
  // src/schema/walk.ts
5
5
  /** Placeholder an array item's name carries until a row index is known. */
6
6
  const INDEX = "{index}";
@@ -9,19 +9,14 @@ const INDEX = "{index}";
9
9
  * `toJSONSchema` flattens `.optional()` / `.default()` into the plain node, so
10
10
  * pairing the two trees requires flattening the zod side the same way.
11
11
  */
12
- const unwrap = ($schema) => {
13
- let current = $schema;
14
- let inner = current._zod?.def?.innerType;
15
- while (inner !== void 0) {
16
- current = inner;
17
- inner = current._zod?.def?.innerType;
18
- }
19
- return current;
12
+ const unwrap = ($schema) => $schema instanceof $ZodOptional || $schema instanceof $ZodNullable || $schema instanceof $ZodDefault || $schema instanceof $ZodPrefault || $schema instanceof $ZodNonOptional || $schema instanceof $ZodCatch || $schema instanceof $ZodReadonly ? unwrap($schema._zod.def.innerType) : $schema;
13
+ const shapeOf = ($schema) => {
14
+ const node = unwrap($schema);
15
+ return node instanceof $ZodObject ? node._zod.def.shape : void 0;
20
16
  };
21
- const shapeOf = ($schema) => unwrap($schema).shape;
22
17
  const elementOf = ($schema) => {
23
- const candidate = unwrap($schema);
24
- return candidate.element ?? candidate._zod?.def?.element;
18
+ const node = unwrap($schema);
19
+ return node instanceof $ZodArray ? node._zod.def.element : void 0;
25
20
  };
26
21
  /**
27
22
  * BigInt has no JSON Schema form, so its node arrives empty and reads as a
@@ -31,7 +26,7 @@ const elementOf = ($schema) => {
31
26
  */
32
27
  const kindOf = (json, $schema) => {
33
28
  const kind = controlKindOf(json);
34
- return kind === "text" && unwrap($schema)._zod?.def?.type === "bigint" ? "number" : kind;
29
+ return kind === "text" && unwrap($schema)._zod.def.type === "bigint" ? "number" : kind;
35
30
  };
36
31
  /**
37
32
  * 文字列を読むスキーマのチェックボックスが、チェック時に送る文字列。スキーマ
@@ -1,5 +1,6 @@
1
1
  import { FieldInput, FormFields, FormState, StringCheckboxInput } from "./types.mjs";
2
2
  import { FocusEvent, Ref, SubmitEvent, SyntheticEvent } from "react";
3
+ type Control = HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement;
3
4
  export type FieldView<Input extends FieldInput = FieldInput> = {
4
5
  input: Input;
5
6
  error: string | undefined;
@@ -49,6 +50,12 @@ export type UseFormReturn<FieldPath extends string = string, ArrayPath extends s
49
50
  formError: FormErrorView;
50
51
  /** True once any field differs from the value it was rendered with. */
51
52
  isDirty: boolean;
53
+ /**
54
+ * Reads a control's validity again and shows what it says, as leaving the
55
+ * control does — for a verdict that lands after the blur, such as
56
+ * `useAsyncCheck`'s answer.
57
+ */
58
+ revalidate: (control: Control) => void;
52
59
  };
53
60
  /**
54
61
  * Wire derived fields to a form.
@@ -59,4 +66,5 @@ export type UseFormReturn<FieldPath extends string = string, ArrayPath extends s
59
66
  * identity of each repeated row, one dirty flag, and the row counts adding or
60
67
  * removing a row is measured against.
61
68
  */
62
- export declare const useForm: <FieldPath extends string, ArrayPath extends string, StringCheckboxPath extends string = never>(fields: FormFields<FieldPath, ArrayPath, StringCheckboxPath>, state?: FormState) => UseFormReturn<FieldPath, ArrayPath, StringCheckboxPath>;
69
+ export declare const useForm: <FieldPath extends string, ArrayPath extends string, StringCheckboxPath extends string = never>(fields: FormFields<FieldPath, ArrayPath, StringCheckboxPath>, state?: FormState) => UseFormReturn<FieldPath, ArrayPath, StringCheckboxPath>;
70
+ export {};
package/dist/use-form.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  "use client";
2
2
  import { breachOf } from "./rules/rules.mjs";
3
- import { useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "react";
3
+ import { useCallback, useEffect, useEffectEvent, useId, useLayoutEffect, useMemo, useRef, useState } from "react";
4
4
  // src/use-form.ts
5
5
  const INDEX = "{index}";
6
6
  const FLAGS = [
@@ -53,6 +53,18 @@ const rowKeysFor = (counts, current = {}) => {
53
53
  }
54
54
  return rows;
55
55
  };
56
+ const blankNotes = (result, arrived, fields, state, rowKeys) => {
57
+ const baselineRows = rowCountsFor(fields, state);
58
+ return {
59
+ result,
60
+ arrived,
61
+ clientErrors: {},
62
+ edited: /* @__PURE__ */ new Set(),
63
+ domDirty: false,
64
+ baselineRows,
65
+ rowKeys: rowKeysFor(baselineRows, rowKeys)
66
+ };
67
+ };
56
68
  /**
57
69
  * Rename one concrete indexed name after the row at `removed` is gone: entries
58
70
  * on that row are dropped, entries on later rows slide down one index. Without
@@ -99,33 +111,20 @@ const useForm = (fields, state = {}) => {
99
111
  const formRef = useRef(null);
100
112
  const nextKey = useRef(0);
101
113
  const ownedRuleMessages = useRef(/* @__PURE__ */ new Map());
102
- const [clientErrors, setClientErrors] = useState({});
103
- const [edited, setEdited] = useState(/* @__PURE__ */ new Set());
104
- const [domDirty, setDomDirty] = useState(false);
105
- const [baselineRows, setBaselineRows] = useState(() => rowCountsFor(lookup, state));
106
- const [rowKeys, setRowKeys] = useState(() => rowKeysFor(baselineRows));
107
114
  const formErrorId = useId();
108
115
  const arrayErrorIdBase = useId();
109
- const stateKey = JSON.stringify(state);
110
- const lastKey = useRef(stateKey);
111
- useEffect(() => {
112
- if (lastKey.current === stateKey) return;
113
- lastKey.current = stateKey;
114
- setClientErrors({});
115
- setEdited(/* @__PURE__ */ new Set());
116
- setDomDirty(false);
117
- const counts = rowCountsFor(lookup, state);
118
- setBaselineRows(counts);
119
- setRowKeys((previous) => rowKeysFor(counts, previous));
116
+ const result = JSON.stringify(state);
117
+ const [notes, setNotes] = useState(() => blankNotes(result, false, lookup, state));
118
+ if (notes.result !== result) setNotes(blankNotes(result, true, lookup, state, notes.rowKeys));
119
+ const { clientErrors, edited, domDirty, baselineRows, rowKeys } = notes;
120
+ const focusFirstFailure = useEffectEvent(() => {
120
121
  const messageIds = [...state.formError === void 0 ? [] : [formErrorId], ...Object.keys(lookup.arrays).filter((path) => state.errors?.[path] !== void 0).map((path) => arrayErrorId(arrayErrorIdBase, path))];
121
122
  firstFailure(formRef.current, state.errors ?? {}, messageIds)?.focus();
122
- }, [
123
- stateKey,
124
- state,
125
- lookup,
126
- formErrorId,
127
- arrayErrorIdBase
128
- ]);
123
+ });
124
+ const { arrived } = notes;
125
+ useEffect(() => {
126
+ if (arrived) focusFirstFailure();
127
+ }, [result, arrived]);
129
128
  useLayoutEffect(() => {
130
129
  writeEchoToSelects(formRef.current, lookup, state.values);
131
130
  }, [lookup, state.values]);
@@ -135,8 +134,8 @@ const useForm = (fields, state = {}) => {
135
134
  applyRules(form, lookup.rules, ownedRuleMessages.current);
136
135
  const names = /* @__PURE__ */ new Set([target.name]);
137
136
  for (const rule of lookup.rules) names.add(rule.field);
138
- setClientErrors((previous) => {
139
- let next = previous;
137
+ setNotes((previous) => {
138
+ let next = previous.clientErrors;
140
139
  for (const name of names) {
141
140
  const field = fieldFor(lookup, name);
142
141
  if (field === void 0) continue;
@@ -153,17 +152,27 @@ const useForm = (fields, state = {}) => {
153
152
  [name]: message
154
153
  };
155
154
  }
156
- return next;
155
+ return next === previous.clientErrors ? previous : {
156
+ ...previous,
157
+ clientErrors: next
158
+ };
157
159
  });
158
160
  }, [lookup]);
159
161
  const onBlur = useCallback((event) => {
160
162
  evaluate(event.target, false);
161
163
  }, [evaluate]);
164
+ const revalidate = useCallback((control) => {
165
+ evaluate(control, false);
166
+ }, [evaluate]);
162
167
  const onInput = useCallback((event) => {
163
168
  const { target } = event;
164
169
  if (isControl(target)) {
165
- setEdited((previous) => previous.has(target.name) ? previous : new Set(previous).add(target.name));
166
- setDomDirty(isFormDirty(formRef.current));
170
+ const dirty = isFormDirty(formRef.current);
171
+ setNotes((previous) => previous.edited.has(target.name) && previous.domDirty === dirty ? previous : {
172
+ ...previous,
173
+ edited: previous.edited.has(target.name) ? previous.edited : new Set(previous.edited).add(target.name),
174
+ domDirty: dirty
175
+ });
167
176
  }
168
177
  evaluate(target, true);
169
178
  }, [evaluate]);
@@ -176,16 +185,15 @@ const useForm = (fields, state = {}) => {
176
185
  if (failed === void 0) return;
177
186
  event.preventDefault();
178
187
  const messages = messagesIn(form, lookup);
179
- setClientErrors(messages);
188
+ setNotes((previous) => ({
189
+ ...previous,
190
+ clientErrors: messages
191
+ }));
180
192
  failed.focus();
181
193
  if (!Object.hasOwn(messages, failed.name)) failed.reportValidity();
182
194
  }, [lookup]);
183
195
  const onReset = useCallback(() => {
184
- setClientErrors({});
185
- setEdited(/* @__PURE__ */ new Set());
186
- const counts = rowCountsFor(lookup, state);
187
- setBaselineRows(counts);
188
- setRowKeys((previous) => rowKeysFor(counts, previous));
196
+ setNotes((previous) => blankNotes(previous.result, previous.arrived, lookup, state, previous.rowKeys));
189
197
  const form = formRef.current;
190
198
  for (const [name, message] of ownedRuleMessages.current) {
191
199
  const control = controlNamed(form, name);
@@ -193,7 +201,11 @@ const useForm = (fields, state = {}) => {
193
201
  }
194
202
  ownedRuleMessages.current.clear();
195
203
  setTimeout(() => {
196
- setDomDirty(isFormDirty(formRef.current));
204
+ const dirty = isFormDirty(formRef.current);
205
+ setNotes((previous) => previous.domDirty === dirty ? previous : {
206
+ ...previous,
207
+ domDirty: dirty
208
+ });
197
209
  }, 0);
198
210
  }, [lookup, state]);
199
211
  const viewOf = useCallback((field, name) => {
@@ -230,12 +242,15 @@ const useForm = (fields, state = {}) => {
230
242
  const remove = (key) => {
231
243
  const index = keys.indexOf(key);
232
244
  if (index === -1) return;
233
- setRowKeys((previous) => ({
245
+ setNotes((previous) => ({
234
246
  ...previous,
235
- [path]: (previous[path] ?? []).filter((candidate) => candidate !== key)
247
+ rowKeys: {
248
+ ...previous.rowKeys,
249
+ [path]: (previous.rowKeys[path] ?? []).filter((candidate) => candidate !== key)
250
+ },
251
+ clientErrors: shiftRecord(previous.clientErrors, path, index),
252
+ edited: shiftSet(previous.edited, path, index)
236
253
  }));
237
- setClientErrors((previous) => shiftRecord(previous, path, index));
238
- setEdited((previous) => shiftSet(previous, path, index));
239
254
  };
240
255
  return {
241
256
  rows: keys.map((key, index) => ({
@@ -253,9 +268,12 @@ const useForm = (fields, state = {}) => {
253
268
  add: () => {
254
269
  nextKey.current += 1;
255
270
  const key = `${path}-new-${String(nextKey.current)}`;
256
- setRowKeys((previous) => ({
271
+ setNotes((previous) => ({
257
272
  ...previous,
258
- [path]: [...previous[path] ?? [], key]
273
+ rowKeys: {
274
+ ...previous.rowKeys,
275
+ [path]: [...previous.rowKeys[path] ?? [], key]
276
+ }
259
277
  }));
260
278
  },
261
279
  canAdd: derived.maxItems === void 0 || keys.length < derived.maxItems,
@@ -303,7 +321,8 @@ const useForm = (fields, state = {}) => {
303
321
  field,
304
322
  array,
305
323
  formError,
306
- isDirty: domDirty || structuralDirty
324
+ isDirty: domDirty || structuralDirty,
325
+ revalidate
307
326
  };
308
327
  };
309
328
  /**
package/docs/GUIDE.md CHANGED
@@ -546,11 +546,17 @@ answer.
546
546
 
547
547
  `check` receives the field's value and resolves to the message to show, or to
548
548
  `undefined` when the value is fine. A rejected promise applies no verdict
549
- either way; the server still checks the submission.
549
+ either way; the server still checks the submission, and what it rejected with
550
+ goes to `reportError`, which reports it the way an uncaught error is.
551
+
552
+ The answer lands after the blur, so `useAsyncCheck` is handed
553
+ `form.revalidate`, which reads a control's validity again and shows what it
554
+ says, as leaving the control does. Anything else that changes a control's
555
+ validity outside an event can call it the same way.
550
556
 
551
557
  ```tsx
552
558
  const slug = form.field('slug');
553
- const taken = useAsyncCheck(checkSlugAvailable); // a Server Action
559
+ const taken = useAsyncCheck(checkSlugAvailable, form.revalidate); // a Server Action
554
560
 
555
561
  <input {...slug.input} {...taken.props} />;
556
562
  <button disabled={taken.isChecking} type="submit">
package/docs/llms.txt CHANGED
@@ -41,13 +41,14 @@ row. Rules cannot target fields inside repeated rows.
41
41
  `invalid` / `required`, an `array(path)` accessor for repeated rows (its
42
42
  `error` is the array's own message, with `errorProps` to let focus land on
43
43
  it), `formError` (the message no field owns, with the props that let focus
44
- land on it), and `isDirty`. On submit it checks every field — untouched ones
44
+ land on it), `isDirty`, and `revalidate(control)`, which reads a control's
45
+ validity again and shows what it says, as leaving it does. On submit it checks every field — untouched ones
45
46
  and the rules included — and stops a failing submission, a GET form with no
46
47
  action as much as one with (a `formNoValidate` button skips the check);
47
48
  after a submission stopped here or failed on the server, focus moves to the
48
49
  first failure in document order, and a first failure the hook has no
49
50
  message for (a control outside the schema) is reported by the browser
50
- itself through `reportValidity()`. Also `useAsyncCheck` for server-answered
51
+ itself through `reportValidity()`. Also `useAsyncCheck(check, form.revalidate)` for server-answered
51
52
  per-field checks and `HiddenValue` for components that render no input of
52
53
  their own. The types
53
54
  of the `formFields` result (`FormFields`, `DerivedField`, `DerivedArray`,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@k8ordo/form",
3
- "version": "1.4.3",
3
+ "version": "2.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,7 +43,7 @@
43
43
  },
44
44
  "devDependencies": {
45
45
  "@arethetypeswrong/cli": "0.18.5",
46
- "@k8ordo/state": "^1.4.3",
46
+ "@k8ordo/state": "^2.0.0",
47
47
  "@types/react": "19.3.0",
48
48
  "@vitejs/plugin-react": "6.1.2",
49
49
  "@vitest/browser-playwright": "5.0.5",