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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +304 -2
  3. package/package.json +437 -4
  4. package/src/autocomplete.tsx +581 -0
  5. package/src/breadcrumbs.tsx +297 -0
  6. package/src/button.tsx +468 -0
  7. package/src/calendar.tsx +2316 -0
  8. package/src/checkbox.tsx +732 -0
  9. package/src/collections.ts +1059 -0
  10. package/src/color.ts +2119 -0
  11. package/src/colorpicker.tsx +2023 -0
  12. package/src/colorswatchpicker.tsx +240 -0
  13. package/src/combobox.tsx +3003 -0
  14. package/src/command.tsx +1203 -0
  15. package/src/date.ts +674 -0
  16. package/src/datefield.tsx +2066 -0
  17. package/src/datepicker.tsx +907 -0
  18. package/src/dialog.tsx +1077 -0
  19. package/src/disclosure.tsx +711 -0
  20. package/src/dnd/clipboard.ts +125 -0
  21. package/src/dnd/collection.ts +1265 -0
  22. package/src/dnd/data.ts +409 -0
  23. package/src/dnd/drag-drop.ts +801 -0
  24. package/src/dnd/index.ts +133 -0
  25. package/src/dnd/manager.ts +639 -0
  26. package/src/dnd/strings.ts +1279 -0
  27. package/src/dnd/targets.ts +726 -0
  28. package/src/dnd/types.ts +212 -0
  29. package/src/dom.ts +703 -0
  30. package/src/drag-and-drop.tsx +669 -0
  31. package/src/drawer.ts +674 -0
  32. package/src/dropzone.tsx +208 -0
  33. package/src/file-trigger.tsx +103 -0
  34. package/src/focus.ts +1370 -0
  35. package/src/form.tsx +94 -0
  36. package/src/gridlist.tsx +1354 -0
  37. package/src/group.tsx +146 -0
  38. package/src/i18n.ts +823 -0
  39. package/src/index.ts +1672 -0
  40. package/src/interactions/description.ts +73 -0
  41. package/src/interactions/flags.ts +35 -0
  42. package/src/interactions/focus-events.ts +226 -0
  43. package/src/interactions/focusable.ts +86 -0
  44. package/src/interactions/hover.ts +213 -0
  45. package/src/interactions/interact-outside.ts +123 -0
  46. package/src/interactions/keyboard.ts +298 -0
  47. package/src/interactions/listeners.ts +78 -0
  48. package/src/interactions/long-press.ts +160 -0
  49. package/src/interactions/modality.ts +428 -0
  50. package/src/interactions/move.ts +257 -0
  51. package/src/interactions/open-link.ts +226 -0
  52. package/src/interactions/press.ts +915 -0
  53. package/src/interactions/prevent-focus.ts +102 -0
  54. package/src/interactions/scroll-wheel.ts +43 -0
  55. package/src/interactions/text-selection.ts +77 -0
  56. package/src/interactions.ts +81 -0
  57. package/src/label.ts +140 -0
  58. package/src/link.tsx +477 -0
  59. package/src/listbox.tsx +1247 -0
  60. package/src/live.ts +208 -0
  61. package/src/menu.tsx +2383 -0
  62. package/src/menubar.tsx +579 -0
  63. package/src/navigation-tree.tsx +357 -0
  64. package/src/navigation.ts +735 -0
  65. package/src/numberfield.tsx +942 -0
  66. package/src/otp.ts +430 -0
  67. package/src/overlay-arrow.tsx +157 -0
  68. package/src/overlays.ts +1549 -0
  69. package/src/platform.ts +75 -0
  70. package/src/presence.ts +164 -0
  71. package/src/preview-trigger.tsx +582 -0
  72. package/src/progress-bar-context.ts +15 -0
  73. package/src/questionnaire.tsx +1717 -0
  74. package/src/radio.tsx +641 -0
  75. package/src/register-dom.ts +12 -0
  76. package/src/scroller.ts +1165 -0
  77. package/src/select.tsx +1745 -0
  78. package/src/selection-indicator.tsx +74 -0
  79. package/src/selection.ts +1472 -0
  80. package/src/shared-element-transition.tsx +316 -0
  81. package/src/sheet.tsx +1461 -0
  82. package/src/slider.tsx +1137 -0
  83. package/src/splitter.ts +1152 -0
  84. package/src/static-collection.ts +211 -0
  85. package/src/switch.tsx +212 -0
  86. package/src/table.tsx +2218 -0
  87. package/src/tabs.tsx +1127 -0
  88. package/src/tag.tsx +637 -0
  89. package/src/textarea.tsx +186 -0
  90. package/src/textfield.tsx +483 -0
  91. package/src/toast-components.tsx +589 -0
  92. package/src/toast.ts +658 -0
  93. package/src/toggle-button-group.tsx +175 -0
  94. package/src/toggle-input.tsx +86 -0
  95. package/src/toggle.ts +384 -0
  96. package/src/togglegroup.ts +365 -0
  97. package/src/tokenfield.tsx +1673 -0
  98. package/src/toolbar.tsx +184 -0
  99. package/src/tooltip.tsx +674 -0
  100. package/src/tree.tsx +2075 -0
  101. package/src/utils.ts +787 -0
  102. package/src/validation.ts +504 -0
  103. package/src/virtualizer.tsx +837 -0
@@ -0,0 +1,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,298 @@
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 { contains, targetElement } from "../dom.ts";
16
+ import { isMac } from "../platform.ts";
17
+ import { access, type DOMProps, type MaybeAccessor } from "../utils.ts";
18
+
19
+ /** A native event with the opt-out from this module's default. */
20
+ export type BaseEvent<E extends Event> = E & { continuePropagation(): void };
21
+
22
+ const CONTINUE = Symbol.for("barq.aria.continuePropagation");
23
+
24
+ interface Marked {
25
+ [CONTINUE]?: boolean;
26
+ }
27
+
28
+ /**
29
+ * Wrap a handler so the event it receives stops propagating unless the handler
30
+ * calls `continuePropagation()`.
31
+ *
32
+ * Nesting composes: an inner wrapper that was told to continue tells the outer
33
+ * one too, so an event a child chose to let through is not swallowed by the
34
+ * parent that delegated to it.
35
+ */
36
+ export function createEventHandler<E extends Event>(
37
+ handler?: (event: BaseEvent<E>) => void,
38
+ ): ((event: E) => void) | undefined {
39
+ if (handler === undefined) return undefined;
40
+
41
+ return (event: E): void => {
42
+ const marked = event as E & Marked;
43
+ const outer = (event as unknown as Partial<BaseEvent<E>>).continuePropagation;
44
+ let shouldStop = true;
45
+
46
+ Object.defineProperty(event, "continuePropagation", {
47
+ configurable: true,
48
+ writable: true,
49
+ value: (): void => {
50
+ shouldStop = false;
51
+ marked[CONTINUE] = true;
52
+ // A wrapper further out has already decided to stop; tell it not to.
53
+ outer?.call(event);
54
+ },
55
+ });
56
+
57
+ try {
58
+ handler(event as BaseEvent<E>);
59
+ } finally {
60
+ if (outer === undefined) {
61
+ delete (event as unknown as Partial<BaseEvent<E>>).continuePropagation;
62
+ } else
63
+ Object.defineProperty(event, "continuePropagation", { configurable: true, value: outer });
64
+ }
65
+
66
+ if (shouldStop && !event.cancelBubble) event.stopPropagation();
67
+ };
68
+ }
69
+
70
+ // ---------------------------------------------------------------------------
71
+ // Shortcuts
72
+ // ---------------------------------------------------------------------------
73
+
74
+ /**
75
+ * What a shortcut does. Returning nothing or `true` prevents the default and
76
+ * stops the event; `false` lets it through untouched; an object decides each.
77
+ */
78
+ export type KeyboardShortcutAction = (
79
+ event: BaseEvent<KeyboardEvent>,
80
+ ) =>
81
+ | void
82
+ | boolean
83
+ | Partial<{ shouldContinuePropagation: boolean; shouldPreventDefault: boolean }>;
84
+
85
+ /** Shortcut strings (`"Mod+s"`, `"Control+Shift+a"`, `"Escape"`) to what they do. */
86
+ export type KeyboardShortcutBindings = Record<string, KeyboardShortcutAction>;
87
+
88
+ export interface ParsedKeyboardShortcut {
89
+ shift: boolean;
90
+ alt: boolean;
91
+ ctrl: boolean;
92
+ meta: boolean;
93
+ /** Command on Apple platforms, Control everywhere else. */
94
+ mod: boolean;
95
+ key: string;
96
+ }
97
+
98
+ const MODIFIER_ORDER = ["Alt", "Control", "Meta", "Shift"] as const;
99
+
100
+ const KEY_ALIASES: Record<string, string> = {
101
+ space: " ",
102
+ esc: "escape",
103
+ del: "delete",
104
+ ins: "insert",
105
+ left: "arrowleft",
106
+ right: "arrowright",
107
+ up: "arrowup",
108
+ down: "arrowdown",
109
+ };
110
+
111
+ /** `"Mod+Shift+z"` into its parts. Modifiers ignore case and order. */
112
+ export function parseKeyboardShortcut(spec: string): ParsedKeyboardShortcut {
113
+ const parsed: ParsedKeyboardShortcut = {
114
+ shift: false,
115
+ alt: false,
116
+ ctrl: false,
117
+ meta: false,
118
+ mod: false,
119
+ key: "",
120
+ };
121
+ for (const part of spec.split("+")) {
122
+ const lower = part.toLowerCase();
123
+ if (lower === "shift") parsed.shift = true;
124
+ else if (lower === "alt") parsed.alt = true;
125
+ else if (lower === "control") parsed.ctrl = true;
126
+ else if (lower === "meta") parsed.meta = true;
127
+ else if (lower === "mod") parsed.mod = true;
128
+ else parsed.key = part;
129
+ }
130
+ if (parsed.key === "") {
131
+ throw new Error(
132
+ `Invalid keyboard shortcut: "${spec}". Must include exactly one non-modifier key (e.g. "a", "Enter", "ArrowDown"). Combine any of Shift, Alt, Control, Meta, and Mod.`,
133
+ );
134
+ }
135
+ return parsed;
136
+ }
137
+
138
+ function joinShortcut(modifiers: Set<string>, key: string): string {
139
+ const ordered = MODIFIER_ORDER.filter((name) => modifiers.has(name));
140
+ return ordered.length > 0 ? `${ordered.join("+")}+${key}` : key;
141
+ }
142
+
143
+ /** One spelling per shortcut, so `Shift+Mod+a` and `Mod+Shift+a` are the same key. */
144
+ export function canonicalKeyboardShortcut(parsed: ParsedKeyboardShortcut): string {
145
+ const modifiers = new Set<string>();
146
+ if (parsed.alt) modifiers.add("Alt");
147
+ if (parsed.shift) modifiers.add("Shift");
148
+ if (parsed.ctrl) modifiers.add("Control");
149
+ if (parsed.meta) modifiers.add("Meta");
150
+ if (parsed.mod) modifiers.add(isMac() ? "Meta" : "Control");
151
+ const key = parsed.key.toLowerCase();
152
+ return joinShortcut(modifiers, KEY_ALIASES[key] ?? key);
153
+ }
154
+
155
+ /** The canonical shortcut a keydown spells. */
156
+ export function keyboardEventToCanonicalShortcut(event: KeyboardEvent): string {
157
+ const modifiers = new Set<string>();
158
+ if (event.altKey) modifiers.add("Alt");
159
+ if (event.ctrlKey) modifiers.add("Control");
160
+ if (event.metaKey) modifiers.add("Meta");
161
+ if (event.shiftKey) modifiers.add("Shift");
162
+ return joinShortcut(modifiers, event.key.toLowerCase());
163
+ }
164
+
165
+ /**
166
+ * A keydown handler that runs the binding whose modifiers and key match the
167
+ * event exactly. Two bindings that spell the same shortcut: the later wins.
168
+ *
169
+ * ```ts
170
+ * const onKeyDown = createKeyboardShortcutHandler({ "Mod+s": () => save() });
171
+ * ```
172
+ */
173
+ export function createKeyboardShortcutHandler(
174
+ bindings: KeyboardShortcutBindings,
175
+ ): (event: BaseEvent<KeyboardEvent>) => void {
176
+ const map = new Map<string, KeyboardShortcutAction>();
177
+ for (const [spec, action] of Object.entries(bindings)) {
178
+ map.set(canonicalKeyboardShortcut(parseKeyboardShortcut(spec)), action);
179
+ }
180
+
181
+ return (event) => {
182
+ const action = map.get(keyboardEventToCanonicalShortcut(event));
183
+ if (action === undefined) {
184
+ event.continuePropagation();
185
+ return;
186
+ }
187
+ const result = action(event);
188
+ const outcome =
189
+ result === undefined
190
+ ? { shouldContinuePropagation: false, shouldPreventDefault: true }
191
+ : typeof result === "boolean"
192
+ ? { shouldContinuePropagation: !result, shouldPreventDefault: result }
193
+ : result;
194
+ if (outcome.shouldPreventDefault === true) event.preventDefault();
195
+ if (outcome.shouldContinuePropagation === true) event.continuePropagation();
196
+ };
197
+ }
198
+
199
+ /**
200
+ * Call a handler that does not decide propagation. It still receives a
201
+ * `continuePropagation`, the enclosing handler's when there is one.
202
+ */
203
+ function callUndecided(
204
+ handler: ((event: BaseEvent<KeyboardEvent>) => void) | undefined,
205
+ event: KeyboardEvent,
206
+ ): void {
207
+ if (handler === undefined) return;
208
+ const base = event as Partial<BaseEvent<KeyboardEvent>>;
209
+ if (typeof base.continuePropagation === "function") {
210
+ handler(event as BaseEvent<KeyboardEvent>);
211
+ return;
212
+ }
213
+ Object.defineProperty(event, "continuePropagation", {
214
+ configurable: true,
215
+ writable: true,
216
+ value: (): void => {},
217
+ });
218
+ try {
219
+ handler(event as BaseEvent<KeyboardEvent>);
220
+ } finally {
221
+ delete base.continuePropagation;
222
+ }
223
+ }
224
+
225
+ export interface KeyboardOptions {
226
+ isDisabled?: MaybeAccessor<boolean | undefined>;
227
+ onKeyDown?: (event: BaseEvent<KeyboardEvent>) => void;
228
+ onKeyUp?: (event: BaseEvent<KeyboardEvent>) => void;
229
+ /**
230
+ * Keyboard shortcuts on keydown. With these, `onKeyDown` and `onKeyUp` run
231
+ * as they are and only the shortcuts decide whether the event goes on.
232
+ */
233
+ shortcuts?: KeyboardShortcutBindings;
234
+ /** Run shortcuts for a held key's repeats too. */
235
+ allowRepeats?: MaybeAccessor<boolean | undefined>;
236
+ /** Run shortcuts while an input method is composing. */
237
+ allowComposing?: MaybeAccessor<boolean | undefined>;
238
+ }
239
+
240
+ export interface KeyboardResult {
241
+ keyboardProps: DOMProps;
242
+ }
243
+
244
+ /**
245
+ * Key handling for a focusable element.
246
+ *
247
+ * ```tsx
248
+ * const { keyboardProps } = keyboard({
249
+ * onKeyDown: (e) => {
250
+ * if (e.key !== "Escape") e.continuePropagation();
251
+ * else close();
252
+ * },
253
+ * });
254
+ * ```
255
+ */
256
+ export function keyboard(options: KeyboardOptions = {}): KeyboardResult {
257
+ const enabled = (): boolean => access(options.isDisabled) !== true;
258
+ let down: ((event: KeyboardEvent) => void) | undefined;
259
+ let up: ((event: KeyboardEvent) => void) | undefined;
260
+
261
+ if (options.shortcuts === undefined) {
262
+ down = createEventHandler(options.onKeyDown);
263
+ up = createEventHandler(options.onKeyUp);
264
+ } else {
265
+ const shortcut = createKeyboardShortcutHandler(options.shortcuts);
266
+ const onShortcut = createEventHandler<KeyboardEvent>((event) => {
267
+ // A key from a portalled subtree is not this element's.
268
+ if (!contains(event.currentTarget as Element | null, targetElement(event))) {
269
+ event.continuePropagation();
270
+ return;
271
+ }
272
+ if (
273
+ (event.repeat && access(options.allowRepeats) !== true) ||
274
+ (event.isComposing && access(options.allowComposing) !== true)
275
+ ) {
276
+ event.continuePropagation();
277
+ return;
278
+ }
279
+ shortcut(event);
280
+ });
281
+ down = (event) => {
282
+ callUndecided(options.onKeyDown, event);
283
+ onShortcut?.(event);
284
+ };
285
+ up = (event) => callUndecided(options.onKeyUp, event);
286
+ }
287
+
288
+ return {
289
+ keyboardProps: {
290
+ onKeyDown: (event: KeyboardEvent) => {
291
+ if (enabled()) down?.(event);
292
+ },
293
+ onKeyUp: (event: KeyboardEvent) => {
294
+ if (enabled()) up?.(event);
295
+ },
296
+ },
297
+ };
298
+ }
@@ -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;