@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,73 @@
1
+ /**
2
+ * A description for assistive technology that has nowhere visible to live.
3
+ *
4
+ * "Long press to open the menu" is not shown to sighted users, who can see the
5
+ * affordance, and cannot be `aria-label` because that would replace the
6
+ * button's name. It goes in a hidden element referenced by `aria-describedby`.
7
+ *
8
+ * One element per distinct string, reference counted: a table with two hundred
9
+ * rows offering the same long press adds one node, not two hundred.
10
+ */
11
+
12
+ import { createEffect, createSignal } from "@barqjs/core";
13
+ import { isServer } from "@barqjs/web";
14
+ import { tryCleanup } from "@barqjs/primitives/utils";
15
+ import { access, type DOMProps, type MaybeAccessor } from "../utils.ts";
16
+
17
+ let nextId = 0;
18
+ const nodes = new Map<string, { count: number; element: Element }>();
19
+
20
+ function acquire(text: string): string {
21
+ let entry = nodes.get(text);
22
+ if (entry === undefined) {
23
+ const element = document.createElement("div");
24
+ element.id = `barq-description-${nextId++}`;
25
+ element.style.display = "none";
26
+ element.textContent = text;
27
+ document.body.appendChild(element);
28
+ entry = { count: 0, element };
29
+ nodes.set(text, entry);
30
+ }
31
+ entry.count++;
32
+ return entry.element.id;
33
+ }
34
+
35
+ function release(text: string): void {
36
+ const entry = nodes.get(text);
37
+ if (entry === undefined) return;
38
+ entry.count--;
39
+ if (entry.count > 0) return;
40
+ entry.element.remove();
41
+ nodes.delete(text);
42
+ }
43
+
44
+ /**
45
+ * ```tsx
46
+ * const described = description(() => props.accessibilityDescription?.());
47
+ * <button {...described} />
48
+ * ```
49
+ */
50
+ export function description(text: MaybeAccessor<string | undefined>): DOMProps {
51
+ // `ownedWrite` for the cleanup below: it runs inside whichever computation
52
+ // disposed this scope, a list dropping a row for one.
53
+ const [describedBy, setDescribedBy] = createSignal<string | undefined>(undefined, {
54
+ ownedWrite: true,
55
+ });
56
+ if (isServer) return { "aria-describedby": describedBy };
57
+
58
+ createEffect(
59
+ () => access(text),
60
+ (value) => {
61
+ if (value === undefined || value === "") {
62
+ setDescribedBy(undefined);
63
+ return undefined;
64
+ }
65
+ setDescribedBy(acquire(value));
66
+ return () => release(value);
67
+ },
68
+ );
69
+
70
+ tryCleanup(() => setDescribedBy(undefined));
71
+
72
+ return { "aria-describedby": () => describedBy() };
73
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Two module-level flags that three otherwise independent modules read.
3
+ *
4
+ * They live here rather than beside the code that sets them because the
5
+ * alternative is an import cycle: the modality tracker must ignore the focus
6
+ * events `preventFocus` fabricates, and `preventFocus` is part of press, which
7
+ * asks the modality tracker what the pointer type is.
8
+ */
9
+
10
+ let ignoringFocus = false;
11
+ let openingLink = false;
12
+
13
+ /** Whether a focus event now is one `preventFocus` is undoing, not a real one. */
14
+ export function isIgnoringFocus(): boolean {
15
+ return ignoringFocus;
16
+ }
17
+
18
+ export function setIgnoringFocus(value: boolean): void {
19
+ ignoringFocus = value;
20
+ }
21
+
22
+ /**
23
+ * Whether a link is being opened right now.
24
+ *
25
+ * The synthetic click that opens a link must not be read as a virtual click,
26
+ * which is what would otherwise switch the page into virtual modality and make
27
+ * every focus ring appear.
28
+ */
29
+ export function isOpeningLink(): boolean {
30
+ return openingLink;
31
+ }
32
+
33
+ export function setOpeningLink(value: boolean): void {
34
+ openingLink = value;
35
+ }
@@ -0,0 +1,226 @@
1
+ /**
2
+ * Focus and blur, for the element itself and for its subtree.
3
+ *
4
+ * Two platform gaps are papered over here.
5
+ *
6
+ * A form control that is disabled while it has focus loses it, but Firefox
7
+ * fires no event to say so, and no engine fires one when the focused element
8
+ * is simply removed from the document. A component whose "is focused" state
9
+ * never returns to false keeps a ring, or an open popover, on something that
10
+ * is not there.
11
+ *
12
+ * The first is watched with a `MutationObserver` on the `disabled` attribute;
13
+ * the second with a capturing `focus` listener on the document, which reports
14
+ * where focus went instead.
15
+ */
16
+
17
+ import { type Accessor, createSignal } from "@barqjs/core";
18
+ import { tryCleanup } from "@barqjs/primitives/utils";
19
+ import { activeElement, contains, ownerDocument, targetElement } from "../dom.ts";
20
+ import { access, type DOMProps, type MaybeAccessor } from "../utils.ts";
21
+ import { globalListeners } from "./listeners.ts";
22
+
23
+ export interface FocusOptions {
24
+ isDisabled?: MaybeAccessor<boolean | undefined>;
25
+ onFocus?: (event: FocusEvent) => void;
26
+ onBlur?: (event: FocusEvent) => void;
27
+ onFocusChange?: (isFocused: boolean) => void;
28
+ }
29
+
30
+ export interface FocusResult {
31
+ focusProps: DOMProps;
32
+ /** Whether the element itself has focus. */
33
+ isFocused: Accessor<boolean>;
34
+ }
35
+
36
+ /**
37
+ * A blur for a control that was disabled while focused.
38
+ *
39
+ * Returns the `focus` handler that arms the watch; it disarms itself on the
40
+ * first `focusout`, which every engine but Firefox fires on its own, and the
41
+ * observer then never gets the chance to fire a second one.
42
+ */
43
+ function watchDisabledBlur(onBlur: (event: FocusEvent) => void): {
44
+ arm: (event: FocusEvent) => void;
45
+ disconnect: () => void;
46
+ } {
47
+ const state = { isFocused: false, observer: null as MutationObserver | null };
48
+
49
+ const disconnect = (): void => {
50
+ state.observer?.disconnect();
51
+ state.observer = null;
52
+ };
53
+
54
+ const arm = (event: FocusEvent): void => {
55
+ const target = targetElement(event);
56
+ if (
57
+ !(target instanceof HTMLButtonElement) &&
58
+ !(target instanceof HTMLInputElement) &&
59
+ !(target instanceof HTMLTextAreaElement) &&
60
+ !(target instanceof HTMLSelectElement)
61
+ ) {
62
+ return;
63
+ }
64
+
65
+ state.isFocused = true;
66
+
67
+ target.addEventListener(
68
+ "focusout",
69
+ (out: Event) => {
70
+ state.isFocused = false;
71
+ if (target.disabled) onBlur(out as FocusEvent);
72
+ disconnect();
73
+ },
74
+ { once: true },
75
+ );
76
+
77
+ disconnect();
78
+ state.observer = new MutationObserver(() => {
79
+ if (!state.isFocused || !target.disabled) return;
80
+ disconnect();
81
+ const related = target === activeElement(ownerDocument(target)) ? null : activeElement();
82
+ target.dispatchEvent(new FocusEvent("blur", { relatedTarget: related }));
83
+ target.dispatchEvent(new FocusEvent("focusout", { bubbles: true, relatedTarget: related }));
84
+ });
85
+ state.observer.observe(target, { attributes: true, attributeFilter: ["disabled"] });
86
+ };
87
+
88
+ return { arm, disconnect };
89
+ }
90
+
91
+ /**
92
+ * Focus for the element itself; anything a descendant does is ignored.
93
+ *
94
+ * ```tsx
95
+ * const { focusProps, isFocused } = focused({ onFocusChange: (on) => open.set(on) });
96
+ * <input {...focusProps} data-focused={isFocused} />
97
+ * ```
98
+ */
99
+ export function focused(options: FocusOptions = {}): FocusResult {
100
+ const [isFocused, setIsFocused] = createSignal(false);
101
+
102
+ const onBlur = (event: FocusEvent): void => {
103
+ if (targetElement(event) !== event.currentTarget && event.currentTarget !== null) return;
104
+ setIsFocused(false);
105
+ options.onBlur?.(event);
106
+ options.onFocusChange?.(false);
107
+ };
108
+
109
+ const disabledBlur = watchDisabledBlur(onBlur);
110
+ tryCleanup(disabledBlur.disconnect);
111
+
112
+ const onFocus = (event: FocusEvent): void => {
113
+ // A handler chained before this one may already have moved focus.
114
+ const target = targetElement(event);
115
+ const active = activeElement(ownerDocument(target));
116
+ if (target !== event.currentTarget || target !== active) return;
117
+
118
+ setIsFocused(true);
119
+ options.onFocus?.(event);
120
+ options.onFocusChange?.(true);
121
+ disabledBlur.arm(event);
122
+ };
123
+
124
+ const enabled = (): boolean => access(options.isDisabled) !== true;
125
+
126
+ return {
127
+ isFocused,
128
+ focusProps: {
129
+ onFocus: (event: FocusEvent) => {
130
+ if (enabled()) onFocus(event);
131
+ },
132
+ onBlur: (event: FocusEvent) => {
133
+ if (enabled()) onBlur(event);
134
+ },
135
+ },
136
+ };
137
+ }
138
+
139
+ export interface FocusWithinOptions {
140
+ isDisabled?: MaybeAccessor<boolean | undefined>;
141
+ onFocusWithin?: (event: FocusEvent) => void;
142
+ onBlurWithin?: (event: FocusEvent) => void;
143
+ onFocusWithinChange?: (isFocusWithin: boolean) => void;
144
+ }
145
+
146
+ export interface FocusWithinResult {
147
+ focusWithinProps: DOMProps;
148
+ /** Whether the element or anything inside it has focus. */
149
+ isFocusWithin: Accessor<boolean>;
150
+ }
151
+
152
+ /**
153
+ * Focus for the element and everything inside it.
154
+ *
155
+ * Bound to `focusin`/`focusout`, which bubble. `focus` and `blur` do not, so a
156
+ * listener on a container never hears a child take focus.
157
+ */
158
+ export function focusWithin(options: FocusWithinOptions = {}): FocusWithinResult {
159
+ const [isFocusWithin, setIsFocusWithin] = createSignal(false);
160
+ // What the handlers test. The signal is for readers: a write to it lands at
161
+ // the next flush, and a handler that passes focus on to a child sends a
162
+ // second arrival before then, which the signal would report as the first.
163
+ let within = false;
164
+ const setWithin = (next: boolean): void => {
165
+ within = next;
166
+ setIsFocusWithin(next);
167
+ };
168
+ const listeners = globalListeners();
169
+
170
+ const onBlur = (event: FocusEvent): void => {
171
+ const currentTarget = event.currentTarget as Element | null;
172
+ if (currentTarget === null || !contains(currentTarget, targetElement(event))) return;
173
+
174
+ // Focus moving between two children is not leaving. `relatedTarget` is
175
+ // where it is going.
176
+ if (!within || contains(currentTarget, event.relatedTarget as Element | null)) return;
177
+
178
+ setWithin(false);
179
+ listeners.removeAll();
180
+ options.onBlurWithin?.(event);
181
+ options.onFocusWithinChange?.(false);
182
+ };
183
+
184
+ const onFocus = (event: FocusEvent): void => {
185
+ const currentTarget = event.currentTarget as Element | null;
186
+ if (currentTarget === null || !contains(currentTarget, targetElement(event))) return;
187
+
188
+ const target = targetElement(event);
189
+ const doc = ownerDocument(target);
190
+ if (within || activeElement(doc) !== target) return;
191
+
192
+ setWithin(true);
193
+ options.onFocusWithin?.(event);
194
+ options.onFocusWithinChange?.(true);
195
+
196
+ // No blur fires when the focused element is removed. A focus landing
197
+ // outside is the evidence that it left.
198
+ listeners.add(
199
+ doc,
200
+ "focus",
201
+ (moved: Event) => {
202
+ const next = targetElement(moved);
203
+ if (!within || contains(currentTarget, next)) return;
204
+ const synthetic = new FocusEvent("blur", { relatedTarget: next });
205
+ Object.defineProperty(synthetic, "target", { value: currentTarget });
206
+ Object.defineProperty(synthetic, "currentTarget", { value: currentTarget });
207
+ onBlur(synthetic);
208
+ },
209
+ { capture: true },
210
+ );
211
+ };
212
+
213
+ const enabled = (): boolean => access(options.isDisabled) !== true;
214
+
215
+ return {
216
+ isFocusWithin,
217
+ focusWithinProps: {
218
+ onFocusIn: (event: FocusEvent) => {
219
+ if (enabled()) onFocus(event);
220
+ },
221
+ onFocusOut: (event: FocusEvent) => {
222
+ if (enabled()) onBlur(event);
223
+ },
224
+ },
225
+ };
226
+ }
@@ -0,0 +1,86 @@
1
+ /**
2
+ * Making an element focusable, and moving focus to one safely.
3
+ *
4
+ * `element.focus()` has two failure modes a widget hits constantly. It scrolls
5
+ * the element into view, which yanks the page when a menu opens below the
6
+ * fold. And under a virtual cursor on iOS, focusing an element that is mid
7
+ * transition scrolls the page to wherever the element was rather than where it
8
+ * is going, so VoiceOver reads the wrong thing.
9
+ */
10
+
11
+ import { createEffect, createSignal } from "@barqjs/core";
12
+ import { isServer } from "@barqjs/web";
13
+ import { activeElement, focusWithoutScrolling, ownerDocument, runAfterTransition } from "../dom.ts";
14
+ import { access, mergeProps, type DOMProps, type MaybeAccessor } from "../utils.ts";
15
+ import { focused, type FocusOptions } from "./focus-events.ts";
16
+ import { keyboard, type BaseEvent } from "./keyboard.ts";
17
+ import { getInteractionModality } from "./modality.ts";
18
+ import type { ElementRef } from "./press.ts";
19
+
20
+ /**
21
+ * Move focus without scrolling, and without landing mid-transition when a
22
+ * virtual cursor is driving.
23
+ */
24
+ export function focusSafely(element: HTMLElement | SVGElement): void {
25
+ if (!element.isConnected) return;
26
+
27
+ if (getInteractionModality() !== "virtual") {
28
+ focusWithoutScrolling(element);
29
+ return;
30
+ }
31
+
32
+ const doc = ownerDocument(element);
33
+ const before = activeElement(doc);
34
+ runAfterTransition(() => {
35
+ const active = activeElement(doc);
36
+ // Only if nothing else claimed focus in the meantime.
37
+ if ((active === before || active === doc.body) && element.isConnected) {
38
+ focusWithoutScrolling(element);
39
+ }
40
+ });
41
+ }
42
+
43
+ export interface FocusableOptions extends FocusOptions {
44
+ /** Take focus when first rendered. */
45
+ autoFocus?: MaybeAccessor<boolean | undefined>;
46
+ /** Stay focusable, but out of the Tab order. */
47
+ excludeFromTabOrder?: MaybeAccessor<boolean | undefined>;
48
+ onKeyDown?: (event: BaseEvent<KeyboardEvent>) => void;
49
+ onKeyUp?: (event: BaseEvent<KeyboardEvent>) => void;
50
+ }
51
+
52
+ export interface FocusableResult {
53
+ focusableProps: DOMProps;
54
+ }
55
+
56
+ /**
57
+ * Focus, keys and tab order for one element.
58
+ *
59
+ * `tabIndex` is always written, even for a native button: WebKit leaves
60
+ * buttons and form controls out of the Tab order unless one is present, which
61
+ * is the "full keyboard access" preference being off by default.
62
+ */
63
+ export function focusable(options: FocusableOptions, ref?: ElementRef): FocusableResult {
64
+ const { focusProps } = focused(options);
65
+ const { keyboardProps } = keyboard(options);
66
+
67
+ const [shouldAutoFocus, setShouldAutoFocus] = createSignal(access(options.autoFocus) === true);
68
+
69
+ if (!isServer) {
70
+ createEffect(
71
+ () => (shouldAutoFocus() && ref !== undefined ? access(ref) : null),
72
+ (element) => {
73
+ if (element === null || element === undefined) return;
74
+ setShouldAutoFocus(false);
75
+ focusSafely(element as HTMLElement);
76
+ },
77
+ );
78
+ }
79
+
80
+ const tabIndex = (): number | undefined => {
81
+ if (access(options.isDisabled) === true) return undefined;
82
+ return access(options.excludeFromTabOrder) === true ? -1 : 0;
83
+ };
84
+
85
+ return { focusableProps: mergeProps(focusProps, keyboardProps, { tabIndex }) };
86
+ }
@@ -0,0 +1,213 @@
1
+ /**
2
+ * Hover, minus the two things CSS `:hover` gets wrong for a widget.
3
+ *
4
+ * A touch leaves the element in the hover state until the user taps somewhere
5
+ * else, so a tooltip opened on tap never closes. And when a hovered element is
6
+ * removed or shrinks out from under the pointer the browser fires no
7
+ * `pointerleave` at all, so the state sticks until the pointer moves again.
8
+ *
9
+ * Emulated mouse events are the mechanism behind the first: iOS fires
10
+ * `pointerenter` twice for a tap, once as `touch` and once as `mouse`. The
11
+ * `mouse` one is suppressed for half a second after any touch anywhere on the
12
+ * page, which has to be page-wide because the second event can land on a
13
+ * different element than the first.
14
+ */
15
+
16
+ import { type Accessor, createEffect, createSignal } from "@barqjs/core";
17
+ import { isServer } from "@barqjs/web";
18
+ import { tryCleanup } from "@barqjs/primitives/utils";
19
+ import { contains, ownerDocument, targetElement } from "../dom.ts";
20
+ import { access, type DOMProps, type MaybeAccessor } from "../utils.ts";
21
+ import { globalListeners } from "./listeners.ts";
22
+ import type { PointerType } from "./modality.ts";
23
+
24
+ export interface HoverEvent {
25
+ type: "hoverstart" | "hoverend";
26
+ pointerType: "mouse" | "pen";
27
+ target: Element;
28
+ }
29
+
30
+ export interface HoverOptions {
31
+ isDisabled?: MaybeAccessor<boolean | undefined>;
32
+ onHoverStart?: (event: HoverEvent) => void;
33
+ onHoverEnd?: (event: HoverEvent) => void;
34
+ onHoverChange?: (isHovered: boolean) => void;
35
+ }
36
+
37
+ export interface HoverResult {
38
+ /** Props to spread on the hoverable element. */
39
+ hoverProps: DOMProps;
40
+ /** Whether a pointer that can hover is over the element. */
41
+ isHovered: Accessor<boolean>;
42
+ }
43
+
44
+ let ignoreEmulatedMouseEvents = false;
45
+ let hoverCount = 0;
46
+
47
+ function suppressEmulatedMouseEvents(): void {
48
+ ignoreEmulatedMouseEvents = true;
49
+ // Cleared shortly after: iOS fires the emulated `pointerenter` immediately
50
+ // after `pointerup`, and a touch now must not suppress a genuine mouse hover
51
+ // a minute from now.
52
+ setTimeout(() => {
53
+ ignoreEmulatedMouseEvents = false;
54
+ }, 500);
55
+ }
56
+
57
+ function onGlobalPointerUp(event: Event): void {
58
+ if ((event as PointerEvent).pointerType === "touch") suppressEmulatedMouseEvents();
59
+ }
60
+
61
+ /** One document listener shared by every hover on the page. */
62
+ function trackEmulatedMouseEvents(): () => void {
63
+ const doc = ownerDocument(null);
64
+ if (doc === undefined) return () => {};
65
+
66
+ if (hoverCount === 0) {
67
+ if (typeof PointerEvent !== "undefined") {
68
+ doc.addEventListener("pointerup", onGlobalPointerUp);
69
+ } else {
70
+ doc.addEventListener("touchend", suppressEmulatedMouseEvents);
71
+ }
72
+ }
73
+ hoverCount++;
74
+
75
+ return () => {
76
+ hoverCount--;
77
+ if (hoverCount > 0) return;
78
+ if (typeof PointerEvent !== "undefined") {
79
+ doc.removeEventListener("pointerup", onGlobalPointerUp);
80
+ } else {
81
+ doc.removeEventListener("touchend", suppressEmulatedMouseEvents);
82
+ }
83
+ };
84
+ }
85
+
86
+ /**
87
+ * Hover handling for one element.
88
+ *
89
+ * ```tsx
90
+ * const { hoverProps, isHovered } = hover({ onHoverChange: (over) => tip.set(over) });
91
+ * <button {...hoverProps} data-hovered={isHovered} />
92
+ * ```
93
+ */
94
+ export function hover(options: HoverOptions): HoverResult {
95
+ const [hovered, setHovered] = createSignal(false);
96
+ const listeners = globalListeners();
97
+
98
+ const state = {
99
+ isHovered: false,
100
+ ignoreEmulatedMouseEvents: false,
101
+ pointerType: "" as PointerType | "",
102
+ target: null as Element | null,
103
+ };
104
+
105
+ if (!isServer) tryCleanup(trackEmulatedMouseEvents());
106
+
107
+ const isDisabled = (): boolean => access(options.isDisabled) === true;
108
+
109
+ const triggerHoverEnd = (target: Element | null, pointerType: PointerType | ""): void => {
110
+ const element = target ?? state.target;
111
+ state.pointerType = "";
112
+ state.target = null;
113
+
114
+ if (pointerType === "touch" || !state.isHovered || element === null) return;
115
+
116
+ state.isHovered = false;
117
+ listeners.removeAll();
118
+
119
+ options.onHoverEnd?.({
120
+ type: "hoverend",
121
+ target: element,
122
+ pointerType: pointerType as "mouse",
123
+ });
124
+ options.onHoverChange?.(false);
125
+ setHovered(false);
126
+ };
127
+
128
+ const triggerHoverStart = (event: Event, pointerType: PointerType): void => {
129
+ state.pointerType = pointerType;
130
+ const currentTarget = event.currentTarget as Element | null;
131
+ if (
132
+ isDisabled() ||
133
+ pointerType === "touch" ||
134
+ state.isHovered ||
135
+ currentTarget === null ||
136
+ !contains(currentTarget, targetElement(event))
137
+ ) {
138
+ return;
139
+ }
140
+
141
+ state.isHovered = true;
142
+ state.target = currentTarget;
143
+
144
+ // The browser fires no `pointerleave` when the hovered element is removed,
145
+ // but it does fire `pointerover` on whatever is under the pointer next —
146
+ // immediately in Chrome, on the next pixel of movement elsewhere.
147
+ listeners.add(
148
+ ownerDocument(targetElement(event)),
149
+ "pointerover",
150
+ (over: Event) => {
151
+ const pointer = over as PointerEvent;
152
+ if (
153
+ state.isHovered &&
154
+ state.target !== null &&
155
+ !contains(state.target, targetElement(pointer))
156
+ ) {
157
+ triggerHoverEnd(state.target, pointer.pointerType as PointerType);
158
+ }
159
+ },
160
+ { capture: true },
161
+ );
162
+
163
+ options.onHoverStart?.({
164
+ type: "hoverstart",
165
+ target: currentTarget,
166
+ pointerType: pointerType as "mouse",
167
+ });
168
+ options.onHoverChange?.(true);
169
+ setHovered(true);
170
+ };
171
+
172
+ const hoverProps: DOMProps = {};
173
+
174
+ if (typeof PointerEvent !== "undefined") {
175
+ hoverProps.onPointerEnter = (event: PointerEvent): void => {
176
+ if (ignoreEmulatedMouseEvents && event.pointerType === "mouse") return;
177
+ triggerHoverStart(event, event.pointerType as PointerType);
178
+ };
179
+
180
+ hoverProps.onPointerLeave = (event: PointerEvent): void => {
181
+ const currentTarget = event.currentTarget as Element | null;
182
+ if (isDisabled() || currentTarget === null) return;
183
+ if (!contains(currentTarget, targetElement(event))) return;
184
+ triggerHoverEnd(currentTarget, event.pointerType as PointerType);
185
+ };
186
+ } else {
187
+ hoverProps.onTouchStart = (): void => {
188
+ state.ignoreEmulatedMouseEvents = true;
189
+ };
190
+
191
+ hoverProps.onMouseEnter = (event: MouseEvent): void => {
192
+ if (!state.ignoreEmulatedMouseEvents && !ignoreEmulatedMouseEvents) {
193
+ triggerHoverStart(event, "mouse");
194
+ }
195
+ state.ignoreEmulatedMouseEvents = false;
196
+ };
197
+
198
+ hoverProps.onMouseLeave = (event: MouseEvent): void => {
199
+ const currentTarget = event.currentTarget as Element | null;
200
+ if (isDisabled() || currentTarget === null) return;
201
+ if (!contains(currentTarget, targetElement(event))) return;
202
+ triggerHoverEnd(currentTarget, "mouse");
203
+ };
204
+ }
205
+
206
+ // Disabling mid-hover has to end it, or a tooltip stays open over a control
207
+ // that no longer responds.
208
+ createEffect(isDisabled, (disabled) => {
209
+ if (disabled) triggerHoverEnd(state.target, state.pointerType);
210
+ });
211
+
212
+ return { hoverProps, isHovered: hovered };
213
+ }