@canonical/svelte-ds-global-form 0.49.0 → 0.50.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,7 +1,7 @@
1
1
  <script lang="ts">
2
2
  import { untrack } from "svelte";
3
3
  import type { Option } from "../../../subcomponent/types.js";
4
- import runLatest from "../../../utils/owner/runLatest.js";
4
+ import { runLatest } from "../../../utils/index.js";
5
5
  import { List, ResetButton } from "./common/index.js";
6
6
  import { VALUE_KEY } from "./constants.js";
7
7
  import createCombobox from "./createCombobox.svelte.js";
@@ -1,7 +1,7 @@
1
1
  <script lang="ts">
2
2
  import { untrack } from "svelte";
3
3
  import type { Option } from "../../../subcomponent/types.js";
4
- import runLatest from "../../../utils/owner/runLatest.js";
4
+ import { runLatest } from "../../../utils/index.js";
5
5
  import { List, ResetButton } from "./common/index.js";
6
6
  import { VALUE_KEY } from "./constants.js";
7
7
  import createCombobox from "./createCombobox.svelte.js";
@@ -1,5 +1,5 @@
1
1
  import { untrack } from "svelte";
2
- import { getFormOwnerContext } from "../utils/owner/formOwnerContext.js";
2
+ import { getFormOwnerContext } from "../utils/index.js";
3
3
  /**
4
4
  * Decides whether a field is shown. The condition receives the enclosing form
5
5
  * owner's values; outside a form with an owner it receives an empty object and
@@ -1,6 +1,5 @@
1
1
  <script lang="ts" generics="Values extends FormValues = FormValues">
2
- import { setFormOwnerContext } from "../../utils/owner/formOwnerContext.js";
3
- import type { FormValues } from "../../utils/owner/types.js";
2
+ import { type FormValues, setFormOwnerContext } from "../../utils/index.js";
4
3
  import type { FormProps } from "./types.js";
5
4
 
6
5
  const componentCssClassName = "ds form";
@@ -1,4 +1,4 @@
1
- import type { FormValues } from "../../utils/owner/types.js";
1
+ import { type FormValues } from "../../utils/index.js";
2
2
  import type { FormProps } from "./types.js";
3
3
  declare function $$render<Values extends FormValues = FormValues>(): {
4
4
  props: FormProps<Values>;
@@ -1,6 +1,6 @@
1
1
  import type { Snippet } from "svelte";
2
2
  import type { HTMLFormAttributes } from "svelte/elements";
3
- import type { FormOwner, FormValues } from "../../utils/owner/types.js";
3
+ import type { FormOwner, FormValues } from "../../utils/index.js";
4
4
  /**
5
5
  * Props for the Form. Native form attributes (`method`, `action`, …),
6
6
  * handlers and attachments are passed through to the `<form>`.
@@ -9,6 +9,6 @@ import "./styles.css";
9
9
  *
10
10
  * @implements ds:global.subcomponent.checkbox_input
11
11
  */
12
- declare const CheckboxInput: import("svelte").Component<CheckboxInputProps, {}, "group" | "checked">;
12
+ declare const CheckboxInput: import("svelte").Component<CheckboxInputProps, {}, "checked" | "group">;
13
13
  type CheckboxInput = ReturnType<typeof CheckboxInput>;
14
14
  export default CheckboxInput;
@@ -10,6 +10,6 @@ import "./styles.css";
10
10
  *
11
11
  * @implements ds:global.subcomponent.radio_input
12
12
  */
13
- declare const RadioInput: import("svelte").Component<RadioInputProps, {}, "group" | "checked">;
13
+ declare const RadioInput: import("svelte").Component<RadioInputProps, {}, "checked" | "group">;
14
14
  type RadioInput = ReturnType<typeof RadioInput>;
15
15
  export default RadioInput;
@@ -1,5 +1,5 @@
1
1
  import type { Option } from "../../subcomponent/types.js";
2
- import type { FieldValidator } from "../owner/types.js";
2
+ import type { FieldValidator } from "../owner/index.js";
3
3
  /** A control whose value `validateRemotely` checks. */
4
4
  export type ValidatedControl = HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement;
5
5
  /** When `validateRemotely` checks a value, and how long it waits for an answer. */
@@ -1,5 +1,5 @@
1
1
  import { VALIDITY_EVENT } from "../../common/constants.js";
2
- import runLatest from "../owner/runLatest.js";
2
+ import { runLatest } from "../owner/index.js";
3
3
  /** The message shown when the endpoint rejects a value without a readable one. */
4
4
  const DEFAULT_ERROR_MESSAGE = "Validation failed";
5
5
  /**
@@ -12,9 +12,13 @@ import type { FieldArray, FieldArrayItem, FormOwner, FormValues, Path } from "./
12
12
  * ```
13
13
  *
14
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.
15
+ * owner's validation mode applies to it. Before `remove`, `move` and
16
+ * `replace` write, the owner's `reindex`, if any, moves the errors and
17
+ * touched fields kept under the array with their items, as `useFieldArray`
18
+ * does: `remove` drops the removed item's, `move` carries them along,
19
+ * `replace` keeps those within the new length and drops the rest, and
20
+ * `append` adds none. A change made elsewhere, such as a `reset`, keeps the
21
+ * keys of the items still in place and adds keys for new ones.
18
22
  * @note Pure: the returned binding holds only its items' keys.
19
23
  */
20
24
  export default function bindFieldArray<Values extends FormValues, Name extends Path<Values>>(owner: FormOwner<Values>, name: Name): FieldArray<FieldArrayItem<Values, Name>>;
@@ -12,9 +12,13 @@ import readOwnerValue from "./readOwnerValue.js";
12
12
  * ```
13
13
  *
14
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.
15
+ * owner's validation mode applies to it. Before `remove`, `move` and
16
+ * `replace` write, the owner's `reindex`, if any, moves the errors and
17
+ * touched fields kept under the array with their items, as `useFieldArray`
18
+ * does: `remove` drops the removed item's, `move` carries them along,
19
+ * `replace` keeps those within the new length and drops the rest, and
20
+ * `append` adds none. A change made elsewhere, such as a `reset`, keeps the
21
+ * keys of the items still in place and adds keys for new ones.
18
22
  * @note Pure: the returned binding holds only its items' keys.
19
23
  */
20
24
  export default function bindFieldArray(owner, name) {
@@ -29,6 +33,16 @@ export default function bindFieldArray(owner, name) {
29
33
  keys.push(String(nextKey++));
30
34
  return items;
31
35
  }
36
+ /**
37
+ * Tells the owner where each item went: `order` holds the old index of
38
+ * each item, in the new order.
39
+ */
40
+ function reindex(order) {
41
+ owner.reindex?.(name, (index) => {
42
+ const to = order.indexOf(index);
43
+ return to === -1 ? undefined : to;
44
+ });
45
+ }
32
46
  /** Writes the array through the owner. */
33
47
  function write(items) {
34
48
  owner.setValue(name, items);
@@ -46,16 +60,21 @@ export default function bindFieldArray(owner, name) {
46
60
  remove(index) {
47
61
  const items = readItems();
48
62
  keys.splice(index, 1);
63
+ reindex(items.map((_, at) => at).filter((at) => at !== index));
49
64
  write(items.filter((_, at) => at !== index));
50
65
  },
51
66
  move(from, to) {
52
67
  const items = [...readItems()];
68
+ const order = items.map((_, at) => at);
53
69
  items.splice(to, 0, ...items.splice(from, 1));
70
+ order.splice(to, 0, ...order.splice(from, 1));
54
71
  keys.splice(to, 0, ...keys.splice(from, 1));
72
+ reindex(order);
55
73
  write(items);
56
74
  },
57
75
  replace(values) {
58
76
  keys.length = 0;
77
+ reindex(values.map((_, at) => at));
59
78
  write([...values]);
60
79
  },
61
80
  };
@@ -18,9 +18,18 @@ import type { FormState, FormStateOptions, FormValues } from "./types.js";
18
18
  * On submit, every field is validated. An invalid form does not post and its
19
19
  * first invalid control is focused. A valid form calls `onSubmit` instead of
20
20
  * posting, or posts natively when `onSubmit` is unset. After the first submit,
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.
21
+ * a field is validated again on its every change.
22
+ *
23
+ * `validate` may return a promise, as react-hook-form's asynchronous resolvers
24
+ * do. Only the latest validation counts, and `reset` cancels it. A submit that
25
+ * meets one is stopped, since a submit event can only be stopped at once; when
26
+ * the validation settles, a valid form calls `onSubmit`, or is submitted again
27
+ * with the same submitter so it posts (and SvelteKit's `enhance` sees it), and
28
+ * an invalid one focuses its first invalid control. A validation that throws
29
+ * keeps the messages as they are and drops the waiting submit.
30
+ *
31
+ * A field array (`bindFieldArray`) moves the errors and touched fields under
32
+ * its array with the items, through `reindex`, without validating.
24
33
  * @note Pure: the returned owner holds its own state.
25
34
  */
26
35
  export default function createFormState<Values extends FormValues>({ defaultValues, errors: initialErrors, validate, mode, onSubmit, }?: FormStateOptions<Values>): FormState<Values>;
@@ -4,6 +4,29 @@ import normalizePath from "./normalizePath.js";
4
4
  import setPath from "./setPath.js";
5
5
  /** Tells whether `key` is the field `name` or a field inside it. */
6
6
  const isWithin = (key, name) => key === name || key.startsWith(`${name}.`);
7
+ /**
8
+ * Joins the fields two validations update: `undefined` stands for every
9
+ * field.
10
+ */
11
+ const joinScopes = (first, second) => (first && second ? [...first, ...second] : undefined);
12
+ /**
13
+ * Moves a key under the array `prefix` (as `contacts.`) to its item's new
14
+ * index, as `contacts.2.email` to `contacts.1.email`. Returns `undefined` for
15
+ * an item that is gone, and any other key as it is.
16
+ */
17
+ function moveItemKey(key, prefix, toIndex) {
18
+ if (!key.startsWith(prefix))
19
+ return key;
20
+ const [segment, ...rest] = key.slice(prefix.length).split(".");
21
+ if (!/^\d+$/.test(String(segment)))
22
+ return key;
23
+ const index = toIndex(Number(segment));
24
+ return index === undefined ? undefined : [prefix + index, ...rest].join(".");
25
+ }
26
+ /** Focuses the first invalid control of `form`, once its error state renders. */
27
+ function focusFirstInvalid(form) {
28
+ void tick().then(() => form.querySelector('[aria-invalid="true"]')?.focus());
29
+ }
7
30
  /**
8
31
  * Builds a minimal form owner on `$state`: values, errors and touched fields,
9
32
  * validated by one `validate` function at the time `mode` says, as
@@ -23,9 +46,18 @@ const isWithin = (key, name) => key === name || key.startsWith(`${name}.`);
23
46
  * On submit, every field is validated. An invalid form does not post and its
24
47
  * first invalid control is focused. A valid form calls `onSubmit` instead of
25
48
  * posting, or posts natively when `onSubmit` is unset. After the first submit,
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.
49
+ * a field is validated again on its every change.
50
+ *
51
+ * `validate` may return a promise, as react-hook-form's asynchronous resolvers
52
+ * do. Only the latest validation counts, and `reset` cancels it. A submit that
53
+ * meets one is stopped, since a submit event can only be stopped at once; when
54
+ * the validation settles, a valid form calls `onSubmit`, or is submitted again
55
+ * with the same submitter so it posts (and SvelteKit's `enhance` sees it), and
56
+ * an invalid one focuses its first invalid control. A validation that throws
57
+ * keeps the messages as they are and drops the waiting submit.
58
+ *
59
+ * A field array (`bindFieldArray`) moves the errors and touched fields under
60
+ * its array with the items, through `reindex`, without validating.
29
61
  * @note Pure: the returned owner holds its own state.
30
62
  */
31
63
  export default function createFormState({ defaultValues = {}, errors: initialErrors = {}, validate, mode = "onSubmit", onSubmit, } = {}) {
@@ -36,23 +68,106 @@ export default function createFormState({ defaultValues = {}, errors: initialErr
36
68
  const touched = $state({});
37
69
  let isSubmitted = $state(false);
38
70
  let isSubmitting = $state(false);
71
+ let isValidating = $state(false);
72
+ /** Counts the validations started, so a settling one knows if it is the latest. */
73
+ let latestRun = 0;
74
+ /** The fields the running validation updates when it settles. */
75
+ let pendingScope = [];
76
+ /** The submit waiting for the running validation. */
77
+ let pendingSubmit;
78
+ /** Is the form being submitted again after its validation passed. */
79
+ let isApproved = false;
39
80
  /**
40
- * Validates the form and updates the messages within `names`, or of every
41
- * field. Returns whether the whole form is valid.
81
+ * Updates the messages within `scope`, or of every field, from a
82
+ * validation's result. Returns whether the whole form is valid.
42
83
  */
43
- function runValidation(names) {
44
- const found = Object.entries(validate?.($state.snapshot(values)) ?? {})
84
+ function applyErrors(result, scope) {
85
+ const found = Object.entries(result)
45
86
  .filter((entry) => entry[1] !== undefined)
46
87
  .map(([name, message]) => [normalizePath(name), message]);
47
- const isAffected = (key) => !names || names.some((name) => isWithin(key, name));
88
+ const isAffected = (key) => !scope || scope.some((name) => isWithin(key, name));
48
89
  for (const key of Object.keys(errors))
49
90
  if (isAffected(key))
50
91
  delete errors[key];
51
92
  for (const [key, message] of found)
52
93
  if (isAffected(key))
53
94
  errors[key] = message;
95
+ isValidating = false;
54
96
  return found.length === 0;
55
97
  }
98
+ /**
99
+ * Validates the form and updates the messages within `names`, or of every
100
+ * field. A validation that supersedes a running one also updates the fields
101
+ * that one would have. Returns whether the whole form is valid, or
102
+ * `undefined` while an asynchronous validation runs; the submit waiting for
103
+ * it completes when it settles.
104
+ */
105
+ function runValidation(names) {
106
+ const scope = isValidating ? joinScopes(pendingScope, names) : names;
107
+ const run = ++latestRun;
108
+ const result = validate?.($state.snapshot(values)) ?? {};
109
+ if (!(result instanceof Promise)) {
110
+ const isValid = applyErrors(result, scope);
111
+ completeSubmit(isValid);
112
+ return isValid;
113
+ }
114
+ isValidating = true;
115
+ pendingScope = scope;
116
+ void result.then((resolved) => {
117
+ if (run === latestRun)
118
+ completeSubmit(applyErrors(resolved, scope));
119
+ }, () => {
120
+ if (run !== latestRun)
121
+ return;
122
+ isValidating = false;
123
+ pendingSubmit = undefined;
124
+ });
125
+ return undefined;
126
+ }
127
+ /** Calls `handleSubmit` with the values, tracking a promise it returns. */
128
+ function callOnSubmit(handleSubmit) {
129
+ const done = handleSubmit($state.snapshot(values));
130
+ if (!(done instanceof Promise))
131
+ return;
132
+ isSubmitting = true;
133
+ void done.finally(() => {
134
+ isSubmitting = false;
135
+ });
136
+ }
137
+ /**
138
+ * Completes the submit waiting for a validation, if any: focuses the first
139
+ * invalid control, calls `onSubmit`, or submits the form again, which this
140
+ * owner lets through.
141
+ */
142
+ function completeSubmit(isValid) {
143
+ const waiting = pendingSubmit;
144
+ if (!waiting)
145
+ return;
146
+ pendingSubmit = undefined;
147
+ if (!isValid)
148
+ focusFirstInvalid(waiting.form);
149
+ else if (onSubmit)
150
+ callOnSubmit(onSubmit);
151
+ else {
152
+ isApproved = true;
153
+ try {
154
+ waiting.form.requestSubmit(waiting.submitter);
155
+ }
156
+ finally {
157
+ isApproved = false;
158
+ }
159
+ }
160
+ }
161
+ /** Moves the keys of a `$state` record under the array `prefix` with its items. */
162
+ function moveItemKeys(record, prefix, toIndex) {
163
+ const entries = Object.entries(record);
164
+ clear(record);
165
+ for (const [key, entry] of entries) {
166
+ const moved = moveItemKey(key, prefix, toIndex);
167
+ if (moved !== undefined)
168
+ record[moved] = entry;
169
+ }
170
+ }
56
171
  /** Empties a `$state` record in place, so its readers stay subscribed. */
57
172
  function clear(record) {
58
173
  for (const key of Object.keys(record))
@@ -74,15 +189,16 @@ export default function createFormState({ defaultValues = {}, errors: initialErr
74
189
  get isSubmitting() {
75
190
  return isSubmitting;
76
191
  },
192
+ get isValidating() {
193
+ return isValidating;
194
+ },
77
195
  getValue: (name) => getPath(values, name),
78
196
  setValue(name, value) {
79
197
  const key = normalizePath(name);
80
198
  setPath(values, key, value);
81
- const isBranch = typeof value === "object" && value !== null;
82
199
  if (isSubmitted ||
83
200
  mode === "onChange" ||
84
- (mode === "onTouched" && touched[key]) ||
85
- (isBranch && Object.keys(errors).some((shown) => isWithin(shown, key))))
201
+ (mode === "onTouched" && touched[key]))
86
202
  runValidation([key]);
87
203
  },
88
204
  getError: (name) => errors[normalizePath(name)],
@@ -92,7 +208,21 @@ export default function createFormState({ defaultValues = {}, errors: initialErr
92
208
  if (mode === "onBlur" || mode === "onTouched")
93
209
  runValidation([key]);
94
210
  },
211
+ reindex(name, toIndex) {
212
+ const prefix = `${normalizePath(name)}.`;
213
+ moveItemKeys(errors, prefix, toIndex);
214
+ moveItemKeys(touched, prefix, toIndex);
215
+ if (!isValidating)
216
+ return;
217
+ // The running validation read the items at their old places: start it
218
+ // again on the fields it was updating, at their new places.
219
+ pendingScope = pendingScope?.flatMap((key) => moveItemKey(key, prefix, toIndex) ?? []);
220
+ runValidation([]);
221
+ },
95
222
  reset() {
223
+ latestRun++;
224
+ isValidating = false;
225
+ pendingSubmit = undefined;
96
226
  clear(values);
97
227
  Object.assign(values, defaultValues);
98
228
  clear(errors);
@@ -101,23 +231,27 @@ export default function createFormState({ defaultValues = {}, errors: initialErr
101
231
  },
102
232
  submit(event) {
103
233
  isSubmitted = true;
104
- if (!runValidation()) {
234
+ if (isApproved) {
235
+ isApproved = false;
236
+ return;
237
+ }
238
+ const form = event.currentTarget;
239
+ pendingSubmit = undefined;
240
+ const isValid = runValidation();
241
+ if (isValid === undefined) {
105
242
  event.preventDefault();
106
- const form = event.currentTarget;
107
- // The error state renders on the next update; focus it then.
108
- void tick().then(() => form.querySelector('[aria-invalid="true"]')?.focus());
243
+ pendingSubmit = { form, submitter: event.submitter };
244
+ return;
245
+ }
246
+ if (!isValid) {
247
+ event.preventDefault();
248
+ focusFirstInvalid(form);
109
249
  return;
110
250
  }
111
251
  if (!onSubmit)
112
252
  return;
113
253
  event.preventDefault();
114
- const done = onSubmit($state.snapshot(values));
115
- if (!(done instanceof Promise))
116
- return;
117
- isSubmitting = true;
118
- void done.finally(() => {
119
- isSubmitting = false;
120
- });
254
+ callOnSubmit(onSubmit);
121
255
  },
122
256
  };
123
257
  }
@@ -12,10 +12,9 @@ import type { FormErrors, FormValues, StandardSchema } from "./types.js";
12
12
  * message for a path wins. An issue without a path is keyed by `""`, which no
13
13
  * field shows: give a whole-form refinement a `path` to show it on a field.
14
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`.
15
+ * A schema that validates asynchronously, such as a Zod schema with an
16
+ * `async` refinement, returns a promise of the messages, which
17
+ * `createFormState` waits for; a synchronous schema returns them at once.
19
18
  * @note Pure: the returned function only reads the schema.
20
19
  */
21
- export default function createSchemaValidator<Values extends FormValues>(schema: StandardSchema<Values, unknown>): (values: Readonly<Values>) => FormErrors<Values>;
20
+ export default function createSchemaValidator<Values extends FormValues>(schema: StandardSchema<Values, unknown>): (values: Readonly<Values>) => FormErrors<Values> | Promise<FormErrors<Values>>;
@@ -4,6 +4,13 @@ function readIssueName({ path = [] }) {
4
4
  .map((segment) => String(typeof segment === "object" ? segment.key : segment))
5
5
  .join(".");
6
6
  }
7
+ /** Keys each issue's message by its name; the first message for a name wins. */
8
+ function readErrors(result) {
9
+ const errors = {};
10
+ for (const issue of result.issues ?? [])
11
+ errors[readIssueName(issue)] ??= issue.message;
12
+ return errors;
13
+ }
7
14
  /**
8
15
  * Turns a Standard Schema, such as a Zod, Valibot or ArkType schema, into the
9
16
  * `validate` function of `createFormState`, as react-hook-form's resolvers
@@ -17,20 +24,16 @@ function readIssueName({ path = [] }) {
17
24
  * message for a path wins. An issue without a path is keyed by `""`, which no
18
25
  * field shows: give a whole-form refinement a `path` to show it on a field.
19
26
  *
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`.
27
+ * A schema that validates asynchronously, such as a Zod schema with an
28
+ * `async` refinement, returns a promise of the messages, which
29
+ * `createFormState` waits for; a synchronous schema returns them at once.
24
30
  * @note Pure: the returned function only reads the schema.
25
31
  */
26
32
  export default function createSchemaValidator(schema) {
27
33
  return (values) => {
28
34
  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
+ return result instanceof Promise
36
+ ? result.then((readErrors))
37
+ : readErrors(result);
35
38
  };
36
39
  }
@@ -50,6 +50,7 @@ export default function createValidatedBinding(owner, validators) {
50
50
  },
51
51
  getError,
52
52
  blur: owner.blur?.bind(owner),
53
+ reindex: owner.reindex?.bind(owner),
53
54
  submit(event) {
54
55
  if (messages.size > 0)
55
56
  event.preventDefault();
@@ -16,14 +16,16 @@ type PathIn<Values, Seen> = Values extends readonly (infer Item)[] ? PathFrom<`$
16
16
  * A field name that reaches into nested values, as react-hook-form's `Path`:
17
17
  * object keys and array indices joined with `.`, as `address.city` or
18
18
  * `contacts.0.email`. The fields also accept SvelteKit's `contacts[0].email`
19
- * at runtime; the types follow the dotted form.
19
+ * at runtime; the types follow the dotted form. A name that is not a path of
20
+ * `Values` does not type-check.
20
21
  */
21
22
  export type Path<Values> = Values extends unknown ? PathIn<Values, Values> : never;
22
23
  /** The value of one segment of a path in `Values`. */
23
24
  type SegmentValue<Values, Segment extends string> = Values extends readonly (infer Item)[] ? Segment extends `${number}` ? Item | undefined : undefined : Segment extends keyof Values ? Values[Segment] : undefined;
24
25
  /**
25
26
  * The value at a path in `Values`, as react-hook-form's `PathValue`:
26
- * `PathValue<{ address: { city: string } }, "address.city">` is `string`.
27
+ * `PathValue<{ address: { city: string } }, "address.city">` is `string`, so
28
+ * a value of another type does not type-check there.
27
29
  */
28
30
  export type PathValue<Values, P extends string> = unknown extends Values ? unknown : string extends keyof Values ? unknown extends Values[keyof Values] ? unknown : PathValueIn<Values, P> : PathValueIn<Values, P>;
29
31
  /** The value at a path in `Values`, segment by segment. */
@@ -56,6 +58,13 @@ export type FormOwner<Values extends FormValues = FormValues> = {
56
58
  * `event.preventDefault()` to stop the browser posting the form.
57
59
  */
58
60
  submit?(event: SubmitEvent): void;
61
+ /**
62
+ * Called by a field array before it writes the array at `name`, to move the
63
+ * state kept under it, such as errors and touched fields, with its items:
64
+ * `toIndex` returns an item's new index, or `undefined` for an item that is
65
+ * gone.
66
+ */
67
+ reindex?(name: Path<Values>, toIndex: (index: number) => number | undefined): void;
59
68
  };
60
69
  /** The owner state of one field, to spread onto a `Field` or field component. */
61
70
  export type FieldBinding = {
@@ -93,8 +102,11 @@ export type FormStateOptions<Values extends FormValues = FormValues> = {
93
102
  * `form.errors`. Validation replaces them, and `reset` clears them.
94
103
  */
95
104
  errors?: FormErrors<Values>;
96
- /** Returns the messages of the invalid fields. Leave a valid field out. */
97
- validate?: (values: Readonly<Values>) => FormErrors<Values>;
105
+ /**
106
+ * Returns the messages of the invalid fields, or a promise of them, as
107
+ * react-hook-form's asynchronous resolvers do. Leave a valid field out.
108
+ */
109
+ validate?: (values: Readonly<Values>) => FormErrors<Values> | Promise<FormErrors<Values>>;
98
110
  /** When to validate. Default: "onSubmit". */
99
111
  mode?: ValidationMode;
100
112
  /**
@@ -114,10 +126,13 @@ export type FormState<Values extends FormValues = FormValues> = ResettableOwner<
114
126
  readonly isSubmitted: boolean;
115
127
  /** Is an asynchronous `onSubmit` running. */
116
128
  readonly isSubmitting: boolean;
129
+ /** Is an asynchronous validation running. */
130
+ readonly isValidating: boolean;
117
131
  getValue<Name extends Path<Values>>(name: Name): PathValue<Values, Name> | undefined;
118
132
  getError(name: Path<Values>): string | undefined;
119
133
  blur(name: Path<Values>): void;
120
134
  submit(event: SubmitEvent): void;
135
+ reindex(name: Path<Values>, toIndex: (index: number) => number | undefined): void;
121
136
  };
122
137
  /** A field's asynchronous check: resolves to its message, or `undefined` when valid. */
123
138
  export type FieldValidator<Value> = (value: Value, signal: AbortSignal) => Promise<string | undefined>;
@@ -193,13 +208,19 @@ export type FieldArray<Item> = {
193
208
  readonly key: string;
194
209
  readonly value: Item;
195
210
  }[];
196
- /** Adds an item at the end. */
211
+ /** Adds an item at the end, without errors or touched fields. */
197
212
  append(value: Item): void;
198
- /** Removes the item at `index`. */
213
+ /** Removes the item at `index`, with its errors and touched fields. */
199
214
  remove(index: number): void;
200
- /** Moves the item at `from` to `to`, shifting the items between. */
215
+ /**
216
+ * Moves the item at `from` to `to`, shifting the items between, with their
217
+ * errors and touched fields.
218
+ */
201
219
  move(from: number, to: number): void;
202
- /** Replaces every item, with new keys. */
220
+ /**
221
+ * Replaces every item, with new keys. The errors and touched fields at the
222
+ * indices within the new length stay; those beyond it are dropped.
223
+ */
203
224
  replace(values: readonly Item[]): void;
204
225
  };
205
226
  /**
@@ -12,8 +12,9 @@ import type { FittingInputType, RemoteField, RemoteFieldBinding, RemoteFieldOpti
12
12
  * binds, including those that fire no `input` event; a single file is bound
13
13
  * as a list of one. `error` is the first issue's message.
14
14
  *
15
- * The `inputType` must post the field's value type: a number field takes
16
- * `number`, `range` or `rating`, not `text`. A kind that can hold several
15
+ * The `inputType` is one of `Field`'s kinds and must post the field's value
16
+ * type: a number field takes `number`, `range` or `rating`, not `text`, and a
17
+ * `checkbox` binds a boolean, never an array. A kind that can hold several
17
18
  * values takes `{ multiple: true }` when the value is an array, and the
18
19
  * binding then sets the field's `multiple` or `isMultiple`. A `custom` field
19
20
  * names its SvelteKit type: `{ type: "number" }`. A `hidden` field takes its
@@ -18,8 +18,9 @@ const IS_MULTIPLE_KINDS = new Set([
18
18
  * binds, including those that fire no `input` event; a single file is bound
19
19
  * as a list of one. `error` is the first issue's message.
20
20
  *
21
- * The `inputType` must post the field's value type: a number field takes
22
- * `number`, `range` or `rating`, not `text`. A kind that can hold several
21
+ * The `inputType` is one of `Field`'s kinds and must post the field's value
22
+ * type: a number field takes `number`, `range` or `rating`, not `text`, and a
23
+ * `checkbox` binds a boolean, never an array. A kind that can hold several
23
24
  * values takes `{ multiple: true }` when the value is an array, and the
24
25
  * binding then sets the field's `multiple` or `isMultiple`. A `custom` field
25
26
  * names its SvelteKit type: `{ type: "number" }`. A `hidden` field takes its
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@canonical/svelte-ds-global-form",
3
3
  "description": "Svelte form fields for the Pragma design system, with bindable values.",
4
- "version": "0.49.0",
4
+ "version": "0.50.0",
5
5
  "type": "module",
6
6
  "module": "dist/index.js",
7
7
  "types": "dist/index.d.ts",
@@ -56,18 +56,18 @@
56
56
  "test:server": "vitest --run --project=server"
57
57
  },
58
58
  "dependencies": {
59
- "@canonical/ds-utils": "^0.49.0",
60
- "@canonical/styles": "^0.49.0"
59
+ "@canonical/ds-utils": "^0.50.0",
60
+ "@canonical/styles": "^0.50.0"
61
61
  },
62
62
  "devDependencies": {
63
63
  "@biomejs/biome": "2.6.9",
64
64
  "@canonical/biome-config": "0.47.0",
65
- "@canonical/storybook-addon-msw": "^0.49.0",
66
- "@canonical/storybook-config": "^0.49.0",
67
- "@canonical/storybook-helpers": "^0.49.0",
68
- "@canonical/svelte-ds-global": "^0.49.0",
69
- "@canonical/svelte-ssr-test": "^0.49.0",
70
- "@canonical/typescript-config-svelte": "^0.49.0",
65
+ "@canonical/storybook-addon-msw": "^0.50.0",
66
+ "@canonical/storybook-config": "^0.50.0",
67
+ "@canonical/storybook-helpers": "^0.50.0",
68
+ "@canonical/svelte-ds-global": "^0.50.0",
69
+ "@canonical/svelte-ssr-test": "^0.50.0",
70
+ "@canonical/typescript-config-svelte": "^0.50.0",
71
71
  "@canonical/webarchitect": "0.46.0",
72
72
  "@storybook/addon-docs": "^10.6.0",
73
73
  "@storybook/addon-svelte-csf": "^5.1.3",
@@ -110,5 +110,5 @@
110
110
  "playwright"
111
111
  ]
112
112
  },
113
- "gitHead": "9b71099ded16351ee14432246e3d8190f48767ed"
113
+ "gitHead": "4a2ca02b4767a0ee8e58a679281194fdc316fd71"
114
114
  }