@canonical/svelte-ds-global-form 0.47.0 → 0.49.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/LICENSE +166 -0
  2. package/README.md +213 -8
  3. package/dist/component/CheckboxField/CheckboxField.svelte +21 -3
  4. package/dist/component/CheckboxField/CheckboxField.svelte.d.ts +2 -2
  5. package/dist/component/CheckboxField/types.d.ts +13 -1
  6. package/dist/component/ChoicesField/Choices.svelte +5 -3
  7. package/dist/component/RichChoicesField/RichChoices.svelte +5 -3
  8. package/dist/index.d.ts +2 -2
  9. package/dist/index.js +1 -1
  10. package/dist/pattern/Field/Field.svelte +20 -4
  11. package/dist/pattern/Field/types.d.ts +1 -1
  12. package/dist/subcomponent/CheckboxInput/CheckboxInput.svelte +18 -2
  13. package/dist/subcomponent/CheckboxInput/CheckboxInput.svelte.d.ts +4 -2
  14. package/dist/subcomponent/CheckboxInput/types.d.ts +7 -0
  15. package/dist/subcomponent/RadioInput/RadioInput.svelte +28 -4
  16. package/dist/subcomponent/RadioInput/RadioInput.svelte.d.ts +4 -2
  17. package/dist/subcomponent/RadioInput/types.d.ts +7 -0
  18. package/dist/utils/index.d.ts +3 -0
  19. package/dist/utils/index.js +3 -0
  20. package/dist/utils/owner/bindField.d.ts +5 -3
  21. package/dist/utils/owner/bindField.js +3 -1
  22. package/dist/utils/owner/bindFieldArray.d.ts +20 -0
  23. package/dist/utils/owner/bindFieldArray.js +62 -0
  24. package/dist/utils/owner/bindTanStackForm.d.ts +18 -0
  25. package/dist/utils/owner/bindTanStackForm.js +65 -0
  26. package/dist/utils/owner/createBinding.js +6 -0
  27. package/dist/utils/owner/createFormState.svelte.d.ts +12 -3
  28. package/dist/utils/owner/createFormState.svelte.js +43 -21
  29. package/dist/utils/owner/createSchemaValidator.d.ts +21 -0
  30. package/dist/utils/owner/createSchemaValidator.js +36 -0
  31. package/dist/utils/owner/createValidatedBinding.d.ts +2 -2
  32. package/dist/utils/owner/createValidatedBinding.js +8 -4
  33. package/dist/utils/owner/getPath.d.ts +6 -0
  34. package/dist/utils/owner/getPath.js +15 -0
  35. package/dist/utils/owner/index.d.ts +8 -0
  36. package/dist/utils/owner/index.js +8 -0
  37. package/dist/utils/owner/normalizePath.d.ts +6 -0
  38. package/dist/utils/owner/normalizePath.js +9 -0
  39. package/dist/utils/owner/readOwnerValue.d.ts +7 -0
  40. package/dist/utils/owner/readOwnerValue.js +11 -0
  41. package/dist/utils/owner/setPath.d.ts +12 -0
  42. package/dist/utils/owner/setPath.js +36 -0
  43. package/dist/utils/owner/splitPath.d.ts +7 -0
  44. package/dist/utils/owner/splitPath.js +9 -0
  45. package/dist/utils/owner/types.d.ts +141 -12
  46. package/dist/utils/remoteForm/bindRemoteField.d.ts +23 -0
  47. package/dist/utils/remoteForm/bindRemoteField.js +68 -0
  48. package/dist/utils/remoteForm/bindRemoteForm.d.ts +20 -0
  49. package/dist/utils/remoteForm/bindRemoteForm.js +31 -0
  50. package/dist/utils/remoteForm/constants.d.ts +42 -0
  51. package/dist/utils/remoteForm/constants.js +42 -0
  52. package/dist/utils/remoteForm/index.d.ts +3 -0
  53. package/dist/utils/remoteForm/index.js +2 -0
  54. package/dist/utils/remoteForm/types.d.ts +90 -0
  55. package/dist/utils/remoteForm/types.js +1 -0
  56. package/package.json +24 -11
  57. /package/dist/{component/ChoicesField → utils}/isChoiceChecked.d.ts +0 -0
  58. /package/dist/{component/ChoicesField → utils}/isChoiceChecked.js +0 -0
  59. /package/dist/{component/ChoicesField → utils}/toggleChoice.d.ts +0 -0
  60. /package/dist/{component/ChoicesField → utils}/toggleChoice.js +0 -0
@@ -1,4 +1,5 @@
1
1
  <script lang="ts">
2
+ import { isChoiceChecked, toggleChoice } from "../../utils/index.js";
2
3
  import type { CheckboxInputProps } from "./types.js";
3
4
  import "./styles.css";
4
5
 
@@ -9,14 +10,29 @@
9
10
  class: className,
10
11
  style,
11
12
  checked = $bindable(),
13
+ group = $bindable(),
12
14
  ...rest
13
15
  }: CheckboxInputProps = $props();
16
+
17
+ // The value the checkbox posts, and adds to `group` when checked.
18
+ const choice = $derived(String(rest.value ?? "on"));
19
+
20
+ // With a `group`, the checkbox is checked while the group holds its value,
21
+ // and checking it adds the value to the group, as Svelte's `bind:group`.
22
+ const readChecked = () =>
23
+ group === undefined ? checked : isChoiceChecked(group, choice, true);
24
+ const writeChecked = (next: boolean | undefined) => {
25
+ if (group === undefined) checked = next;
26
+ else group = toggleChoice(group, choice, Boolean(next), true) as string[];
27
+ };
14
28
  </script>
15
29
 
16
- <input {id} {style} class={[componentCssClassName, className]} bind:checked {...rest} type="checkbox" />
30
+ <input {id} {style} class={[componentCssClassName, className]} bind:checked={readChecked, writeChecked} {...rest} type="checkbox" />
17
31
 
18
32
  <!-- @component
19
- Presentational checkbox. Bind `checked` for two-way binding.
33
+ Presentational checkbox. Bind `checked` for two-way binding, or bind `group`
34
+ to an array shared by several checkboxes, which holds the `value` of each
35
+ checked one, as Svelte's `bind:group` does for inputs in one component.
20
36
 
21
37
  `import { CheckboxInput } from "@canonical/svelte-ds-global-form";`
22
38
 
@@ -1,12 +1,14 @@
1
1
  import type { CheckboxInputProps } from "./types.js";
2
2
  import "./styles.css";
3
3
  /**
4
- * Presentational checkbox. Bind `checked` for two-way binding.
4
+ * Presentational checkbox. Bind `checked` for two-way binding, or bind `group`
5
+ * to an array shared by several checkboxes, which holds the `value` of each
6
+ * checked one, as Svelte's `bind:group` does for inputs in one component.
5
7
  *
6
8
  * `import { CheckboxInput } from "@canonical/svelte-ds-global-form";`
7
9
  *
8
10
  * @implements ds:global.subcomponent.checkbox_input
9
11
  */
10
- declare const CheckboxInput: import("svelte").Component<CheckboxInputProps, {}, "checked">;
12
+ declare const CheckboxInput: import("svelte").Component<CheckboxInputProps, {}, "group" | "checked">;
11
13
  type CheckboxInput = ReturnType<typeof CheckboxInput>;
12
14
  export default CheckboxInput;
@@ -3,4 +3,11 @@ import type { HTMLInputAttributes } from "svelte/elements";
3
3
  export type CheckboxInputProps = Omit<HTMLInputAttributes, "type"> & {
4
4
  /** Whether the checkbox is checked. Bindable. */
5
5
  checked?: boolean;
6
+ /**
7
+ * The values of the checked checkboxes of a group: the checkbox is checked
8
+ * while it holds `value`, and checking or unchecking it adds or removes
9
+ * `value`. Start it as an array; `checked` is ignored while it is set.
10
+ * Bindable.
11
+ */
12
+ group?: string[];
6
13
  };
@@ -10,10 +10,16 @@
10
10
  class: className,
11
11
  style,
12
12
  checked = $bindable(),
13
+ group = $bindable(),
13
14
  onchange,
14
15
  ...rest
15
16
  }: RadioInputProps = $props();
16
17
 
18
+ // The value the radio posts, and sets `group` to when selected.
19
+ const choice = $derived(String(rest.value ?? "on"));
20
+ // With a `group`, the radio is selected while the group holds its value.
21
+ const isSelected = $derived(group === undefined ? checked : group === choice);
22
+
17
23
  // Keeps a selection made before hydration: a pre-effect runs once, in the
18
24
  // browser, before the `checked` property below is written to the
19
25
  // server-rendered input.
@@ -24,14 +30,29 @@
24
30
  inputElement instanceof HTMLInputElement &&
25
31
  inputElement.checked !== inputElement.defaultChecked
26
32
  )
27
- checked = inputElement.checked;
33
+ select(inputElement.checked);
28
34
  });
29
35
  });
30
36
 
37
+ /** Records the radio's selection, and sets the group to it when selected. */
38
+ function select(isChecked: boolean): void {
39
+ checked = isChecked;
40
+ if (group !== undefined && isChecked) group = choice;
41
+ }
42
+
43
+ // A radio is unchecked silently when a sibling is chosen. A group changed
44
+ // away and back before the page updates leaves `isSelected` as it was, so
45
+ // the `checked` attribute is not written again: every write to the group
46
+ // writes the property.
47
+ const syncChecked = (inputElement: HTMLInputElement) => {
48
+ void group;
49
+ inputElement.checked = untrack(() => isSelected === true);
50
+ };
51
+
31
52
  // A radio is checked by its own change event, but unchecked silently when a
32
53
  // sibling is chosen, so `checked` reports selection rather than tracking it.
33
54
  const handleChange = (event: Event & { currentTarget: HTMLInputElement }) => {
34
- checked = event.currentTarget.checked;
55
+ select(event.currentTarget.checked);
35
56
  onchange?.(event);
36
57
  };
37
58
  </script>
@@ -40,15 +61,18 @@
40
61
  {id}
41
62
  {style}
42
63
  class={[componentCssClassName, className]}
43
- {checked}
64
+ checked={isSelected}
44
65
  onchange={handleChange}
66
+ {@attach syncChecked}
45
67
  {...rest}
46
68
  type="radio"
47
69
  />
48
70
 
49
71
  <!-- @component
50
72
  Presentational radio: the atomic single-select indicator, with no label of its
51
- own. Bind `checked` to learn when it is selected.
73
+ own. Bind `checked` to learn when it is selected, or bind `group` to a string
74
+ shared by several radios, which holds the `value` of the selected one, as
75
+ Svelte's `bind:group` does for inputs in one component.
52
76
 
53
77
  `import { RadioInput } from "@canonical/svelte-ds-global-form";`
54
78
 
@@ -2,12 +2,14 @@ import type { RadioInputProps } from "./types.js";
2
2
  import "./styles.css";
3
3
  /**
4
4
  * Presentational radio: the atomic single-select indicator, with no label of its
5
- * own. Bind `checked` to learn when it is selected.
5
+ * own. Bind `checked` to learn when it is selected, or bind `group` to a string
6
+ * shared by several radios, which holds the `value` of the selected one, as
7
+ * Svelte's `bind:group` does for inputs in one component.
6
8
  *
7
9
  * `import { RadioInput } from "@canonical/svelte-ds-global-form";`
8
10
  *
9
11
  * @implements ds:global.subcomponent.radio_input
10
12
  */
11
- declare const RadioInput: import("svelte").Component<RadioInputProps, {}, "checked">;
13
+ declare const RadioInput: import("svelte").Component<RadioInputProps, {}, "group" | "checked">;
12
14
  type RadioInput = ReturnType<typeof RadioInput>;
13
15
  export default RadioInput;
@@ -3,4 +3,11 @@ import type { HTMLInputAttributes } from "svelte/elements";
3
3
  export type RadioInputProps = Omit<HTMLInputAttributes, "type"> & {
4
4
  /** Whether the radio is selected. Bindable. */
5
5
  checked?: boolean;
6
+ /**
7
+ * The selected value of a radio group: the radio is selected while it
8
+ * equals `value`, and selecting it sets it to `value`. Start it as a
9
+ * string, empty when nothing is selected; `checked` is ignored while it is
10
+ * set. Bindable.
11
+ */
12
+ group?: string;
6
13
  };
@@ -1,5 +1,8 @@
1
+ export { default as isChoiceChecked } from "./isChoiceChecked.js";
1
2
  export * from "./middleware/index.js";
2
3
  export * from "./owner/index.js";
3
4
  export * from "./phone/index.js";
4
5
  export { default as readEditedChoices } from "./readEditedChoices.js";
5
6
  export { default as readEditedSelection } from "./readEditedSelection.js";
7
+ export * from "./remoteForm/index.js";
8
+ export { default as toggleChoice } from "./toggleChoice.js";
@@ -1,5 +1,8 @@
1
+ export { default as isChoiceChecked } from "./isChoiceChecked.js";
1
2
  export * from "./middleware/index.js";
2
3
  export * from "./owner/index.js";
3
4
  export * from "./phone/index.js";
4
5
  export { default as readEditedChoices } from "./readEditedChoices.js";
5
6
  export { default as readEditedSelection } from "./readEditedSelection.js";
7
+ export * from "./remoteForm/index.js";
8
+ export { default as toggleChoice } from "./toggleChoice.js";
@@ -1,4 +1,4 @@
1
- import type { FieldBinding, FormOwner, FormValues } from "./types.js";
1
+ import type { FieldBinding, FormOwner, FormValues, Path } from "./types.js";
2
2
  /**
3
3
  * Returns a field's error and blur handler from an owner, to
4
4
  * spread onto a `Field` or field component outside a `Form` with that owner.
@@ -10,7 +10,9 @@ import type { FieldBinding, FormOwner, FormValues } from "./types.js";
10
10
  * {...bindField(owner, "email")} />
11
11
  * ```
12
12
  *
13
- * The properties are getters, so the spread stays reactive.
13
+ * A nested name reads and writes its path, as `address.city`; read the value
14
+ * with `owner.getValue` when the owner has it. The properties are getters, so
15
+ * the spread stays reactive.
14
16
  * @note Pure.
15
17
  */
16
- export default function bindField<Values extends FormValues>(owner: FormOwner<Values>, name: keyof Values & string): FieldBinding;
18
+ export default function bindField<Values extends FormValues>(owner: FormOwner<Values>, name: Path<Values>): FieldBinding;
@@ -9,7 +9,9 @@
9
9
  * {...bindField(owner, "email")} />
10
10
  * ```
11
11
  *
12
- * The properties are getters, so the spread stays reactive.
12
+ * A nested name reads and writes its path, as `address.city`; read the value
13
+ * with `owner.getValue` when the owner has it. The properties are getters, so
14
+ * the spread stays reactive.
13
15
  * @note Pure.
14
16
  */
15
17
  export default function bindField(owner, name) {
@@ -0,0 +1,20 @@
1
+ import type { FieldArray, FieldArrayItem, FormOwner, FormValues, Path } from "./types.js";
2
+ /**
3
+ * Binds a list of repeated fields to the array at `name` in an owner, as
4
+ * react-hook-form's `useFieldArray`. `items` gives each item a key that stays
5
+ * with it across `move` and `remove`, for a keyed `{#each}`; the fields inside
6
+ * are named by index:
7
+ *
8
+ * ```svelte
9
+ * {#each contacts.items as item, index (item.key)}
10
+ * <Field inputType="email" name={`contacts.${index}.email`} label="Email" />
11
+ * {/each}
12
+ * ```
13
+ *
14
+ * Every change writes the whole array through `owner.setValue`, so the
15
+ * owner's validation mode applies to it. A change made elsewhere, such as a
16
+ * `reset`, keeps the keys of the items still in place and adds keys for new
17
+ * ones.
18
+ * @note Pure: the returned binding holds only its items' keys.
19
+ */
20
+ export default function bindFieldArray<Values extends FormValues, Name extends Path<Values>>(owner: FormOwner<Values>, name: Name): FieldArray<FieldArrayItem<Values, Name>>;
@@ -0,0 +1,62 @@
1
+ import readOwnerValue from "./readOwnerValue.js";
2
+ /**
3
+ * Binds a list of repeated fields to the array at `name` in an owner, as
4
+ * react-hook-form's `useFieldArray`. `items` gives each item a key that stays
5
+ * with it across `move` and `remove`, for a keyed `{#each}`; the fields inside
6
+ * are named by index:
7
+ *
8
+ * ```svelte
9
+ * {#each contacts.items as item, index (item.key)}
10
+ * <Field inputType="email" name={`contacts.${index}.email`} label="Email" />
11
+ * {/each}
12
+ * ```
13
+ *
14
+ * Every change writes the whole array through `owner.setValue`, so the
15
+ * owner's validation mode applies to it. A change made elsewhere, such as a
16
+ * `reset`, keeps the keys of the items still in place and adds keys for new
17
+ * ones.
18
+ * @note Pure: the returned binding holds only its items' keys.
19
+ */
20
+ export default function bindFieldArray(owner, name) {
21
+ const keys = [];
22
+ let nextKey = 0;
23
+ /** Reads the array, and matches the keys to its length. */
24
+ function readItems() {
25
+ const current = readOwnerValue(owner, name);
26
+ const items = Array.isArray(current) ? current : [];
27
+ keys.length = Math.min(keys.length, items.length);
28
+ while (keys.length < items.length)
29
+ keys.push(String(nextKey++));
30
+ return items;
31
+ }
32
+ /** Writes the array through the owner. */
33
+ function write(items) {
34
+ owner.setValue(name, items);
35
+ }
36
+ return {
37
+ get items() {
38
+ return readItems().map((value, index) => ({
39
+ key: keys.at(index),
40
+ value,
41
+ }));
42
+ },
43
+ append(value) {
44
+ write([...readItems(), value]);
45
+ },
46
+ remove(index) {
47
+ const items = readItems();
48
+ keys.splice(index, 1);
49
+ write(items.filter((_, at) => at !== index));
50
+ },
51
+ move(from, to) {
52
+ const items = [...readItems()];
53
+ items.splice(to, 0, ...items.splice(from, 1));
54
+ keys.splice(to, 0, ...keys.splice(from, 1));
55
+ write(items);
56
+ },
57
+ replace(values) {
58
+ keys.length = 0;
59
+ write([...values]);
60
+ },
61
+ };
62
+ }
@@ -0,0 +1,18 @@
1
+ import type { FormValues, ResettableOwner, TanStackFormApi } from "./types.js";
2
+ /**
3
+ * Makes a TanStack Form instance a form owner, for a `Form` or `bindField`:
4
+ *
5
+ * ```svelte
6
+ * <Form owner={bindTanStackForm(form)}>
7
+ * ```
8
+ *
9
+ * Values, including nested ones, are read with TanStack's own path read and
10
+ * written with `setFieldValue`. A field shows its first error: the `message`
11
+ * of a schema issue, or a validator's string. Leaving a field marks it
12
+ * blurred and runs the `onBlur` validators. A submit runs `handleSubmit`,
13
+ * which validates and calls the form's `onSubmit`, instead of posting, and
14
+ * `reset` resets the form. TanStack keys an index in brackets
15
+ * (`contacts[0].email`); either path form may name a field.
16
+ * @note Pure: subscribes to the form only while an effect reads the owner.
17
+ */
18
+ export default function bindTanStackForm<Values extends FormValues>(form: TanStackFormApi<Values>): ResettableOwner<Values>;
@@ -0,0 +1,65 @@
1
+ import createBinding from "./createBinding.js";
2
+ import splitPath from "./splitPath.js";
3
+ /**
4
+ * Writes a field name as TanStack Form keys its fields and errors: an index
5
+ * in brackets, as `contacts[0].email`, whichever path form it is given.
6
+ */
7
+ const formatTanStackName = (name) => splitPath(name)
8
+ .map((segment, index) => /^\d+$/.test(segment)
9
+ ? `[${segment}]`
10
+ : index === 0
11
+ ? segment
12
+ : `.${segment}`)
13
+ .join("");
14
+ /** Returns the message of a TanStack error: a schema issue or a string. */
15
+ const readMessage = (error) => typeof error === "string"
16
+ ? error
17
+ : error?.message;
18
+ /**
19
+ * Makes a TanStack Form instance a form owner, for a `Form` or `bindField`:
20
+ *
21
+ * ```svelte
22
+ * <Form owner={bindTanStackForm(form)}>
23
+ * ```
24
+ *
25
+ * Values, including nested ones, are read with TanStack's own path read and
26
+ * written with `setFieldValue`. A field shows its first error: the `message`
27
+ * of a schema issue, or a validator's string. Leaving a field marks it
28
+ * blurred and runs the `onBlur` validators. A submit runs `handleSubmit`,
29
+ * which validates and calls the form's `onSubmit`, instead of posting, and
30
+ * `reset` resets the form. TanStack keys an index in brackets
31
+ * (`contacts[0].email`); either path form may name a field.
32
+ * @note Pure: subscribes to the form only while an effect reads the owner.
33
+ */
34
+ export default function bindTanStackForm(form) {
35
+ const owner = createBinding({
36
+ getValues: () => form.state.values,
37
+ getValue: (name) => form.getFieldValue(formatTanStackName(name)),
38
+ setValue: (name, value) => form.setFieldValue(formatTanStackName(name), (() => value)),
39
+ subscribe: (notify) => form.store.subscribe(notify).unsubscribe,
40
+ getError: (name) => readMessage(form.getFieldMeta(formatTanStackName(name))?.errors?.at(0)),
41
+ blur: (name) => {
42
+ const field = formatTanStackName(name);
43
+ form.setFieldMeta(field, ((meta) => ({
44
+ ...meta,
45
+ isBlurred: true,
46
+ })));
47
+ void form.validateField(field, "blur");
48
+ },
49
+ submit: (event) => {
50
+ event.preventDefault();
51
+ void form.handleSubmit();
52
+ },
53
+ });
54
+ return {
55
+ get values() {
56
+ return owner.values;
57
+ },
58
+ getValue: owner.getValue,
59
+ setValue: owner.setValue,
60
+ getError: owner.getError,
61
+ blur: owner.blur,
62
+ submit: owner.submit,
63
+ reset: () => form.reset(),
64
+ };
65
+ }
@@ -12,6 +12,12 @@ export default function createBinding(source) {
12
12
  track();
13
13
  return source.getValues();
14
14
  },
15
+ getValue: source.getValue
16
+ ? (name) => {
17
+ track();
18
+ return source.getValue?.(name);
19
+ }
20
+ : undefined,
15
21
  setValue: (name, value) => source.setValue(name, value),
16
22
  getError: (name) => {
17
23
  track();
@@ -2,16 +2,25 @@ import type { FormState, FormStateOptions, FormValues } from "./types.js";
2
2
  /**
3
3
  * Builds a minimal form owner on `$state`: values, errors and touched fields,
4
4
  * validated by one `validate` function at the time `mode` says, as
5
- * react-hook-form's `useForm`. Pass it to a `Form`:
5
+ * react-hook-form's `useForm`. Names reach into nested values, as
6
+ * `address.city` or `contacts.0.email` (SvelteKit's `contacts[0].email` too):
7
+ * a write creates the objects along the path, or an array where the next
8
+ * segment is an index, and errors and touched fields are keyed by the path
9
+ * joined with `.`, as `createSchemaValidator` keys its messages. Pass it to a `Form`:
6
10
  *
7
11
  * ```svelte
8
12
  * <Form owner={createFormState({ defaultValues, validate, onSubmit })}>
9
13
  * ```
10
14
  *
15
+ * Seed `errors` with messages to show from the start, such as a SvelteKit
16
+ * action's `form.errors` after a post without JavaScript.
17
+ *
11
18
  * On submit, every field is validated. An invalid form does not post and its
12
19
  * first invalid control is focused. A valid form calls `onSubmit` instead of
13
20
  * posting, or posts natively when `onSubmit` is unset. After the first submit,
14
- * a field is validated again on its every change.
21
+ * a field is validated again on its every change. Writing a whole branch, as a
22
+ * field array does, also validates again the messages showing inside it, so
23
+ * they follow the moved items.
15
24
  * @note Pure: the returned owner holds its own state.
16
25
  */
17
- export default function createFormState<Values extends FormValues>({ defaultValues, validate, mode, onSubmit, }?: FormStateOptions<Values>): FormState<Values>;
26
+ export default function createFormState<Values extends FormValues>({ defaultValues, errors: initialErrors, validate, mode, onSubmit, }?: FormStateOptions<Values>): FormState<Values>;
@@ -1,36 +1,56 @@
1
1
  import { tick } from "svelte";
2
+ import getPath from "./getPath.js";
3
+ import normalizePath from "./normalizePath.js";
4
+ import setPath from "./setPath.js";
5
+ /** Tells whether `key` is the field `name` or a field inside it. */
6
+ const isWithin = (key, name) => key === name || key.startsWith(`${name}.`);
2
7
  /**
3
8
  * Builds a minimal form owner on `$state`: values, errors and touched fields,
4
9
  * validated by one `validate` function at the time `mode` says, as
5
- * react-hook-form's `useForm`. Pass it to a `Form`:
10
+ * react-hook-form's `useForm`. Names reach into nested values, as
11
+ * `address.city` or `contacts.0.email` (SvelteKit's `contacts[0].email` too):
12
+ * a write creates the objects along the path, or an array where the next
13
+ * segment is an index, and errors and touched fields are keyed by the path
14
+ * joined with `.`, as `createSchemaValidator` keys its messages. Pass it to a `Form`:
6
15
  *
7
16
  * ```svelte
8
17
  * <Form owner={createFormState({ defaultValues, validate, onSubmit })}>
9
18
  * ```
10
19
  *
20
+ * Seed `errors` with messages to show from the start, such as a SvelteKit
21
+ * action's `form.errors` after a post without JavaScript.
22
+ *
11
23
  * On submit, every field is validated. An invalid form does not post and its
12
24
  * first invalid control is focused. A valid form calls `onSubmit` instead of
13
25
  * posting, or posts natively when `onSubmit` is unset. After the first submit,
14
- * a field is validated again on its every change.
26
+ * a field is validated again on its every change. Writing a whole branch, as a
27
+ * field array does, also validates again the messages showing inside it, so
28
+ * they follow the moved items.
15
29
  * @note Pure: the returned owner holds its own state.
16
30
  */
17
- export default function createFormState({ defaultValues = {}, validate, mode = "onSubmit", onSubmit, } = {}) {
31
+ export default function createFormState({ defaultValues = {}, errors: initialErrors = {}, validate, mode = "onSubmit", onSubmit, } = {}) {
18
32
  const values = $state({ ...defaultValues });
19
- const errors = $state({});
33
+ const errors = $state(Object.fromEntries(Object.entries(initialErrors)
34
+ .filter((entry) => entry[1] !== undefined)
35
+ .map(([name, message]) => [normalizePath(name), message])));
20
36
  const touched = $state({});
21
37
  let isSubmitted = $state(false);
22
38
  let isSubmitting = $state(false);
23
39
  /**
24
- * Validates the form and updates the messages of `names`, or of every field.
25
- * Returns whether the whole form is valid.
40
+ * Validates the form and updates the messages within `names`, or of every
41
+ * field. Returns whether the whole form is valid.
26
42
  */
27
43
  function runValidation(names) {
28
- const found = Object.entries(validate?.($state.snapshot(values)) ?? {}).filter((entry) => entry[1] !== undefined);
29
- for (const name of names ?? Object.keys(errors))
30
- delete errors[name];
31
- for (const [name, message] of found)
32
- if (!names || names.includes(name))
33
- errors[name] = message;
44
+ const found = Object.entries(validate?.($state.snapshot(values)) ?? {})
45
+ .filter((entry) => entry[1] !== undefined)
46
+ .map(([name, message]) => [normalizePath(name), message]);
47
+ const isAffected = (key) => !names || names.some((name) => isWithin(key, name));
48
+ for (const key of Object.keys(errors))
49
+ if (isAffected(key))
50
+ delete errors[key];
51
+ for (const [key, message] of found)
52
+ if (isAffected(key))
53
+ errors[key] = message;
34
54
  return found.length === 0;
35
55
  }
36
56
  /** Empties a `$state` record in place, so its readers stay subscribed. */
@@ -54,21 +74,23 @@ export default function createFormState({ defaultValues = {}, validate, mode = "
54
74
  get isSubmitting() {
55
75
  return isSubmitting;
56
76
  },
77
+ getValue: (name) => getPath(values, name),
57
78
  setValue(name, value) {
58
- if (value === undefined)
59
- delete values[name];
60
- else
61
- values[name] = value;
79
+ const key = normalizePath(name);
80
+ setPath(values, key, value);
81
+ const isBranch = typeof value === "object" && value !== null;
62
82
  if (isSubmitted ||
63
83
  mode === "onChange" ||
64
- (mode === "onTouched" && touched[name]))
65
- runValidation([name]);
84
+ (mode === "onTouched" && touched[key]) ||
85
+ (isBranch && Object.keys(errors).some((shown) => isWithin(shown, key))))
86
+ runValidation([key]);
66
87
  },
67
- getError: (name) => errors[name],
88
+ getError: (name) => errors[normalizePath(name)],
68
89
  blur(name) {
69
- touched[name] = true;
90
+ const key = normalizePath(name);
91
+ touched[key] = true;
70
92
  if (mode === "onBlur" || mode === "onTouched")
71
- runValidation([name]);
93
+ runValidation([key]);
72
94
  },
73
95
  reset() {
74
96
  clear(values);
@@ -0,0 +1,21 @@
1
+ import type { FormErrors, FormValues, StandardSchema } from "./types.js";
2
+ /**
3
+ * Turns a Standard Schema, such as a Zod, Valibot or ArkType schema, into the
4
+ * `validate` function of `createFormState`, as react-hook-form's resolvers
5
+ * do. The values are inferred from the schema's input type:
6
+ *
7
+ * ```ts
8
+ * createFormState({ validate: createSchemaValidator(schema), defaultValues });
9
+ * ```
10
+ *
11
+ * Each message is keyed by its issue's path joined with `.`, and the first
12
+ * message for a path wins. An issue without a path is keyed by `""`, which no
13
+ * field shows: give a whole-form refinement a `path` to show it on a field.
14
+ *
15
+ * `createFormState` validates synchronously, so a schema that validates
16
+ * asynchronously, such as a Zod schema with an `async` refinement, throws a
17
+ * `TypeError` instead of being skipped. Check a value asynchronously with
18
+ * `createValidatedBinding`.
19
+ * @note Pure: the returned function only reads the schema.
20
+ */
21
+ export default function createSchemaValidator<Values extends FormValues>(schema: StandardSchema<Values, unknown>): (values: Readonly<Values>) => FormErrors<Values>;
@@ -0,0 +1,36 @@
1
+ /** Joins an issue's path with `.`, as `address.city` or `contacts.0.email`. */
2
+ function readIssueName({ path = [] }) {
3
+ return path
4
+ .map((segment) => String(typeof segment === "object" ? segment.key : segment))
5
+ .join(".");
6
+ }
7
+ /**
8
+ * Turns a Standard Schema, such as a Zod, Valibot or ArkType schema, into the
9
+ * `validate` function of `createFormState`, as react-hook-form's resolvers
10
+ * do. The values are inferred from the schema's input type:
11
+ *
12
+ * ```ts
13
+ * createFormState({ validate: createSchemaValidator(schema), defaultValues });
14
+ * ```
15
+ *
16
+ * Each message is keyed by its issue's path joined with `.`, and the first
17
+ * message for a path wins. An issue without a path is keyed by `""`, which no
18
+ * field shows: give a whole-form refinement a `path` to show it on a field.
19
+ *
20
+ * `createFormState` validates synchronously, so a schema that validates
21
+ * asynchronously, such as a Zod schema with an `async` refinement, throws a
22
+ * `TypeError` instead of being skipped. Check a value asynchronously with
23
+ * `createValidatedBinding`.
24
+ * @note Pure: the returned function only reads the schema.
25
+ */
26
+ export default function createSchemaValidator(schema) {
27
+ return (values) => {
28
+ const result = schema["~standard"].validate(values);
29
+ if (result instanceof Promise)
30
+ throw new TypeError("createSchemaValidator: the schema validated asynchronously, but createFormState validates synchronously. Check asynchronous rules with createValidatedBinding.");
31
+ const errors = {};
32
+ for (const issue of result.issues ?? [])
33
+ errors[readIssueName(issue)] ??= issue.message;
34
+ return errors;
35
+ };
36
+ }
@@ -1,4 +1,4 @@
1
- import type { FieldValidator, FormValues, ResettableOwner, ValidatedOwner } from "./types.js";
1
+ import type { FieldValidator, FormValues, Path, PathValue, ResettableOwner, ValidatedOwner } from "./types.js";
2
2
  /**
3
3
  * Adds asynchronous field checks to an owner, such as a server lookup. Every
4
4
  * write to a checked field starts its check; the field keeps its previous
@@ -11,5 +11,5 @@ import type { FieldValidator, FormValues, ResettableOwner, ValidatedOwner } from
11
11
  * @note Pure: the returned owner holds the checks' messages and runs.
12
12
  */
13
13
  export default function createValidatedBinding<Values extends FormValues>(owner: ResettableOwner<Values>, validators: {
14
- [Name in keyof Values & string]?: FieldValidator<Values[Name]>;
14
+ [Name in Path<Values>]?: FieldValidator<PathValue<Values, Name>>;
15
15
  }): ValidatedOwner<Values>;
@@ -1,4 +1,6 @@
1
1
  import { SvelteMap } from "svelte/reactivity";
2
+ import normalizePath from "./normalizePath.js";
3
+ import readOwnerValue from "./readOwnerValue.js";
2
4
  import runLatest from "./runLatest.js";
3
5
  /**
4
6
  * Adds asynchronous field checks to an owner, such as a server lookup. Every
@@ -15,11 +17,12 @@ export default function createValidatedBinding(owner, validators) {
15
17
  const messages = new SvelteMap();
16
18
  const pending = new Map();
17
19
  const runners = new Map(Object.entries(validators).map(([name, validator]) => [
18
- name,
20
+ normalizePath(name),
19
21
  runLatest(validator),
20
22
  ]));
21
23
  /** Checks the field's new value; its message changes when the check is done. */
22
- function startValidation(name, value) {
24
+ function startValidation(fieldName, value) {
25
+ const name = normalizePath(fieldName);
23
26
  const runner = runners.get(name);
24
27
  if (!runner)
25
28
  return;
@@ -35,11 +38,12 @@ export default function createValidatedBinding(owner, validators) {
35
38
  });
36
39
  pending.set(name, run);
37
40
  }
38
- const getError = (name) => messages.get(name) ?? owner.getError?.(name);
41
+ const getError = (name) => messages.get(normalizePath(name)) ?? owner.getError?.(name);
39
42
  return {
40
43
  get values() {
41
44
  return owner.values;
42
45
  },
46
+ getValue: owner.getValue?.bind(owner),
43
47
  setValue(name, value) {
44
48
  owner.setValue(name, value);
45
49
  startValidation(name, value);
@@ -61,7 +65,7 @@ export default function createValidatedBinding(owner, validators) {
61
65
  },
62
66
  async validate() {
63
67
  for (const name of runners.keys())
64
- startValidation(name, owner.values[name]);
68
+ startValidation(name, readOwnerValue(owner, name));
65
69
  while (pending.size > 0)
66
70
  await Promise.all(pending.values());
67
71
  return [...runners.keys()].every((name) => getError(name) === undefined);