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