@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,1549 @@
1
+ /**
2
+ * Overlays: dialogs, popovers, menus, tooltips.
3
+ *
4
+ * Four problems, none of which the platform solves for a `<div>` positioned
5
+ * over the page:
6
+ *
7
+ * - Dismissal. Escape closes the TOP overlay, not every open one, and an
8
+ * interaction outside closes it only if the interaction both began and ended
9
+ * outside.
10
+ * - The rest of the page. A modal must be hidden from a screen reader, or the
11
+ * virtual cursor walks straight out of it into content the user cannot see.
12
+ * `aria-hidden` on everything else is the only mechanism that works, and it
13
+ * has to keep working as the page changes underneath.
14
+ * - Scrolling. `overflow: hidden` on the root is enough everywhere except iOS
15
+ * WebKit, which scrolls anyway in four distinct situations.
16
+ * - Position. A popover has to flip when it would go off screen, shift to stay
17
+ * inside its boundary, and cap its own height rather than overflow.
18
+ */
19
+
20
+ import {
21
+ type Accessor,
22
+ createContext,
23
+ createEffect,
24
+ getContext,
25
+ getOwner,
26
+ install,
27
+ provide,
28
+ createSignal,
29
+ untrack,
30
+ } from "@barqjs/core";
31
+ import { isServer } from "@barqjs/web";
32
+ import {
33
+ addEvent,
34
+ contains,
35
+ isScrollable,
36
+ ownerDocument,
37
+ ownerWindow,
38
+ propagationTargets,
39
+ scrollIntoViewport,
40
+ scrollParents,
41
+ setStyle,
42
+ targetElement,
43
+ TOP_LAYER_ATTRIBUTE,
44
+ } from "./dom.ts";
45
+ import { resizeObserver } from "@barqjs/primitives/observers";
46
+
47
+ import { focusWithin } from "./interactions/focus-events.ts";
48
+ import { interactOutside } from "./interactions/interact-outside.ts";
49
+ import { isTextEntry } from "./interactions/modality.ts";
50
+ import type { ElementRef } from "./interactions/press.ts";
51
+ import { StringDictionary, stringFormatter } from "./i18n.ts";
52
+ import { isIOS, isWebKit } from "./platform.ts";
53
+ import {
54
+ access,
55
+ chain,
56
+ clamp,
57
+ controllable,
58
+ id,
59
+ mergeProps,
60
+ type DOMProps,
61
+ type MaybeAccessor,
62
+ } from "./utils.ts";
63
+
64
+ // ---------------------------------------------------------------------------
65
+ // Open state
66
+ // ---------------------------------------------------------------------------
67
+
68
+ /**
69
+ * Do something for as long as an overlay is open, and undo it after.
70
+ *
71
+ * `read` is where the open state and anything else that matters is READ, and
72
+ * `apply` is what is done about the answer; what `apply` returns undoes it
73
+ * before the next answer and on disposal.
74
+ *
75
+ * The two are apart on purpose. A tracked effect reads inside its own first
76
+ * run, and that run can fall in the same pass as a write made by an effect
77
+ * before it: it then sees the value from before the write and is never woken
78
+ * for the one after. An overlay opened from `onSettled` is exactly that, a
79
+ * welcome popover or a dialog restored from the URL, and it stayed closed
80
+ * while its owner's signal said open. A read made here is part of the graph,
81
+ * which is kept consistent across that pass.
82
+ */
83
+ export function followOpen<T>(read: () => T, apply: (value: T) => (() => void) | undefined): void {
84
+ // `apply` measures and reads refs as they are at that moment, on purpose:
85
+ // what it depends on is what `read` returned.
86
+ createEffect(read, (value) => untrack(() => apply(value)));
87
+ }
88
+
89
+ export interface OverlayTriggerStateOptions {
90
+ isOpen?: MaybeAccessor<boolean | undefined>;
91
+ defaultOpen?: MaybeAccessor<boolean | undefined>;
92
+ onOpenChange?: (isOpen: boolean) => void;
93
+ }
94
+
95
+ /**
96
+ * Every member is a PROPERTY rather than a method, because every one of them
97
+ * is handed on detached: `onClose={state.close}` and `onOpenChange={setOpen}`
98
+ * are the idiom this whole layer is built around. Method shorthand would
99
+ * declare a `this` that no implementation here has and no caller could keep.
100
+ */
101
+ export interface OverlayTriggerState {
102
+ isOpen: Accessor<boolean>;
103
+ setOpen: (isOpen: boolean) => void;
104
+ open: () => void;
105
+ close: () => void;
106
+ toggle: () => void;
107
+ }
108
+
109
+ /** Whether an overlay is open, controlled or not. */
110
+ export function overlayTriggerState(options: OverlayTriggerStateOptions = {}): OverlayTriggerState {
111
+ const [isOpen, setOpen] = controllable<boolean>(
112
+ () => access(options.isOpen),
113
+ () => access(options.defaultOpen) ?? false,
114
+ options.onOpenChange,
115
+ );
116
+
117
+ return {
118
+ isOpen,
119
+ setOpen,
120
+ open: () => setOpen(true),
121
+ close: () => setOpen(false),
122
+ toggle: () => setOpen(!isOpen()),
123
+ };
124
+ }
125
+
126
+ export interface OverlayTriggerOptions {
127
+ /** What the trigger opens. */
128
+ type: "dialog" | "menu" | "listbox" | "tree" | "grid";
129
+ }
130
+
131
+ export interface OverlayTriggerResult {
132
+ triggerProps: DOMProps;
133
+ overlayProps: DOMProps;
134
+ }
135
+
136
+ /**
137
+ * The trigger and the overlay it opens, wired together.
138
+ *
139
+ * `aria-haspopup` is only written for a menu and a listbox: screen readers
140
+ * announce every other value as "menu", which is worse than saying nothing.
141
+ */
142
+ export function overlayTrigger(
143
+ options: OverlayTriggerOptions,
144
+ state: OverlayTriggerState,
145
+ ): OverlayTriggerResult {
146
+ const overlayId = id();
147
+
148
+ const hasPopup =
149
+ options.type === "menu" ? true : options.type === "listbox" ? "listbox" : undefined;
150
+
151
+ return {
152
+ triggerProps: {
153
+ "aria-haspopup": hasPopup,
154
+ "aria-expanded": () => state.isOpen(),
155
+ "aria-controls": () => (state.isOpen() ? overlayId() : undefined),
156
+ onPress: () => state.toggle(),
157
+ },
158
+ overlayProps: { id: overlayId },
159
+ };
160
+ }
161
+
162
+ // ---------------------------------------------------------------------------
163
+ // Where an overlay is rendered
164
+ // ---------------------------------------------------------------------------
165
+
166
+ /**
167
+ * Where overlays below this point are portalled to.
168
+ *
169
+ * `null` means the default, which is `document.body`. A container is asked for
170
+ * rather than held, because the element it names may not exist yet when the
171
+ * provider runs — the root popover's own container is exactly that case.
172
+ */
173
+ export type PortalTarget = () => Element | null;
174
+
175
+ const PortalTargetContext = createContext<PortalTarget | null>(null);
176
+
177
+ /**
178
+ * Send every overlay below here somewhere other than the body.
179
+ *
180
+ * For an application that renders inside a shadow root, a fullscreen element,
181
+ * or a container it styles: an overlay portalled to the body would leave that
182
+ * subtree and lose the styles, the theme and the containing block with it.
183
+ */
184
+ export function providePortalTarget(target: PortalTarget | null): void {
185
+ const owner = getOwner();
186
+ if (owner !== null) install(owner, PortalTargetContext, () => target);
187
+ }
188
+
189
+ /**
190
+ * Build `children` with every overlay inside them sent to `target`.
191
+ *
192
+ * {@link providePortalTarget} installs on whatever scope is current, which is
193
+ * right in a component that owns one and wrong in one that does not: there it
194
+ * lands on the surrounding scope and the siblings read it too.
195
+ */
196
+ export function withPortalTarget(target: PortalTarget | null, children: () => unknown): unknown {
197
+ return provide(PortalTargetContext, () => target, children);
198
+ }
199
+
200
+ /** The portal target in scope, if one was provided. */
201
+ export function usePortalTarget(): PortalTarget | null {
202
+ return getContext(PortalTargetContext) ?? null;
203
+ }
204
+
205
+ /**
206
+ * The element an overlay should be portalled into.
207
+ *
208
+ * `null` on the server and before the document exists, which is the signal to
209
+ * render nothing rather than to render in the wrong place.
210
+ */
211
+ export function portalContainer(target: PortalTarget | null): Element | null {
212
+ const given = target?.() ?? null;
213
+ if (given !== null) return given;
214
+ if (isServer || typeof document === "undefined") return null;
215
+ return document.body;
216
+ }
217
+
218
+ // ---------------------------------------------------------------------------
219
+ // Dismissal
220
+ // ---------------------------------------------------------------------------
221
+
222
+ /**
223
+ * Every open overlay, innermost last.
224
+ *
225
+ * Escape and an outside press act on the last one only: a menu inside a dialog
226
+ * must close the menu, leaving the dialog open.
227
+ */
228
+ const openOverlays: ElementRef[] = [];
229
+
230
+ export interface OverlayOptions {
231
+ isOpen?: MaybeAccessor<boolean | undefined>;
232
+ onClose?: () => void;
233
+ /** Close when the user interacts outside. @default false */
234
+ isDismissable?: MaybeAccessor<boolean | undefined>;
235
+ /** Close when focus leaves. */
236
+ shouldCloseOnBlur?: MaybeAccessor<boolean | undefined>;
237
+ /** @default false */
238
+ isKeyboardDismissDisabled?: MaybeAccessor<boolean | undefined>;
239
+ /**
240
+ * Hear Escape wherever focus is, not only inside the overlay.
241
+ *
242
+ * For an overlay that never takes focus: a hover card opened from the
243
+ * keyboard leaves focus on its trigger, which is outside it, and a handler
244
+ * on the overlay alone would never hear the key.
245
+ *
246
+ * @default false
247
+ */
248
+ shouldCloseOnEscapeAnywhere?: MaybeAccessor<boolean | undefined>;
249
+ /** Veto a dismissal for an interaction with a particular element. */
250
+ shouldCloseOnInteractOutside?: (element: Element) => boolean;
251
+ /**
252
+ * What counts as INSIDE, when that is more than the overlay itself.
253
+ *
254
+ * A submenu is portalled into its root popover's container rather than into
255
+ * the body, so the whole group is one overlay as far as an outside press and
256
+ * `aria-hidden` are concerned. Without this a press on a submenu item is a
257
+ * press outside the menu that opened it.
258
+ *
259
+ * @default the overlay's own element
260
+ */
261
+ groupRef?: ElementRef;
262
+ }
263
+
264
+ export interface OverlayResult {
265
+ overlayProps: DOMProps;
266
+ underlayProps: DOMProps;
267
+ }
268
+
269
+ /** Dismissal behaviour for one overlay. */
270
+ export function overlay(options: OverlayOptions, ref: ElementRef): OverlayResult {
271
+ let lastTopMost: ElementRef | undefined;
272
+ const inside: ElementRef = options.groupRef ?? ref;
273
+
274
+ // Not on the server, where the effects of a render still run: the stack is
275
+ // module state, and a request that opened an overlay would leave it there
276
+ // for every request after.
277
+ if (!isServer) {
278
+ followOpen(
279
+ () => access(options.isOpen) === true,
280
+ (isOpen) => {
281
+ if (!isOpen || openOverlays.includes(ref)) return undefined;
282
+ openOverlays.push(ref);
283
+ return () => {
284
+ const at = openOverlays.indexOf(ref);
285
+ if (at >= 0) openOverlays.splice(at, 1);
286
+ };
287
+ },
288
+ );
289
+ }
290
+
291
+ const isTopMost = (): boolean => openOverlays[openOverlays.length - 1] === ref;
292
+
293
+ const hide = (): void => {
294
+ if (isTopMost()) options.onClose?.();
295
+ };
296
+
297
+ const shouldClose = (element: Element | null): boolean => {
298
+ if (options.shouldCloseOnInteractOutside === undefined) return true;
299
+ return element !== null && options.shouldCloseOnInteractOutside(element);
300
+ };
301
+
302
+ interactOutside({
303
+ ref: inside,
304
+ // The server has no document to hear a press on.
305
+ isDisabled: () =>
306
+ isServer || access(options.isDismissable) !== true || access(options.isOpen) !== true,
307
+ onInteractOutsideStart: (event) => {
308
+ lastTopMost = openOverlays[openOverlays.length - 1];
309
+ if (shouldClose(targetElement(event)) && isTopMost()) event.stopPropagation();
310
+ },
311
+ onInteractOutside: (event) => {
312
+ if (shouldClose(targetElement(event))) {
313
+ if (isTopMost()) event.stopPropagation();
314
+ // Only if this overlay was the top one when the press BEGAN: a press
315
+ // that started while a menu was open must not close the dialog the
316
+ // menu was in once the menu has gone.
317
+ if (lastTopMost === ref) hide();
318
+ }
319
+ lastTopMost = undefined;
320
+ },
321
+ });
322
+
323
+ const { focusWithinProps } = focusWithin({
324
+ isDisabled: () => access(options.shouldCloseOnBlur) !== true,
325
+ onBlurWithin: (event) => {
326
+ // A null `relatedTarget` means focus went to the body: switching tabs,
327
+ // or a VoiceOver quirk. An outside PRESS is handled above; this is only
328
+ // for focus genuinely moving elsewhere.
329
+ const related = event.relatedTarget as Element | null;
330
+ if (related === null) return;
331
+ // Focus going into a submenu, or into an overlay this one opened, has
332
+ // not left: both are this overlay's own, wherever they are mounted.
333
+ if (contains(access(inside), related)) return;
334
+ const above = openOverlays.slice(openOverlays.indexOf(ref) + 1);
335
+ if (above.some((child) => contains(access(child), related))) return;
336
+ if (shouldClose(related)) options.onClose?.();
337
+ },
338
+ });
339
+
340
+ const onKeyDown = (event: KeyboardEvent): void => {
341
+ if (event.key !== "Escape") return;
342
+ if (access(options.isKeyboardDismissDisabled) === true) return;
343
+ event.stopPropagation();
344
+ event.preventDefault();
345
+ hide();
346
+ };
347
+
348
+ if (!isServer) {
349
+ followOpen(
350
+ () => access(options.isOpen) === true && access(options.shouldCloseOnEscapeAnywhere) === true,
351
+ (listens) => {
352
+ if (!listens) return undefined;
353
+ const doc = ownerDocument(access(ref));
354
+ const onDocumentKeyDown = (event: KeyboardEvent): void => {
355
+ // Inside the overlay its own handler has already answered, and an
356
+ // overlay further up the stack is the one Escape belongs to.
357
+ if (event.defaultPrevented || !isTopMost()) return;
358
+ onKeyDown(event);
359
+ };
360
+ doc.addEventListener("keydown", onDocumentKeyDown);
361
+ return () => doc.removeEventListener("keydown", onDocumentKeyDown);
362
+ },
363
+ );
364
+ }
365
+
366
+ return {
367
+ overlayProps: mergeProps(focusWithinProps, { onKeyDown }),
368
+ underlayProps: {},
369
+ };
370
+ }
371
+
372
+ /**
373
+ * Close when the trigger scrolls out from under the overlay.
374
+ *
375
+ * A popover anchored to something that has scrolled away is pointing at
376
+ * nothing. Scrolling inside a field is ignored: a combobox input scrolls its
377
+ * own text when the caret moves, which is not the page moving.
378
+ */
379
+ export function closeOnScroll(options: {
380
+ triggerRef: ElementRef;
381
+ isOpen?: MaybeAccessor<boolean | undefined>;
382
+ onClose?: (() => void) | null;
383
+ }): void {
384
+ if (isServer) return;
385
+
386
+ followOpen(
387
+ () =>
388
+ access(options.isOpen) !== true || options.onClose === null
389
+ ? null
390
+ : ((access(options.triggerRef) as Element | null) ?? null),
391
+ (trigger) => {
392
+ if (trigger === null) return undefined;
393
+
394
+ const onScroll = (event: Event): void => {
395
+ const target = targetElement(event);
396
+ // A scroller elsewhere in the page does not move the trigger.
397
+ if (target !== null && !contains(target, trigger)) return;
398
+ if (target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement) return;
399
+ options.onClose?.();
400
+ };
401
+
402
+ return addEvent(propagationTargets(trigger), "scroll", onScroll, true);
403
+ },
404
+ );
405
+ }
406
+
407
+ // ---------------------------------------------------------------------------
408
+ // Hiding the rest of the page
409
+ // ---------------------------------------------------------------------------
410
+
411
+ const supportsInert = typeof HTMLElement !== "undefined" && "inert" in HTMLElement.prototype;
412
+
413
+ /** How many overlays are hiding each element, so nesting unwinds correctly. */
414
+ const hiddenCounts = new WeakMap<Element, number>();
415
+
416
+ interface HideObserver {
417
+ visible: Set<Element>;
418
+ hidden: Set<Element>;
419
+ observe(): void;
420
+ disconnect(): void;
421
+ }
422
+
423
+ const hideStack: HideObserver[] = [];
424
+
425
+ function isAlwaysVisible(node: Element): boolean {
426
+ const data = (node as HTMLElement).dataset;
427
+ return data?.barqLiveAnnouncer === "true" || node.hasAttribute(TOP_LAYER_ATTRIBUTE);
428
+ }
429
+
430
+ /**
431
+ * Hide everything except `targets` from assistive technology.
432
+ *
433
+ * A `MutationObserver` keeps it true as the page changes: a toast rendered
434
+ * while a dialog is open would otherwise be readable by a screen reader that
435
+ * is supposed to be trapped inside the dialog.
436
+ *
437
+ * Returns the undo.
438
+ */
439
+ export function ariaHideOutside(
440
+ targets: Element[],
441
+ options: { root?: Element; shouldUseInert?: boolean } = {},
442
+ ): () => void {
443
+ if (isServer || typeof MutationObserver === "undefined") return () => {};
444
+
445
+ const view = ownerWindow(targets[0]);
446
+ const root = options.root ?? ownerDocument(targets[0]).body;
447
+ const useInert = options.shouldUseInert === true && supportsInert;
448
+
449
+ const visible = new Set<Element>(targets);
450
+ const hidden = new Set<Element>();
451
+
452
+ const isHidden = (element: Element): boolean =>
453
+ useInert && element instanceof view.HTMLElement
454
+ ? element.inert
455
+ : element.getAttribute("aria-hidden") === "true";
456
+
457
+ const setHidden = (element: Element, value: boolean): void => {
458
+ if (useInert && element instanceof view.HTMLElement) {
459
+ element.inert = value;
460
+ return;
461
+ }
462
+ if (value) {
463
+ element.setAttribute("aria-hidden", "true");
464
+ return;
465
+ }
466
+ element.removeAttribute("aria-hidden");
467
+ if (element instanceof view.HTMLElement) element.inert = false;
468
+ };
469
+
470
+ const hide = (node: Element): void => {
471
+ const count = hiddenCounts.get(node) ?? 0;
472
+ // Already hidden by the page itself: leave it alone entirely, so the undo
473
+ // does not reveal something that was never ours.
474
+ if (isHidden(node) && count === 0) return;
475
+ if (count === 0) setHidden(node, true);
476
+ hidden.add(node);
477
+ hiddenCounts.set(node, count + 1);
478
+ };
479
+
480
+ const walk = (from: Element): void => {
481
+ for (const element of from.querySelectorAll(
482
+ `[data-barq-live-announcer], [${TOP_LAYER_ATTRIBUTE}]`,
483
+ )) {
484
+ visible.add(element);
485
+ }
486
+
487
+ const accept = (node: Element): number => {
488
+ // `aria-hidden` is inherited, so a child of a hidden node needs nothing.
489
+ // `role="row"` is the exception: iOS VoiceOver ignores `aria-hidden` on
490
+ // a row, so its cells have to be hidden individually.
491
+ if (
492
+ hidden.has(node) ||
493
+ visible.has(node) ||
494
+ (node.parentElement !== null &&
495
+ hidden.has(node.parentElement) &&
496
+ node.parentElement.getAttribute("role") !== "row")
497
+ ) {
498
+ return NodeFilter.FILTER_REJECT;
499
+ }
500
+
501
+ // An ancestor of a target stays visible, but its other children do not.
502
+ for (const target of visible) {
503
+ if (contains(node, target)) return NodeFilter.FILTER_SKIP;
504
+ }
505
+
506
+ return NodeFilter.FILTER_ACCEPT;
507
+ };
508
+
509
+ const verdict = accept(from);
510
+ if (verdict === NodeFilter.FILTER_ACCEPT) hide(from);
511
+ if (verdict === NodeFilter.FILTER_REJECT) return;
512
+
513
+ const walker = ownerDocument(from).createTreeWalker(from, NodeFilter.SHOW_ELEMENT, {
514
+ acceptNode: accept,
515
+ });
516
+ let node = walker.nextNode();
517
+ while (node !== null) {
518
+ hide(node as Element);
519
+ node = walker.nextNode();
520
+ }
521
+ };
522
+
523
+ // A previous call's observer stops watching while this one is on top.
524
+ hideStack[hideStack.length - 1]?.disconnect();
525
+
526
+ walk(root);
527
+
528
+ const observer = new MutationObserver((changes) => {
529
+ for (const change of changes) {
530
+ if (change.type !== "childList") continue;
531
+ if (!change.target.isConnected) continue;
532
+ if ([...visible, ...hidden].some((node) => contains(node, change.target))) continue;
533
+
534
+ for (const node of change.addedNodes) {
535
+ if (node instanceof Element && isAlwaysVisible(node)) visible.add(node);
536
+ else if (node instanceof Element) walk(node);
537
+ }
538
+ }
539
+ });
540
+
541
+ observer.observe(root, { childList: true, subtree: true });
542
+
543
+ const entry: HideObserver = {
544
+ visible,
545
+ hidden,
546
+ observe: () => observer.observe(root, { childList: true, subtree: true }),
547
+ disconnect: () => observer.disconnect(),
548
+ };
549
+ hideStack.push(entry);
550
+
551
+ return () => {
552
+ observer.disconnect();
553
+
554
+ for (const node of hidden) {
555
+ const count = hiddenCounts.get(node);
556
+ if (count === undefined) continue;
557
+ if (count === 1) {
558
+ setHidden(node, false);
559
+ hiddenCounts.delete(node);
560
+ } else {
561
+ hiddenCounts.set(node, count - 1);
562
+ }
563
+ }
564
+
565
+ const at = hideStack.indexOf(entry);
566
+ if (at === hideStack.length - 1) {
567
+ hideStack.pop();
568
+ hideStack[hideStack.length - 1]?.observe();
569
+ } else if (at >= 0) {
570
+ hideStack.splice(at, 1);
571
+ }
572
+ };
573
+ }
574
+
575
+ /** Keep an element visible to assistive technology inside the current overlay. */
576
+ export function keepVisible(element: Element): (() => void) | undefined {
577
+ const entry = hideStack[hideStack.length - 1];
578
+ if (entry === undefined || entry.visible.has(element)) return undefined;
579
+ entry.visible.add(element);
580
+ return () => entry.visible.delete(element);
581
+ }
582
+
583
+ // ---------------------------------------------------------------------------
584
+ // Preventing scroll
585
+ // ---------------------------------------------------------------------------
586
+
587
+ let scrollLocks = 0;
588
+ let releaseScroll: (() => void) | null = null;
589
+
590
+ /**
591
+ * Stop the page scrolling behind a modal.
592
+ *
593
+ * `overflow: hidden` on the root is enough everywhere but iOS WebKit, where
594
+ * the page still scrolls when the toolbars are collapsed, when the keyboard is
595
+ * up, when an input is focused, and when the keyboard's next/previous buttons
596
+ * move between fields. Each needs its own answer.
597
+ */
598
+ export function preventScroll(
599
+ options: { isDisabled?: MaybeAccessor<boolean | undefined> } = {},
600
+ ): void {
601
+ if (isServer) return;
602
+
603
+ followOpen(
604
+ () => access(options.isDisabled) !== true,
605
+ (locks) => {
606
+ if (!locks) return undefined;
607
+
608
+ scrollLocks++;
609
+ if (scrollLocks === 1) {
610
+ releaseScroll = isIOS() && isWebKit() ? preventScrollWebKitIOS() : preventScrollStandard();
611
+ }
612
+
613
+ return () => {
614
+ scrollLocks--;
615
+ if (scrollLocks === 0) {
616
+ releaseScroll?.();
617
+ releaseScroll = null;
618
+ }
619
+ };
620
+ },
621
+ );
622
+ }
623
+
624
+ function preventScrollStandard(): () => void {
625
+ const root = document.documentElement;
626
+ const scrollbarWidth = window.innerWidth - root.clientWidth;
627
+
628
+ // `scrollbar-gutter` where it exists, because padding does not hold a fixed
629
+ // element in place and the gutter does.
630
+ const compensate =
631
+ scrollbarWidth > 0
632
+ ? "scrollbarGutter" in root.style
633
+ ? setStyle(root, "scrollbar-gutter", "stable")
634
+ : setStyle(root, "padding-right", `${scrollbarWidth}px`)
635
+ : () => {};
636
+
637
+ return chain(compensate, setStyle(root, "overflow", "hidden"));
638
+ }
639
+
640
+ function preventScrollWebKitIOS(): () => void {
641
+ // Also what tells `scrollIntoViewport` to scroll only the scroll parents.
642
+ const restoreOverflow = setStyle(document.documentElement, "overflow", "hidden");
643
+
644
+ let scroller: Element | null = null;
645
+ let allowTouchMove = false;
646
+
647
+ const onTouchStart = (event: Event): void => {
648
+ const touch = event as TouchEvent;
649
+ const target = targetElement(touch);
650
+ if (target === null) return;
651
+
652
+ scroller = isScrollable(target) ? target : (scrollParents(target, true)[0] ?? null);
653
+ allowTouchMove = false;
654
+
655
+ // Adjusting a text selection, dragging a slider and moving a selection
656
+ // handle are all touch moves the user meant.
657
+ const selection = ownerWindow(target).getSelection();
658
+ if (selection !== null && !selection.isCollapsed && selection.containsNode(target, true)) {
659
+ allowTouchMove = true;
660
+ }
661
+ if (touch.composedPath().some((el) => el instanceof HTMLInputElement && el.type === "range")) {
662
+ allowTouchMove = true;
663
+ }
664
+ if (
665
+ target instanceof HTMLInputElement &&
666
+ target.selectionStart !== null &&
667
+ target.selectionEnd !== null &&
668
+ target.selectionStart < target.selectionEnd &&
669
+ ownerDocument(target).activeElement === target
670
+ ) {
671
+ allowTouchMove = true;
672
+ }
673
+ };
674
+
675
+ const onTouchMove = (event: Event): void => {
676
+ const touch = event as TouchEvent;
677
+ if (touch.touches.length === 2 || allowTouchMove) return;
678
+
679
+ if (scroller === null || scroller === document.documentElement || scroller === document.body) {
680
+ touch.preventDefault();
681
+ return;
682
+ }
683
+
684
+ // `overscroll-behavior: contain` should stop the chain to the page, and
685
+ // does not when the element does not actually overflow.
686
+ if (
687
+ scroller.scrollHeight === scroller.clientHeight &&
688
+ scroller.scrollWidth === scroller.clientWidth
689
+ ) {
690
+ touch.preventDefault();
691
+ }
692
+ };
693
+
694
+ // Injected as a stylesheet because iOS 26 requires it to be in effect before
695
+ // the touchstart, which a property set in the handler is not.
696
+ const style = document.createElement("style");
697
+ const nonce = cspNonce(document);
698
+ if (nonce !== undefined) style.nonce = nonce;
699
+ style.textContent = "@layer{*{overscroll-behavior:contain}}";
700
+ document.head.prepend(style);
701
+
702
+ const restoreFocus = overrideFocus();
703
+ const removeEvents = chain(
704
+ addEvent(document, "touchstart", onTouchStart, { passive: false, capture: true }),
705
+ addEvent(document, "touchmove", onTouchMove, { passive: false, capture: true }),
706
+ addEvent(document, "blur", onBlurForKeyboard, true),
707
+ );
708
+
709
+ return () => {
710
+ restoreOverflow();
711
+ removeEvents();
712
+ style.remove();
713
+ restoreFocus();
714
+ };
715
+ }
716
+
717
+ /**
718
+ * The nonce a Content Security Policy wants on an injected `<style>`, as the
719
+ * page publishes it: a `csp-nonce` meta tag, or the bundler's global.
720
+ */
721
+ function cspNonce(doc: Document): string | undefined {
722
+ const view = doc.defaultView;
723
+ const meta = doc.querySelector('meta[name="csp-nonce"], meta[property="csp-nonce"]');
724
+ if (view !== null && meta instanceof view.HTMLMetaElement) {
725
+ const declared = meta.nonce || meta.content;
726
+ if (declared) return declared;
727
+ }
728
+ const bundled =
729
+ (view as { __webpack_nonce__?: string } | null)?.__webpack_nonce__ ??
730
+ (globalThis as { __webpack_nonce__?: string }).__webpack_nonce__;
731
+ return bundled === undefined || bundled === "" ? undefined : bundled;
732
+ }
733
+
734
+ /**
735
+ * Run once the on-screen keyboard has finished appearing, if focus is about to
736
+ * bring it up, and straight away otherwise.
737
+ *
738
+ * Two frames for focus to land, then the visual viewport's resize, which is
739
+ * the keyboard arriving. A keyboard that never arrives (a hardware one is
740
+ * attached) is given up on after the time iOS takes to animate one in.
741
+ */
742
+ function afterKeyboard(run: () => void): void {
743
+ const view = window;
744
+ view.requestAnimationFrame(() => {
745
+ view.requestAnimationFrame(() => {
746
+ const visual = view.visualViewport;
747
+ if (visual === null || visual === undefined || !isTextEntry(document.activeElement)) {
748
+ run();
749
+ return;
750
+ }
751
+ let done = false;
752
+ const finish = (): void => {
753
+ if (done) return;
754
+ done = true;
755
+ visual.removeEventListener("resize", finish);
756
+ clearTimeout(timer);
757
+ run();
758
+ };
759
+ const timer = setTimeout(finish, KEYBOARD_TIMEOUT);
760
+ visual.addEventListener("resize", finish);
761
+ });
762
+ });
763
+ }
764
+
765
+ /** How long iOS takes to bring the on-screen keyboard in. */
766
+ const KEYBOARD_TIMEOUT = 600;
767
+
768
+ /**
769
+ * Programmatic focus that does not scroll the page.
770
+ *
771
+ * WebKit on iOS scrolls the whole page to centre a focused field, which moves
772
+ * even a fixed modal off the screen. Focus is taken without scrolling, and the
773
+ * field is brought into view by its own scroll parents once the keyboard has
774
+ * taken its share of the screen.
775
+ */
776
+ function overrideFocus(): () => void {
777
+ const prototype = HTMLElement.prototype;
778
+ const own = Object.getOwnPropertyDescriptor(prototype, "focus");
779
+ const focus = Reflect.get(prototype, "focus");
780
+ Reflect.defineProperty(prototype, "focus", {
781
+ configurable: true,
782
+ writable: true,
783
+ value(this: HTMLElement, options?: FocusOptions) {
784
+ focus.call(this, { ...options, preventScroll: true });
785
+ if (options?.preventScroll === true) return;
786
+ afterKeyboard(() => {
787
+ if (ownerDocument(this).activeElement === this) scrollIntoViewport(this);
788
+ });
789
+ },
790
+ });
791
+ return () => {
792
+ if (own === undefined) Reflect.deleteProperty(prototype, "focus");
793
+ else Reflect.defineProperty(prototype, "focus", own);
794
+ };
795
+ }
796
+
797
+ /**
798
+ * Route focus moves that WebKit makes itself through {@link overrideFocus}.
799
+ *
800
+ * Tapping a field focuses it natively, which scrolls the page; focusing it
801
+ * again from here takes the path that does not. The keyboard's Done button
802
+ * sends focus to the body, and the next tap on the same field then fires no
803
+ * blur at all, so focus goes to the nearest focusable ancestor instead.
804
+ */
805
+ function onBlurForKeyboard(event: Event): void {
806
+ const blur = event as FocusEvent;
807
+ const target = targetElement(blur);
808
+ const related = blur.relatedTarget as HTMLElement | null;
809
+ if (related !== null && isTextEntry(related)) {
810
+ related.focus();
811
+ } else if (related === null) {
812
+ const holder = target?.parentElement?.closest<HTMLElement>("[tabindex]") ?? null;
813
+ holder?.focus({ preventScroll: true });
814
+ }
815
+ }
816
+
817
+ // ---------------------------------------------------------------------------
818
+ // Positioning
819
+ // ---------------------------------------------------------------------------
820
+
821
+ export type Placement =
822
+ | "top"
823
+ | "top start"
824
+ | "top end"
825
+ | "bottom"
826
+ | "bottom start"
827
+ | "bottom end"
828
+ | "left"
829
+ | "left top"
830
+ | "left bottom"
831
+ | "right"
832
+ | "right top"
833
+ | "right bottom"
834
+ | "start"
835
+ | "start top"
836
+ | "start bottom"
837
+ | "end"
838
+ | "end top"
839
+ | "end bottom";
840
+
841
+ export type Axis = "top" | "bottom" | "left" | "right";
842
+
843
+ /** Which edge of the trigger an overlay hangs off, as Radix and Base UI name it. */
844
+ export type Side = "top" | "right" | "bottom" | "left" | "inline-start" | "inline-end";
845
+
846
+ /** Where along that edge it sits. */
847
+ export type Align = "start" | "center" | "end";
848
+
849
+ /**
850
+ * The {@link Placement} a side and an alignment name.
851
+ *
852
+ * Two vocabularies for one position: `side="bottom" align="start"` is
853
+ * `"bottom start"`, and `side="right" align="end"` is `"right bottom"`, because
854
+ * a placement names the cross axis by the edge it lines up with.
855
+ */
856
+ export function placementFor(side: Side, align: Align = "center"): Placement {
857
+ const main = side === "inline-start" ? "start" : side === "inline-end" ? "end" : side;
858
+ if (align === "center") return main;
859
+ if (main === "top" || main === "bottom") return `${main} ${align}`;
860
+ return `${main} ${align === "start" ? "top" : "bottom"}`;
861
+ }
862
+
863
+ /** The alignment a {@link Placement} asks for, in the other vocabulary. */
864
+ export function alignOf(placement: Placement): Align {
865
+ const cross = placement.split(" ")[1];
866
+ if (cross === "start" || cross === "top") return "start";
867
+ if (cross === "end" || cross === "bottom") return "end";
868
+ return "center";
869
+ }
870
+
871
+ export interface PositionOptions {
872
+ /** The element the overlay is anchored to. */
873
+ targetRef: ElementRef;
874
+ /**
875
+ * A box in client coordinates to place against, instead of the target's own.
876
+ *
877
+ * A context menu is anchored to the point the pointer was at, which is not
878
+ * an element and has no box to measure. `targetRef` stays whatever that
879
+ * point was inside, so scrolling the region away still closes the overlay
880
+ * and a resize there still re-places it.
881
+ */
882
+ targetRect?: MaybeAccessor<AnchorRect | null | undefined>;
883
+ /** The overlay itself. */
884
+ overlayRef: ElementRef;
885
+ /** What the overlay must stay inside. @default the viewport */
886
+ boundaryRef?: ElementRef;
887
+ /** Which side, and how the cross axis aligns. @default "bottom" */
888
+ placement?: MaybeAccessor<Placement | undefined>;
889
+ /** Distance from the target, along the main axis. @default 0 */
890
+ offset?: MaybeAccessor<number | undefined>;
891
+ /** Distance along the cross axis. @default 0 */
892
+ crossOffset?: MaybeAccessor<number | undefined>;
893
+ /** Flip to the opposite side when there is no room. @default true */
894
+ shouldFlip?: MaybeAccessor<boolean | undefined>;
895
+ /** Keep this far from the boundary's edges. @default 12 */
896
+ containerPadding?: MaybeAccessor<number | undefined>;
897
+ /** The arrow element, so it can be centred on the target. */
898
+ arrowRef?: ElementRef;
899
+ /**
900
+ * The least distance between the arrow and the overlay's ends, so it stays
901
+ * clear of a rounded corner. @default 0
902
+ */
903
+ arrowBoundaryOffset?: MaybeAccessor<number | undefined>;
904
+ isOpen?: MaybeAccessor<boolean | undefined>;
905
+ onClose?: () => void;
906
+ /** Text direction, for `start` and `end` placements. @default "ltr" */
907
+ direction?: MaybeAccessor<"ltr" | "rtl" | undefined>;
908
+ }
909
+
910
+ export interface PositionResult {
911
+ /** Style for the overlay: absolute position and a maximum height. */
912
+ overlayProps: DOMProps;
913
+ /** Style for the arrow: its offset along the cross axis. */
914
+ arrowProps: DOMProps;
915
+ /** Where the overlay ended up, which may not be where it was asked to go. */
916
+ placement: Accessor<Axis>;
917
+ /** Re-measure and re-place. */
918
+ update(): void;
919
+ }
920
+
921
+ /** A box in client coordinates: what an overlay is placed against. */
922
+ export interface AnchorRect {
923
+ top: number;
924
+ left: number;
925
+ width: number;
926
+ height: number;
927
+ }
928
+
929
+ type Box = AnchorRect;
930
+
931
+ const OPPOSITE: Record<Axis, Axis> = {
932
+ top: "bottom",
933
+ bottom: "top",
934
+ left: "right",
935
+ right: "left",
936
+ };
937
+
938
+ function resolveAxis(placement: Placement, direction: "ltr" | "rtl"): [Axis, string] {
939
+ const [side, align = "center"] = placement.split(" ") as [string, string?];
940
+ if (side === "start") return [direction === "rtl" ? "right" : "left", align];
941
+ if (side === "end") return [direction === "rtl" ? "left" : "right", align];
942
+ // `start` and `end` under or over a trigger are its inline edges, so they
943
+ // trade places with the text direction.
944
+ if (direction === "rtl" && (side === "top" || side === "bottom")) {
945
+ return [side, align === "start" ? "end" : align === "end" ? "start" : align];
946
+ }
947
+ return [side as Axis, align];
948
+ }
949
+
950
+ function boxOf(element: Element): Box {
951
+ const rect = element.getBoundingClientRect();
952
+ return { top: rect.top, left: rect.left, width: rect.width, height: rect.height };
953
+ }
954
+
955
+ /**
956
+ * Width and height before any transform.
957
+ *
958
+ * `getBoundingClientRect` reports what is PAINTED, which for anything mid-
959
+ * animation is the wrong number to place it by.
960
+ */
961
+ function layoutSize(element: Element): { width: number; height: number } {
962
+ const html = element as HTMLElement;
963
+ return html.offsetWidth > 0 || html.offsetHeight > 0
964
+ ? { width: html.offsetWidth, height: html.offsetHeight }
965
+ : boxOf(element);
966
+ }
967
+
968
+ function place(
969
+ target: Box,
970
+ panel: { width: number; height: number },
971
+ axis: Axis,
972
+ align: string,
973
+ offset: number,
974
+ cross: number,
975
+ ): {
976
+ top: number;
977
+ left: number;
978
+ } {
979
+ let top = 0;
980
+ let left = 0;
981
+
982
+ if (axis === "top" || axis === "bottom") {
983
+ top = axis === "top" ? target.top - panel.height - offset : target.top + target.height + offset;
984
+ if (align === "start") left = target.left;
985
+ else if (align === "end") left = target.left + target.width - panel.width;
986
+ else left = target.left + target.width / 2 - panel.width / 2;
987
+ left += cross;
988
+ } else {
989
+ left =
990
+ axis === "left" ? target.left - panel.width - offset : target.left + target.width + offset;
991
+ if (align === "top" || align === "start") top = target.top;
992
+ else if (align === "bottom" || align === "end") top = target.top + target.height - panel.height;
993
+ else top = target.top + target.height / 2 - panel.height / 2;
994
+ top += cross;
995
+ }
996
+
997
+ return { top, left };
998
+ }
999
+
1000
+ /** The room between the target and the boundary on one side, past the offset and the padding. */
1001
+ function spaceOn(axis: Axis, target: Box, boundary: Box, offset: number, padding: number): number {
1002
+ const room =
1003
+ axis === "top"
1004
+ ? target.top - boundary.top
1005
+ : axis === "bottom"
1006
+ ? boundary.top + boundary.height - (target.top + target.height)
1007
+ : axis === "left"
1008
+ ? target.left - boundary.left
1009
+ : boundary.left + boundary.width - (target.left + target.width);
1010
+ return Math.max(0, room - offset - padding);
1011
+ }
1012
+
1013
+ /**
1014
+ * How far to move an overlay along one axis so it stays inside the boundary.
1015
+ *
1016
+ * When it is bigger than the boundary its START edge wins, so the beginning of
1017
+ * a list too long for the screen is what stays in view.
1018
+ */
1019
+ function shiftInto(start: number, size: number, low: number, high: number): number {
1020
+ if (start < low) return low - start;
1021
+ if (start + size > high) return Math.max(high - (start + size), low - start);
1022
+ return 0;
1023
+ }
1024
+
1025
+ /**
1026
+ * What an overlay inside the page is laid out in: the area the user can see.
1027
+ *
1028
+ * The visual viewport where there is one. A pinch-zoomed page and an iOS page
1029
+ * with the on-screen keyboard up both show less than `innerHeight`, and an
1030
+ * overlay sized to the layout viewport is cut off behind the keyboard.
1031
+ */
1032
+ function visibleViewport(view: Window): Box {
1033
+ const visual = view.visualViewport;
1034
+ if (visual !== null && visual !== undefined) {
1035
+ return {
1036
+ top: visual.offsetTop,
1037
+ left: visual.offsetLeft,
1038
+ width: visual.width,
1039
+ height: visual.height,
1040
+ };
1041
+ }
1042
+ return { top: 0, left: 0, width: view.innerWidth, height: view.innerHeight };
1043
+ }
1044
+
1045
+ /** A computed value that is set, which happy-dom reports as "" rather than "none". */
1046
+ function isSet(value: string | undefined): boolean {
1047
+ return value !== undefined && value !== "" && value !== "none";
1048
+ }
1049
+
1050
+ function establishesContainingBlock(style: CSSStyleDeclaration): boolean {
1051
+ const backdrop = (style as CSSStyleDeclaration & { webkitBackdropFilter?: string })
1052
+ .webkitBackdropFilter;
1053
+ return (
1054
+ (style.position !== "" && style.position !== "static") ||
1055
+ isSet(style.transform) ||
1056
+ /transform|perspective/.test(style.willChange) ||
1057
+ isSet(style.filter) ||
1058
+ style.contain === "paint" ||
1059
+ isSet(style.backdropFilter) ||
1060
+ isSet(backdrop)
1061
+ );
1062
+ }
1063
+
1064
+ /**
1065
+ * The element an absolutely positioned overlay is placed relative to, or
1066
+ * `null` for the initial containing block.
1067
+ *
1068
+ * An overlay portalled into a container of the page's own (a transformed
1069
+ * shell, a `position: relative` panel) is offset from THAT box, so page
1070
+ * coordinates put it wherever the container happens to sit away from the
1071
+ * page's origin.
1072
+ */
1073
+ function containingBlock(element: Element): Element | null {
1074
+ const view = ownerWindow(element);
1075
+ const doc = ownerDocument(element);
1076
+ let node = element.parentElement;
1077
+ while (node !== null && node !== doc.documentElement) {
1078
+ if (establishesContainingBlock(view.getComputedStyle(node))) return node;
1079
+ node = node.parentElement;
1080
+ }
1081
+ return null;
1082
+ }
1083
+
1084
+ /**
1085
+ * Place an overlay next to its trigger.
1086
+ *
1087
+ * The order is: try the requested side; flip to the opposite side if it does
1088
+ * not fit, flipping is allowed and the opposite side has more room; then shift
1089
+ * along the cross axis to stay inside the boundary; then cap the height to
1090
+ * what is left. Shifting after
1091
+ * flipping rather than instead of it is what keeps a popover pointing at its
1092
+ * trigger rather than sliding across the screen.
1093
+ */
1094
+ export function overlayPosition(options: PositionOptions): PositionResult {
1095
+ const [position, setPosition] = createSignal<{
1096
+ top: number;
1097
+ left: number;
1098
+ maxHeight: number;
1099
+ maxWidth: number;
1100
+ targetWidth: number;
1101
+ targetHeight: number;
1102
+ originX: number;
1103
+ originY: number;
1104
+ }>({
1105
+ top: 0,
1106
+ left: 0,
1107
+ maxHeight: Number.POSITIVE_INFINITY,
1108
+ maxWidth: Number.POSITIVE_INFINITY,
1109
+ targetWidth: 0,
1110
+ targetHeight: 0,
1111
+ originX: 0,
1112
+ originY: 0,
1113
+ });
1114
+ const [arrowOffset, setArrowOffset] = createSignal<number | undefined>(undefined);
1115
+ const [resolvedAxis, setResolvedAxis] = createSignal<Axis>("bottom");
1116
+
1117
+ const update = (): void => {
1118
+ const target = access(options.targetRef) ?? null;
1119
+ const rect = access(options.targetRect) ?? null;
1120
+ const element = access(options.overlayRef) as Element | null;
1121
+ if (element === null || access(options.isOpen) === false) return;
1122
+ const targetBox = rect ?? (target === null ? null : boxOf(target));
1123
+ if (targetBox === null) return;
1124
+
1125
+ const boundaryElement = access(options.boundaryRef ?? undefined) as Element | null;
1126
+ const view = ownerWindow(element);
1127
+ const viewport = visibleViewport(view);
1128
+ const boundary: Box =
1129
+ boundaryElement !== null && boundaryElement !== undefined ? boxOf(boundaryElement) : viewport;
1130
+
1131
+ // The overlay's LAYOUT size, not its painted one. Every overlay here enters
1132
+ // with `zoom-in-95`, so the first measurement caught it at 95% — a 288px
1133
+ // popover measured 274 and was centred on that, then finished its animation
1134
+ // 7px off its trigger and stayed there. A transform on the thing being
1135
+ // placed must not decide where it goes.
1136
+ const overlayBox = { top: 0, left: 0, ...layoutSize(element) };
1137
+ const offset = access(options.offset) ?? 0;
1138
+ const cross = access(options.crossOffset) ?? 0;
1139
+ const padding = access(options.containerPadding) ?? 12;
1140
+ const direction = access(options.direction) ?? "ltr";
1141
+
1142
+ const [start, align] = resolveAxis(access(options.placement) ?? "bottom", direction);
1143
+ let axis = start;
1144
+
1145
+ // Flip only on the MAIN axis, and to whichever side has more room. Whether
1146
+ // the overlay also overhangs sideways is the cross-axis shift's business,
1147
+ // and an overlay that fits neither side still belongs on the larger one,
1148
+ // where the height cap below costs it least.
1149
+ if (access(options.shouldFlip) !== false) {
1150
+ const size = axis === "top" || axis === "bottom" ? overlayBox.height : overlayBox.width;
1151
+ const room = spaceOn(axis, targetBox, boundary, offset, padding);
1152
+ if (size > room && spaceOn(OPPOSITE[axis], targetBox, boundary, offset, padding) > room) {
1153
+ axis = OPPOSITE[axis];
1154
+ }
1155
+ }
1156
+
1157
+ // What the height may grow to, inside both the boundary and what is
1158
+ // visible of the page.
1159
+ const visibleTop = Math.max(boundary.top, viewport.top);
1160
+ const visibleBottom = Math.min(boundary.top + boundary.height, viewport.top + viewport.height);
1161
+
1162
+ // An arrow is measured by its layout box too: it is usually a rotated
1163
+ // square, and `getBoundingClientRect` reports the box the rotation sweeps
1164
+ // out, wider than the arrow itself.
1165
+ const arrow = access(options.arrowRef ?? undefined) as Element | null;
1166
+ const arrowBox = arrow === null || arrow === undefined ? null : layoutSize(arrow);
1167
+ const vertical = axis === "top" || axis === "bottom";
1168
+ const arrowSize = arrowBox === null ? 0 : vertical ? arrowBox.width : arrowBox.height;
1169
+ const arrowEdge = access(options.arrowBoundaryOffset) ?? 0;
1170
+
1171
+ // Shift along the cross axis, never the main one: moving along the main
1172
+ // axis would detach the overlay from its trigger. An overlay with an arrow
1173
+ // first keeps enough of itself over the trigger for the arrow to point at
1174
+ // it, however far a cross offset asked it to go.
1175
+ const shift = (at: { top: number; left: number }, height: number): void => {
1176
+ if (vertical) {
1177
+ if (arrowSize > 0) {
1178
+ at.left = clamp(
1179
+ at.left,
1180
+ targetBox.left - overlayBox.width + arrowSize + arrowEdge,
1181
+ targetBox.left + targetBox.width - arrowSize - arrowEdge,
1182
+ );
1183
+ }
1184
+ at.left += shiftInto(
1185
+ at.left,
1186
+ overlayBox.width,
1187
+ boundary.left + padding,
1188
+ boundary.left + boundary.width - padding,
1189
+ );
1190
+ } else {
1191
+ if (arrowSize > 0) {
1192
+ at.top = clamp(
1193
+ at.top,
1194
+ targetBox.top - height + arrowSize + arrowEdge,
1195
+ targetBox.top + targetBox.height - arrowSize - arrowEdge,
1196
+ );
1197
+ }
1198
+ at.top += shiftInto(
1199
+ at.top,
1200
+ height,
1201
+ boundary.top + padding,
1202
+ boundary.top + boundary.height - padding,
1203
+ );
1204
+ }
1205
+ };
1206
+
1207
+ let placed = place(targetBox, overlayBox, axis, align, offset, cross);
1208
+ shift(placed, overlayBox.height);
1209
+
1210
+ const maxHeight =
1211
+ axis === "top"
1212
+ ? targetBox.top - offset - visibleTop - padding
1213
+ : axis === "bottom"
1214
+ ? visibleBottom - padding - (targetBox.top + targetBox.height + offset)
1215
+ : align === "bottom" || align === "end"
1216
+ ? placed.top + overlayBox.height - visibleTop - padding
1217
+ : visibleBottom - padding - placed.top;
1218
+
1219
+ // Placed again at the height it will have once capped. An overlay above
1220
+ // its trigger is positioned by its top edge, and it is the capped height
1221
+ // that puts its bottom edge against the trigger.
1222
+ const height = Math.min(overlayBox.height, Math.max(0, maxHeight));
1223
+ placed = place(targetBox, { width: overlayBox.width, height }, axis, align, offset, cross);
1224
+ shift(placed, height);
1225
+
1226
+ // The same question along the other axis. A menu placed to the RIGHT has
1227
+ // the space between its trigger and the boundary edge to grow into, and a
1228
+ // popup asked to fill the available width has no other way to know it: the
1229
+ // overlay is portalled to the body, so a percentage resolves against the
1230
+ // page rather than against anything to do with the trigger.
1231
+ const maxWidth =
1232
+ axis === "left"
1233
+ ? targetBox.left - offset - boundary.left - padding
1234
+ : axis === "right"
1235
+ ? boundary.left + boundary.width - padding - (targetBox.left + targetBox.width + offset)
1236
+ : boundary.width - padding * 2;
1237
+
1238
+ // Where the overlay grows FROM: the point on its own edge nearest the
1239
+ // trigger, so a scale animation appears to come out of the control that
1240
+ // opened it rather than out of the overlay's own middle. After a cross-axis
1241
+ // shift the two are no longer aligned, which is why this is measured from
1242
+ // the trigger's centre and not from the overlay's.
1243
+ const originX =
1244
+ axis === "right"
1245
+ ? 0
1246
+ : axis === "left"
1247
+ ? overlayBox.width
1248
+ : clamp(targetBox.left + targetBox.width / 2 - placed.left, 0, overlayBox.width);
1249
+ const originY =
1250
+ axis === "bottom"
1251
+ ? 0
1252
+ : axis === "top"
1253
+ ? height
1254
+ : clamp(targetBox.top + targetBox.height / 2 - placed.top, 0, height);
1255
+
1256
+ // Everything so far is in client coordinates. Relative to the page, the
1257
+ // scroll offset is part of the answer; relative to a containing block of
1258
+ // the page's own, that block's box and its scroll are.
1259
+ const container = containingBlock(element);
1260
+ let originTop = -view.scrollY;
1261
+ let originLeft = -view.scrollX;
1262
+ if (container !== null) {
1263
+ const containerBox = container.getBoundingClientRect();
1264
+ const style = view.getComputedStyle(container);
1265
+ originTop =
1266
+ containerBox.top + (Number.parseFloat(style.borderTopWidth) || 0) - container.scrollTop;
1267
+ originLeft =
1268
+ containerBox.left + (Number.parseFloat(style.borderLeftWidth) || 0) - container.scrollLeft;
1269
+ }
1270
+
1271
+ setPosition({
1272
+ top: placed.top - originTop,
1273
+ left: placed.left - originLeft,
1274
+ maxHeight: Math.max(0, maxHeight),
1275
+ maxWidth: Math.max(0, maxWidth),
1276
+ targetWidth: targetBox.width,
1277
+ targetHeight: targetBox.height,
1278
+ originX,
1279
+ originY,
1280
+ });
1281
+ setResolvedAxis(axis);
1282
+
1283
+ if (arrowBox !== null) {
1284
+ // Centred on the TARGET, not on the overlay: after a shift the two are
1285
+ // no longer aligned, and the arrow has to keep pointing at the trigger.
1286
+ // Kept over the trigger, then inside the overlay clear of its ends.
1287
+ const from = vertical ? targetBox.left - placed.left : targetBox.top - placed.top;
1288
+ const along = vertical ? targetBox.width : targetBox.height;
1289
+ const extent = vertical ? overlayBox.width : height;
1290
+ const centre = clamp(
1291
+ clamp(from + along / 2, from + arrowSize / 2, from + along - arrowSize / 2),
1292
+ arrowSize / 2 + arrowEdge,
1293
+ extent - arrowSize / 2 - arrowEdge,
1294
+ );
1295
+ setArrowOffset(centre - arrowSize / 2);
1296
+ }
1297
+ };
1298
+
1299
+ if (!isServer) {
1300
+ const onChange = (): void => update();
1301
+ const whileOpen = (ref: ElementRef): Element | null =>
1302
+ access(options.isOpen) === false ? null : (access(ref) as Element | null);
1303
+
1304
+ // The FIRST measurement is taken the moment the ref resolves, which is
1305
+ // before the browser has laid the overlay out: a popover measured 275px
1306
+ // wide, was centred on that, and then rendered at 288px, sitting 7px off
1307
+ // its trigger until something else forced a resize. Observing both boxes
1308
+ // re-places it once the real sizes exist, and again whenever the content
1309
+ // grows.
1310
+ resizeObserver(() => whileOpen(options.targetRef), onChange);
1311
+ resizeObserver(() => whileOpen(options.overlayRef), onChange);
1312
+
1313
+ followOpen(
1314
+ // Everything the placement is computed from, so it is recomputed when the
1315
+ // refs resolve and whenever one of the answers changes. A fresh array
1316
+ // each time: any of them moving is a reason to place again.
1317
+ () =>
1318
+ access(options.isOpen) === false
1319
+ ? null
1320
+ : [
1321
+ access(options.targetRef),
1322
+ access(options.targetRect),
1323
+ access(options.overlayRef),
1324
+ access(options.boundaryRef ?? undefined),
1325
+ access(options.arrowRef ?? undefined),
1326
+ access(options.arrowBoundaryOffset),
1327
+ access(options.placement),
1328
+ access(options.offset),
1329
+ access(options.crossOffset),
1330
+ access(options.shouldFlip),
1331
+ access(options.containerPadding),
1332
+ access(options.direction),
1333
+ ],
1334
+ (measured) => {
1335
+ if (measured === null) return undefined;
1336
+ update();
1337
+
1338
+ const view = window;
1339
+ view.addEventListener("resize", onChange);
1340
+ view.addEventListener("scroll", onChange, true);
1341
+
1342
+ return () => {
1343
+ view.removeEventListener("resize", onChange);
1344
+ view.removeEventListener("scroll", onChange, true);
1345
+ };
1346
+ },
1347
+ );
1348
+ }
1349
+
1350
+ closeOnScroll({
1351
+ triggerRef: options.targetRef,
1352
+ isOpen: options.isOpen,
1353
+ onClose: options.onClose ?? null,
1354
+ });
1355
+
1356
+ return {
1357
+ overlayProps: {
1358
+ style: () => {
1359
+ const current = position();
1360
+ return {
1361
+ position: "absolute",
1362
+ top: `${current.top}px`,
1363
+ left: `${current.left}px`,
1364
+ // On the POSITIONER, which is the positioned element. A popup's own
1365
+ // `z-index` does nothing, because the popup is static — so an overlay
1366
+ // portalled to the body painted in document order and lost to any
1367
+ // page chrome that had a stacking context of its own. Measured on the
1368
+ // gallery: a picker's menu opened underneath the card that owns it.
1369
+ // 50 is what Radix and Base UI both put on theirs.
1370
+ zIndex: 50,
1371
+ maxHeight: Number.isFinite(current.maxHeight) ? `${current.maxHeight}px` : undefined,
1372
+ // What the trigger measures, for an overlay that wants to match it.
1373
+ // A listbox under a combobox is the case: `width: 100%` resolves
1374
+ // against the PORTAL container, which is the body, so a popover asked
1375
+ // to be as wide as its trigger came out as wide as the page.
1376
+ "--barq-trigger-width": `${current.targetWidth}px`,
1377
+ "--barq-trigger-height": `${current.targetHeight}px`,
1378
+ // And what the overlay has to grow into, for one that sizes itself
1379
+ // rather than its trigger. `max-height` above is the same number,
1380
+ // applied; this is the number, for a rule that wants to compute with
1381
+ // it — `w-[calc(var(--available-width)-1.5rem)]` is shadcn's.
1382
+ //
1383
+ // Left UNSET until there is a measurement rather than defaulted to
1384
+ // something plausible: an undefined `var()` makes the declaration
1385
+ // invalid at computed-value time, so the rule reading it falls back
1386
+ // to `width: auto`, which is what an unmeasured overlay should be. A
1387
+ // stand-in number would size it wrongly and look deliberate.
1388
+ ...(Number.isFinite(current.maxWidth)
1389
+ ? { "--barq-available-width": `${current.maxWidth}px` }
1390
+ : {}),
1391
+ ...(Number.isFinite(current.maxHeight)
1392
+ ? { "--barq-available-height": `${current.maxHeight}px` }
1393
+ : {}),
1394
+ "--barq-transform-origin": `${current.originX}px ${current.originY}px`,
1395
+ };
1396
+ },
1397
+ },
1398
+ arrowProps: {
1399
+ style: () => {
1400
+ const offset = arrowOffset();
1401
+ if (offset === undefined) return {};
1402
+ const axis = resolvedAxis();
1403
+ return axis === "top" || axis === "bottom"
1404
+ ? { position: "absolute", left: `${offset}px` }
1405
+ : { position: "absolute", top: `${offset}px` };
1406
+ },
1407
+ "data-placement": resolvedAxis,
1408
+ },
1409
+ placement: resolvedAxis,
1410
+ update,
1411
+ };
1412
+ }
1413
+
1414
+ // ---------------------------------------------------------------------------
1415
+ // Modal
1416
+ // ---------------------------------------------------------------------------
1417
+
1418
+ export interface ModalOverlayOptions extends OverlayOptions {
1419
+ /** Let the page scroll behind the modal. @default false */
1420
+ isScrollDisabled?: MaybeAccessor<boolean | undefined>;
1421
+ /** Nothing outside is hidden from assistive technology, and it is not marked modal. */
1422
+ isNonModal?: MaybeAccessor<boolean | undefined>;
1423
+ /**
1424
+ * Still animating in. The rest of the page is hidden only once it has
1425
+ * arrived: moving a screen reader's cursor into a modal that is still sliding
1426
+ * in scrolls, and on iOS that interrupts the animation. Until then the modal
1427
+ * is only kept visible inside whatever is already hiding the page.
1428
+ *
1429
+ * Moving focus in waits for the same moment, and is the caller's: a focus
1430
+ * scope's `autoFocus`.
1431
+ *
1432
+ * @default false
1433
+ */
1434
+ isEntering?: MaybeAccessor<boolean | undefined>;
1435
+ }
1436
+
1437
+ export interface ModalOverlayResult extends OverlayResult {
1438
+ modalProps: DOMProps;
1439
+ }
1440
+
1441
+ /**
1442
+ * A modal: the page behind it is inert, unscrollable, and invisible to a
1443
+ * screen reader.
1444
+ */
1445
+ export function modalOverlay(
1446
+ options: ModalOverlayOptions,
1447
+ state: OverlayTriggerState,
1448
+ ref: ElementRef,
1449
+ ): ModalOverlayResult {
1450
+ const { overlayProps, underlayProps } = overlay(
1451
+ { ...options, isOpen: state.isOpen, onClose: state.close },
1452
+ ref,
1453
+ );
1454
+
1455
+ preventScroll({
1456
+ isDisabled: () => !state.isOpen() || access(options.isScrollDisabled) === true,
1457
+ });
1458
+
1459
+ followOpen(
1460
+ () =>
1461
+ state.isOpen() && access(options.isNonModal) !== true
1462
+ ? ([(access(ref) as Element | null) ?? null, access(options.isEntering) === true] as const)
1463
+ : null,
1464
+ (open) => {
1465
+ if (open === null || open[0] === null) return undefined;
1466
+ const [element, isEntering] = open;
1467
+ return isEntering ? keepVisible(element) : ariaHideOutside([element]);
1468
+ },
1469
+ );
1470
+
1471
+ return {
1472
+ modalProps: { "data-barq-modal": () => access(options.isNonModal) !== true || undefined },
1473
+ overlayProps,
1474
+ underlayProps,
1475
+ };
1476
+ }
1477
+
1478
+ const overlayStrings = new StringDictionary<"dismiss">({
1479
+ "ar-AE": { dismiss: "تجاهل" },
1480
+ "bg-BG": { dismiss: "Отхвърляне" },
1481
+ "cs-CZ": { dismiss: "Odstranit" },
1482
+ "da-DK": { dismiss: "Luk" },
1483
+ "de-DE": { dismiss: "Schließen" },
1484
+ "el-GR": { dismiss: "Απόρριψη" },
1485
+ "en-US": { dismiss: "Dismiss" },
1486
+ "es-ES": { dismiss: "Descartar" },
1487
+ "et-EE": { dismiss: "Lõpeta" },
1488
+ "fi-FI": { dismiss: "Hylkää" },
1489
+ "fr-FR": { dismiss: "Rejeter" },
1490
+ "he-IL": { dismiss: "התעלם" },
1491
+ "hr-HR": { dismiss: "Odbaci" },
1492
+ "hu-HU": { dismiss: "Elutasítás" },
1493
+ "it-IT": { dismiss: "Ignora" },
1494
+ "ja-JP": { dismiss: "閉じる" },
1495
+ "ko-KR": { dismiss: "무시" },
1496
+ "lt-LT": { dismiss: "Atmesti" },
1497
+ "lv-LV": { dismiss: "Nerādīt" },
1498
+ "nb-NO": { dismiss: "Lukk" },
1499
+ "nl-NL": { dismiss: "Negeren" },
1500
+ "pl-PL": { dismiss: "Zignoruj" },
1501
+ "pt-BR": { dismiss: "Descartar" },
1502
+ "pt-PT": { dismiss: "Dispensar" },
1503
+ "ro-RO": { dismiss: "Revocare" },
1504
+ "ru-RU": { dismiss: "Пропустить" },
1505
+ "sk-SK": { dismiss: "Zrušiť" },
1506
+ "sl-SI": { dismiss: "Opusti" },
1507
+ "sr-SP": { dismiss: "Odbaci" },
1508
+ "sv-SE": { dismiss: "Avvisa" },
1509
+ "tr-TR": { dismiss: "Kapat" },
1510
+ "uk-UA": { dismiss: "Скасувати" },
1511
+ "zh-CN": { dismiss: "取消" },
1512
+ "zh-TW": { dismiss: "關閉" },
1513
+ });
1514
+
1515
+ /**
1516
+ * A button that closes the overlay, rendered at its end and visible only to a
1517
+ * screen reader.
1518
+ *
1519
+ * iOS VoiceOver has no way out of a popover otherwise: the user swipes to the
1520
+ * last element and the next swipe leaves the overlay without closing it.
1521
+ */
1522
+ export function dismissButtonProps(onDismiss: () => void): DOMProps {
1523
+ const message = stringFormatter(overlayStrings);
1524
+ return {
1525
+ type: "button",
1526
+ tabIndex: -1,
1527
+ "aria-label": () => message().format("dismiss"),
1528
+ style: {
1529
+ width: "1px",
1530
+ height: "1px",
1531
+ position: "absolute",
1532
+ overflow: "hidden",
1533
+ clip: "rect(0 0 0 0)",
1534
+ clipPath: "inset(50%)",
1535
+ whiteSpace: "nowrap",
1536
+ border: "0",
1537
+ padding: "0",
1538
+ margin: "-1px",
1539
+ },
1540
+ onClick: onDismiss,
1541
+ };
1542
+ }
1543
+
1544
+ export { TOP_LAYER_ATTRIBUTE };
1545
+
1546
+ /** Mark a subtree as being above every overlay: a toast region. */
1547
+ export function topLayerProps(): DOMProps {
1548
+ return { [TOP_LAYER_ATTRIBUTE]: true };
1549
+ }