@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/dom.ts ADDED
@@ -0,0 +1,706 @@
1
+ /**
2
+ * The DOM questions every accessible widget has to ask, answered once.
3
+ *
4
+ * Three of them are not what the platform API says they are:
5
+ *
6
+ * - `node.contains(other)` stops at a shadow boundary, so a component whose
7
+ * trigger is slotted into a custom element decides the click landed outside
8
+ * itself and closes.
9
+ * - `document.activeElement` reports the shadow HOST, not the element inside
10
+ * it that actually has focus.
11
+ * - `event.target` is retargeted to the host for the same reason.
12
+ *
13
+ * The shadow-safe answers cost a walk per call, and the overwhelming majority
14
+ * of applications have no shadow roots at all, so they are behind
15
+ * {@link enableShadowDOM} rather than on by default. Adapted from Tabster's
16
+ * `Shadowdomize/DOMFunctions`, which is where react-aria took them from.
17
+ */
18
+
19
+ let shadowDOMEnabled = false;
20
+
21
+ /**
22
+ * Make every DOM question in this package shadow-safe.
23
+ *
24
+ * Call it once, before rendering, if any part of the application renders into
25
+ * a shadow root. It cannot be inferred: an open shadow root that exists is not
26
+ * evidence that a component's own subtree crosses one, and paying the walk
27
+ * everywhere to find out is the cost this flag avoids.
28
+ */
29
+ export function enableShadowDOM(): void {
30
+ shadowDOMEnabled = true;
31
+ }
32
+
33
+ /** Whether {@link enableShadowDOM} has been called. */
34
+ export function isShadowDOMEnabled(): boolean {
35
+ return shadowDOMEnabled;
36
+ }
37
+
38
+ /** A value with a numeric `nodeType`. */
39
+ export function isNode(value: unknown): value is Node {
40
+ return (
41
+ value !== null &&
42
+ typeof value === "object" &&
43
+ "nodeType" in value &&
44
+ typeof (value as Node).nodeType === "number"
45
+ );
46
+ }
47
+
48
+ /** A value with `nodeType === 1`. */
49
+ export function isElement(value: unknown): value is Element {
50
+ return isNode(value) && value.nodeType === 1;
51
+ }
52
+
53
+ /**
54
+ * An element carrying a `style` map: an `HTMLElement` or an `SVGElement`.
55
+ *
56
+ * Duck-typed, like {@link isNode}, and for one more reason than that one has.
57
+ * `instanceof HTMLElement` is wrong across realms — an element from an
58
+ * `<iframe>` fails it — and it is wrong where there is no realm at all: on a
59
+ * server the global does not exist, so the test THROWS rather than answering
60
+ * false. A cleanup that ran while a server-rendered tree was disposed took the
61
+ * whole render with it, reported as `ReferenceError: HTMLElement is not
62
+ * defined` from a line asking whether it had an element.
63
+ */
64
+ export function isStyledElement(value: unknown): value is HTMLElement | SVGElement {
65
+ return isElement(value) && "style" in value;
66
+ }
67
+
68
+ function isWindow(value: unknown): value is Window & typeof globalThis {
69
+ return (
70
+ typeof value === "object" &&
71
+ value !== null &&
72
+ "window" in value &&
73
+ (value as Window).window === value
74
+ );
75
+ }
76
+
77
+ export function isDocument(value: unknown): value is Document {
78
+ return isNode(value) && value.nodeType === 9;
79
+ }
80
+
81
+ export function isShadowRoot(value: unknown): value is ShadowRoot {
82
+ return isNode(value) && value.nodeType === 11 && "host" in value;
83
+ }
84
+
85
+ /**
86
+ * The document `target` lives in.
87
+ *
88
+ * Not `document`: a portal into an `<iframe>` or a popped-out window has its
89
+ * own, and a listener bound to the wrong one never fires.
90
+ */
91
+ export function ownerDocument(target?: EventTarget | null): Document {
92
+ if (isWindow(target)) return target.document;
93
+ if (isDocument(target)) return target;
94
+ const owned = (target as Node | null | undefined)?.ownerDocument;
95
+ const fallback = typeof document !== "undefined" ? document : (undefined as never);
96
+ // A node cloned from a `<template>` belongs to the INERT template document
97
+ // until it is inserted, and that document has no browsing context: its
98
+ // `activeElement` is null, its `defaultView` is null, and a listener added to
99
+ // it never fires. barq builds every element by cloning a template, so any
100
+ // question asked of a node before it is in the page was being asked of the
101
+ // wrong document — which is why an overlay's focus scope recorded `null` as
102
+ // the element to restore focus to, and gave the user back nothing when it
103
+ // closed. `defaultView` is the test the platform itself uses for "has a
104
+ // browsing context".
105
+ if (owned === null || owned === undefined) return fallback;
106
+ return owned.defaultView === null ? fallback : owned;
107
+ }
108
+
109
+ /** The window `target` lives in. See {@link ownerDocument}. */
110
+ export function ownerWindow(target?: EventTarget | null): Window & typeof globalThis {
111
+ const doc = ownerDocument(target);
112
+ return doc?.defaultView ?? (typeof window !== "undefined" ? window : (undefined as never));
113
+ }
114
+
115
+ /**
116
+ * `node.contains(other)`, crossing shadow boundaries and slots when
117
+ * {@link enableShadowDOM} is on.
118
+ */
119
+ export function contains(
120
+ node: Node | Element | null | undefined,
121
+ other: Node | Element | null | undefined,
122
+ ): boolean {
123
+ if (node === null || node === undefined || other === null || other === undefined) return false;
124
+ if (!shadowDOMEnabled) return node.contains(other);
125
+
126
+ let current: Node | null | undefined = other;
127
+ while (current !== null && current !== undefined) {
128
+ if (current === node) return true;
129
+
130
+ const slot: HTMLSlotElement | null = (current as HTMLSlotElement).assignedSlot;
131
+ if (typeof (current as HTMLSlotElement).assignedElements !== "function" && slot?.parentNode) {
132
+ current = slot.parentNode;
133
+ } else if (isShadowRoot(current)) {
134
+ current = current.host;
135
+ } else {
136
+ current = current.parentNode;
137
+ }
138
+ }
139
+
140
+ return false;
141
+ }
142
+
143
+ /**
144
+ * `document.activeElement`, descending into shadow roots when
145
+ * {@link enableShadowDOM} is on.
146
+ */
147
+ export function activeElement(doc?: Document): Element | null {
148
+ const from = doc ?? (typeof document !== "undefined" ? document : undefined);
149
+ if (from === undefined) return null;
150
+ if (!shadowDOMEnabled) return from.activeElement;
151
+
152
+ let active: Element | null = from.activeElement;
153
+ while (active !== null && "shadowRoot" in active && active.shadowRoot?.activeElement) {
154
+ active = active.shadowRoot.activeElement;
155
+ }
156
+ return active;
157
+ }
158
+
159
+ /**
160
+ * `event.target`, un-retargeted through the shadow boundary when
161
+ * {@link enableShadowDOM} is on.
162
+ */
163
+ export function eventTarget(event: Event): EventTarget | null {
164
+ if (shadowDOMEnabled && event.target instanceof Element && event.target.shadowRoot) {
165
+ if (typeof event.composedPath === "function") return event.composedPath()[0] ?? null;
166
+ }
167
+ return event.target;
168
+ }
169
+
170
+ /** {@link eventTarget}, narrowed to an Element, which is what every caller wants. */
171
+ export function targetElement(event: Event): Element | null {
172
+ const target = eventTarget(event);
173
+ return target instanceof Element ? target : null;
174
+ }
175
+
176
+ /**
177
+ * Every target a listener must be bound to in order to observe an event
178
+ * globally, given where it starts.
179
+ *
180
+ * An event dispatched inside a shadow root does not reach a listener on the
181
+ * document until it crosses the boundary, and it is retargeted when it does.
182
+ * A capturing listener on each intervening root is what makes an outside-click
183
+ * check see the real element.
184
+ */
185
+ export function propagationTargets(
186
+ from: Element | null | undefined,
187
+ to?: Document | Window | Element | null,
188
+ ): EventTarget[] {
189
+ if (to === null) return [];
190
+ const root = to ?? ownerWindow(from);
191
+ const targets: EventTarget[] = [root];
192
+ if (!shadowDOMEnabled || !from || (from as unknown) === root) return targets;
193
+
194
+ const stop = "getRootNode" in root ? root.getRootNode() : null;
195
+ let current: Node | null = from.getRootNode() ?? null;
196
+ while (isShadowRoot(current) && current !== stop) {
197
+ targets.push(current);
198
+ current = current.host.getRootNode();
199
+ }
200
+
201
+ return targets;
202
+ }
203
+
204
+ /**
205
+ * Add a listener to one or many targets and get back the removal.
206
+ *
207
+ * Not owned by a scope: some callers unbind on their own schedule (a press
208
+ * that ends, a transition that finishes). {@link listen} in the interactions
209
+ * module is the owned form.
210
+ */
211
+ export function addEvent(
212
+ target: EventTarget | readonly EventTarget[] | null | undefined,
213
+ type: string,
214
+ listener: EventListenerOrEventListenerObject | null | undefined,
215
+ options?: boolean | AddEventListenerOptions,
216
+ ): () => void {
217
+ if (listener === null || listener === undefined || target === null || target === undefined) {
218
+ return () => {};
219
+ }
220
+
221
+ const targets = Array.isArray(target) ? target : [target as EventTarget];
222
+ for (const one of targets) one.addEventListener(type, listener, options);
223
+
224
+ return () => {
225
+ for (const one of targets) one.removeEventListener(type, listener, options);
226
+ };
227
+ }
228
+
229
+ /** Set a CSS property and get back the restoration of what was there. */
230
+ export function setStyle(
231
+ target: HTMLElement | readonly HTMLElement[] | null | undefined,
232
+ property: string,
233
+ value: string,
234
+ priority?: string,
235
+ ): () => void {
236
+ if (target === null || target === undefined) return () => {};
237
+
238
+ const targets = Array.isArray(target) ? target : [target as HTMLElement];
239
+ const restore: (() => void)[] = [];
240
+
241
+ for (const one of targets) {
242
+ const previous = one.style.getPropertyValue(property);
243
+ const previousPriority = one.style.getPropertyPriority(property);
244
+ one.style.setProperty(property, value, priority);
245
+ restore.unshift(() => {
246
+ if (previous) one.style.setProperty(property, previous, previousPriority);
247
+ else one.style.removeProperty(property);
248
+ });
249
+ }
250
+
251
+ return () => {
252
+ for (const undo of restore) undo();
253
+ };
254
+ }
255
+
256
+ // ---------------------------------------------------------------------------
257
+ // Focusability
258
+ // ---------------------------------------------------------------------------
259
+
260
+ const FOCUSABLE_TAGS = [
261
+ "input:not([disabled]):not([type=hidden])",
262
+ "select:not([disabled])",
263
+ "textarea:not([disabled])",
264
+ "button:not([disabled])",
265
+ "a[href]",
266
+ "area[href]",
267
+ "summary",
268
+ "iframe",
269
+ "object",
270
+ "embed",
271
+ "audio[controls]",
272
+ "video[controls]",
273
+ '[contenteditable]:not([contenteditable^="false"])',
274
+ ];
275
+
276
+ const FOCUSABLE_SELECTOR = `${FOCUSABLE_TAGS.join(":not([hidden]),")},[tabindex]:not([disabled]):not([hidden])`;
277
+
278
+ const TABBABLE_SELECTOR = [
279
+ ...FOCUSABLE_TAGS,
280
+ '[tabindex]:not([tabindex="-1"]):not([disabled])',
281
+ ].join(':not([hidden]):not([tabindex="-1"]),');
282
+
283
+ /**
284
+ * The attribute an element carries to be skipped by the walker while still
285
+ * being in the document: the hidden native input a custom widget keeps for
286
+ * form participation, which must never be reachable by Tab.
287
+ */
288
+ export const PREVENT_FOCUS_ATTRIBUTE = "data-barq-prevent-focus";
289
+
290
+ /** The attribute marking a subtree focus containment must always let through. */
291
+ export const TOP_LAYER_ATTRIBUTE = "data-barq-top-layer";
292
+
293
+ function isInert(element: Element): boolean {
294
+ let node: Element | null = element;
295
+ while (node !== null) {
296
+ if (node instanceof ownerWindow(node).HTMLElement && node.inert) return true;
297
+ node = node.parentElement;
298
+ }
299
+ return false;
300
+ }
301
+
302
+ const supportsCheckVisibility =
303
+ typeof Element !== "undefined" && "checkVisibility" in Element.prototype;
304
+
305
+ function isStyleVisible(element: Element): boolean {
306
+ const view = ownerWindow(element);
307
+ if (!(element instanceof view.HTMLElement) && !(element instanceof view.SVGElement)) return false;
308
+
309
+ const { display, visibility } = element.style;
310
+ if (display === "none" || visibility === "hidden" || visibility === "collapse") return false;
311
+
312
+ const computed = view.getComputedStyle(element);
313
+ return (
314
+ computed.display !== "none" &&
315
+ computed.visibility !== "hidden" &&
316
+ computed.visibility !== "collapse"
317
+ );
318
+ }
319
+
320
+ function isAttributeVisible(element: Element, child?: Element): boolean {
321
+ if (element.hasAttribute("hidden")) return false;
322
+ if (element.hasAttribute(PREVENT_FOCUS_ATTRIBUTE)) return false;
323
+ // A `<details>` that is closed renders only its `<summary>`.
324
+ if (element.nodeName === "DETAILS" && child && child.nodeName !== "SUMMARY") {
325
+ return element.hasAttribute("open");
326
+ }
327
+ return true;
328
+ }
329
+
330
+ /**
331
+ * Whether the element renders at all: `display`, `visibility`, `hidden`, and
332
+ * every ancestor's answer to the same question.
333
+ */
334
+ export function isElementVisible(element: Element, child?: Element): boolean {
335
+ if (supportsCheckVisibility) {
336
+ return (
337
+ element.checkVisibility({ visibilityProperty: true }) &&
338
+ element.closest(`[${PREVENT_FOCUS_ATTRIBUTE}]`) === null
339
+ );
340
+ }
341
+
342
+ return (
343
+ element.nodeName !== "#comment" &&
344
+ isStyleVisible(element) &&
345
+ isAttributeVisible(element, child) &&
346
+ (element.parentElement === null || isElementVisible(element.parentElement, element))
347
+ );
348
+ }
349
+
350
+ /** Whether focus can be moved to the element programmatically. */
351
+ export function isFocusable(
352
+ element: Element,
353
+ options?: { skipVisibilityCheck?: boolean },
354
+ ): boolean {
355
+ return (
356
+ element.matches(FOCUSABLE_SELECTOR) &&
357
+ !isInert(element) &&
358
+ (options?.skipVisibilityCheck === true || isElementVisible(element))
359
+ );
360
+ }
361
+
362
+ /** Whether the element is in the browser's own Tab order. */
363
+ export function isTabbable(element: Element): boolean {
364
+ return element.matches(TABBABLE_SELECTOR) && isElementVisible(element) && !isInert(element);
365
+ }
366
+
367
+ // ---------------------------------------------------------------------------
368
+ // Focus without scrolling
369
+ // ---------------------------------------------------------------------------
370
+
371
+ let supportsPreventScroll: boolean | null = null;
372
+
373
+ function preventScrollSupported(): boolean {
374
+ if (supportsPreventScroll === null) {
375
+ supportsPreventScroll = false;
376
+ try {
377
+ const probe = document.createElement("div");
378
+ probe.focus({
379
+ get preventScroll(): boolean {
380
+ supportsPreventScroll = true;
381
+ return true;
382
+ },
383
+ });
384
+ } catch {
385
+ // The probe cannot fail in a way that matters; `false` is the answer.
386
+ }
387
+ }
388
+ return supportsPreventScroll;
389
+ }
390
+
391
+ interface ScrollState {
392
+ element: HTMLElement;
393
+ scrollTop: number;
394
+ scrollLeft: number;
395
+ }
396
+
397
+ function scrollableAncestors(element: Element): ScrollState[] {
398
+ const states: ScrollState[] = [];
399
+ const rootScroller = document.scrollingElement ?? document.documentElement;
400
+
401
+ let parent = element.parentNode;
402
+ while (parent instanceof HTMLElement && parent !== rootScroller) {
403
+ if (parent.offsetHeight < parent.scrollHeight || parent.offsetWidth < parent.scrollWidth) {
404
+ states.push({ element: parent, scrollTop: parent.scrollTop, scrollLeft: parent.scrollLeft });
405
+ }
406
+ parent = parent.parentNode;
407
+ }
408
+
409
+ if (rootScroller instanceof HTMLElement) {
410
+ states.push({
411
+ element: rootScroller,
412
+ scrollTop: rootScroller.scrollTop,
413
+ scrollLeft: rootScroller.scrollLeft,
414
+ });
415
+ }
416
+
417
+ return states;
418
+ }
419
+
420
+ /**
421
+ * `element.focus({ preventScroll: true })`, with the restore-the-scroll
422
+ * fallback for engines that ignore the option.
423
+ */
424
+ export function focusWithoutScrolling(element: HTMLElement | SVGElement): void {
425
+ if (preventScrollSupported()) {
426
+ element.focus({ preventScroll: true });
427
+ return;
428
+ }
429
+
430
+ const states = scrollableAncestors(element);
431
+ element.focus();
432
+ for (const { element: node, scrollTop, scrollLeft } of states) {
433
+ node.scrollTop = scrollTop;
434
+ node.scrollLeft = scrollLeft;
435
+ }
436
+ }
437
+
438
+ // ---------------------------------------------------------------------------
439
+ // runAfterTransition
440
+ // ---------------------------------------------------------------------------
441
+
442
+ // Which properties are mid-transition, per element. A count would not do:
443
+ // Chrome sometimes fires both `transitionend` and `transitioncancel` for one
444
+ // property, and a count would go negative and never settle.
445
+ const transitioning = new Map<EventTarget, Set<string>>();
446
+ const pending = new Set<() => void>();
447
+ let transitionListenersInstalled = false;
448
+
449
+ function isTransitionEvent(event: Event): event is TransitionEvent {
450
+ return "propertyName" in event;
451
+ }
452
+
453
+ function onTransitionEnd(event: Event): void {
454
+ const target = eventTarget(event);
455
+ if (!isTransitionEvent(event) || target === null) return;
456
+
457
+ const properties = transitioning.get(target);
458
+ if (properties === undefined) return;
459
+
460
+ properties.delete(event.propertyName);
461
+ if (properties.size === 0) {
462
+ target.removeEventListener("transitioncancel", onTransitionEnd);
463
+ transitioning.delete(target);
464
+ }
465
+
466
+ if (transitioning.size === 0) {
467
+ for (const callback of pending) callback();
468
+ pending.clear();
469
+ }
470
+ }
471
+
472
+ function onTransitionRun(event: Event): void {
473
+ const target = eventTarget(event);
474
+ if (!isTransitionEvent(event) || target === null) return;
475
+
476
+ let properties = transitioning.get(target);
477
+ if (properties === undefined) {
478
+ properties = new Set();
479
+ transitioning.set(target, properties);
480
+ // On the element itself, not the document: a node removed mid-transition
481
+ // has nowhere to bubble its cancel to.
482
+ target.addEventListener("transitioncancel", onTransitionEnd, { once: true });
483
+ }
484
+
485
+ properties.add(event.propertyName);
486
+ }
487
+
488
+ function installTransitionListeners(): void {
489
+ if (transitionListenersInstalled || typeof document === "undefined") return;
490
+ transitionListenersInstalled = true;
491
+
492
+ const install = (): void => {
493
+ document.body.addEventListener("transitionrun", onTransitionRun);
494
+ document.body.addEventListener("transitionend", onTransitionEnd);
495
+ };
496
+
497
+ if (document.readyState !== "loading") install();
498
+ else document.addEventListener("DOMContentLoaded", install, { once: true });
499
+ }
500
+
501
+ /**
502
+ * Run `fn` once nothing on the page is mid-transition.
503
+ *
504
+ * Moving focus during a transition makes WebKit recompute style for the whole
505
+ * document and, on iOS, scrolls the page under VoiceOver. Waiting one frame
506
+ * first is what catches a transition that starts on mount.
507
+ */
508
+ export function runAfterTransition(fn: () => void): void {
509
+ installTransitionListeners();
510
+
511
+ requestAnimationFrame(() => {
512
+ // A node removed while transitioning never fires its end event, so its
513
+ // entry would hold every queued callback forever.
514
+ for (const [target] of transitioning) {
515
+ if ("isConnected" in target && !(target as Node).isConnected) transitioning.delete(target);
516
+ }
517
+
518
+ if (transitioning.size === 0) fn();
519
+ else pending.add(fn);
520
+ });
521
+ }
522
+
523
+ // ---------------------------------------------------------------------------
524
+ // Scrolling
525
+ // ---------------------------------------------------------------------------
526
+
527
+ /** Whether the element scrolls, and optionally whether it has anything to scroll. */
528
+ export function isScrollable(node: Element | null, checkForOverflow?: boolean): boolean {
529
+ if (node === null) return false;
530
+
531
+ const style = ownerWindow(node).getComputedStyle(node);
532
+ const root = ownerDocument(node).scrollingElement ?? ownerDocument(node).documentElement;
533
+ let scrollable = /(auto|scroll)/.test(style.overflow + style.overflowX + style.overflowY);
534
+
535
+ // The root scrolls despite its `visible` overflow.
536
+ if (node === root && style.overflow !== "hidden") scrollable = true;
537
+
538
+ if (scrollable && checkForOverflow === true) {
539
+ scrollable = node.scrollHeight !== node.clientHeight || node.scrollWidth !== node.clientWidth;
540
+ }
541
+
542
+ return scrollable;
543
+ }
544
+
545
+ /** Every scrollable ancestor, nearest first. */
546
+ export function scrollParents(node: Element, checkForOverflow?: boolean): Element[] {
547
+ const parents: Element[] = [];
548
+ let at: Element | null = node;
549
+ while (at !== null) {
550
+ if (isScrollable(at, checkForOverflow)) parents.push(at);
551
+ at = at.parentElement;
552
+ }
553
+ return parents;
554
+ }
555
+
556
+ export interface ScrollIntoViewOptions {
557
+ block?: ScrollLogicalPosition;
558
+ inline?: ScrollLogicalPosition;
559
+ }
560
+
561
+ /**
562
+ * Scroll `view` so `element` is visible, without touching anything above it.
563
+ *
564
+ * `element.scrollIntoView({ block: "nearest" })` would do it, and also scrolls
565
+ * every ancestor scroller including the page, which moves a popover out from
566
+ * under the pointer. This computes the offset for one scroller only.
567
+ */
568
+ export function scrollIntoView(
569
+ view: HTMLElement,
570
+ element: HTMLElement,
571
+ options: ScrollIntoViewOptions = {},
572
+ ): void {
573
+ const { block = "nearest", inline = "nearest" } = options;
574
+ if (view === element) return;
575
+
576
+ let y = view.scrollTop;
577
+ let x = view.scrollLeft;
578
+
579
+ const target = element.getBoundingClientRect();
580
+ const bounds = view.getBoundingClientRect();
581
+ const win = ownerWindow(view);
582
+ const itemStyle = win.getComputedStyle(element);
583
+ const viewStyle = win.getComputedStyle(view);
584
+ const root = ownerDocument(view).scrollingElement ?? ownerDocument(view).documentElement;
585
+ const isRoot = view === root;
586
+
587
+ const number = (value: string): number => Number.parseFloat(value) || 0;
588
+
589
+ const viewTop = isRoot ? 0 : bounds.top;
590
+ const viewBottom = isRoot ? view.clientHeight : bounds.bottom;
591
+ const viewLeft = isRoot ? 0 : bounds.left;
592
+ const viewRight = isRoot ? view.clientWidth : bounds.right;
593
+
594
+ const borderTop = number(viewStyle.borderTopWidth);
595
+ const borderBottom = number(viewStyle.borderBottomWidth);
596
+ const borderLeft = number(viewStyle.borderLeftWidth);
597
+ const borderRight = number(viewStyle.borderRightWidth);
598
+
599
+ const areaTop = target.top - number(itemStyle.scrollMarginTop);
600
+ const areaBottom = target.bottom + number(itemStyle.scrollMarginBottom);
601
+ const areaLeft = target.left - number(itemStyle.scrollMarginLeft);
602
+ const areaRight = target.right + number(itemStyle.scrollMarginRight);
603
+
604
+ const barOffsetX = isRoot ? 0 : borderLeft + borderRight;
605
+ const barOffsetY = isRoot ? 0 : borderTop + borderBottom;
606
+ const barWidth = isRoot ? 0 : view.offsetWidth - view.clientWidth - barOffsetX;
607
+ const barHeight = isRoot ? 0 : view.offsetHeight - view.clientHeight - barOffsetY;
608
+
609
+ const portTop = viewTop + (isRoot ? 0 : borderTop) + number(viewStyle.scrollPaddingTop);
610
+ const portBottom =
611
+ viewBottom - (isRoot ? 0 : borderBottom) - number(viewStyle.scrollPaddingBottom) - barHeight;
612
+ let portLeft = viewLeft + (isRoot ? 0 : borderLeft) + number(viewStyle.scrollPaddingLeft);
613
+ let portRight = viewRight - (isRoot ? 0 : borderRight) - number(viewStyle.scrollPaddingRight);
614
+
615
+ // WebKit on iOS puts the scrollbar on the right whichever way the text runs.
616
+ if (viewStyle.direction === "rtl" && !isWebKitIOS()) portLeft += barWidth;
617
+ else portRight -= barWidth;
618
+
619
+ const scrollBlock = areaTop < portTop || areaBottom > portBottom;
620
+ const scrollInline = areaLeft < portLeft || areaRight > portRight;
621
+
622
+ if (scrollBlock) {
623
+ if (block === "start") y += areaTop - portTop;
624
+ else if (block === "center") y += (areaTop + areaBottom) / 2 - (portTop + portBottom) / 2;
625
+ else if (block === "end") y += areaBottom - portBottom;
626
+ else {
627
+ const start = areaTop - portTop;
628
+ const end = areaBottom - portBottom;
629
+ y += Math.abs(start) <= Math.abs(end) ? start : end;
630
+ }
631
+ }
632
+
633
+ if (scrollInline) {
634
+ if (inline === "start") x += areaLeft - portLeft;
635
+ else if (inline === "center") x += (areaLeft + areaRight) / 2 - (portLeft + portRight) / 2;
636
+ else if (inline === "end") x += areaRight - portRight;
637
+ else {
638
+ const start = areaLeft - portLeft;
639
+ const end = areaRight - portRight;
640
+ x += Math.abs(start) <= Math.abs(end) ? start : end;
641
+ }
642
+ }
643
+
644
+ // `scrollTo` is animated and a headless DOM does not implement it; the
645
+ // assignment is what a test can observe.
646
+ if (typeof view.scrollTo === "function") view.scrollTo({ left: x, top: y });
647
+ else {
648
+ view.scrollLeft = x;
649
+ view.scrollTop = y;
650
+ }
651
+ }
652
+
653
+ function isWebKitIOS(): boolean {
654
+ if (typeof navigator === "undefined") return false;
655
+ return /AppleWebKit/i.test(navigator.userAgent) && /iPhone|iPad/i.test(navigator.platform ?? "");
656
+ }
657
+
658
+ /**
659
+ * Scroll the element into the viewport, without scrolling the page when the
660
+ * page's own scrolling has been prevented.
661
+ *
662
+ * A focused option inside an open modal must come into view; scrolling the
663
+ * body to do it would move the modal off screen with no way back.
664
+ */
665
+ export function scrollIntoViewport(
666
+ target: Element | null,
667
+ options: { containingElement?: Element | null } = {},
668
+ ): void {
669
+ if (target === null || !target.isConnected) return;
670
+
671
+ const doc = ownerDocument(target);
672
+ const root = doc.scrollingElement ?? doc.documentElement;
673
+ const prevented = ownerWindow(target).getComputedStyle(root).overflow === "hidden";
674
+
675
+ const before = target.getBoundingClientRect();
676
+
677
+ if (!prevented) {
678
+ target.scrollIntoView?.({ block: "nearest" });
679
+ const after = target.getBoundingClientRect();
680
+ if (Math.abs(before.left - after.left) > 1 || Math.abs(before.top - after.top) > 1) {
681
+ options.containingElement?.scrollIntoView?.({ block: "center", inline: "center" });
682
+ target.scrollIntoView?.({ block: "nearest" });
683
+ }
684
+ return;
685
+ }
686
+
687
+ for (const parent of scrollParents(target, true)) {
688
+ scrollIntoView(parent as HTMLElement, target as HTMLElement);
689
+ }
690
+
691
+ const after = target.getBoundingClientRect();
692
+ if (Math.abs(before.left - after.left) <= 1 && Math.abs(before.top - after.top) <= 1) return;
693
+
694
+ const containing = options.containingElement;
695
+ if (containing !== null && containing !== undefined) {
696
+ for (const parent of scrollParents(containing, true)) {
697
+ scrollIntoView(parent as HTMLElement, containing as HTMLElement, {
698
+ block: "center",
699
+ inline: "center",
700
+ });
701
+ }
702
+ }
703
+ for (const parent of scrollParents(target, true)) {
704
+ scrollIntoView(parent as HTMLElement, target as HTMLElement);
705
+ }
706
+ }