@canonical/svelte-ds-global-form 0.47.0 → 0.49.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +166 -0
- package/README.md +213 -8
- package/dist/component/CheckboxField/CheckboxField.svelte +21 -3
- package/dist/component/CheckboxField/CheckboxField.svelte.d.ts +2 -2
- package/dist/component/CheckboxField/types.d.ts +13 -1
- package/dist/component/ChoicesField/Choices.svelte +5 -3
- package/dist/component/RichChoicesField/RichChoices.svelte +5 -3
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/pattern/Field/Field.svelte +20 -4
- package/dist/pattern/Field/types.d.ts +1 -1
- package/dist/subcomponent/CheckboxInput/CheckboxInput.svelte +18 -2
- package/dist/subcomponent/CheckboxInput/CheckboxInput.svelte.d.ts +4 -2
- package/dist/subcomponent/CheckboxInput/types.d.ts +7 -0
- package/dist/subcomponent/RadioInput/RadioInput.svelte +28 -4
- package/dist/subcomponent/RadioInput/RadioInput.svelte.d.ts +4 -2
- package/dist/subcomponent/RadioInput/types.d.ts +7 -0
- package/dist/utils/index.d.ts +3 -0
- package/dist/utils/index.js +3 -0
- package/dist/utils/owner/bindField.d.ts +5 -3
- package/dist/utils/owner/bindField.js +3 -1
- package/dist/utils/owner/bindFieldArray.d.ts +20 -0
- package/dist/utils/owner/bindFieldArray.js +62 -0
- package/dist/utils/owner/bindTanStackForm.d.ts +18 -0
- package/dist/utils/owner/bindTanStackForm.js +65 -0
- package/dist/utils/owner/createBinding.js +6 -0
- package/dist/utils/owner/createFormState.svelte.d.ts +12 -3
- package/dist/utils/owner/createFormState.svelte.js +43 -21
- package/dist/utils/owner/createSchemaValidator.d.ts +21 -0
- package/dist/utils/owner/createSchemaValidator.js +36 -0
- package/dist/utils/owner/createValidatedBinding.d.ts +2 -2
- package/dist/utils/owner/createValidatedBinding.js +8 -4
- package/dist/utils/owner/getPath.d.ts +6 -0
- package/dist/utils/owner/getPath.js +15 -0
- package/dist/utils/owner/index.d.ts +8 -0
- package/dist/utils/owner/index.js +8 -0
- package/dist/utils/owner/normalizePath.d.ts +6 -0
- package/dist/utils/owner/normalizePath.js +9 -0
- package/dist/utils/owner/readOwnerValue.d.ts +7 -0
- package/dist/utils/owner/readOwnerValue.js +11 -0
- package/dist/utils/owner/setPath.d.ts +12 -0
- package/dist/utils/owner/setPath.js +36 -0
- package/dist/utils/owner/splitPath.d.ts +7 -0
- package/dist/utils/owner/splitPath.js +9 -0
- package/dist/utils/owner/types.d.ts +141 -12
- package/dist/utils/remoteForm/bindRemoteField.d.ts +23 -0
- package/dist/utils/remoteForm/bindRemoteField.js +68 -0
- package/dist/utils/remoteForm/bindRemoteForm.d.ts +20 -0
- package/dist/utils/remoteForm/bindRemoteForm.js +31 -0
- package/dist/utils/remoteForm/constants.d.ts +42 -0
- package/dist/utils/remoteForm/constants.js +42 -0
- package/dist/utils/remoteForm/index.d.ts +3 -0
- package/dist/utils/remoteForm/index.js +2 -0
- package/dist/utils/remoteForm/types.d.ts +90 -0
- package/dist/utils/remoteForm/types.js +1 -0
- package/package.json +24 -11
- /package/dist/{component/ChoicesField → utils}/isChoiceChecked.d.ts +0 -0
- /package/dist/{component/ChoicesField → utils}/isChoiceChecked.js +0 -0
- /package/dist/{component/ChoicesField → utils}/toggleChoice.d.ts +0 -0
- /package/dist/{component/ChoicesField → utils}/toggleChoice.js +0 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
GNU LESSER GENERAL PUBLIC LICENSE
|
|
2
|
+
Version 3, 29 June 2007
|
|
3
|
+
|
|
4
|
+
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
|
5
|
+
Everyone is permitted to copy and distribute verbatim copies
|
|
6
|
+
of this license document, but changing it is not allowed.
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
This version of the GNU Lesser General Public License incorporates
|
|
10
|
+
the terms and conditions of version 3 of the GNU General Public
|
|
11
|
+
License, supplemented by the additional permissions listed below.
|
|
12
|
+
|
|
13
|
+
0. Additional Definitions.
|
|
14
|
+
|
|
15
|
+
As used herein, "this License" refers to version 3 of the GNU Lesser
|
|
16
|
+
General Public License, and the "GNU GPL" refers to version 3 of the GNU
|
|
17
|
+
General Public License.
|
|
18
|
+
|
|
19
|
+
"The Library" refers to a covered work governed by this License,
|
|
20
|
+
other than an Application or a Combined Work as defined below.
|
|
21
|
+
|
|
22
|
+
An "Application" is any work that makes use of an interface provided
|
|
23
|
+
by the Library, but which is not otherwise based on the Library.
|
|
24
|
+
Defining a subclass of a class defined by the Library is deemed a mode
|
|
25
|
+
of using an interface provided by the Library.
|
|
26
|
+
|
|
27
|
+
A "Combined Work" is a work produced by combining or linking an
|
|
28
|
+
Application with the Library. The particular version of the Library
|
|
29
|
+
with which the Combined Work was made is also called the "Linked
|
|
30
|
+
Version".
|
|
31
|
+
|
|
32
|
+
The "Minimal Corresponding Source" for a Combined Work means the
|
|
33
|
+
Corresponding Source for the Combined Work, excluding any source code
|
|
34
|
+
for portions of the Combined Work that, considered in isolation, are
|
|
35
|
+
based on the Application, and not on the Linked Version.
|
|
36
|
+
|
|
37
|
+
The "Corresponding Application Code" for a Combined Work means the
|
|
38
|
+
object code and/or source code for the Application, including any data
|
|
39
|
+
and utility programs needed for reproducing the Combined Work from the
|
|
40
|
+
Application, but excluding the System Libraries of the Combined Work.
|
|
41
|
+
|
|
42
|
+
1. Exception to Section 3 of the GNU GPL.
|
|
43
|
+
|
|
44
|
+
You may convey a covered work under sections 3 and 4 of this License
|
|
45
|
+
without being bound by section 3 of the GNU GPL.
|
|
46
|
+
|
|
47
|
+
2. Conveying Modified Versions.
|
|
48
|
+
|
|
49
|
+
If you modify a copy of the Library, and, in your modifications, a
|
|
50
|
+
facility refers to a function or data to be supplied by an Application
|
|
51
|
+
that uses the facility (other than as an argument passed when the
|
|
52
|
+
facility is invoked), then you may convey a copy of the modified
|
|
53
|
+
version:
|
|
54
|
+
|
|
55
|
+
a) under this License, provided that you make a good faith effort to
|
|
56
|
+
ensure that, in the event an Application does not supply the
|
|
57
|
+
function or data, the facility still operates, and performs
|
|
58
|
+
whatever part of its purpose remains meaningful, or
|
|
59
|
+
|
|
60
|
+
b) under the GNU GPL, with none of the additional permissions of
|
|
61
|
+
this License applicable to that copy.
|
|
62
|
+
|
|
63
|
+
3. Object Code Incorporating Material from Library Header Files.
|
|
64
|
+
|
|
65
|
+
The object code form of an Application may incorporate material from
|
|
66
|
+
a header file that is part of the Library. You may convey such object
|
|
67
|
+
code under terms of your choice, provided that, if the incorporated
|
|
68
|
+
material is not limited to numerical parameters, data structure
|
|
69
|
+
layouts and accessors, or small macros, inline functions and templates
|
|
70
|
+
(ten or fewer lines in length), you do both of the following:
|
|
71
|
+
|
|
72
|
+
a) Give prominent notice with each copy of the object code that the
|
|
73
|
+
Library is used in it and that the Library and its use are
|
|
74
|
+
covered by this License.
|
|
75
|
+
|
|
76
|
+
b) Accompany the object code with a copy of the GNU GPL and this license
|
|
77
|
+
document.
|
|
78
|
+
|
|
79
|
+
4. Combined Works.
|
|
80
|
+
|
|
81
|
+
You may convey a Combined Work under terms of your choice that,
|
|
82
|
+
taken together, effectively do not restrict modification of the
|
|
83
|
+
portions of the Library contained in the Combined Work and reverse
|
|
84
|
+
engineering for debugging such modifications, if you also do each of
|
|
85
|
+
the following:
|
|
86
|
+
|
|
87
|
+
a) Give prominent notice with each copy of the Combined Work that
|
|
88
|
+
the Library is used in it and that the Library and its use are
|
|
89
|
+
covered by this License.
|
|
90
|
+
|
|
91
|
+
b) Accompany the Combined Work with a copy of the GNU GPL and this license
|
|
92
|
+
document.
|
|
93
|
+
|
|
94
|
+
c) For a Combined Work that displays copyright notices during
|
|
95
|
+
execution, include the copyright notice for the Library among
|
|
96
|
+
these notices, as well as a reference directing the user to the
|
|
97
|
+
copies of the GNU GPL and this license document.
|
|
98
|
+
|
|
99
|
+
d) Do one of the following:
|
|
100
|
+
|
|
101
|
+
0) Convey the Minimal Corresponding Source under the terms of this
|
|
102
|
+
License, and the Corresponding Application Code in a form
|
|
103
|
+
suitable for, and under terms that permit, the user to
|
|
104
|
+
recombine or relink the Application with a modified version of
|
|
105
|
+
the Linked Version to produce a modified Combined Work, in the
|
|
106
|
+
manner specified by section 6 of the GNU GPL for conveying
|
|
107
|
+
Corresponding Source.
|
|
108
|
+
|
|
109
|
+
1) Use a suitable shared library mechanism for linking with the
|
|
110
|
+
Library. A suitable mechanism is one that (a) uses at run time
|
|
111
|
+
a copy of the Library already present on the user's computer
|
|
112
|
+
system, and (b) will operate properly with a modified version
|
|
113
|
+
of the Library that is interface-compatible with the Linked
|
|
114
|
+
Version.
|
|
115
|
+
|
|
116
|
+
e) Provide Installation Information, but only if you would otherwise
|
|
117
|
+
be required to provide such information under section 6 of the
|
|
118
|
+
GNU GPL, and only to the extent that such information is
|
|
119
|
+
necessary to install and execute a modified version of the
|
|
120
|
+
Combined Work produced by recombining or relinking the
|
|
121
|
+
Application with a modified version of the Linked Version. (If
|
|
122
|
+
you use option 4d0, the Installation Information must accompany
|
|
123
|
+
the Minimal Corresponding Source and Corresponding Application
|
|
124
|
+
Code. If you use option 4d1, you must provide the Installation
|
|
125
|
+
Information in the manner specified by section 6 of the GNU GPL
|
|
126
|
+
for conveying Corresponding Source.)
|
|
127
|
+
|
|
128
|
+
5. Combined Libraries.
|
|
129
|
+
|
|
130
|
+
You may place library facilities that are a work based on the
|
|
131
|
+
Library side by side in a single library together with other library
|
|
132
|
+
facilities that are not Applications and are not covered by this
|
|
133
|
+
License, and convey such a combined library under terms of your
|
|
134
|
+
choice, if you do both of the following:
|
|
135
|
+
|
|
136
|
+
a) Accompany the combined library with a copy of the same work based
|
|
137
|
+
on the Library, uncombined with any other library facilities,
|
|
138
|
+
conveyed under the terms of this License.
|
|
139
|
+
|
|
140
|
+
b) Give prominent notice with the combined library that part of it
|
|
141
|
+
is a work based on the Library, and explaining where to find the
|
|
142
|
+
accompanying uncombined form of the same work.
|
|
143
|
+
|
|
144
|
+
6. Revised Versions of the GNU Lesser General Public License.
|
|
145
|
+
|
|
146
|
+
The Free Software Foundation may publish revised and/or new versions
|
|
147
|
+
of the GNU Lesser General Public License from time to time. Such new
|
|
148
|
+
versions will be similar in spirit to the present version, but may
|
|
149
|
+
differ in detail to address new problems or concerns.
|
|
150
|
+
|
|
151
|
+
Each version is given a distinguishing version number. If the
|
|
152
|
+
Library as you received it specifies that a certain numbered version
|
|
153
|
+
of the GNU Lesser General Public License "or any later version"
|
|
154
|
+
applies to it, you have the option of following the terms and
|
|
155
|
+
conditions either of that published version or of any later version
|
|
156
|
+
published by the Free Software Foundation. If the Library as you
|
|
157
|
+
received it does not specify a version number of the GNU Lesser
|
|
158
|
+
General Public License, you may choose any version of the GNU Lesser
|
|
159
|
+
General Public License ever published by the Free Software Foundation.
|
|
160
|
+
|
|
161
|
+
If the Library as you received it specifies that a proxy can decide
|
|
162
|
+
whether future versions of the GNU Lesser General Public License shall
|
|
163
|
+
apply, that proxy's public statement of acceptance of any version is
|
|
164
|
+
permanent authorization for you to choose that version for the
|
|
165
|
+
Library.
|
|
166
|
+
|
package/README.md
CHANGED
|
@@ -86,6 +86,7 @@ values, errors and touched fields in `$state`, with react-hook-form's options:
|
|
|
86
86
|
<Form
|
|
87
87
|
owner={createFormState({
|
|
88
88
|
defaultValues: { email: "" },
|
|
89
|
+
errors: form?.errors, // messages to show from the start, such as an action's
|
|
89
90
|
validate: (values) => ({ email: values.email ? undefined : "Email is required" }),
|
|
90
91
|
mode: "onSubmit", // or "onChange", "onBlur", "onTouched"
|
|
91
92
|
onSubmit: (values) => save(values), // unset: a valid form posts natively
|
|
@@ -101,13 +102,17 @@ show the owner's message for a missing required value. The owner also exposes
|
|
|
101
102
|
|
|
102
103
|
The owner sees each submit before the form's other listeners, and a submit it
|
|
103
104
|
stops reaches `onsubmit` but none of them, so `<Form method="POST" owner={…}
|
|
104
|
-
{@attach fromAction(enhance)}>` posts only a valid form.
|
|
105
|
+
{@attach fromAction(enhance)}>` posts only a valid form. Seed such an owner from the
|
|
106
|
+
action's answer (`defaultValues: form?.values`, `errors: form?.errors`) so it
|
|
107
|
+
renders the answer on the server; the Progressive Enhancement guide in the
|
|
108
|
+
package's Storybook walks through the pattern and `enhance`'s reset.
|
|
105
109
|
|
|
106
110
|
Any object meeting the contract is an owner:
|
|
107
111
|
|
|
108
112
|
```ts
|
|
109
113
|
type FormOwner<Values> = {
|
|
110
114
|
readonly values: Values; // must be reactive under runes, as `$state` is
|
|
115
|
+
getValue?(name): unknown; // unset: fields read the path in `values`
|
|
111
116
|
setValue(name, value): void; // `undefined` drops the value
|
|
112
117
|
getError?(name): string | undefined;
|
|
113
118
|
blur?(name): void;
|
|
@@ -115,9 +120,14 @@ type FormOwner<Values> = {
|
|
|
115
120
|
};
|
|
116
121
|
```
|
|
117
122
|
|
|
118
|
-
- `
|
|
119
|
-
|
|
120
|
-
|
|
123
|
+
- `bindTanStackForm(form)` makes a TanStack Form instance an owner:
|
|
124
|
+
`<Form owner={bindTanStackForm(form)}>`. It reads values (nested ones too) with
|
|
125
|
+
TanStack's own path read, shows a schema issue's `message`, runs the `onBlur`
|
|
126
|
+
validators when a field is left, submits through `handleSubmit`, and resets
|
|
127
|
+
the form. `@tanstack/svelte-form` is an optional peer dependency.
|
|
128
|
+
- `createBinding(source)` adapts any other store that is not reactive under
|
|
129
|
+
runes (`getValues`, `setValue`, `subscribe`, plus the optional methods
|
|
130
|
+
above) into an owner; `bindTanStackForm` is built on it.
|
|
121
131
|
- `createValidatedBinding(owner, checks)` adds latest-only asynchronous checks
|
|
122
132
|
per field to an owner that can `reset`. A field keeps its previous message
|
|
123
133
|
while its check runs and when the check fails; a submit is stopped while a
|
|
@@ -127,6 +137,199 @@ type FormOwner<Values> = {
|
|
|
127
137
|
`bind:value={() => owner.values.email, (v) => owner.setValue("email", v)}`
|
|
128
138
|
and spread `{...bindField(owner, "email")}` for `error` and `onblur`.
|
|
129
139
|
|
|
140
|
+
### Nested names
|
|
141
|
+
|
|
142
|
+
A name reaches into nested values, as react-hook-form's names do:
|
|
143
|
+
`address.city` or `contacts.0.email`, and SvelteKit's `contacts[0].email`.
|
|
144
|
+
`createFormState` writes the value at its path, creating the objects along it
|
|
145
|
+
(an array where the next segment is an index), and keys `errors` and `touched`
|
|
146
|
+
by the path joined with `.`, the keys `createSchemaValidator` gives its messages.
|
|
147
|
+
`getPath(values, name)` and `setPath(values, name, value)` read and write a
|
|
148
|
+
path in either form. `Path<Values>` and `PathValue<Values, Path>` type the
|
|
149
|
+
names and values of the owner methods, `bindField` and `bindFieldArray`;
|
|
150
|
+
`Field`'s `name` stays a string. A `condition` receives the nested values, and
|
|
151
|
+
a field that hides writes `undefined` at its path. Without an owner, a nested
|
|
152
|
+
name is posted as given, for the server to decode.
|
|
153
|
+
|
|
154
|
+
### Field arrays
|
|
155
|
+
|
|
156
|
+
`bindFieldArray(owner, name)` binds a list of repeated fields to the array at
|
|
157
|
+
`name`, as react-hook-form's `useFieldArray`. Its `items` carry a `key` that
|
|
158
|
+
stays with each item across `move` and `remove`; `append`, `remove`, `move` and
|
|
159
|
+
`replace` write the whole array through `owner.setValue`, so the owner's
|
|
160
|
+
validation mode applies, and `createFormState` moves the messages showing
|
|
161
|
+
inside the array with their items:
|
|
162
|
+
|
|
163
|
+
```svelte
|
|
164
|
+
<script lang="ts">
|
|
165
|
+
const owner = createFormState({ defaultValues: { contacts: [{ email: "" }] } });
|
|
166
|
+
const contacts = bindFieldArray(owner, "contacts");
|
|
167
|
+
</script>
|
|
168
|
+
|
|
169
|
+
<Form {owner}>
|
|
170
|
+
{#each contacts.items as item, index (item.key)}
|
|
171
|
+
<Field inputType="email" name={`contacts.${index}.email`} label="Email" />
|
|
172
|
+
<Button type="button" onclick={() => contacts.remove(index)}>Remove</Button>
|
|
173
|
+
{/each}
|
|
174
|
+
<Button type="button" onclick={() => contacts.append({ email: "" })}>Add</Button>
|
|
175
|
+
</Form>
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
Without an owner, a plain `{#each}` over your own `$state` array works too.
|
|
179
|
+
|
|
180
|
+
### Checkbox and radio groups
|
|
181
|
+
|
|
182
|
+
Checkboxes that share a `name` and give a `controlValue` hold an array of the
|
|
183
|
+
checked ones' values in the owner, as react-hook-form's checkboxes do:
|
|
184
|
+
`<Field inputType="checkbox" name="toppings" controlValue="ham" controlLabel="Ham" />`.
|
|
185
|
+
Without an owner, bind `group` on `CheckboxField` or `CheckboxInput` (an array)
|
|
186
|
+
or `RadioInput` (a string, empty when nothing is selected), as Svelte's
|
|
187
|
+
`bind:group` does for inputs in one component. `bind:group` takes no function
|
|
188
|
+
binding; bind an accessor to reach an owner:
|
|
189
|
+
|
|
190
|
+
```svelte
|
|
191
|
+
<script lang="ts">
|
|
192
|
+
const plan = {
|
|
193
|
+
get value() { return owner.values.plan; },
|
|
194
|
+
set value(next) { owner.setValue("plan", next); },
|
|
195
|
+
};
|
|
196
|
+
</script>
|
|
197
|
+
|
|
198
|
+
<RadioInput name="plan" value="pro" bind:group={plan.value} />
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
`ChoicesField` keeps binding its `value` for a group rendered from `options`.
|
|
202
|
+
|
|
203
|
+
### Schema validation (optional)
|
|
204
|
+
|
|
205
|
+
To check the whole form against one schema instead of writing `validate` by
|
|
206
|
+
hand, use `createSchemaValidator(schema)`. It accepts any
|
|
207
|
+
[Standard Schema](https://standardschema.dev): Zod 3.24 or later, Valibot or
|
|
208
|
+
ArkType. This package does not include a schema library, so add one:
|
|
209
|
+
|
|
210
|
+
```bash
|
|
211
|
+
bun add zod
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
```ts
|
|
215
|
+
import { createFormState, createSchemaValidator } from "@canonical/svelte-ds-global-form";
|
|
216
|
+
import { z } from "zod";
|
|
217
|
+
|
|
218
|
+
const schema = z.object({
|
|
219
|
+
name: z.string().min(1, "Name is required"),
|
|
220
|
+
email: z.string().email("Enter a valid email"),
|
|
221
|
+
});
|
|
222
|
+
|
|
223
|
+
const owner = createFormState({
|
|
224
|
+
validate: createSchemaValidator(schema),
|
|
225
|
+
defaultValues: { name: "", email: "" },
|
|
226
|
+
});
|
|
227
|
+
// <Form {owner} …> — no per-field checks needed
|
|
228
|
+
```
|
|
229
|
+
|
|
230
|
+
The values are typed from the schema. Messages are keyed by the issue's path
|
|
231
|
+
joined with `.` (`address.city`), and the first message for a path wins.
|
|
232
|
+
`createFormState` validates synchronously, so a schema that validates
|
|
233
|
+
asynchronously throws a `TypeError`; check that rule with
|
|
234
|
+
`createValidatedBinding`. The same schema validates a SvelteKit action through
|
|
235
|
+
`schema.safeParse(…)`, and TanStack Form through its own `validators`.
|
|
236
|
+
|
|
237
|
+
### SvelteKit remote forms
|
|
238
|
+
|
|
239
|
+
A SvelteKit [remote form](https://svelte.dev/docs/kit/remote-functions#form)
|
|
240
|
+
holds its values, validates them with a Standard Schema on the server, and can
|
|
241
|
+
check them in the browser first with `preflight`. Remote functions are
|
|
242
|
+
experimental: turn on `kit.experimental.remoteFunctions` and
|
|
243
|
+
`compilerOptions.experimental.async` in `svelte.config.js`. `@sveltejs/kit` is
|
|
244
|
+
an optional peer dependency, read for its types only.
|
|
245
|
+
|
|
246
|
+
```ts
|
|
247
|
+
// data.remote.ts
|
|
248
|
+
import { form } from "$app/server";
|
|
249
|
+
import { z } from "zod";
|
|
250
|
+
|
|
251
|
+
export const save = form(
|
|
252
|
+
z.object({ name: z.string().min(1), age: z.number(), agree: z.boolean().optional() }),
|
|
253
|
+
async (data) => { /* … */ },
|
|
254
|
+
);
|
|
255
|
+
```
|
|
256
|
+
|
|
257
|
+
For a field whose value is a string, spread SvelteKit's own `.as(type)` and
|
|
258
|
+
pass the first issue as `error`:
|
|
259
|
+
|
|
260
|
+
```svelte
|
|
261
|
+
<form {...save}>
|
|
262
|
+
<Field inputType="text" label="Name" {...save.fields.name.as("text")}
|
|
263
|
+
error={save.fields.name.issues()?.at(0)?.message} />
|
|
264
|
+
</form>
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
This works for `text`, `email`, `tel`, `url`, `password`, `select`, multiple
|
|
268
|
+
`select` and `hidden` (a hidden field takes no `label`). SvelteKit tracks the
|
|
269
|
+
value through the form's `input` events, and `set()` shows in the field.
|
|
270
|
+
|
|
271
|
+
`bindRemoteField(field, inputType)` covers every field kind, and is the way
|
|
272
|
+
for the rest:
|
|
273
|
+
|
|
274
|
+
```svelte
|
|
275
|
+
<script lang="ts">
|
|
276
|
+
import { Field, bindRemoteField } from "@canonical/svelte-ds-global-form";
|
|
277
|
+
import { save } from "./data.remote";
|
|
278
|
+
</script>
|
|
279
|
+
|
|
280
|
+
<form {...save}>
|
|
281
|
+
<Field {...bindRemoteField(save.fields.name, "text")} label="Name" />
|
|
282
|
+
<Field {...bindRemoteField(save.fields.age, "number")} label="Age" />
|
|
283
|
+
<Field {...bindRemoteField(save.fields.agree, "checkbox")} controlLabel="I agree" isOptional />
|
|
284
|
+
<Field {...bindRemoteField(save.fields.tags, "choices", { multiple: true })} label="Tags" {options} />
|
|
285
|
+
</form>
|
|
286
|
+
```
|
|
287
|
+
|
|
288
|
+
- `name` is the one `.as(type)` gives: `n:age` for a number and `b:agree` for a
|
|
289
|
+
checkbox, so the server decodes the right type, and `tags[]` for an array.
|
|
290
|
+
- `value` reads and writes the remote form's value, so every control binds,
|
|
291
|
+
including those that fire no `input` event (a combobox, a dropped file). A
|
|
292
|
+
single file is bound as a list of one.
|
|
293
|
+
- `error` is the field's first issue.
|
|
294
|
+
- The `inputType` must post the field's value type: a number field takes
|
|
295
|
+
`number`, `range`, `rating` or `hidden`, and TypeScript rejects `text`. A kind that
|
|
296
|
+
holds several values (`select`, `choices`, `rich-choices`, `combobox`,
|
|
297
|
+
`file`) takes `{ multiple: true }` when the value is an array, and the
|
|
298
|
+
binding sets the field's `multiple` or `isMultiple`. A `custom` field names
|
|
299
|
+
its SvelteKit type: `{ type: "number" }`.
|
|
300
|
+
|
|
301
|
+
`bindRemoteForm(form)` makes the remote form a `Form`'s owner, so fields bind by
|
|
302
|
+
name, nested names and field arrays included:
|
|
303
|
+
|
|
304
|
+
```svelte
|
|
305
|
+
<script lang="ts">
|
|
306
|
+
const owner = bindRemoteForm(save);
|
|
307
|
+
</script>
|
|
308
|
+
|
|
309
|
+
<Form {...save} {owner}>
|
|
310
|
+
<Field inputType="text" name="address.city" label="City" />
|
|
311
|
+
<Field inputType="number" name={save.fields.age.as("number").name} label="Age" />
|
|
312
|
+
</Form>
|
|
313
|
+
```
|
|
314
|
+
|
|
315
|
+
It reads the values, writes through each field's `set`, and shows each field's
|
|
316
|
+
first issue. It has no `submit`: the remote form submits and validates. A
|
|
317
|
+
number or checkbox field still needs SvelteKit's prefixed name to post its
|
|
318
|
+
type; the owner finds the field under either name.
|
|
319
|
+
|
|
320
|
+
Caveats:
|
|
321
|
+
|
|
322
|
+
- Prefer `bindRemoteField` or the owner to the native spread when you pass your
|
|
323
|
+
own `error`: the spread's `aria-invalid` follows SvelteKit's issues and
|
|
324
|
+
replaces the field's own.
|
|
325
|
+
- The native spread gives a number or date field a string value, which
|
|
326
|
+
TypeScript rejects; use `bindRemoteField`.
|
|
327
|
+
- A hidden field's prefix follows its value's type, so give it a value.
|
|
328
|
+
- SvelteKit resets the form after a successful submit, and shows a field's
|
|
329
|
+
issues once it was changed or the form submitted.
|
|
330
|
+
- Without JavaScript the form posts natively and the server validates; the
|
|
331
|
+
issues show when the page renders again.
|
|
332
|
+
|
|
130
333
|
## Remote validation and options
|
|
131
334
|
|
|
132
335
|
Middleware that changes the control is a Svelte attachment. `{@attach}` on a
|
|
@@ -199,9 +402,10 @@ the browser fires no event. A custom `component` renders its own error.
|
|
|
199
402
|
Fields render their values on the server, carry native `name`, `required` and
|
|
200
403
|
constraint attributes, and post with the form, so a `Form` without an owner
|
|
201
404
|
works with SvelteKit actions and with JavaScript disabled. Pass the action's
|
|
202
|
-
messages back as `error`.
|
|
203
|
-
|
|
204
|
-
|
|
405
|
+
messages back as `error`. An owned form renders and posts without JavaScript
|
|
406
|
+
too, showing the action's answer when the owner is seeded from it; the owner's
|
|
407
|
+
checks, `condition`, `validateRemotely` and `createRemoteOptions` need
|
|
408
|
+
JavaScript. Fetch options in `load` to have them on the server.
|
|
205
409
|
|
|
206
410
|
`file` fields post their files without JavaScript: the named file input mirrors
|
|
207
411
|
the bound files, including dropped ones. A plain form needs
|
|
@@ -219,7 +423,8 @@ The presentational inputs work outside a form, for example in a filter bar:
|
|
|
219
423
|
`TextInput`, `NumberInput`, `PasswordInput`, `TextareaInput`, `SelectInput`,
|
|
220
424
|
`DateInput`, `TimeInput`, `DateTimeInput`, `RangeInput`, `HiddenInput` and
|
|
221
425
|
`PhoneInput` bind `value`; `CheckboxInput`, `SwitchInput` and `RadioInput` bind
|
|
222
|
-
`checked
|
|
426
|
+
`checked`, and `CheckboxInput` and `RadioInput` also bind `group`;
|
|
427
|
+
`FileUploadInput` binds `files`.
|
|
223
428
|
|
|
224
429
|
## File upload
|
|
225
430
|
|
|
@@ -2,17 +2,35 @@
|
|
|
2
2
|
import splitChromeProps from "../../common/splitChromeProps.js";
|
|
3
3
|
import ToggleWrapper from "../../common/Wrapper/ToggleWrapper.svelte";
|
|
4
4
|
import { CheckboxInput } from "../../subcomponent/CheckboxInput/index.js";
|
|
5
|
+
import { toggleChoice } from "../../utils/index.js";
|
|
5
6
|
import type { CheckboxFieldProps } from "./types.js";
|
|
6
7
|
|
|
7
|
-
let {
|
|
8
|
+
let {
|
|
9
|
+
value = $bindable(),
|
|
10
|
+
group = $bindable(),
|
|
11
|
+
controlValue,
|
|
12
|
+
...props
|
|
13
|
+
}: CheckboxFieldProps = $props();
|
|
8
14
|
|
|
9
15
|
const { chrome, control } = $derived(splitChromeProps(props));
|
|
16
|
+
|
|
17
|
+
/** Drops the field's value, and its choice from the group, when it hides. */
|
|
18
|
+
function hide(): void {
|
|
19
|
+
value = undefined;
|
|
20
|
+
if (group !== undefined)
|
|
21
|
+
group = toggleChoice(
|
|
22
|
+
group,
|
|
23
|
+
controlValue ?? "on",
|
|
24
|
+
false,
|
|
25
|
+
true,
|
|
26
|
+
) as string[];
|
|
27
|
+
}
|
|
10
28
|
</script>
|
|
11
29
|
|
|
12
|
-
<ToggleWrapper {...chrome} onhide={
|
|
30
|
+
<ToggleWrapper {...chrome} onhide={hide}>{#snippet children(controlProps)}<CheckboxInput {...controlProps} {...control} name={chrome.name} value={controlValue} bind:checked={value} bind:group />{/snippet}</ToggleWrapper>
|
|
13
31
|
|
|
14
32
|
<!-- @component
|
|
15
|
-
CheckboxInput wrapped with the toggle field chrome (inline label, optional heading, description, error) and conditional display. Requires at least one of `label`/`controlLabel`. Bind `value` to the checked state.
|
|
33
|
+
CheckboxInput wrapped with the toggle field chrome (inline label, optional heading, description, error) and conditional display. Requires at least one of `label`/`controlLabel`. Bind `value` to the checked state, or bind `group` to an array shared by several checkboxes, which holds the `controlValue` of each checked one.
|
|
16
34
|
|
|
17
35
|
`import { CheckboxField } from "@canonical/svelte-ds-global-form";`
|
|
18
36
|
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import type { CheckboxFieldProps } from "./types.js";
|
|
2
2
|
/**
|
|
3
|
-
* CheckboxInput wrapped with the toggle field chrome (inline label, optional heading, description, error) and conditional display. Requires at least one of `label`/`controlLabel`. Bind `value` to the checked state.
|
|
3
|
+
* CheckboxInput wrapped with the toggle field chrome (inline label, optional heading, description, error) and conditional display. Requires at least one of `label`/`controlLabel`. Bind `value` to the checked state, or bind `group` to an array shared by several checkboxes, which holds the `controlValue` of each checked one.
|
|
4
4
|
*
|
|
5
5
|
* `import { CheckboxField } from "@canonical/svelte-ds-global-form";`
|
|
6
6
|
*
|
|
7
7
|
* @implements ds:global.component.checkbox_field
|
|
8
8
|
*/
|
|
9
|
-
declare const CheckboxField: import("svelte").Component<CheckboxFieldProps, {}, "value">;
|
|
9
|
+
declare const CheckboxField: import("svelte").Component<CheckboxFieldProps, {}, "value" | "group">;
|
|
10
10
|
type CheckboxField = ReturnType<typeof CheckboxField>;
|
|
11
11
|
export default CheckboxField;
|
|
@@ -4,7 +4,19 @@ import type { CheckboxInputProps } from "../../subcomponent/CheckboxInput/types.
|
|
|
4
4
|
* Props for the CheckboxField: toggle chrome plus the CheckboxInput props. `value` is the
|
|
5
5
|
* checked state; at least one of `label`/`controlLabel` is required.
|
|
6
6
|
*/
|
|
7
|
-
export type CheckboxFieldProps = ToggleChromeProps & Omit<CheckboxInputProps, "id" | "class" | "style" | "name" | "checked" | "value"> & {
|
|
7
|
+
export type CheckboxFieldProps = ToggleChromeProps & Omit<CheckboxInputProps, "id" | "class" | "style" | "name" | "checked" | "value" | "group"> & {
|
|
8
8
|
/** Whether the control is checked. Bindable. */
|
|
9
9
|
value?: boolean;
|
|
10
|
+
/**
|
|
11
|
+
* The value the checkbox posts when checked, and adds to `group`.
|
|
12
|
+
* Default: the browser's "on".
|
|
13
|
+
*/
|
|
14
|
+
controlValue?: string;
|
|
15
|
+
/**
|
|
16
|
+
* The values of the checked checkboxes of a group sharing one `name`:
|
|
17
|
+
* checking this one adds its `controlValue`, unchecking it removes it, and
|
|
18
|
+
* hiding it removes it. Start it as an array; `value` is ignored while it
|
|
19
|
+
* is set. Bindable.
|
|
20
|
+
*/
|
|
21
|
+
group?: string[];
|
|
10
22
|
};
|
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
<script lang="ts">
|
|
2
2
|
import { untrack } from "svelte";
|
|
3
|
-
import
|
|
3
|
+
import {
|
|
4
|
+
isChoiceChecked,
|
|
5
|
+
readEditedChoices,
|
|
6
|
+
toggleChoice,
|
|
7
|
+
} from "../../utils/index.js";
|
|
4
8
|
import { Option } from "./common/index.js";
|
|
5
|
-
import isChoiceChecked from "./isChoiceChecked.js";
|
|
6
|
-
import toggleChoice from "./toggleChoice.js";
|
|
7
9
|
import type { ChoicesProps } from "./types.js";
|
|
8
10
|
import "./styles.css";
|
|
9
11
|
|
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
<script lang="ts">
|
|
2
2
|
import { untrack } from "svelte";
|
|
3
|
-
import
|
|
4
|
-
|
|
5
|
-
|
|
3
|
+
import {
|
|
4
|
+
isChoiceChecked,
|
|
5
|
+
readEditedChoices,
|
|
6
|
+
toggleChoice,
|
|
7
|
+
} from "../../utils/index.js";
|
|
6
8
|
import { Option } from "./common/index.js";
|
|
7
9
|
import type { RichChoicesProps } from "./types.js";
|
|
8
10
|
import "./styles.css";
|
package/dist/index.d.ts
CHANGED
|
@@ -13,5 +13,5 @@ export { VALIDITY_EVENT } from "./common/constants.js";
|
|
|
13
13
|
export * from "./pattern/index.js";
|
|
14
14
|
export type { CheckboxInputProps, DateInputProps, DateTimeInputProps, FileMessage, FileMessageLevel, FileUploadInputProps, FileUploadMessages, HiddenInputProps, NumberInputProps, PasswordInputProps, PhoneCountry, PhoneInputProps, PhoneValue, RadioInputProps, RangeInputProps, SelectInputProps, SwitchInputProps, TextareaInputProps, TextInputProps, TextInputType, TimeInputProps, UploadFunction, UploadOptions, UploadSummary, } from "./subcomponent/index.js";
|
|
15
15
|
export { CheckboxInput, DateInput, DateTimeInput, FileUploadInput, HiddenInput, NumberInput, PasswordInput, PhoneInput, RadioInput, RangeInput, SelectInput, SwitchInput, TextareaInput, TextInput, TimeInput, } from "./subcomponent/index.js";
|
|
16
|
-
export type { BindingSource, FieldBinding, FieldValidator, FormErrors, FormOwner, FormState, FormStateOptions, FormValues, LatestOutcome, OptionsFetchOptions, RESTValidationOptions, RemoteCheck, RemoteOptions, RemoteOptionsFieldProps, RemoteValidationOptions, ResettableOwner, ValidatedControl, ValidatedOwner, ValidationMode, } from "./utils/index.js";
|
|
17
|
-
export { bindField, createBinding, createFormState, createRemoteOptions, createValidatedBinding, decodePhone, extractPhoneDigits, fetchOptions, formatPhone, runLatest, validateRemotely, } from "./utils/index.js";
|
|
16
|
+
export type { BindingSource, FieldArray, FieldArrayItem, FieldBinding, FieldInputType, FieldValidator, FittingInputType, FormErrors, FormOwner, FormState, FormStateOptions, FormValues, KitInputType, LatestOutcome, OptionsFetchOptions, Path, PathValue, RESTValidationOptions, RemoteCheck, RemoteFieldBinding, RemoteFieldOptions, RemoteFormOf, RemoteOptions, RemoteOptionsFieldProps, RemoteValidationOptions, ResettableOwner, StandardSchema, StandardSchemaIssue, StandardSchemaResult, TanStackFormApi, ValidatedControl, ValidatedOwner, ValidationMode, } from "./utils/index.js";
|
|
17
|
+
export { bindField, bindFieldArray, bindRemoteField, bindRemoteForm, bindTanStackForm, createBinding, createFormState, createRemoteOptions, createSchemaValidator, createValidatedBinding, decodePhone, extractPhoneDigits, fetchOptions, formatPhone, getPath, runLatest, setPath, validateRemotely, } from "./utils/index.js";
|
package/dist/index.js
CHANGED
|
@@ -2,4 +2,4 @@ export { ColorInput, ComboboxInput, RatingInput, } from "./_work_in_progress/ind
|
|
|
2
2
|
export { VALIDITY_EVENT } from "./common/constants.js";
|
|
3
3
|
export * from "./pattern/index.js";
|
|
4
4
|
export { CheckboxInput, DateInput, DateTimeInput, FileUploadInput, HiddenInput, NumberInput, PasswordInput, PhoneInput, RadioInput, RangeInput, SelectInput, SwitchInput, TextareaInput, TextInput, TimeInput, } from "./subcomponent/index.js";
|
|
5
|
-
export { bindField, createBinding, createFormState, createRemoteOptions, createValidatedBinding, decodePhone, extractPhoneDigits, fetchOptions, formatPhone, runLatest, validateRemotely, } from "./utils/index.js";
|
|
5
|
+
export { bindField, bindFieldArray, bindRemoteField, bindRemoteForm, bindTanStackForm, createBinding, createFormState, createRemoteOptions, createSchemaValidator, createValidatedBinding, decodePhone, extractPhoneDigits, fetchOptions, formatPhone, getPath, runLatest, setPath, validateRemotely, } from "./utils/index.js";
|
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
import { TextareaField } from "../../component/TextareaField/index.js";
|
|
19
19
|
import { TextField } from "../../component/TextField/index.js";
|
|
20
20
|
import { TimeField } from "../../component/TimeField/index.js";
|
|
21
|
-
import { getFormOwnerContext } from "../../utils/
|
|
21
|
+
import { getFormOwnerContext, readOwnerValue } from "../../utils/index.js";
|
|
22
22
|
import type { FieldProps } from "./types.js";
|
|
23
23
|
|
|
24
24
|
let { value = $bindable(), ...props }: FieldProps<Extra, Value> = $props();
|
|
@@ -61,13 +61,29 @@
|
|
|
61
61
|
});
|
|
62
62
|
// The bound value's type follows `inputType`, which the branches below
|
|
63
63
|
// narrow; these accessors carry it across without a cast per branch, and
|
|
64
|
-
// read and write the owner's value
|
|
64
|
+
// read and write the owner's value at the field's path when it is owned.
|
|
65
65
|
const getValue = () =>
|
|
66
|
-
(valueOwner ? valueOwner
|
|
66
|
+
(valueOwner ? readOwnerValue(valueOwner, props.name) : value) as never;
|
|
67
67
|
const setValue = (next: unknown) => {
|
|
68
68
|
if (valueOwner) valueOwner.setValue(props.name, next);
|
|
69
69
|
else value = next as typeof value;
|
|
70
70
|
};
|
|
71
|
+
// Owned checkboxes that share a name and give a `controlValue` hold an
|
|
72
|
+
// array of the checked ones' values, as react-hook-form's checkboxes do.
|
|
73
|
+
// `bind:group` takes no function binding, so it binds to an accessor.
|
|
74
|
+
const isOwnedGroup = $derived(
|
|
75
|
+
valueOwner !== undefined &&
|
|
76
|
+
(props as { controlValue?: string }).controlValue !== undefined,
|
|
77
|
+
);
|
|
78
|
+
const ownedGroup = {
|
|
79
|
+
get current(): string[] {
|
|
80
|
+
const current: unknown = getValue();
|
|
81
|
+
return Array.isArray(current) ? current : [];
|
|
82
|
+
},
|
|
83
|
+
set current(next: string[]) {
|
|
84
|
+
setValue(next);
|
|
85
|
+
},
|
|
86
|
+
};
|
|
71
87
|
// A custom component gets every prop but the routing ones, and renders its
|
|
72
88
|
// own label, description and error, as React's `CustomComponent` does.
|
|
73
89
|
// biome-ignore lint/suspicious/noExplicitAny: the component's props are the caller's
|
|
@@ -81,7 +97,7 @@
|
|
|
81
97
|
});
|
|
82
98
|
</script>
|
|
83
99
|
|
|
84
|
-
{#if props.inputType === "textarea"}<TextareaField {...routed} bind:value={getValue, setValue} />{:else if props.inputType === "checkbox"}<CheckboxField {...routed} bind:value={getValue, setValue} />{:else if props.inputType === "switch"}<SwitchField {...routed} bind:value={getValue, setValue} />{:else if props.inputType === "rating"}<RatingField {...routed} bind:value={getValue, setValue} />{:else if props.inputType === "range"}<RangeField {...routed} bind:value={getValue, setValue} />{:else if props.inputType === "select"}<SelectField {...routed} bind:value={getValue, setValue} />{:else if props.inputType === "choices"}<ChoicesField {...routed} bind:value={getValue, setValue} />{:else if props.inputType === "combobox"}<ComboboxField {...routed} bind:value={getValue, setValue} />{:else if props.inputType === "hidden"}<HiddenField {...routed} bind:value={getValue, setValue} />{:else if props.inputType === "date"}<DateField {...routed} bind:value={getValue, setValue} />{:else if props.inputType === "time"}<TimeField {...routed} bind:value={getValue, setValue} />{:else if props.inputType === "datetime"}<DateTimeField {...routed} bind:value={getValue, setValue} />{:else if props.inputType === "file"}<FileUploadField {...routed} bind:value={getValue, setValue} />{:else if props.inputType === "color"}<ColorField {...routed} bind:value={getValue, setValue} />{:else if props.inputType === "phone"}<PhoneField {...routed} bind:value={getValue, setValue} />{:else if props.inputType === "password"}<PasswordField {...routed} bind:value={getValue, setValue} />{:else if props.inputType === "number"}<NumberField {...routed} bind:value={getValue, setValue} />{:else if props.inputType === "rich-choices"}<RichChoicesField {...routed} bind:value={getValue, setValue} />{:else if props.inputType === "custom"}<custom.component {...custom.forwarded} bind:value={getValue, setValue} />{:else}<TextField {...routed} inputType={props.inputType} bind:value={getValue, setValue} />{/if}
|
|
100
|
+
{#if props.inputType === "textarea"}<TextareaField {...routed} bind:value={getValue, setValue} />{:else if props.inputType === "checkbox"}{#if isOwnedGroup}<CheckboxField {...routed} bind:group={ownedGroup.current} />{:else}<CheckboxField {...routed} bind:value={getValue, setValue} />{/if}{:else if props.inputType === "switch"}<SwitchField {...routed} bind:value={getValue, setValue} />{:else if props.inputType === "rating"}<RatingField {...routed} bind:value={getValue, setValue} />{:else if props.inputType === "range"}<RangeField {...routed} bind:value={getValue, setValue} />{:else if props.inputType === "select"}<SelectField {...routed} bind:value={getValue, setValue} />{:else if props.inputType === "choices"}<ChoicesField {...routed} bind:value={getValue, setValue} />{:else if props.inputType === "combobox"}<ComboboxField {...routed} bind:value={getValue, setValue} />{:else if props.inputType === "hidden"}<HiddenField {...routed} bind:value={getValue, setValue} />{:else if props.inputType === "date"}<DateField {...routed} bind:value={getValue, setValue} />{:else if props.inputType === "time"}<TimeField {...routed} bind:value={getValue, setValue} />{:else if props.inputType === "datetime"}<DateTimeField {...routed} bind:value={getValue, setValue} />{:else if props.inputType === "file"}<FileUploadField {...routed} bind:value={getValue, setValue} />{:else if props.inputType === "color"}<ColorField {...routed} bind:value={getValue, setValue} />{:else if props.inputType === "phone"}<PhoneField {...routed} bind:value={getValue, setValue} />{:else if props.inputType === "password"}<PasswordField {...routed} bind:value={getValue, setValue} />{:else if props.inputType === "number"}<NumberField {...routed} bind:value={getValue, setValue} />{:else if props.inputType === "rich-choices"}<RichChoicesField {...routed} bind:value={getValue, setValue} />{:else if props.inputType === "custom"}<custom.component {...custom.forwarded} bind:value={getValue, setValue} />{:else}<TextField {...routed} inputType={props.inputType} bind:value={getValue, setValue} />{/if}
|
|
85
101
|
|
|
86
102
|
<!-- @component
|
|
87
103
|
A form field pairs a single input with the meaning a user needs to act on it: a
|
|
@@ -32,7 +32,7 @@ type BuiltinFields = ({
|
|
|
32
32
|
inputType: "number";
|
|
33
33
|
} & NumberFieldProps) | ({
|
|
34
34
|
inputType: "checkbox";
|
|
35
|
-
} & CheckboxFieldProps) | ({
|
|
35
|
+
} & Omit<CheckboxFieldProps, "group">) | ({
|
|
36
36
|
inputType: "switch";
|
|
37
37
|
} & SwitchFieldProps) | ({
|
|
38
38
|
inputType: "hidden";
|