@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.
Files changed (103) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +304 -2
  3. package/package.json +437 -4
  4. package/src/autocomplete.tsx +581 -0
  5. package/src/breadcrumbs.tsx +297 -0
  6. package/src/button.tsx +468 -0
  7. package/src/calendar.tsx +2316 -0
  8. package/src/checkbox.tsx +732 -0
  9. package/src/collections.ts +1059 -0
  10. package/src/color.ts +2119 -0
  11. package/src/colorpicker.tsx +2023 -0
  12. package/src/colorswatchpicker.tsx +240 -0
  13. package/src/combobox.tsx +3003 -0
  14. package/src/command.tsx +1203 -0
  15. package/src/date.ts +674 -0
  16. package/src/datefield.tsx +2066 -0
  17. package/src/datepicker.tsx +907 -0
  18. package/src/dialog.tsx +1077 -0
  19. package/src/disclosure.tsx +711 -0
  20. package/src/dnd/clipboard.ts +125 -0
  21. package/src/dnd/collection.ts +1265 -0
  22. package/src/dnd/data.ts +409 -0
  23. package/src/dnd/drag-drop.ts +801 -0
  24. package/src/dnd/index.ts +133 -0
  25. package/src/dnd/manager.ts +639 -0
  26. package/src/dnd/strings.ts +1279 -0
  27. package/src/dnd/targets.ts +726 -0
  28. package/src/dnd/types.ts +212 -0
  29. package/src/dom.ts +703 -0
  30. package/src/drag-and-drop.tsx +669 -0
  31. package/src/drawer.ts +674 -0
  32. package/src/dropzone.tsx +208 -0
  33. package/src/file-trigger.tsx +103 -0
  34. package/src/focus.ts +1370 -0
  35. package/src/form.tsx +94 -0
  36. package/src/gridlist.tsx +1354 -0
  37. package/src/group.tsx +146 -0
  38. package/src/i18n.ts +823 -0
  39. package/src/index.ts +1672 -0
  40. package/src/interactions/description.ts +73 -0
  41. package/src/interactions/flags.ts +35 -0
  42. package/src/interactions/focus-events.ts +226 -0
  43. package/src/interactions/focusable.ts +86 -0
  44. package/src/interactions/hover.ts +213 -0
  45. package/src/interactions/interact-outside.ts +123 -0
  46. package/src/interactions/keyboard.ts +298 -0
  47. package/src/interactions/listeners.ts +78 -0
  48. package/src/interactions/long-press.ts +160 -0
  49. package/src/interactions/modality.ts +428 -0
  50. package/src/interactions/move.ts +257 -0
  51. package/src/interactions/open-link.ts +226 -0
  52. package/src/interactions/press.ts +915 -0
  53. package/src/interactions/prevent-focus.ts +102 -0
  54. package/src/interactions/scroll-wheel.ts +43 -0
  55. package/src/interactions/text-selection.ts +77 -0
  56. package/src/interactions.ts +81 -0
  57. package/src/label.ts +140 -0
  58. package/src/link.tsx +477 -0
  59. package/src/listbox.tsx +1247 -0
  60. package/src/live.ts +208 -0
  61. package/src/menu.tsx +2383 -0
  62. package/src/menubar.tsx +579 -0
  63. package/src/navigation-tree.tsx +357 -0
  64. package/src/navigation.ts +735 -0
  65. package/src/numberfield.tsx +942 -0
  66. package/src/otp.ts +430 -0
  67. package/src/overlay-arrow.tsx +157 -0
  68. package/src/overlays.ts +1549 -0
  69. package/src/platform.ts +75 -0
  70. package/src/presence.ts +164 -0
  71. package/src/preview-trigger.tsx +582 -0
  72. package/src/progress-bar-context.ts +15 -0
  73. package/src/questionnaire.tsx +1717 -0
  74. package/src/radio.tsx +641 -0
  75. package/src/register-dom.ts +12 -0
  76. package/src/scroller.ts +1165 -0
  77. package/src/select.tsx +1745 -0
  78. package/src/selection-indicator.tsx +74 -0
  79. package/src/selection.ts +1472 -0
  80. package/src/shared-element-transition.tsx +316 -0
  81. package/src/sheet.tsx +1461 -0
  82. package/src/slider.tsx +1137 -0
  83. package/src/splitter.ts +1152 -0
  84. package/src/static-collection.ts +211 -0
  85. package/src/switch.tsx +212 -0
  86. package/src/table.tsx +2218 -0
  87. package/src/tabs.tsx +1127 -0
  88. package/src/tag.tsx +637 -0
  89. package/src/textarea.tsx +186 -0
  90. package/src/textfield.tsx +483 -0
  91. package/src/toast-components.tsx +589 -0
  92. package/src/toast.ts +658 -0
  93. package/src/toggle-button-group.tsx +175 -0
  94. package/src/toggle-input.tsx +86 -0
  95. package/src/toggle.ts +384 -0
  96. package/src/togglegroup.ts +365 -0
  97. package/src/tokenfield.tsx +1673 -0
  98. package/src/toolbar.tsx +184 -0
  99. package/src/tooltip.tsx +674 -0
  100. package/src/tree.tsx +2075 -0
  101. package/src/utils.ts +787 -0
  102. package/src/validation.ts +504 -0
  103. package/src/virtualizer.tsx +837 -0
@@ -0,0 +1,732 @@
1
+ /**
2
+ * Checkboxes, on their own and in a group.
3
+ *
4
+ * The indeterminate state is the interesting part: it is a PROPERTY, settable
5
+ * only from script, and it is presentational — the box shows a dash, but the
6
+ * checkbox is still either checked or not, and pressing it commits whichever
7
+ * the value already was. A group's "select all" is the usual reason for one.
8
+ */
9
+
10
+ import {
11
+ cells,
12
+ type Accessor,
13
+ type Child,
14
+ createContext,
15
+ createEffect,
16
+ getContext,
17
+ getOwner,
18
+ type Incoming,
19
+ install,
20
+ } from "@barqjs/core";
21
+ import { ref as makeRef, type RefTarget } from "@barqjs/primitives/refs";
22
+ import { focusRing } from "./focus.ts";
23
+ import { hover } from "./interactions/hover.ts";
24
+ import type { PressEvent } from "./interactions/press.ts";
25
+ import type { ElementRef } from "./interactions/press.ts";
26
+ import { field, type FieldOptions } from "./label.ts";
27
+ import {
28
+ toggle,
29
+ toggleState,
30
+ toggleElementType,
31
+ type ToggleElementType,
32
+ type ToggleOptions,
33
+ type ToggleResult,
34
+ } from "./toggle.ts";
35
+ import { toggleInput, withHelpText } from "./toggle-input.tsx";
36
+ import type { ToggleState } from "./button.tsx";
37
+ import {
38
+ fieldValidation,
39
+ formValidationState,
40
+ VALID_RESULT,
41
+ type ValidationResult,
42
+ type FormValidationState,
43
+ type ValidateFunction,
44
+ type ValidationBehavior,
45
+ } from "./validation.ts";
46
+ import {
47
+ access,
48
+ callback,
49
+ controllable,
50
+ type DOMProps,
51
+ filterDOMProps,
52
+ fromProps,
53
+ type MaybeAccessor,
54
+ mergeProps,
55
+ type StyleProps,
56
+ styleProps,
57
+ } from "./utils.ts";
58
+
59
+ export interface CheckboxOptions extends ToggleOptions {
60
+ /**
61
+ * Show the mixed state.
62
+ *
63
+ * Presentational: the value is still checked or unchecked underneath, and
64
+ * pressing the checkbox commits that value rather than a third one.
65
+ */
66
+ isIndeterminate?: MaybeAccessor<boolean | undefined>;
67
+ }
68
+
69
+ export type CheckboxResult = ToggleResult;
70
+
71
+ export function checkbox(
72
+ options: CheckboxOptions,
73
+ state: ToggleState,
74
+ ref: ElementRef<HTMLInputElement>,
75
+ ): CheckboxResult {
76
+ const result = toggle(options, state, ref);
77
+
78
+ // `indeterminate` has no attribute; it exists only as a property.
79
+ createEffect(
80
+ () =>
81
+ [access(ref) as HTMLInputElement | null, access(options.isIndeterminate) === true] as const,
82
+ ([input, indeterminate]) => {
83
+ if (input === null) return;
84
+ input.indeterminate = indeterminate;
85
+ },
86
+ );
87
+
88
+ return {
89
+ ...result,
90
+ inputProps: mergeProps(result.inputProps, {
91
+ // The box shows a dash, and a screen reader must say "mixed".
92
+ "aria-checked": () => (access(options.isIndeterminate) === true ? "mixed" : undefined),
93
+ }),
94
+ };
95
+ }
96
+
97
+ // ---------------------------------------------------------------------------
98
+ // Group
99
+ // ---------------------------------------------------------------------------
100
+
101
+ export interface CheckboxGroupStateOptions {
102
+ value?: MaybeAccessor<string[] | undefined>;
103
+ defaultValue?: MaybeAccessor<string[] | undefined>;
104
+ isDisabled?: MaybeAccessor<boolean | undefined>;
105
+ isReadOnly?: MaybeAccessor<boolean | undefined>;
106
+ isRequired?: MaybeAccessor<boolean | undefined>;
107
+ isInvalid?: MaybeAccessor<boolean | undefined>;
108
+ /** What the page thinks of the whole selection, checked as it changes. */
109
+ validate?: ValidateFunction<string[]>;
110
+ /** @default "aria" */
111
+ validationBehavior?: MaybeAccessor<ValidationBehavior | undefined>;
112
+ /** The caller's own message, which wins over anything validation found. */
113
+ errorMessage?: MaybeAccessor<unknown>;
114
+ /** The form field name, for matching a server error to this group. */
115
+ name?: MaybeAccessor<string | undefined>;
116
+ onChange?: (value: string[]) => void;
117
+ }
118
+
119
+ export interface CheckboxGroupState {
120
+ value: Accessor<string[]>;
121
+ setValue(value: string[]): void;
122
+ isSelected(value: string): boolean;
123
+ addValue(value: string): void;
124
+ removeValue(value: string): void;
125
+ toggleValue(value: string): void;
126
+ isDisabled: Accessor<boolean>;
127
+ isReadOnly: Accessor<boolean>;
128
+ /**
129
+ * Whether a member still has to be checked: required, and nothing is.
130
+ *
131
+ * Every member carries it, so one checked box is what satisfies the group
132
+ * rather than each box on its own.
133
+ */
134
+ isRequired: Accessor<boolean>;
135
+ isInvalid: Accessor<boolean>;
136
+ /** The group's own behaviour, or the form's, which its members follow. */
137
+ validationBehavior: Accessor<ValidationBehavior | undefined>;
138
+ /**
139
+ * What one member found wrong with itself, by its value: a member's own
140
+ * `validate`, or what the browser makes of its input.
141
+ */
142
+ setInvalid(value: string, result: ValidationResult): void;
143
+ /**
144
+ * The validation lives on the STATE rather than on `checkboxGroup`, because
145
+ * a member checkbox reads it too: a group that is invalid marks every box in
146
+ * it, and the box has no way back to the hook.
147
+ */
148
+ validation: FormValidationState;
149
+ errors: Accessor<string[]>;
150
+ /** For `field`, so `aria-describedby` points at whatever is being shown. */
151
+ errorMessage: Accessor<unknown>;
152
+ }
153
+
154
+ export function checkboxGroupState(options: CheckboxGroupStateOptions): CheckboxGroupState {
155
+ const [value, setValue] = controllable<string[]>(
156
+ () => access(options.value),
157
+ () => access(options.defaultValue) ?? [],
158
+ options.onChange,
159
+ );
160
+
161
+ const isReadOnly = (): boolean => access(options.isReadOnly) === true;
162
+ const isDisabled = (): boolean => access(options.isDisabled) === true;
163
+
164
+ const add = (next: string): void => {
165
+ if (isReadOnly() || isDisabled()) return;
166
+ if (value().includes(next)) return;
167
+ commit([...value(), next]);
168
+ };
169
+
170
+ const remove = (next: string): void => {
171
+ if (isReadOnly() || isDisabled()) return;
172
+ if (!value().includes(next)) return;
173
+ commit(value().filter((entry) => entry !== next));
174
+ };
175
+
176
+ const {
177
+ state: validation,
178
+ behavior,
179
+ isInvalid,
180
+ errors,
181
+ errorMessage,
182
+ } = fieldValidation<string[]>({
183
+ value,
184
+ validate: options.validate,
185
+ validationBehavior: options.validationBehavior,
186
+ isInvalid: options.isInvalid,
187
+ errorMessage: options.errorMessage,
188
+ name: options.name,
189
+ });
190
+
191
+ const commit = (next: string[]): void => {
192
+ setValue(next);
193
+ validation.commitValidation();
194
+ };
195
+
196
+ const invalidMembers = new Map<string, ValidationResult>();
197
+
198
+ return {
199
+ value,
200
+ setValue: (next) => {
201
+ if (isReadOnly() || isDisabled()) return;
202
+ commit(next);
203
+ },
204
+ isSelected: (entry) => value().includes(entry),
205
+ addValue: add,
206
+ removeValue: remove,
207
+ toggleValue: (entry) => (value().includes(entry) ? remove(entry) : add(entry)),
208
+ isDisabled,
209
+ isReadOnly,
210
+ isRequired: () => access(options.isRequired) === true && value().length === 0,
211
+ isInvalid,
212
+ validationBehavior: behavior,
213
+ setInvalid: (member, result) => {
214
+ if (result.isInvalid) invalidMembers.set(member, result);
215
+ else invalidMembers.delete(member);
216
+ validation.updateValidation(mergeValidation([...invalidMembers.values()]));
217
+ },
218
+ validation,
219
+ errors,
220
+ errorMessage,
221
+ };
222
+ }
223
+
224
+ /** Every member's finding as one: invalid if any is, with each message once. */
225
+ function mergeValidation(results: ValidationResult[]): ValidationResult {
226
+ if (results.length === 0) return VALID_RESULT;
227
+ const any = (key: keyof ValidityState): boolean =>
228
+ results.some((result) => result.validationDetails[key]);
229
+ return {
230
+ isInvalid: true,
231
+ validationErrors: [...new Set(results.flatMap((result) => result.validationErrors))],
232
+ validationDetails: {
233
+ badInput: any("badInput"),
234
+ customError: any("customError"),
235
+ patternMismatch: any("patternMismatch"),
236
+ rangeOverflow: any("rangeOverflow"),
237
+ rangeUnderflow: any("rangeUnderflow"),
238
+ stepMismatch: any("stepMismatch"),
239
+ tooLong: any("tooLong"),
240
+ tooShort: any("tooShort"),
241
+ typeMismatch: any("typeMismatch"),
242
+ valueMissing: any("valueMissing"),
243
+ valid: false,
244
+ },
245
+ };
246
+ }
247
+
248
+ export interface CheckboxGroupOptions extends FieldOptions {
249
+ isDisabled?: MaybeAccessor<boolean | undefined>;
250
+ isRequired?: MaybeAccessor<boolean | undefined>;
251
+ isReadOnly?: MaybeAccessor<boolean | undefined>;
252
+ name?: MaybeAccessor<string | undefined>;
253
+ /** The id of the `<form>` the members belong to, when they are not inside it. */
254
+ form?: MaybeAccessor<string | undefined>;
255
+ }
256
+
257
+ export interface CheckboxGroupResult {
258
+ groupProps: DOMProps;
259
+ labelProps: DOMProps;
260
+ descriptionProps: DOMProps;
261
+ errorMessageProps: DOMProps;
262
+ /** For each member's `aria-describedby`: the group's help text and error. */
263
+ descriptionIds: Accessor<string | undefined>;
264
+ }
265
+
266
+ /**
267
+ * A set of related checkboxes.
268
+ *
269
+ * `role="group"`, not `radiogroup` and not `list`: the members are
270
+ * independently checkable, and the group exists only so the shared label is
271
+ * announced with each of them. A `<fieldset>` with a `<legend>` would do the
272
+ * same, and this is what to use when the markup cannot be one.
273
+ */
274
+ export function checkboxGroup(
275
+ options: CheckboxGroupOptions,
276
+ state: CheckboxGroupState,
277
+ ): CheckboxGroupResult {
278
+ const { labelProps, fieldProps, descriptionProps, errorMessageProps, descriptionIds } = field({
279
+ ...options,
280
+ isInvalid: state.isInvalid,
281
+ errorMessage: state.errorMessage,
282
+ // A group is not a labelable element, so `<label for>` would do nothing.
283
+ labelElementType: "span",
284
+ });
285
+
286
+ return {
287
+ groupProps: mergeProps(filterDOMProps(options, { labelable: true }), fieldProps, {
288
+ role: "group",
289
+ "aria-disabled": () => access(options.isDisabled) === true || undefined,
290
+ "aria-invalid": () => state.isInvalid() || undefined,
291
+ "aria-required": () => access(options.isRequired) === true || undefined,
292
+ }),
293
+ labelProps,
294
+ descriptionProps,
295
+ errorMessageProps,
296
+ descriptionIds,
297
+ };
298
+ }
299
+
300
+ // ---------------------------------------------------------------------------
301
+ // Components
302
+ // ---------------------------------------------------------------------------
303
+
304
+ export interface CheckboxComponentProps extends StyleProps {
305
+ children?: Child;
306
+ /**
307
+ * `"label"` when the children are the checkbox's name, `"span"` when they
308
+ * are its drawing and the name comes from somewhere else. Defaults to a
309
+ * label with children and a span without.
310
+ */
311
+ elementType?: ToggleElementType;
312
+ isSelected?: boolean;
313
+ defaultSelected?: boolean;
314
+ isIndeterminate?: boolean;
315
+ isDisabled?: boolean;
316
+ isReadOnly?: boolean;
317
+ isRequired?: boolean;
318
+ isInvalid?: boolean;
319
+ /** What the page thinks of the value, checked as it changes. */
320
+ validate?: ValidateFunction<boolean>;
321
+ /** @default "aria" */
322
+ validationBehavior?: ValidationBehavior;
323
+ /** Help text, rendered after the checkbox and announced with it. */
324
+ description?: Child;
325
+ /**
326
+ * What is wrong, rendered after the checkbox while it is invalid. Without
327
+ * one, whatever validation found is shown.
328
+ */
329
+ errorMessage?: Child;
330
+ value?: string;
331
+ name?: string;
332
+ form?: string;
333
+ autoFocus?: boolean;
334
+ excludeFromTabOrder?: boolean;
335
+ "aria-label"?: string;
336
+ "aria-labelledby"?: string;
337
+ "aria-describedby"?: string;
338
+ ref?: RefTarget<HTMLInputElement>;
339
+ onChange?: (isSelected: boolean) => void;
340
+ onFocus?: (event: FocusEvent) => void;
341
+ onBlur?: (event: FocusEvent) => void;
342
+ onPress?: (event: PressEvent) => void;
343
+ }
344
+
345
+ /** What a part drawn inside a checkbox reads. */
346
+ export interface CheckboxContextValue {
347
+ isSelected: Accessor<boolean>;
348
+ isIndeterminate: Accessor<boolean>;
349
+ isDisabled: Accessor<boolean>;
350
+ }
351
+
352
+ const CheckboxContext = createContext<CheckboxContextValue | null>(null);
353
+
354
+ /**
355
+ * The checkbox a part is drawn inside: the tick or the dash of a design
356
+ * system's box, which appears with a state it does not own.
357
+ */
358
+ export function useCheckbox(): CheckboxContextValue {
359
+ const value = getContext(CheckboxContext);
360
+ if (value === null || value === undefined) {
361
+ throw new Error("This must be rendered inside a Checkbox.");
362
+ }
363
+ return value;
364
+ }
365
+
366
+ function checkedState(value: CheckboxContextValue): "checked" | "unchecked" | "indeterminate" {
367
+ if (value.isIndeterminate()) return "indeterminate";
368
+ return value.isSelected() ? "checked" : "unchecked";
369
+ }
370
+
371
+ /**
372
+ * ```tsx
373
+ * <Checkbox defaultSelected onChange={(on) => agreed.set(on)}>
374
+ * I agree
375
+ * </Checkbox>
376
+ * ```
377
+ *
378
+ * The `<input>` is a real one, hidden with a clip rectangle rather than
379
+ * `display: none`, so it stays focusable and keeps its place in the form.
380
+ *
381
+ * With children it is a `<label>` around them, and they name it. With none it
382
+ * is a `<span>`, so it can sit inside the `<label>` that carries the text:
383
+ *
384
+ * ```tsx
385
+ * <label>
386
+ * <Checkbox /> I agree
387
+ * </label>
388
+ * ```
389
+ */
390
+ export function Checkbox(props: Incoming<CheckboxComponentProps>) {
391
+ const inputRef = makeRef<HTMLInputElement>();
392
+ const options = fromProps(props);
393
+
394
+ const state = toggleState(options);
395
+ const {
396
+ labelProps,
397
+ inputProps,
398
+ descriptionProps,
399
+ errorMessageProps,
400
+ isSelected,
401
+ isPressed,
402
+ isDisabled,
403
+ isReadOnly,
404
+ isInvalid,
405
+ errorMessage,
406
+ } = checkbox(
407
+ {
408
+ ...(options as CheckboxOptions),
409
+ validate: callback(props.validate),
410
+ validationBehavior: () => props.validationBehavior?.(),
411
+ },
412
+ state,
413
+ inputRef,
414
+ );
415
+ const { hoverProps, isHovered } = hover({ isDisabled: options.isDisabled });
416
+ const { focusProps, isFocused, isFocusVisible } = focusRing();
417
+
418
+ const part: CheckboxContextValue = {
419
+ isSelected,
420
+ isIndeterminate: () => props.isIndeterminate?.() === true,
421
+ isDisabled,
422
+ };
423
+ const owner = getOwner();
424
+ if (owner !== null) install(owner, CheckboxContext, () => part);
425
+
426
+ const outerProps = mergeProps(
427
+ labelProps,
428
+ hoverProps,
429
+ // NOT `id`: this is a `<label>`, and `id` belongs on the input it wraps.
430
+ // A `<label for>` elsewhere on the page can only reach a LABELABLE element,
431
+ // so an `id` here answered `getElementById` first — the label came earlier
432
+ // in the document — and clicking the text toggled nothing. Measured on the
433
+ // site's checkbox page.
434
+ filterDOMProps(options, { global: true, id: false }),
435
+ styleProps(props),
436
+ {
437
+ "data-selected": isSelected,
438
+ "data-state": () => checkedState(part),
439
+ "data-indeterminate": () => props.isIndeterminate?.() === true,
440
+ "data-pressed": isPressed,
441
+ "data-hovered": isHovered,
442
+ "data-focused": isFocused,
443
+ "data-focus-visible": isFocusVisible,
444
+ "data-disabled": isDisabled,
445
+ "data-readonly": isReadOnly,
446
+ "data-invalid": isInvalid,
447
+ "data-required": () => props.isRequired?.() === true,
448
+ },
449
+ );
450
+
451
+ return withHelpText(
452
+ toggleInput({
453
+ elementType: toggleElementType(props.elementType?.(), props.children),
454
+ outerProps,
455
+ inputProps,
456
+ focusProps,
457
+ inputRef,
458
+ ref: props.ref?.(),
459
+ children: props.children,
460
+ isDisabled,
461
+ }),
462
+ {
463
+ descriptionProps,
464
+ errorMessageProps,
465
+ description: () => props.description?.(),
466
+ errorMessage: () => (isInvalid() ? errorMessage() : undefined),
467
+ },
468
+ );
469
+ }
470
+
471
+ export interface CheckboxGroupComponentProps extends StyleProps {
472
+ children?: Child;
473
+ label?: Child;
474
+ description?: Child;
475
+ errorMessage?: Child;
476
+ value?: string[];
477
+ defaultValue?: string[];
478
+ isDisabled?: boolean;
479
+ isReadOnly?: boolean;
480
+ isRequired?: boolean;
481
+ isInvalid?: boolean;
482
+ /** What the page thinks of the whole selection, checked as it changes. */
483
+ validate?: ValidateFunction<string[]>;
484
+ /** @default "aria" */
485
+ validationBehavior?: ValidationBehavior;
486
+ name?: string;
487
+ /** The id of the `<form>` the members belong to, when they are not inside it. */
488
+ form?: string;
489
+ "aria-label"?: string;
490
+ "aria-labelledby"?: string;
491
+ onChange?: (value: string[]) => void;
492
+ }
493
+
494
+ /**
495
+ * ```tsx
496
+ * <CheckboxGroup label="Toppings" onChange={(v) => picked.set(v)}>
497
+ * <GroupCheckbox value="cheese">Cheese</GroupCheckbox>
498
+ * <GroupCheckbox value="olives">Olives</GroupCheckbox>
499
+ * </CheckboxGroup>
500
+ * ```
501
+ */
502
+ export function CheckboxGroup(props: CheckboxGroupComponentProps) {
503
+ const options = fromProps(cells(props));
504
+ const state = checkboxGroupState({
505
+ ...(options as CheckboxGroupStateOptions),
506
+ validate: callback(cells(props).validate),
507
+ validationBehavior: () => props.validationBehavior,
508
+ });
509
+ const { groupProps, labelProps, descriptionProps, errorMessageProps, descriptionIds } =
510
+ checkboxGroup(options, state);
511
+
512
+ provideCheckboxGroup({
513
+ state,
514
+ name: () => props.name,
515
+ form: () => props.form,
516
+ descriptionIds,
517
+ });
518
+
519
+ const outerProps = mergeProps(
520
+ groupProps,
521
+ filterDOMProps(options, { global: true }),
522
+ styleProps(cells(props)),
523
+ {
524
+ "data-disabled": state.isDisabled,
525
+ "data-readonly": state.isReadOnly,
526
+ "data-invalid": state.isInvalid,
527
+ "data-required": () => props.isRequired === true,
528
+ "data-testid": () => props["data-testid"],
529
+ },
530
+ );
531
+
532
+ return (
533
+ <div {...outerProps}>
534
+ <span {...labelProps}>{props.label}</span>
535
+ {props.children}
536
+ <span {...descriptionProps}>{props.description}</span>
537
+ <span {...errorMessageProps}>
538
+ {() => (state.isInvalid() ? (state.errorMessage() as Child) : null)}
539
+ </span>
540
+ </div>
541
+ );
542
+ }
543
+
544
+ export interface GroupCheckboxProps extends Omit<
545
+ CheckboxComponentProps,
546
+ "isSelected" | "defaultSelected" | "errorMessage"
547
+ > {
548
+ value: string;
549
+ }
550
+
551
+ /**
552
+ * A checkbox that belongs to the enclosing {@link CheckboxGroup}.
553
+ *
554
+ * Its selection lives in the group, so the group's value is one array rather
555
+ * than one boolean per member. So does its validity: a member's own `validate`
556
+ * makes the whole group invalid, and the group's error is the one shown.
557
+ */
558
+ export function GroupCheckbox(props: Incoming<GroupCheckboxProps>) {
559
+ const inputRef = makeRef<HTMLInputElement>();
560
+ const options = fromProps(props);
561
+ const group = useCheckboxGroup();
562
+ const groupValidation = group.state.validation;
563
+
564
+ const state = toggleState({
565
+ isSelected: () => group.state.isSelected(props.value()),
566
+ isReadOnly: () => group.state.isReadOnly() || props.isReadOnly?.() === true,
567
+ onChange: (selected) => {
568
+ if (selected) group.state.addValue(props.value());
569
+ else group.state.removeValue(props.value());
570
+ props.onChange?.()?.(selected);
571
+ },
572
+ });
573
+
574
+ const behavior = (): ValidationBehavior | undefined =>
575
+ props.validationBehavior?.() ?? group.state.validationBehavior();
576
+
577
+ // Its own `validate`, shown as it happens whatever the behaviour: it only
578
+ // decides what the group is told, and the group decides when to show it.
579
+ const own = formValidationState<boolean>({
580
+ value: state.isSelected,
581
+ validate: callback(props.validate),
582
+ validationBehavior: "aria",
583
+ });
584
+
585
+ // What the browser made of this input, and what this member last told the
586
+ // group under which of its values.
587
+ let native: ValidationResult = VALID_RESULT;
588
+ let current: { value: string; own: ValidationResult } | null = null;
589
+ const report = (): void => {
590
+ if (current === null) return;
591
+ group.state.setInvalid(current.value, current.own.isInvalid ? current.own : native);
592
+ };
593
+
594
+ createEffect(
595
+ () => [props.value(), own.realtimeValidation()] as const,
596
+ ([value, found]) => {
597
+ if (current !== null && current.value !== value) {
598
+ group.state.setInvalid(current.value, VALID_RESULT);
599
+ }
600
+ current = { value, own: found };
601
+ report();
602
+ },
603
+ );
604
+
605
+ const realtimeValidation = (): ValidationResult => {
606
+ const whole = groupValidation.realtimeValidation();
607
+ return whole.isInvalid ? whole : own.realtimeValidation();
608
+ };
609
+ const validation: FormValidationState = {
610
+ realtimeValidation,
611
+ displayValidation: () =>
612
+ behavior() === "native" ? groupValidation.displayValidation() : realtimeValidation(),
613
+ updateValidation: (result) => {
614
+ native = result;
615
+ report();
616
+ },
617
+ resetValidation: () => groupValidation.resetValidation(),
618
+ commitValidation: () => groupValidation.commitValidation(),
619
+ };
620
+
621
+ const {
622
+ labelProps,
623
+ inputProps,
624
+ descriptionProps,
625
+ isSelected,
626
+ isPressed,
627
+ isDisabled,
628
+ isReadOnly,
629
+ isInvalid,
630
+ } = checkbox(
631
+ {
632
+ ...(options as CheckboxOptions),
633
+ validate: undefined,
634
+ validationState: validation,
635
+ validationBehavior: behavior,
636
+ isDisabled: () => group.state.isDisabled() || props.isDisabled?.() === true,
637
+ isReadOnly: () => group.state.isReadOnly() || props.isReadOnly?.() === true,
638
+ isRequired: () => props.isRequired?.() ?? group.state.isRequired(),
639
+ isInvalid: () => props.isInvalid?.(),
640
+ name: () => props.name?.() ?? group.name(),
641
+ form: () => props.form?.() ?? group.form(),
642
+ },
643
+ state,
644
+ inputRef,
645
+ );
646
+
647
+ const { hoverProps, isHovered } = hover({ isDisabled });
648
+ const { focusProps, isFocused, isFocusVisible } = focusRing();
649
+
650
+ const part: CheckboxContextValue = {
651
+ isSelected,
652
+ isIndeterminate: () => props.isIndeterminate?.() === true,
653
+ isDisabled,
654
+ };
655
+ const owner = getOwner();
656
+ if (owner !== null) install(owner, CheckboxContext, () => part);
657
+
658
+ const outerProps = mergeProps(
659
+ labelProps,
660
+ hoverProps,
661
+ // NOT `id`: this is a `<label>`, and `id` belongs on the input it wraps.
662
+ // A `<label for>` elsewhere on the page can only reach a LABELABLE element,
663
+ // so an `id` here answered `getElementById` first — the label came earlier
664
+ // in the document — and clicking the text toggled nothing. Measured on the
665
+ // site's checkbox page.
666
+ filterDOMProps(options, { global: true, id: false }),
667
+ styleProps(props),
668
+ {
669
+ "data-selected": isSelected,
670
+ "data-state": () => checkedState(part),
671
+ "data-pressed": isPressed,
672
+ "data-hovered": isHovered,
673
+ "data-focused": isFocused,
674
+ "data-focus-visible": isFocusVisible,
675
+ "data-disabled": isDisabled,
676
+ "data-readonly": isReadOnly,
677
+ "data-invalid": isInvalid,
678
+ "data-required": () => props.isRequired?.() ?? group.state.isRequired(),
679
+ "data-testid": () => props["data-testid"]?.(),
680
+ },
681
+ );
682
+
683
+ return withHelpText(
684
+ toggleInput({
685
+ elementType: toggleElementType(props.elementType?.(), props.children),
686
+ outerProps,
687
+ // The group's help text and error describe each member as well: a
688
+ // screen reader moving from box to box never passes the group.
689
+ inputProps: mergeProps(inputProps, { "aria-describedby": group.descriptionIds }),
690
+ focusProps,
691
+ inputRef,
692
+ ref: props.ref?.(),
693
+ children: props.children,
694
+ isDisabled,
695
+ }),
696
+ {
697
+ descriptionProps,
698
+ errorMessageProps: {},
699
+ description: () => props.description?.(),
700
+ errorMessage: () => undefined,
701
+ },
702
+ );
703
+ }
704
+
705
+ // ---------------------------------------------------------------------------
706
+ // The group's context
707
+ // ---------------------------------------------------------------------------
708
+
709
+ interface CheckboxGroupContextValue {
710
+ state: CheckboxGroupState;
711
+ name: Accessor<string | undefined>;
712
+ form: Accessor<string | undefined>;
713
+ /** The group's help text and error, for each member's description. */
714
+ descriptionIds: Accessor<string | undefined>;
715
+ }
716
+
717
+ const CheckboxGroupContext = createContext<CheckboxGroupContextValue | null>(null);
718
+
719
+ function provideCheckboxGroup(value: CheckboxGroupContextValue): void {
720
+ const owner = getOwner();
721
+ if (owner === null) return;
722
+ install(owner, CheckboxGroupContext, () => value);
723
+ }
724
+
725
+ /** The enclosing checkbox group. Throws outside one, which is a coding error. */
726
+ export function useCheckboxGroup(): CheckboxGroupContextValue {
727
+ const value = getContext(CheckboxGroupContext);
728
+ if (value === null || value === undefined) {
729
+ throw new Error("A GroupCheckbox must be rendered inside a CheckboxGroup.");
730
+ }
731
+ return value;
732
+ }