@barqjs/aria 0.0.0-stage → 0.2.0-next.1
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 +21 -0
- package/README.md +304 -2
- package/package.json +437 -4
- package/src/autocomplete.tsx +581 -0
- package/src/breadcrumbs.tsx +297 -0
- package/src/button.tsx +468 -0
- package/src/calendar.tsx +2316 -0
- package/src/checkbox.tsx +732 -0
- package/src/collections.ts +1059 -0
- package/src/color.ts +2119 -0
- package/src/colorpicker.tsx +2023 -0
- package/src/colorswatchpicker.tsx +240 -0
- package/src/combobox.tsx +3003 -0
- package/src/command.tsx +1203 -0
- package/src/date.ts +674 -0
- package/src/datefield.tsx +2066 -0
- package/src/datepicker.tsx +907 -0
- package/src/dialog.tsx +1077 -0
- package/src/disclosure.tsx +711 -0
- package/src/dnd/clipboard.ts +125 -0
- package/src/dnd/collection.ts +1265 -0
- package/src/dnd/data.ts +409 -0
- package/src/dnd/drag-drop.ts +801 -0
- package/src/dnd/index.ts +133 -0
- package/src/dnd/manager.ts +639 -0
- package/src/dnd/strings.ts +1279 -0
- package/src/dnd/targets.ts +726 -0
- package/src/dnd/types.ts +212 -0
- package/src/dom.ts +703 -0
- package/src/drag-and-drop.tsx +669 -0
- package/src/drawer.ts +674 -0
- package/src/dropzone.tsx +208 -0
- package/src/file-trigger.tsx +103 -0
- package/src/focus.ts +1370 -0
- package/src/form.tsx +94 -0
- package/src/gridlist.tsx +1354 -0
- package/src/group.tsx +146 -0
- package/src/i18n.ts +823 -0
- package/src/index.ts +1672 -0
- package/src/interactions/description.ts +73 -0
- package/src/interactions/flags.ts +35 -0
- package/src/interactions/focus-events.ts +226 -0
- package/src/interactions/focusable.ts +86 -0
- package/src/interactions/hover.ts +213 -0
- package/src/interactions/interact-outside.ts +123 -0
- package/src/interactions/keyboard.ts +298 -0
- package/src/interactions/listeners.ts +78 -0
- package/src/interactions/long-press.ts +160 -0
- package/src/interactions/modality.ts +428 -0
- package/src/interactions/move.ts +257 -0
- package/src/interactions/open-link.ts +226 -0
- package/src/interactions/press.ts +915 -0
- package/src/interactions/prevent-focus.ts +102 -0
- package/src/interactions/scroll-wheel.ts +43 -0
- package/src/interactions/text-selection.ts +77 -0
- package/src/interactions.ts +81 -0
- package/src/label.ts +140 -0
- package/src/link.tsx +477 -0
- package/src/listbox.tsx +1247 -0
- package/src/live.ts +208 -0
- package/src/menu.tsx +2383 -0
- package/src/menubar.tsx +579 -0
- package/src/navigation-tree.tsx +357 -0
- package/src/navigation.ts +735 -0
- package/src/numberfield.tsx +942 -0
- package/src/otp.ts +430 -0
- package/src/overlay-arrow.tsx +157 -0
- package/src/overlays.ts +1549 -0
- package/src/platform.ts +75 -0
- package/src/presence.ts +164 -0
- package/src/preview-trigger.tsx +582 -0
- package/src/progress-bar-context.ts +15 -0
- package/src/questionnaire.tsx +1717 -0
- package/src/radio.tsx +641 -0
- package/src/register-dom.ts +12 -0
- package/src/scroller.ts +1165 -0
- package/src/select.tsx +1745 -0
- package/src/selection-indicator.tsx +74 -0
- package/src/selection.ts +1472 -0
- package/src/shared-element-transition.tsx +316 -0
- package/src/sheet.tsx +1461 -0
- package/src/slider.tsx +1137 -0
- package/src/splitter.ts +1152 -0
- package/src/static-collection.ts +211 -0
- package/src/switch.tsx +212 -0
- package/src/table.tsx +2218 -0
- package/src/tabs.tsx +1127 -0
- package/src/tag.tsx +637 -0
- package/src/textarea.tsx +186 -0
- package/src/textfield.tsx +483 -0
- package/src/toast-components.tsx +589 -0
- package/src/toast.ts +658 -0
- package/src/toggle-button-group.tsx +175 -0
- package/src/toggle-input.tsx +86 -0
- package/src/toggle.ts +384 -0
- package/src/togglegroup.ts +365 -0
- package/src/tokenfield.tsx +1673 -0
- package/src/toolbar.tsx +184 -0
- package/src/tooltip.tsx +674 -0
- package/src/tree.tsx +2075 -0
- package/src/utils.ts +787 -0
- package/src/validation.ts +504 -0
- package/src/virtualizer.tsx +837 -0
|
@@ -0,0 +1,504 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Validation: what is wrong with a field, and when to say so.
|
|
3
|
+
*
|
|
4
|
+
* Three things can find a problem, and they disagree about when the user
|
|
5
|
+
* should hear about it:
|
|
6
|
+
*
|
|
7
|
+
* - **The browser.** `required`, `type="email"`, `min`, `pattern` — the native
|
|
8
|
+
* constraints. They are checked on submit and their messages are localised
|
|
9
|
+
* into the browser's own language, which no library can match.
|
|
10
|
+
* - **The page.** A `validate` function, checked as the value changes.
|
|
11
|
+
* - **The server.** Errors that came back from a submission, which the client
|
|
12
|
+
* could not have known.
|
|
13
|
+
*
|
|
14
|
+
* When they are SHOWN is the whole design, and it is what
|
|
15
|
+
* `validationBehavior` decides:
|
|
16
|
+
*
|
|
17
|
+
* - `"aria"` (the default) never blocks a submit and shows everything as it
|
|
18
|
+
* happens. The field is described by its error and marked `aria-invalid`;
|
|
19
|
+
* the form still submits, because the page is in charge of what it accepts.
|
|
20
|
+
* - `"native"` uses the platform's own validation: the browser refuses the
|
|
21
|
+
* submit, focuses the first bad field, and the error is shown from that
|
|
22
|
+
* point on rather than while the user is still typing. Errors typed AT are
|
|
23
|
+
* errors nobody has finished making yet.
|
|
24
|
+
*
|
|
25
|
+
* The browser's own error bubble is always suppressed. It appears at a fixed
|
|
26
|
+
* place, in a fixed style, and vanishes after a few seconds — the message goes
|
|
27
|
+
* into the page instead, where it stays and where `aria-describedby` can point
|
|
28
|
+
* at it.
|
|
29
|
+
*/
|
|
30
|
+
|
|
31
|
+
import {
|
|
32
|
+
type Accessor,
|
|
33
|
+
createContext,
|
|
34
|
+
createEffect,
|
|
35
|
+
getOwner,
|
|
36
|
+
install,
|
|
37
|
+
createSignal,
|
|
38
|
+
onFlush,
|
|
39
|
+
useContext,
|
|
40
|
+
} from "@barqjs/core";
|
|
41
|
+
import { isServer } from "@barqjs/web";
|
|
42
|
+
import type { ElementRef } from "./interactions/press.ts";
|
|
43
|
+
import { setInteractionModality } from "./interactions/modality.ts";
|
|
44
|
+
import { access, type MaybeAccessor } from "./utils.ts";
|
|
45
|
+
|
|
46
|
+
export type ValidationBehavior = "aria" | "native";
|
|
47
|
+
|
|
48
|
+
/** What a field's validity is, and why. */
|
|
49
|
+
export interface ValidationResult {
|
|
50
|
+
isInvalid: boolean;
|
|
51
|
+
/** Every message, in the order they were found. */
|
|
52
|
+
validationErrors: string[];
|
|
53
|
+
/** Which constraint failed, when the browser is the one that found it. */
|
|
54
|
+
validationDetails: ValidityState;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// `satisfies` rather than an annotation: typed as `ValidityState` this is a
|
|
58
|
+
// DOM interface, and spreading one to build `CUSTOM` would be spreading a class
|
|
59
|
+
// instance and losing its prototype.
|
|
60
|
+
const VALID = {
|
|
61
|
+
badInput: false,
|
|
62
|
+
customError: false,
|
|
63
|
+
patternMismatch: false,
|
|
64
|
+
rangeOverflow: false,
|
|
65
|
+
rangeUnderflow: false,
|
|
66
|
+
stepMismatch: false,
|
|
67
|
+
tooLong: false,
|
|
68
|
+
tooShort: false,
|
|
69
|
+
typeMismatch: false,
|
|
70
|
+
valueMissing: false,
|
|
71
|
+
valid: true,
|
|
72
|
+
} satisfies ValidityState;
|
|
73
|
+
|
|
74
|
+
const CUSTOM: ValidityState = { ...VALID, customError: true, valid: false };
|
|
75
|
+
|
|
76
|
+
export const VALID_RESULT: ValidationResult = {
|
|
77
|
+
isInvalid: false,
|
|
78
|
+
validationErrors: [],
|
|
79
|
+
validationDetails: VALID,
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
/** Errors a submission came back with, by field name. */
|
|
83
|
+
export type ValidationErrors = Record<string, string | string[]>;
|
|
84
|
+
|
|
85
|
+
const FormValidationContext = createContext<ValidationErrors>({});
|
|
86
|
+
|
|
87
|
+
/** Hand a form's server errors to the fields inside it. */
|
|
88
|
+
export function provideValidationErrors(errors: MaybeAccessor<ValidationErrors>): void {
|
|
89
|
+
const owner = getOwner();
|
|
90
|
+
if (owner !== null) install(owner, FormValidationContext, () => access(errors));
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// Wrapped in an object, because a context whose default IS `undefined` cannot
|
|
94
|
+
// tell "nobody provided one" from "somebody provided undefined".
|
|
95
|
+
const ValidationBehaviorContext = createContext<{ behavior?: ValidationBehavior }>({});
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* One behaviour for every field inside a form.
|
|
99
|
+
*
|
|
100
|
+
* Setting it per field is how a form ends up half native and half ARIA, which
|
|
101
|
+
* means half of it blocks submission and half does not.
|
|
102
|
+
*/
|
|
103
|
+
export function provideValidationBehavior(
|
|
104
|
+
behavior: MaybeAccessor<ValidationBehavior | undefined>,
|
|
105
|
+
): void {
|
|
106
|
+
const owner = getOwner();
|
|
107
|
+
if (owner !== null) {
|
|
108
|
+
install(owner, ValidationBehaviorContext, () => ({ behavior: access(behavior) }));
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** What the enclosing form said, if anything. */
|
|
113
|
+
export function useValidationBehavior(): ValidationBehavior | undefined {
|
|
114
|
+
return useContext(ValidationBehaviorContext)()?.behavior;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export type ValidateFunction<T> = (value: T) => string | string[] | true | null | undefined;
|
|
118
|
+
|
|
119
|
+
export interface FormValidationStateOptions<T> {
|
|
120
|
+
value: MaybeAccessor<T>;
|
|
121
|
+
/** @default "aria" */
|
|
122
|
+
validationBehavior?: MaybeAccessor<ValidationBehavior | undefined>;
|
|
123
|
+
/** Said by the caller, whatever anything else found. */
|
|
124
|
+
isInvalid?: MaybeAccessor<boolean | undefined>;
|
|
125
|
+
validate?: ValidateFunction<T>;
|
|
126
|
+
/** The form field name, for matching a server error to this field. */
|
|
127
|
+
name?: MaybeAccessor<string | string[] | undefined>;
|
|
128
|
+
/** What the browser found, when the field has a native control. */
|
|
129
|
+
builtinValidation?: Accessor<ValidationResult | undefined>;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export interface FormValidationState {
|
|
133
|
+
/** As it stands now, whatever is being shown. */
|
|
134
|
+
realtimeValidation: Accessor<ValidationResult>;
|
|
135
|
+
/** What the user is being told, which lags behind under `"native"`. */
|
|
136
|
+
displayValidation: Accessor<ValidationResult>;
|
|
137
|
+
updateValidation(result: ValidationResult): void;
|
|
138
|
+
resetValidation(): void;
|
|
139
|
+
/** Show what has been found. Blur, change and submit all do this. */
|
|
140
|
+
commitValidation(): void;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function asArray(value: string | string[] | undefined | null): string[] {
|
|
144
|
+
if (value === undefined || value === null || value === "") return [];
|
|
145
|
+
return Array.isArray(value) ? value : [value];
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function resultFor(errors: string[]): ValidationResult | null {
|
|
149
|
+
if (errors.length === 0) return null;
|
|
150
|
+
return { isInvalid: true, validationErrors: errors, validationDetails: CUSTOM };
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function sameResult(a: ValidationResult, b: ValidationResult): boolean {
|
|
154
|
+
return (
|
|
155
|
+
a.isInvalid === b.isInvalid &&
|
|
156
|
+
a.validationErrors.length === b.validationErrors.length &&
|
|
157
|
+
a.validationErrors.every((error, at) => error === b.validationErrors[at]) &&
|
|
158
|
+
a.validationDetails === b.validationDetails
|
|
159
|
+
);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
export function formValidationState<T>(
|
|
163
|
+
options: FormValidationStateOptions<T>,
|
|
164
|
+
): FormValidationState {
|
|
165
|
+
// The field's own, then the form's, then the default.
|
|
166
|
+
const inherited = useValidationBehavior();
|
|
167
|
+
const behavior = (): ValidationBehavior =>
|
|
168
|
+
access(options.validationBehavior) ?? inherited ?? "aria";
|
|
169
|
+
|
|
170
|
+
/** What the caller said, which nothing else can argue with. */
|
|
171
|
+
const controlled = (): ValidationResult | null => {
|
|
172
|
+
const invalid = access(options.isInvalid);
|
|
173
|
+
if (invalid === undefined) return null;
|
|
174
|
+
return { isInvalid: invalid, validationErrors: [], validationDetails: CUSTOM };
|
|
175
|
+
};
|
|
176
|
+
|
|
177
|
+
const client = (): ValidationResult | null => {
|
|
178
|
+
const validate = options.validate;
|
|
179
|
+
if (validate === undefined) return null;
|
|
180
|
+
const value = access(options.value) as T;
|
|
181
|
+
if (value === null || value === undefined) return null;
|
|
182
|
+
const errors = validate(value);
|
|
183
|
+
return resultFor(errors === true ? [] : asArray(errors));
|
|
184
|
+
};
|
|
185
|
+
|
|
186
|
+
const builtin = (): ValidationResult | null => {
|
|
187
|
+
const found = options.builtinValidation?.();
|
|
188
|
+
if (found === undefined || found.validationDetails.valid) return null;
|
|
189
|
+
return found;
|
|
190
|
+
};
|
|
191
|
+
|
|
192
|
+
// The CELL, read once here where there is an owner. Reading the context on
|
|
193
|
+
// every call would throw from an event handler, which is where a commit
|
|
194
|
+
// comes from.
|
|
195
|
+
const serverErrors = useContext(FormValidationContext);
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* A server error is CLEARED by the next edit.
|
|
199
|
+
*
|
|
200
|
+
* The user changing the value has invalidated whatever the server said about
|
|
201
|
+
* the old one, and leaving it up would be telling them they still have a
|
|
202
|
+
* problem they have just fixed. It is derived from the errors themselves, so
|
|
203
|
+
* a fresh answer from the server is shown whatever was cleared before it.
|
|
204
|
+
*/
|
|
205
|
+
const [serverCleared, setServerCleared] = createSignal<boolean>(() => {
|
|
206
|
+
serverErrors();
|
|
207
|
+
return false;
|
|
208
|
+
});
|
|
209
|
+
|
|
210
|
+
const server = (): ValidationResult | null => {
|
|
211
|
+
const errors = serverErrors() ?? {};
|
|
212
|
+
if (serverCleared()) return null;
|
|
213
|
+
|
|
214
|
+
const name = access(options.name);
|
|
215
|
+
if (name === undefined) return null;
|
|
216
|
+
const messages = Array.isArray(name)
|
|
217
|
+
? name.flatMap((entry) => asArray(errors[entry]))
|
|
218
|
+
: asArray(errors[name]);
|
|
219
|
+
return resultFor(messages);
|
|
220
|
+
};
|
|
221
|
+
|
|
222
|
+
/** What has been found but not yet shown, under `"native"`. */
|
|
223
|
+
let pending: ValidationResult = VALID_RESULT;
|
|
224
|
+
const [shown, setShown] = createSignal<ValidationResult>(VALID_RESULT);
|
|
225
|
+
/** What the last commit put up, read without subscribing to it. */
|
|
226
|
+
let committed: ValidationResult = VALID_RESULT;
|
|
227
|
+
let queued = false;
|
|
228
|
+
|
|
229
|
+
const show = (result: ValidationResult): void => {
|
|
230
|
+
if (sameResult(committed, result)) return;
|
|
231
|
+
committed = result;
|
|
232
|
+
setShown(result);
|
|
233
|
+
};
|
|
234
|
+
|
|
235
|
+
const commitNow = (): void => show(client() ?? builtin() ?? pending);
|
|
236
|
+
|
|
237
|
+
const realtimeValidation = (): ValidationResult =>
|
|
238
|
+
controlled() ?? server() ?? client() ?? builtin() ?? VALID_RESULT;
|
|
239
|
+
|
|
240
|
+
const displayValidation = (): ValidationResult => {
|
|
241
|
+
if (behavior() === "native") return controlled() ?? server() ?? shown();
|
|
242
|
+
return controlled() ?? server() ?? client() ?? builtin() ?? shown();
|
|
243
|
+
};
|
|
244
|
+
|
|
245
|
+
return {
|
|
246
|
+
realtimeValidation,
|
|
247
|
+
displayValidation,
|
|
248
|
+
updateValidation: (result) => {
|
|
249
|
+
// Under `"aria"` everything is shown as it happens; under `"native"` it
|
|
250
|
+
// waits for a commit.
|
|
251
|
+
if (behavior() === "aria") {
|
|
252
|
+
show(result);
|
|
253
|
+
return;
|
|
254
|
+
}
|
|
255
|
+
pending = result;
|
|
256
|
+
},
|
|
257
|
+
resetValidation: () => {
|
|
258
|
+
// Back to valid even if the native validity still says otherwise: it
|
|
259
|
+
// will say so again on the next submit.
|
|
260
|
+
show(VALID_RESULT);
|
|
261
|
+
pending = VALID_RESULT;
|
|
262
|
+
queued = false;
|
|
263
|
+
setServerCleared(true);
|
|
264
|
+
},
|
|
265
|
+
commitValidation: () => {
|
|
266
|
+
setServerCleared(true);
|
|
267
|
+
if (behavior() !== "native") return;
|
|
268
|
+
commitNow();
|
|
269
|
+
// A commit comes from the event that changed the value, before the write
|
|
270
|
+
// has been applied, so `validate` and the element's validity both still
|
|
271
|
+
// describe the old value. Committed again once the flush has run, which
|
|
272
|
+
// is the value the user is looking at.
|
|
273
|
+
if (queued) return;
|
|
274
|
+
queued = true;
|
|
275
|
+
onFlush(() => {
|
|
276
|
+
if (!queued) return;
|
|
277
|
+
queued = false;
|
|
278
|
+
commitNow();
|
|
279
|
+
});
|
|
280
|
+
},
|
|
281
|
+
};
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
// ---------------------------------------------------------------------------
|
|
285
|
+
// What a field wires up
|
|
286
|
+
// ---------------------------------------------------------------------------
|
|
287
|
+
|
|
288
|
+
export interface FieldValidationOptions<T> extends FormValidationStateOptions<T> {
|
|
289
|
+
/** The caller's own message, which wins over anything found here. */
|
|
290
|
+
errorMessage?: MaybeAccessor<unknown>;
|
|
291
|
+
/**
|
|
292
|
+
* A state to show instead of one of the field's own: a checkbox in a group
|
|
293
|
+
* shows the group's validity, which its own `validate` feeds into.
|
|
294
|
+
*/
|
|
295
|
+
state?: FormValidationState;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
export interface FieldValidation {
|
|
299
|
+
state: FormValidationState;
|
|
300
|
+
/** The field's own behaviour, or the form's, for {@link formValidation}. */
|
|
301
|
+
behavior: Accessor<ValidationBehavior | undefined>;
|
|
302
|
+
isInvalid: Accessor<boolean>;
|
|
303
|
+
/** The messages to show, which may be the browser's own. */
|
|
304
|
+
errors: Accessor<string[]>;
|
|
305
|
+
/**
|
|
306
|
+
* What the error element will HOLD, for {@link field}.
|
|
307
|
+
*
|
|
308
|
+
* `aria-describedby` has to point at it whether the message came from the
|
|
309
|
+
* caller, the page or the browser, and an id pointing at an empty element is
|
|
310
|
+
* announced as nothing.
|
|
311
|
+
*/
|
|
312
|
+
errorMessage: Accessor<unknown>;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/**
|
|
316
|
+
* The five things every validated field needs, wired together once.
|
|
317
|
+
*
|
|
318
|
+
* A field still calls {@link formValidation} itself when it has a native
|
|
319
|
+
* control to attach to: that half needs the element, and half the fields here
|
|
320
|
+
* (a listbox, a group of radios) do not have one.
|
|
321
|
+
*
|
|
322
|
+
* `validate` is NOT called for an absent value: `null` and `undefined` mean
|
|
323
|
+
* the field is empty, and "empty" is `isRequired`'s business rather than a
|
|
324
|
+
* page rule's. A validator handed an empty value would have to re-implement
|
|
325
|
+
* required-ness, and would then disagree with the browser about it.
|
|
326
|
+
*/
|
|
327
|
+
export function fieldValidation<T>(options: FieldValidationOptions<T>): FieldValidation {
|
|
328
|
+
const inherited = useValidationBehavior();
|
|
329
|
+
|
|
330
|
+
const state = options.state ?? formValidationState<T>(options);
|
|
331
|
+
|
|
332
|
+
const behavior = (): ValidationBehavior | undefined =>
|
|
333
|
+
access(options.validationBehavior) ?? inherited;
|
|
334
|
+
|
|
335
|
+
const isInvalid = (): boolean =>
|
|
336
|
+
access(options.isInvalid) === true || state.displayValidation().isInvalid;
|
|
337
|
+
|
|
338
|
+
const errors = (): string[] => state.displayValidation().validationErrors;
|
|
339
|
+
|
|
340
|
+
const errorMessage = (): unknown => {
|
|
341
|
+
const given = access(options.errorMessage);
|
|
342
|
+
if (given !== undefined && given !== null && given !== "") return given;
|
|
343
|
+
const found = errors();
|
|
344
|
+
return found.length === 0 ? undefined : found.join(" ");
|
|
345
|
+
};
|
|
346
|
+
|
|
347
|
+
return { state, behavior, isInvalid, errors, errorMessage };
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
// ---------------------------------------------------------------------------
|
|
351
|
+
// The native half
|
|
352
|
+
// ---------------------------------------------------------------------------
|
|
353
|
+
|
|
354
|
+
/** An element the platform can validate. */
|
|
355
|
+
export type ValidatableElement =
|
|
356
|
+
| HTMLInputElement
|
|
357
|
+
| HTMLTextAreaElement
|
|
358
|
+
| HTMLSelectElement
|
|
359
|
+
| HTMLButtonElement;
|
|
360
|
+
|
|
361
|
+
export interface FormValidationOptions {
|
|
362
|
+
validationBehavior?: MaybeAccessor<ValidationBehavior | undefined>;
|
|
363
|
+
/** Where to put focus when this field is the first invalid one. */
|
|
364
|
+
focus?: () => void;
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/** What the browser makes of an element, as a {@link ValidationResult}. */
|
|
368
|
+
export function nativeValidity(element: ValidatableElement): ValidationResult {
|
|
369
|
+
const validity = element.validity;
|
|
370
|
+
return {
|
|
371
|
+
isInvalid: !validity.valid,
|
|
372
|
+
validationErrors: validity.valid ? [] : [element.validationMessage],
|
|
373
|
+
validationDetails: {
|
|
374
|
+
badInput: validity.badInput,
|
|
375
|
+
customError: validity.customError,
|
|
376
|
+
patternMismatch: validity.patternMismatch,
|
|
377
|
+
rangeOverflow: validity.rangeOverflow,
|
|
378
|
+
rangeUnderflow: validity.rangeUnderflow,
|
|
379
|
+
stepMismatch: validity.stepMismatch,
|
|
380
|
+
tooLong: validity.tooLong,
|
|
381
|
+
tooShort: validity.tooShort,
|
|
382
|
+
typeMismatch: validity.typeMismatch,
|
|
383
|
+
valueMissing: validity.valueMissing,
|
|
384
|
+
valid: validity.valid,
|
|
385
|
+
},
|
|
386
|
+
};
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
/**
|
|
390
|
+
* Wire a native control to a validation state.
|
|
391
|
+
*
|
|
392
|
+
* Three things happen here and each one is load-bearing:
|
|
393
|
+
*
|
|
394
|
+
* - The page's own errors are written onto the element with
|
|
395
|
+
* `setCustomValidity`, so the BROWSER refuses the submit rather than the
|
|
396
|
+
* page having to intercept it.
|
|
397
|
+
* - The `invalid` event's default is prevented, which suppresses the browser's
|
|
398
|
+
* error bubble; the message goes into the page instead.
|
|
399
|
+
* - The first invalid field in the form takes focus, with the focus ring
|
|
400
|
+
* showing, because a submit that silently does nothing is the most
|
|
401
|
+
* frustrating failure a form has.
|
|
402
|
+
*/
|
|
403
|
+
export function formValidation(
|
|
404
|
+
options: FormValidationOptions,
|
|
405
|
+
state: FormValidationState,
|
|
406
|
+
ref: ElementRef<ValidatableElement>,
|
|
407
|
+
): void {
|
|
408
|
+
if (isServer) return;
|
|
409
|
+
|
|
410
|
+
const isNative = (): boolean => access(options.validationBehavior) === "native";
|
|
411
|
+
|
|
412
|
+
const sync = (element: ValidatableElement, found: ValidationResult): void => {
|
|
413
|
+
if (typeof element.setCustomValidity !== "function") return;
|
|
414
|
+
if ((element as HTMLInputElement).disabled) return;
|
|
415
|
+
|
|
416
|
+
element.setCustomValidity(
|
|
417
|
+
found.isInvalid ? found.validationErrors.join(" ") || "Invalid value." : "",
|
|
418
|
+
);
|
|
419
|
+
// Firefox shows the `title` in the validation bubble, so an empty one
|
|
420
|
+
// keeps the page's message from being repeated in the browser's.
|
|
421
|
+
if (!element.hasAttribute("title")) element.title = "";
|
|
422
|
+
|
|
423
|
+
if (!found.isInvalid) state.updateValidation(nativeValidity(element));
|
|
424
|
+
};
|
|
425
|
+
|
|
426
|
+
createEffect(
|
|
427
|
+
() => {
|
|
428
|
+
const element = access(ref) as ValidatableElement | null;
|
|
429
|
+
if (element === null || !isNative()) return null;
|
|
430
|
+
return [element, state.realtimeValidation()] as const;
|
|
431
|
+
},
|
|
432
|
+
(next) => {
|
|
433
|
+
if (next !== null) sync(next[0], next[1]);
|
|
434
|
+
},
|
|
435
|
+
);
|
|
436
|
+
|
|
437
|
+
createEffect(
|
|
438
|
+
() => access(ref) as ValidatableElement | null,
|
|
439
|
+
(element) => {
|
|
440
|
+
if (element === null) return undefined;
|
|
441
|
+
|
|
442
|
+
const onInvalid = (event: Event): void => {
|
|
443
|
+
// Only when nothing is being shown yet: committing over a server error
|
|
444
|
+
// the user has not fixed would replace it with the browser's message.
|
|
445
|
+
if (!state.displayValidation().isInvalid) state.commitValidation();
|
|
446
|
+
|
|
447
|
+
const form = element.form;
|
|
448
|
+
if (!event.defaultPrevented && form !== null) {
|
|
449
|
+
if (firstInvalid(form) === element) {
|
|
450
|
+
if (options.focus !== undefined) options.focus();
|
|
451
|
+
else element.focus();
|
|
452
|
+
// The focus ring shows: focus moved for a reason the user did not
|
|
453
|
+
// ask for, so they have to be able to see where it went.
|
|
454
|
+
setInteractionModality("keyboard");
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
// The browser's own bubble is suppressed; the message is in the page.
|
|
459
|
+
event.preventDefault();
|
|
460
|
+
};
|
|
461
|
+
|
|
462
|
+
// An edit can change what the browser thinks (`required`, `pattern`,
|
|
463
|
+
// `type="email"`) without changing anything the page's own validation
|
|
464
|
+
// reads, and then nothing re-runs the effect above. Read it again here,
|
|
465
|
+
// so the commit that follows is not of the value before the edit.
|
|
466
|
+
const onInput = (): void => {
|
|
467
|
+
if (isNative()) sync(element, state.realtimeValidation());
|
|
468
|
+
};
|
|
469
|
+
const onChange = (): void => {
|
|
470
|
+
onInput();
|
|
471
|
+
state.commitValidation();
|
|
472
|
+
};
|
|
473
|
+
const onReset = (event: Event): void => {
|
|
474
|
+
if (!event.defaultPrevented) state.resetValidation();
|
|
475
|
+
};
|
|
476
|
+
|
|
477
|
+
element.addEventListener("invalid", onInvalid);
|
|
478
|
+
element.addEventListener("input", onInput);
|
|
479
|
+
element.addEventListener("change", onChange);
|
|
480
|
+
element.form?.addEventListener("reset", onReset);
|
|
481
|
+
|
|
482
|
+
return () => {
|
|
483
|
+
element.removeEventListener("invalid", onInvalid);
|
|
484
|
+
element.removeEventListener("input", onInput);
|
|
485
|
+
element.removeEventListener("change", onChange);
|
|
486
|
+
element.form?.removeEventListener("reset", onReset);
|
|
487
|
+
};
|
|
488
|
+
},
|
|
489
|
+
);
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
/**
|
|
493
|
+
* The control a refused submit should land on.
|
|
494
|
+
*
|
|
495
|
+
* Not `form.querySelector(":invalid")`: a `<fieldset>` matches `:invalid` when
|
|
496
|
+
* anything inside it does, and it comes before its contents in tree order, so
|
|
497
|
+
* a form with its fields in a fieldset would focus nothing.
|
|
498
|
+
*/
|
|
499
|
+
function firstInvalid(form: HTMLFormElement): Element | null {
|
|
500
|
+
for (const element of form.elements) {
|
|
501
|
+
if ((element as Partial<ValidatableElement>).validity?.valid === false) return element;
|
|
502
|
+
}
|
|
503
|
+
return null;
|
|
504
|
+
}
|