@barqjs/aria 0.0.0-stage → 0.2.0-next.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.
Files changed (76) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +293 -2
  3. package/package.json +347 -4
  4. package/src/breadcrumbs.tsx +296 -0
  5. package/src/button.tsx +342 -0
  6. package/src/calendar.tsx +1389 -0
  7. package/src/checkbox.tsx +570 -0
  8. package/src/collections.ts +976 -0
  9. package/src/color.ts +562 -0
  10. package/src/colorpicker.tsx +1478 -0
  11. package/src/combobox.tsx +2481 -0
  12. package/src/command.tsx +1184 -0
  13. package/src/date.ts +652 -0
  14. package/src/datefield.tsx +951 -0
  15. package/src/datepicker.tsx +556 -0
  16. package/src/dialog.tsx +890 -0
  17. package/src/disclosure.tsx +659 -0
  18. package/src/dom.ts +706 -0
  19. package/src/drawer.ts +674 -0
  20. package/src/focus.ts +1370 -0
  21. package/src/form.tsx +94 -0
  22. package/src/gridlist.tsx +563 -0
  23. package/src/i18n.ts +823 -0
  24. package/src/index.ts +1270 -0
  25. package/src/interactions/description.ts +73 -0
  26. package/src/interactions/flags.ts +35 -0
  27. package/src/interactions/focus-events.ts +218 -0
  28. package/src/interactions/focusable.ts +86 -0
  29. package/src/interactions/hover.ts +213 -0
  30. package/src/interactions/interact-outside.ts +123 -0
  31. package/src/interactions/keyboard.ts +105 -0
  32. package/src/interactions/listeners.ts +78 -0
  33. package/src/interactions/long-press.ts +160 -0
  34. package/src/interactions/modality.ts +416 -0
  35. package/src/interactions/move.ts +257 -0
  36. package/src/interactions/open-link.ts +193 -0
  37. package/src/interactions/press.ts +898 -0
  38. package/src/interactions/prevent-focus.ts +102 -0
  39. package/src/interactions/scroll-wheel.ts +43 -0
  40. package/src/interactions/text-selection.ts +77 -0
  41. package/src/interactions.ts +81 -0
  42. package/src/label.ts +128 -0
  43. package/src/link.tsx +381 -0
  44. package/src/listbox.tsx +721 -0
  45. package/src/live.ts +204 -0
  46. package/src/menu.tsx +2290 -0
  47. package/src/menubar.tsx +575 -0
  48. package/src/navigation.ts +735 -0
  49. package/src/numberfield.tsx +838 -0
  50. package/src/otp.ts +430 -0
  51. package/src/overlays.ts +1247 -0
  52. package/src/platform.ts +74 -0
  53. package/src/presence.ts +164 -0
  54. package/src/questionnaire.tsx +1712 -0
  55. package/src/radio.tsx +567 -0
  56. package/src/register-dom.ts +12 -0
  57. package/src/scroller.ts +1165 -0
  58. package/src/select.tsx +1665 -0
  59. package/src/selection.ts +1415 -0
  60. package/src/slider.tsx +1042 -0
  61. package/src/splitter.ts +1152 -0
  62. package/src/static-collection.ts +211 -0
  63. package/src/switch.tsx +186 -0
  64. package/src/table.tsx +0 -0
  65. package/src/tabs.tsx +1018 -0
  66. package/src/tag.tsx +452 -0
  67. package/src/textfield.tsx +417 -0
  68. package/src/toast.ts +658 -0
  69. package/src/toggle-input.tsx +48 -0
  70. package/src/toggle.ts +321 -0
  71. package/src/togglegroup.ts +365 -0
  72. package/src/toolbar.tsx +179 -0
  73. package/src/tooltip.tsx +657 -0
  74. package/src/utils.ts +758 -0
  75. package/src/validation.ts +447 -0
  76. package/src/virtualizer.tsx +674 -0
package/src/tabs.tsx ADDED
@@ -0,0 +1,1018 @@
1
+ /**
2
+ * Tabs: one list of choices, one panel showing what was chosen.
3
+ *
4
+ * The tab list is ONE Tab stop. Inside it the arrow keys move between tabs and
5
+ * Tab leaves for the panel, which is the whole reason the pattern exists: a
6
+ * dozen tabs must not be a dozen stops between the user and the content.
7
+ *
8
+ * Two decisions have visible consequences and no obvious default:
9
+ *
10
+ * - **Automatic or manual activation.** Automatic selects as focus moves,
11
+ * which is right when switching is instant. Manual waits for Enter or
12
+ * Space, and is right when a tab loads something: arrowing through five tabs
13
+ * under automatic activation starts five loads the user did not ask for.
14
+ * - **Whether the panel is a Tab stop.** It is one only when it holds nothing
15
+ * focusable. With a form inside, Tab should reach the first field; with
16
+ * prose inside, Tab has to reach the panel or a keyboard user cannot scroll
17
+ * it.
18
+ *
19
+ * `aria-controls` on the tab and `aria-labelledby` on the panel are the same
20
+ * relationship stated from both ends, and assistive technology uses both.
21
+ */
22
+
23
+ import {
24
+ type Accessor,
25
+ type Child,
26
+ createEffect,
27
+ For,
28
+ createContext,
29
+ getContext,
30
+ getOwner,
31
+ type Incoming,
32
+ install,
33
+ Show,
34
+ createSignal,
35
+ untrack,
36
+ } from "@barqjs/core";
37
+ import { isServer } from "@barqjs/web";
38
+ import { ref as makeRef, mergeRefs, type RefTarget } from "@barqjs/primitives/refs";
39
+ import type { Collection, ItemAccessors, Key, Node } from "./collections.ts";
40
+ import {
41
+ buildCollection,
42
+ singleSelectListState,
43
+ type SingleSelectListState,
44
+ } from "./collections.ts";
45
+ import { focusableWalker } from "./focus.ts";
46
+ import { focusRing } from "./focus.ts";
47
+ import { hover } from "./interactions/hover.ts";
48
+ import type { ElementRef } from "./interactions/press.ts";
49
+ import { provideDirection, useDirection, useLocale, type ReadingDirection } from "./i18n.ts";
50
+ import {
51
+ selectableCollection,
52
+ selectableItem,
53
+ type Direction,
54
+ type KeyboardDelegate,
55
+ type Orientation,
56
+ } from "./selection.ts";
57
+ import {
58
+ access,
59
+ controllable,
60
+ type DOMProps,
61
+ filterDOMProps,
62
+ fromProps,
63
+ id,
64
+ type MaybeAccessor,
65
+ mergeProps,
66
+ type StyleProps,
67
+ styleProps,
68
+ } from "./utils.ts";
69
+
70
+ // ---------------------------------------------------------------------------
71
+ // State
72
+ // ---------------------------------------------------------------------------
73
+
74
+ export interface TabListStateOptions<T> extends ItemAccessors<T> {
75
+ items?: MaybeAccessor<Iterable<T> | undefined>;
76
+ selectedKey?: MaybeAccessor<Key | null | undefined>;
77
+ defaultSelectedKey?: MaybeAccessor<Key | null | undefined>;
78
+ disabledKeys?: MaybeAccessor<Iterable<Key> | undefined>;
79
+ /** The whole tab list is unavailable, but still shows what is selected. */
80
+ isDisabled?: MaybeAccessor<boolean | undefined>;
81
+ onSelectionChange?: (key: Key) => void;
82
+ }
83
+
84
+ export interface TabListState<T> extends SingleSelectListState<T> {
85
+ isDisabled: Accessor<boolean>;
86
+ }
87
+
88
+ /**
89
+ * A tab list always has a selection.
90
+ *
91
+ * "Nothing selected" is not a state a tabbed interface can be in: the panel
92
+ * would be empty and no tab would be in the Tab order. So the first enabled
93
+ * tab is selected when nothing else is, including after the selected tab is
94
+ * removed.
95
+ */
96
+ export function tabListState<T>(options: TabListStateOptions<T>): TabListState<T> {
97
+ const firstEnabled = (collection: Collection<T>, disabled: Set<Key>): Key | null => {
98
+ let key = collection.getFirstKey();
99
+ const last = collection.getLastKey();
100
+ while (
101
+ key !== null &&
102
+ (disabled.has(key) || collection.getItem(key)?.props?.isDisabled === true) &&
103
+ key !== last
104
+ ) {
105
+ key = collection.getKeyAfter(key);
106
+ }
107
+ // Every tab disabled: the first reads better than the last.
108
+ if (
109
+ key !== null &&
110
+ (disabled.has(key) || collection.getItem(key)?.props?.isDisabled === true)
111
+ ) {
112
+ return collection.getFirstKey();
113
+ }
114
+ return key;
115
+ };
116
+
117
+ // Worked out BEFORE the state exists, not repaired afterwards: a default is
118
+ // not a choice, and putting it in through the setter would report a
119
+ // selection change the user never made.
120
+ const state = singleSelectListState<T>({
121
+ ...options,
122
+ defaultSelectedKey: (): Key | null => {
123
+ const declared = access(options.defaultSelectedKey);
124
+ if (declared !== undefined && declared !== null) return declared;
125
+ const collection = buildCollection(access(options.items) ?? [], options);
126
+ return firstEnabled(collection, new Set(access(options.disabledKeys) ?? []));
127
+ },
128
+ onSelectionChange: (key) => {
129
+ if (key !== null) options.onSelectionChange?.(key);
130
+ },
131
+ });
132
+
133
+ if (!isServer) {
134
+ // The selected tab going away IS a change, so this one reports.
135
+ createEffect(
136
+ () =>
137
+ [
138
+ state.collection(),
139
+ state.selectedKey(),
140
+ access(options.selectedKey),
141
+ state.disabledKeys(),
142
+ ] as const,
143
+ ([collection, selected, controlled, disabledKeys]) => {
144
+ if (controlled !== undefined && controlled !== null) return;
145
+ if (selected !== null && collection.getItem(selected) !== null) return;
146
+
147
+ const next = firstEnabled(collection, disabledKeys);
148
+ if (next !== null) state.setSelectedKey(next);
149
+ },
150
+ );
151
+
152
+ // The roving tabindex starts on the selected tab, so tabbing in reaches
153
+ // what is showing rather than the first tab in the list.
154
+ createEffect(
155
+ () => {
156
+ const manager = state.selectionManager();
157
+ return [manager, state.selectedKey(), manager.isFocused, manager.focusedKey] as const;
158
+ },
159
+ ([manager, selected, isFocused, focusedKey]) => {
160
+ if (selected === null || isFocused) return;
161
+ if (focusedKey === selected) return;
162
+ manager.setFocusedKey(selected);
163
+ },
164
+ );
165
+ }
166
+
167
+ return { ...state, isDisabled: () => access(options.isDisabled) === true };
168
+ }
169
+
170
+ // ---------------------------------------------------------------------------
171
+ // Navigation
172
+ // ---------------------------------------------------------------------------
173
+
174
+ export interface TabsKeyboardDelegateOptions {
175
+ collection: Accessor<Collection<unknown>>;
176
+ disabledKeys?: Accessor<Set<Key>>;
177
+ orientation?: MaybeAccessor<Orientation | undefined>;
178
+ direction?: MaybeAccessor<Direction | undefined>;
179
+ }
180
+
181
+ /**
182
+ * Navigation within a tab list: along the list, and wrapping.
183
+ *
184
+ * Left and right follow the WRITING direction whatever the orientation, so an
185
+ * RTL user's Left moves to the next tab; up and down follow the list and are
186
+ * never flipped. A vertical list answers nothing for left and right, and a
187
+ * horizontal one nothing for up and down, so the arrows that mean nothing here
188
+ * keep bubbling to whatever they do mean something to.
189
+ */
190
+ export class TabsKeyboardDelegate implements KeyboardDelegate {
191
+ #options: TabsKeyboardDelegateOptions;
192
+
193
+ constructor(options: TabsKeyboardDelegateOptions) {
194
+ this.#options = options;
195
+ }
196
+
197
+ get #collection(): Collection<unknown> {
198
+ return this.#options.collection();
199
+ }
200
+
201
+ get #horizontal(): boolean {
202
+ return (access(this.#options.orientation) ?? "horizontal") === "horizontal";
203
+ }
204
+
205
+ get #flipped(): boolean {
206
+ return (access(this.#options.direction) ?? "ltr") === "rtl";
207
+ }
208
+
209
+ #isDisabled(key: Key): boolean {
210
+ if (this.#options.disabledKeys?.().has(key) === true) return true;
211
+ return this.#collection.getItem(key)?.props?.isDisabled === true;
212
+ }
213
+
214
+ getKeyLeftOf(key: Key): Key | null {
215
+ return this.#flipped ? this.getKeyAfter(key) : this.getKeyBefore(key);
216
+ }
217
+
218
+ getKeyRightOf(key: Key): Key | null {
219
+ return this.#flipped ? this.getKeyBefore(key) : this.getKeyAfter(key);
220
+ }
221
+
222
+ getKeyAbove(key: Key): Key | null {
223
+ return this.#horizontal ? null : this.getKeyBefore(key);
224
+ }
225
+
226
+ getKeyBelow(key: Key): Key | null {
227
+ return this.#horizontal ? null : this.getKeyAfter(key);
228
+ }
229
+
230
+ getFirstKey(): Key | null {
231
+ const key = this.#collection.getFirstKey();
232
+ if (key !== null && this.#isDisabled(key)) return this.getKeyAfter(key);
233
+ return key;
234
+ }
235
+
236
+ getLastKey(): Key | null {
237
+ const key = this.#collection.getLastKey();
238
+ if (key !== null && this.#isDisabled(key)) return this.getKeyBefore(key);
239
+ return key;
240
+ }
241
+
242
+ getKeyAfter(from: Key): Key | null {
243
+ let key: Key | null = from;
244
+ do {
245
+ key = this.#collection.getKeyAfter(key);
246
+ if (key === null) key = this.#collection.getFirstKey();
247
+ } while (key !== null && this.#isDisabled(key) && key !== from);
248
+ return key;
249
+ }
250
+
251
+ getKeyBefore(from: Key): Key | null {
252
+ let key: Key | null = from;
253
+ do {
254
+ key = this.#collection.getKeyBefore(key);
255
+ if (key === null) key = this.#collection.getLastKey();
256
+ } while (key !== null && this.#isDisabled(key) && key !== from);
257
+ return key;
258
+ }
259
+ }
260
+
261
+ // ---------------------------------------------------------------------------
262
+ // Ids
263
+ // ---------------------------------------------------------------------------
264
+
265
+ /**
266
+ * The ids a tab and its panel point at each other with.
267
+ *
268
+ * Derived from the key rather than generated per element, because each end
269
+ * names the other before the other exists.
270
+ */
271
+ function partId(base: string, key: Key | null, part: "tab" | "tabpanel"): string {
272
+ return `${base}-${part}-${key === null ? "none" : String(key)}`;
273
+ }
274
+
275
+ // ---------------------------------------------------------------------------
276
+ // Hooks
277
+ // ---------------------------------------------------------------------------
278
+
279
+ export interface TabListOptions {
280
+ ref: ElementRef;
281
+ /** @default "horizontal" */
282
+ orientation?: MaybeAccessor<Orientation | undefined>;
283
+ /** Select as focus moves, or wait for Enter. @default "automatic" */
284
+ keyboardActivation?: MaybeAccessor<"automatic" | "manual" | undefined>;
285
+ "aria-label"?: MaybeAccessor<string | undefined>;
286
+ "aria-labelledby"?: MaybeAccessor<string | undefined>;
287
+ }
288
+
289
+ export interface TabListResult {
290
+ tabListProps: DOMProps;
291
+ /** The base every tab and panel id in this group is derived from. */
292
+ baseId: Accessor<string>;
293
+ }
294
+
295
+ export function tabList(options: TabListOptions, state: TabListState<unknown>): TabListResult {
296
+ const locale = useLocale();
297
+ const baseId = id();
298
+
299
+ const delegate = new TabsKeyboardDelegate({
300
+ collection: state.collection,
301
+ disabledKeys: state.disabledKeys,
302
+ orientation: options.orientation,
303
+ direction: () => locale().direction,
304
+ });
305
+
306
+ const { collectionProps } = selectableCollection({
307
+ ref: options.ref,
308
+ selectionManager: state.selectionManager,
309
+ keyboardDelegate: delegate,
310
+ selectOnFocus: () => (access(options.keyboardActivation) ?? "automatic") === "automatic",
311
+ disallowEmptySelection: true,
312
+ scrollRef: options.ref,
313
+ linkBehavior: "selection",
314
+ });
315
+
316
+ return {
317
+ baseId,
318
+ tabListProps: mergeProps(filterDOMProps(options, { labelable: true }), collectionProps, {
319
+ role: "tablist",
320
+ "aria-orientation": () => access(options.orientation) ?? "horizontal",
321
+ // The tabs carry the roving tabindex; the list itself is never the stop.
322
+ tabIndex: () => undefined,
323
+ }),
324
+ };
325
+ }
326
+
327
+ export interface TabOptions {
328
+ key: Key;
329
+ ref: ElementRef;
330
+ baseId: MaybeAccessor<string>;
331
+ isDisabled?: MaybeAccessor<boolean | undefined>;
332
+ /** @default false, unless the tab is a link */
333
+ shouldSelectOnPressUp?: MaybeAccessor<boolean | undefined>;
334
+ "aria-label"?: MaybeAccessor<string | undefined>;
335
+ }
336
+
337
+ export interface TabResult {
338
+ tabProps: DOMProps;
339
+ isSelected: Accessor<boolean>;
340
+ isDisabled: Accessor<boolean>;
341
+ isPressed: Accessor<boolean>;
342
+ isFocused: Accessor<boolean>;
343
+ }
344
+
345
+ export function tab(options: TabOptions, state: TabListState<unknown>): TabResult {
346
+ const node = (): Node<unknown> | null => state.collection().getItem(options.key);
347
+
348
+ const isDisabled = (): boolean =>
349
+ access(options.isDisabled) === true ||
350
+ state.isDisabled() ||
351
+ state.selectionManager().isDisabled(options.key);
352
+
353
+ const item = selectableItem({
354
+ key: options.key,
355
+ ref: options.ref,
356
+ id: () => partId(access(options.baseId), options.key, "tab"),
357
+ selectionManager: state.selectionManager,
358
+ isDisabled,
359
+ // A tab that is a link navigates, and a browser navigates on release: a
360
+ // press that began here and ended elsewhere is not a navigation.
361
+ shouldSelectOnPressUp: () =>
362
+ access(options.shouldSelectOnPressUp) ?? node()?.props?.href !== undefined,
363
+ linkBehavior: "selection",
364
+ });
365
+
366
+ const isSelected = (): boolean => state.selectedKey() === options.key;
367
+
368
+ return {
369
+ isSelected,
370
+ isDisabled,
371
+ isPressed: item.isPressed,
372
+ isFocused: item.isFocused,
373
+ tabProps: mergeProps(item.itemProps, {
374
+ role: "tab",
375
+ "aria-selected": isSelected,
376
+ "aria-disabled": () => isDisabled() || undefined,
377
+ // Only the SELECTED tab controls a panel: the others control nothing
378
+ // that is on the page, and pointing at an absent element is worse than
379
+ // pointing at nothing.
380
+ "aria-controls": () =>
381
+ isSelected() ? partId(access(options.baseId), options.key, "tabpanel") : undefined,
382
+ "aria-label": () => access(options["aria-label"]) ?? node()?.["aria-label"],
383
+ // `disabled` would take the tab out of the Tab order and out of the
384
+ // arrow-key walk, and a disabled tab still has to be reachable to be
385
+ // announced as disabled.
386
+ disabled: () => undefined,
387
+ }),
388
+ };
389
+ }
390
+
391
+ export interface TabPanelOptions {
392
+ ref: ElementRef;
393
+ baseId: MaybeAccessor<string>;
394
+ /** Which tab's panel this is. @default the selected one */
395
+ key?: MaybeAccessor<Key | null | undefined>;
396
+ "aria-label"?: MaybeAccessor<string | undefined>;
397
+ "aria-describedby"?: MaybeAccessor<string | undefined>;
398
+ }
399
+
400
+ export interface TabPanelResult {
401
+ tabPanelProps: DOMProps;
402
+ }
403
+
404
+ export function tabPanel(options: TabPanelOptions, state: TabListState<unknown>): TabPanelResult {
405
+ const key = (): Key | null => access(options.key) ?? state.selectedKey();
406
+ const focusable = hasTabbableChild(options.ref, key);
407
+
408
+ return {
409
+ tabPanelProps: mergeProps(filterDOMProps(options, { labelable: true }), {
410
+ role: "tabpanel",
411
+ id: () => partId(access(options.baseId), key(), "tabpanel"),
412
+ "aria-labelledby": () =>
413
+ access(options["aria-label"]) === undefined
414
+ ? partId(access(options.baseId), key(), "tab")
415
+ : undefined,
416
+ "aria-describedby": () => access(options["aria-describedby"]),
417
+ // A panel with something focusable inside is not a stop of its own: Tab
418
+ // from the tab list should reach the first field, not the container
419
+ // around it. A panel of prose has nothing else to receive focus, and a
420
+ // keyboard user needs somewhere to stand to scroll it.
421
+ tabIndex: () => (focusable() ? undefined : 0),
422
+ }),
423
+ };
424
+ }
425
+
426
+ /**
427
+ * Whether the element holds anything the browser would stop at.
428
+ *
429
+ * Answered after the children exist and again whenever they are replaced,
430
+ * because the answer is about the content and the content is what changes.
431
+ */
432
+ function hasTabbableChild(ref: ElementRef, key: () => Key | null): Accessor<boolean> {
433
+ const [found, setFound] = createSignal(false);
434
+ if (isServer) return found;
435
+
436
+ createEffect(
437
+ // Read, so swapping the panel's contents re-asks.
438
+ () => [key(), access(ref) as Element | null] as const,
439
+ ([, element]) => {
440
+ if (element === null) {
441
+ setFound(false);
442
+ return;
443
+ }
444
+ setFound(focusableWalker(element, { tabbable: true }).nextNode() !== null);
445
+ },
446
+ );
447
+
448
+ return found;
449
+ }
450
+
451
+ // ---------------------------------------------------------------------------
452
+ // Components
453
+ // ---------------------------------------------------------------------------
454
+
455
+ interface TabsContextValue {
456
+ state: TabListState<unknown>;
457
+ baseId: Accessor<string>;
458
+ orientation: Accessor<Orientation>;
459
+ keyboardActivation: Accessor<"automatic" | "manual">;
460
+ }
461
+
462
+ const TabsContext = createContext<TabsContextValue | null>(null);
463
+ const TabNodeContext = createContext<Node<unknown> | null>(null);
464
+
465
+ export function useTabs(): TabsContextValue {
466
+ const value = getContext(TabsContext);
467
+ if (value === null || value === undefined) {
468
+ throw new Error("This must be rendered inside a Tabs.");
469
+ }
470
+ return value;
471
+ }
472
+
473
+ /** The collection node the enclosing tab is for. */
474
+ export function useTabNode(): Node<unknown> {
475
+ const node = getContext(TabNodeContext);
476
+ if (node === null || node === undefined) {
477
+ throw new Error("A Tab must be rendered inside a TabList's item callback.");
478
+ }
479
+ return node;
480
+ }
481
+
482
+ export interface TabsComponentProps<T> extends StyleProps, ItemAccessors<T> {
483
+ /** The tabs, in order. */
484
+ items: Iterable<T>;
485
+ children?: Child;
486
+ selectedKey?: Key;
487
+ defaultSelectedKey?: Key;
488
+ disabledKeys?: Iterable<Key>;
489
+ isDisabled?: boolean;
490
+ /** @default "horizontal" */
491
+ orientation?: Orientation;
492
+ /** @default "automatic" */
493
+ keyboardActivation?: "automatic" | "manual";
494
+ onSelectionChange?: (key: Key) => void;
495
+ }
496
+
497
+ /**
498
+ * ```tsx
499
+ * <Tabs items={sections()} onSelectionChange={(key) => open.set(key)}>
500
+ * <TabList aria-label="Sections">{(s) => <Tab>{s.name}</Tab>}</TabList>
501
+ * <TabPanel>{(s) => <p>{s.body}</p>}</TabPanel>
502
+ * </Tabs>
503
+ * ```
504
+ *
505
+ * One `<TabPanel>`, not one per tab: only the selected panel is ever on the
506
+ * page, so the element is the same element throughout and its id and its
507
+ * labelling follow the selection.
508
+ */
509
+ export function Tabs<T>(props: Incoming<TabsComponentProps<T>>) {
510
+ const options = fromProps(props as unknown as Incoming<Record<string, unknown>>);
511
+ const state = tabListState<T>({
512
+ ...(options as TabListStateOptions<T>),
513
+ onSelectionChange: (key) => props.onSelectionChange?.()?.(key),
514
+ });
515
+
516
+ declareDirection(props.dir);
517
+
518
+ const baseId = id();
519
+ const owner = getOwner();
520
+ if (owner !== null) {
521
+ const value: TabsContextValue = {
522
+ state: state,
523
+ baseId,
524
+ orientation: () => props.orientation?.() ?? "horizontal",
525
+ keyboardActivation: () => props.keyboardActivation?.() ?? "automatic",
526
+ };
527
+ install(owner, TabsContext, () => value);
528
+ }
529
+
530
+ const elementProps = mergeProps(
531
+ filterDOMProps(fromProps(props), { global: true }),
532
+ styleProps(props),
533
+ {
534
+ "data-orientation": () => props.orientation?.() ?? "horizontal",
535
+ "data-testid": () => props["data-testid"]?.(),
536
+ },
537
+ );
538
+
539
+ return <div {...elementProps}>{props.children}</div>;
540
+ }
541
+
542
+ export interface TabListComponentProps<T> extends StyleProps {
543
+ /** How one tab renders. Return a `<Tab>`. */
544
+ children: (item: T) => Child;
545
+ "aria-label"?: string;
546
+ "aria-labelledby"?: string;
547
+ ref?: RefTarget<HTMLDivElement>;
548
+ }
549
+
550
+ export function TabList<T>(props: Incoming<TabListComponentProps<T>>) {
551
+ const domRef = makeRef<HTMLDivElement>();
552
+ const tabs = useTabs();
553
+
554
+ const { tabListProps } = tabList(
555
+ {
556
+ ref: domRef,
557
+ orientation: tabs.orientation,
558
+ keyboardActivation: tabs.keyboardActivation,
559
+ "aria-label": () => props["aria-label"]?.(),
560
+ "aria-labelledby": () => props["aria-labelledby"]?.(),
561
+ },
562
+ tabs.state,
563
+ );
564
+
565
+ const elementProps = mergeProps(
566
+ tabListProps,
567
+ filterDOMProps(fromProps(props), { global: true }),
568
+ styleProps(props),
569
+ {
570
+ "data-orientation": tabs.orientation,
571
+ "data-testid": () => props["data-testid"]?.(),
572
+ },
573
+ );
574
+
575
+ const render = props.children;
576
+
577
+ return (
578
+ <div {...elementProps} ref={mergeRefs(domRef.set, props.ref?.())}>
579
+ <For each={() => [...tabs.state.collection()]}>
580
+ {(node: Node<unknown>) => {
581
+ const rowOwner = getOwner();
582
+ if (rowOwner !== null) install(rowOwner, TabNodeContext, () => node);
583
+ return render(node.value as T);
584
+ }}
585
+ </For>
586
+ </div>
587
+ );
588
+ }
589
+
590
+ export interface TabComponentProps extends StyleProps {
591
+ children?: Child;
592
+ "aria-label"?: string;
593
+ ref?: RefTarget<HTMLButtonElement>;
594
+ }
595
+
596
+ /**
597
+ * One tab. Its key and disabled state come from the collection node the
598
+ * enclosing {@link TabList} is rendering.
599
+ */
600
+ export function Tab(props: Incoming<TabComponentProps>) {
601
+ const domRef = makeRef<HTMLButtonElement>();
602
+ const tabs = useTabs();
603
+ const node = useTabNode();
604
+
605
+ const { tabProps, isSelected, isDisabled, isPressed, isFocused } = tab(
606
+ {
607
+ key: node.key,
608
+ ref: domRef,
609
+ baseId: tabs.baseId,
610
+ "aria-label": () => props["aria-label"]?.(),
611
+ isDisabled: () => node.props?.isDisabled === true,
612
+ },
613
+ tabs.state,
614
+ );
615
+
616
+ const { hoverProps, isHovered } = hover({ isDisabled });
617
+ const { focusProps, isFocusVisible } = focusRing();
618
+
619
+ const elementProps = mergeProps(
620
+ tabProps,
621
+ hoverProps,
622
+ focusProps,
623
+ filterDOMProps(fromProps(props), { global: true }),
624
+ styleProps(props),
625
+ {
626
+ type: "button",
627
+ "data-selected": isSelected,
628
+ "data-focused": isFocused,
629
+ "data-focus-visible": isFocusVisible,
630
+ "data-pressed": isPressed,
631
+ "data-hovered": isHovered,
632
+ "data-disabled": isDisabled,
633
+ "data-state": () => (isSelected() ? "active" : "inactive"),
634
+ "data-orientation": tabs.orientation,
635
+ "data-testid": () => props["data-testid"]?.(),
636
+ },
637
+ );
638
+
639
+ return (
640
+ <button {...elementProps} ref={mergeRefs(domRef.set, props.ref?.())}>
641
+ {props.children}
642
+ </button>
643
+ );
644
+ }
645
+
646
+ export interface TabPanelComponentProps<T> extends StyleProps {
647
+ /** What the selected tab shows. Given the selected item. */
648
+ children: ((item: T) => Child) | Child;
649
+ "aria-label"?: string;
650
+ ref?: RefTarget<HTMLDivElement>;
651
+ }
652
+
653
+ export function TabPanel<T>(props: Incoming<TabPanelComponentProps<T>>) {
654
+ const domRef = makeRef<HTMLDivElement>();
655
+ const tabs = useTabs();
656
+
657
+ const { tabPanelProps } = tabPanel(
658
+ {
659
+ ref: domRef,
660
+ baseId: tabs.baseId,
661
+ "aria-label": () => props["aria-label"]?.(),
662
+ },
663
+ tabs.state,
664
+ );
665
+
666
+ const elementProps = mergeProps(
667
+ tabPanelProps,
668
+ filterDOMProps(fromProps(props), { global: true }),
669
+ styleProps(props),
670
+ {
671
+ "data-state": "active",
672
+ "data-orientation": tabs.orientation,
673
+ "data-testid": () => props["data-testid"]?.(),
674
+ },
675
+ );
676
+
677
+ // The children are a Block, and a Block that closes over the selected item
678
+ // has to be REBUILT when the selection changes rather than re-read. `Show`
679
+ // keyed on the selected key is what rebuilds it, and only then: the panel
680
+ // is one element throughout, and only its contents are swapped.
681
+ const renderPanel = props.children as unknown as (item: T | undefined) => Child;
682
+
683
+ return (
684
+ <div {...elementProps} ref={mergeRefs(domRef.set, props.ref?.())}>
685
+ <Show when={tabs.state.selectedKey()} keyed>
686
+ {() => {
687
+ // The keyed `Show` supplies the selected KEY, and the panel wants the
688
+ // ITEM. Reading it untracked keeps the rebuild governed by the key
689
+ // alone, so an item mutated in place does not discard the panel.
690
+ const selected = untrack(() => tabs.state.selectedItem());
691
+ return renderPanel(selected === null ? undefined : (selected.value as T));
692
+ }}
693
+ </Show>
694
+ </div>
695
+ );
696
+ }
697
+
698
+ // ---------------------------------------------------------------------------
699
+ // Tabs that name themselves
700
+ // ---------------------------------------------------------------------------
701
+
702
+ interface ValueTabsContextValue {
703
+ value: Accessor<string | null>;
704
+ select: (value: string) => void;
705
+ /** Called by each enabled tab as it is built; the first one stands in for a missing choice. */
706
+ adopt: (value: string) => void;
707
+ baseId: Accessor<string>;
708
+ orientation: Accessor<Orientation>;
709
+ activationMode: Accessor<"automatic" | "manual">;
710
+ isDisabled: Accessor<boolean>;
711
+ }
712
+
713
+ const ValueTabsContext = createContext<ValueTabsContextValue | null>(null);
714
+
715
+ /** The enclosing {@link ValueTabs}, or `null` outside one. */
716
+ export function useValueTabs(): ValueTabsContextValue | null {
717
+ return getContext(ValueTabsContext) ?? null;
718
+ }
719
+
720
+ function requireValueTabs(): ValueTabsContextValue {
721
+ const value = useValueTabs();
722
+ if (value === null) throw new Error("This must be rendered inside a ValueTabs.");
723
+ return value;
724
+ }
725
+
726
+ /**
727
+ * `dir` on the root is a declaration as well as an attribute.
728
+ *
729
+ * The attribute alone lays the text out and leaves the arrow keys following
730
+ * whatever direction the page has, so a mirrored tab list would walk backwards.
731
+ * `"auto"` is the browser's to resolve and says nothing here.
732
+ */
733
+ function declareDirection(dir: Accessor<"ltr" | "rtl" | "auto" | undefined> | undefined): void {
734
+ if (dir === undefined) return;
735
+ const inherited = useDirection();
736
+ provideDirection((): ReadingDirection => {
737
+ const declared = dir();
738
+ return declared === "ltr" || declared === "rtl" ? declared : inherited();
739
+ });
740
+ }
741
+
742
+ /** An id is one token, and a value is whatever the caller wrote. */
743
+ function valuePartId(base: string, value: string, part: "tab" | "tabpanel"): string {
744
+ return partId(base, value.replace(/\s+/g, "_"), part);
745
+ }
746
+
747
+ export interface ValueTabsComponentProps extends StyleProps {
748
+ children?: Child;
749
+ value?: string;
750
+ defaultValue?: string;
751
+ onValueChange?: (value: string) => void;
752
+ /** @default "horizontal" */
753
+ orientation?: Orientation;
754
+ /** Select as focus moves, or wait for Enter. @default "automatic" */
755
+ activationMode?: "automatic" | "manual";
756
+ isDisabled?: boolean;
757
+ }
758
+
759
+ /**
760
+ * Tabs written out as markup, each trigger and panel naming its `value`.
761
+ *
762
+ * ```tsx
763
+ * <ValueTabs defaultValue="account">
764
+ * <ValueTabList aria-label="Settings">
765
+ * <ValueTab value="account">Account</ValueTab>
766
+ * <ValueTab value="password">Password</ValueTab>
767
+ * </ValueTabList>
768
+ * <ValueTabPanel value="account">…</ValueTabPanel>
769
+ * <ValueTabPanel value="password">…</ValueTabPanel>
770
+ * </ValueTabs>
771
+ * ```
772
+ *
773
+ * {@link Tabs} takes its tabs as data and is the one to reach for when they
774
+ * are data. This is for a fixed handful known when the markup is written,
775
+ * where an `items` array would only restate it.
776
+ *
777
+ * - **The order is the document's.** The arrow keys walk the tabs as they sit
778
+ * in the list at the moment of the keypress, so a tab that is rendered
779
+ * conditionally takes its place without registering anywhere.
780
+ * - **There is always a selection.** With no `value` and no `defaultValue` the
781
+ * first enabled tab stands in, and `onValueChange` is not called for it:
782
+ * a default is not a choice.
783
+ * - **A disabled tab stays focusable by pointer and is skipped by the arrows**,
784
+ * as in {@link Tabs}, so it can still be announced as disabled.
785
+ */
786
+ export function ValueTabs(props: Incoming<ValueTabsComponentProps>) {
787
+ const [chosen, setChosen] = controllable<string | null>(
788
+ () => props.value?.(),
789
+ () => props.defaultValue?.() ?? null,
790
+ (next) => {
791
+ if (next !== null) props.onValueChange?.()?.(next);
792
+ },
793
+ );
794
+
795
+ // `ownedWrite`: a tab adopts while it is being built. The value is kept
796
+ // beside the signal because writes are staged, and the second tab would
797
+ // otherwise still read "nothing adopted" and take the place of the first.
798
+ let first: string | null = null;
799
+ const [adopted, setAdopted] = createSignal<string | null>(null, { ownedWrite: true });
800
+
801
+ const value = (): string | null => chosen() ?? adopted();
802
+ const orientation = (): Orientation => props.orientation?.() ?? "horizontal";
803
+
804
+ declareDirection(props.dir);
805
+
806
+ const owner = getOwner();
807
+ if (owner !== null) {
808
+ const context: ValueTabsContextValue = {
809
+ value,
810
+ select: (next) => {
811
+ if (untrack(value) !== next) setChosen(next);
812
+ },
813
+ adopt: (next) => {
814
+ if (first !== null) return;
815
+ first = next;
816
+ setAdopted(next);
817
+ },
818
+ baseId: id(),
819
+ orientation,
820
+ activationMode: () => props.activationMode?.() ?? "automatic",
821
+ isDisabled: () => props.isDisabled?.() === true,
822
+ };
823
+ install(owner, ValueTabsContext, () => context);
824
+ }
825
+
826
+ const elementProps = mergeProps(
827
+ filterDOMProps(fromProps(props), { global: true }),
828
+ styleProps(props),
829
+ {
830
+ "data-orientation": orientation,
831
+ "data-testid": () => props["data-testid"]?.(),
832
+ },
833
+ );
834
+
835
+ return <div {...elementProps}>{props.children}</div>;
836
+ }
837
+
838
+ export interface ValueTabListComponentProps extends StyleProps {
839
+ children?: Child;
840
+ /** Whether the arrows wrap round the ends. @default true */
841
+ loop?: boolean;
842
+ "aria-label"?: string;
843
+ "aria-labelledby"?: string;
844
+ ref?: RefTarget<HTMLDivElement>;
845
+ }
846
+
847
+ export function ValueTabList(props: Incoming<ValueTabListComponentProps>) {
848
+ const tabs = requireValueTabs();
849
+ const direction = useDirection();
850
+
851
+ const onKeyDown = (event: KeyboardEvent): void => {
852
+ if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return;
853
+ const list = event.currentTarget as HTMLElement;
854
+ const from = event.target as HTMLElement;
855
+ // A tablist nested in a panel of this one is its own list.
856
+ if (from.getAttribute("role") !== "tab" || from.closest('[role="tablist"]') !== list) return;
857
+
858
+ const horizontal = tabs.orientation() === "horizontal";
859
+ const forward = direction() === "rtl" ? "ArrowLeft" : "ArrowRight";
860
+ const backward = direction() === "rtl" ? "ArrowRight" : "ArrowLeft";
861
+
862
+ const stops = [...list.querySelectorAll<HTMLElement>('[role="tab"]')].filter(
863
+ (stop) =>
864
+ stop.closest('[role="tablist"]') === list &&
865
+ (stop === from || stop.getAttribute("aria-disabled") !== "true"),
866
+ );
867
+ const at = stops.indexOf(from);
868
+ const enabled = stops.filter((stop) => stop.getAttribute("aria-disabled") !== "true");
869
+ if (enabled.length === 0) return;
870
+
871
+ const step = (by: 1 | -1): HTMLElement | undefined => {
872
+ const next = at + by;
873
+ if (next >= 0 && next < stops.length) return stops[next];
874
+ if (props.loop?.() === false) return undefined;
875
+ return by === 1 ? stops[0] : stops[stops.length - 1];
876
+ };
877
+
878
+ let target: HTMLElement | undefined;
879
+ if (event.key === "Home") target = enabled[0];
880
+ else if (event.key === "End") target = enabled[enabled.length - 1];
881
+ else if (horizontal && event.key === forward) target = step(1);
882
+ else if (horizontal && event.key === backward) target = step(-1);
883
+ else if (!horizontal && event.key === "ArrowDown") target = step(1);
884
+ else if (!horizontal && event.key === "ArrowUp") target = step(-1);
885
+ else return;
886
+
887
+ event.preventDefault();
888
+ // A disabled tab the walk started from is in `stops`, and landing back on
889
+ // it after a full loop is not a move.
890
+ if (target === undefined || target === from) return;
891
+ target.focus();
892
+ };
893
+
894
+ const elementProps = mergeProps(
895
+ filterDOMProps(fromProps(props), { global: true, labelable: true }),
896
+ styleProps(props),
897
+ {
898
+ role: "tablist",
899
+ "aria-orientation": tabs.orientation,
900
+ "data-orientation": tabs.orientation,
901
+ "data-testid": () => props["data-testid"]?.(),
902
+ onKeyDown,
903
+ },
904
+ );
905
+
906
+ return (
907
+ <div {...elementProps} ref={mergeRefs(props.ref?.())}>
908
+ {props.children}
909
+ </div>
910
+ );
911
+ }
912
+
913
+ export interface ValueTabComponentProps extends StyleProps {
914
+ value: string;
915
+ children?: Child;
916
+ isDisabled?: boolean;
917
+ "aria-label"?: string;
918
+ ref?: RefTarget<HTMLButtonElement>;
919
+ }
920
+
921
+ export function ValueTab(props: Incoming<ValueTabComponentProps>) {
922
+ const tabs = requireValueTabs();
923
+
924
+ const isSelected = (): boolean => tabs.value() === props.value();
925
+ const isDisabled = (): boolean => tabs.isDisabled() || props.isDisabled?.() === true;
926
+
927
+ if (!untrack(isDisabled)) tabs.adopt(untrack(() => props.value()));
928
+
929
+ const { hoverProps, isHovered } = hover({ isDisabled });
930
+ const { focusProps, isFocused, isFocusVisible } = focusRing();
931
+
932
+ const select = (): void => {
933
+ if (!isDisabled()) tabs.select(props.value());
934
+ };
935
+
936
+ const elementProps = mergeProps(
937
+ hoverProps,
938
+ focusProps,
939
+ filterDOMProps(fromProps(props), { global: true, labelable: true }),
940
+ styleProps(props),
941
+ {
942
+ type: "button",
943
+ role: "tab",
944
+ id: () => valuePartId(tabs.baseId(), props.value(), "tab"),
945
+ "aria-selected": isSelected,
946
+ "aria-disabled": () => isDisabled() || undefined,
947
+ // Only the SELECTED tab controls a panel: the others control nothing
948
+ // that is on the page.
949
+ "aria-controls": () =>
950
+ isSelected() ? valuePartId(tabs.baseId(), props.value(), "tabpanel") : undefined,
951
+ tabIndex: () => (isSelected() ? 0 : -1),
952
+ "data-selected": isSelected,
953
+ "data-focused": isFocused,
954
+ "data-focus-visible": isFocusVisible,
955
+ "data-hovered": isHovered,
956
+ "data-disabled": isDisabled,
957
+ "data-state": () => (isSelected() ? "active" : "inactive"),
958
+ "data-orientation": tabs.orientation,
959
+ "data-testid": () => props["data-testid"]?.(),
960
+ onClick: select,
961
+ onKeyDown: (event: KeyboardEvent) => {
962
+ if (event.key === "Enter" || event.key === " ") select();
963
+ },
964
+ onFocus: () => {
965
+ if (tabs.activationMode() === "automatic") select();
966
+ },
967
+ },
968
+ );
969
+
970
+ return (
971
+ <button {...elementProps} ref={mergeRefs(props.ref?.())}>
972
+ {props.children}
973
+ </button>
974
+ );
975
+ }
976
+
977
+ export interface ValueTabPanelComponentProps extends StyleProps {
978
+ value: string;
979
+ children?: Child;
980
+ /** Keep the panel in the document while another is showing, hidden. */
981
+ forceMount?: boolean;
982
+ "aria-label"?: string;
983
+ ref?: RefTarget<HTMLDivElement>;
984
+ }
985
+
986
+ export function ValueTabPanel(props: Incoming<ValueTabPanelComponentProps>) {
987
+ const domRef = makeRef<HTMLDivElement>();
988
+ const tabs = requireValueTabs();
989
+
990
+ const isSelected = (): boolean => tabs.value() === props.value();
991
+ const focusable = hasTabbableChild(domRef, () => (isSelected() ? props.value() : null));
992
+
993
+ const elementProps = mergeProps(
994
+ filterDOMProps(fromProps(props), { global: true, labelable: true }),
995
+ styleProps(props),
996
+ {
997
+ role: "tabpanel",
998
+ id: () => valuePartId(tabs.baseId(), props.value(), "tabpanel"),
999
+ "aria-labelledby": () =>
1000
+ props["aria-label"]?.() === undefined
1001
+ ? valuePartId(tabs.baseId(), props.value(), "tab")
1002
+ : undefined,
1003
+ tabIndex: () => (focusable() ? undefined : 0),
1004
+ hidden: () => !isSelected(),
1005
+ "data-state": () => (isSelected() ? "active" : "inactive"),
1006
+ "data-orientation": tabs.orientation,
1007
+ "data-testid": () => props["data-testid"]?.(),
1008
+ },
1009
+ );
1010
+
1011
+ return (
1012
+ <Show when={isSelected() || props.forceMount?.() === true}>
1013
+ <div {...elementProps} ref={mergeRefs(domRef.set, props.ref?.())}>
1014
+ {props.children}
1015
+ </div>
1016
+ </Show>
1017
+ );
1018
+ }