@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
package/src/dialog.tsx ADDED
@@ -0,0 +1,1077 @@
1
+ /**
2
+ * Dialogs, modals and popovers.
3
+ *
4
+ * A modal dialog is four separate obligations, and leaving any one out makes
5
+ * the other three pointless:
6
+ *
7
+ * - Focus goes into it when it opens and back where it came from when it
8
+ * closes, and cannot leave while it is open.
9
+ * - Everything else on the page is hidden from assistive technology, or the
10
+ * virtual cursor walks straight out of the dialog into content the user
11
+ * cannot see or reach.
12
+ * - The page behind does not scroll.
13
+ * - Escape closes it, and an interaction outside closes it if it is
14
+ * dismissable — the TOP one only, so a menu inside a dialog closes the menu.
15
+ *
16
+ * A popover is the same minus the modality: focus is contained but the rest of
17
+ * the page is still there.
18
+ */
19
+
20
+ import {
21
+ cells,
22
+ type Accessor,
23
+ type Child,
24
+ createEffect,
25
+ type Incoming,
26
+ isDev,
27
+ onCleanup,
28
+ onSettled,
29
+ Show,
30
+ createSignal,
31
+ untrack,
32
+ } from "@barqjs/core";
33
+ import { Portal } from "@barqjs/web";
34
+ import { ref as makeRef, mergeRefs, type RefTarget } from "@barqjs/primitives/refs";
35
+
36
+ import { focusScope, type FocusScopeOptions } from "./focus.ts";
37
+ import { declaredDirection, useLocale } from "./i18n.ts";
38
+ import type { ElementRef } from "./interactions/press.ts";
39
+ import {
40
+ alignOf,
41
+ ariaHideOutside,
42
+ dismissButtonProps,
43
+ followOpen,
44
+ keepVisible,
45
+ modalOverlay,
46
+ overlay,
47
+ portalContainer,
48
+ usePortalTarget,
49
+ withPortalTarget,
50
+ overlayPosition,
51
+ overlayTrigger,
52
+ overlayTriggerState,
53
+ preventScroll,
54
+ type Align,
55
+ type AnchorRect,
56
+ type Axis,
57
+ type OverlayOptions,
58
+ type OverlayTriggerState,
59
+ type Placement,
60
+ } from "./overlays.ts";
61
+ import { OverlayArrowProvider } from "./overlay-arrow.tsx";
62
+ import { presence } from "./presence.ts";
63
+ import {
64
+ access,
65
+ type DOMProps,
66
+ filterDOMProps,
67
+ fromProps,
68
+ id,
69
+ type MaybeAccessor,
70
+ clearTriggerSlot,
71
+ mergeProps,
72
+ type StyleProps,
73
+ styleProps,
74
+ } from "./utils.ts";
75
+
76
+ export interface DialogOptions {
77
+ /** @default "dialog" */
78
+ role?: MaybeAccessor<"dialog" | "alertdialog" | undefined>;
79
+ "aria-label"?: MaybeAccessor<string | undefined>;
80
+ "aria-labelledby"?: MaybeAccessor<string | undefined>;
81
+ "aria-describedby"?: MaybeAccessor<string | undefined>;
82
+ }
83
+
84
+ export interface DialogResult {
85
+ dialogProps: DOMProps;
86
+ /** For the heading that names the dialog. */
87
+ titleProps: DOMProps;
88
+ /** For the element that describes it. */
89
+ descriptionProps: DOMProps;
90
+ /** The same id, for a component that builds its own props. */
91
+ descriptionId: Accessor<string>;
92
+ /**
93
+ * Whether a description is on screen, which is what makes the dialog point
94
+ * at one.
95
+ *
96
+ * A dialog that names an `aria-describedby` no element carries is announced
97
+ * with nothing where the description should be, so the attribute appears
98
+ * only once something has registered and goes again when it leaves.
99
+ */
100
+ readonly describe: (has: boolean) => void;
101
+ /** The same for the title, which is what makes the dialog point at it. */
102
+ readonly title: (has: boolean) => void;
103
+ }
104
+
105
+ /**
106
+ * A dialog's own props.
107
+ *
108
+ * `tabIndex={-1}` is not decoration: when a dialog holds nothing focusable,
109
+ * focus has to land on the dialog itself or it falls to the body, outside the
110
+ * focus scope that is supposed to be containing it.
111
+ */
112
+ export function dialog(options: DialogOptions = {}): DialogResult {
113
+ const titleId = id();
114
+ const descriptionId = id();
115
+ // A count and not a flag: two descriptions is a mistake, but one leaving
116
+ // while the other stays must not take the attribute with it.
117
+ // A description registers from its own component body, so the write is one
118
+ // the body makes on purpose.
119
+ const [described, setDescribed] = createSignal(0, { ownedWrite: true });
120
+ const [titled, setTitled] = createSignal(0, { ownedWrite: true });
121
+ // The title's id is written until the dialog has settled, which is all the
122
+ // server ever renders: a title registers from an effect, and there are no
123
+ // effects there. Once settled, it is written only while a title is present,
124
+ // so a dialog without one points at nothing.
125
+ const [settled, setSettled] = createSignal(false);
126
+ onSettled(() => {
127
+ setSettled(true);
128
+ });
129
+ const labelled = (): string | undefined =>
130
+ access(options["aria-labelledby"]) ?? (titled() > 0 || !settled() ? titleId() : undefined);
131
+
132
+ return {
133
+ titleProps: { id: titleId },
134
+ descriptionProps: { id: descriptionId },
135
+ descriptionId,
136
+ describe: (has) => setDescribed((n) => n + (has ? 1 : -1)),
137
+ title: (has) => setTitled((n) => n + (has ? 1 : -1)),
138
+ dialogProps: mergeProps(filterDOMProps(options, { labelable: true }), {
139
+ role: () => access(options.role) ?? "dialog",
140
+ tabIndex: -1,
141
+ "aria-label": () => access(options["aria-label"]),
142
+ "aria-labelledby": () =>
143
+ access(options["aria-label"]) === undefined ? labelled() : undefined,
144
+ // Only the fallback. `filterDOMProps` already forwarded the caller's
145
+ // own, and `mergeProps` COMBINES this attribute rather than replacing
146
+ // it, so returning it here again wrote it twice.
147
+ "aria-describedby": () =>
148
+ access(options["aria-describedby"]) === undefined && described() > 0
149
+ ? descriptionId()
150
+ : undefined,
151
+ }),
152
+ };
153
+ }
154
+
155
+ // ---------------------------------------------------------------------------
156
+ // Components
157
+ // ---------------------------------------------------------------------------
158
+
159
+ export interface DialogComponentProps extends StyleProps {
160
+ children?: Child;
161
+ /** @default "dialog" */
162
+ role?: "dialog" | "alertdialog";
163
+ "aria-label"?: string;
164
+ "aria-labelledby"?: string;
165
+ /** In place of the description the dialog finds for itself. */
166
+ "aria-describedby"?: string;
167
+ ref?: RefTarget<HTMLElement>;
168
+ }
169
+
170
+ /**
171
+ * The dialog itself, without any of the overlay behaviour.
172
+ *
173
+ * Use it inside {@link Modal} or {@link Popover}, which supply the focus
174
+ * scope, the dismissal and the modality.
175
+ *
176
+ * ```tsx
177
+ * <Dialog>
178
+ * <Heading slot="title">Delete?</Heading>
179
+ * <Button onPress={close}>Cancel</Button>
180
+ * </Dialog>
181
+ * ```
182
+ */
183
+ export function Dialog(props: DialogComponentProps) {
184
+ const domRef = makeRef<HTMLElement>();
185
+ const options = fromProps(cells(props));
186
+ const { dialogProps, titleProps, descriptionId, describe, title } = dialog(options);
187
+
188
+ provideDialog({ titleProps, descriptionId, describe, title });
189
+
190
+ if (isDev) {
191
+ onSettled(() => {
192
+ // After the title has had its chance to register, which happens as the
193
+ // content settles.
194
+ queueMicrotask(() => {
195
+ const element = domRef();
196
+ if (element === null || !element.isConnected) return;
197
+ if (element.hasAttribute("aria-label") || element.hasAttribute("aria-labelledby")) return;
198
+ console.warn(
199
+ 'A Dialog with no <Heading slot="title"> needs an aria-label or an aria-labelledby, or a screen reader announces it with no name.',
200
+ );
201
+ });
202
+ });
203
+ }
204
+
205
+ const elementProps = mergeProps(
206
+ dialogProps,
207
+ filterDOMProps(options, { global: true }),
208
+ styleProps(cells(props)),
209
+ {
210
+ "data-testid": () => props["data-testid"],
211
+ },
212
+ );
213
+
214
+ return (
215
+ <section {...elementProps} ref={mergeRefs(domRef.set, props.ref)}>
216
+ {props.children}
217
+ </section>
218
+ );
219
+ }
220
+
221
+ export interface HeadingComponentProps extends StyleProps {
222
+ children?: Child;
223
+ /** `title` names the enclosing dialog. */
224
+ slot?: "title";
225
+ /** @default 3 */
226
+ level?: 1 | 2 | 3 | 4 | 5 | 6;
227
+ }
228
+
229
+ /**
230
+ * A heading. With `slot="title"` it becomes the enclosing dialog's name.
231
+ *
232
+ * The level is a real `<h1>`–`<h6>`, not `role="heading" aria-level`, because
233
+ * the platform's own headings are what a screen reader's heading list is built
234
+ * from.
235
+ */
236
+ export function Heading(props: HeadingComponentProps) {
237
+ const slots = getContext(DialogSlotsContext) ?? null;
238
+ const title = slots?.titleProps ?? null;
239
+
240
+ // Only a heading that says it is the title names the dialog, and only for
241
+ // as long as it is there.
242
+ createEffect(
243
+ () => props.slot === "title",
244
+ (isTitle) => {
245
+ if (!isTitle || slots === null) return undefined;
246
+ slots.title(true);
247
+ return () => slots.title(false);
248
+ },
249
+ );
250
+
251
+ const elementProps = mergeProps(
252
+ filterDOMProps(fromProps(cells(props)), { global: true }),
253
+ styleProps(cells(props)),
254
+ {
255
+ // The title names the dialog only when it says it is the title.
256
+ id: () =>
257
+ props.slot === "title" ? access(title?.id as MaybeAccessor<string | undefined>) : props.id,
258
+ "aria-level": () => props.level ?? 3,
259
+ "data-testid": () => props["data-testid"],
260
+ },
261
+ );
262
+
263
+ return <h3 {...elementProps}>{props.children}</h3>;
264
+ }
265
+
266
+ export interface ModalComponentProps extends StyleProps, OverlayOptions {
267
+ children?: Child;
268
+ isOpen?: boolean;
269
+ defaultOpen?: boolean;
270
+ /** @default true */
271
+ isDismissable?: boolean;
272
+ isKeyboardDismissDisabled?: boolean;
273
+ /**
274
+ * Leave the page behind usable: Tab may leave, nothing behind is hidden from
275
+ * assistive technology, the page still scrolls, and a press outside does not
276
+ * close it. Escape still does. @default false
277
+ */
278
+ isNonModal?: boolean;
279
+ /** Move focus inside when it opens. @default true */
280
+ autoFocus?: boolean;
281
+ /**
282
+ * The class for the UNDERLAY — the element covering the page behind the
283
+ * dialog.
284
+ *
285
+ * `class` styles the dialog. The underlay is a second element with a second
286
+ * job, and a design system has to be able to dim the page: without this it
287
+ * could only be reached by a global rule on `[data-barq-underlay]`, which
288
+ * every modal on the page would then share.
289
+ */
290
+ underlayClass?: string;
291
+ underlaySlot?: string;
292
+ /**
293
+ * Anything else the underlay should carry: a second class, a `data-*`, a
294
+ * handler. A design system's own overlay part is written by the caller and
295
+ * rendered here, so what the caller gave it has to arrive on this element.
296
+ */
297
+ underlayProps?: DOMProps;
298
+ onOpenChange?: (isOpen: boolean) => void;
299
+ /** The element `class` and `style` land on. */
300
+ ref?: RefTarget<HTMLDivElement>;
301
+ }
302
+
303
+ /**
304
+ * A modal: contained focus, an inert page behind it, no scrolling, and Escape.
305
+ *
306
+ * Renders nothing while closed. There is no hidden-but-present state, because
307
+ * a dialog that exists in the DOM while closed is a dialog a screen reader can
308
+ * still find.
309
+ */
310
+ /** A `dir` the caller wrote on the component, which wins over the one in scope. */
311
+ function callerDirection(options: object): string | undefined {
312
+ return access((options as { dir?: MaybeAccessor<string | undefined> }).dir);
313
+ }
314
+
315
+ export function Modal(props: ModalComponentProps) {
316
+ clearTriggerSlot();
317
+ const options = fromProps(cells(props));
318
+ const state = overlayTriggerState(options);
319
+ // Read here, where the modal is written. What it draws is portalled out from
320
+ // under the element that carries `dir`.
321
+ const direction = declaredDirection();
322
+
323
+ return (
324
+ <ModalContents
325
+ isOpen={state.isOpen()}
326
+ onClose={state.close}
327
+ isDismissable={props.isDismissable !== false}
328
+ isKeyboardDismissDisabled={props.isKeyboardDismissDisabled === true}
329
+ isNonModal={props.isNonModal === true}
330
+ autoFocus={props.autoFocus !== false}
331
+ underlayClass={props.underlayClass}
332
+ underlaySlot={props.underlaySlot}
333
+ underlayProps={props.underlayProps}
334
+ class={props.class ?? props.className}
335
+ style={props.style}
336
+ // The global attributes, the global events and every `data-*` the caller
337
+ // gave THIS component, forwarded to the element the caller can see. They
338
+ // cannot be spread on `<ModalContents>` itself: it is a private component
339
+ // with its own props, and a `data-slot` landing there would be a prop it
340
+ // does not have rather than an attribute on the dialog.
341
+ domProps={mergeProps(filterDOMProps(options, { global: true }), {
342
+ dir: () => callerDirection(options) ?? direction(),
343
+ })}
344
+ contentRef={props.ref}
345
+ >
346
+ {props.children}
347
+ </ModalContents>
348
+ );
349
+ }
350
+
351
+ interface ContentsProps extends StyleProps {
352
+ isOpen: boolean;
353
+ onClose: () => void;
354
+ isDismissable: boolean;
355
+ isKeyboardDismissDisabled: boolean;
356
+ isNonModal: boolean;
357
+ autoFocus: boolean;
358
+ underlayClass?: string;
359
+ underlaySlot?: string;
360
+ underlayProps?: DOMProps;
361
+ /** What `Modal` filtered out of its own props for the dialog's element. */
362
+ domProps?: DOMProps;
363
+ contentRef?: RefTarget<HTMLDivElement>;
364
+ children?: Child;
365
+ }
366
+
367
+ /**
368
+ * The modal's body, mounted while it is open and for as long as it takes to
369
+ * leave.
370
+ *
371
+ * A dialog that stays in the DOM while CLOSED is a dialog a screen reader can
372
+ * still find, so there is no hidden-but-present state to style. `presence`
373
+ * holds it only while the stylesheet is still drawing it, marked `data-closed`
374
+ * — and when nothing is animating, that is no time at all.
375
+ */
376
+ function ModalContents(props: ContentsProps) {
377
+ // `<Show>`, not a bare `{() => …}`: a Cell at a component's root travels in
378
+ // the array its caller places, and an array hole is ONE effect — so the
379
+ // condition would become a dependency of whatever hole holds this component,
380
+ // and opening the modal would rebuild every sibling around it.
381
+ const target = usePortalTarget();
382
+ // The ref lives HERE and the focus scope does not. The scope has to be
383
+ // created with the content it contains, because its disposal is what restores
384
+ // focus; the ref only has to outlive the content so the exit can be measured.
385
+ const domRef = makeRef<HTMLDivElement>();
386
+ const gate = presence({ isOpen: cells(props).isOpen, ref: domRef });
387
+
388
+ return (
389
+ <Show when={gate.isPresent()}>
390
+ <Portal mount={portalContainer(target)}>
391
+ <ModalBody
392
+ domRef={domRef}
393
+ isExiting={gate.isExiting()}
394
+ onClose={props.onClose}
395
+ isDismissable={props.isDismissable}
396
+ isKeyboardDismissDisabled={props.isKeyboardDismissDisabled}
397
+ isNonModal={props.isNonModal}
398
+ autoFocus={props.autoFocus}
399
+ underlayClass={props.underlayClass}
400
+ underlaySlot={props.underlaySlot}
401
+ underlayProps={props.underlayProps}
402
+ domProps={props.domProps}
403
+ contentRef={props.contentRef}
404
+ class={props.class}
405
+ style={props.style}
406
+ >
407
+ {props.children}
408
+ </ModalBody>
409
+ </Portal>
410
+ </Show>
411
+ );
412
+ }
413
+
414
+ interface BodyProps extends StyleProps {
415
+ domRef: ReturnType<typeof makeRef<HTMLDivElement>>;
416
+ isExiting: boolean;
417
+ onClose: () => void;
418
+ isDismissable: boolean;
419
+ isKeyboardDismissDisabled: boolean;
420
+ isNonModal: boolean;
421
+ autoFocus: boolean;
422
+ underlayClass?: string;
423
+ underlaySlot?: string;
424
+ underlayProps?: DOMProps;
425
+ domProps?: DOMProps;
426
+ contentRef?: RefTarget<HTMLDivElement>;
427
+ children?: Child;
428
+ }
429
+
430
+ /**
431
+ * Inside the `<Show>`, and that is the whole reason it is a component.
432
+ *
433
+ * The focus scope has to be created WITH the content it contains: closing the
434
+ * modal disposes this subtree, and disposal is what restores focus to whatever
435
+ * opened it. Called one level up — in `ModalContents`, beside the `<Show>` —
436
+ * the scope outlives every open and close, so nothing was ever disposed and
437
+ * focus was left on `<body>`. No test saw it: happy-dom leaves `activeElement`
438
+ * on an element after it is removed, so the assertion passed for the wrong
439
+ * reason.
440
+ */
441
+ function ModalBody(props: BodyProps) {
442
+ const domRef = props.domRef;
443
+ const scope = focusScope({
444
+ contain: () => !props.isNonModal,
445
+ restoreFocus: true,
446
+ autoFocus: () => props.autoFocus,
447
+ });
448
+
449
+ const state: OverlayTriggerState = {
450
+ isOpen: () => true,
451
+ setOpen: (open) => {
452
+ if (!open) props.onClose();
453
+ },
454
+ open: () => {},
455
+ close: () => props.onClose(),
456
+ toggle: () => props.onClose(),
457
+ };
458
+
459
+ const { overlayProps, underlayProps, modalProps } = modalOverlay(
460
+ {
461
+ isDismissable: () => props.isDismissable && !props.isNonModal,
462
+ isKeyboardDismissDisabled: () => props.isKeyboardDismissDisabled,
463
+ isScrollDisabled: () => props.isNonModal,
464
+ isNonModal: () => props.isNonModal,
465
+ // Focus is free to leave a dialog that is not modal, and Escape still
466
+ // belongs to it wherever focus went.
467
+ shouldCloseOnEscapeAnywhere: () => props.isNonModal,
468
+ },
469
+ state,
470
+ domRef,
471
+ );
472
+
473
+ const elementProps = mergeProps(
474
+ overlayProps,
475
+ modalProps,
476
+ props.domProps ?? null,
477
+ styleProps(cells(props)),
478
+ );
479
+
480
+ // The caller's class joins the component's own rather than replacing it,
481
+ // and every other key is the caller's to set.
482
+ const underlay = mergeProps(
483
+ underlayProps,
484
+ {
485
+ class: () => props.underlayClass,
486
+ // A `data-slot` like every other element in this package, and the reason
487
+ // is a consumer's stylesheet: `[data-barq-underlay]` is one global rule
488
+ // and cannot tell a dialog's backdrop from a sheet's. shadcn names them
489
+ // separately (`cn-dialog-overlay`, `cn-sheet-overlay`) and so can anyone
490
+ // styling these.
491
+ "data-slot": () => props.underlaySlot,
492
+ },
493
+ // Taken once, as the body is built: the underlay's own attributes are
494
+ // accessors already, and the set of them does not change while it is open.
495
+ untrack(() => props.underlayProps) ?? null,
496
+ );
497
+
498
+ return (
499
+ <div
500
+ {...underlay}
501
+ data-barq-underlay
502
+ data-closed={props.isExiting ? "" : undefined}
503
+ data-state={props.isExiting ? "closed" : "open"}
504
+ >
505
+ <span hidden ref={scope.startRef} />
506
+ <div
507
+ {...elementProps}
508
+ data-non-modal={props.isNonModal ? "" : undefined}
509
+ data-closed={props.isExiting ? "" : undefined}
510
+ data-state={props.isExiting ? "closed" : "open"}
511
+ ref={mergeRefs(domRef.set, props.contentRef)}
512
+ >
513
+ <Show when={props.isDismissable && !props.isNonModal}>
514
+ <DismissButton onDismiss={props.onClose} />
515
+ </Show>
516
+ {props.children}
517
+ </div>
518
+ <span hidden ref={scope.endRef} />
519
+ </div>
520
+ );
521
+ }
522
+
523
+ export interface PopoverComponentProps extends StyleProps {
524
+ children?: Child;
525
+ /**
526
+ * The element the popover is anchored to. Without it, the trigger in scope
527
+ * ({@link providePopoverTrigger}) is.
528
+ */
529
+ triggerRef?: ElementRef;
530
+ /**
531
+ * A box to place against instead of the trigger's own, in client
532
+ * coordinates. A context menu passes the point the pointer was at.
533
+ */
534
+ triggerRect?: AnchorRect | null;
535
+ isOpen?: boolean;
536
+ defaultOpen?: boolean;
537
+ /** @default "bottom" */
538
+ placement?: Placement;
539
+ /** @default 8 */
540
+ offset?: number;
541
+ crossOffset?: number;
542
+ shouldFlip?: boolean;
543
+ containerPadding?: number;
544
+ /** @default true */
545
+ isDismissable?: boolean;
546
+ isKeyboardDismissDisabled?: boolean;
547
+ /** Hide the rest of the page from assistive technology. @default false */
548
+ isModal?: boolean;
549
+ /**
550
+ * Opened from inside another popover, so it joins that one's group.
551
+ *
552
+ * A submenu sets it. Without it a popover portals to the body and counts as
553
+ * a separate overlay, and a press inside it closes the one it came from.
554
+ */
555
+ isNested?: boolean;
556
+ /**
557
+ * Move focus in when it opens, hold it there, and give it back on closing.
558
+ *
559
+ * `false` for a popover that opens while the user is somewhere else and must
560
+ * not take the keyboard from there: a hover card opened by resting the
561
+ * pointer, or by focus arriving on its trigger, which a focus scope would
562
+ * immediately pull away again.
563
+ *
564
+ * @default true
565
+ */
566
+ shouldContainFocus?: boolean;
567
+ onOpenChange?: (isOpen: boolean) => void;
568
+ "aria-label"?: string;
569
+ "aria-labelledby"?: string;
570
+ "aria-describedby"?: string;
571
+ /** The positioned element, which `class` and `style` land on. */
572
+ ref?: RefTarget<HTMLDivElement>;
573
+ }
574
+
575
+ /**
576
+ * A popover anchored to a trigger: positioned, dismissable, focus-contained.
577
+ *
578
+ * Not modal by default. A popover the user can still reach the page behind is
579
+ * the right default for a menu or a colour picker; a date picker that must not
580
+ * be escaped sets `isModal`.
581
+ */
582
+ export function Popover(props: PopoverComponentProps) {
583
+ clearTriggerSlot();
584
+ const direction = declaredDirection();
585
+ const domRef = makeRef<HTMLDivElement>();
586
+ const options = fromProps(cells(props));
587
+ const trigger = usePopoverTrigger();
588
+ const own = overlayTriggerState(options);
589
+ // The trigger in scope owns the state, unless this popover was told its own.
590
+ const fromTrigger = (): boolean =>
591
+ trigger !== null && props.isOpen === undefined && props.defaultOpen === undefined;
592
+ const state: OverlayTriggerState = {
593
+ isOpen: () => (fromTrigger() ? (trigger?.state.isOpen() ?? false) : own.isOpen()),
594
+ setOpen: (open) => {
595
+ if (fromTrigger()) trigger?.state.setOpen(open);
596
+ else own.setOpen(open);
597
+ },
598
+ open: () => state.setOpen(true),
599
+ close: () => state.setOpen(false),
600
+ toggle: () => state.setOpen(!state.isOpen()),
601
+ };
602
+ const containsFocus = (): boolean =>
603
+ (props.shouldContainFocus ?? access(trigger?.shouldContainFocus)) !== false;
604
+ const locale = useLocale();
605
+ const placement = (): Placement => props.placement ?? "bottom";
606
+
607
+ const arrowRef = makeRef<Element>();
608
+ const position = overlayPosition({
609
+ targetRef: () => access(props.triggerRef ?? trigger?.triggerRef),
610
+ targetRect: () => props.triggerRect ?? null,
611
+ overlayRef: domRef,
612
+ arrowRef,
613
+ placement,
614
+ direction: () => locale().direction,
615
+ offset: () => props.offset ?? 8,
616
+ crossOffset: () => props.crossOffset,
617
+ shouldFlip: () => props.shouldFlip,
618
+ containerPadding: () => props.containerPadding,
619
+ isOpen: state.isOpen,
620
+ onClose: state.close,
621
+ });
622
+
623
+ // A popover opened from INSIDE another one — a submenu — is portalled into
624
+ // the outer popover's own container rather than into the body, so that the
625
+ // two are one overlay as far as an outside press and `aria-hidden` are
626
+ // concerned. Pressing a submenu item is not a press outside its menu.
627
+ const group = usePopoverGroup();
628
+ const nested = group !== null && props.isNested === true;
629
+ const groupRef = makeRef<HTMLDivElement>();
630
+
631
+ const { overlayProps } = overlay(
632
+ {
633
+ isOpen: state.isOpen,
634
+ onClose: state.close,
635
+ isDismissable: () => props.isDismissable !== false,
636
+ isKeyboardDismissDisabled: () => props.isKeyboardDismissDisabled === true,
637
+ // Focus was never moved in, so Escape arrives wherever it already was.
638
+ shouldCloseOnEscapeAnywhere: () => !containsFocus(),
639
+ shouldCloseOnBlur: true,
640
+ groupRef: nested ? group : groupRef,
641
+ },
642
+ domRef,
643
+ );
644
+
645
+ preventScroll({ isDisabled: () => !state.isOpen() || props.isModal !== true });
646
+
647
+ // A modal popover hides the rest of the page. One that is not still has to
648
+ // be exempt from whatever is hiding the page around it: a list opened from
649
+ // inside a modal dialog is portalled out of the dialog, and the dialog's own
650
+ // hiding would otherwise take it for more of the page behind.
651
+ followOpen(
652
+ () =>
653
+ state.isOpen()
654
+ ? ([
655
+ ((nested ? access(group) : groupRef()) as Element | null) ?? null,
656
+ props.isModal === true,
657
+ ] as const)
658
+ : null,
659
+ (open) => {
660
+ if (open === null || open[0] === null) return undefined;
661
+ const [element, isModal] = open;
662
+ return isModal ? ariaHideOutside([element], { shouldUseInert: true }) : keepVisible(element);
663
+ },
664
+ );
665
+
666
+ const elementProps = mergeProps(
667
+ overlayProps,
668
+ position.overlayProps,
669
+ trigger?.overlayProps ?? null,
670
+ filterDOMProps(options, { global: true, labelable: true }),
671
+ // Portalled out from under the element that carries `dir`.
672
+ { dir: () => callerDirection(options) ?? direction() },
673
+ styleProps(cells(props)),
674
+ {
675
+ "data-placement": position.placement,
676
+ "data-side": position.placement,
677
+ "data-align": () => alignOf(placement()),
678
+ "data-testid": () => props["data-testid"],
679
+ },
680
+ );
681
+
682
+ const target = usePortalTarget();
683
+ const mount = (): Element | null =>
684
+ nested
685
+ ? ((access(group) as Element | null) ?? portalContainer(target))
686
+ : portalContainer(target);
687
+
688
+ const gate = presence({ isOpen: state.isOpen, ref: domRef });
689
+ const placed: PopoverPlacement = {
690
+ side: position.placement,
691
+ align: () => alignOf(placement()),
692
+ isExiting: gate.isExiting,
693
+ };
694
+
695
+ return (
696
+ <Show when={gate.isPresent()}>
697
+ <Portal mount={mount()}>
698
+ {/* `display: contents` so the container lays nothing out. It exists to
699
+ be a PLACE: what a nested popover portals into, and what
700
+ `aria-hidden` and outside-press detection treat as the whole
701
+ overlay. A nested popover passes the ROOT's container down rather
702
+ than its own, so a submenu three deep is still one group. */}
703
+ <div ref={groupRef.set} style={{ display: "contents" }}>
704
+ <PopoverGroupProvider value={nested && group !== null ? group : groupRef} placed={placed}>
705
+ <OverlayArrowProvider
706
+ value={{
707
+ placement: position.placement,
708
+ arrowProps: position.arrowProps,
709
+ ref: arrowRef.set,
710
+ }}
711
+ >
712
+ <PopoverBody
713
+ elementProps={elementProps}
714
+ domRef={domRef}
715
+ forwardedRef={props.ref}
716
+ isExiting={gate.isExiting()}
717
+ containsFocus={containsFocus()}
718
+ isModal={props.isModal === true}
719
+ onDismiss={state.close}
720
+ >
721
+ {props.children}
722
+ </PopoverBody>
723
+ </OverlayArrowProvider>
724
+ </PopoverGroupProvider>
725
+ </div>
726
+ </Portal>
727
+ </Show>
728
+ );
729
+ }
730
+
731
+ interface PopoverBodyProps {
732
+ elementProps: DOMProps;
733
+ domRef: ReturnType<typeof makeRef<HTMLDivElement>>;
734
+ forwardedRef?: RefTarget<HTMLDivElement>;
735
+ isExiting: boolean;
736
+ containsFocus: boolean;
737
+ isModal: boolean;
738
+ onDismiss: () => void;
739
+ children?: Child;
740
+ }
741
+
742
+ /**
743
+ * Inside the `<Show>`, for the same reason `ModalBody` is.
744
+ *
745
+ * The focus scope has to be created WITH the content it contains: closing the
746
+ * popover disposes this subtree, and disposal is what restores focus to the
747
+ * trigger. Called in `Popover`'s own body the scope outlives every open and
748
+ * close, so nothing is ever disposed and focus is left on `<body>`.
749
+ */
750
+ function PopoverBody(props: PopoverBodyProps) {
751
+ const domRef = props.domRef;
752
+ const setElement = mergeRefs(domRef.set, props.forwardedRef);
753
+
754
+ // Read once: a popover does not change its mind about focus while it is open,
755
+ // and a scope that came and went with a prop would restore focus mid-flight.
756
+ if (!props.containsFocus) {
757
+ return (
758
+ <div
759
+ {...props.elementProps}
760
+ data-closed={props.isExiting ? "" : undefined}
761
+ data-state={props.isExiting ? "closed" : "open"}
762
+ ref={setElement}
763
+ >
764
+ <Show when={props.isModal}>
765
+ <DismissButton onDismiss={props.onDismiss} />
766
+ </Show>
767
+ {props.children}
768
+ <Show when={props.isModal}>
769
+ <DismissButton onDismiss={props.onDismiss} />
770
+ </Show>
771
+ </div>
772
+ );
773
+ }
774
+
775
+ const scope = focusScope({ contain: true, restoreFocus: true, autoFocus: true });
776
+
777
+ return (
778
+ <>
779
+ <span hidden ref={scope.startRef} />
780
+ <div
781
+ {...props.elementProps}
782
+ data-closed={props.isExiting ? "" : undefined}
783
+ data-state={props.isExiting ? "closed" : "open"}
784
+ ref={setElement}
785
+ >
786
+ <Show when={props.isModal}>
787
+ <DismissButton onDismiss={props.onDismiss} />
788
+ </Show>
789
+ {props.children}
790
+ <Show when={props.isModal}>
791
+ <DismissButton onDismiss={props.onDismiss} />
792
+ </Show>
793
+ </div>
794
+ <span hidden ref={scope.endRef} />
795
+ </>
796
+ );
797
+ }
798
+
799
+ export interface DismissButtonComponentProps {
800
+ /** Called when a screen reader activates it. */
801
+ onDismiss?: () => void;
802
+ /** @default "Dismiss", in the locale in scope */
803
+ "aria-label"?: string;
804
+ "aria-labelledby"?: string;
805
+ id?: string;
806
+ }
807
+
808
+ /**
809
+ * A button only a screen reader can find, that closes the overlay it is in.
810
+ *
811
+ * iOS VoiceOver has no Escape key: without one of these at the end of a
812
+ * popover, swiping past its last element leaves the popover open behind the
813
+ * user with no way back to close it.
814
+ */
815
+ export function DismissButton(props: DismissButtonComponentProps) {
816
+ const elementProps = mergeProps(
817
+ dismissButtonProps(() => props.onDismiss?.()),
818
+ filterDOMProps(fromProps(cells(props)), { labelable: true }),
819
+ );
820
+ return <button {...elementProps} />;
821
+ }
822
+
823
+ export interface DialogTriggerComponentProps {
824
+ children?: Child;
825
+ isOpen?: boolean;
826
+ defaultOpen?: boolean;
827
+ onOpenChange?: (isOpen: boolean) => void;
828
+ }
829
+
830
+ /**
831
+ * A trigger and the overlay it opens, sharing one piece of state.
832
+ *
833
+ * ```tsx
834
+ * const state = useDialogTrigger();
835
+ * <Button onPress={state.toggle}>Open</Button>
836
+ * <Modal isOpen={state.isOpen()} onOpenChange={state.setOpen}>…</Modal>
837
+ * ```
838
+ */
839
+ export function DialogTrigger(props: Incoming<DialogTriggerComponentProps>) {
840
+ const options = fromProps(props);
841
+ const state = overlayTriggerState(options);
842
+ const { triggerProps, overlayProps } = overlayTrigger({ type: "dialog" }, state);
843
+
844
+ return provideDialogTrigger({ state, triggerProps, overlayProps }, () => props.children);
845
+ }
846
+
847
+ // ---------------------------------------------------------------------------
848
+ // Contexts
849
+ // ---------------------------------------------------------------------------
850
+
851
+ import { createContext, getContext, getOwner, install, provide } from "@barqjs/core";
852
+
853
+ /**
854
+ * The container a group of popovers is portalled into.
855
+ *
856
+ * A ROOT popover renders one and offers it here; a nested one — a submenu —
857
+ * portals into it rather than into the body. That is what keeps the two
858
+ * together for `aria-hidden` and for outside-press detection while still
859
+ * taking the nested one out of its trigger's DOM.
860
+ */
861
+ const PopoverGroupContext = createContext<ElementRef | null>(null);
862
+
863
+ /**
864
+ * What opens a popover, for a {@link Popover} written inside it with no
865
+ * `triggerRef` and no `isOpen` of its own.
866
+ */
867
+ export interface PopoverTriggerValue {
868
+ /** The element the popover is anchored to. */
869
+ triggerRef: ElementRef;
870
+ /** Whether it is open, and how the popover closes it. */
871
+ state: OverlayTriggerState;
872
+ /** Props for the popover's own element: the id the trigger points at, handlers. */
873
+ overlayProps?: DOMProps;
874
+ /** @default true */
875
+ shouldContainFocus?: MaybeAccessor<boolean | undefined>;
876
+ }
877
+
878
+ const PopoverTriggerContext = createContext<PopoverTriggerValue | null>(null);
879
+
880
+ /**
881
+ * Offer a trigger to the popovers written inside `children`.
882
+ *
883
+ * A trigger of a new kind (a hover preview, a toolbar's overflow) provides
884
+ * this and renders the ordinary `<Popover>`, rather than a popover component
885
+ * of its own that passes the same four props through.
886
+ */
887
+ export function providePopoverTrigger(value: PopoverTriggerValue, children: () => Child): Child {
888
+ return provide(
889
+ PopoverTriggerContext,
890
+ () => value,
891
+ () => children() as unknown,
892
+ ) as Child;
893
+ }
894
+
895
+ /** The trigger in scope, if one was provided. */
896
+ export function usePopoverTrigger(): PopoverTriggerValue | null {
897
+ return getContext(PopoverTriggerContext) ?? null;
898
+ }
899
+
900
+ /** The enclosing popover's container, if this is inside one. */
901
+ export function usePopoverGroup(): ElementRef | null {
902
+ return getContext(PopoverGroupContext) ?? null;
903
+ }
904
+
905
+ /**
906
+ * Where the enclosing popover ended up and whether it is on its way out.
907
+ *
908
+ * The popover's own element is the POSITIONER, and a design system names the
909
+ * element inside it. A rule written `[data-slot="x"][data-side="top"]` needs
910
+ * the side on that inner element, which only the popover knows.
911
+ */
912
+ export interface PopoverPlacement {
913
+ /** The side it is on, after any flip. */
914
+ side: Accessor<Axis>;
915
+ align: Accessor<Align>;
916
+ /** Still drawn, and leaving. */
917
+ isExiting: Accessor<boolean>;
918
+ }
919
+
920
+ const PopoverPlacementContext = createContext<PopoverPlacement | null>(null);
921
+
922
+ /** The enclosing popover's placement, if this is inside one. */
923
+ export function usePopoverPlacement(): PopoverPlacement | null {
924
+ return getContext(PopoverPlacementContext) ?? null;
925
+ }
926
+
927
+ /**
928
+ * `data-state`, `data-side` and `data-align` for an element inside a popover,
929
+ * and nothing at all outside one.
930
+ */
931
+ export function popoverStateProps(): DOMProps {
932
+ const placed = usePopoverPlacement();
933
+ if (placed === null) return {};
934
+ return {
935
+ "data-state": () => (placed.isExiting() ? "closed" : "open"),
936
+ "data-side": placed.side,
937
+ "data-align": placed.align,
938
+ };
939
+ }
940
+
941
+ function PopoverGroupProvider(props: {
942
+ value: ElementRef;
943
+ placed: PopoverPlacement;
944
+ children?: Child;
945
+ }) {
946
+ return provide(
947
+ PopoverGroupContext,
948
+ () => props.value,
949
+ () =>
950
+ provide(
951
+ PopoverPlacementContext,
952
+ () => props.placed,
953
+ // A popover opened from inside this one has a trigger of its own.
954
+ () =>
955
+ provide(
956
+ PopoverTriggerContext,
957
+ () => null,
958
+ () => props.children as unknown,
959
+ ),
960
+ ),
961
+ );
962
+ }
963
+
964
+ export interface PortalProviderComponentProps {
965
+ /**
966
+ * Where overlays below here are rendered. Returning `null` means the body.
967
+ *
968
+ * A function rather than an element, because the container often does not
969
+ * exist when the provider runs.
970
+ */
971
+ getContainer?: () => Element | null;
972
+ children?: Child;
973
+ }
974
+
975
+ /**
976
+ * Send every overlay below here somewhere other than the body.
977
+ *
978
+ * For an application rendering inside a shadow root, a fullscreen element or a
979
+ * container it styles: an overlay portalled to the body leaves that subtree
980
+ * and loses the styles, the theme and the containing block with it.
981
+ */
982
+ export function PortalProvider(props: Incoming<PortalProviderComponentProps>) {
983
+ // A scope of its own, so the container reaches what is INSIDE and nothing
984
+ // beside it: installed on the ambient owner it was every later sibling's too.
985
+ return withPortalTarget(
986
+ () => {
987
+ // A zero-argument arrow written inline IS the prop's Cell, so reading it
988
+ // has already called it; one passed by name arrives wrapped and has not.
989
+ const given: unknown = props.getContainer?.();
990
+ const container: unknown = typeof given === "function" ? (given as () => unknown)() : given;
991
+ return container instanceof Element ? container : null;
992
+ },
993
+ () => props.children,
994
+ ) as never;
995
+ }
996
+
997
+ interface DialogSlots {
998
+ titleProps: DOMProps;
999
+ descriptionId: Accessor<string>;
1000
+ readonly describe: (has: boolean) => void;
1001
+ readonly title: (has: boolean) => void;
1002
+ }
1003
+
1004
+ export interface DialogDescription {
1005
+ readonly id: Accessor<string>;
1006
+ }
1007
+
1008
+ const DialogSlotsContext = createContext<DialogSlots | null>(null);
1009
+
1010
+ function provideDialog(slots: DialogSlots): void {
1011
+ const owner = getOwner();
1012
+ if (owner !== null) install(owner, DialogSlotsContext, () => slots);
1013
+ }
1014
+
1015
+ /**
1016
+ * The props the enclosing dialog's title element must carry, and the
1017
+ * registration that makes the dialog point at it, for as long as the caller
1018
+ * is rendered: a design system's own heading names the dialog this way.
1019
+ */
1020
+ export function useDialogTitle(): DOMProps | null {
1021
+ const slots = getContext(DialogSlotsContext);
1022
+ if (slots === null || slots === undefined) return null;
1023
+ slots.title(true);
1024
+ onCleanup(() => slots.title(false));
1025
+ return slots.titleProps;
1026
+ }
1027
+
1028
+ /**
1029
+ * The props the enclosing dialog's description must carry, and the
1030
+ * registration that makes the dialog point at it.
1031
+ *
1032
+ * Calling this is what turns `aria-describedby` on, and leaving turns it off
1033
+ * again: a design system's `<DialogDescription>` is the only thing that knows
1034
+ * a description exists, and without this the paragraph under the title is read
1035
+ * only by someone who goes looking for it.
1036
+ */
1037
+ export function useDialogDescription(): DialogDescription | null {
1038
+ const slots = getContext(DialogSlotsContext);
1039
+ if (slots === null || slots === undefined) return null;
1040
+ slots.describe(true);
1041
+ onCleanup(() => slots.describe(false));
1042
+ return { id: slots.descriptionId };
1043
+ }
1044
+
1045
+ export interface DialogTriggerValue {
1046
+ state: OverlayTriggerState;
1047
+ triggerProps: DOMProps;
1048
+ overlayProps: DOMProps;
1049
+ }
1050
+
1051
+ const DialogTriggerContext = createContext<DialogTriggerValue | null>(null);
1052
+
1053
+ /**
1054
+ * `provide`, not `install`: a component gets no scope of its own, so
1055
+ * installing on the ambient owner writes where its SIBLINGS read. Two dialog
1056
+ * triggers beside each other both run their bodies before either one's
1057
+ * children are built, and every child of both then sees the second one.
1058
+ */
1059
+ function provideDialogTrigger(value: DialogTriggerValue, children: () => Child) {
1060
+ return provide(
1061
+ DialogTriggerContext,
1062
+ () => value,
1063
+ () => children() as unknown,
1064
+ );
1065
+ }
1066
+
1067
+ /** The enclosing {@link DialogTrigger}'s state and props. */
1068
+ export function useDialogTrigger(): DialogTriggerValue {
1069
+ const value = getContext(DialogTriggerContext);
1070
+ if (value === null || value === undefined) {
1071
+ throw new Error("This must be rendered inside a DialogTrigger.");
1072
+ }
1073
+ return value;
1074
+ }
1075
+
1076
+ export type { FocusScopeOptions };
1077
+ export type DialogState = Accessor<boolean>;