@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/utils.ts ADDED
@@ -0,0 +1,787 @@
1
+ /**
2
+ * The prop plumbing every hook in this package shares.
3
+ *
4
+ * Two things here are not what the same-named helper in `@barqjs/core` does,
5
+ * and the difference is the point:
6
+ *
7
+ * - {@link mergeProps} CHAINS event handlers and COMBINES `class`, where the
8
+ * core's overrides. Two hooks both need `onKeyDown` on one element, and the
9
+ * last one to be merged is not more correct than the first.
10
+ * - {@link id} hands back an accessor rather than a string, because
11
+ * {@link mergeIds} can repoint it: when two components label the same
12
+ * element, one id has to win and everything already pointing at the loser
13
+ * has to follow.
14
+ */
15
+
16
+ import {
17
+ asRecord,
18
+ type Accessor,
19
+ type Child,
20
+ type Incoming,
21
+ createContext,
22
+ createUniqueId,
23
+ getContext,
24
+ getOwner,
25
+ install,
26
+ createSignal,
27
+ untrack,
28
+ } from "@barqjs/core";
29
+ import { mergeRefs, type RefTarget } from "@barqjs/primitives/refs";
30
+ import { access, type MaybeAccessor } from "@barqjs/primitives/utils";
31
+
32
+ export type { MaybeAccessor };
33
+ export { access };
34
+
35
+ /** What a hook writes onto an element: static values, accessors, handlers. */
36
+ export type DOMProps = Record<string, unknown>;
37
+
38
+ /**
39
+ * A callback option that may have arrived wrapped in a Cell.
40
+ *
41
+ * Inside a component every prop is a Cell, callbacks included, so
42
+ * `getTextValue={(item) => item.name}` reaches the callee as a function that
43
+ * RETURNS the callback. The two are told apart by arity: an option like this
44
+ * always takes at least one argument, and a Cell takes none — the same rule
45
+ * `access` uses, and sound here for the same reason.
46
+ */
47
+ export function callback<A extends unknown[], R>(
48
+ value: MaybeAccessor<((...args: A) => R) | undefined> | undefined,
49
+ ): ((...args: A) => R) | undefined {
50
+ if (typeof value !== "function") return undefined;
51
+ if (value.length === 0) return (value as () => ((...args: A) => R) | undefined)();
52
+ return value as (...args: A) => R;
53
+ }
54
+
55
+ /** One function calling each of `fns` in order with the same arguments. */
56
+ export function chain<Args extends unknown[]>(
57
+ ...fns: (((...args: Args) => void) | undefined | null)[]
58
+ ): (...args: Args) => void {
59
+ return (...args: Args): void => {
60
+ for (const fn of fns) fn?.(...args);
61
+ };
62
+ }
63
+
64
+ const HANDLER = /^on[A-Z]/;
65
+
66
+ function isHandlerKey(key: string): boolean {
67
+ return HANDLER.test(key);
68
+ }
69
+
70
+ function combineTokens(a: unknown, b: unknown): unknown {
71
+ const empty = (value: unknown): boolean => value === undefined || value === null || value === "";
72
+ if (empty(a)) return b;
73
+ if (empty(b)) return a;
74
+ if (typeof a === "function" || typeof b === "function") {
75
+ return (): string | undefined => {
76
+ const left = access(a);
77
+ const right = access(b);
78
+ const joined = [left, right].filter(Boolean).join(" ");
79
+ return joined === "" ? undefined : joined;
80
+ };
81
+ }
82
+ return `${String(a)} ${String(b)}`;
83
+ }
84
+
85
+ /**
86
+ * Later sources win, except where losing would drop behaviour:
87
+ *
88
+ * - `on*` handlers are chained, in source order.
89
+ * - `class` and `className` are concatenated.
90
+ * - `aria-describedby` is concatenated. Descriptions ACCUMULATE: a field's
91
+ * help text, its error, and a tooltip on top of both are three descriptions
92
+ * of one control, and the last hook to be merged is not the only one that
93
+ * had something to say. A label does not work that way, so
94
+ * `aria-labelledby` still overrides.
95
+ * - `id`s are merged, so both labels keep pointing at one element.
96
+ * - `ref`s are merged, so both consumers get the node.
97
+ * - a later `undefined` does not override an earlier value.
98
+ *
99
+ * Values may be accessors; nothing here calls one, so the result stays as lazy
100
+ * as its sources.
101
+ */
102
+ export function mergeProps(...sources: (DOMProps | null | undefined)[]): Record<string, unknown> {
103
+ const result: Record<string, unknown> = { ...sources[0] };
104
+
105
+ for (let i = 1; i < sources.length; i++) {
106
+ const source = sources[i];
107
+ if (source === null || source === undefined) continue;
108
+
109
+ for (const key in source) {
110
+ const a = result[key];
111
+ const b = source[key];
112
+
113
+ if (typeof a === "function" && typeof b === "function" && isHandlerKey(key)) {
114
+ result[key] = chain(a as (...args: unknown[]) => void, b as (...args: unknown[]) => void);
115
+ } else if (key === "class" || key === "className" || key === "aria-describedby") {
116
+ result[key] = combineTokens(a, b);
117
+ } else if (key === "id" && a !== undefined && b !== undefined) {
118
+ result[key] = mergeIds(a as MaybeAccessor<string>, b as MaybeAccessor<string>);
119
+ } else if (key === "ref" && a !== undefined && b !== undefined) {
120
+ result[key] = mergeRefs(a as RefTarget<never>, b as RefTarget<never>);
121
+ } else {
122
+ result[key] = b !== undefined ? b : a;
123
+ }
124
+ }
125
+ }
126
+
127
+ return result;
128
+ }
129
+
130
+ // ---------------------------------------------------------------------------
131
+ // Identifiers
132
+ // ---------------------------------------------------------------------------
133
+
134
+ /**
135
+ * Every accessor handed out for a given id value, so {@link mergeIds} can
136
+ * repoint them all at once.
137
+ *
138
+ * A plain `Map` keyed by string leaks nothing that matters here: the entry is
139
+ * removed when the last holder's scope disposes, and a component that never
140
+ * disposes was going to hold its id anyway.
141
+ */
142
+ const idGroups = new Map<string, { set: (next: string) => void }[]>();
143
+
144
+ /**
145
+ * A stable, SSR-safe identifier.
146
+ *
147
+ * The value is `createUniqueId`'s: the declaration's position among the scopes
148
+ * of its render, so the server and the client produce the same string for the
149
+ * same element and hydration matches.
150
+ *
151
+ * ```tsx
152
+ * const labelId = id();
153
+ * <span id={labelId}>Name</span>
154
+ * <input aria-labelledby={labelId} />
155
+ * ```
156
+ */
157
+ export function id(given?: MaybeAccessor<string | undefined>): Accessor<string> {
158
+ const generated = createUniqueId();
159
+
160
+ // `mergeIds` repoints this from a component body, and a second merge in the
161
+ // same body asks where the first one left it. The value therefore lives
162
+ // beside the signal, which only tells an attribute already bound to look
163
+ // again.
164
+ let now = generated;
165
+ const [track, publish] = createSignal(generated, { ownedWrite: true });
166
+ const current = (): string => {
167
+ track();
168
+ return now;
169
+ };
170
+ const entry = {
171
+ set: (next: string): void => {
172
+ now = next;
173
+ publish(next);
174
+ },
175
+ };
176
+
177
+ const group = idGroups.get(generated);
178
+ if (group === undefined) idGroups.set(generated, [entry]);
179
+ else group.push(entry);
180
+
181
+ if (given === undefined) return current;
182
+ return () => access(given) ?? current();
183
+ }
184
+
185
+ function isEmptyId(value: unknown): boolean {
186
+ return value === undefined || value === null || value === "";
187
+ }
188
+
189
+ /**
190
+ * One id for two components that both wrote one onto the same element.
191
+ *
192
+ * Whichever of the two was handed out by {@link id} loses its own value and
193
+ * follows the other, so an `aria-labelledby` written before the merge still
194
+ * resolves. When neither is ours, the later one wins, as `mergeProps` would.
195
+ */
196
+ export function mergeIds(
197
+ a: MaybeAccessor<string>,
198
+ b: MaybeAccessor<string>,
199
+ ): MaybeAccessor<string> {
200
+ const left = access(a);
201
+ const right = access(b);
202
+ if (left === right) return a;
203
+
204
+ // A side that names no id has nothing to merge: repointing a generated id
205
+ // at it would leave the element with no id and every reference to it
206
+ // dangling. Whichever side has one keeps it, and an empty one that later
207
+ // gains a value still wins, as `mergeProps` lets a later value win.
208
+ if (isEmptyId(left) || isEmptyId(right)) {
209
+ return () => {
210
+ const later = access(b);
211
+ return isEmptyId(later) ? access(a) : later;
212
+ };
213
+ }
214
+
215
+ const leftGroup = idGroups.get(left);
216
+ if (leftGroup !== undefined) {
217
+ for (const entry of leftGroup) entry.set(right);
218
+ idGroups.delete(left);
219
+ const rightGroup = idGroups.get(right);
220
+ if (rightGroup === undefined) idGroups.set(right, leftGroup);
221
+ else rightGroup.push(...leftGroup);
222
+ return b;
223
+ }
224
+
225
+ const rightGroup = idGroups.get(right);
226
+ if (rightGroup !== undefined) {
227
+ for (const entry of rightGroup) entry.set(left);
228
+ idGroups.delete(right);
229
+ idGroups.set(left, rightGroup);
230
+ return a;
231
+ }
232
+
233
+ return b;
234
+ }
235
+
236
+ /**
237
+ * `aria-labelledby`/`aria-label` for a widget whose label lives elsewhere.
238
+ *
239
+ * Returns nothing when neither is given, so a caller can spread the result
240
+ * unconditionally without writing an empty `aria-labelledby`.
241
+ */
242
+ export function labelProps(props: {
243
+ "aria-label"?: MaybeAccessor<string | undefined>;
244
+ "aria-labelledby"?: MaybeAccessor<string | undefined>;
245
+ defaultLabel?: MaybeAccessor<string | undefined>;
246
+ }): DOMProps {
247
+ return {
248
+ "aria-label": () => access(props["aria-label"]) ?? access(props.defaultLabel),
249
+ "aria-labelledby": () => access(props["aria-labelledby"]),
250
+ };
251
+ }
252
+
253
+ // ---------------------------------------------------------------------------
254
+ // filterDOMProps
255
+ // ---------------------------------------------------------------------------
256
+
257
+ const LABELLING = new Set(["aria-label", "aria-labelledby", "aria-describedby", "aria-details"]);
258
+
259
+ const LINK = new Set(["href", "hrefLang", "target", "rel", "download", "ping", "referrerPolicy"]);
260
+
261
+ /**
262
+ * The global attributes a component forwards.
263
+ *
264
+ * `tabIndex` and `title` are as global as `dir` is, and both are load-bearing
265
+ * rather than decorative: an overlay with nothing focusable inside needs
266
+ * `tabIndex={-1}` on itself or a focus scope has nowhere to put focus, and
267
+ * Escape — whose handler is on the overlay — then never reaches it.
268
+ */
269
+ const GLOBAL_ATTRS = new Set(["dir", "lang", "hidden", "inert", "translate", "tabIndex", "title"]);
270
+
271
+ const GLOBAL_EVENTS = new Set([
272
+ // The focus four. A collection here moves REAL DOM focus through its items
273
+ // rather than a virtual highlight, so `onFocus` on an item is how a caller
274
+ // hears about keyboard browsing — and without these it was filtered out,
275
+ // leaving the pointer as the only observable way through a menu.
276
+ "onFocus",
277
+ "onBlur",
278
+ "onFocusIn",
279
+ "onFocusOut",
280
+ "onClick",
281
+ "onAuxClick",
282
+ "onContextMenu",
283
+ "onDoubleClick",
284
+ "onMouseDown",
285
+ "onMouseEnter",
286
+ "onMouseLeave",
287
+ "onMouseMove",
288
+ "onMouseOut",
289
+ "onMouseOver",
290
+ "onMouseUp",
291
+ "onTouchCancel",
292
+ "onTouchEnd",
293
+ "onTouchMove",
294
+ "onTouchStart",
295
+ "onPointerDown",
296
+ "onPointerMove",
297
+ "onPointerUp",
298
+ "onPointerCancel",
299
+ "onPointerEnter",
300
+ "onPointerLeave",
301
+ "onPointerOver",
302
+ "onPointerOut",
303
+ "onGotPointerCapture",
304
+ "onLostPointerCapture",
305
+ "onScroll",
306
+ "onWheel",
307
+ "onAnimationStart",
308
+ "onAnimationEnd",
309
+ "onAnimationIteration",
310
+ "onTransitionCancel",
311
+ "onTransitionEnd",
312
+ "onTransitionRun",
313
+ "onTransitionStart",
314
+ ]);
315
+
316
+ const DATA_ATTR = /^data-/;
317
+
318
+ export interface FilterDOMPropsOptions {
319
+ /** Include `aria-label`, `aria-labelledby`, `aria-describedby`, `aria-details`. */
320
+ labelable?: boolean;
321
+ /** Include the `<a>` attributes. */
322
+ isLink?: boolean;
323
+ /** Include `dir`, `lang`, `hidden`, `inert`, `translate`. */
324
+ global?: boolean;
325
+ /** Include the global DOM events. Defaults to `global`. */
326
+ events?: boolean;
327
+ /** Any other names to keep. */
328
+ propNames?: ReadonlySet<string>;
329
+ /**
330
+ * Keep `id`. @default true
331
+ *
332
+ * `false` for the OUTER element of a control that wraps a hidden input in a
333
+ * label — a checkbox, a switch, a radio, a colour swatch. `id` belongs on
334
+ * the input, which is the labelable element: an `id` on both writes it
335
+ * twice, `document.getElementById` answers with the label because it comes
336
+ * first, and `<label for>` pointing at a `<label>` does nothing at all.
337
+ * Measured on the site's checkbox page as clicking the text toggling
338
+ * nothing.
339
+ */
340
+ id?: boolean;
341
+ }
342
+
343
+ /**
344
+ * The subset of a component's props that belongs on a DOM element.
345
+ *
346
+ * A widget's own options (`isDisabled`, `onSelectionChange`) must not reach
347
+ * the element: React tolerates unknown props by dropping them, but barq writes
348
+ * every unrecognised key as an attribute, so an unfiltered spread puts
349
+ * `isdisabled="true"` in the document.
350
+ */
351
+ export function filterDOMProps(props: object, options: FilterDOMPropsOptions = {}): DOMProps {
352
+ const { labelable, isLink, global, events = global, propNames, id: keepId = true } = options;
353
+ const filtered: DOMProps = {};
354
+ const source = props as DOMProps;
355
+
356
+ for (const key in source) {
357
+ if (!Object.hasOwn(source, key)) continue;
358
+ const keep =
359
+ (key === "id" && keepId) ||
360
+ (labelable === true && LABELLING.has(key)) ||
361
+ (isLink === true && LINK.has(key)) ||
362
+ (global === true && GLOBAL_ATTRS.has(key)) ||
363
+ (events === true &&
364
+ (GLOBAL_EVENTS.has(key) ||
365
+ (key.endsWith("Capture") && GLOBAL_EVENTS.has(key.slice(0, -7))))) ||
366
+ propNames?.has(key) === true ||
367
+ DATA_ATTR.test(key);
368
+ if (keep) filtered[key] = source[key];
369
+ }
370
+
371
+ return filtered;
372
+ }
373
+
374
+ // ---------------------------------------------------------------------------
375
+ // Numbers
376
+ // ---------------------------------------------------------------------------
377
+
378
+ export function clamp(
379
+ value: number,
380
+ min = Number.NEGATIVE_INFINITY,
381
+ max = Number.POSITIVE_INFINITY,
382
+ ): number {
383
+ return Math.min(Math.max(value, min), max);
384
+ }
385
+
386
+ /**
387
+ * `value` rounded to the number of decimals `step` implies.
388
+ *
389
+ * Without it, `0.1 + 0.2` reaches an `aria-valuenow` as `0.30000000000000004`
390
+ * and a screen reader reads all seventeen digits.
391
+ */
392
+ export function roundToStepPrecision(value: number, step: number): number {
393
+ let precision = 0;
394
+ const text = step.toString();
395
+ const exponent = text.toLowerCase().indexOf("e-");
396
+ if (exponent > 0) {
397
+ precision = Math.abs(Math.floor(Math.log10(Math.abs(step)))) + exponent;
398
+ } else {
399
+ const point = text.indexOf(".");
400
+ if (point >= 0) precision = text.length - point;
401
+ }
402
+
403
+ if (precision <= 0) return value;
404
+ const scale = 10 ** precision;
405
+ return Math.round(value * scale) / scale;
406
+ }
407
+
408
+ /** The nearest value reachable from `min` in whole `step`s, inside the range. */
409
+ export function snapValueToStep(
410
+ value: number,
411
+ min: number | undefined,
412
+ max: number | undefined,
413
+ step: number,
414
+ ): number {
415
+ const low = Number(min);
416
+ const high = Number(max);
417
+ const remainder = (value - (Number.isNaN(low) ? 0 : low)) % step;
418
+ let snapped = roundToStepPrecision(
419
+ Math.abs(remainder) * 2 >= step
420
+ ? value + Math.sign(remainder) * (step - Math.abs(remainder))
421
+ : value - remainder,
422
+ step,
423
+ );
424
+
425
+ if (!Number.isNaN(low)) {
426
+ if (snapped < low) {
427
+ snapped = low;
428
+ } else if (!Number.isNaN(high) && snapped > high) {
429
+ snapped = low + Math.floor(roundToStepPrecision((high - low) / step, step)) * step;
430
+ }
431
+ } else if (!Number.isNaN(high) && snapped > high) {
432
+ snapped = Math.floor(roundToStepPrecision(high / step, step)) * step;
433
+ }
434
+
435
+ return roundToStepPrecision(snapped, step);
436
+ }
437
+
438
+ export function toFixedNumber(value: number, digits: number, base = 10): number {
439
+ const scale = base ** digits;
440
+ return Math.round(value * scale) / scale;
441
+ }
442
+
443
+ // ---------------------------------------------------------------------------
444
+ // Controlled and uncontrolled state
445
+ // ---------------------------------------------------------------------------
446
+
447
+ /** The two halves of a piece of state a component may or may not own. */
448
+ export type Controllable<T> = [Accessor<T>, (next: T | ((previous: T) => T)) => void];
449
+
450
+ /**
451
+ * State the caller may control, and owns when it does.
452
+ *
453
+ * `value` present means controlled: reads go to the prop and the setter only
454
+ * reports. `value` absent means uncontrolled: the setter writes the signal
455
+ * behind this and reports as well. One component supports both without its
456
+ * body knowing which it got.
457
+ *
458
+ * ```ts
459
+ * const [isOpen, setOpen] = controllable(props.isOpen, () => props.defaultOpen?.() ?? false, props.onOpenChange?.());
460
+ * ```
461
+ */
462
+ export function controllable<T>(
463
+ value: MaybeAccessor<T | undefined> | undefined,
464
+ defaultValue: MaybeAccessor<T>,
465
+ onChange?: (value: T) => void,
466
+ ): Controllable<T> {
467
+ const isControlled = (): boolean => access(value) !== undefined;
468
+ const [internal, setInternal] = createSignal<T>(
469
+ (access(value) ?? access(defaultValue)) as Exclude<T, Function>,
470
+ );
471
+
472
+ // What the LAST setter call produced, kept only long enough for a second
473
+ // call in the same event to compose from it. A controlled parent has not
474
+ // re-run by then, so the prop still reads as the value before the first call.
475
+ let pending: { value: T } | null = null;
476
+ let scheduled = false;
477
+
478
+ const read = (): T => {
479
+ const controlled = access(value);
480
+ return controlled !== undefined ? (controlled as T) : internal();
481
+ };
482
+
483
+ const currentUntracked = (): T => {
484
+ if (pending !== null) return pending.value;
485
+ return untrack(read);
486
+ };
487
+
488
+ const set = (next: T | ((previous: T) => T)): void => {
489
+ const previous = currentUntracked();
490
+ const resolved = typeof next === "function" ? (next as (previous: T) => T)(previous) : next;
491
+ if (Object.is(previous, resolved)) return;
492
+
493
+ pending = { value: resolved };
494
+ if (!scheduled) {
495
+ scheduled = true;
496
+ queueMicrotask(() => {
497
+ scheduled = false;
498
+ pending = null;
499
+ });
500
+ }
501
+
502
+ // Written even when controlled, so a component that later drops the prop
503
+ // continues from where the caller left it rather than from its default.
504
+ if (!isControlled()) setInternal(() => resolved);
505
+ onChange?.(resolved);
506
+ };
507
+
508
+ return [read, set];
509
+ }
510
+
511
+ // ---------------------------------------------------------------------------
512
+ // Component props, as hook options
513
+ // ---------------------------------------------------------------------------
514
+
515
+ /**
516
+ * What a hook in this package accepts: every value option may be an accessor,
517
+ * and every handler is a plain function.
518
+ */
519
+ export type Options<P> = {
520
+ [K in keyof P]?: K extends `on${string}` ? P[K] : MaybeAccessor<P[K]>;
521
+ };
522
+
523
+ /**
524
+ * A component's props, as hook options.
525
+ *
526
+ * Inside a barq component EVERY prop is a Cell, handlers included: the caller
527
+ * wrote `onPress={handler}` and the compiler wrapped it, so `props.onPress` is
528
+ * `() => handler` rather than the handler. Passing that straight to a hook
529
+ * would bind a function that returns the handler and calls nothing.
530
+ *
531
+ * A value Cell is already a valid accessor and passes through untouched. A
532
+ * handler key — `on` followed by a capital — is wrapped in one stable function
533
+ * that reads the current Cell and invokes what it yields, so a handler prop
534
+ * that changes is followed without the hook re-running.
535
+ *
536
+ * ```tsx
537
+ * export function Button(props: Incoming<ButtonProps>) {
538
+ * const { buttonProps } = button(fromProps(props), domRef);
539
+ * return <button {...buttonProps}>{props.children}</button>;
540
+ * }
541
+ * ```
542
+ *
543
+ * Calling a hook directly, outside a component, needs none of this: write the
544
+ * options object by hand and pass handlers as themselves.
545
+ */
546
+ export function fromProps<P extends object>(props: Incoming<P>): Options<P> {
547
+ const wrappers = new Map<string, (...args: unknown[]) => void>();
548
+
549
+ return new Proxy(props, {
550
+ get(target, key: string | symbol): unknown {
551
+ const value = Reflect.get(target, key);
552
+ if (typeof key !== "string" || value === undefined || !HANDLER.test(key)) return value;
553
+
554
+ let wrapper = wrappers.get(key);
555
+ if (wrapper === undefined) {
556
+ wrapper = (...args: unknown[]): void => {
557
+ const carrier = Reflect.get(target, key) as (() => unknown) | undefined;
558
+ const handler = typeof carrier === "function" ? carrier() : carrier;
559
+ if (typeof handler === "function") (handler as (...a: unknown[]) => void)(...args);
560
+ };
561
+ wrappers.set(key, wrapper);
562
+ }
563
+ return wrapper;
564
+ },
565
+ }) as Options<P>;
566
+ }
567
+
568
+ // ---------------------------------------------------------------------------
569
+ // What the surroundings contribute to a control
570
+ // ---------------------------------------------------------------------------
571
+
572
+ export interface TriggerSlot {
573
+ /** Props for the control's own element. */
574
+ props: DOMProps;
575
+ /**
576
+ * The control's element, for whatever anchors to or measures it.
577
+ *
578
+ * Method syntax, so the parameter is checked BIVARIANTLY. A ref created for
579
+ * an `HTMLButtonElement` is what a menu trigger has, and a property-shaped
580
+ * `(element: Element | null) => void` refuses it under
581
+ * `strictFunctionTypes` — every caller then wrote the same cast, which is a
582
+ * claim nobody was checking. The element handed here is the control's own,
583
+ * so the narrower ref is the right one and the widening was the fiction.
584
+ *
585
+ * `this: void` because it is passed as a VALUE — `mergeRefs(domRef.set,
586
+ * slot.ref)` — and a method referenced unbound is what `unbound-method`
587
+ * exists to catch. Declaring that it uses no `this` is the difference between
588
+ * silencing that and answering it.
589
+ */
590
+ ref?(this: void, element: Element | null): void;
591
+ }
592
+
593
+ const TriggerSlotContext = createContext<TriggerSlot | null>(null);
594
+
595
+ /**
596
+ * Contribute props to the control rendered inside this component.
597
+ *
598
+ * A tooltip trigger has to write `aria-describedby` and its focus handlers on
599
+ * the control ITSELF. Focus does not bubble, so a wrapper never hears it, and
600
+ * a description on a wrapper describes the wrapper. The alternative — reaching
601
+ * into the child element and setting attributes on it — fights every part of
602
+ * the rendering model, so the trigger OFFERS and the control TAKES.
603
+ *
604
+ * Nesting accumulates rather than replaces: a button inside a menu trigger
605
+ * inside a tooltip trigger gets both, the inner one's handlers chained after
606
+ * the outer one's.
607
+ */
608
+ export function provideTriggerSlot(slot: TriggerSlot): void {
609
+ const owner = getOwner();
610
+ if (owner === null) return;
611
+ const outer = getContext(TriggerSlotContext) ?? null;
612
+ const merged: TriggerSlot =
613
+ outer === null
614
+ ? slot
615
+ : {
616
+ props: mergeProps(outer.props, slot.props),
617
+ ref:
618
+ outer.ref === undefined || slot.ref === undefined
619
+ ? (slot.ref ?? outer.ref)
620
+ : (element: Element | null): void => {
621
+ outer.ref?.(element);
622
+ slot.ref?.(element);
623
+ },
624
+ };
625
+ install(owner, TriggerSlotContext, () => merged);
626
+ }
627
+
628
+ /** What the surroundings want on this control, if anything. */
629
+ export function triggerSlot(): TriggerSlot {
630
+ return getContext(TriggerSlotContext) ?? { props: {} };
631
+ }
632
+
633
+ /**
634
+ * End the reach of every trigger slot above, for what the calling component
635
+ * builds. A slot is meant for the control that opens an overlay, and the
636
+ * overlay's own content is written under the same trigger: without this a
637
+ * close button inside a popover takes the trigger's `onPress` and its
638
+ * `aria-expanded`, and pressing it opens what it was meant to close.
639
+ */
640
+ export function clearTriggerSlot(): void {
641
+ const owner = getOwner();
642
+ if (owner === null) return;
643
+ install(owner, TriggerSlotContext, () => null);
644
+ }
645
+
646
+ // ---------------------------------------------------------------------------
647
+ // The caller's element in a part's place
648
+ // ---------------------------------------------------------------------------
649
+
650
+ /** What a part hands the element a caller draws in its place. */
651
+ export interface PartRender {
652
+ /** The part's slot, class and state, and whatever the caller wrote on the part. */
653
+ props: DOMProps;
654
+ /** For the same element, so a `ref` written on the part still reaches it. */
655
+ ref: (element: Element | null) => void;
656
+ }
657
+
658
+ /**
659
+ * A part's `render`: another element in the place of the one it draws.
660
+ *
661
+ * shadcn's `asChild` clones its child; nothing is cloned here, so the caller
662
+ * builds the element from the props and the ref it is handed, as a trigger's
663
+ * `render` does.
664
+ *
665
+ * A part with state hands it as the second argument, every field an accessor:
666
+ * the element is built once, so a value read at that moment would never change.
667
+ *
668
+ * ```tsx
669
+ * <BreadcrumbLink render={(link) => <RouterLink {...link.props} ref={link.ref} to="/" />} />
670
+ *
671
+ * <QuestionnaireProgress
672
+ * render={(part, state) => (
673
+ * <div {...part.props} ref={part.ref}>{() => `${state.current()} / ${state.total()}`}</div>
674
+ * )}
675
+ * />
676
+ * ```
677
+ */
678
+ export type RenderPart<State = void> = (part: PartRender, state: State) => Child;
679
+
680
+ export function partRender(props: DOMProps): PartRender {
681
+ const { ref, ...rest } = props as DOMProps & { ref?: RefTarget<Element | null> };
682
+ return { props: asRecord(rest), ref: mergeRefs<Element | null>(ref) };
683
+ }
684
+
685
+ /**
686
+ * What every headless component in this package accepts on top of its own
687
+ * props: how it looks, and how a test finds it.
688
+ */
689
+ /**
690
+ * The events every component forwards, typed.
691
+ *
692
+ * `filterDOMProps(options, { global: true })` passes `GLOBAL_EVENTS` through to
693
+ * the element, and until these were declared the type said otherwise: a caller
694
+ * with a pointer handler to add had nowhere to put it, and spreading a props
695
+ * OBJECT instead is worse than nothing, because `fromProps` unwraps a component
696
+ * prop by CALLING it. A plain handler spread that way runs once, immediately,
697
+ * with no event.
698
+ */
699
+ export interface GlobalEvents {
700
+ onFocus?: (event: FocusEvent) => void;
701
+ onBlur?: (event: FocusEvent) => void;
702
+ onFocusIn?: (event: FocusEvent) => void;
703
+ onFocusOut?: (event: FocusEvent) => void;
704
+ onClick?: (event: MouseEvent) => void;
705
+ onAuxClick?: (event: MouseEvent) => void;
706
+ onContextMenu?: (event: MouseEvent) => void;
707
+ onDoubleClick?: (event: MouseEvent) => void;
708
+ onMouseDown?: (event: MouseEvent) => void;
709
+ onMouseEnter?: (event: MouseEvent) => void;
710
+ onMouseLeave?: (event: MouseEvent) => void;
711
+ onMouseMove?: (event: MouseEvent) => void;
712
+ onMouseOut?: (event: MouseEvent) => void;
713
+ onMouseOver?: (event: MouseEvent) => void;
714
+ onMouseUp?: (event: MouseEvent) => void;
715
+ onTouchCancel?: (event: TouchEvent) => void;
716
+ onTouchEnd?: (event: TouchEvent) => void;
717
+ onTouchMove?: (event: TouchEvent) => void;
718
+ onTouchStart?: (event: TouchEvent) => void;
719
+ onPointerDown?: (event: PointerEvent) => void;
720
+ onPointerMove?: (event: PointerEvent) => void;
721
+ onPointerUp?: (event: PointerEvent) => void;
722
+ onPointerCancel?: (event: PointerEvent) => void;
723
+ onPointerEnter?: (event: PointerEvent) => void;
724
+ onPointerLeave?: (event: PointerEvent) => void;
725
+ onPointerOver?: (event: PointerEvent) => void;
726
+ onPointerOut?: (event: PointerEvent) => void;
727
+ onGotPointerCapture?: (event: PointerEvent) => void;
728
+ onLostPointerCapture?: (event: PointerEvent) => void;
729
+ onScroll?: (event: Event) => void;
730
+ onWheel?: (event: WheelEvent) => void;
731
+ onAnimationStart?: (event: AnimationEvent) => void;
732
+ onAnimationEnd?: (event: AnimationEvent) => void;
733
+ onAnimationIteration?: (event: AnimationEvent) => void;
734
+ onTransitionCancel?: (event: TransitionEvent) => void;
735
+ onTransitionEnd?: (event: TransitionEvent) => void;
736
+ onTransitionRun?: (event: TransitionEvent) => void;
737
+ onTransitionStart?: (event: TransitionEvent) => void;
738
+ }
739
+
740
+ export interface StyleProps extends GlobalEvents {
741
+ class?: string;
742
+ className?: string;
743
+ style?: Record<string, string | number | undefined>;
744
+ id?: string;
745
+ /**
746
+ * The global attributes, which every component forwards.
747
+ *
748
+ * Declared here rather than on each component because the runtime already
749
+ * treats them uniformly — `filterDOMProps(options, { global: true })` — and a
750
+ * type that refused what the component then wrote to the element was the
751
+ * inconsistency this removes.
752
+ */
753
+ dir?: "ltr" | "rtl" | "auto";
754
+ lang?: string;
755
+ hidden?: boolean;
756
+ inert?: boolean;
757
+ translate?: "yes" | "no";
758
+ tabIndex?: number;
759
+ title?: string;
760
+ /** Anything `data-*`, which is how a design system marks the elements it styles. */
761
+ readonly [attribute: `data-${string}`]: unknown;
762
+ }
763
+
764
+ /**
765
+ * The presentation props, passed through untouched.
766
+ *
767
+ * `class` and `className` are both accepted because both are written in the
768
+ * wild; barq maps them to the same attribute.
769
+ */
770
+ export function styleProps(props: {
771
+ class?: () => string | undefined;
772
+ className?: () => string | undefined;
773
+ style?: () => Record<string, string | number | undefined> | undefined;
774
+ }): DOMProps {
775
+ const out: DOMProps = {};
776
+ // A key is only present when the caller GAVE it. Returning `style: () => …`
777
+ // unconditionally made this the last word on `style` in every merge that
778
+ // ends with it — `mergeProps` keeps the later value, and an accessor that
779
+ // yields `undefined` is still a value — so a popover with no `style` prop
780
+ // lost the `position: absolute` and the coordinates `overlayPosition` had
781
+ // just computed, and rendered in the document flow.
782
+ if (props.class !== undefined || props.className !== undefined) {
783
+ out.class = () => props.class?.() ?? props.className?.();
784
+ }
785
+ if (props.style !== undefined) out.style = () => props.style?.();
786
+ return out;
787
+ }