@canonical/svelte-ds-global-form 0.48.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.
Files changed (67) hide show
  1. package/README.md +213 -8
  2. package/dist/_work_in_progress/subcomponent/ComboboxInput/MultipleCombobox.svelte +1 -1
  3. package/dist/_work_in_progress/subcomponent/ComboboxInput/SingleCombobox.svelte +1 -1
  4. package/dist/common/useConditionalDisplay.svelte.js +1 -1
  5. package/dist/component/CheckboxField/CheckboxField.svelte +21 -3
  6. package/dist/component/CheckboxField/CheckboxField.svelte.d.ts +2 -2
  7. package/dist/component/CheckboxField/types.d.ts +13 -1
  8. package/dist/component/ChoicesField/Choices.svelte +5 -3
  9. package/dist/component/RichChoicesField/RichChoices.svelte +5 -3
  10. package/dist/index.d.ts +2 -2
  11. package/dist/index.js +1 -1
  12. package/dist/pattern/Field/Field.svelte +20 -4
  13. package/dist/pattern/Field/types.d.ts +1 -1
  14. package/dist/pattern/Form/Form.svelte +1 -2
  15. package/dist/pattern/Form/Form.svelte.d.ts +1 -1
  16. package/dist/pattern/Form/types.d.ts +1 -1
  17. package/dist/subcomponent/CheckboxInput/CheckboxInput.svelte +18 -2
  18. package/dist/subcomponent/CheckboxInput/CheckboxInput.svelte.d.ts +4 -2
  19. package/dist/subcomponent/CheckboxInput/types.d.ts +7 -0
  20. package/dist/subcomponent/RadioInput/RadioInput.svelte +28 -4
  21. package/dist/subcomponent/RadioInput/RadioInput.svelte.d.ts +4 -2
  22. package/dist/subcomponent/RadioInput/types.d.ts +7 -0
  23. package/dist/utils/index.d.ts +3 -0
  24. package/dist/utils/index.js +3 -0
  25. package/dist/utils/middleware/types.d.ts +1 -1
  26. package/dist/utils/middleware/validateRemotely.js +1 -1
  27. package/dist/utils/owner/bindField.d.ts +5 -3
  28. package/dist/utils/owner/bindField.js +3 -1
  29. package/dist/utils/owner/bindFieldArray.d.ts +24 -0
  30. package/dist/utils/owner/bindFieldArray.js +81 -0
  31. package/dist/utils/owner/bindTanStackForm.d.ts +18 -0
  32. package/dist/utils/owner/bindTanStackForm.js +65 -0
  33. package/dist/utils/owner/createBinding.js +6 -0
  34. package/dist/utils/owner/createFormState.svelte.d.ts +20 -2
  35. package/dist/utils/owner/createFormState.svelte.js +188 -32
  36. package/dist/utils/owner/createSchemaValidator.d.ts +20 -0
  37. package/dist/utils/owner/createSchemaValidator.js +39 -0
  38. package/dist/utils/owner/createValidatedBinding.d.ts +2 -2
  39. package/dist/utils/owner/createValidatedBinding.js +9 -4
  40. package/dist/utils/owner/getPath.d.ts +6 -0
  41. package/dist/utils/owner/getPath.js +15 -0
  42. package/dist/utils/owner/index.d.ts +8 -0
  43. package/dist/utils/owner/index.js +8 -0
  44. package/dist/utils/owner/normalizePath.d.ts +6 -0
  45. package/dist/utils/owner/normalizePath.js +9 -0
  46. package/dist/utils/owner/readOwnerValue.d.ts +7 -0
  47. package/dist/utils/owner/readOwnerValue.js +11 -0
  48. package/dist/utils/owner/setPath.d.ts +12 -0
  49. package/dist/utils/owner/setPath.js +36 -0
  50. package/dist/utils/owner/splitPath.d.ts +7 -0
  51. package/dist/utils/owner/splitPath.js +9 -0
  52. package/dist/utils/owner/types.d.ts +164 -14
  53. package/dist/utils/remoteForm/bindRemoteField.d.ts +24 -0
  54. package/dist/utils/remoteForm/bindRemoteField.js +69 -0
  55. package/dist/utils/remoteForm/bindRemoteForm.d.ts +20 -0
  56. package/dist/utils/remoteForm/bindRemoteForm.js +31 -0
  57. package/dist/utils/remoteForm/constants.d.ts +42 -0
  58. package/dist/utils/remoteForm/constants.js +42 -0
  59. package/dist/utils/remoteForm/index.d.ts +3 -0
  60. package/dist/utils/remoteForm/index.js +2 -0
  61. package/dist/utils/remoteForm/types.d.ts +90 -0
  62. package/dist/utils/remoteForm/types.js +1 -0
  63. package/package.json +23 -11
  64. /package/dist/{component/ChoicesField → utils}/isChoiceChecked.d.ts +0 -0
  65. /package/dist/{component/ChoicesField → utils}/isChoiceChecked.js +0 -0
  66. /package/dist/{component/ChoicesField → utils}/toggleChoice.d.ts +0 -0
  67. /package/dist/{component/ChoicesField → utils}/toggleChoice.js +0 -0
@@ -1,5 +1,35 @@
1
1
  /** A form's values, by field name. */
2
2
  export type FormValues = Record<string, unknown>;
3
+ /** The values a path stops at rather than reading into. */
4
+ type PathLeaf = string | number | boolean | bigint | symbol | null | undefined | Date | Blob | FileList;
5
+ /** Tells whether two types are the same type. */
6
+ type IsEqual<A, B> = (<G>() => G extends A ? 1 : 2) extends <G>() => G extends B ? 1 : 2 ? true : false;
7
+ /** Tells whether any member of the union `Seen` is `Value`. */
8
+ type IsSeen<Seen, Value> = Seen extends unknown ? IsEqual<Seen, Value> extends true ? true : never : never;
9
+ /** The paths to `Key` and below it, whose value is `Value`. */
10
+ type PathFrom<Key extends string, Value, Seen> = unknown extends Value ? Key | `${Key}.${string}` : Value extends PathLeaf ? Key : true extends IsSeen<Seen, Value> ? Key : Key | `${Key}.${PathIn<Value, Seen | Value>}`;
11
+ /** The paths inside `Values`, stopping at a type already walked through. */
12
+ type PathIn<Values, Seen> = Values extends readonly (infer Item)[] ? PathFrom<`${number}`, Item, Seen> : {
13
+ [Key in keyof Values & string]-?: PathFrom<Key, Values[Key], Seen>;
14
+ }[keyof Values & string];
15
+ /**
16
+ * A field name that reaches into nested values, as react-hook-form's `Path`:
17
+ * object keys and array indices joined with `.`, as `address.city` or
18
+ * `contacts.0.email`. The fields also accept SvelteKit's `contacts[0].email`
19
+ * at runtime; the types follow the dotted form. A name that is not a path of
20
+ * `Values` does not type-check.
21
+ */
22
+ export type Path<Values> = Values extends unknown ? PathIn<Values, Values> : never;
23
+ /** The value of one segment of a path in `Values`. */
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;
25
+ /**
26
+ * The value at a path in `Values`, as react-hook-form's `PathValue`:
27
+ * `PathValue<{ address: { city: string } }, "address.city">` is `string`, so
28
+ * a value of another type does not type-check there.
29
+ */
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>;
31
+ /** The value at a path in `Values`, segment by segment. */
32
+ type PathValueIn<Values, P extends string> = P extends `${infer Segment}.${infer Rest}` ? PathValue<SegmentValue<Values, Segment>, Rest> : SegmentValue<Values, P>;
3
33
  /**
4
34
  * The state a `Form` reads and writes by field name: values, and optionally
5
35
  * errors, blur and submission. Every read must be reactive under runes, as
@@ -7,22 +37,34 @@ export type FormValues = Record<string, unknown>;
7
37
  * `createBinding`.
8
38
  */
9
39
  export type FormOwner<Values extends FormValues = FormValues> = {
10
- /** The current values, by field name. */
40
+ /** The current values, by field name, nested as the names say. */
11
41
  readonly values: Values;
12
- /** Writes one field's value. Writing `undefined` drops it. */
13
- setValue<Name extends keyof Values & string>(name: Name, value: Values[Name] | undefined): void;
42
+ /**
43
+ * Returns the value at a field's path. Leave it unset and the fields read
44
+ * the path in `values` themselves.
45
+ */
46
+ getValue?<Name extends Path<Values>>(name: Name): PathValue<Values, Name> | undefined;
47
+ /** Writes the value at a field's path. Writing `undefined` drops it. */
48
+ setValue<Name extends Path<Values>>(name: Name, value: PathValue<Values, Name> | undefined): void;
14
49
  /**
15
50
  * Returns the field's validation message, if any. A field shows every
16
51
  * message it is given: when errors exist is the owner's business.
17
52
  */
18
- getError?(name: keyof Values & string): string | undefined;
53
+ getError?(name: Path<Values>): string | undefined;
19
54
  /** Called when the user leaves the field. */
20
- blur?(name: keyof Values & string): void;
55
+ blur?(name: Path<Values>): void;
21
56
  /**
22
57
  * Called when the form is submitted, after native validation passed. Call
23
58
  * `event.preventDefault()` to stop the browser posting the form.
24
59
  */
25
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;
26
68
  };
27
69
  /** The owner state of one field, to spread onto a `Field` or field component. */
28
70
  export type FieldBinding = {
@@ -40,8 +82,8 @@ export type BindingSource<Values extends FormValues = FormValues> = Omit<FormOwn
40
82
  /** Calls `notify` after every change, and returns a function that stops it. */
41
83
  subscribe(notify: () => void): () => void;
42
84
  };
43
- /** A form's validation messages, by field name. */
44
- export type FormErrors<Values extends FormValues = FormValues> = Partial<Record<keyof Values & string, string>>;
85
+ /** A form's validation messages, by field path joined with `.`. */
86
+ export type FormErrors<Values extends FormValues = FormValues> = Partial<Record<Path<Values>, string>>;
45
87
  /**
46
88
  * When `createFormState` validates, as react-hook-form's `mode`. Every mode
47
89
  * also validates on submit, and after the first submit on every change.
@@ -55,8 +97,16 @@ export type ValidationMode = "onSubmit" | "onChange" | "onBlur" | "onTouched";
55
97
  export type FormStateOptions<Values extends FormValues = FormValues> = {
56
98
  /** The initial values, restored by `reset`. */
57
99
  defaultValues?: Values;
58
- /** Returns the messages of the invalid fields. Leave a valid field out. */
59
- validate?: (values: Readonly<Values>) => FormErrors<Values>;
100
+ /**
101
+ * Messages to show from the start, such as a SvelteKit action's
102
+ * `form.errors`. Validation replaces them, and `reset` clears them.
103
+ */
104
+ errors?: 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>>;
60
110
  /** When to validate. Default: "onSubmit". */
61
111
  mode?: ValidationMode;
62
112
  /**
@@ -68,17 +118,21 @@ export type FormStateOptions<Values extends FormValues = FormValues> = {
68
118
  };
69
119
  /** The owner `createFormState` returns. */
70
120
  export type FormState<Values extends FormValues = FormValues> = ResettableOwner<Values> & {
71
- /** The current messages, by field name. */
121
+ /** The current messages, by field path joined with `.`. */
72
122
  readonly errors: Readonly<FormErrors<Values>>;
73
- /** The fields the user has left, by field name. */
74
- readonly touched: Readonly<Partial<Record<keyof Values & string, true>>>;
123
+ /** The fields the user has left, by field path joined with `.`. */
124
+ readonly touched: Readonly<Partial<Record<Path<Values>, true>>>;
75
125
  /** Has the form been submitted since it was created or reset. */
76
126
  readonly isSubmitted: boolean;
77
127
  /** Is an asynchronous `onSubmit` running. */
78
128
  readonly isSubmitting: boolean;
79
- getError(name: keyof Values & string): string | undefined;
80
- blur(name: keyof Values & string): void;
129
+ /** Is an asynchronous validation running. */
130
+ readonly isValidating: boolean;
131
+ getValue<Name extends Path<Values>>(name: Name): PathValue<Values, Name> | undefined;
132
+ getError(name: Path<Values>): string | undefined;
133
+ blur(name: Path<Values>): void;
81
134
  submit(event: SubmitEvent): void;
135
+ reindex(name: Path<Values>, toIndex: (index: number) => number | undefined): void;
82
136
  };
83
137
  /** A field's asynchronous check: resolves to its message, or `undefined` when valid. */
84
138
  export type FieldValidator<Value> = (value: Value, signal: AbortSignal) => Promise<string | undefined>;
@@ -105,3 +159,99 @@ export type LatestOutcome<Output> = {
105
159
  } | {
106
160
  status: "superseded";
107
161
  };
162
+ /**
163
+ * A schema that follows Standard Schema v1, the interface Zod (3.24 and
164
+ * later), Valibot and ArkType schemas implement under their `~standard`
165
+ * property. The interface is copied here, as the specification intends, so the
166
+ * package needs no dependency to accept such a schema.
167
+ */
168
+ export type StandardSchema<Input = unknown, Output = Input> = {
169
+ readonly "~standard": {
170
+ /** The version of the specification. */
171
+ readonly version: 1;
172
+ /** The library that made the schema. */
173
+ readonly vendor: string;
174
+ /** Validates an unknown value, synchronously or not. */
175
+ readonly validate: (value: unknown) => StandardSchemaResult<Output> | Promise<StandardSchemaResult<Output>>;
176
+ /** The input and output types, for inference only. */
177
+ readonly types?: {
178
+ readonly input: Input;
179
+ readonly output: Output;
180
+ } | undefined;
181
+ };
182
+ };
183
+ /** The result of a Standard Schema validation: a value, or issues. */
184
+ export type StandardSchemaResult<Output> = {
185
+ readonly value: Output;
186
+ readonly issues?: undefined;
187
+ } | {
188
+ readonly issues: readonly StandardSchemaIssue[];
189
+ };
190
+ /** One problem a Standard Schema found. */
191
+ export type StandardSchemaIssue = {
192
+ /** The message to show. */
193
+ readonly message: string;
194
+ /** Where the problem is in the value: keys, or segments holding a key. */
195
+ readonly path?: readonly (PropertyKey | {
196
+ readonly key: PropertyKey;
197
+ })[] | undefined;
198
+ };
199
+ /** The type of one item of the array at `Name` in `Values`. */
200
+ export type FieldArrayItem<Values extends FormValues, Name extends Path<Values>> = NonNullable<PathValue<Values, Name>> extends readonly (infer Item)[] ? Item : unknown;
201
+ /** A list of repeated fields bound to an owner's array, by `bindFieldArray`. */
202
+ export type FieldArray<Item> = {
203
+ /**
204
+ * The current items, each with a key that stays with it across `move` and
205
+ * `remove`: key an `{#each}` by it.
206
+ */
207
+ readonly items: readonly {
208
+ readonly key: string;
209
+ readonly value: Item;
210
+ }[];
211
+ /** Adds an item at the end, without errors or touched fields. */
212
+ append(value: Item): void;
213
+ /** Removes the item at `index`, with its errors and touched fields. */
214
+ remove(index: number): void;
215
+ /**
216
+ * Moves the item at `from` to `to`, shifting the items between, with their
217
+ * errors and touched fields.
218
+ */
219
+ move(from: number, to: number): void;
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
+ */
224
+ replace(values: readonly Item[]): void;
225
+ };
226
+ /**
227
+ * The part of a TanStack Form instance (`createForm` or `FormApi`, version 1)
228
+ * that `bindTanStackForm` uses. It is written out here, so the package needs no
229
+ * dependency on TanStack Form to accept one; the names are TanStack's own.
230
+ */
231
+ export type TanStackFormApi<Values extends FormValues = FormValues> = {
232
+ /** The form's state, whose `values` hold every value. */
233
+ readonly state: {
234
+ readonly values: Values;
235
+ };
236
+ /** The store holding the state, which tells its listeners of each change. */
237
+ readonly store: {
238
+ subscribe(listener: () => void): {
239
+ unsubscribe(): void;
240
+ };
241
+ };
242
+ /** Reads the value at a field's path. */
243
+ getFieldValue(field: never): unknown;
244
+ /** Writes the value at a field's path. */
245
+ setFieldValue(field: never, updater: never): void;
246
+ /** Reads a field's meta, which holds its errors. */
247
+ getFieldMeta(field: never): unknown;
248
+ /** Updates a field's meta. */
249
+ setFieldMeta(field: never, updater: never): void;
250
+ /** Runs a field's validators for one cause. */
251
+ validateField(field: never, cause: "blur"): unknown;
252
+ /** Validates the form and calls its `onSubmit` when it is valid. */
253
+ handleSubmit(): Promise<void>;
254
+ /** Returns every value to its default. */
255
+ reset(): void;
256
+ };
257
+ export {};
@@ -0,0 +1,24 @@
1
+ import type { FittingInputType, RemoteField, RemoteFieldBinding, RemoteFieldOptions, RemoteValueOf } from "./types.js";
2
+ /**
3
+ * Returns a SvelteKit remote form field's state, to spread onto a `Field`:
4
+ *
5
+ * ```svelte
6
+ * <Field {...bindRemoteField(form.fields.age, "number")} label="Age" />
7
+ * ```
8
+ *
9
+ * `name` is the one SvelteKit's `.as(type)` gives, so it carries the `n:` or
10
+ * `b:` prefix that makes the server decode a number or a boolean, and `[]` for
11
+ * an array. `value` reads and writes the remote form's value, so any control
12
+ * binds, including those that fire no `input` event; a single file is bound
13
+ * as a list of one. `error` is the first issue's message.
14
+ *
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
18
+ * values takes `{ multiple: true }` when the value is an array, and the
19
+ * binding then sets the field's `multiple` or `isMultiple`. A `custom` field
20
+ * names its SvelteKit type: `{ type: "number" }`. A `hidden` field takes its
21
+ * prefix from its current value, so give it one.
22
+ * @note Pure: the properties are getters and a setter over the field.
23
+ */
24
+ export default function bindRemoteField<Field extends RemoteField, Kind extends FittingInputType<RemoteValueOf<Field>>>(field: Field, inputType: Kind, ...[options]: RemoteFieldOptions<Kind, RemoteValueOf<Field>>): RemoteFieldBinding<Kind, RemoteValueOf<Field>>;
@@ -0,0 +1,69 @@
1
+ import { REMOTE_INPUT_TYPES, REMOTE_MULTIPLE_INPUT_TYPES, } from "./constants.js";
2
+ /** The `inputType`s whose multiple prop is `isMultiple` rather than `multiple`. */
3
+ const IS_MULTIPLE_KINDS = new Set([
4
+ "choices",
5
+ "rich-choices",
6
+ "combobox",
7
+ ]);
8
+ /**
9
+ * Returns a SvelteKit remote form field's state, to spread onto a `Field`:
10
+ *
11
+ * ```svelte
12
+ * <Field {...bindRemoteField(form.fields.age, "number")} label="Age" />
13
+ * ```
14
+ *
15
+ * `name` is the one SvelteKit's `.as(type)` gives, so it carries the `n:` or
16
+ * `b:` prefix that makes the server decode a number or a boolean, and `[]` for
17
+ * an array. `value` reads and writes the remote form's value, so any control
18
+ * binds, including those that fire no `input` event; a single file is bound
19
+ * as a list of one. `error` is the first issue's message.
20
+ *
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
24
+ * values takes `{ multiple: true }` when the value is an array, and the
25
+ * binding then sets the field's `multiple` or `isMultiple`. A `custom` field
26
+ * names its SvelteKit type: `{ type: "number" }`. A `hidden` field takes its
27
+ * prefix from its current value, so give it one.
28
+ * @note Pure: the properties are getters and a setter over the field.
29
+ */
30
+ export default function bindRemoteField(field, inputType, ...[options]) {
31
+ const settings = options;
32
+ const isMultiple = settings?.multiple === true;
33
+ const kitType = (settings?.type ??
34
+ (isMultiple
35
+ ? REMOTE_MULTIPLE_INPUT_TYPES[inputType]
36
+ : REMOTE_INPUT_TYPES[inputType]));
37
+ // SvelteKit needs a value to name some inputs: a checkbox of an array,
38
+ // whose value marks it as one; a radio, which it requires; and a hidden
39
+ // input, whose value's type sets the prefix. The value does not change the
40
+ // name otherwise.
41
+ const readName = () => {
42
+ const probe = kitType === "hidden" || kitType === "submit"
43
+ ? (field.value() ?? "")
44
+ : kitType === "radio" || (kitType === "checkbox" && isMultiple)
45
+ ? "on"
46
+ : undefined;
47
+ return field.as(kitType, probe).name;
48
+ };
49
+ const isFile = kitType === "file";
50
+ const binding = {
51
+ inputType,
52
+ get name() {
53
+ return readName();
54
+ },
55
+ get value() {
56
+ const value = field.value();
57
+ return (isFile && value !== undefined ? [value] : value);
58
+ },
59
+ set value(next) {
60
+ field.set((isFile ? next?.at(0) : next));
61
+ },
62
+ get error() {
63
+ return field.issues()?.at(0)?.message;
64
+ },
65
+ };
66
+ if (!isMultiple || settings?.type !== undefined)
67
+ return binding;
68
+ return Object.defineProperty(binding, IS_MULTIPLE_KINDS.has(inputType) ? "isMultiple" : "multiple", { value: true, enumerable: true });
69
+ }
@@ -0,0 +1,20 @@
1
+ import type { RemoteFormInput } from "@sveltejs/kit";
2
+ import { type FormOwner } from "../owner/index.js";
3
+ import type { RemoteFormOf } from "./types.js";
4
+ /**
5
+ * Makes a SvelteKit remote form a form owner, for a `Form` or `bindField`:
6
+ *
7
+ * ```svelte
8
+ * <Form {...save} owner={bindRemoteForm(save)}>
9
+ * ```
10
+ *
11
+ * `values` are the remote form's values; a field reads and writes its value
12
+ * at its path through the remote form's field, and shows its first issue's
13
+ * message. A name may be the posted one: SvelteKit's `n:` and `b:` prefixes
14
+ * and `[]` suffix are dropped to find the field, so a number or checkbox
15
+ * field can take its name from `.as(type).name` and still post its type.
16
+ * The owner has no `submit`: the remote form handles the submit and its
17
+ * validation, and marks a field touched when its control changes.
18
+ * @note Pure: reads and writes the remote form.
19
+ */
20
+ export default function bindRemoteForm<Input extends RemoteFormInput>(form: RemoteFormOf<Input>): FormOwner<Input>;
@@ -0,0 +1,31 @@
1
+ import { splitPath } from "../owner/index.js";
2
+ /**
3
+ * Makes a SvelteKit remote form a form owner, for a `Form` or `bindField`:
4
+ *
5
+ * ```svelte
6
+ * <Form {...save} owner={bindRemoteForm(save)}>
7
+ * ```
8
+ *
9
+ * `values` are the remote form's values; a field reads and writes its value
10
+ * at its path through the remote form's field, and shows its first issue's
11
+ * message. A name may be the posted one: SvelteKit's `n:` and `b:` prefixes
12
+ * and `[]` suffix are dropped to find the field, so a number or checkbox
13
+ * field can take its name from `.as(type).name` and still post its type.
14
+ * The owner has no `submit`: the remote form handles the submit and its
15
+ * validation, and marks a field touched when its control changes.
16
+ * @note Pure: reads and writes the remote form.
17
+ */
18
+ export default function bindRemoteForm(form) {
19
+ const root = form.fields;
20
+ const readField = (name) => splitPath(name.replace(/^[nb]:/, "")).reduce((node, segment) => node[segment], root);
21
+ return {
22
+ get values() {
23
+ return (root.value() ?? {});
24
+ },
25
+ getValue: (name) => readField(name).value(),
26
+ setValue: (name, value) => {
27
+ readField(name).set(value);
28
+ },
29
+ getError: (name) => readField(name).issues()?.at(0)?.message,
30
+ };
31
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * The SvelteKit input type each `Field` `inputType` posts as, which gives the
3
+ * posted name its prefix: `n:` for a number, `b:` for a checkbox. A textarea
4
+ * posts as text; a choice group as a radio; a phone number as a `tel`. A
5
+ * custom field names its own type.
6
+ */
7
+ export declare const REMOTE_INPUT_TYPES: {
8
+ readonly text: "text";
9
+ readonly email: "email";
10
+ readonly tel: "tel";
11
+ readonly url: "url";
12
+ readonly password: "password";
13
+ readonly number: "number";
14
+ readonly checkbox: "checkbox";
15
+ readonly switch: "checkbox";
16
+ readonly hidden: "hidden";
17
+ readonly range: "range";
18
+ readonly rating: "number";
19
+ readonly select: "select";
20
+ readonly combobox: "select";
21
+ readonly choices: "radio";
22
+ readonly textarea: "text";
23
+ readonly date: "date";
24
+ readonly time: "time";
25
+ readonly datetime: "datetime-local";
26
+ readonly file: "file";
27
+ readonly color: "color";
28
+ readonly phone: "tel";
29
+ readonly "rich-choices": "radio";
30
+ readonly custom: null;
31
+ };
32
+ /**
33
+ * The SvelteKit input type of each `Field` `inputType` that can hold several
34
+ * values, when it does: the posted name ends in `[]`.
35
+ */
36
+ export declare const REMOTE_MULTIPLE_INPUT_TYPES: {
37
+ readonly select: "select multiple";
38
+ readonly combobox: "select multiple";
39
+ readonly choices: "checkbox";
40
+ readonly "rich-choices": "checkbox";
41
+ readonly file: "file multiple";
42
+ };
@@ -0,0 +1,42 @@
1
+ /**
2
+ * The SvelteKit input type each `Field` `inputType` posts as, which gives the
3
+ * posted name its prefix: `n:` for a number, `b:` for a checkbox. A textarea
4
+ * posts as text; a choice group as a radio; a phone number as a `tel`. A
5
+ * custom field names its own type.
6
+ */
7
+ export const REMOTE_INPUT_TYPES = {
8
+ text: "text",
9
+ email: "email",
10
+ tel: "tel",
11
+ url: "url",
12
+ password: "password",
13
+ number: "number",
14
+ checkbox: "checkbox",
15
+ switch: "checkbox",
16
+ hidden: "hidden",
17
+ range: "range",
18
+ rating: "number",
19
+ select: "select",
20
+ combobox: "select",
21
+ choices: "radio",
22
+ textarea: "text",
23
+ date: "date",
24
+ time: "time",
25
+ datetime: "datetime-local",
26
+ file: "file",
27
+ color: "color",
28
+ phone: "tel",
29
+ "rich-choices": "radio",
30
+ custom: null,
31
+ };
32
+ /**
33
+ * The SvelteKit input type of each `Field` `inputType` that can hold several
34
+ * values, when it does: the posted name ends in `[]`.
35
+ */
36
+ export const REMOTE_MULTIPLE_INPUT_TYPES = {
37
+ select: "select multiple",
38
+ combobox: "select multiple",
39
+ choices: "checkbox",
40
+ "rich-choices": "checkbox",
41
+ file: "file multiple",
42
+ };
@@ -0,0 +1,3 @@
1
+ export { default as bindRemoteField } from "./bindRemoteField.js";
2
+ export { default as bindRemoteForm } from "./bindRemoteForm.js";
3
+ export type * from "./types.js";
@@ -0,0 +1,2 @@
1
+ export { default as bindRemoteField } from "./bindRemoteField.js";
2
+ export { default as bindRemoteForm } from "./bindRemoteForm.js";
@@ -0,0 +1,90 @@
1
+ import type { RemoteForm, RemoteFormFieldType, RemoteFormFieldValue, RemoteFormInput, RemoteFormIssue } from "@sveltejs/kit";
2
+ import type { FieldProps } from "../../pattern/index.js";
3
+ import type { REMOTE_INPUT_TYPES, REMOTE_MULTIPLE_INPUT_TYPES } from "./constants.js";
4
+ /** Every `inputType` a `Field` routes on. */
5
+ export type FieldInputType = FieldProps["inputType"];
6
+ /** Every input type a SvelteKit remote form field takes in `.as(type)`. */
7
+ export type KitInputType = RemoteFormFieldType<RemoteFormFieldValue>;
8
+ /**
9
+ * A SvelteKit remote form field that holds a value, as `bindRemoteField`
10
+ * uses it: `form.fields.age`, not a field holding nested fields.
11
+ */
12
+ export type RemoteField = {
13
+ /** Returns the value that will be posted. */
14
+ value(): unknown;
15
+ /** Writes the value that will be posted. */
16
+ set(value: never): unknown;
17
+ /** Returns the field's validation issues, if any. */
18
+ issues(): RemoteFormIssue[] | undefined;
19
+ /** Returns the props to spread on an input of a SvelteKit type. */
20
+ as(...args: never[]): {
21
+ name: string;
22
+ };
23
+ };
24
+ /**
25
+ * The value type of a remote form field, read back from its `value()`: an
26
+ * array's items are not optional.
27
+ */
28
+ export type RemoteValueOf<Field extends RemoteField> = NonNullable<ReturnType<Field["value"]>> extends readonly (infer Item)[] ? NonNullable<Item>[] : NonNullable<ReturnType<Field["value"]>>;
29
+ /** The `inputType`s whose value can hold several values. */
30
+ type MultipleInputType = keyof typeof REMOTE_MULTIPLE_INPUT_TYPES;
31
+ /**
32
+ * The SvelteKit type a `Field` `inputType` posts as, for a value type: the
33
+ * multiple type of a kind with one when the value is an array.
34
+ */
35
+ type KitTypeOf<Kind extends FieldInputType, Value> = [Value] extends [
36
+ readonly unknown[]
37
+ ] ? Kind extends MultipleInputType ? (typeof REMOTE_MULTIPLE_INPUT_TYPES)[Kind] : never : (typeof REMOTE_INPUT_TYPES)[Kind];
38
+ /** The value a field of `Kind` binds, from a remote value: a file is a list. */
39
+ type BoundValue<Kind extends FieldInputType, Value> = Kind extends "file" ? Value extends File ? File[] : Value : Value;
40
+ /** The value type of a `Field` of `Kind`. */
41
+ type FieldValueOf<Kind extends FieldInputType> = FieldProps extends infer Props ? Props extends {
42
+ inputType: infer Type;
43
+ value?: infer Bound;
44
+ } ? Kind extends Type ? Bound : never : never : never;
45
+ /** Tells whether a field of `Kind` binds a remote value of type `Value`. */
46
+ type Fits<Kind extends FieldInputType, Value> = Kind extends "custom" ? true : [KitTypeOf<Kind, Value>] extends [never] ? false : [KitTypeOf<Kind, Value>] extends [RemoteFormFieldType<Value>] ? [BoundValue<Kind, Value>] extends [NonNullable<FieldValueOf<Kind>>] ? true : false : false;
47
+ /**
48
+ * The `Field` `inputType`s that bind a remote value of type `Value`: the
49
+ * SvelteKit type each posts as takes the value, and the field binds it.
50
+ */
51
+ export type FittingInputType<Value> = {
52
+ [Kind in FieldInputType]: Fits<Kind, Value> extends true ? Kind : never;
53
+ }[FieldInputType];
54
+ /**
55
+ * The options `bindRemoteField` needs: the SvelteKit type of a custom field,
56
+ * and `multiple` for a kind that holds an array.
57
+ */
58
+ export type RemoteFieldOptions<Kind extends FieldInputType, Value> = Kind extends "custom" ? [
59
+ options: {
60
+ /** The SvelteKit type the custom control posts as. */
61
+ type: RemoteFormFieldType<Value>;
62
+ /** Is the value an array of checkbox values. */
63
+ multiple?: true;
64
+ }
65
+ ] : [Value] extends [readonly unknown[]] ? [options: {
66
+ multiple: true;
67
+ }] : [];
68
+ /** The prop that makes a `Field` of `Kind` hold several values. */
69
+ type MultipleProp<Kind extends FieldInputType> = Kind extends "select" | "file" ? {
70
+ readonly multiple: true;
71
+ } : Kind extends MultipleInputType ? {
72
+ readonly isMultiple: true;
73
+ } : unknown;
74
+ /**
75
+ * A remote form field's state, to spread onto a `Field`: its `inputType`, the
76
+ * name SvelteKit decodes, the bound value and the first issue's message.
77
+ */
78
+ export type RemoteFieldBinding<Kind extends FieldInputType, Value> = {
79
+ /** The field kind `Field` routes on. */
80
+ readonly inputType: Kind;
81
+ /** The posted name, with SvelteKit's type prefix and array suffix. */
82
+ readonly name: string;
83
+ /** The field's value. Writing it sets the remote form's value. */
84
+ value: BoundValue<Kind, Value> | undefined;
85
+ /** The first validation issue's message, if any. */
86
+ readonly error: string | undefined;
87
+ } & ([Value] extends [readonly unknown[]] ? MultipleProp<Kind> : unknown);
88
+ /** A SvelteKit remote form that takes input, as `bindRemoteForm` reads it. */
89
+ export type RemoteFormOf<Input extends RemoteFormInput> = Pick<RemoteForm<Input, unknown>, "fields">;
90
+ export {};
@@ -0,0 +1 @@
1
+ export {};
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.48.0",
4
+ "version": "0.50.0",
5
5
  "type": "module",
6
6
  "module": "dist/index.js",
7
7
  "types": "dist/index.d.ts",
@@ -56,21 +56,22 @@
56
56
  "test:server": "vitest --run --project=server"
57
57
  },
58
58
  "dependencies": {
59
- "@canonical/ds-utils": "^0.48.0",
60
- "@canonical/styles": "^0.48.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.48.0",
66
- "@canonical/storybook-config": "^0.48.0",
67
- "@canonical/storybook-helpers": "^0.48.0",
68
- "@canonical/svelte-ds-global": "^0.48.0",
69
- "@canonical/svelte-ssr-test": "^0.48.0",
70
- "@canonical/typescript-config-svelte": "^0.48.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",
74
+ "@sveltejs/kit": "2.70.3",
74
75
  "@sveltejs/package": "3.0.0",
75
76
  "@sveltejs/vite-plugin-svelte": "^7.0.0",
76
77
  "@tanstack/svelte-form": "1.33.5",
@@ -88,15 +89,26 @@
88
89
  "typescript": "~6.0.3",
89
90
  "vite": "^8.0.1",
90
91
  "vitest": "^5.0.0",
91
- "vitest-browser-svelte": "^3.0.0"
92
+ "vitest-browser-svelte": "^3.0.0",
93
+ "zod": "^4.6.7"
92
94
  },
93
95
  "peerDependencies": {
96
+ "@sveltejs/kit": "^2.70.0",
97
+ "@tanstack/svelte-form": "^1.33.5",
94
98
  "svelte": "^5.47.1"
95
99
  },
100
+ "peerDependenciesMeta": {
101
+ "@sveltejs/kit": {
102
+ "optional": true
103
+ },
104
+ "@tanstack/svelte-form": {
105
+ "optional": true
106
+ }
107
+ },
96
108
  "nx": {
97
109
  "tags": [
98
110
  "playwright"
99
111
  ]
100
112
  },
101
- "gitHead": "aee4aebab851f90159776a7ba658d0c62e0d2bf4"
113
+ "gitHead": "4a2ca02b4767a0ee8e58a679281194fdc316fd71"
102
114
  }