@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
|
@@ -1,38 +1,173 @@
|
|
|
1
1
|
import { tick } from "svelte";
|
|
2
|
+
import getPath from "./getPath.js";
|
|
3
|
+
import normalizePath from "./normalizePath.js";
|
|
4
|
+
import setPath from "./setPath.js";
|
|
5
|
+
/** Tells whether `key` is the field `name` or a field inside it. */
|
|
6
|
+
const isWithin = (key, name) => key === name || key.startsWith(`${name}.`);
|
|
7
|
+
/**
|
|
8
|
+
* Joins the fields two validations update: `undefined` stands for every
|
|
9
|
+
* field.
|
|
10
|
+
*/
|
|
11
|
+
const joinScopes = (first, second) => (first && second ? [...first, ...second] : undefined);
|
|
12
|
+
/**
|
|
13
|
+
* Moves a key under the array `prefix` (as `contacts.`) to its item's new
|
|
14
|
+
* index, as `contacts.2.email` to `contacts.1.email`. Returns `undefined` for
|
|
15
|
+
* an item that is gone, and any other key as it is.
|
|
16
|
+
*/
|
|
17
|
+
function moveItemKey(key, prefix, toIndex) {
|
|
18
|
+
if (!key.startsWith(prefix))
|
|
19
|
+
return key;
|
|
20
|
+
const [segment, ...rest] = key.slice(prefix.length).split(".");
|
|
21
|
+
if (!/^\d+$/.test(String(segment)))
|
|
22
|
+
return key;
|
|
23
|
+
const index = toIndex(Number(segment));
|
|
24
|
+
return index === undefined ? undefined : [prefix + index, ...rest].join(".");
|
|
25
|
+
}
|
|
26
|
+
/** Focuses the first invalid control of `form`, once its error state renders. */
|
|
27
|
+
function focusFirstInvalid(form) {
|
|
28
|
+
void tick().then(() => form.querySelector('[aria-invalid="true"]')?.focus());
|
|
29
|
+
}
|
|
2
30
|
/**
|
|
3
31
|
* Builds a minimal form owner on `$state`: values, errors and touched fields,
|
|
4
32
|
* validated by one `validate` function at the time `mode` says, as
|
|
5
|
-
* react-hook-form's `useForm`.
|
|
33
|
+
* react-hook-form's `useForm`. Names reach into nested values, as
|
|
34
|
+
* `address.city` or `contacts.0.email` (SvelteKit's `contacts[0].email` too):
|
|
35
|
+
* a write creates the objects along the path, or an array where the next
|
|
36
|
+
* segment is an index, and errors and touched fields are keyed by the path
|
|
37
|
+
* joined with `.`, as `createSchemaValidator` keys its messages. Pass it to a `Form`:
|
|
6
38
|
*
|
|
7
39
|
* ```svelte
|
|
8
40
|
* <Form owner={createFormState({ defaultValues, validate, onSubmit })}>
|
|
9
41
|
* ```
|
|
10
42
|
*
|
|
43
|
+
* Seed `errors` with messages to show from the start, such as a SvelteKit
|
|
44
|
+
* action's `form.errors` after a post without JavaScript.
|
|
45
|
+
*
|
|
11
46
|
* On submit, every field is validated. An invalid form does not post and its
|
|
12
47
|
* first invalid control is focused. A valid form calls `onSubmit` instead of
|
|
13
48
|
* posting, or posts natively when `onSubmit` is unset. After the first submit,
|
|
14
49
|
* a field is validated again on its every change.
|
|
50
|
+
*
|
|
51
|
+
* `validate` may return a promise, as react-hook-form's asynchronous resolvers
|
|
52
|
+
* do. Only the latest validation counts, and `reset` cancels it. A submit that
|
|
53
|
+
* meets one is stopped, since a submit event can only be stopped at once; when
|
|
54
|
+
* the validation settles, a valid form calls `onSubmit`, or is submitted again
|
|
55
|
+
* with the same submitter so it posts (and SvelteKit's `enhance` sees it), and
|
|
56
|
+
* an invalid one focuses its first invalid control. A validation that throws
|
|
57
|
+
* keeps the messages as they are and drops the waiting submit.
|
|
58
|
+
*
|
|
59
|
+
* A field array (`bindFieldArray`) moves the errors and touched fields under
|
|
60
|
+
* its array with the items, through `reindex`, without validating.
|
|
15
61
|
* @note Pure: the returned owner holds its own state.
|
|
16
62
|
*/
|
|
17
|
-
export default function createFormState({ defaultValues = {}, validate, mode = "onSubmit", onSubmit, } = {}) {
|
|
63
|
+
export default function createFormState({ defaultValues = {}, errors: initialErrors = {}, validate, mode = "onSubmit", onSubmit, } = {}) {
|
|
18
64
|
const values = $state({ ...defaultValues });
|
|
19
|
-
const errors = $state(
|
|
65
|
+
const errors = $state(Object.fromEntries(Object.entries(initialErrors)
|
|
66
|
+
.filter((entry) => entry[1] !== undefined)
|
|
67
|
+
.map(([name, message]) => [normalizePath(name), message])));
|
|
20
68
|
const touched = $state({});
|
|
21
69
|
let isSubmitted = $state(false);
|
|
22
70
|
let isSubmitting = $state(false);
|
|
71
|
+
let isValidating = $state(false);
|
|
72
|
+
/** Counts the validations started, so a settling one knows if it is the latest. */
|
|
73
|
+
let latestRun = 0;
|
|
74
|
+
/** The fields the running validation updates when it settles. */
|
|
75
|
+
let pendingScope = [];
|
|
76
|
+
/** The submit waiting for the running validation. */
|
|
77
|
+
let pendingSubmit;
|
|
78
|
+
/** Is the form being submitted again after its validation passed. */
|
|
79
|
+
let isApproved = false;
|
|
23
80
|
/**
|
|
24
|
-
*
|
|
25
|
-
* Returns whether the whole form is valid.
|
|
81
|
+
* Updates the messages within `scope`, or of every field, from a
|
|
82
|
+
* validation's result. Returns whether the whole form is valid.
|
|
26
83
|
*/
|
|
27
|
-
function
|
|
28
|
-
const found = Object.entries(
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
84
|
+
function applyErrors(result, scope) {
|
|
85
|
+
const found = Object.entries(result)
|
|
86
|
+
.filter((entry) => entry[1] !== undefined)
|
|
87
|
+
.map(([name, message]) => [normalizePath(name), message]);
|
|
88
|
+
const isAffected = (key) => !scope || scope.some((name) => isWithin(key, name));
|
|
89
|
+
for (const key of Object.keys(errors))
|
|
90
|
+
if (isAffected(key))
|
|
91
|
+
delete errors[key];
|
|
92
|
+
for (const [key, message] of found)
|
|
93
|
+
if (isAffected(key))
|
|
94
|
+
errors[key] = message;
|
|
95
|
+
isValidating = false;
|
|
34
96
|
return found.length === 0;
|
|
35
97
|
}
|
|
98
|
+
/**
|
|
99
|
+
* Validates the form and updates the messages within `names`, or of every
|
|
100
|
+
* field. A validation that supersedes a running one also updates the fields
|
|
101
|
+
* that one would have. Returns whether the whole form is valid, or
|
|
102
|
+
* `undefined` while an asynchronous validation runs; the submit waiting for
|
|
103
|
+
* it completes when it settles.
|
|
104
|
+
*/
|
|
105
|
+
function runValidation(names) {
|
|
106
|
+
const scope = isValidating ? joinScopes(pendingScope, names) : names;
|
|
107
|
+
const run = ++latestRun;
|
|
108
|
+
const result = validate?.($state.snapshot(values)) ?? {};
|
|
109
|
+
if (!(result instanceof Promise)) {
|
|
110
|
+
const isValid = applyErrors(result, scope);
|
|
111
|
+
completeSubmit(isValid);
|
|
112
|
+
return isValid;
|
|
113
|
+
}
|
|
114
|
+
isValidating = true;
|
|
115
|
+
pendingScope = scope;
|
|
116
|
+
void result.then((resolved) => {
|
|
117
|
+
if (run === latestRun)
|
|
118
|
+
completeSubmit(applyErrors(resolved, scope));
|
|
119
|
+
}, () => {
|
|
120
|
+
if (run !== latestRun)
|
|
121
|
+
return;
|
|
122
|
+
isValidating = false;
|
|
123
|
+
pendingSubmit = undefined;
|
|
124
|
+
});
|
|
125
|
+
return undefined;
|
|
126
|
+
}
|
|
127
|
+
/** Calls `handleSubmit` with the values, tracking a promise it returns. */
|
|
128
|
+
function callOnSubmit(handleSubmit) {
|
|
129
|
+
const done = handleSubmit($state.snapshot(values));
|
|
130
|
+
if (!(done instanceof Promise))
|
|
131
|
+
return;
|
|
132
|
+
isSubmitting = true;
|
|
133
|
+
void done.finally(() => {
|
|
134
|
+
isSubmitting = false;
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Completes the submit waiting for a validation, if any: focuses the first
|
|
139
|
+
* invalid control, calls `onSubmit`, or submits the form again, which this
|
|
140
|
+
* owner lets through.
|
|
141
|
+
*/
|
|
142
|
+
function completeSubmit(isValid) {
|
|
143
|
+
const waiting = pendingSubmit;
|
|
144
|
+
if (!waiting)
|
|
145
|
+
return;
|
|
146
|
+
pendingSubmit = undefined;
|
|
147
|
+
if (!isValid)
|
|
148
|
+
focusFirstInvalid(waiting.form);
|
|
149
|
+
else if (onSubmit)
|
|
150
|
+
callOnSubmit(onSubmit);
|
|
151
|
+
else {
|
|
152
|
+
isApproved = true;
|
|
153
|
+
try {
|
|
154
|
+
waiting.form.requestSubmit(waiting.submitter);
|
|
155
|
+
}
|
|
156
|
+
finally {
|
|
157
|
+
isApproved = false;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
/** Moves the keys of a `$state` record under the array `prefix` with its items. */
|
|
162
|
+
function moveItemKeys(record, prefix, toIndex) {
|
|
163
|
+
const entries = Object.entries(record);
|
|
164
|
+
clear(record);
|
|
165
|
+
for (const [key, entry] of entries) {
|
|
166
|
+
const moved = moveItemKey(key, prefix, toIndex);
|
|
167
|
+
if (moved !== undefined)
|
|
168
|
+
record[moved] = entry;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
36
171
|
/** Empties a `$state` record in place, so its readers stay subscribed. */
|
|
37
172
|
function clear(record) {
|
|
38
173
|
for (const key of Object.keys(record))
|
|
@@ -54,23 +189,40 @@ export default function createFormState({ defaultValues = {}, validate, mode = "
|
|
|
54
189
|
get isSubmitting() {
|
|
55
190
|
return isSubmitting;
|
|
56
191
|
},
|
|
192
|
+
get isValidating() {
|
|
193
|
+
return isValidating;
|
|
194
|
+
},
|
|
195
|
+
getValue: (name) => getPath(values, name),
|
|
57
196
|
setValue(name, value) {
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
else
|
|
61
|
-
values[name] = value;
|
|
197
|
+
const key = normalizePath(name);
|
|
198
|
+
setPath(values, key, value);
|
|
62
199
|
if (isSubmitted ||
|
|
63
200
|
mode === "onChange" ||
|
|
64
|
-
(mode === "onTouched" && touched[
|
|
65
|
-
runValidation([
|
|
201
|
+
(mode === "onTouched" && touched[key]))
|
|
202
|
+
runValidation([key]);
|
|
66
203
|
},
|
|
67
|
-
getError: (name) => errors[name],
|
|
204
|
+
getError: (name) => errors[normalizePath(name)],
|
|
68
205
|
blur(name) {
|
|
69
|
-
|
|
206
|
+
const key = normalizePath(name);
|
|
207
|
+
touched[key] = true;
|
|
70
208
|
if (mode === "onBlur" || mode === "onTouched")
|
|
71
|
-
runValidation([
|
|
209
|
+
runValidation([key]);
|
|
210
|
+
},
|
|
211
|
+
reindex(name, toIndex) {
|
|
212
|
+
const prefix = `${normalizePath(name)}.`;
|
|
213
|
+
moveItemKeys(errors, prefix, toIndex);
|
|
214
|
+
moveItemKeys(touched, prefix, toIndex);
|
|
215
|
+
if (!isValidating)
|
|
216
|
+
return;
|
|
217
|
+
// The running validation read the items at their old places: start it
|
|
218
|
+
// again on the fields it was updating, at their new places.
|
|
219
|
+
pendingScope = pendingScope?.flatMap((key) => moveItemKey(key, prefix, toIndex) ?? []);
|
|
220
|
+
runValidation([]);
|
|
72
221
|
},
|
|
73
222
|
reset() {
|
|
223
|
+
latestRun++;
|
|
224
|
+
isValidating = false;
|
|
225
|
+
pendingSubmit = undefined;
|
|
74
226
|
clear(values);
|
|
75
227
|
Object.assign(values, defaultValues);
|
|
76
228
|
clear(errors);
|
|
@@ -79,23 +231,27 @@ export default function createFormState({ defaultValues = {}, validate, mode = "
|
|
|
79
231
|
},
|
|
80
232
|
submit(event) {
|
|
81
233
|
isSubmitted = true;
|
|
82
|
-
if (
|
|
234
|
+
if (isApproved) {
|
|
235
|
+
isApproved = false;
|
|
236
|
+
return;
|
|
237
|
+
}
|
|
238
|
+
const form = event.currentTarget;
|
|
239
|
+
pendingSubmit = undefined;
|
|
240
|
+
const isValid = runValidation();
|
|
241
|
+
if (isValid === undefined) {
|
|
83
242
|
event.preventDefault();
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
243
|
+
pendingSubmit = { form, submitter: event.submitter };
|
|
244
|
+
return;
|
|
245
|
+
}
|
|
246
|
+
if (!isValid) {
|
|
247
|
+
event.preventDefault();
|
|
248
|
+
focusFirstInvalid(form);
|
|
87
249
|
return;
|
|
88
250
|
}
|
|
89
251
|
if (!onSubmit)
|
|
90
252
|
return;
|
|
91
253
|
event.preventDefault();
|
|
92
|
-
|
|
93
|
-
if (!(done instanceof Promise))
|
|
94
|
-
return;
|
|
95
|
-
isSubmitting = true;
|
|
96
|
-
void done.finally(() => {
|
|
97
|
-
isSubmitting = false;
|
|
98
|
-
});
|
|
254
|
+
callOnSubmit(onSubmit);
|
|
99
255
|
},
|
|
100
256
|
};
|
|
101
257
|
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { FormErrors, FormValues, StandardSchema } from "./types.js";
|
|
2
|
+
/**
|
|
3
|
+
* Turns a Standard Schema, such as a Zod, Valibot or ArkType schema, into the
|
|
4
|
+
* `validate` function of `createFormState`, as react-hook-form's resolvers
|
|
5
|
+
* do. The values are inferred from the schema's input type:
|
|
6
|
+
*
|
|
7
|
+
* ```ts
|
|
8
|
+
* createFormState({ validate: createSchemaValidator(schema), defaultValues });
|
|
9
|
+
* ```
|
|
10
|
+
*
|
|
11
|
+
* Each message is keyed by its issue's path joined with `.`, and the first
|
|
12
|
+
* message for a path wins. An issue without a path is keyed by `""`, which no
|
|
13
|
+
* field shows: give a whole-form refinement a `path` to show it on a field.
|
|
14
|
+
*
|
|
15
|
+
* A schema that validates asynchronously, such as a Zod schema with an
|
|
16
|
+
* `async` refinement, returns a promise of the messages, which
|
|
17
|
+
* `createFormState` waits for; a synchronous schema returns them at once.
|
|
18
|
+
* @note Pure: the returned function only reads the schema.
|
|
19
|
+
*/
|
|
20
|
+
export default function createSchemaValidator<Values extends FormValues>(schema: StandardSchema<Values, unknown>): (values: Readonly<Values>) => FormErrors<Values> | Promise<FormErrors<Values>>;
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/** Joins an issue's path with `.`, as `address.city` or `contacts.0.email`. */
|
|
2
|
+
function readIssueName({ path = [] }) {
|
|
3
|
+
return path
|
|
4
|
+
.map((segment) => String(typeof segment === "object" ? segment.key : segment))
|
|
5
|
+
.join(".");
|
|
6
|
+
}
|
|
7
|
+
/** Keys each issue's message by its name; the first message for a name wins. */
|
|
8
|
+
function readErrors(result) {
|
|
9
|
+
const errors = {};
|
|
10
|
+
for (const issue of result.issues ?? [])
|
|
11
|
+
errors[readIssueName(issue)] ??= issue.message;
|
|
12
|
+
return errors;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Turns a Standard Schema, such as a Zod, Valibot or ArkType schema, into the
|
|
16
|
+
* `validate` function of `createFormState`, as react-hook-form's resolvers
|
|
17
|
+
* do. The values are inferred from the schema's input type:
|
|
18
|
+
*
|
|
19
|
+
* ```ts
|
|
20
|
+
* createFormState({ validate: createSchemaValidator(schema), defaultValues });
|
|
21
|
+
* ```
|
|
22
|
+
*
|
|
23
|
+
* Each message is keyed by its issue's path joined with `.`, and the first
|
|
24
|
+
* message for a path wins. An issue without a path is keyed by `""`, which no
|
|
25
|
+
* field shows: give a whole-form refinement a `path` to show it on a field.
|
|
26
|
+
*
|
|
27
|
+
* A schema that validates asynchronously, such as a Zod schema with an
|
|
28
|
+
* `async` refinement, returns a promise of the messages, which
|
|
29
|
+
* `createFormState` waits for; a synchronous schema returns them at once.
|
|
30
|
+
* @note Pure: the returned function only reads the schema.
|
|
31
|
+
*/
|
|
32
|
+
export default function createSchemaValidator(schema) {
|
|
33
|
+
return (values) => {
|
|
34
|
+
const result = schema["~standard"].validate(values);
|
|
35
|
+
return result instanceof Promise
|
|
36
|
+
? result.then((readErrors))
|
|
37
|
+
: readErrors(result);
|
|
38
|
+
};
|
|
39
|
+
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { FieldValidator, FormValues, ResettableOwner, ValidatedOwner } from "./types.js";
|
|
1
|
+
import type { FieldValidator, FormValues, Path, PathValue, ResettableOwner, ValidatedOwner } from "./types.js";
|
|
2
2
|
/**
|
|
3
3
|
* Adds asynchronous field checks to an owner, such as a server lookup. Every
|
|
4
4
|
* write to a checked field starts its check; the field keeps its previous
|
|
@@ -11,5 +11,5 @@ import type { FieldValidator, FormValues, ResettableOwner, ValidatedOwner } from
|
|
|
11
11
|
* @note Pure: the returned owner holds the checks' messages and runs.
|
|
12
12
|
*/
|
|
13
13
|
export default function createValidatedBinding<Values extends FormValues>(owner: ResettableOwner<Values>, validators: {
|
|
14
|
-
[Name in
|
|
14
|
+
[Name in Path<Values>]?: FieldValidator<PathValue<Values, Name>>;
|
|
15
15
|
}): ValidatedOwner<Values>;
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { SvelteMap } from "svelte/reactivity";
|
|
2
|
+
import normalizePath from "./normalizePath.js";
|
|
3
|
+
import readOwnerValue from "./readOwnerValue.js";
|
|
2
4
|
import runLatest from "./runLatest.js";
|
|
3
5
|
/**
|
|
4
6
|
* Adds asynchronous field checks to an owner, such as a server lookup. Every
|
|
@@ -15,11 +17,12 @@ export default function createValidatedBinding(owner, validators) {
|
|
|
15
17
|
const messages = new SvelteMap();
|
|
16
18
|
const pending = new Map();
|
|
17
19
|
const runners = new Map(Object.entries(validators).map(([name, validator]) => [
|
|
18
|
-
name,
|
|
20
|
+
normalizePath(name),
|
|
19
21
|
runLatest(validator),
|
|
20
22
|
]));
|
|
21
23
|
/** Checks the field's new value; its message changes when the check is done. */
|
|
22
|
-
function startValidation(
|
|
24
|
+
function startValidation(fieldName, value) {
|
|
25
|
+
const name = normalizePath(fieldName);
|
|
23
26
|
const runner = runners.get(name);
|
|
24
27
|
if (!runner)
|
|
25
28
|
return;
|
|
@@ -35,17 +38,19 @@ export default function createValidatedBinding(owner, validators) {
|
|
|
35
38
|
});
|
|
36
39
|
pending.set(name, run);
|
|
37
40
|
}
|
|
38
|
-
const getError = (name) => messages.get(name) ?? owner.getError?.(name);
|
|
41
|
+
const getError = (name) => messages.get(normalizePath(name)) ?? owner.getError?.(name);
|
|
39
42
|
return {
|
|
40
43
|
get values() {
|
|
41
44
|
return owner.values;
|
|
42
45
|
},
|
|
46
|
+
getValue: owner.getValue?.bind(owner),
|
|
43
47
|
setValue(name, value) {
|
|
44
48
|
owner.setValue(name, value);
|
|
45
49
|
startValidation(name, value);
|
|
46
50
|
},
|
|
47
51
|
getError,
|
|
48
52
|
blur: owner.blur?.bind(owner),
|
|
53
|
+
reindex: owner.reindex?.bind(owner),
|
|
49
54
|
submit(event) {
|
|
50
55
|
if (messages.size > 0)
|
|
51
56
|
event.preventDefault();
|
|
@@ -61,7 +66,7 @@ export default function createValidatedBinding(owner, validators) {
|
|
|
61
66
|
},
|
|
62
67
|
async validate() {
|
|
63
68
|
for (const name of runners.keys())
|
|
64
|
-
startValidation(name, owner
|
|
69
|
+
startValidation(name, readOwnerValue(owner, name));
|
|
65
70
|
while (pending.size > 0)
|
|
66
71
|
await Promise.all(pending.values());
|
|
67
72
|
return [...runners.keys()].every((name) => getError(name) === undefined);
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import splitPath from "./splitPath.js";
|
|
2
|
+
/**
|
|
3
|
+
* Reads the value at a field's path in nested values, as `address.city` or
|
|
4
|
+
* `contacts[0].email`. Returns `undefined` when the path stops early.
|
|
5
|
+
* @note Pure.
|
|
6
|
+
*/
|
|
7
|
+
export default function getPath(values, name) {
|
|
8
|
+
let current = values;
|
|
9
|
+
for (const segment of splitPath(name)) {
|
|
10
|
+
if (typeof current !== "object" || current === null)
|
|
11
|
+
return undefined;
|
|
12
|
+
current = current[segment];
|
|
13
|
+
}
|
|
14
|
+
return current;
|
|
15
|
+
}
|
|
@@ -1,7 +1,15 @@
|
|
|
1
1
|
export { default as bindField } from "./bindField.js";
|
|
2
|
+
export { default as bindFieldArray } from "./bindFieldArray.js";
|
|
3
|
+
export { default as bindTanStackForm } from "./bindTanStackForm.js";
|
|
2
4
|
export { default as createBinding } from "./createBinding.js";
|
|
3
5
|
export { default as createFormState } from "./createFormState.svelte.js";
|
|
6
|
+
export { default as createSchemaValidator } from "./createSchemaValidator.js";
|
|
4
7
|
export { default as createValidatedBinding } from "./createValidatedBinding.js";
|
|
5
8
|
export { getFormOwnerContext, setFormOwnerContext, } from "./formOwnerContext.js";
|
|
9
|
+
export { default as getPath } from "./getPath.js";
|
|
10
|
+
export { default as normalizePath } from "./normalizePath.js";
|
|
11
|
+
export { default as readOwnerValue } from "./readOwnerValue.js";
|
|
6
12
|
export { default as runLatest } from "./runLatest.js";
|
|
13
|
+
export { default as setPath } from "./setPath.js";
|
|
14
|
+
export { default as splitPath } from "./splitPath.js";
|
|
7
15
|
export type * from "./types.js";
|
|
@@ -1,6 +1,14 @@
|
|
|
1
1
|
export { default as bindField } from "./bindField.js";
|
|
2
|
+
export { default as bindFieldArray } from "./bindFieldArray.js";
|
|
3
|
+
export { default as bindTanStackForm } from "./bindTanStackForm.js";
|
|
2
4
|
export { default as createBinding } from "./createBinding.js";
|
|
3
5
|
export { default as createFormState } from "./createFormState.svelte.js";
|
|
6
|
+
export { default as createSchemaValidator } from "./createSchemaValidator.js";
|
|
4
7
|
export { default as createValidatedBinding } from "./createValidatedBinding.js";
|
|
5
8
|
export { getFormOwnerContext, setFormOwnerContext, } from "./formOwnerContext.js";
|
|
9
|
+
export { default as getPath } from "./getPath.js";
|
|
10
|
+
export { default as normalizePath } from "./normalizePath.js";
|
|
11
|
+
export { default as readOwnerValue } from "./readOwnerValue.js";
|
|
6
12
|
export { default as runLatest } from "./runLatest.js";
|
|
13
|
+
export { default as setPath } from "./setPath.js";
|
|
14
|
+
export { default as splitPath } from "./splitPath.js";
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import splitPath from "./splitPath.js";
|
|
2
|
+
/**
|
|
3
|
+
* Writes a field name in one form, its segments joined with `.`, so both path
|
|
4
|
+
* forms name one field: `contacts[0].email` gives `contacts.0.email`.
|
|
5
|
+
* @note Pure.
|
|
6
|
+
*/
|
|
7
|
+
export default function normalizePath(name) {
|
|
8
|
+
return splitPath(name).join(".");
|
|
9
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { FormOwner, FormValues, Path, PathValue } from "./types.js";
|
|
2
|
+
/**
|
|
3
|
+
* Reads a field's value from an owner: through its `getValue` when it has
|
|
4
|
+
* one, or by reading the path in its `values`.
|
|
5
|
+
* @note Pure.
|
|
6
|
+
*/
|
|
7
|
+
export default function readOwnerValue<Values extends FormValues, Name extends Path<Values>>(owner: FormOwner<Values>, name: Name): PathValue<Values, Name> | undefined;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import getPath from "./getPath.js";
|
|
2
|
+
/**
|
|
3
|
+
* Reads a field's value from an owner: through its `getValue` when it has
|
|
4
|
+
* one, or by reading the path in its `values`.
|
|
5
|
+
* @note Pure.
|
|
6
|
+
*/
|
|
7
|
+
export default function readOwnerValue(owner, name) {
|
|
8
|
+
return owner.getValue
|
|
9
|
+
? owner.getValue(name)
|
|
10
|
+
: getPath(owner.values, name);
|
|
11
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Writes the value at a field's path in nested values, as `address.city` or
|
|
3
|
+
* `contacts[0].email`, creating the objects along the path, or an array where
|
|
4
|
+
* the next segment is an index. Writing `undefined` drops the key, or leaves
|
|
5
|
+
* an array's slot `undefined` so the later items keep their indices; it
|
|
6
|
+
* creates nothing on the way.
|
|
7
|
+
*
|
|
8
|
+
* Each container is read back after it is created, so a `$state` proxy is
|
|
9
|
+
* written through and stays reactive.
|
|
10
|
+
* @note Impure: mutates `values` in place.
|
|
11
|
+
*/
|
|
12
|
+
export default function setPath(values: Record<string, unknown>, name: string, value: unknown): void;
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import splitPath from "./splitPath.js";
|
|
2
|
+
/** Tells whether a path segment is an array index. */
|
|
3
|
+
const isIndex = (segment) => /^\d+$/.test(segment);
|
|
4
|
+
/**
|
|
5
|
+
* Writes the value at a field's path in nested values, as `address.city` or
|
|
6
|
+
* `contacts[0].email`, creating the objects along the path, or an array where
|
|
7
|
+
* the next segment is an index. Writing `undefined` drops the key, or leaves
|
|
8
|
+
* an array's slot `undefined` so the later items keep their indices; it
|
|
9
|
+
* creates nothing on the way.
|
|
10
|
+
*
|
|
11
|
+
* Each container is read back after it is created, so a `$state` proxy is
|
|
12
|
+
* written through and stays reactive.
|
|
13
|
+
* @note Impure: mutates `values` in place.
|
|
14
|
+
*/
|
|
15
|
+
export default function setPath(values, name, value) {
|
|
16
|
+
const segments = splitPath(name);
|
|
17
|
+
const last = segments.pop();
|
|
18
|
+
if (last === undefined)
|
|
19
|
+
return;
|
|
20
|
+
let parent = values;
|
|
21
|
+
for (const [index, segment] of segments.entries()) {
|
|
22
|
+
if (typeof parent[segment] !== "object" || parent[segment] === null) {
|
|
23
|
+
if (value === undefined)
|
|
24
|
+
return;
|
|
25
|
+
const next = segments.at(index + 1) ?? last;
|
|
26
|
+
parent[segment] = isIndex(next) ? [] : {};
|
|
27
|
+
}
|
|
28
|
+
parent = parent[segment];
|
|
29
|
+
}
|
|
30
|
+
if (value !== undefined)
|
|
31
|
+
parent[last] = value;
|
|
32
|
+
else if (Array.isArray(parent))
|
|
33
|
+
parent[last] = undefined;
|
|
34
|
+
else
|
|
35
|
+
delete parent[last];
|
|
36
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Splits a field name into its path segments. Both react-hook-form's dotted
|
|
3
|
+
* form and SvelteKit's bracket form are read: `contacts.0.email` and
|
|
4
|
+
* `contacts[0].email` both give `["contacts", "0", "email"]`.
|
|
5
|
+
* @note Pure.
|
|
6
|
+
*/
|
|
7
|
+
export default function splitPath(name: string): string[];
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Splits a field name into its path segments. Both react-hook-form's dotted
|
|
3
|
+
* form and SvelteKit's bracket form are read: `contacts.0.email` and
|
|
4
|
+
* `contacts[0].email` both give `["contacts", "0", "email"]`.
|
|
5
|
+
* @note Pure.
|
|
6
|
+
*/
|
|
7
|
+
export default function splitPath(name) {
|
|
8
|
+
return name.split(/[.[\]]+/).filter((segment) => segment !== "");
|
|
9
|
+
}
|