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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +304 -2
  3. package/package.json +437 -4
  4. package/src/autocomplete.tsx +581 -0
  5. package/src/breadcrumbs.tsx +297 -0
  6. package/src/button.tsx +468 -0
  7. package/src/calendar.tsx +2316 -0
  8. package/src/checkbox.tsx +732 -0
  9. package/src/collections.ts +1059 -0
  10. package/src/color.ts +2119 -0
  11. package/src/colorpicker.tsx +2023 -0
  12. package/src/colorswatchpicker.tsx +240 -0
  13. package/src/combobox.tsx +3003 -0
  14. package/src/command.tsx +1203 -0
  15. package/src/date.ts +674 -0
  16. package/src/datefield.tsx +2066 -0
  17. package/src/datepicker.tsx +907 -0
  18. package/src/dialog.tsx +1077 -0
  19. package/src/disclosure.tsx +711 -0
  20. package/src/dnd/clipboard.ts +125 -0
  21. package/src/dnd/collection.ts +1265 -0
  22. package/src/dnd/data.ts +409 -0
  23. package/src/dnd/drag-drop.ts +801 -0
  24. package/src/dnd/index.ts +133 -0
  25. package/src/dnd/manager.ts +639 -0
  26. package/src/dnd/strings.ts +1279 -0
  27. package/src/dnd/targets.ts +726 -0
  28. package/src/dnd/types.ts +212 -0
  29. package/src/dom.ts +703 -0
  30. package/src/drag-and-drop.tsx +669 -0
  31. package/src/drawer.ts +674 -0
  32. package/src/dropzone.tsx +208 -0
  33. package/src/file-trigger.tsx +103 -0
  34. package/src/focus.ts +1370 -0
  35. package/src/form.tsx +94 -0
  36. package/src/gridlist.tsx +1354 -0
  37. package/src/group.tsx +146 -0
  38. package/src/i18n.ts +823 -0
  39. package/src/index.ts +1672 -0
  40. package/src/interactions/description.ts +73 -0
  41. package/src/interactions/flags.ts +35 -0
  42. package/src/interactions/focus-events.ts +226 -0
  43. package/src/interactions/focusable.ts +86 -0
  44. package/src/interactions/hover.ts +213 -0
  45. package/src/interactions/interact-outside.ts +123 -0
  46. package/src/interactions/keyboard.ts +298 -0
  47. package/src/interactions/listeners.ts +78 -0
  48. package/src/interactions/long-press.ts +160 -0
  49. package/src/interactions/modality.ts +428 -0
  50. package/src/interactions/move.ts +257 -0
  51. package/src/interactions/open-link.ts +226 -0
  52. package/src/interactions/press.ts +915 -0
  53. package/src/interactions/prevent-focus.ts +102 -0
  54. package/src/interactions/scroll-wheel.ts +43 -0
  55. package/src/interactions/text-selection.ts +77 -0
  56. package/src/interactions.ts +81 -0
  57. package/src/label.ts +140 -0
  58. package/src/link.tsx +477 -0
  59. package/src/listbox.tsx +1247 -0
  60. package/src/live.ts +208 -0
  61. package/src/menu.tsx +2383 -0
  62. package/src/menubar.tsx +579 -0
  63. package/src/navigation-tree.tsx +357 -0
  64. package/src/navigation.ts +735 -0
  65. package/src/numberfield.tsx +942 -0
  66. package/src/otp.ts +430 -0
  67. package/src/overlay-arrow.tsx +157 -0
  68. package/src/overlays.ts +1549 -0
  69. package/src/platform.ts +75 -0
  70. package/src/presence.ts +164 -0
  71. package/src/preview-trigger.tsx +582 -0
  72. package/src/progress-bar-context.ts +15 -0
  73. package/src/questionnaire.tsx +1717 -0
  74. package/src/radio.tsx +641 -0
  75. package/src/register-dom.ts +12 -0
  76. package/src/scroller.ts +1165 -0
  77. package/src/select.tsx +1745 -0
  78. package/src/selection-indicator.tsx +74 -0
  79. package/src/selection.ts +1472 -0
  80. package/src/shared-element-transition.tsx +316 -0
  81. package/src/sheet.tsx +1461 -0
  82. package/src/slider.tsx +1137 -0
  83. package/src/splitter.ts +1152 -0
  84. package/src/static-collection.ts +211 -0
  85. package/src/switch.tsx +212 -0
  86. package/src/table.tsx +2218 -0
  87. package/src/tabs.tsx +1127 -0
  88. package/src/tag.tsx +637 -0
  89. package/src/textarea.tsx +186 -0
  90. package/src/textfield.tsx +483 -0
  91. package/src/toast-components.tsx +589 -0
  92. package/src/toast.ts +658 -0
  93. package/src/toggle-button-group.tsx +175 -0
  94. package/src/toggle-input.tsx +86 -0
  95. package/src/toggle.ts +384 -0
  96. package/src/togglegroup.ts +365 -0
  97. package/src/tokenfield.tsx +1673 -0
  98. package/src/toolbar.tsx +184 -0
  99. package/src/tooltip.tsx +674 -0
  100. package/src/tree.tsx +2075 -0
  101. package/src/utils.ts +787 -0
  102. package/src/validation.ts +504 -0
  103. package/src/virtualizer.tsx +837 -0
package/src/otp.ts ADDED
@@ -0,0 +1,430 @@
1
+ /**
2
+ * A one-time code: one real input, and what to draw for each character of it.
3
+ *
4
+ * This is the piece `@barqjs/ui`'s `<InputOTP>` needed. shadcn's is the
5
+ * `input-otp` package, which is React hooks around a context, so the engine is
6
+ * written here and the behaviour is that package's.
7
+ *
8
+ * **One input, not one per character.** An input per character breaks paste
9
+ * (each takes one character), breaks `autocomplete="one-time-code"` (the
10
+ * platform fills one field) and gives a screen reader six unlabelled boxes.
11
+ * Everything below follows from keeping one: the boxes are drawings, so which
12
+ * box is "active" has to be derived from the input's own selection.
13
+ *
14
+ * **A caret on a character selects it.** A box holds one character, so a caret
15
+ * between two of them has nothing to draw. Wherever the browser puts a
16
+ * collapsed caret on a filled position the field widens it to that character,
17
+ * which is also what makes typing there replace rather than insert and push
18
+ * the last character off the end.
19
+ *
20
+ * **A change the pattern refuses is dropped whole.** Not filtered: `pattern`
21
+ * is the HTML attribute's meaning, a test of the entire value, and a paste of
22
+ * `12ab` into a digits field is a mistake to ignore rather than a `12` to keep.
23
+ * `sanitize` runs first for a caller who does want filtering.
24
+ *
25
+ * **The input is invisible by colour, not by opacity.** Password managers and
26
+ * the platform's own code autofill skip a field they consider hidden, and
27
+ * `opacity: 0` is how they decide. The badge a manager then draws inside the
28
+ * field would sit on top of the last box, so the input is widened past the
29
+ * boxes and clipped back, which moves the badge out beside them.
30
+ */
31
+
32
+ import { createSignal, createEffect, onCleanup, type Accessor } from "@barqjs/core";
33
+
34
+ import { access, type MaybeAccessor } from "./utils.ts";
35
+
36
+ /** Digits only. For `pattern`. */
37
+ export const REGEXP_ONLY_DIGITS = "^\\d+$";
38
+ /** Latin letters only. For `pattern`. */
39
+ export const REGEXP_ONLY_CHARS = "^[a-zA-Z]+$";
40
+ /** Digits and Latin letters. For `pattern`. */
41
+ export const REGEXP_ONLY_DIGITS_AND_CHARS = "^[a-zA-Z0-9]+$";
42
+
43
+ export type OtpSelectionDirection = "forward" | "backward" | "none";
44
+
45
+ export interface OtpSelection {
46
+ readonly start: number | null;
47
+ readonly end: number | null;
48
+ readonly direction?: OtpSelectionDirection | undefined;
49
+ }
50
+
51
+ export interface OtpSelectionInput {
52
+ value: string;
53
+ maxLength: number;
54
+ /** Where the browser has the selection now. */
55
+ start: number | null;
56
+ end: number | null;
57
+ direction?: OtpSelectionDirection | null | undefined;
58
+ /** What this function answered last time, which is how it knows which way the caret moved. */
59
+ previous: OtpSelection;
60
+ }
61
+
62
+ /**
63
+ * The selection the field should hold, given where the browser put it.
64
+ *
65
+ * A range the person made is returned as it is, and so is the caret at the end
66
+ * of a value with room left, which is where the next character goes. Every
67
+ * other collapsed caret becomes the one character it points at.
68
+ */
69
+ export function otpSelection(input: OtpSelectionInput): OtpSelection {
70
+ const { value, maxLength, start, end, previous } = input;
71
+ const given = input.direction ?? undefined;
72
+ if (value.length === 0 || start === null || end === null) {
73
+ return { start, end, direction: given };
74
+ }
75
+
76
+ const isCaret = start === end;
77
+ const isInserting = start === value.length && value.length < maxLength;
78
+ if (!isCaret || isInserting) return { start, end, direction: given };
79
+
80
+ if (start === 0) return { start: 0, end: 1, direction: "forward" };
81
+ if (start === maxLength) return { start: start - 1, end: start, direction: "backward" };
82
+ if (maxLength <= 1 || value.length <= 1) return { start, end, direction: given };
83
+
84
+ let offset = 0;
85
+ let direction = given;
86
+ if (previous.start !== null && previous.end !== null) {
87
+ direction = start < previous.end ? "backward" : "forward";
88
+ const wasInserting = previous.start === previous.end && previous.start < maxLength;
89
+ // Leaving a selected character leftward lands the caret on its own left
90
+ // edge, so the character meant is the one before.
91
+ if (direction === "backward" && !wasInserting) offset = -1;
92
+ }
93
+ return { start: start + offset, end: start + offset + 1, direction };
94
+ }
95
+
96
+ export interface OtpSlot {
97
+ /** The character in this position, or `null` while it is empty. */
98
+ readonly char: string | null;
99
+ /** The placeholder's character for this position, while the whole field is empty. */
100
+ readonly placeholderChar: string | null;
101
+ /** The caret or the selection is on it. */
102
+ readonly isActive: boolean;
103
+ /** It is active and empty, so a caret has to be drawn: the real one is invisible. */
104
+ readonly hasFakeCaret: boolean;
105
+ }
106
+
107
+ export type OtpPasswordManagerStrategy = "increase-width" | "none";
108
+
109
+ export interface OtpFieldOptions {
110
+ /** How many characters. */
111
+ maxLength: MaybeAccessor<number>;
112
+ value?: MaybeAccessor<string | undefined>;
113
+ defaultValue?: MaybeAccessor<string | undefined>;
114
+ onChange?: (value: string) => void;
115
+ /** Called when the value BECOMES full, by typing, pasting or the caller. */
116
+ onComplete?: (value: string) => void;
117
+ /** A test of the whole value. A change that fails it is refused. */
118
+ pattern?: MaybeAccessor<string | RegExp | undefined>;
119
+ /** Applied to what was typed before `pattern` judges it. */
120
+ sanitize?: (raw: string) => string;
121
+ /** Applied to pasted text before it is inserted, for a code copied with its separators. */
122
+ pasteTransformer?: MaybeAccessor<((pasted: string) => string) | undefined>;
123
+ placeholder?: MaybeAccessor<string | undefined>;
124
+ /**
125
+ * What to do about the badge a password manager draws inside the field.
126
+ * @default "increase-width"
127
+ */
128
+ pushPasswordManagerStrategy?: MaybeAccessor<OtpPasswordManagerStrategy | undefined>;
129
+ }
130
+
131
+ export interface OtpField {
132
+ readonly value: Accessor<string>;
133
+ readonly isFocused: Accessor<boolean>;
134
+ readonly isHovering: Accessor<boolean>;
135
+ /** One entry per position, `maxLength` of them. */
136
+ readonly slots: Accessor<readonly OtpSlot[]>;
137
+ /**
138
+ * Whether the input should be widened by {@link OTP_BADGE_SPACE} and clipped
139
+ * back, which moves a password manager's badge out beside the boxes.
140
+ */
141
+ readonly willPushPasswordManagerBadge: Accessor<boolean>;
142
+ /** The handlers for the real input. */
143
+ readonly inputProps: {
144
+ onInput(event: Event): void;
145
+ onPaste(event: ClipboardEvent): void;
146
+ onFocus(): void;
147
+ onBlur(): void;
148
+ onSelect(): void;
149
+ onKeyUp(): void;
150
+ onClick(): void;
151
+ onMouseEnter(): void;
152
+ onMouseLeave(): void;
153
+ };
154
+ }
155
+
156
+ /** How far the input is widened to carry a password manager's badge out of the boxes. */
157
+ export const OTP_BADGE_SPACE = "40px";
158
+ const BADGE_SPACE_PX = 40;
159
+ /** How far in from the right edge a manager draws its badge. */
160
+ const BADGE_INSET = 18;
161
+
162
+ const PASSWORD_MANAGERS = [
163
+ "[data-lastpass-icon-root]",
164
+ "com-1password-button",
165
+ "[data-dashlanecreated]",
166
+ '[style$="2147483647 !important;"]',
167
+ ].join(",");
168
+
169
+ type InputRef = () => HTMLInputElement | null | undefined;
170
+ type ContainerRef = () => HTMLElement | null | undefined;
171
+
172
+ function toRegExp(pattern: string | RegExp | undefined): RegExp | null {
173
+ if (pattern === undefined) return null;
174
+ // A fresh one either way: `lastIndex` is state on a global or sticky regex,
175
+ // and reusing the caller's would fail every other test.
176
+ return typeof pattern === "string"
177
+ ? new RegExp(pattern)
178
+ : new RegExp(pattern.source, pattern.flags.replace(/[gy]/g, ""));
179
+ }
180
+
181
+ /**
182
+ * Whether a password manager has drawn a badge in the field, and whether there
183
+ * is room beside the field to move it to.
184
+ *
185
+ * Looked for only once the field is focused, and a few times over, because a
186
+ * manager injects its badge whenever it gets round to it. A known manager is
187
+ * recognised by its own markup; an unknown one by something other than the
188
+ * field answering a hit test where a badge would be.
189
+ */
190
+ function passwordManagerBadge(
191
+ input: InputRef,
192
+ container: ContainerRef,
193
+ isFocused: Accessor<boolean>,
194
+ strategy: Accessor<OtpPasswordManagerStrategy>,
195
+ ): Accessor<boolean> {
196
+ const [hasBadge, setHasBadge] = createSignal(false);
197
+ const [hasSpace, setHasSpace] = createSignal(false);
198
+ let done = false;
199
+
200
+ const look = (): void => {
201
+ const box = container();
202
+ const field = input();
203
+ if (done || box === null || box === undefined || field === null || field === undefined) return;
204
+
205
+ const rect = box.getBoundingClientRect();
206
+ setHasSpace(window.innerWidth - rect.right >= BADGE_SPACE_PX);
207
+
208
+ if (document.querySelectorAll(PASSWORD_MANAGERS).length === 0) {
209
+ const x = rect.left + box.offsetWidth - BADGE_INSET;
210
+ const y = rect.top + box.offsetHeight / 2;
211
+ const found =
212
+ typeof document.elementFromPoint === "function" ? document.elementFromPoint(x, y) : null;
213
+ if (found === null || found === field || box.contains(found)) return;
214
+ }
215
+ done = true;
216
+ setHasBadge(true);
217
+ };
218
+
219
+ createEffect(
220
+ () => (strategy() === "none" || !isFocused() ? null : strategy()),
221
+ (active) => {
222
+ if (active === null) return undefined;
223
+ const timers = [0, 2000, 5000].map((delay) => setTimeout(look, delay));
224
+ timers.push(
225
+ setTimeout(() => {
226
+ done = true;
227
+ }, 6000),
228
+ );
229
+ return () => {
230
+ for (const timer of timers) clearTimeout(timer);
231
+ };
232
+ },
233
+ );
234
+
235
+ return () => strategy() === "increase-width" && hasBadge() && hasSpace();
236
+ }
237
+
238
+ /**
239
+ * The state of a one-time-code field over the real input at `input`.
240
+ *
241
+ * `container` is the element the boxes are in, which is what a password
242
+ * manager's badge is looked for against.
243
+ */
244
+ export function otpField(
245
+ options: OtpFieldOptions,
246
+ input: InputRef,
247
+ container: ContainerRef = () => null,
248
+ ): OtpField {
249
+ const [inner, setInner] = createSignal(access(options.defaultValue) ?? "");
250
+ const [isFocused, setFocused] = createSignal(false);
251
+ const [isHovering, setHovering] = createSignal(false);
252
+ const [mirror, setMirror] = createSignal<OtpSelection>({ start: null, end: null });
253
+
254
+ const maxLength = (): number => access(options.maxLength);
255
+ const value = (): string => access(options.value) ?? inner();
256
+
257
+ // The gesture's own copies: an `input` event is handled in the tick it
258
+ // arrives, and a signal write is not published until the flush.
259
+ let held = value();
260
+ let previous: OtpSelection = { start: null, end: null };
261
+
262
+ const sync = (): void => {
263
+ const element = input();
264
+ if (element === null || element === undefined) return;
265
+ // The root's, not the document's: inside a shadow tree the document only
266
+ // ever reports the host.
267
+ const root = element.getRootNode() as Document | ShadowRoot;
268
+ if (root.activeElement !== element) {
269
+ // Every field on the page hears every selection change, so one that was
270
+ // already idle says nothing.
271
+ if (previous.start === null && previous.end === null) return;
272
+ previous = { start: null, end: null };
273
+ setMirror(previous);
274
+ return;
275
+ }
276
+
277
+ const next = otpSelection({
278
+ value: element.value,
279
+ maxLength: maxLength(),
280
+ start: element.selectionStart,
281
+ end: element.selectionEnd,
282
+ direction: element.selectionDirection,
283
+ previous,
284
+ });
285
+ if (
286
+ next.start !== null &&
287
+ next.end !== null &&
288
+ (next.start !== element.selectionStart || next.end !== element.selectionEnd)
289
+ ) {
290
+ element.setSelectionRange(next.start, next.end, next.direction);
291
+ }
292
+ if (next.start === previous.start && next.end === previous.end) return;
293
+ previous = next;
294
+ setMirror(next);
295
+ };
296
+
297
+ const commit = (next: string): void => {
298
+ held = next;
299
+ if (access(options.value) === undefined) setInner(next);
300
+ options.onChange?.(next);
301
+ };
302
+
303
+ const accepts = (candidate: string): boolean => {
304
+ if (candidate.length === 0) return true;
305
+ const pattern = toRegExp(access(options.pattern));
306
+ return pattern === null || pattern.test(candidate);
307
+ };
308
+
309
+ if (typeof document !== "undefined") {
310
+ // The one event that hears an arrow key, a drag and a programmatic change
311
+ // alike. It fires on the document, for whichever field holds the selection.
312
+ document.addEventListener("selectionchange", sync, { capture: true });
313
+ onCleanup(() => document.removeEventListener("selectionchange", sync, { capture: true }));
314
+ }
315
+
316
+ let before: string | undefined;
317
+ createEffect(
318
+ () => [value(), maxLength()] as const,
319
+ ([next, full]) => {
320
+ held = next;
321
+ if (before !== undefined && next !== before && before.length < full && next.length === full) {
322
+ options.onComplete?.(next);
323
+ }
324
+ before = next;
325
+ return undefined;
326
+ },
327
+ );
328
+
329
+ const willPushPasswordManagerBadge = passwordManagerBadge(
330
+ input,
331
+ container,
332
+ isFocused,
333
+ () => access(options.pushPasswordManagerStrategy) ?? "increase-width",
334
+ );
335
+
336
+ const slots = (): readonly OtpSlot[] => {
337
+ const current = value();
338
+ const { start, end } = mirror();
339
+ const focused = isFocused();
340
+ const placeholder = access(options.placeholder);
341
+ const count = maxLength();
342
+ const out: OtpSlot[] = [];
343
+ for (let index = 0; index < count; index++) {
344
+ const char = current[index] ?? null;
345
+ // At the very end of a full value there is no box past the last, so the
346
+ // caret belongs to the last one.
347
+ const caret = start === null ? null : Math.min(start, count - 1);
348
+ const isActive =
349
+ focused &&
350
+ start !== null &&
351
+ end !== null &&
352
+ (start === end ? index === caret : index >= start && index < end);
353
+ out.push({
354
+ char,
355
+ placeholderChar: current.length === 0 ? (placeholder?.[index] ?? null) : null,
356
+ isActive,
357
+ hasFakeCaret: isActive && char === null,
358
+ });
359
+ }
360
+ return out;
361
+ };
362
+
363
+ return {
364
+ value,
365
+ isFocused,
366
+ isHovering,
367
+ slots,
368
+ willPushPasswordManagerBadge,
369
+ inputProps: {
370
+ onInput(event) {
371
+ const element = event.target as HTMLInputElement;
372
+ const raw =
373
+ options.sanitize === undefined ? element.value : options.sanitize(element.value);
374
+ const next = raw.slice(0, maxLength());
375
+ if (!accepts(next)) {
376
+ element.value = held;
377
+ sync();
378
+ return;
379
+ }
380
+ if (element.value !== next) element.value = next;
381
+ commit(next);
382
+ sync();
383
+ },
384
+ onPaste(event) {
385
+ const transform = access(options.pasteTransformer);
386
+ const element = input();
387
+ // Without a transformer the browser's own paste is right, and arrives
388
+ // as an `input` event like any other change.
389
+ if (transform === undefined || element === null || element === undefined) return;
390
+ const pasted = transform(event.clipboardData?.getData("text/plain") ?? "");
391
+ event.preventDefault();
392
+
393
+ const start = element.selectionStart ?? held.length;
394
+ const end = element.selectionEnd ?? start;
395
+ const next = (held.slice(0, start) + pasted + held.slice(end)).slice(0, maxLength());
396
+ if (!accepts(next)) return;
397
+
398
+ element.value = next;
399
+ commit(next);
400
+ element.setSelectionRange(Math.min(next.length, maxLength() - 1), next.length);
401
+ sync();
402
+ },
403
+ onFocus() {
404
+ const element = input();
405
+ if (element !== null && element !== undefined) {
406
+ // The next position to fill, or the last character of a full value:
407
+ // wherever the click landed, that is what typing should act on.
408
+ const length = element.value.length;
409
+ element.setSelectionRange(Math.min(length, maxLength() - 1), length);
410
+ }
411
+ setFocused(true);
412
+ sync();
413
+ },
414
+ onBlur() {
415
+ setFocused(false);
416
+ previous = { start: null, end: null };
417
+ setMirror(previous);
418
+ },
419
+ onSelect: sync,
420
+ onKeyUp: sync,
421
+ onClick: sync,
422
+ onMouseEnter() {
423
+ setHovering(true);
424
+ },
425
+ onMouseLeave() {
426
+ setHovering(false);
427
+ },
428
+ },
429
+ };
430
+ }
@@ -0,0 +1,157 @@
1
+ /**
2
+ * The arrow on a popover or a tooltip, pointing at the trigger.
3
+ *
4
+ * Its shape is the caller's (an SVG, a rotated square); what is here is where
5
+ * it goes. It sits outside the overlay's edge on the side facing the trigger,
6
+ * which is the side the overlay ended up on after any flip and not the one it
7
+ * asked for, and along that edge it lines up with the trigger's centre.
8
+ *
9
+ * Both come from the overlay. The side is its placement; the position along
10
+ * the edge is `overlayPosition`'s `arrowProps`, measured once the overlay has
11
+ * been shifted to fit the viewport, since after a shift the overlay's middle
12
+ * is no longer the trigger's. An overlay that offers only its side gets an
13
+ * arrow centred on its own edge.
14
+ *
15
+ * `data-placement` names the side, so a stylesheet can turn the shape to face
16
+ * the trigger.
17
+ */
18
+
19
+ import {
20
+ cells,
21
+ type Accessor,
22
+ type Child,
23
+ createContext,
24
+ getContext,
25
+ type Incoming,
26
+ provide,
27
+ } from "@barqjs/core";
28
+ import { mergeRefs, type RefTarget } from "@barqjs/primitives/refs";
29
+ import type { Axis } from "./overlays.ts";
30
+ import {
31
+ access,
32
+ type DOMProps,
33
+ filterDOMProps,
34
+ fromProps,
35
+ type MaybeAccessor,
36
+ mergeProps,
37
+ type StyleProps,
38
+ } from "./utils.ts";
39
+
40
+ export interface OverlayArrowValue {
41
+ /** The side of the trigger the overlay is on, after any flip. */
42
+ placement: Accessor<Axis | null>;
43
+ /** `overlayPosition`'s `arrowProps`: the measured offset along the edge. */
44
+ arrowProps?: DOMProps;
45
+ /** Where the arrow's element goes, for the overlay to measure it. */
46
+ ref?: (element: Element | null) => void;
47
+ }
48
+
49
+ const OverlayArrowContext = createContext<OverlayArrowValue | null>(null);
50
+
51
+ export interface OverlayArrowProviderProps {
52
+ value: OverlayArrowValue;
53
+ children?: Child;
54
+ }
55
+
56
+ /** Offer an overlay's placement and arrow position to an {@link OverlayArrow} inside it. */
57
+ export function OverlayArrowProvider(props: Incoming<OverlayArrowProviderProps>) {
58
+ return provide(
59
+ OverlayArrowContext,
60
+ () => props.value(),
61
+ () => props.children as unknown,
62
+ );
63
+ }
64
+
65
+ /**
66
+ * Where the enclosing overlay is, as its {@link OverlayArrowProvider} says. A
67
+ * `<Popover>` and a `<Tooltip>` each provide one.
68
+ */
69
+ export function useOverlayArrow(): OverlayArrowValue | null {
70
+ return getContext(OverlayArrowContext) ?? null;
71
+ }
72
+
73
+ type CrossOffset = Partial<Record<"left" | "top", string>>;
74
+
75
+ export interface OverlayArrowOptions {
76
+ placement: MaybeAccessor<Axis | null>;
77
+ arrowProps?: DOMProps;
78
+ }
79
+
80
+ export interface OverlayArrowResult {
81
+ arrowProps: DOMProps;
82
+ placement: Accessor<Axis | null>;
83
+ }
84
+
85
+ export function overlayArrow(options: OverlayArrowOptions): OverlayArrowResult {
86
+ const placement = (): Axis | null => access(options.placement);
87
+ const measured = (): CrossOffset => {
88
+ const style = access(options.arrowProps?.style as MaybeAccessor<CrossOffset | undefined>);
89
+ return style ?? {};
90
+ };
91
+
92
+ return {
93
+ placement,
94
+ arrowProps: {
95
+ "data-placement": placement,
96
+ style: () => {
97
+ const side = placement();
98
+ const vertical = side === "top" || side === "bottom";
99
+ const offset = measured();
100
+ const style: Record<string, string> = { position: "absolute" };
101
+ if (side !== null) style[side] = "100%";
102
+ const along = vertical ? offset.left : offset.top;
103
+ if (along !== undefined) {
104
+ style[vertical ? "left" : "top"] = along;
105
+ } else if (side !== null) {
106
+ style[vertical ? "left" : "top"] = "50%";
107
+ style.transform = vertical ? "translateX(-50%)" : "translateY(-50%)";
108
+ }
109
+ return style;
110
+ },
111
+ },
112
+ };
113
+ }
114
+
115
+ export interface OverlayArrowComponentProps extends StyleProps {
116
+ children?: Child;
117
+ ref?: RefTarget<HTMLDivElement>;
118
+ }
119
+
120
+ /**
121
+ * ```tsx
122
+ * <Popover triggerRef={trigger} isOpen={open()}>
123
+ * <OverlayArrow>
124
+ * <svg width={12} height={12} viewBox="0 0 12 12"><path d="M0 0 L6 6 L12 0" /></svg>
125
+ * </OverlayArrow>
126
+ * …
127
+ * </Popover>
128
+ * ```
129
+ */
130
+ export function OverlayArrow(props: OverlayArrowComponentProps) {
131
+ const overlay = useOverlayArrow();
132
+ const { arrowProps } = overlayArrow({
133
+ placement: () => overlay?.placement() ?? null,
134
+ arrowProps: overlay?.arrowProps,
135
+ });
136
+
137
+ const elementProps = mergeProps(
138
+ arrowProps,
139
+ filterDOMProps(fromProps(cells(props)), { global: true }),
140
+ {
141
+ class: () => props.class ?? props.className,
142
+ // The caller's style on top of the position, so a size or a colour does
143
+ // not have to restate where the arrow goes.
144
+ style: () => ({
145
+ ...access(arrowProps.style as MaybeAccessor<Record<string, string>>),
146
+ ...props.style,
147
+ }),
148
+ "data-testid": () => props["data-testid"],
149
+ },
150
+ );
151
+
152
+ return (
153
+ <div {...elementProps} ref={mergeRefs(overlay?.ref, props.ref)}>
154
+ {props.children}
155
+ </div>
156
+ );
157
+ }