@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
@@ -0,0 +1,123 @@
1
+ /**
2
+ * "The user did something outside this element", for a popover or dialog that
3
+ * closes when they do.
4
+ *
5
+ * A `click` listener alone gets three cases wrong. It fires for a drag that
6
+ * began inside and ended outside, which should not close anything: hence the
7
+ * pointerdown/click pair, with the close only when both landed outside. It
8
+ * misses the element having been removed between the two. And in a shadow DOM
9
+ * `event.target` is the host, so the composed path is what actually answers
10
+ * "was this inside".
11
+ *
12
+ * `pointerup` would be the obvious partner for `pointerdown`; `click` is used
13
+ * instead because Chrome on Android delays and sometimes drops the pointer
14
+ * events after a tap on a form control.
15
+ */
16
+
17
+ import { createEffect } from "@barqjs/core";
18
+ import { contains, ownerDocument, targetElement, TOP_LAYER_ATTRIBUTE } from "../dom.ts";
19
+ import { access, type MaybeAccessor } from "../utils.ts";
20
+ import type { ElementRef } from "./press.ts";
21
+
22
+ export interface InteractOutsideOptions {
23
+ /** The element that defines "inside". */
24
+ ref: ElementRef;
25
+ isDisabled?: MaybeAccessor<boolean | undefined>;
26
+ /** Fired on the pointer going down outside, before the interaction completes. */
27
+ onInteractOutsideStart?: (event: PointerEvent) => void;
28
+ /** Fired once the interaction outside has completed. */
29
+ onInteractOutside?: (event: PointerEvent) => void;
30
+ }
31
+
32
+ function isOutside(event: Event, element: Element | null | undefined): boolean {
33
+ if ((event as MouseEvent).button > 0) return false;
34
+
35
+ const target = targetElement(event);
36
+ if (target !== null) {
37
+ // An element already detached tells us nothing about where the user
38
+ // pointed; treating it as outside closes overlays on their own teardown.
39
+ const doc = target.ownerDocument;
40
+ if (doc === null || !contains(doc.documentElement, target)) return false;
41
+ // The top layer is above everything, so an interaction there is not
42
+ // "outside" anything below it.
43
+ if (target.closest(`[${TOP_LAYER_ATTRIBUTE}]`) !== null) return false;
44
+ }
45
+
46
+ if (element === null || element === undefined) return false;
47
+
48
+ // The composed path, not `target`: inside a shadow root the two differ, and
49
+ // only the path names the element the user actually pointed at.
50
+ const path = typeof event.composedPath === "function" ? event.composedPath() : [event.target];
51
+ return !path.includes(element);
52
+ }
53
+
54
+ /**
55
+ * ```tsx
56
+ * interactOutside({ ref: popover, onInteractOutside: () => setOpen(false) });
57
+ * ```
58
+ */
59
+ export function interactOutside(options: InteractOutsideOptions): void {
60
+ const state = { isPointerDown: false, ignoreEmulatedMouseEvents: false };
61
+
62
+ createEffect(
63
+ () => (access(options.isDisabled) === true ? null : ownerDocument(access(options.ref))),
64
+ (doc) => {
65
+ if (doc === null) return undefined;
66
+
67
+ const onPointerDown = (event: Event): void => {
68
+ if (options.onInteractOutside === undefined) return;
69
+ if (!isOutside(event, access(options.ref))) return;
70
+ options.onInteractOutsideStart?.(event as PointerEvent);
71
+ state.isPointerDown = true;
72
+ };
73
+
74
+ if (typeof PointerEvent !== "undefined") {
75
+ const onClick = (event: Event): void => {
76
+ if (state.isPointerDown && isOutside(event, access(options.ref))) {
77
+ options.onInteractOutside?.(event as PointerEvent);
78
+ }
79
+ state.isPointerDown = false;
80
+ };
81
+
82
+ // Capturing: a handler in between may stop propagation, and a combobox
83
+ // that closes on selection removes the element before the bubble phase.
84
+ doc.addEventListener("pointerdown", onPointerDown, true);
85
+ doc.addEventListener("click", onClick, true);
86
+
87
+ return () => {
88
+ doc.removeEventListener("pointerdown", onPointerDown, true);
89
+ doc.removeEventListener("click", onClick, true);
90
+ };
91
+ }
92
+
93
+ const onMouseUp = (event: Event): void => {
94
+ if (state.ignoreEmulatedMouseEvents) {
95
+ state.ignoreEmulatedMouseEvents = false;
96
+ } else if (state.isPointerDown && isOutside(event, access(options.ref))) {
97
+ options.onInteractOutside?.(event as PointerEvent);
98
+ }
99
+ state.isPointerDown = false;
100
+ };
101
+
102
+ const onTouchEnd = (event: Event): void => {
103
+ state.ignoreEmulatedMouseEvents = true;
104
+ if (state.isPointerDown && isOutside(event, access(options.ref))) {
105
+ options.onInteractOutside?.(event as PointerEvent);
106
+ }
107
+ state.isPointerDown = false;
108
+ };
109
+
110
+ doc.addEventListener("mousedown", onPointerDown, true);
111
+ doc.addEventListener("mouseup", onMouseUp, true);
112
+ doc.addEventListener("touchstart", onPointerDown, true);
113
+ doc.addEventListener("touchend", onTouchEnd, true);
114
+
115
+ return () => {
116
+ doc.removeEventListener("mousedown", onPointerDown, true);
117
+ doc.removeEventListener("mouseup", onMouseUp, true);
118
+ doc.removeEventListener("touchstart", onPointerDown, true);
119
+ doc.removeEventListener("touchend", onTouchEnd, true);
120
+ };
121
+ },
122
+ );
123
+ }
@@ -0,0 +1,105 @@
1
+ /**
2
+ * Keyboard handling with propagation stopped by default.
3
+ *
4
+ * A component nested inside another that also handles keys — a menu inside a
5
+ * dialog inside a listbox — must not let one Escape close all three. So a
6
+ * handler here consumes the event unless it says otherwise, which inverts the
7
+ * platform default and makes composition the easy case rather than the one
8
+ * every caller has to remember.
9
+ *
10
+ * `continuePropagation()` is added to the native event rather than to a
11
+ * synthetic copy of it, because barq has no synthetic event system and a copy
12
+ * would break `preventDefault`, `currentTarget` and every other live property.
13
+ */
14
+
15
+ import { access, type DOMProps, type MaybeAccessor } from "../utils.ts";
16
+
17
+ /** A native event with the opt-out from this module's default. */
18
+ export type BaseEvent<E extends Event> = E & { continuePropagation(): void };
19
+
20
+ const CONTINUE = Symbol.for("barq.aria.continuePropagation");
21
+
22
+ interface Marked {
23
+ [CONTINUE]?: boolean;
24
+ }
25
+
26
+ /**
27
+ * Wrap a handler so the event it receives stops propagating unless the handler
28
+ * calls `continuePropagation()`.
29
+ *
30
+ * Nesting composes: an inner wrapper that was told to continue tells the outer
31
+ * one too, so an event a child chose to let through is not swallowed by the
32
+ * parent that delegated to it.
33
+ */
34
+ export function createEventHandler<E extends Event>(
35
+ handler?: (event: BaseEvent<E>) => void,
36
+ ): ((event: E) => void) | undefined {
37
+ if (handler === undefined) return undefined;
38
+
39
+ return (event: E): void => {
40
+ const marked = event as E & Marked;
41
+ const outer = (event as unknown as Partial<BaseEvent<E>>).continuePropagation;
42
+ let shouldStop = true;
43
+
44
+ Object.defineProperty(event, "continuePropagation", {
45
+ configurable: true,
46
+ writable: true,
47
+ value: (): void => {
48
+ shouldStop = false;
49
+ marked[CONTINUE] = true;
50
+ // A wrapper further out has already decided to stop; tell it not to.
51
+ outer?.call(event);
52
+ },
53
+ });
54
+
55
+ try {
56
+ handler(event as BaseEvent<E>);
57
+ } finally {
58
+ if (outer === undefined) {
59
+ delete (event as unknown as Partial<BaseEvent<E>>).continuePropagation;
60
+ } else
61
+ Object.defineProperty(event, "continuePropagation", { configurable: true, value: outer });
62
+ }
63
+
64
+ if (shouldStop && !event.cancelBubble) event.stopPropagation();
65
+ };
66
+ }
67
+
68
+ export interface KeyboardOptions {
69
+ isDisabled?: MaybeAccessor<boolean | undefined>;
70
+ onKeyDown?: (event: BaseEvent<KeyboardEvent>) => void;
71
+ onKeyUp?: (event: BaseEvent<KeyboardEvent>) => void;
72
+ }
73
+
74
+ export interface KeyboardResult {
75
+ keyboardProps: DOMProps;
76
+ }
77
+
78
+ /**
79
+ * Key handling for a focusable element.
80
+ *
81
+ * ```tsx
82
+ * const { keyboardProps } = keyboard({
83
+ * onKeyDown: (e) => {
84
+ * if (e.key !== "Escape") e.continuePropagation();
85
+ * else close();
86
+ * },
87
+ * });
88
+ * ```
89
+ */
90
+ export function keyboard(options: KeyboardOptions = {}): KeyboardResult {
91
+ const down = createEventHandler(options.onKeyDown);
92
+ const up = createEventHandler(options.onKeyUp);
93
+ const enabled = (): boolean => access(options.isDisabled) !== true;
94
+
95
+ return {
96
+ keyboardProps: {
97
+ onKeyDown: (event: KeyboardEvent) => {
98
+ if (enabled()) down?.(event);
99
+ },
100
+ onKeyUp: (event: KeyboardEvent) => {
101
+ if (enabled()) up?.(event);
102
+ },
103
+ },
104
+ };
105
+ }
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Listeners on targets a component does not own.
3
+ *
4
+ * A press that begins on a button ends wherever the pointer happens to be, so
5
+ * the `pointerup` has to be on the document; a hover ends when the element
6
+ * under the pointer is removed, which only a document-level `pointerover`
7
+ * reports. Both are bound mid-interaction and must come off when the
8
+ * interaction ends AND when the component is disposed, whichever is first.
9
+ */
10
+
11
+ import { tryCleanup } from "@barqjs/primitives/utils";
12
+
13
+ interface Registration {
14
+ target: EventTarget;
15
+ type: string;
16
+ listener: EventListenerOrEventListenerObject;
17
+ options?: boolean | AddEventListenerOptions;
18
+ }
19
+
20
+ export interface GlobalListeners {
21
+ add(
22
+ target: EventTarget,
23
+ type: string,
24
+ listener: EventListenerOrEventListenerObject,
25
+ options?: boolean | AddEventListenerOptions,
26
+ ): void;
27
+ remove(
28
+ target: EventTarget,
29
+ type: string,
30
+ listener: EventListenerOrEventListenerObject,
31
+ options?: boolean | EventListenerOptions,
32
+ ): void;
33
+ removeAll(): void;
34
+ }
35
+
36
+ /**
37
+ * A set of global listeners tied to the calling scope.
38
+ *
39
+ * `{ once: true }` is handled here rather than being handed to the platform,
40
+ * because a listener the platform removed is still in this registry and
41
+ * `removeAll` would then try to remove it a second time and, worse, keep a
42
+ * reference to it alive.
43
+ */
44
+ export function globalListeners(): GlobalListeners {
45
+ const registered = new Map<EventListenerOrEventListenerObject, Registration>();
46
+
47
+ const remove: GlobalListeners["remove"] = (target, type, listener, options) => {
48
+ const entry = registered.get(listener);
49
+ target.removeEventListener(type, entry?.listener ?? listener, options);
50
+ registered.delete(listener);
51
+ };
52
+
53
+ const removeAll = (): void => {
54
+ // A copy, because `remove` deletes from the map being walked.
55
+ for (const [key, entry] of Array.from(registered)) {
56
+ remove(entry.target, entry.type, key, entry.options);
57
+ }
58
+ };
59
+
60
+ tryCleanup(removeAll);
61
+
62
+ return {
63
+ add(target, type, listener, options) {
64
+ const wrapped =
65
+ typeof options === "object" && options?.once === true
66
+ ? (event: Event): void => {
67
+ registered.delete(listener);
68
+ if (typeof listener === "function") listener(event);
69
+ else listener.handleEvent(event);
70
+ }
71
+ : listener;
72
+ registered.set(listener, { target, type, listener: wrapped, options });
73
+ target.addEventListener(type, wrapped, options);
74
+ },
75
+ remove,
76
+ removeAll,
77
+ };
78
+ }
@@ -0,0 +1,160 @@
1
+ /**
2
+ * A press held past a threshold, with the platform's own long-press behaviour
3
+ * suppressed for the duration.
4
+ *
5
+ * Three things fight a long press. The context menu opens on touch, which is
6
+ * the platform's own long press. The click that follows would activate the
7
+ * short-press action as well, so both would fire. And on touch the browser
8
+ * only focuses on pointer up, so the element the menu belongs to has no focus
9
+ * when the menu opens.
10
+ *
11
+ * A `pointercancel` is dispatched at the threshold so any other press on the
12
+ * same element abandons its own interaction rather than firing too.
13
+ */
14
+
15
+ import { focusWithoutScrolling, ownerDocument, ownerWindow } from "../dom.ts";
16
+ import { access, mergeProps, type DOMProps, type MaybeAccessor } from "../utils.ts";
17
+ import { description } from "./description.ts";
18
+ import { globalListeners } from "./listeners.ts";
19
+ import type { PointerType } from "./modality.ts";
20
+ import { press, type PressEvent } from "./press.ts";
21
+
22
+ export interface LongPressEvent extends Omit<PressEvent, "type"> {
23
+ type: "longpressstart" | "longpressend" | "longpress";
24
+ }
25
+
26
+ export interface LongPressOptions {
27
+ isDisabled?: MaybeAccessor<boolean | undefined>;
28
+ /** Which pointer types count. Both mouse and touch by default. */
29
+ pointerType?: MaybeAccessor<"mouse" | "touch" | undefined>;
30
+ /** How long the press must be held. @default 500 */
31
+ threshold?: MaybeAccessor<number | undefined>;
32
+ /**
33
+ * What assistive technology should say the long press does, e.g.
34
+ * "Long press to open the menu". There is no visible affordance to infer it
35
+ * from, so without this the action is undiscoverable.
36
+ */
37
+ accessibilityDescription?: MaybeAccessor<string | undefined>;
38
+ onLongPressStart?: (event: LongPressEvent) => void;
39
+ onLongPressEnd?: (event: LongPressEvent) => void;
40
+ onLongPress?: (event: LongPressEvent) => void;
41
+ }
42
+
43
+ export interface LongPressResult {
44
+ longPressProps: DOMProps;
45
+ }
46
+
47
+ export interface LongPressHandlers {
48
+ onPressStart: (event: PressEvent) => void;
49
+ onPressEnd: (event: PressEvent) => void;
50
+ /** `aria-describedby` for the accessibility description, if there is one. */
51
+ describedProps: DOMProps;
52
+ }
53
+
54
+ const DEFAULT_THRESHOLD = 500;
55
+
56
+ function asLongPress(event: PressEvent, type: LongPressEvent["type"]): LongPressEvent {
57
+ return {
58
+ type,
59
+ pointerType: event.pointerType,
60
+ target: event.target,
61
+ shiftKey: event.shiftKey,
62
+ ctrlKey: event.ctrlKey,
63
+ metaKey: event.metaKey,
64
+ altKey: event.altKey,
65
+ x: event.x,
66
+ y: event.y,
67
+ key: event.key,
68
+ continuePropagation: () => event.continuePropagation(),
69
+ };
70
+ }
71
+
72
+ /**
73
+ * The long press as press callbacks, for an element that already has a press.
74
+ *
75
+ * A menu trigger is a button, so it has one already; a second `press` on the
76
+ * same element would mean two pressed states and two sets of global pointer
77
+ * listeners racing over one gesture.
78
+ */
79
+ export function longPressHandlers(options: LongPressOptions): LongPressHandlers {
80
+ const listeners = globalListeners();
81
+ let timer: ReturnType<typeof setTimeout> | undefined;
82
+
83
+ const accepts = (event: PressEvent): boolean => {
84
+ const wanted = access(options.pointerType);
85
+ if (wanted !== undefined) return event.pointerType === wanted;
86
+ return event.pointerType === "mouse" || event.pointerType === "touch";
87
+ };
88
+
89
+ const described = description(() => {
90
+ if (options.onLongPress === undefined || access(options.isDisabled) === true) return undefined;
91
+ return access(options.accessibilityDescription);
92
+ });
93
+
94
+ return {
95
+ describedProps: described,
96
+ onPressStart(event) {
97
+ // A long press is not a press: the short-press handler on the same
98
+ // element must still see this event.
99
+ event.continuePropagation();
100
+ if (!accepts(event)) return;
101
+
102
+ options.onLongPressStart?.(asLongPress(event, "longpressstart"));
103
+
104
+ const threshold = access(options.threshold) ?? DEFAULT_THRESHOLD;
105
+ timer = setTimeout(() => {
106
+ // Any other press bound to this element abandons its interaction.
107
+ event.target.dispatchEvent(new PointerEvent("pointercancel", { bubbles: true }));
108
+ // And the click that would otherwise follow is swallowed, so a long
109
+ // press on a link does not also open it.
110
+ listeners.add(event.target, "click", (click) => click.preventDefault(), { once: true });
111
+
112
+ // On touch the browser focuses on pointer up, which has not happened.
113
+ if (ownerDocument(event.target).activeElement !== event.target) {
114
+ focusWithoutScrolling(event.target as HTMLElement);
115
+ }
116
+
117
+ options.onLongPress?.(asLongPress(event, "longpress"));
118
+ timer = undefined;
119
+ }, threshold);
120
+
121
+ if (event.pointerType === "touch") {
122
+ listeners.add(event.target, "contextmenu", (menu) => menu.preventDefault(), { once: true });
123
+ }
124
+
125
+ listeners.add(
126
+ ownerWindow(event.target),
127
+ "pointerup",
128
+ () => {
129
+ // The click and contextmenu handlers above are only for the events
130
+ // this long press provoked. If neither arrives promptly, they must
131
+ // come off, or the next ordinary click is swallowed too.
132
+ setTimeout(() => listeners.removeAll(), 100);
133
+ },
134
+ { once: true },
135
+ );
136
+ },
137
+ onPressEnd(event) {
138
+ if (timer !== undefined) clearTimeout(timer);
139
+ timer = undefined;
140
+ if (accepts(event)) options.onLongPressEnd?.(asLongPress(event, "longpressend"));
141
+ },
142
+ };
143
+ }
144
+
145
+ /**
146
+ * ```tsx
147
+ * const { longPressProps } = longPress({
148
+ * accessibilityDescription: "Long press to open the menu",
149
+ * onLongPress: () => menu.open(),
150
+ * });
151
+ * ```
152
+ */
153
+ export function longPress(options: LongPressOptions): LongPressResult {
154
+ const { describedProps, ...handlers } = longPressHandlers(options);
155
+ const { pressProps } = press({ isDisabled: options.isDisabled, ...handlers });
156
+ return { longPressProps: mergeProps(pressProps, describedProps) };
157
+ }
158
+
159
+ /** What a pointer type is called, for a consumer branching on it. */
160
+ export type LongPressPointerType = PointerType;