@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.
- package/README.md +213 -8
- package/dist/_work_in_progress/subcomponent/ComboboxInput/MultipleCombobox.svelte +1 -1
- package/dist/_work_in_progress/subcomponent/ComboboxInput/SingleCombobox.svelte +1 -1
- package/dist/common/useConditionalDisplay.svelte.js +1 -1
- 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/pattern/Form/Form.svelte +1 -2
- package/dist/pattern/Form/Form.svelte.d.ts +1 -1
- package/dist/pattern/Form/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/middleware/types.d.ts +1 -1
- package/dist/utils/middleware/validateRemotely.js +1 -1
- package/dist/utils/owner/bindField.d.ts +5 -3
- package/dist/utils/owner/bindField.js +3 -1
- package/dist/utils/owner/bindFieldArray.d.ts +24 -0
- package/dist/utils/owner/bindFieldArray.js +81 -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 +20 -2
- package/dist/utils/owner/createFormState.svelte.js +188 -32
- package/dist/utils/owner/createSchemaValidator.d.ts +20 -0
- package/dist/utils/owner/createSchemaValidator.js +39 -0
- package/dist/utils/owner/createValidatedBinding.d.ts +2 -2
- package/dist/utils/owner/createValidatedBinding.js +9 -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 +164 -14
- package/dist/utils/remoteForm/bindRemoteField.d.ts +24 -0
- package/dist/utils/remoteForm/bindRemoteField.js +69 -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 +23 -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/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
|
|
|
@@ -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/
|
|
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/
|
|
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/
|
|
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
|
|
@@ -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";
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
<script lang="ts" generics="Values extends FormValues = FormValues">
|
|
2
|
-
import { setFormOwnerContext } from "../../utils/
|
|
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,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/
|
|
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>`.
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
<script lang="ts">
|
|
2
|
+
import { isChoiceChecked, toggleChoice } from "../../utils/index.js";
|
|
2
3
|
import type { CheckboxInputProps } from "./types.js";
|
|
3
4
|
import "./styles.css";
|
|
4
5
|
|
|
@@ -9,14 +10,29 @@
|
|
|
9
10
|
class: className,
|
|
10
11
|
style,
|
|
11
12
|
checked = $bindable(),
|
|
13
|
+
group = $bindable(),
|
|
12
14
|
...rest
|
|
13
15
|
}: CheckboxInputProps = $props();
|
|
16
|
+
|
|
17
|
+
// The value the checkbox posts, and adds to `group` when checked.
|
|
18
|
+
const choice = $derived(String(rest.value ?? "on"));
|
|
19
|
+
|
|
20
|
+
// With a `group`, the checkbox is checked while the group holds its value,
|
|
21
|
+
// and checking it adds the value to the group, as Svelte's `bind:group`.
|
|
22
|
+
const readChecked = () =>
|
|
23
|
+
group === undefined ? checked : isChoiceChecked(group, choice, true);
|
|
24
|
+
const writeChecked = (next: boolean | undefined) => {
|
|
25
|
+
if (group === undefined) checked = next;
|
|
26
|
+
else group = toggleChoice(group, choice, Boolean(next), true) as string[];
|
|
27
|
+
};
|
|
14
28
|
</script>
|
|
15
29
|
|
|
16
|
-
<input {id} {style} class={[componentCssClassName, className]} bind:checked {...rest} type="checkbox" />
|
|
30
|
+
<input {id} {style} class={[componentCssClassName, className]} bind:checked={readChecked, writeChecked} {...rest} type="checkbox" />
|
|
17
31
|
|
|
18
32
|
<!-- @component
|
|
19
|
-
Presentational checkbox. Bind `checked` for two-way binding
|
|
33
|
+
Presentational checkbox. Bind `checked` for two-way binding, or bind `group`
|
|
34
|
+
to an array shared by several checkboxes, which holds the `value` of each
|
|
35
|
+
checked one, as Svelte's `bind:group` does for inputs in one component.
|
|
20
36
|
|
|
21
37
|
`import { CheckboxInput } from "@canonical/svelte-ds-global-form";`
|
|
22
38
|
|
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
import type { CheckboxInputProps } from "./types.js";
|
|
2
2
|
import "./styles.css";
|
|
3
3
|
/**
|
|
4
|
-
* Presentational checkbox. Bind `checked` for two-way binding
|
|
4
|
+
* Presentational checkbox. Bind `checked` for two-way binding, or bind `group`
|
|
5
|
+
* to an array shared by several checkboxes, which holds the `value` of each
|
|
6
|
+
* checked one, as Svelte's `bind:group` does for inputs in one component.
|
|
5
7
|
*
|
|
6
8
|
* `import { CheckboxInput } from "@canonical/svelte-ds-global-form";`
|
|
7
9
|
*
|
|
8
10
|
* @implements ds:global.subcomponent.checkbox_input
|
|
9
11
|
*/
|
|
10
|
-
declare const CheckboxInput: import("svelte").Component<CheckboxInputProps, {}, "checked">;
|
|
12
|
+
declare const CheckboxInput: import("svelte").Component<CheckboxInputProps, {}, "checked" | "group">;
|
|
11
13
|
type CheckboxInput = ReturnType<typeof CheckboxInput>;
|
|
12
14
|
export default CheckboxInput;
|
|
@@ -3,4 +3,11 @@ import type { HTMLInputAttributes } from "svelte/elements";
|
|
|
3
3
|
export type CheckboxInputProps = Omit<HTMLInputAttributes, "type"> & {
|
|
4
4
|
/** Whether the checkbox is checked. Bindable. */
|
|
5
5
|
checked?: boolean;
|
|
6
|
+
/**
|
|
7
|
+
* The values of the checked checkboxes of a group: the checkbox is checked
|
|
8
|
+
* while it holds `value`, and checking or unchecking it adds or removes
|
|
9
|
+
* `value`. Start it as an array; `checked` is ignored while it is set.
|
|
10
|
+
* Bindable.
|
|
11
|
+
*/
|
|
12
|
+
group?: string[];
|
|
6
13
|
};
|