@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,711 @@
1
+ /**
2
+ * A disclosure: a button that shows and hides one panel, and an accordion of
3
+ * several.
4
+ *
5
+ * The panel is `hidden="until-found"` rather than removed. That is the whole
6
+ * reason to prefer it over a conditional: the browser's own find-in-page
7
+ * searches a `until-found` subtree, scrolls to a match and fires `beforematch`
8
+ * so the disclosure can open itself. Content the user cannot search for is
9
+ * content they cannot find, and Ctrl+F is how most people navigate a long
10
+ * page.
11
+ *
12
+ * `aria-expanded` on the button and `aria-controls` pointing at the panel are
13
+ * what make the pair a disclosure rather than a button beside a div. The panel
14
+ * points back with `aria-labelledby`, so a screen reader entering it knows
15
+ * what it is a panel of.
16
+ *
17
+ * An accordion is disclosures sharing one state. Whether more than one may be
18
+ * open at a time is the caller's decision and not ARIA's: `allowsMultiple`.
19
+ */
20
+
21
+ import {
22
+ cells,
23
+ type Accessor,
24
+ type Child,
25
+ For,
26
+ createContext,
27
+ createEffect,
28
+ createMemo,
29
+ getContext,
30
+ getOwner,
31
+ type Incoming,
32
+ install,
33
+ provide,
34
+ } from "@barqjs/core";
35
+ import { isServer } from "@barqjs/web";
36
+ import { ref as makeRef, mergeRefs, type RefTarget } from "@barqjs/primitives/refs";
37
+ import { button, type ButtonOptions } from "./button.tsx";
38
+ import type { ItemAccessors, Key, Node } from "./collections.ts";
39
+ import { buildCollection, type ListCollection } from "./collections.ts";
40
+ import { exitDuration } from "./presence.ts";
41
+ import { focusRing } from "./focus.ts";
42
+ import { useLocale } from "./i18n.ts";
43
+ import { hover } from "./interactions/hover.ts";
44
+ import type { ElementRef, PressEvent } from "./interactions/press.ts";
45
+ import {
46
+ access,
47
+ controllable,
48
+ type DOMProps,
49
+ filterDOMProps,
50
+ fromProps,
51
+ id,
52
+ type MaybeAccessor,
53
+ mergeProps,
54
+ type StyleProps,
55
+ styleProps,
56
+ } from "./utils.ts";
57
+
58
+ // ---------------------------------------------------------------------------
59
+ // State
60
+ // ---------------------------------------------------------------------------
61
+
62
+ export interface DisclosureStateOptions {
63
+ isExpanded?: MaybeAccessor<boolean | undefined>;
64
+ defaultExpanded?: MaybeAccessor<boolean | undefined>;
65
+ onExpandedChange?: (isExpanded: boolean) => void;
66
+ }
67
+
68
+ export interface DisclosureState {
69
+ isExpanded: Accessor<boolean>;
70
+ setExpanded(isExpanded: boolean): void;
71
+ expand(): void;
72
+ collapse(): void;
73
+ toggle(): void;
74
+ }
75
+
76
+ export function disclosureState(options: DisclosureStateOptions = {}): DisclosureState {
77
+ const [isExpanded, setExpanded] = controllable<boolean>(
78
+ () => access(options.isExpanded),
79
+ () => access(options.defaultExpanded) ?? false,
80
+ options.onExpandedChange,
81
+ );
82
+
83
+ return {
84
+ isExpanded,
85
+ setExpanded,
86
+ expand: () => setExpanded(true),
87
+ collapse: () => setExpanded(false),
88
+ toggle: () => setExpanded(!isExpanded()),
89
+ };
90
+ }
91
+
92
+ export interface DisclosureGroupStateOptions {
93
+ expandedKeys?: MaybeAccessor<Iterable<Key> | undefined>;
94
+ defaultExpandedKeys?: MaybeAccessor<Iterable<Key> | undefined>;
95
+ /** Let more than one panel be open at once. @default false */
96
+ allowsMultiple?: MaybeAccessor<boolean | undefined>;
97
+ /**
98
+ * Whether the one open section may be shut, leaving none open. Read only
99
+ * without `allowsMultiple`, where every section closes on its own anyway.
100
+ * @default true
101
+ */
102
+ isCollapsible?: MaybeAccessor<boolean | undefined>;
103
+ isDisabled?: MaybeAccessor<boolean | undefined>;
104
+ onExpandedChange?: (keys: Set<Key>) => void;
105
+ }
106
+
107
+ export interface DisclosureGroupState {
108
+ expandedKeys: Accessor<Set<Key>>;
109
+ allowsMultiple: Accessor<boolean>;
110
+ /** Whether pressing this open section would do nothing. */
111
+ isLocked(key: Key): boolean;
112
+ isDisabled: Accessor<boolean>;
113
+ toggleKey(key: Key): void;
114
+ setExpandedKeys(keys: Set<Key>): void;
115
+ }
116
+
117
+ /** Several disclosures sharing which of them is open. */
118
+ export function disclosureGroupState(
119
+ options: DisclosureGroupStateOptions = {},
120
+ ): DisclosureGroupState {
121
+ const [stored, setExpandedKeys] = controllable<Set<Key>>(
122
+ () => {
123
+ const given = access(options.expandedKeys);
124
+ return given === undefined ? undefined : new Set(given);
125
+ },
126
+ () => new Set(access(options.defaultExpandedKeys) ?? []),
127
+ options.onExpandedChange,
128
+ );
129
+
130
+ const allowsMultiple = (): boolean => access(options.allowsMultiple) === true;
131
+ const expandedKeys = createMemo((): Set<Key> => {
132
+ const keys = stored();
133
+ if (allowsMultiple() || keys.size <= 1) return keys;
134
+ const [first] = keys;
135
+ return new Set([first as Key]);
136
+ });
137
+ const isLocked = (key: Key): boolean =>
138
+ !allowsMultiple() && access(options.isCollapsible) === false && expandedKeys().has(key);
139
+
140
+ return {
141
+ expandedKeys,
142
+ allowsMultiple,
143
+ isLocked,
144
+ isDisabled: () => access(options.isDisabled) === true,
145
+ setExpandedKeys,
146
+ toggleKey: (key) => {
147
+ const open = expandedKeys();
148
+ if (open.has(key)) {
149
+ if (isLocked(key)) return;
150
+ const next = new Set(open);
151
+ next.delete(key);
152
+ setExpandedKeys(next);
153
+ return;
154
+ }
155
+ // Closing the others is the DEFAULT: an accordion whose panels all open
156
+ // at once is a list of disclosures, and the caller says so.
157
+ setExpandedKeys(allowsMultiple() ? new Set([...open, key]) : new Set([key]));
158
+ },
159
+ };
160
+ }
161
+
162
+ // ---------------------------------------------------------------------------
163
+ // Hooks
164
+ // ---------------------------------------------------------------------------
165
+
166
+ export interface DisclosureOptions {
167
+ panelRef: ElementRef;
168
+ isDisabled?: MaybeAccessor<boolean | undefined>;
169
+ }
170
+
171
+ export interface DisclosureResult {
172
+ /** Options for {@link button}, not props for an element. */
173
+ buttonProps: DOMProps;
174
+ panelProps: DOMProps;
175
+ }
176
+
177
+ export function disclosure(options: DisclosureOptions, state: DisclosureState): DisclosureResult {
178
+ const triggerId = id();
179
+ const panelId = id();
180
+ const isDisabled = (): boolean => access(options.isDisabled) === true;
181
+
182
+ if (!isServer) {
183
+ /**
184
+ * Find-in-page opens it.
185
+ *
186
+ * The browser strips `hidden` before firing `beforematch`, so the
187
+ * attribute is put back and the state told to open: without that the panel
188
+ * is visible while the state still says it is closed, and the next toggle
189
+ * closes nothing.
190
+ */
191
+ createEffect(
192
+ () => access(options.panelRef) as HTMLElement | null,
193
+ (panel) => {
194
+ if (panel === null) return undefined;
195
+ const onBeforeMatch = (): void => {
196
+ panel.setAttribute("hidden", "until-found");
197
+ state.expand();
198
+ };
199
+ panel.addEventListener("beforematch", onBeforeMatch);
200
+ return () => panel.removeEventListener("beforematch", onBeforeMatch);
201
+ },
202
+ );
203
+
204
+ /**
205
+ * `until-found`, not `true`: the panel stays searchable while it is shut.
206
+ *
207
+ * The attribute goes on only once the stylesheet has finished closing the
208
+ * panel. `hidden` stops the content being rendered AT ONCE, so setting it
209
+ * the moment the state flipped cancelled the collapse: a panel whose CSS
210
+ * transitions `grid-template-rows` opened over 200ms and then vanished in
211
+ * one frame, and the transition it was still running painted nothing.
212
+ *
213
+ * It is set synchronously in every other case — a panel that starts shut,
214
+ * one with no transition, and one under `prefers-reduced-motion` — so
215
+ * nothing flashes open on the first render.
216
+ */
217
+ let previous: boolean | null = null;
218
+ createEffect(
219
+ () => [access(options.panelRef) as HTMLElement | null, state.isExpanded()] as const,
220
+ ([panel, expanded]) => {
221
+ if (panel === null) return undefined;
222
+
223
+ const first = previous === null;
224
+ previous = expanded;
225
+ const hide = (): void => panel.setAttribute("hidden", "until-found");
226
+ const size = (width: string, height: string): void => {
227
+ panel.style.setProperty("--disclosure-panel-width", width);
228
+ panel.style.setProperty("--disclosure-panel-height", height);
229
+ };
230
+ const measured = (): void => size(`${panel.scrollWidth}px`, `${panel.scrollHeight}px`);
231
+
232
+ if (expanded) {
233
+ panel.removeAttribute("hidden");
234
+ if (first || typeof panel.getAnimations !== "function") {
235
+ size("auto", "auto");
236
+ return undefined;
237
+ }
238
+ // Pixels, so a transition has two lengths to run between; `auto`
239
+ // again once it is done, so the content can grow and shrink.
240
+ measured();
241
+ let settled = false;
242
+ Promise.all(panel.getAnimations().map((animation) => animation.finished)).then(
243
+ () => {
244
+ if (!settled) size("auto", "auto");
245
+ },
246
+ () => {},
247
+ );
248
+ return () => {
249
+ settled = true;
250
+ };
251
+ }
252
+
253
+ if (first) {
254
+ size("0px", "0px");
255
+ hide();
256
+ return undefined;
257
+ }
258
+
259
+ measured();
260
+ // Layout is forced between the two lengths, or the browser coalesces
261
+ // them and the transition starts from zero.
262
+ panel.getBoundingClientRect();
263
+ size("0px", "0px");
264
+
265
+ const closing = exitDuration(panel);
266
+ if (closing <= 0) {
267
+ hide();
268
+ return undefined;
269
+ }
270
+ const timer = setTimeout(hide, closing);
271
+ return () => clearTimeout(timer);
272
+ },
273
+ );
274
+ }
275
+
276
+ return {
277
+ buttonProps: {
278
+ id: triggerId,
279
+ isDisabled: options.isDisabled,
280
+ "aria-expanded": () => state.isExpanded(),
281
+ "aria-controls": panelId,
282
+ // On press for a pointer, on press START for a key: a keyboard toggle
283
+ // that waited for the key to come up would feel a frame late next to
284
+ // everything else the platform does on key down.
285
+ onPress: (event: PressEvent) => {
286
+ if (isDisabled() || event.pointerType === "keyboard") return;
287
+ state.toggle();
288
+ },
289
+ onPressStart: (event: PressEvent) => {
290
+ if (isDisabled() || event.pointerType !== "keyboard") return;
291
+ state.toggle();
292
+ },
293
+ },
294
+ panelProps: {
295
+ id: panelId,
296
+ role: "group",
297
+ "aria-labelledby": triggerId,
298
+ // At once, while `hidden` waits for the collapse to finish: a panel on
299
+ // its way out is still painted, and still read, unless it says so.
300
+ "aria-hidden": () => !state.isExpanded() || undefined,
301
+ // On the SERVER the attribute is all there is: the effects above have
302
+ // not run, and a panel rendered without it would flash open.
303
+ hidden: () => (isServer ? (state.isExpanded() ? undefined : "until-found") : undefined),
304
+ },
305
+ };
306
+ }
307
+
308
+ // ---------------------------------------------------------------------------
309
+ // Components
310
+ // ---------------------------------------------------------------------------
311
+
312
+ interface DisclosureContextValue {
313
+ state: DisclosureState;
314
+ buttonProps: DOMProps;
315
+ panelProps: DOMProps;
316
+ panelRef: ReturnType<typeof makeRef<HTMLDivElement>>;
317
+ isDisabled: Accessor<boolean>;
318
+ /** Open, and not allowed to shut: the last open section of a group that may not be empty. */
319
+ isLocked?: Accessor<boolean>;
320
+ /** The group this section belongs to. Absent for a lone disclosure. */
321
+ group?: DisclosureGroupContextValue;
322
+ }
323
+
324
+ const DisclosureContext = createContext<DisclosureContextValue | null>(null);
325
+
326
+ export function useDisclosure(): DisclosureContextValue {
327
+ const value = getContext(DisclosureContext);
328
+ if (value === null || value === undefined) {
329
+ throw new Error("This must be rendered inside a Disclosure.");
330
+ }
331
+ return value;
332
+ }
333
+
334
+ /**
335
+ * NO `StyleProps`, and that is the whole of what this component is.
336
+ *
337
+ * `<Disclosure>` renders no element — it is a provider, like every grouping
338
+ * component here — so a `class`, an `id` or a `data-*` handed to it has nothing
339
+ * to land on and vanishes in silence. It used to declare them anyway, and
340
+ * `@barqjs/ui`'s accordion lost its dividers to exactly that on
341
+ * `<DisclosureGroupItem>`. A consumer that needs an element brings its own
342
+ * around this one, which is what `<Collapsible>` and `<AccordionItem>` do.
343
+ */
344
+ export interface DisclosureComponentProps {
345
+ children?: Child;
346
+ isExpanded?: boolean;
347
+ defaultExpanded?: boolean;
348
+ isDisabled?: boolean;
349
+ onExpandedChange?: (isExpanded: boolean) => void;
350
+ }
351
+
352
+ /**
353
+ * ```tsx
354
+ * <Disclosure>
355
+ * <DisclosureButton>Details</DisclosureButton>
356
+ * <DisclosurePanel>Everything else</DisclosurePanel>
357
+ * </Disclosure>
358
+ * ```
359
+ */
360
+ export function Disclosure(props: Incoming<DisclosureComponentProps>) {
361
+ const panelRef = makeRef<HTMLDivElement>();
362
+ const options = fromProps(props);
363
+ const state = disclosureState(options);
364
+
365
+ const { buttonProps, panelProps } = disclosure(
366
+ { panelRef, isDisabled: () => props.isDisabled?.() },
367
+ state,
368
+ );
369
+
370
+ const value: DisclosureContextValue = {
371
+ state,
372
+ buttonProps,
373
+ panelProps,
374
+ panelRef,
375
+ isDisabled: () => props.isDisabled?.() === true,
376
+ };
377
+ return provide(
378
+ DisclosureContext,
379
+ () => value,
380
+ () => props.children as unknown,
381
+ );
382
+ }
383
+
384
+ export interface DisclosureButtonComponentProps extends StyleProps {
385
+ children?: Child;
386
+ isDisabled?: boolean;
387
+ ref?: RefTarget<HTMLButtonElement>;
388
+ }
389
+
390
+ export function DisclosureButton(props: DisclosureButtonComponentProps) {
391
+ const domRef = makeRef<HTMLButtonElement>();
392
+ const value = useDisclosure();
393
+
394
+ const { buttonProps, isPressed } = button(
395
+ { ...(fromProps(cells(props)) as ButtonOptions), ...value.buttonProps },
396
+ domRef,
397
+ );
398
+ const { hoverProps, isHovered } = hover({ isDisabled: () => props.isDisabled });
399
+ const { focusProps, isFocusVisible } = focusRing();
400
+ // `button()` delivers `onClick` itself; bound on the element as well, a
401
+ // caller's handler runs twice for every mouse click.
402
+ const { onClick: _, ...forwarded } = filterDOMProps(fromProps(cells(props)), { global: true });
403
+
404
+ const elementProps = mergeProps(
405
+ buttonProps,
406
+ { id: value.buttonProps.id },
407
+ hoverProps,
408
+ focusProps,
409
+ forwarded,
410
+ styleProps(cells(props)),
411
+ {
412
+ "aria-disabled": () => value.isLocked?.() === true || undefined,
413
+ "data-expanded": value.state.isExpanded,
414
+ "data-state": () => (value.state.isExpanded() ? "open" : "closed"),
415
+ "data-orientation": () => value.group?.orientation(),
416
+ "data-pressed": isPressed,
417
+ "data-hovered": isHovered,
418
+ "data-focus-visible": isFocusVisible,
419
+ "data-disabled": () => props.isDisabled === true || value.isDisabled(),
420
+ "data-testid": () => props["data-testid"],
421
+ },
422
+ );
423
+
424
+ const group = value.group;
425
+ const enlist = (element: HTMLButtonElement | null): void => {
426
+ if (element !== null && group !== undefined) headerGroups.set(element, group);
427
+ };
428
+
429
+ return (
430
+ <button {...elementProps} ref={mergeRefs(domRef.set, enlist, props.ref)}>
431
+ {props.children}
432
+ </button>
433
+ );
434
+ }
435
+
436
+ export interface DisclosurePanelComponentProps extends StyleProps {
437
+ children?: Child;
438
+ /** @default "group" */
439
+ role?: string;
440
+ ref?: RefTarget<HTMLDivElement>;
441
+ }
442
+
443
+ /**
444
+ * The panel. Still in the document while collapsed, so find-in-page can reach
445
+ * it and open the disclosure it belongs to.
446
+ */
447
+ export function DisclosurePanel(props: DisclosurePanelComponentProps) {
448
+ const value = useDisclosure();
449
+ const { focusProps, isFocusVisible } = focusRing({ within: true });
450
+
451
+ const elementProps = mergeProps(
452
+ value.panelProps,
453
+ filterDOMProps(fromProps(cells(props)), { global: true, labelable: true }),
454
+ styleProps(cells(props)),
455
+ focusProps,
456
+ {
457
+ role: () => props.role ?? "group",
458
+ "data-focus-visible-within": isFocusVisible,
459
+ "data-expanded": value.state.isExpanded,
460
+ "data-state": () => (value.state.isExpanded() ? "open" : "closed"),
461
+ "data-orientation": () => value.group?.orientation(),
462
+ "data-disabled": value.isDisabled,
463
+ "data-testid": () => props["data-testid"],
464
+ },
465
+ );
466
+
467
+ return (
468
+ <div {...elementProps} ref={mergeRefs(value.panelRef.set, props.ref)}>
469
+ {props.children}
470
+ </div>
471
+ );
472
+ }
473
+
474
+ // ---------------------------------------------------------------------------
475
+ // A group of them
476
+ // ---------------------------------------------------------------------------
477
+
478
+ interface DisclosureGroupContextValue {
479
+ state: DisclosureGroupState;
480
+ orientation: Accessor<"vertical" | "horizontal">;
481
+ }
482
+
483
+ /**
484
+ * Which group each header button belongs to.
485
+ *
486
+ * By element rather than by a query, because an accordion inside another
487
+ * accordion's panel has headers that match any selector the outer one could
488
+ * write, and the arrow keys must not walk into them.
489
+ */
490
+ const headerGroups = new WeakMap<Element, DisclosureGroupContextValue>();
491
+
492
+ const DisclosureGroupContext = createContext<DisclosureGroupContextValue | null>(null);
493
+ const DisclosureNodeContext = createContext<Node<unknown> | null>(null);
494
+
495
+ export function useDisclosureGroup(): DisclosureGroupContextValue {
496
+ const value = getContext(DisclosureGroupContext);
497
+ if (value === null || value === undefined) {
498
+ throw new Error("This must be rendered inside a DisclosureGroup.");
499
+ }
500
+ return value;
501
+ }
502
+
503
+ /** The collection node the section being built is for. */
504
+ export function useDisclosureNode(): Node<unknown> {
505
+ const node = getContext(DisclosureNodeContext);
506
+ if (node === null || node === undefined) {
507
+ throw new Error("This must be rendered inside a DisclosureGroup's item callback.");
508
+ }
509
+ return node;
510
+ }
511
+
512
+ export interface DisclosureGroupComponentProps<T> extends StyleProps, ItemAccessors<T> {
513
+ /** The sections, in order. Leave it out to write the sections as children. */
514
+ items?: Iterable<T>;
515
+ /**
516
+ * How one section renders, returning a `<DisclosureGroupItem>`. Without
517
+ * `items`, the sections themselves, each with an `id`.
518
+ */
519
+ children?: ((item: T) => Child) | Child;
520
+ expandedKeys?: Iterable<Key>;
521
+ defaultExpandedKeys?: Iterable<Key>;
522
+ /** @default false */
523
+ allowsMultiple?: boolean;
524
+ /** Whether the one open section may be shut. @default true */
525
+ isCollapsible?: boolean;
526
+ /** Which arrow keys move between the headers. @default "vertical" */
527
+ orientation?: "vertical" | "horizontal";
528
+ /** Overrides the direction in scope for the left and right arrows. */
529
+ dir?: "ltr" | "rtl";
530
+ isDisabled?: boolean;
531
+ ref?: RefTarget<HTMLDivElement>;
532
+ onExpandedChange?: (keys: Set<Key>) => void;
533
+ }
534
+
535
+ /**
536
+ * An accordion.
537
+ *
538
+ * ```tsx
539
+ * <DisclosureGroup items={sections()}>
540
+ * {(section) => (
541
+ * <DisclosureGroupItem>
542
+ * <DisclosureButton>{section.name}</DisclosureButton>
543
+ * <DisclosurePanel>{section.body}</DisclosurePanel>
544
+ * </DisclosureGroupItem>
545
+ * )}
546
+ * </DisclosureGroup>
547
+ * ```
548
+ *
549
+ * Or written out, each section naming itself:
550
+ *
551
+ * ```tsx
552
+ * <DisclosureGroup>
553
+ * <DisclosureGroupItem id="billing">…</DisclosureGroupItem>
554
+ * <DisclosureGroupItem id="shipping">…</DisclosureGroupItem>
555
+ * </DisclosureGroup>
556
+ * ```
557
+ *
558
+ * The arrow keys, Home and End move between the headers. The authoring
559
+ * practices call that optional; it is here because a long accordion is
560
+ * otherwise a Tab stop per section with nothing faster.
561
+ */
562
+ export function DisclosureGroup<T>(props: DisclosureGroupComponentProps<T>) {
563
+ const options = fromProps(cells(props) as unknown as Incoming<Record<string, unknown>>);
564
+ const state = disclosureGroupState({
565
+ ...(options as DisclosureGroupStateOptions),
566
+ onExpandedChange: (keys) => props.onExpandedChange?.(keys),
567
+ });
568
+
569
+ const items = cells(props).items;
570
+ const collection = (): ListCollection<T> =>
571
+ buildCollection(items?.() ?? [], cells(props) as unknown as ItemAccessors<T>);
572
+
573
+ const locale = useLocale();
574
+ const orientation = (): "vertical" | "horizontal" => props.orientation ?? "vertical";
575
+ const group: DisclosureGroupContextValue = { state, orientation };
576
+
577
+ const owner = getOwner();
578
+ if (owner !== null) install(owner, DisclosureGroupContext, () => group);
579
+
580
+ const onKeyDown = (event: KeyboardEvent): void => {
581
+ const root = event.currentTarget as Element | null;
582
+ const from = (event.target as Element | null)?.closest("button") ?? null;
583
+ if (root === null || from === null || headerGroups.get(from) !== group) return;
584
+
585
+ const rtl = (props.dir ?? locale().direction) === "rtl";
586
+ const horizontal = orientation() === "horizontal";
587
+ const forward = horizontal ? (rtl ? "ArrowLeft" : "ArrowRight") : "ArrowDown";
588
+ const back = horizontal ? (rtl ? "ArrowRight" : "ArrowLeft") : "ArrowUp";
589
+ if (
590
+ event.key !== forward &&
591
+ event.key !== back &&
592
+ event.key !== "Home" &&
593
+ event.key !== "End"
594
+ ) {
595
+ return;
596
+ }
597
+
598
+ const headers = [...root.querySelectorAll<HTMLButtonElement>("button")].filter(
599
+ (candidate) => headerGroups.get(candidate) === group && !candidate.disabled,
600
+ );
601
+ const at = headers.indexOf(from);
602
+ if (at === -1) return;
603
+
604
+ let next = at;
605
+ if (event.key === "Home") next = 0;
606
+ else if (event.key === "End") next = headers.length - 1;
607
+ else if (event.key === forward) next = (at + 1) % headers.length;
608
+ else next = (at - 1 + headers.length) % headers.length;
609
+
610
+ event.preventDefault();
611
+ headers[next]?.focus();
612
+ };
613
+
614
+ const elementProps = mergeProps(
615
+ filterDOMProps(fromProps(cells(props)), { global: true }),
616
+ styleProps(cells(props)),
617
+ {
618
+ onKeyDown,
619
+ "data-orientation": orientation,
620
+ "data-disabled": state.isDisabled,
621
+ "data-testid": () => props["data-testid"],
622
+ },
623
+ );
624
+
625
+ if (items === undefined) {
626
+ // A written-out group inside a section of a collection-driven one must not
627
+ // key its sections by the outer section's node.
628
+ if (owner !== null) install(owner, DisclosureNodeContext, () => null);
629
+ return (
630
+ <div {...elementProps} ref={mergeRefs(props.ref)}>
631
+ {props.children}
632
+ </div>
633
+ );
634
+ }
635
+
636
+ const render = props.children as unknown as (item: T) => Child;
637
+
638
+ return (
639
+ <div {...elementProps} ref={mergeRefs(props.ref)}>
640
+ <For each={() => [...collection()]}>
641
+ {(node: Node<T>) => {
642
+ const rowOwner = getOwner();
643
+ if (rowOwner !== null) {
644
+ install(rowOwner, DisclosureNodeContext, () => node as Node<unknown>);
645
+ }
646
+ return render(node.value as T);
647
+ }}
648
+ </For>
649
+ </div>
650
+ );
651
+ }
652
+
653
+ /** No `StyleProps`, for the reason on {@link DisclosureComponentProps}. */
654
+ export interface DisclosureGroupItemComponentProps {
655
+ children?: Child;
656
+ isDisabled?: boolean;
657
+ /**
658
+ * The key this section answers to in `expandedKeys`. Read when the group was
659
+ * given no `items`; with them the key is the item's own.
660
+ */
661
+ id?: Key;
662
+ }
663
+
664
+ /**
665
+ * One section of a {@link DisclosureGroup}, sharing the group's state.
666
+ *
667
+ * The same `<DisclosureButton>` and `<DisclosurePanel>` go inside it as go
668
+ * inside a lone `<Disclosure>`: what changes is where "expanded" is kept.
669
+ */
670
+ export function DisclosureGroupItem(props: Incoming<DisclosureGroupItemComponentProps>) {
671
+ const panelRef = makeRef<HTMLDivElement>();
672
+ const group = useDisclosureGroup();
673
+ const node = getContext(DisclosureNodeContext) ?? null;
674
+ const generated = id();
675
+ const key = (): Key => node?.key ?? props.id?.() ?? generated();
676
+
677
+ const state: DisclosureState = {
678
+ isExpanded: () => group.state.expandedKeys().has(key()),
679
+ setExpanded: (expanded) => {
680
+ if (expanded === group.state.expandedKeys().has(key())) return;
681
+ group.state.toggleKey(key());
682
+ },
683
+ expand: () => {
684
+ if (!group.state.expandedKeys().has(key())) group.state.toggleKey(key());
685
+ },
686
+ collapse: () => {
687
+ if (group.state.expandedKeys().has(key())) group.state.toggleKey(key());
688
+ },
689
+ toggle: () => group.state.toggleKey(key()),
690
+ };
691
+
692
+ const isDisabled = (): boolean =>
693
+ props.isDisabled?.() === true || group.state.isDisabled() || node?.props?.isDisabled === true;
694
+
695
+ const { buttonProps, panelProps } = disclosure({ panelRef, isDisabled }, state);
696
+
697
+ const value: DisclosureContextValue = {
698
+ state,
699
+ buttonProps,
700
+ panelProps,
701
+ panelRef,
702
+ isDisabled,
703
+ isLocked: () => group.state.isLocked(key()),
704
+ group,
705
+ };
706
+ return provide(
707
+ DisclosureContext,
708
+ () => value,
709
+ () => props.children as unknown,
710
+ );
711
+ }