@canonical/svelte-ds-global-form 0.48.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 (59) hide show
  1. package/README.md +213 -8
  2. package/dist/component/CheckboxField/CheckboxField.svelte +21 -3
  3. package/dist/component/CheckboxField/CheckboxField.svelte.d.ts +2 -2
  4. package/dist/component/CheckboxField/types.d.ts +13 -1
  5. package/dist/component/ChoicesField/Choices.svelte +5 -3
  6. package/dist/component/RichChoicesField/RichChoices.svelte +5 -3
  7. package/dist/index.d.ts +2 -2
  8. package/dist/index.js +1 -1
  9. package/dist/pattern/Field/Field.svelte +20 -4
  10. package/dist/pattern/Field/types.d.ts +1 -1
  11. package/dist/subcomponent/CheckboxInput/CheckboxInput.svelte +18 -2
  12. package/dist/subcomponent/CheckboxInput/CheckboxInput.svelte.d.ts +4 -2
  13. package/dist/subcomponent/CheckboxInput/types.d.ts +7 -0
  14. package/dist/subcomponent/RadioInput/RadioInput.svelte +28 -4
  15. package/dist/subcomponent/RadioInput/RadioInput.svelte.d.ts +4 -2
  16. package/dist/subcomponent/RadioInput/types.d.ts +7 -0
  17. package/dist/utils/index.d.ts +3 -0
  18. package/dist/utils/index.js +3 -0
  19. package/dist/utils/owner/bindField.d.ts +5 -3
  20. package/dist/utils/owner/bindField.js +3 -1
  21. package/dist/utils/owner/bindFieldArray.d.ts +20 -0
  22. package/dist/utils/owner/bindFieldArray.js +62 -0
  23. package/dist/utils/owner/bindTanStackForm.d.ts +18 -0
  24. package/dist/utils/owner/bindTanStackForm.js +65 -0
  25. package/dist/utils/owner/createBinding.js +6 -0
  26. package/dist/utils/owner/createFormState.svelte.d.ts +12 -3
  27. package/dist/utils/owner/createFormState.svelte.js +43 -21
  28. package/dist/utils/owner/createSchemaValidator.d.ts +21 -0
  29. package/dist/utils/owner/createSchemaValidator.js +36 -0
  30. package/dist/utils/owner/createValidatedBinding.d.ts +2 -2
  31. package/dist/utils/owner/createValidatedBinding.js +8 -4
  32. package/dist/utils/owner/getPath.d.ts +6 -0
  33. package/dist/utils/owner/getPath.js +15 -0
  34. package/dist/utils/owner/index.d.ts +8 -0
  35. package/dist/utils/owner/index.js +8 -0
  36. package/dist/utils/owner/normalizePath.d.ts +6 -0
  37. package/dist/utils/owner/normalizePath.js +9 -0
  38. package/dist/utils/owner/readOwnerValue.d.ts +7 -0
  39. package/dist/utils/owner/readOwnerValue.js +11 -0
  40. package/dist/utils/owner/setPath.d.ts +12 -0
  41. package/dist/utils/owner/setPath.js +36 -0
  42. package/dist/utils/owner/splitPath.d.ts +7 -0
  43. package/dist/utils/owner/splitPath.js +9 -0
  44. package/dist/utils/owner/types.d.ts +141 -12
  45. package/dist/utils/remoteForm/bindRemoteField.d.ts +23 -0
  46. package/dist/utils/remoteForm/bindRemoteField.js +68 -0
  47. package/dist/utils/remoteForm/bindRemoteForm.d.ts +20 -0
  48. package/dist/utils/remoteForm/bindRemoteForm.js +31 -0
  49. package/dist/utils/remoteForm/constants.d.ts +42 -0
  50. package/dist/utils/remoteForm/constants.js +42 -0
  51. package/dist/utils/remoteForm/index.d.ts +3 -0
  52. package/dist/utils/remoteForm/index.js +2 -0
  53. package/dist/utils/remoteForm/types.d.ts +90 -0
  54. package/dist/utils/remoteForm/types.js +1 -0
  55. package/package.json +23 -11
  56. /package/dist/{component/ChoicesField → utils}/isChoiceChecked.d.ts +0 -0
  57. /package/dist/{component/ChoicesField → utils}/isChoiceChecked.js +0 -0
  58. /package/dist/{component/ChoicesField → utils}/toggleChoice.d.ts +0 -0
  59. /package/dist/{component/ChoicesField → utils}/toggleChoice.js +0 -0
@@ -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);
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Reads the value at a field's path in nested values, as `address.city` or
3
+ * `contacts[0].email`. Returns `undefined` when the path stops early.
4
+ * @note Pure.
5
+ */
6
+ export default function getPath(values: unknown, name: string): unknown;
@@ -0,0 +1,15 @@
1
+ import splitPath from "./splitPath.js";
2
+ /**
3
+ * Reads the value at a field's path in nested values, as `address.city` or
4
+ * `contacts[0].email`. Returns `undefined` when the path stops early.
5
+ * @note Pure.
6
+ */
7
+ export default function getPath(values, name) {
8
+ let current = values;
9
+ for (const segment of splitPath(name)) {
10
+ if (typeof current !== "object" || current === null)
11
+ return undefined;
12
+ current = current[segment];
13
+ }
14
+ return current;
15
+ }
@@ -1,7 +1,15 @@
1
1
  export { default as bindField } from "./bindField.js";
2
+ export { default as bindFieldArray } from "./bindFieldArray.js";
3
+ export { default as bindTanStackForm } from "./bindTanStackForm.js";
2
4
  export { default as createBinding } from "./createBinding.js";
3
5
  export { default as createFormState } from "./createFormState.svelte.js";
6
+ export { default as createSchemaValidator } from "./createSchemaValidator.js";
4
7
  export { default as createValidatedBinding } from "./createValidatedBinding.js";
5
8
  export { getFormOwnerContext, setFormOwnerContext, } from "./formOwnerContext.js";
9
+ export { default as getPath } from "./getPath.js";
10
+ export { default as normalizePath } from "./normalizePath.js";
11
+ export { default as readOwnerValue } from "./readOwnerValue.js";
6
12
  export { default as runLatest } from "./runLatest.js";
13
+ export { default as setPath } from "./setPath.js";
14
+ export { default as splitPath } from "./splitPath.js";
7
15
  export type * from "./types.js";
@@ -1,6 +1,14 @@
1
1
  export { default as bindField } from "./bindField.js";
2
+ export { default as bindFieldArray } from "./bindFieldArray.js";
3
+ export { default as bindTanStackForm } from "./bindTanStackForm.js";
2
4
  export { default as createBinding } from "./createBinding.js";
3
5
  export { default as createFormState } from "./createFormState.svelte.js";
6
+ export { default as createSchemaValidator } from "./createSchemaValidator.js";
4
7
  export { default as createValidatedBinding } from "./createValidatedBinding.js";
5
8
  export { getFormOwnerContext, setFormOwnerContext, } from "./formOwnerContext.js";
9
+ export { default as getPath } from "./getPath.js";
10
+ export { default as normalizePath } from "./normalizePath.js";
11
+ export { default as readOwnerValue } from "./readOwnerValue.js";
6
12
  export { default as runLatest } from "./runLatest.js";
13
+ export { default as setPath } from "./setPath.js";
14
+ export { default as splitPath } from "./splitPath.js";
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Writes a field name in one form, its segments joined with `.`, so both path
3
+ * forms name one field: `contacts[0].email` gives `contacts.0.email`.
4
+ * @note Pure.
5
+ */
6
+ export default function normalizePath(name: string): string;
@@ -0,0 +1,9 @@
1
+ import splitPath from "./splitPath.js";
2
+ /**
3
+ * Writes a field name in one form, its segments joined with `.`, so both path
4
+ * forms name one field: `contacts[0].email` gives `contacts.0.email`.
5
+ * @note Pure.
6
+ */
7
+ export default function normalizePath(name) {
8
+ return splitPath(name).join(".");
9
+ }
@@ -0,0 +1,7 @@
1
+ import type { FormOwner, FormValues, Path, PathValue } from "./types.js";
2
+ /**
3
+ * Reads a field's value from an owner: through its `getValue` when it has
4
+ * one, or by reading the path in its `values`.
5
+ * @note Pure.
6
+ */
7
+ export default function readOwnerValue<Values extends FormValues, Name extends Path<Values>>(owner: FormOwner<Values>, name: Name): PathValue<Values, Name> | undefined;
@@ -0,0 +1,11 @@
1
+ import getPath from "./getPath.js";
2
+ /**
3
+ * Reads a field's value from an owner: through its `getValue` when it has
4
+ * one, or by reading the path in its `values`.
5
+ * @note Pure.
6
+ */
7
+ export default function readOwnerValue(owner, name) {
8
+ return owner.getValue
9
+ ? owner.getValue(name)
10
+ : getPath(owner.values, name);
11
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Writes the value at a field's path in nested values, as `address.city` or
3
+ * `contacts[0].email`, creating the objects along the path, or an array where
4
+ * the next segment is an index. Writing `undefined` drops the key, or leaves
5
+ * an array's slot `undefined` so the later items keep their indices; it
6
+ * creates nothing on the way.
7
+ *
8
+ * Each container is read back after it is created, so a `$state` proxy is
9
+ * written through and stays reactive.
10
+ * @note Impure: mutates `values` in place.
11
+ */
12
+ export default function setPath(values: Record<string, unknown>, name: string, value: unknown): void;
@@ -0,0 +1,36 @@
1
+ import splitPath from "./splitPath.js";
2
+ /** Tells whether a path segment is an array index. */
3
+ const isIndex = (segment) => /^\d+$/.test(segment);
4
+ /**
5
+ * Writes the value at a field's path in nested values, as `address.city` or
6
+ * `contacts[0].email`, creating the objects along the path, or an array where
7
+ * the next segment is an index. Writing `undefined` drops the key, or leaves
8
+ * an array's slot `undefined` so the later items keep their indices; it
9
+ * creates nothing on the way.
10
+ *
11
+ * Each container is read back after it is created, so a `$state` proxy is
12
+ * written through and stays reactive.
13
+ * @note Impure: mutates `values` in place.
14
+ */
15
+ export default function setPath(values, name, value) {
16
+ const segments = splitPath(name);
17
+ const last = segments.pop();
18
+ if (last === undefined)
19
+ return;
20
+ let parent = values;
21
+ for (const [index, segment] of segments.entries()) {
22
+ if (typeof parent[segment] !== "object" || parent[segment] === null) {
23
+ if (value === undefined)
24
+ return;
25
+ const next = segments.at(index + 1) ?? last;
26
+ parent[segment] = isIndex(next) ? [] : {};
27
+ }
28
+ parent = parent[segment];
29
+ }
30
+ if (value !== undefined)
31
+ parent[last] = value;
32
+ else if (Array.isArray(parent))
33
+ parent[last] = undefined;
34
+ else
35
+ delete parent[last];
36
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Splits a field name into its path segments. Both react-hook-form's dotted
3
+ * form and SvelteKit's bracket form are read: `contacts.0.email` and
4
+ * `contacts[0].email` both give `["contacts", "0", "email"]`.
5
+ * @note Pure.
6
+ */
7
+ export default function splitPath(name: string): string[];
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Splits a field name into its path segments. Both react-hook-form's dotted
3
+ * form and SvelteKit's bracket form are read: `contacts.0.email` and
4
+ * `contacts[0].email` both give `["contacts", "0", "email"]`.
5
+ * @note Pure.
6
+ */
7
+ export default function splitPath(name) {
8
+ return name.split(/[.[\]]+/).filter((segment) => segment !== "");
9
+ }