@barqjs/aria 0.0.0-stage → 0.2.0-next.0

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