@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.
Files changed (76) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +293 -2
  3. package/package.json +347 -4
  4. package/src/breadcrumbs.tsx +296 -0
  5. package/src/button.tsx +342 -0
  6. package/src/calendar.tsx +1389 -0
  7. package/src/checkbox.tsx +570 -0
  8. package/src/collections.ts +976 -0
  9. package/src/color.ts +562 -0
  10. package/src/colorpicker.tsx +1478 -0
  11. package/src/combobox.tsx +2481 -0
  12. package/src/command.tsx +1184 -0
  13. package/src/date.ts +652 -0
  14. package/src/datefield.tsx +951 -0
  15. package/src/datepicker.tsx +556 -0
  16. package/src/dialog.tsx +890 -0
  17. package/src/disclosure.tsx +659 -0
  18. package/src/dom.ts +706 -0
  19. package/src/drawer.ts +674 -0
  20. package/src/focus.ts +1370 -0
  21. package/src/form.tsx +94 -0
  22. package/src/gridlist.tsx +563 -0
  23. package/src/i18n.ts +823 -0
  24. package/src/index.ts +1270 -0
  25. package/src/interactions/description.ts +73 -0
  26. package/src/interactions/flags.ts +35 -0
  27. package/src/interactions/focus-events.ts +218 -0
  28. package/src/interactions/focusable.ts +86 -0
  29. package/src/interactions/hover.ts +213 -0
  30. package/src/interactions/interact-outside.ts +123 -0
  31. package/src/interactions/keyboard.ts +105 -0
  32. package/src/interactions/listeners.ts +78 -0
  33. package/src/interactions/long-press.ts +160 -0
  34. package/src/interactions/modality.ts +416 -0
  35. package/src/interactions/move.ts +257 -0
  36. package/src/interactions/open-link.ts +193 -0
  37. package/src/interactions/press.ts +898 -0
  38. package/src/interactions/prevent-focus.ts +102 -0
  39. package/src/interactions/scroll-wheel.ts +43 -0
  40. package/src/interactions/text-selection.ts +77 -0
  41. package/src/interactions.ts +81 -0
  42. package/src/label.ts +128 -0
  43. package/src/link.tsx +381 -0
  44. package/src/listbox.tsx +721 -0
  45. package/src/live.ts +204 -0
  46. package/src/menu.tsx +2290 -0
  47. package/src/menubar.tsx +575 -0
  48. package/src/navigation.ts +735 -0
  49. package/src/numberfield.tsx +838 -0
  50. package/src/otp.ts +430 -0
  51. package/src/overlays.ts +1247 -0
  52. package/src/platform.ts +74 -0
  53. package/src/presence.ts +164 -0
  54. package/src/questionnaire.tsx +1712 -0
  55. package/src/radio.tsx +567 -0
  56. package/src/register-dom.ts +12 -0
  57. package/src/scroller.ts +1165 -0
  58. package/src/select.tsx +1665 -0
  59. package/src/selection.ts +1415 -0
  60. package/src/slider.tsx +1042 -0
  61. package/src/splitter.ts +1152 -0
  62. package/src/static-collection.ts +211 -0
  63. package/src/switch.tsx +186 -0
  64. package/src/table.tsx +0 -0
  65. package/src/tabs.tsx +1018 -0
  66. package/src/tag.tsx +452 -0
  67. package/src/textfield.tsx +417 -0
  68. package/src/toast.ts +658 -0
  69. package/src/toggle-input.tsx +48 -0
  70. package/src/toggle.ts +321 -0
  71. package/src/togglegroup.ts +365 -0
  72. package/src/toolbar.tsx +179 -0
  73. package/src/tooltip.tsx +657 -0
  74. package/src/utils.ts +758 -0
  75. package/src/validation.ts +447 -0
  76. package/src/virtualizer.tsx +674 -0
package/src/slider.tsx ADDED
@@ -0,0 +1,1042 @@
1
+ /**
2
+ * Sliders: one or more thumbs on a track.
3
+ *
4
+ * Each thumb is a real `<input type="range">`, visually hidden under whatever
5
+ * the caller draws. That is not a shortcut — it is the only way to get the
6
+ * behaviour right without reimplementing it:
7
+ *
8
+ * - The arrow keys, Home, End and Page Up/Down all work, in the direction the
9
+ * platform expects, including the ones that differ between screen readers.
10
+ * - It participates in a form, and a reset puts it back.
11
+ * - Assistive technology announces it as a slider with a value, and iOS
12
+ * VoiceOver's rotor can adjust it, which no `role="slider"` div supports.
13
+ *
14
+ * What is left for this file is the geometry — where a press on the track puts
15
+ * the nearest thumb, and how far a drag moves it — and the ARIA that connects
16
+ * a group of thumbs to one label.
17
+ *
18
+ * A range slider's thumbs cannot cross: each one's minimum is the thumb below
19
+ * it and its maximum is the thumb above. Letting them swap would mean the same
20
+ * gesture produces a different value depending on how fast the pointer moved.
21
+ */
22
+
23
+ import {
24
+ type Accessor,
25
+ type Child,
26
+ For,
27
+ createMemo,
28
+ createContext,
29
+ createEffect,
30
+ getContext,
31
+ getOwner,
32
+ type Incoming,
33
+ install,
34
+ createSignal,
35
+ onSettled,
36
+ untrack,
37
+ } from "@barqjs/core";
38
+ import { isServer } from "@barqjs/web";
39
+ import { ref as makeRef, mergeRefs, type RefTarget } from "@barqjs/primitives/refs";
40
+ import { focusWithoutScrolling } from "./dom.ts";
41
+ import { focusRing } from "./focus.ts";
42
+ import { numberFormatter, useLocale } from "./i18n.ts";
43
+ import { focusable } from "./interactions/focusable.ts";
44
+ import { hover } from "./interactions/hover.ts";
45
+ import { globalListeners } from "./interactions/listeners.ts";
46
+ import { move } from "./interactions/move.ts";
47
+ import type { ElementRef } from "./interactions/press.ts";
48
+ import { label as useLabelHook, type LabelOptions } from "./label.ts";
49
+ import { visuallyHidden } from "./live.ts";
50
+ import type { Orientation } from "./selection.ts";
51
+ import { formReset } from "./toggle.ts";
52
+ import {
53
+ access,
54
+ clamp,
55
+ type DOMProps,
56
+ filterDOMProps,
57
+ fromProps,
58
+ id,
59
+ type MaybeAccessor,
60
+ mergeProps,
61
+ snapValueToStep,
62
+ type StyleProps,
63
+ styleProps,
64
+ } from "./utils.ts";
65
+
66
+ // ---------------------------------------------------------------------------
67
+ // State
68
+ // ---------------------------------------------------------------------------
69
+
70
+ const DEFAULT_MIN = 0;
71
+ const DEFAULT_MAX = 100;
72
+ const DEFAULT_STEP = 1;
73
+
74
+ export interface SliderStateOptions {
75
+ value?: MaybeAccessor<number | number[] | undefined>;
76
+ defaultValue?: MaybeAccessor<number | number[] | undefined>;
77
+ /** @default 0 */
78
+ minValue?: MaybeAccessor<number | undefined>;
79
+ /** @default 100 */
80
+ maxValue?: MaybeAccessor<number | undefined>;
81
+ /** @default 1 */
82
+ step?: MaybeAccessor<number | undefined>;
83
+ /** @default "horizontal" */
84
+ orientation?: MaybeAccessor<Orientation | undefined>;
85
+ isDisabled?: MaybeAccessor<boolean | undefined>;
86
+ /**
87
+ * Puts the minimum at the far end: the right of a horizontal slider (the
88
+ * left, right to left) and the top of a vertical one.
89
+ */
90
+ isInverted?: MaybeAccessor<boolean | undefined>;
91
+ /** How many steps two neighbouring thumbs must stay apart. @default 0 */
92
+ minStepsBetweenThumbs?: MaybeAccessor<number | undefined>;
93
+ /** How the value is spoken and shown. */
94
+ formatOptions?: MaybeAccessor<Intl.NumberFormatOptions | undefined>;
95
+ onChange?: (value: number[]) => void;
96
+ /** Called once, when the gesture that changed the value ends. */
97
+ onChangeEnd?: (value: number[]) => void;
98
+ }
99
+
100
+ export interface SliderState {
101
+ values: Accessor<number[]>;
102
+ defaultValues: Accessor<number[]>;
103
+ getThumbValue(index: number): number;
104
+ setThumbValue(index: number, value: number): void;
105
+ setThumbPercent(index: number, percent: number): void;
106
+ isThumbDragging(index: number): boolean;
107
+ setThumbDragging(index: number, dragging: boolean): void;
108
+ focusedThumb: Accessor<number | undefined>;
109
+ setFocusedThumb(index: number | undefined): void;
110
+ getThumbPercent(index: number): number;
111
+ getValuePercent(value: number): number;
112
+ getThumbValueLabel(index: number): string;
113
+ getFormattedValue(value?: number | number[]): string;
114
+ getThumbMinValue(index: number): number;
115
+ getThumbMaxValue(index: number): number;
116
+ getPercentValue(percent: number): number;
117
+ isThumbEditable(index: number): boolean;
118
+ setThumbEditable(index: number, editable: boolean): void;
119
+ incrementThumb(index: number, stepSize?: number): void;
120
+ decrementThumb(index: number, stepSize?: number): void;
121
+ step: Accessor<number>;
122
+ /** How far Page Up and Page Down move. A tenth of the range, at least a step. */
123
+ pageSize: Accessor<number>;
124
+ orientation: Accessor<Orientation>;
125
+ isInverted: Accessor<boolean>;
126
+ isDisabled: Accessor<boolean>;
127
+ }
128
+
129
+ function asArray(value: number | number[] | undefined): number[] | undefined {
130
+ if (value === undefined) return undefined;
131
+ return Array.isArray(value) ? [...value] : [value];
132
+ }
133
+
134
+ export function sliderState(options: SliderStateOptions): SliderState {
135
+ const min = (): number => access(options.minValue) ?? DEFAULT_MIN;
136
+ const max = (): number => access(options.maxValue) ?? DEFAULT_MAX;
137
+ const step = (): number => access(options.step) ?? DEFAULT_STEP;
138
+ const isDisabled = (): boolean => access(options.isDisabled) === true;
139
+
140
+ const pageSize = (): number => {
141
+ const size = (max() - min()) / 10;
142
+ return Math.max(snapValueToStep(size, 0, size + step(), step()), step());
143
+ };
144
+
145
+ const gap = (): number => Math.max(access(options.minStepsBetweenThumbs) ?? 0, 0) * step();
146
+
147
+ /**
148
+ * Every thumb snapped to the step, and penned in by its neighbours.
149
+ *
150
+ * In order, each against the one already placed below it, so two values that
151
+ * arrive closer than the gap are opened out upwards rather than crossing.
152
+ */
153
+ const restrict = (values: number[]): number[] => {
154
+ const out: number[] = [];
155
+ values.forEach((value, index) => {
156
+ const lower = index === 0 ? min() : (out[index - 1] as number) + gap();
157
+ const upper = max() - (values.length - 1 - index) * gap();
158
+ out.push(snapValueToStep(value, Math.min(lower, upper), upper, step()));
159
+ });
160
+ return out;
161
+ };
162
+
163
+ const controlled = (): number[] | undefined => {
164
+ const given = asArray(access(options.value));
165
+ return given === undefined ? undefined : restrict(given);
166
+ };
167
+
168
+ const [internal, setInternal] = createSignal<number[]>(
169
+ controlled() ?? restrict(asArray(access(options.defaultValue)) ?? [min()]),
170
+ );
171
+
172
+ const values = (): number[] => controlled() ?? internal();
173
+
174
+ // What the LAST write produced, so a gesture reads its own change back
175
+ // rather than the value a controlled owner has not caught up with yet.
176
+ let live = values();
177
+
178
+ const initial = values();
179
+
180
+ const setValues = (next: number[]): void => {
181
+ live = next;
182
+ if (controlled() === undefined) setInternal(next);
183
+ options.onChange?.(next);
184
+ };
185
+
186
+ const [dragging, setDragging] = createSignal<boolean[]>(
187
+ new Array<boolean>(values().length).fill(false),
188
+ );
189
+ // What the last write to `dragging` produced. A keyboard change starts and
190
+ // ends its gesture in one tick, and the signal does not publish until the
191
+ // flush, so reading it back would find the gesture never begun.
192
+ let liveDragging: boolean[] = new Array(values().length).fill(false);
193
+ const editable: boolean[] = new Array(values().length).fill(true);
194
+ const [focused, setFocused] = createSignal<number | undefined>(undefined);
195
+
196
+ const getThumbMinValue = (index: number): number =>
197
+ index === 0 ? min() : (values()[index - 1] as number) + gap();
198
+ const getThumbMaxValue = (index: number): number =>
199
+ index === values().length - 1 ? max() : (values()[index + 1] as number) - gap();
200
+
201
+ const isThumbEditable = (index: number): boolean => editable[index] !== false;
202
+
203
+ const updateValue = (index: number, value: number): void => {
204
+ if (isDisabled() || !isThumbEditable(index)) return;
205
+ const snapped = snapValueToStep(
206
+ value,
207
+ getThumbMinValue(index),
208
+ getThumbMaxValue(index),
209
+ step(),
210
+ );
211
+ if (live[index] === snapped) return;
212
+ const next = [...live];
213
+ next[index] = snapped;
214
+ setValues(next);
215
+ };
216
+
217
+ const updateDragging = (index: number, isDragging: boolean): void => {
218
+ if (isDisabled() || !isThumbEditable(index)) return;
219
+ const current = liveDragging;
220
+ const wasDragging = current[index] === true;
221
+ if (isDragging) live = values();
222
+
223
+ const next = [...current];
224
+ next[index] = isDragging;
225
+ liveDragging = next;
226
+ setDragging(next);
227
+
228
+ // `onChangeEnd` fires once the whole gesture is over, not once per thumb:
229
+ // a two-thumb drag is one interaction.
230
+ if (wasDragging && !next.some(Boolean)) options.onChangeEnd?.(live);
231
+ };
232
+
233
+ const format = createMemo(() => numberFormatter(access(options.formatOptions))());
234
+ const locale = useLocale();
235
+ let listFormat: Intl.ListFormat | null = null;
236
+
237
+ const getFormattedValue = (value: number | number[] = values()): string => {
238
+ const list = Array.isArray(value) ? value : [value];
239
+ if (list.length === 0) return "";
240
+ if (list.length === 1) return format().format(list[0] as number);
241
+ if (list.length === 2) return format().formatRange(list[0] as number, list[1] as number);
242
+ if (listFormat === null) listFormat = new Intl.ListFormat(locale().locale, { type: "unit" });
243
+ return listFormat.format(list.map((entry) => format().format(entry)));
244
+ };
245
+
246
+ const getValuePercent = (value: number): number => (value - min()) / (max() - min());
247
+
248
+ const getPercentValue = (percent: number): number => {
249
+ const raw = percent * (max() - min()) + min();
250
+ const rounded = Math.round((raw - min()) / step()) * step() + min();
251
+ return clamp(rounded, min(), max());
252
+ };
253
+
254
+ return {
255
+ values,
256
+ defaultValues: () =>
257
+ access(options.defaultValue) !== undefined
258
+ ? restrict(asArray(access(options.defaultValue)) as number[])
259
+ : initial,
260
+ getThumbValue: (index) => values()[index] as number,
261
+ setThumbValue: updateValue,
262
+ setThumbPercent: (index, percent) => updateValue(index, getPercentValue(percent)),
263
+ isThumbDragging: (index) => dragging()[index] === true,
264
+ setThumbDragging: updateDragging,
265
+ focusedThumb: focused,
266
+ setFocusedThumb: (index) => setFocused(index),
267
+ getThumbPercent: (index) => getValuePercent(values()[index] as number),
268
+ getValuePercent,
269
+ getThumbValueLabel: (index) => getFormattedValue(values()[index]),
270
+ getFormattedValue,
271
+ getThumbMinValue,
272
+ getThumbMaxValue,
273
+ getPercentValue,
274
+ isThumbEditable,
275
+ setThumbEditable: (index, value) => {
276
+ editable[index] = value;
277
+ },
278
+ incrementThumb: (index, stepSize = 1) => {
279
+ const size = Math.max(stepSize, step());
280
+ updateValue(index, snapValueToStep((live[index] as number) + size, min(), max(), step()));
281
+ },
282
+ decrementThumb: (index, stepSize = 1) => {
283
+ const size = Math.max(stepSize, step());
284
+ updateValue(index, snapValueToStep((live[index] as number) - size, min(), max(), step()));
285
+ },
286
+ step,
287
+ pageSize,
288
+ orientation: () => access(options.orientation) ?? "horizontal",
289
+ isInverted: () => access(options.isInverted) === true,
290
+ isDisabled,
291
+ };
292
+ }
293
+
294
+ // ---------------------------------------------------------------------------
295
+ // Hooks
296
+ // ---------------------------------------------------------------------------
297
+
298
+ /**
299
+ * Whether a larger value sits at a smaller coordinate: nearer the left, or
300
+ * nearer the top.
301
+ *
302
+ * A vertical slider starts that way, because its minimum is at the bottom; a
303
+ * horizontal one only right to left. `isInverted` reverses whichever it was.
304
+ */
305
+ export function runsBackwards(state: SliderState, rtl: boolean): boolean {
306
+ const backwards = state.orientation() === "vertical" ? true : rtl;
307
+ return backwards !== state.isInverted();
308
+ }
309
+
310
+ /** The ids a slider's thumbs and its group share. */
311
+ function thumbId(base: string, index: number): string {
312
+ return `${base}-thumb-${index}`;
313
+ }
314
+
315
+ export interface SliderOptions extends LabelOptions {
316
+ trackRef: ElementRef;
317
+ /** The first thumb's id, when the caller chose it: what the label's press focuses. */
318
+ firstThumbId?: MaybeAccessor<string | undefined>;
319
+ isDisabled?: MaybeAccessor<boolean | undefined>;
320
+ "aria-describedby"?: MaybeAccessor<string | undefined>;
321
+ }
322
+
323
+ export interface SliderResult {
324
+ labelProps: DOMProps;
325
+ /** For the element holding every thumb: one group, one label. */
326
+ groupProps: DOMProps;
327
+ trackProps: DOMProps;
328
+ outputProps: DOMProps;
329
+ /** The base every thumb id is derived from. */
330
+ baseId: Accessor<string>;
331
+ }
332
+
333
+ export function slider(options: SliderOptions, state: SliderState): SliderResult {
334
+ const baseId = id();
335
+ const locale = useLocale();
336
+ const listeners = globalListeners();
337
+
338
+ const isVertical = (): boolean => state.orientation() === "vertical";
339
+ const flipped = (): boolean => runsBackwards(state, locale().direction === "rtl");
340
+
341
+ const { labelProps, fieldProps } = useLabelHook({
342
+ ...options,
343
+ // The label names the GROUP, not any one thumb: pointing it at the first
344
+ // thumb makes iOS VoiceOver announce that thumb as the whole slider.
345
+ labelElementType: "span",
346
+ });
347
+
348
+ let draggingIndex: number | null = null;
349
+ let position: number | null = null;
350
+ let pointer: number | null | undefined;
351
+
352
+ const trackSize = (): number => {
353
+ const track = access(options.trackRef) as Element | null;
354
+ if (track === null) return 0;
355
+ const box = track.getBoundingClientRect();
356
+ return isVertical() ? box.height : box.width;
357
+ };
358
+
359
+ const { moveProps } = move({
360
+ onMoveStart: () => {
361
+ position = null;
362
+ },
363
+ onMove: (event) => {
364
+ if (draggingIndex === null) return;
365
+ const size = trackSize();
366
+ if (size === 0) return;
367
+
368
+ if (position === null) position = state.getThumbPercent(draggingIndex) * size;
369
+
370
+ // Down is a LOWER value on a vertical slider, and right is a lower one
371
+ // in a right-to-left layout, so the delta is flipped rather than the
372
+ // value.
373
+ let delta = isVertical() ? event.deltaY : event.deltaX;
374
+ if (flipped()) delta = -delta;
375
+
376
+ position += delta;
377
+ state.setThumbPercent(draggingIndex, clamp(position / size, 0, 1));
378
+ },
379
+ onMoveEnd: () => {
380
+ if (draggingIndex === null) return;
381
+ state.setThumbDragging(draggingIndex, false);
382
+ draggingIndex = null;
383
+ },
384
+ });
385
+
386
+ /** The thumb a press at this point should pick up. */
387
+ const closestThumb = (value: number): number => {
388
+ const values = state.values();
389
+ const split = values.findIndex((entry) => value - entry < 0);
390
+ if (split === 0) return 0;
391
+ if (split === -1) return values.length - 1;
392
+ const before = values[split - 1] as number;
393
+ const after = values[split] as number;
394
+ // Stacked on top of each other: take the upper one, so a range that has
395
+ // collapsed to a point can still be opened out.
396
+ return Math.abs(before - value) < Math.abs(after - value) ? split - 1 : split;
397
+ };
398
+
399
+ const onUpTrack = (event: Event): void => {
400
+ const identifier =
401
+ (event as PointerEvent).pointerId ??
402
+ (event as TouchEvent).changedTouches?.[0]?.identifier ??
403
+ undefined;
404
+ if (identifier !== pointer) return;
405
+ if (draggingIndex !== null) {
406
+ state.setThumbDragging(draggingIndex, false);
407
+ draggingIndex = null;
408
+ }
409
+ listeners.removeAll();
410
+ };
411
+
412
+ const onDownTrack = (
413
+ event: Event,
414
+ identifier: number | undefined,
415
+ clientX: number,
416
+ clientY: number,
417
+ ): void => {
418
+ const track = access(options.trackRef) as Element | null;
419
+ if (track === null || access(options.isDisabled) === true) return;
420
+ if (state.values().some((_, index) => state.isThumbDragging(index))) return;
421
+
422
+ const box = track.getBoundingClientRect();
423
+ const size = isVertical() ? box.height : box.width;
424
+ if (size === 0) return;
425
+ const offset = (isVertical() ? clientY : clientX) - (isVertical() ? box.top : box.left);
426
+ let percent = offset / size;
427
+ if (flipped()) percent = 1 - percent;
428
+
429
+ const value = state.getPercentValue(percent);
430
+ const index = closestThumb(value);
431
+ if (index < 0 || !state.isThumbEditable(index)) return;
432
+
433
+ // Nothing loses focus: the press is picking a thumb up, not moving focus
434
+ // to the track.
435
+ event.preventDefault();
436
+ draggingIndex = index;
437
+ pointer = identifier;
438
+ state.setFocusedThumb(index);
439
+ state.setThumbDragging(index, true);
440
+ state.setThumbValue(index, value);
441
+
442
+ if (!isServer) {
443
+ const view = (track.ownerDocument.defaultView ?? window) as Window;
444
+ listeners.add(view, "mouseup", onUpTrack);
445
+ listeners.add(view, "touchend", onUpTrack);
446
+ listeners.add(view, "pointerup", onUpTrack);
447
+ }
448
+ };
449
+
450
+ return {
451
+ baseId,
452
+ labelProps: mergeProps(labelProps, {
453
+ // The label points at the group, so clicking it has to move focus by
454
+ // hand — and show the focus ring, since the user is now on the keyboard.
455
+ onClick: () => {
456
+ if (access(options.isDisabled) === true) return;
457
+ const first = (access(options.trackRef) as Element | null)?.ownerDocument.getElementById(
458
+ access(options.firstThumbId) ?? thumbId(baseId(), 0),
459
+ );
460
+ if (first !== null && first !== undefined) focusWithoutScrolling(first);
461
+ },
462
+ }),
463
+ groupProps: mergeProps(filterDOMProps(options, { labelable: true }), fieldProps, {
464
+ role: "group",
465
+ }),
466
+ trackProps: mergeProps(moveProps, {
467
+ onMouseDown: (event: MouseEvent) => {
468
+ if (event.button !== 0 || event.altKey || event.ctrlKey || event.metaKey) return;
469
+ onDownTrack(event, undefined, event.clientX, event.clientY);
470
+ },
471
+ onPointerDown: (event: PointerEvent) => {
472
+ if (
473
+ event.pointerType === "mouse" &&
474
+ (event.button !== 0 || event.altKey || event.ctrlKey || event.metaKey)
475
+ ) {
476
+ return;
477
+ }
478
+ onDownTrack(event, event.pointerId, event.clientX, event.clientY);
479
+ },
480
+ onTouchStart: (event: TouchEvent) => {
481
+ const touch = event.changedTouches[0];
482
+ if (touch === undefined) return;
483
+ onDownTrack(event, touch.identifier, touch.clientX, touch.clientY);
484
+ },
485
+ style: { position: "relative", "touch-action": "none" },
486
+ }),
487
+ outputProps: {
488
+ // `off`, not `polite`: the thumb's own value is announced as it moves,
489
+ // and a live region saying the same thing is the value read twice.
490
+ "aria-live": "off",
491
+ for: () =>
492
+ state
493
+ .values()
494
+ .map((_, index) => thumbId(baseId(), index))
495
+ .join(" "),
496
+ },
497
+ };
498
+ }
499
+
500
+ export interface SliderThumbOptions {
501
+ /** @default 0 */
502
+ index?: number;
503
+ trackRef: ElementRef;
504
+ inputRef: ElementRef<HTMLInputElement>;
505
+ baseId: MaybeAccessor<string>;
506
+ /** The input's id, where the caller chose one. @default derived from `baseId` */
507
+ id?: MaybeAccessor<string | undefined>;
508
+ /** The group's own id, so the thumb is announced with the slider's name. */
509
+ groupLabelId?: MaybeAccessor<string | undefined>;
510
+ isDisabled?: MaybeAccessor<boolean | undefined>;
511
+ isRequired?: MaybeAccessor<boolean | undefined>;
512
+ isInvalid?: MaybeAccessor<boolean | undefined>;
513
+ name?: MaybeAccessor<string | undefined>;
514
+ form?: MaybeAccessor<string | undefined>;
515
+ "aria-label"?: MaybeAccessor<string | undefined>;
516
+ "aria-labelledby"?: MaybeAccessor<string | undefined>;
517
+ "aria-describedby"?: MaybeAccessor<string | undefined>;
518
+ }
519
+
520
+ export interface SliderThumbResult {
521
+ thumbProps: DOMProps;
522
+ /** For the `<input type="range">` under the thumb. */
523
+ inputProps: DOMProps;
524
+ labelProps: DOMProps;
525
+ isDragging: Accessor<boolean>;
526
+ isFocused: Accessor<boolean>;
527
+ isDisabled: Accessor<boolean>;
528
+ }
529
+
530
+ export function sliderThumb(options: SliderThumbOptions, state: SliderState): SliderThumbResult {
531
+ const index = options.index ?? 0;
532
+ const locale = useLocale();
533
+ const listeners = globalListeners();
534
+
535
+ const isVertical = (): boolean => state.orientation() === "vertical";
536
+ const reversed = (): boolean => locale().direction === "rtl";
537
+ const flipped = (): boolean => runsBackwards(state, reversed());
538
+ const isDisabled = (): boolean => access(options.isDisabled) === true || state.isDisabled();
539
+ const isFocused = (): boolean => state.focusedThumb() === index;
540
+
541
+ state.setThumbEditable(index, !isDisabled());
542
+
543
+ const focusInput = (): void => {
544
+ const input = access(options.inputRef) as HTMLInputElement | null;
545
+ if (input !== null) focusWithoutScrolling(input);
546
+ };
547
+
548
+ if (!isServer) {
549
+ // The state decides which thumb is focused — the track hands focus to the
550
+ // one a press picked up — so the DOM follows it rather than the reverse.
551
+ createEffect(isFocused, (focused) => {
552
+ if (focused) untrack(focusInput);
553
+ });
554
+
555
+ createEffect(isDisabled, (disabled) => {
556
+ state.setThumbEditable(index, !disabled);
557
+ });
558
+ }
559
+
560
+ let position: number | null = null;
561
+
562
+ const { moveProps } = move({
563
+ onMoveStart: () => {
564
+ position = null;
565
+ state.setThumbDragging(index, true);
566
+ },
567
+ onMove: (event) => {
568
+ // Before anything is measured: a key needs no geometry, and a track that
569
+ // has none (not laid out yet, or `display: none` on an ancestor) would
570
+ // otherwise swallow it.
571
+ if (event.pointerType === "keyboard") {
572
+ // The native input already handles the plain arrows; what reaches here
573
+ // is the drag emulation, so a Shift is a page rather than a step.
574
+ const amount = event.shiftKey ? state.pageSize() : state.step();
575
+ // The keys follow what is DRAWN. Left and right mirror with the
576
+ // horizontal axis, up and down with the vertical one, and an inversion
577
+ // only reaches the axis the slider runs along.
578
+ const inverted = state.isInverted();
579
+ const lowOnLeft = isVertical() ? !reversed() : reversed() === inverted;
580
+ const lowOnBottom = !(isVertical() && inverted);
581
+ const backwards =
582
+ event.deltaX !== 0 ? event.deltaX < 0 === lowOnLeft : event.deltaY > 0 === lowOnBottom;
583
+ if (backwards) state.decrementThumb(index, amount);
584
+ else state.incrementThumb(index, amount);
585
+ return;
586
+ }
587
+
588
+ const track = access(options.trackRef) as Element | null;
589
+ if (track === null) return;
590
+ const box = track.getBoundingClientRect();
591
+ const size = isVertical() ? box.height : box.width;
592
+ if (size === 0) return;
593
+
594
+ if (position === null) position = state.getThumbPercent(index) * size;
595
+
596
+ let delta = isVertical() ? event.deltaY : event.deltaX;
597
+ if (flipped()) delta = -delta;
598
+ position += delta;
599
+ state.setThumbPercent(index, clamp(position / size, 0, 1));
600
+ },
601
+ onMoveEnd: () => state.setThumbDragging(index, false),
602
+ });
603
+
604
+ const { focusableProps } = focusable(
605
+ {
606
+ isDisabled,
607
+ onFocus: () => state.setFocusedThumb(index),
608
+ onBlur: () => state.setFocusedThumb(undefined),
609
+ },
610
+ options.inputRef,
611
+ );
612
+
613
+ let pointer: number | undefined;
614
+
615
+ const onUp = (event: Event): void => {
616
+ const identifier =
617
+ (event as PointerEvent).pointerId ??
618
+ (event as TouchEvent).changedTouches?.[0]?.identifier ??
619
+ undefined;
620
+ if (identifier !== pointer) return;
621
+ focusInput();
622
+ state.setThumbDragging(index, false);
623
+ listeners.removeAll();
624
+ };
625
+
626
+ const onDown = (identifier?: number): void => {
627
+ focusInput();
628
+ pointer = identifier;
629
+ state.setThumbDragging(index, true);
630
+ if (isServer) return;
631
+ const input = access(options.inputRef) as HTMLInputElement | null;
632
+ const view = (input?.ownerDocument.defaultView ?? window) as Window;
633
+ listeners.add(view, "mouseup", onUp);
634
+ listeners.add(view, "touchend", onUp);
635
+ listeners.add(view, "pointerup", onUp);
636
+ };
637
+
638
+ formReset(
639
+ options.inputRef,
640
+ () => state.defaultValues()[index] ?? 0,
641
+ (value) => state.setThumbValue(index, value),
642
+ );
643
+
644
+ const onKeyDown = (event: KeyboardEvent): void => {
645
+ // The native range input has no page step and no Home/End of its own on
646
+ // every engine, so those four are ours.
647
+ switch (event.key) {
648
+ case "PageUp":
649
+ event.preventDefault();
650
+ state.setThumbDragging(index, true);
651
+ state.incrementThumb(index, state.pageSize());
652
+ state.setThumbDragging(index, false);
653
+ return;
654
+ case "PageDown":
655
+ event.preventDefault();
656
+ state.setThumbDragging(index, true);
657
+ state.decrementThumb(index, state.pageSize());
658
+ state.setThumbDragging(index, false);
659
+ return;
660
+ case "Home":
661
+ event.preventDefault();
662
+ state.setThumbDragging(index, true);
663
+ state.setThumbValue(index, state.getThumbMinValue(index));
664
+ state.setThumbDragging(index, false);
665
+ return;
666
+ case "End":
667
+ event.preventDefault();
668
+ state.setThumbDragging(index, true);
669
+ state.setThumbValue(index, state.getThumbMaxValue(index));
670
+ state.setThumbDragging(index, false);
671
+ return;
672
+ default:
673
+ return;
674
+ }
675
+ };
676
+
677
+ const thumbPercent = (): number => {
678
+ const percent = state.getThumbPercent(index);
679
+ return flipped() ? 1 - percent : percent;
680
+ };
681
+
682
+ const interactions: DOMProps = isDisabled()
683
+ ? {}
684
+ : mergeProps(moveProps, {
685
+ onMouseDown: (event: MouseEvent) => {
686
+ if (event.button !== 0 || event.altKey || event.ctrlKey || event.metaKey) return;
687
+ onDown();
688
+ },
689
+ onPointerDown: (event: PointerEvent) => {
690
+ if (event.button !== 0 || event.altKey || event.ctrlKey || event.metaKey) return;
691
+ onDown(event.pointerId);
692
+ },
693
+ onTouchStart: (event: TouchEvent) => onDown(event.changedTouches[0]?.identifier),
694
+ });
695
+
696
+ return {
697
+ isDragging: () => state.isThumbDragging(index),
698
+ isFocused,
699
+ isDisabled,
700
+ labelProps: { for: () => access(options.id) ?? thumbId(access(options.baseId), index) },
701
+ thumbProps: mergeProps(interactions, {
702
+ style: () => ({
703
+ position: "absolute",
704
+ [isVertical() ? "top" : "left"]: `${thumbPercent() * 100}%`,
705
+ transform: "translate(-50%, -50%)",
706
+ "touch-action": "none",
707
+ }),
708
+ }),
709
+ inputProps: mergeProps(focusableProps, {
710
+ id: () => access(options.id) ?? thumbId(access(options.baseId), index),
711
+ type: "range",
712
+ tabIndex: () => (isDisabled() ? undefined : 0),
713
+ min: () => state.getThumbMinValue(index),
714
+ max: () => state.getThumbMaxValue(index),
715
+ step: state.step,
716
+ value: () => state.getThumbValue(index),
717
+ name: () => access(options.name),
718
+ form: () => access(options.form),
719
+ disabled: isDisabled,
720
+ "aria-orientation": state.orientation,
721
+ // What the number MEANS: "40%", "£12.50". Without it a screen reader
722
+ // reads the raw number and the unit is lost.
723
+ "aria-valuetext": () => state.getThumbValueLabel(index),
724
+ "aria-required": () => access(options.isRequired) === true || undefined,
725
+ "aria-invalid": () => access(options.isInvalid) === true || undefined,
726
+ "aria-label": () => access(options["aria-label"]),
727
+ "aria-labelledby": () =>
728
+ [access(options.groupLabelId), access(options["aria-labelledby"])]
729
+ .filter(Boolean)
730
+ .join(" ") || undefined,
731
+ "aria-describedby": () => access(options["aria-describedby"]),
732
+ onKeyDown,
733
+ onInput: (event: Event) => {
734
+ state.setThumbValue(index, Number.parseFloat((event.target as HTMLInputElement).value));
735
+ },
736
+ onChange: (event: Event) => {
737
+ state.setThumbValue(index, Number.parseFloat((event.target as HTMLInputElement).value));
738
+ },
739
+ }),
740
+ };
741
+ }
742
+
743
+ // ---------------------------------------------------------------------------
744
+ // Components
745
+ // ---------------------------------------------------------------------------
746
+
747
+ /** What `useSlider` returns. Exported because it is the return type of an exported function. */
748
+ export interface SliderContextValue {
749
+ state: SliderState;
750
+ baseId: Accessor<string>;
751
+ trackRef: ReturnType<typeof makeRef<HTMLDivElement>>;
752
+ groupLabelId: Accessor<string | undefined>;
753
+ /** The id the caller gave the slider, which is the first thumb's. */
754
+ firstThumbId: Accessor<string | undefined>;
755
+ outputProps: DOMProps;
756
+ name: Accessor<string | undefined>;
757
+ form: Accessor<string | undefined>;
758
+ }
759
+
760
+ const SliderContext = createContext<SliderContextValue | null>(null);
761
+
762
+ export function useSlider(): SliderContextValue {
763
+ const value = getContext(SliderContext);
764
+ if (value === null || value === undefined) {
765
+ throw new Error("This must be rendered inside a Slider.");
766
+ }
767
+ return value;
768
+ }
769
+
770
+ export interface SliderComponentProps extends StyleProps {
771
+ children?: Child;
772
+ label?: Child;
773
+ value?: number | number[];
774
+ defaultValue?: number | number[];
775
+ /** @default 0 */
776
+ minValue?: number;
777
+ /** @default 100 */
778
+ maxValue?: number;
779
+ /** @default 1 */
780
+ step?: number;
781
+ /** @default "horizontal" */
782
+ orientation?: Orientation;
783
+ isDisabled?: boolean;
784
+ /** Puts the minimum at the far end. See {@link SliderStateOptions.isInverted}. */
785
+ isInverted?: boolean;
786
+ /** How many steps two neighbouring thumbs must stay apart. @default 0 */
787
+ minStepsBetweenThumbs?: number;
788
+ formatOptions?: Intl.NumberFormatOptions;
789
+ name?: string;
790
+ form?: string;
791
+ "aria-label"?: string;
792
+ "aria-labelledby"?: string;
793
+ ref?: RefTarget<HTMLDivElement>;
794
+ onChange?: (value: number[]) => void;
795
+ onChangeEnd?: (value: number[]) => void;
796
+ }
797
+
798
+ /**
799
+ * ```tsx
800
+ * <Slider label="Volume" defaultValue={30} onChange={([v]) => volume.set(v)} />
801
+ * <Slider label="Price" defaultValue={[20, 60]} formatOptions={{ style: "currency", currency: "GBP" }} />
802
+ * ```
803
+ *
804
+ * With no children it draws the ordinary layout — a label, the value, a track
805
+ * and a thumb per value. Compose `<SliderOutput>`, `<SliderTrack>` and
806
+ * `<SliderThumb>` yourself for anything else.
807
+ */
808
+ export function Slider(props: Incoming<SliderComponentProps>) {
809
+ const trackRef = makeRef<HTMLDivElement>();
810
+ const options = fromProps(props);
811
+
812
+ const state = sliderState({
813
+ ...(options as SliderStateOptions),
814
+ onChange: (value) => props.onChange?.()?.(value),
815
+ onChangeEnd: (value) => props.onChangeEnd?.()?.(value),
816
+ });
817
+
818
+ // The caller's `id` is the first thumb's, because the thumb is what a
819
+ // `<label for>` elsewhere on the page can name and focus: on the group it
820
+ // pointed at a `<div>`, which a label reaches neither way.
821
+ const firstThumbId = (): string | undefined => props.id?.();
822
+ const { id: _, ...groupOptions } = options as unknown as SliderOptions & { id?: unknown };
823
+ const { labelProps, groupProps, trackProps, outputProps, baseId } = slider(
824
+ { ...groupOptions, trackRef, firstThumbId },
825
+ state,
826
+ );
827
+ const ownName = (): boolean =>
828
+ props.label !== undefined ||
829
+ props["aria-label"]?.() !== undefined ||
830
+ props["aria-labelledby"]?.() !== undefined;
831
+
832
+ // Named only by a `<label for>` on its first thumb, the group takes its name
833
+ // from the same label. Asked once the slider is in the document, where the
834
+ // label can be found.
835
+ const [namedBy, setNamedBy] = createSignal<string | undefined>(undefined);
836
+ onSettled(() => {
837
+ const given = firstThumbId();
838
+ const track = trackRef();
839
+ if (given === undefined || ownName() || track === null) return;
840
+ const ids: string[] = [];
841
+ for (const label of track.ownerDocument.querySelectorAll("label")) {
842
+ if (label.htmlFor !== given) continue;
843
+ if (label.id === "")
844
+ label.id = `${given}-label${ids.length === 0 ? "" : `-${String(ids.length)}`}`;
845
+ ids.push(label.id);
846
+ }
847
+ if (ids.length > 0) setNamedBy(ids.join(" "));
848
+ });
849
+
850
+ const owner = getOwner();
851
+ if (owner !== null) {
852
+ install(owner, SliderContext, () => ({
853
+ state,
854
+ baseId,
855
+ trackRef,
856
+ /**
857
+ * The label element when there is one, and the GROUP when there is not.
858
+ *
859
+ * A thumb is `role="slider"` and needs a name of its own — that is the
860
+ * thing a screen reader announces, not the group around it. A caller who
861
+ * writes `<Slider aria-label="Volume" />` renders no label element, so
862
+ * `labelProps.id` is undefined and the thumb had no name at all: measured
863
+ * as `role="slider" has no accessible name` on the very first sweep of
864
+ * the library. The group carries the `aria-label`, and `aria-labelledby`
865
+ * resolves through it, so pointing at the group answers both shapes.
866
+ * React Aria does the same, with `data.id` in `useSliderThumb`.
867
+ */
868
+ groupLabelId: () =>
869
+ access(labelProps.id as MaybeAccessor<string | undefined>) ??
870
+ // A thumb labelled by a nameless group would lose the name its own
871
+ // `<label for>` gives it: `aria-labelledby` wins over a label.
872
+ (firstThumbId() !== undefined && !ownName()
873
+ ? undefined
874
+ : access(groupProps.id as MaybeAccessor<string | undefined>)),
875
+ firstThumbId,
876
+ outputProps,
877
+ name: () => props.name?.(),
878
+ form: () => props.form?.(),
879
+ }));
880
+ }
881
+
882
+ const elementProps = mergeProps(
883
+ groupProps,
884
+ filterDOMProps(groupOptions, { global: true }),
885
+ styleProps(props),
886
+ {
887
+ "aria-labelledby": () =>
888
+ access(groupProps["aria-labelledby"] as MaybeAccessor<string | undefined>) ?? namedBy(),
889
+ "data-orientation": state.orientation,
890
+ "data-inverted": state.isInverted,
891
+ "data-disabled": state.isDisabled,
892
+ "data-testid": () => props["data-testid"]?.(),
893
+ },
894
+ );
895
+
896
+ return (
897
+ <div {...elementProps} ref={mergeRefs(props.ref?.())}>
898
+ <span {...labelProps}>{props.label}</span>
899
+ {() =>
900
+ props.children === undefined ? (
901
+ <>
902
+ <SliderOutput />
903
+ <SliderTrack trackProps={trackProps}>
904
+ {(index: number) => <SliderThumb index={index} />}
905
+ </SliderTrack>
906
+ </>
907
+ ) : (
908
+ props.children
909
+ )
910
+ }
911
+ </div>
912
+ );
913
+ }
914
+
915
+ export interface SliderOutputComponentProps extends StyleProps {
916
+ children?: Child;
917
+ }
918
+
919
+ /** The current value, as text. */
920
+ export function SliderOutput(props: Incoming<SliderOutputComponentProps>) {
921
+ const group = useSlider();
922
+
923
+ const elementProps = mergeProps(
924
+ group.outputProps,
925
+ filterDOMProps(fromProps(props), { global: true }),
926
+ styleProps(props),
927
+ {
928
+ "data-testid": () => props["data-testid"]?.(),
929
+ },
930
+ );
931
+
932
+ return (
933
+ <output {...elementProps}>
934
+ {() => (props.children === undefined ? group.state.getFormattedValue() : props.children)}
935
+ </output>
936
+ );
937
+ }
938
+
939
+ export interface SliderTrackComponentProps extends StyleProps {
940
+ /** How one thumb renders. Given its index. */
941
+ children: (index: number) => Child;
942
+ /** Only when composing outside the default layout. */
943
+ trackProps?: DOMProps;
944
+ ref?: RefTarget<HTMLDivElement>;
945
+ }
946
+
947
+ /**
948
+ * The track, and a thumb for every value.
949
+ *
950
+ * A press anywhere on it moves the nearest thumb there, which is what makes a
951
+ * slider usable with one gesture rather than requiring the thumb to be hit.
952
+ */
953
+ export function SliderTrack(props: Incoming<SliderTrackComponentProps>) {
954
+ const group = useSlider();
955
+ const render = props.children;
956
+
957
+ const elementProps = mergeProps(
958
+ props.trackProps?.() ?? {},
959
+ filterDOMProps(fromProps(props), { global: true }),
960
+ styleProps(props),
961
+ {
962
+ "data-orientation": group.state.orientation,
963
+ "data-disabled": group.state.isDisabled,
964
+ "data-testid": () => props["data-testid"]?.(),
965
+ },
966
+ );
967
+
968
+ return (
969
+ <div {...elementProps} ref={mergeRefs(group.trackRef.set, props.ref?.())}>
970
+ <For each={() => group.state.values().map((_, index) => index)}>
971
+ {(index: number) => render(index)}
972
+ </For>
973
+ </div>
974
+ );
975
+ }
976
+
977
+ export interface SliderThumbComponentProps extends StyleProps {
978
+ children?: Child;
979
+ /** @default 0 */
980
+ index?: number;
981
+ isDisabled?: boolean;
982
+ "aria-label"?: string;
983
+ ref?: RefTarget<HTMLDivElement>;
984
+ }
985
+
986
+ /**
987
+ * One thumb, over a visually hidden `<input type="range">`.
988
+ *
989
+ * The input is what the keyboard, the form and assistive technology all talk
990
+ * to; the element around it is only what the user sees.
991
+ */
992
+ export function SliderThumb(props: Incoming<SliderThumbComponentProps>) {
993
+ const group = useSlider();
994
+ const inputRef = makeRef<HTMLInputElement>();
995
+ const index = props.index?.() ?? 0;
996
+
997
+ const { thumbProps, inputProps, isDragging, isFocused, isDisabled } = sliderThumb(
998
+ {
999
+ index,
1000
+ trackRef: group.trackRef,
1001
+ inputRef,
1002
+ baseId: group.baseId,
1003
+ id: () => (index === 0 ? group.firstThumbId() : undefined),
1004
+ groupLabelId: group.groupLabelId,
1005
+ isDisabled: () => props.isDisabled?.(),
1006
+ name: group.name,
1007
+ form: group.form,
1008
+ "aria-label": () => props["aria-label"]?.(),
1009
+ },
1010
+ group.state,
1011
+ );
1012
+
1013
+ const { hoverProps, isHovered } = hover({ isDisabled });
1014
+ const { focusProps, isFocusVisible } = focusRing();
1015
+ const { visuallyHiddenProps } = visuallyHidden();
1016
+
1017
+ const elementProps = mergeProps(
1018
+ thumbProps,
1019
+ hoverProps,
1020
+ filterDOMProps(fromProps(props), { global: true }),
1021
+ styleProps(props),
1022
+ {
1023
+ "data-dragging": isDragging,
1024
+ "data-focused": isFocused,
1025
+ "data-focus-visible": isFocusVisible,
1026
+ "data-hovered": isHovered,
1027
+ "data-disabled": isDisabled,
1028
+ "data-testid": () => props["data-testid"]?.(),
1029
+ },
1030
+ );
1031
+
1032
+ const hiddenInputProps = mergeProps(inputProps, focusProps, {
1033
+ style: visuallyHiddenProps.style,
1034
+ });
1035
+
1036
+ return (
1037
+ <div {...elementProps} ref={mergeRefs(props.ref?.())}>
1038
+ <input {...hiddenInputProps} ref={inputRef.set} />
1039
+ {props.children}
1040
+ </div>
1041
+ );
1042
+ }