@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
@@ -0,0 +1,1478 @@
1
+ /**
2
+ * Colour controls: an area, a slider, a wheel, a field and a swatch.
3
+ *
4
+ * A colour picker is several controls editing one value in different spaces,
5
+ * and the accessibility of each rests on the same idea: a colour is not a
6
+ * picture, it is NUMBERS, and every control has to say which number it is
7
+ * moving and what it currently is.
8
+ *
9
+ * - **The area is two sliders in one element.** Dragging moves saturation and
10
+ * brightness at once, so it carries `role="application"` holding two
11
+ * `slider`s — one per axis — and the arrows move whichever axis they point
12
+ * along. A single slider cannot express two dimensions, and a canvas
13
+ * expresses none.
14
+ * - **Every slider says its value in words.** "Saturation 62%" and, for the
15
+ * colour as a whole, a name: `aria-valuetext` on a hue slider reading "212"
16
+ * tells a screen reader user nothing, and "212 degrees, blue" tells them
17
+ * what they have.
18
+ * - **The swatch is an image, not a button.** It shows a colour, and its
19
+ * `aria-label` is that colour's description — an unlabelled coloured square
20
+ * is invisible to anyone not looking at it.
21
+ */
22
+
23
+ import {
24
+ type Accessor,
25
+ type Child,
26
+ createMemo,
27
+ createContext,
28
+ getContext,
29
+ getOwner,
30
+ type Incoming,
31
+ install,
32
+ createSignal,
33
+ } from "@barqjs/core";
34
+ import { isServer } from "@barqjs/web";
35
+ import { ref as makeRef, mergeRefs, type RefTarget } from "@barqjs/primitives/refs";
36
+ import {
37
+ Color,
38
+ defaultColor,
39
+ parseColor,
40
+ type ColorChannel,
41
+ type ColorFormat,
42
+ type ColorSpace,
43
+ } from "./color.ts";
44
+ import { focusWithoutScrolling } from "./dom.ts";
45
+ import { focusRing } from "./focus.ts";
46
+ import { hover } from "./interactions/hover.ts";
47
+ import { globalListeners } from "./interactions/listeners.ts";
48
+ import { move, type MoveMoveEvent } from "./interactions/move.ts";
49
+ import type { ElementRef } from "./interactions/press.ts";
50
+ import { label as useLabelHook } from "./label.ts";
51
+ import { visuallyHidden } from "./live.ts";
52
+ import { formReset, HIDDEN_INPUT_STYLE } from "./toggle.ts";
53
+ import { textField, type TextFieldOptions } from "./textfield.tsx";
54
+ import {
55
+ type FormValidationState,
56
+ type ValidateFunction,
57
+ type ValidationBehavior,
58
+ } from "./validation.ts";
59
+ import type { Orientation } from "./selection.ts";
60
+ import {
61
+ access,
62
+ callback,
63
+ clamp,
64
+ controllable,
65
+ type DOMProps,
66
+ filterDOMProps,
67
+ fromProps,
68
+ id,
69
+ type MaybeAccessor,
70
+ mergeProps,
71
+ type StyleProps,
72
+ styleProps,
73
+ } from "./utils.ts";
74
+
75
+ // ---------------------------------------------------------------------------
76
+ // The value itself
77
+ // ---------------------------------------------------------------------------
78
+
79
+ export interface ColorStateOptions {
80
+ value?: MaybeAccessor<Color | string | null | undefined>;
81
+ defaultValue?: MaybeAccessor<Color | string | null | undefined>;
82
+ isDisabled?: MaybeAccessor<boolean | undefined>;
83
+ onChange?: (value: Color) => void;
84
+ /** Called once, when the gesture that changed the colour ends. */
85
+ onChangeEnd?: (value: Color) => void;
86
+ }
87
+
88
+ function asColor(value: Color | string | null | undefined): Color | undefined {
89
+ if (value === null || value === undefined) return undefined;
90
+ return typeof value === "string" ? parseColor(value) : value;
91
+ }
92
+
93
+ // ---------------------------------------------------------------------------
94
+ // A single channel: the slider and the wheel
95
+ // ---------------------------------------------------------------------------
96
+
97
+ export interface ColorSliderStateOptions extends ColorStateOptions {
98
+ channel: MaybeAccessor<ColorChannel>;
99
+ /** @default "horizontal" */
100
+ orientation?: MaybeAccessor<Orientation | undefined>;
101
+ }
102
+
103
+ export interface ColorSliderState {
104
+ value: Accessor<Color>;
105
+ setValue(value: Color): void;
106
+ channel: Accessor<ColorChannel>;
107
+ /** The channel's number, in its own units. */
108
+ channelValue: Accessor<number>;
109
+ setChannelValue(value: number): void;
110
+ /** Where the thumb sits, 0 at the minimum and 1 at the maximum. */
111
+ percent: Accessor<number>;
112
+ setPercent(percent: number): void;
113
+ isDragging: Accessor<boolean>;
114
+ setDragging(isDragging: boolean): void;
115
+ isDisabled: Accessor<boolean>;
116
+ orientation: Accessor<Orientation>;
117
+ increment(step?: number): void;
118
+ decrement(step?: number): void;
119
+ /** What the value is, in words. */
120
+ valueText: Accessor<string>;
121
+ }
122
+
123
+ export function colorSliderState(options: ColorSliderStateOptions): ColorSliderState {
124
+ const [value, setValueRaw] = controllable<Color>(
125
+ () => asColor(access(options.value)),
126
+ () => asColor(access(options.defaultValue)) ?? defaultColor(),
127
+ options.onChange,
128
+ );
129
+
130
+ const [dragging, writeDragging] = createSignal(false);
131
+ const channel = (): ColorChannel => access(options.channel);
132
+ const isDisabled = (): boolean => access(options.isDisabled) === true;
133
+
134
+ // What the LAST write produced, so a drag reads its own change back rather
135
+ // than the value a controlled owner has not caught up with yet.
136
+ let live = value();
137
+
138
+ const setValue = (next: Color): void => {
139
+ live = next;
140
+ setValueRaw(next);
141
+ };
142
+
143
+ const range = (): ReturnType<Color["getChannelRange"]> => value().getChannelRange(channel());
144
+
145
+ const setChannelValue = (next: number): void => {
146
+ if (isDisabled()) return;
147
+ setValue(live.withChannelValue(channel(), next));
148
+ };
149
+
150
+ return {
151
+ value,
152
+ setValue,
153
+ channel,
154
+ isDisabled,
155
+ isDragging: dragging,
156
+ orientation: () => access(options.orientation) ?? "horizontal",
157
+ channelValue: () => value().getChannelValue(channel()),
158
+ setChannelValue,
159
+ percent: () => {
160
+ const limits = range();
161
+ return (
162
+ (value().getChannelValue(channel()) - limits.minValue) / (limits.maxValue - limits.minValue)
163
+ );
164
+ },
165
+ setPercent: (percent) => {
166
+ const limits = range();
167
+ const raw = limits.minValue + clamp(percent, 0, 1) * (limits.maxValue - limits.minValue);
168
+ // Snapped to the step, so a drag lands on a value the arrows can reach.
169
+ setChannelValue(Math.round(raw / limits.step) * limits.step);
170
+ },
171
+ setDragging: (next) => {
172
+ const was = dragging();
173
+ writeDragging(next);
174
+ if (was && !next) options.onChangeEnd?.(live);
175
+ },
176
+ increment: (step) => setChannelValue(live.getChannelValue(channel()) + (step ?? range().step)),
177
+ decrement: (step) => setChannelValue(live.getChannelValue(channel()) - (step ?? range().step)),
178
+ valueText: () => {
179
+ const current = value();
180
+ const name = current.getChannelName(channel());
181
+ const amount = current.getChannelValue(channel());
182
+ return `${name} ${channel() === "alpha" ? `${Math.round(amount * 100)}%` : Math.round(amount)}`;
183
+ },
184
+ };
185
+ }
186
+
187
+ // ---------------------------------------------------------------------------
188
+ // Two channels at once: the area
189
+ // ---------------------------------------------------------------------------
190
+
191
+ export interface ColorAreaStateOptions extends ColorStateOptions {
192
+ /** @default the colour's second channel */
193
+ xChannel?: MaybeAccessor<ColorChannel | undefined>;
194
+ /** @default the colour's third channel */
195
+ yChannel?: MaybeAccessor<ColorChannel | undefined>;
196
+ }
197
+
198
+ export interface ColorAreaState {
199
+ value: Accessor<Color>;
200
+ setValue(value: Color): void;
201
+ xChannel: Accessor<ColorChannel>;
202
+ yChannel: Accessor<ColorChannel>;
203
+ xValue: Accessor<number>;
204
+ yValue: Accessor<number>;
205
+ setXValue: (value: number) => void;
206
+ setYValue: (value: number) => void;
207
+ /** Where the thumb sits, 0 to 1 on each axis. `y` counts UP the element. */
208
+ xPercent: Accessor<number>;
209
+ yPercent: Accessor<number>;
210
+ setPercents(x: number, y: number): void;
211
+ isDragging: Accessor<boolean>;
212
+ setDragging(isDragging: boolean): void;
213
+ isDisabled: Accessor<boolean>;
214
+ incrementX(step?: number): void;
215
+ decrementX(step?: number): void;
216
+ incrementY(step?: number): void;
217
+ decrementY(step?: number): void;
218
+ valueText: Accessor<string>;
219
+ }
220
+
221
+ export function colorAreaState(options: ColorAreaStateOptions): ColorAreaState {
222
+ const [value, setValueRaw] = controllable<Color>(
223
+ () => asColor(access(options.value)),
224
+ () => asColor(access(options.defaultValue)) ?? defaultColor(),
225
+ options.onChange,
226
+ );
227
+
228
+ const [dragging, writeDragging] = createSignal(false);
229
+ const isDisabled = (): boolean => access(options.isDisabled) === true;
230
+
231
+ let live = value();
232
+ const setValue = (next: Color): void => {
233
+ live = next;
234
+ setValueRaw(next);
235
+ };
236
+
237
+ // The two channels that are not the first: saturation and brightness in
238
+ // HSB, green and blue in RGB. The first is the one a hue slider or a red
239
+ // slider edits alongside the area.
240
+ const channels = (): [ColorChannel, ColorChannel] => {
241
+ const [, second, third] = value().getColorChannels();
242
+ return [second, third];
243
+ };
244
+
245
+ const xChannel = (): ColorChannel => access(options.xChannel) ?? channels()[0];
246
+ const yChannel = (): ColorChannel => access(options.yChannel) ?? channels()[1];
247
+
248
+ const percentOf = (channel: ColorChannel): number => {
249
+ const limits = value().getChannelRange(channel);
250
+ return (
251
+ (value().getChannelValue(channel) - limits.minValue) / (limits.maxValue - limits.minValue)
252
+ );
253
+ };
254
+
255
+ const set = (channel: ColorChannel, next: number): void => {
256
+ if (isDisabled()) return;
257
+ setValue(live.withChannelValue(channel, next));
258
+ };
259
+
260
+ const step = (channel: ColorChannel, by: number): void =>
261
+ set(channel, live.getChannelValue(channel) + by);
262
+
263
+ return {
264
+ value,
265
+ setValue,
266
+ xChannel,
267
+ yChannel,
268
+ isDisabled,
269
+ isDragging: dragging,
270
+ xValue: () => value().getChannelValue(xChannel()),
271
+ yValue: () => value().getChannelValue(yChannel()),
272
+ setXValue: (next) => set(xChannel(), next),
273
+ setYValue: (next) => set(yChannel(), next),
274
+ xPercent: () => percentOf(xChannel()),
275
+ yPercent: () => percentOf(yChannel()),
276
+ setPercents: (x, y) => {
277
+ if (isDisabled()) return;
278
+ const xLimits = live.getChannelRange(xChannel());
279
+ const yLimits = live.getChannelRange(yChannel());
280
+ const xValue = xLimits.minValue + clamp(x, 0, 1) * (xLimits.maxValue - xLimits.minValue);
281
+ const yValue = yLimits.minValue + clamp(y, 0, 1) * (yLimits.maxValue - yLimits.minValue);
282
+ setValue(
283
+ live
284
+ .withChannelValue(xChannel(), Math.round(xValue / xLimits.step) * xLimits.step)
285
+ .withChannelValue(yChannel(), Math.round(yValue / yLimits.step) * yLimits.step),
286
+ );
287
+ },
288
+ setDragging: (next) => {
289
+ const was = dragging();
290
+ writeDragging(next);
291
+ if (was && !next) options.onChangeEnd?.(live);
292
+ },
293
+ incrementX: (by) => step(xChannel(), by ?? live.getChannelRange(xChannel()).step),
294
+ decrementX: (by) => step(xChannel(), -(by ?? live.getChannelRange(xChannel()).step)),
295
+ incrementY: (by) => step(yChannel(), by ?? live.getChannelRange(yChannel()).step),
296
+ decrementY: (by) => step(yChannel(), -(by ?? live.getChannelRange(yChannel()).step)),
297
+ valueText: () => {
298
+ const current = value();
299
+ return `${current.getChannelName(xChannel())} ${Math.round(
300
+ current.getChannelValue(xChannel()),
301
+ )}, ${current.getChannelName(yChannel())} ${Math.round(current.getChannelValue(yChannel()))}`;
302
+ },
303
+ };
304
+ }
305
+
306
+ // ---------------------------------------------------------------------------
307
+ // Hooks
308
+ // ---------------------------------------------------------------------------
309
+
310
+ export interface ColorSliderOptions {
311
+ trackRef: ElementRef;
312
+ inputRef: ElementRef<HTMLInputElement>;
313
+ label?: MaybeAccessor<Child>;
314
+ "aria-label"?: MaybeAccessor<string | undefined>;
315
+ "aria-labelledby"?: MaybeAccessor<string | undefined>;
316
+ }
317
+
318
+ export interface ColorSliderResult {
319
+ labelProps: DOMProps;
320
+ trackProps: DOMProps;
321
+ thumbProps: DOMProps;
322
+ /** For the visually hidden `<input type="range">` under the thumb. */
323
+ inputProps: DOMProps;
324
+ outputProps: DOMProps;
325
+ }
326
+
327
+ /**
328
+ * One channel on a track.
329
+ *
330
+ * A real range input under the thumb, for the same reason a slider has one:
331
+ * the keys, the form and the screen reader's rotor all come from the platform
332
+ * rather than being reimplemented.
333
+ */
334
+ export function colorSlider(
335
+ options: ColorSliderOptions,
336
+ state: ColorSliderState,
337
+ ): ColorSliderResult {
338
+ const inputId = id();
339
+ const { labelProps, fieldProps } = useLabelHook({
340
+ ...options,
341
+ id: inputId,
342
+ labelElementType: "label",
343
+ });
344
+
345
+ const isVertical = (): boolean => state.orientation() === "vertical";
346
+ let position: number | null = null;
347
+
348
+ const { moveProps } = move({
349
+ onMoveStart: () => {
350
+ position = null;
351
+ state.setDragging(true);
352
+ },
353
+ onMove: (event) => {
354
+ const track = access(options.trackRef) as Element | null;
355
+ if (track === null) return;
356
+ const box = track.getBoundingClientRect();
357
+ const size = isVertical() ? box.height : box.width;
358
+ if (size === 0) return;
359
+
360
+ if (position === null) position = state.percent() * size;
361
+ // Up is MORE on a vertical track, and the y axis counts down.
362
+ position += isVertical() ? -event.deltaY : event.deltaX;
363
+ state.setPercent(position / size);
364
+ },
365
+ onMoveEnd: () => state.setDragging(false),
366
+ });
367
+
368
+ const onTrackDown = (clientX: number, clientY: number): void => {
369
+ const track = access(options.trackRef) as Element | null;
370
+ if (track === null || state.isDisabled()) return;
371
+ const box = track.getBoundingClientRect();
372
+ const size = isVertical() ? box.height : box.width;
373
+ if (size === 0) return;
374
+ const offset = (isVertical() ? clientY : clientX) - (isVertical() ? box.top : box.left);
375
+ state.setDragging(true);
376
+ state.setPercent(isVertical() ? 1 - offset / size : offset / size);
377
+ (access(options.inputRef) as HTMLInputElement | null)?.focus();
378
+ };
379
+
380
+ const range = (): ReturnType<Color["getChannelRange"]> =>
381
+ state.value().getChannelRange(state.channel());
382
+
383
+ return {
384
+ labelProps,
385
+ trackProps: mergeProps(moveProps, {
386
+ onPointerDown: (event: PointerEvent) => {
387
+ if (event.button !== 0) return;
388
+ onTrackDown(event.clientX, event.clientY);
389
+ },
390
+ style: { position: "relative", "touch-action": "none" },
391
+ }),
392
+ thumbProps: {
393
+ style: () => ({
394
+ position: "absolute",
395
+ [isVertical() ? "top" : "left"]:
396
+ `${(isVertical() ? 1 - state.percent() : state.percent()) * 100}%`,
397
+ transform: "translate(-50%, -50%)",
398
+ "touch-action": "none",
399
+ }),
400
+ },
401
+ inputProps: mergeProps(fieldProps, {
402
+ id: inputId,
403
+ type: "range",
404
+ min: () => range().minValue,
405
+ max: () => range().maxValue,
406
+ step: () => range().step,
407
+ value: state.channelValue,
408
+ disabled: state.isDisabled,
409
+ "aria-orientation": state.orientation,
410
+ // The number MEANS something: "212" is not a colour, "Hue 212" is.
411
+ "aria-valuetext": state.valueText,
412
+ onInput: (event: Event) => {
413
+ state.setChannelValue(Number.parseFloat((event.target as HTMLInputElement).value));
414
+ },
415
+ onChange: (event: Event) => {
416
+ state.setChannelValue(Number.parseFloat((event.target as HTMLInputElement).value));
417
+ },
418
+ onKeyDown: (event: KeyboardEvent) => {
419
+ // Page Up and Page Down, which a range input has no notion of.
420
+ if (event.key !== "PageUp" && event.key !== "PageDown") return;
421
+ event.preventDefault();
422
+ state.setDragging(true);
423
+ if (event.key === "PageUp") state.increment(range().pageSize);
424
+ else state.decrement(range().pageSize);
425
+ state.setDragging(false);
426
+ },
427
+ }),
428
+ outputProps: { "aria-live": "off", for: inputId },
429
+ };
430
+ }
431
+
432
+ export interface ColorAreaOptions {
433
+ containerRef: ElementRef;
434
+ xInputRef: ElementRef<HTMLInputElement>;
435
+ yInputRef: ElementRef<HTMLInputElement>;
436
+ "aria-label"?: MaybeAccessor<string | undefined>;
437
+ "aria-labelledby"?: MaybeAccessor<string | undefined>;
438
+ }
439
+
440
+ export interface ColorAreaResult {
441
+ colorAreaProps: DOMProps;
442
+ thumbProps: DOMProps;
443
+ xInputProps: DOMProps;
444
+ yInputProps: DOMProps;
445
+ }
446
+
447
+ /**
448
+ * Two channels in one square.
449
+ *
450
+ * `role="application"` on the container, because the arrow keys inside it move
451
+ * a thumb rather than the reading cursor, and a screen reader has to hand them
452
+ * over. Inside are two real sliders, one per axis: that is what makes the
453
+ * value reachable at all without a pointer.
454
+ */
455
+ export function colorArea(options: ColorAreaOptions, state: ColorAreaState): ColorAreaResult {
456
+ const listeners = globalListeners();
457
+ let position: { x: number; y: number } | null = null;
458
+
459
+ /**
460
+ * Which axis the keyboard last moved, so a drag ends on the input that was
461
+ * driving it.
462
+ *
463
+ * There are two `<input type="range">`s under a colour area, one per channel,
464
+ * and only one can hold focus. Always returning to the X one loses a screen
465
+ * reader user's place the moment they adjust Y: the reader announces the X
466
+ * channel again and the arrows go back to moving X.
467
+ */
468
+ let axis: "x" | "y" = "x";
469
+
470
+ const focusAxis = (): void => {
471
+ const ref = axis === "y" ? options.yInputRef : options.xInputRef;
472
+ (access(ref) as HTMLInputElement | null)?.focus();
473
+ };
474
+
475
+ const { moveProps } = move({
476
+ onMoveStart: () => {
477
+ position = null;
478
+ state.setDragging(true);
479
+ },
480
+ onMove: (event) => {
481
+ const container = access(options.containerRef) as Element | null;
482
+ if (container === null) return;
483
+ const box = container.getBoundingClientRect();
484
+ if (box.width === 0 || box.height === 0) return;
485
+
486
+ if (position === null) {
487
+ position = { x: state.xPercent() * box.width, y: (1 - state.yPercent()) * box.height };
488
+ }
489
+ position.x += event.deltaX;
490
+ position.y += event.deltaY;
491
+ // The y axis counts DOWN the screen and UP the value.
492
+ state.setPercents(position.x / box.width, 1 - position.y / box.height);
493
+ },
494
+ onMoveEnd: () => {
495
+ state.setDragging(false);
496
+ focusAxis();
497
+ },
498
+ });
499
+
500
+ const onDown = (clientX: number, clientY: number): void => {
501
+ const container = access(options.containerRef) as Element | null;
502
+ if (container === null || state.isDisabled()) return;
503
+ const box = container.getBoundingClientRect();
504
+ if (box.width === 0 || box.height === 0) return;
505
+ state.setDragging(true);
506
+ state.setPercents((clientX - box.left) / box.width, 1 - (clientY - box.top) / box.height);
507
+ // A pointer drives both channels at once, so it lands on X — which is what
508
+ // a reader then announces, and what the arrows move next.
509
+ axis = "x";
510
+ focusAxis();
511
+ if (isServer) return;
512
+ const view = container.ownerDocument.defaultView ?? window;
513
+ listeners.add(view, "pointerup", () => {
514
+ state.setDragging(false);
515
+ listeners.removeAll();
516
+ });
517
+ };
518
+
519
+ const inputFor = (axisName: "x" | "y"): DOMProps => {
520
+ const channel = axisName === "x" ? state.xChannel : state.yChannel;
521
+ const read = axisName === "x" ? state.xValue : state.yValue;
522
+ const write = axisName === "x" ? state.setXValue : state.setYValue;
523
+ const range = (): ReturnType<Color["getChannelRange"]> =>
524
+ state.value().getChannelRange(channel());
525
+
526
+ return {
527
+ type: "range",
528
+ min: () => range().minValue,
529
+ max: () => range().maxValue,
530
+ step: () => range().step,
531
+ value: read,
532
+ disabled: state.isDisabled,
533
+ "aria-label": () => state.value().getChannelName(channel()),
534
+ "aria-orientation": axisName === "x" ? "horizontal" : "vertical",
535
+ // Both axes, on both inputs: a screen reader user moving one has to hear
536
+ // what the other is, or the colour is half a description.
537
+ "aria-valuetext": state.valueText,
538
+ onFocus: () => {
539
+ axis = axisName;
540
+ },
541
+ onInput: (event: Event) => {
542
+ axis = axisName;
543
+ write(Number.parseFloat((event.target as HTMLInputElement).value));
544
+ },
545
+ onChange: (event: Event) => {
546
+ axis = axisName;
547
+ write(Number.parseFloat((event.target as HTMLInputElement).value));
548
+ },
549
+ };
550
+ };
551
+
552
+ return {
553
+ colorAreaProps: mergeProps(moveProps, {
554
+ // The arrows belong to the thumb, not to the reading cursor.
555
+ role: "application",
556
+ "aria-label": () => access(options["aria-label"]) ?? "Color area",
557
+ "aria-labelledby": () => access(options["aria-labelledby"]),
558
+ "aria-roledescription": "2D slider",
559
+ "aria-disabled": () => state.isDisabled() || undefined,
560
+ onPointerDown: (event: PointerEvent) => {
561
+ if (event.button !== 0) return;
562
+ onDown(event.clientX, event.clientY);
563
+ },
564
+ style: { position: "relative", "touch-action": "none" },
565
+ }),
566
+ thumbProps: {
567
+ style: () => ({
568
+ position: "absolute",
569
+ left: `${state.xPercent() * 100}%`,
570
+ top: `${(1 - state.yPercent()) * 100}%`,
571
+ transform: "translate(-50%, -50%)",
572
+ "touch-action": "none",
573
+ }),
574
+ },
575
+ xInputProps: inputFor("x"),
576
+ yInputProps: inputFor("y"),
577
+ };
578
+ }
579
+
580
+ // ---------------------------------------------------------------------------
581
+ // The hue on a circle: the wheel
582
+ // ---------------------------------------------------------------------------
583
+
584
+ /** Zero degrees is three o'clock, and the angle grows clockwise. */
585
+ function angleToCartesian(angle: number, radius: number): { x: number; y: number } {
586
+ const radians = ((360 - angle + 90) * Math.PI) / 180;
587
+ return { x: Math.sin(radians) * radius, y: Math.cos(radians) * radius };
588
+ }
589
+
590
+ function cartesianToAngle(x: number, y: number, radius: number): number {
591
+ const degrees = (Math.atan2(y / radius, x / radius) * 180) / Math.PI;
592
+ return (degrees + 360) % 360;
593
+ }
594
+
595
+ /** A positive remainder, which `%` does not give for a negative left-hand side. */
596
+ function mod(n: number, m: number): number {
597
+ return ((n % m) + m) % m;
598
+ }
599
+
600
+ export interface ColorWheelStateOptions extends ColorStateOptions {}
601
+
602
+ export interface ColorWheelState {
603
+ value: Accessor<Color>;
604
+ setValue(value: Color): void;
605
+ /** What a form reset goes back to. */
606
+ defaultValue: Accessor<Color>;
607
+ hue: Accessor<number>;
608
+ setHue(hue: number): void;
609
+ /** From a point relative to the CENTRE of the wheel. */
610
+ setHueFromPoint(x: number, y: number, radius: number): void;
611
+ /** Where the thumb sits, relative to the centre. */
612
+ thumbPosition(radius: number): { x: number; y: number };
613
+ increment(step?: number): void;
614
+ decrement(step?: number): void;
615
+ step: Accessor<number>;
616
+ pageStep: Accessor<number>;
617
+ isDragging: Accessor<boolean>;
618
+ setDragging(isDragging: boolean): void;
619
+ isDisabled: Accessor<boolean>;
620
+ }
621
+
622
+ /**
623
+ * The hue of a colour, as an angle.
624
+ *
625
+ * Hue is the one channel that WRAPS: 359 and 1 are two degrees apart, and a
626
+ * slider cannot say that. Everything here follows from it — incrementing past
627
+ * 360 lands on 0 rather than stopping, and decrementing from 0 goes to the
628
+ * last step below 360 rather than to −1.
629
+ *
630
+ * The value is kept in HSL or HSB, because RGB has no hue to turn.
631
+ */
632
+ export function colorWheelState(options: ColorWheelStateOptions = {}): ColorWheelState {
633
+ const [raw, setRaw] = controllable<Color>(
634
+ () => asColor(access(options.value)),
635
+ () => asColor(access(options.defaultValue)) ?? parseColor("hsl(0, 100%, 50%)"),
636
+ options.onChange,
637
+ );
638
+
639
+ const value = (): Color => {
640
+ const current = raw();
641
+ const space = current.getColorSpace();
642
+ return space === "hsl" || space === "hsb" ? current : current.toFormat("hsl");
643
+ };
644
+
645
+ // Read once: a form reset goes back to where the wheel STARTED, not to
646
+ // wherever the caller's default happens to point by then.
647
+ const initial = value();
648
+
649
+ const [dragging, writeDragging] = createSignal(false);
650
+ const isDisabled = (): boolean => access(options.isDisabled) === true;
651
+
652
+ // What the LAST write produced, so a drag reads its own change back rather
653
+ // than the value a controlled owner has not caught up with yet.
654
+ let live = value();
655
+
656
+ const setValue = (next: Color): void => {
657
+ live = next;
658
+ setRaw(next);
659
+ };
660
+
661
+ const range = (): ReturnType<Color["getChannelRange"]> => value().getChannelRange("hue");
662
+ const step = (): number => range().step;
663
+ const pageStep = (): number => range().pageSize ?? Math.max(step(), 15);
664
+
665
+ const hue = (): number => value().getChannelValue("hue");
666
+
667
+ const setHue = (next: number): void => {
668
+ if (isDisabled()) return;
669
+ // 360 is 0. Without this the wheel has a value the user can reach going up
670
+ // and never going down.
671
+ const wrapped = next > 360 ? 0 : next;
672
+ const snapped = Math.round(mod(wrapped, 360) / step()) * step();
673
+ if (hue() === snapped) return;
674
+ setValue(live.withChannelValue("hue", snapped));
675
+ };
676
+
677
+ return {
678
+ value,
679
+ setValue,
680
+ defaultValue: () => initial,
681
+ hue,
682
+ setHue,
683
+ setHueFromPoint: (x, y, radius) => setHue(cartesianToAngle(x, y, radius)),
684
+ thumbPosition: (radius) => angleToCartesian(hue(), radius),
685
+ step,
686
+ pageStep,
687
+ isDragging: dragging,
688
+ isDisabled,
689
+ setDragging: (next) => {
690
+ const was = dragging();
691
+ writeDragging(next);
692
+ if (was && !next) options.onChangeEnd?.(live);
693
+ },
694
+ increment: (amount) => {
695
+ const by = Math.max(amount ?? 1, step());
696
+ const next = hue() + by;
697
+ // Past the top is back to the bottom, so the wheel turns rather than
698
+ // stopping at a seam the user cannot see.
699
+ setHue(next >= range().maxValue ? range().minValue : mod(next, 360));
700
+ },
701
+ decrement: (amount) => {
702
+ const by = Math.max(amount ?? 1, step());
703
+ if (hue() !== 0) {
704
+ setHue(mod(hue() - by, 360));
705
+ return;
706
+ }
707
+ // Below zero is the last step under 360. Subtracting `by` would land on
708
+ // a negative, and `mod` would bring it back to something that is not on
709
+ // the step grid.
710
+ const top = 360 / by;
711
+ setHue((Number.isInteger(top) ? top - 1 : Math.floor(top)) * by);
712
+ },
713
+ };
714
+ }
715
+
716
+ export interface ColorWheelOptions {
717
+ /** The wheel element, for turning a pointer position into an angle. */
718
+ trackRef: ElementRef;
719
+ inputRef: ElementRef<HTMLInputElement>;
720
+ /** The hole in the middle. A press inside it is not a press on the track. */
721
+ innerRadius: MaybeAccessor<number>;
722
+ outerRadius: MaybeAccessor<number>;
723
+ // No `isDisabled`: the STATE carries it, and a second copy here would be a
724
+ // flag a caller could set and watch do nothing.
725
+ name?: MaybeAccessor<string | undefined>;
726
+ form?: MaybeAccessor<string | undefined>;
727
+ "aria-label"?: MaybeAccessor<string | undefined>;
728
+ "aria-labelledby"?: MaybeAccessor<string | undefined>;
729
+ }
730
+
731
+ export interface ColorWheelResult {
732
+ trackProps: DOMProps;
733
+ thumbProps: DOMProps;
734
+ /** A real `<input type="range">`, hidden, which is what the platform drives. */
735
+ inputProps: DOMProps;
736
+ }
737
+
738
+ /**
739
+ * A circular hue picker.
740
+ *
741
+ * The control is a real `<input type="range">` under the visuals, hidden but
742
+ * focusable, exactly as the sliders here are: it is what a screen reader
743
+ * announces, what the platform's own arrow handling drives, and what a form
744
+ * submits. The circle is decoration over it.
745
+ *
746
+ * A press lands on the track only between the two radii. The hole in the
747
+ * middle usually holds a colour area, and a press there belongs to that.
748
+ */
749
+ export function colorWheel(options: ColorWheelOptions, state: ColorWheelState): ColorWheelResult {
750
+ const inputId = id();
751
+ const thumbRadius = (): number => (access(options.innerRadius) + access(options.outerRadius)) / 2;
752
+
753
+ const focusInput = (): void => {
754
+ const input = access(options.inputRef) as HTMLInputElement | null;
755
+ if (input !== null) focusWithoutScrolling(input);
756
+ };
757
+
758
+ formReset(options.inputRef, state.defaultValue, (next: Color) => state.setValue(next));
759
+
760
+ /** Where the drag is, in wheel coordinates, accumulated across the move. */
761
+ let at: { x: number; y: number } | null = null;
762
+ /** Whether the press that started this drag landed on the ring. */
763
+ let onTrack = false;
764
+
765
+ const beginDrag = (): void => {
766
+ at = null;
767
+ state.setDragging(true);
768
+ };
769
+
770
+ const drag = (event: MoveMoveEvent): void => {
771
+ at ??= state.thumbPosition(thumbRadius());
772
+ at.x += event.deltaX;
773
+ at.y += event.deltaY;
774
+
775
+ if (event.pointerType === "keyboard") {
776
+ // Right and up are more; left and down are less. The wheel has no axis,
777
+ // so both pairs mean the same thing.
778
+ if (event.deltaX > 0 || event.deltaY < 0) {
779
+ state.increment(event.shiftKey ? state.pageStep() : state.step());
780
+ } else if (event.deltaX < 0 || event.deltaY > 0) {
781
+ state.decrement(event.shiftKey ? state.pageStep() : state.step());
782
+ }
783
+ return;
784
+ }
785
+ state.setHueFromPoint(at.x, at.y, thumbRadius());
786
+ };
787
+
788
+ const endDrag = (): void => {
789
+ onTrack = false;
790
+ state.setDragging(false);
791
+ focusInput();
792
+ };
793
+
794
+ const { moveProps: thumbMoveProps } = move({
795
+ onMoveStart: beginDrag,
796
+ onMove: drag,
797
+ onMoveEnd: endDrag,
798
+ });
799
+
800
+ // The same handlers on the CONTAINER, but only once a press has landed on
801
+ // the ring: a drag that began in the hole is not this wheel's.
802
+ const { moveProps: trackMoveProps } = move({
803
+ onMoveStart: () => {
804
+ if (onTrack) beginDrag();
805
+ },
806
+ onMove: (event) => {
807
+ if (onTrack) drag(event);
808
+ },
809
+ onMoveEnd: () => {
810
+ if (onTrack) endDrag();
811
+ },
812
+ });
813
+
814
+ const onTrackDown = (clientX: number, clientY: number): void => {
815
+ const track = access(options.trackRef) as Element | null;
816
+ if (track === null || state.isDisabled()) return;
817
+
818
+ const box = track.getBoundingClientRect();
819
+ const x = clientX - box.x - box.width / 2;
820
+ const y = clientY - box.y - box.height / 2;
821
+ const radius = Math.hypot(x, y);
822
+
823
+ // Between the two radii and nowhere else: the hole belongs to whatever is
824
+ // in it, and outside the ring is the page.
825
+ if (radius <= access(options.innerRadius) || radius >= access(options.outerRadius)) return;
826
+
827
+ onTrack = true;
828
+ state.setHueFromPoint(x, y, radius);
829
+ focusInput();
830
+ state.setDragging(true);
831
+ };
832
+
833
+ return {
834
+ trackProps: mergeProps(trackMoveProps, {
835
+ onPointerDown: (event: PointerEvent) => {
836
+ if (event.button !== 0) return;
837
+ onTrackDown(event.clientX, event.clientY);
838
+ },
839
+ style: { position: "relative", "touch-action": "none" },
840
+ }),
841
+ thumbProps: mergeProps(thumbMoveProps, {
842
+ style: () => {
843
+ const position = state.thumbPosition(thumbRadius());
844
+ return {
845
+ position: "absolute",
846
+ left: `${position.x + access(options.outerRadius)}px`,
847
+ top: `${position.y + access(options.outerRadius)}px`,
848
+ transform: "translate(-50%, -50%)",
849
+ "touch-action": "none",
850
+ };
851
+ },
852
+ onPointerDown: () => {
853
+ if (state.isDisabled()) return;
854
+ focusInput();
855
+ },
856
+ }),
857
+ inputProps: {
858
+ id: inputId,
859
+ type: "range",
860
+ min: 0,
861
+ max: 360,
862
+ step: state.step,
863
+ value: state.hue,
864
+ disabled: state.isDisabled,
865
+ name: () => access(options.name),
866
+ form: () => access(options.form),
867
+ "aria-label": () => access(options["aria-label"]) ?? "Hue",
868
+ "aria-labelledby": () => access(options["aria-labelledby"]),
869
+ // The number MEANS something: "212" is not a colour, "Hue 212" is.
870
+ "aria-valuetext": () => `Hue ${Math.round(state.hue())}`,
871
+ style: HIDDEN_INPUT_STYLE,
872
+ onInput: (event: Event) => {
873
+ state.setHue(Number.parseFloat((event.target as HTMLInputElement).value));
874
+ },
875
+ onChange: (event: Event) => {
876
+ state.setHue(Number.parseFloat((event.target as HTMLInputElement).value));
877
+ },
878
+ onKeyDown: (event: KeyboardEvent) => {
879
+ // Page Up and Page Down, which a range input has no notion of.
880
+ if (event.key !== "PageUp" && event.key !== "PageDown") return;
881
+ event.preventDefault();
882
+ state.setDragging(true);
883
+ if (event.key === "PageUp") state.increment(state.pageStep());
884
+ else state.decrement(state.pageStep());
885
+ state.setDragging(false);
886
+ },
887
+ },
888
+ };
889
+ }
890
+
891
+ export interface ColorFieldOptions extends Omit<
892
+ TextFieldOptions,
893
+ "value" | "onChange" | "type" | "validate"
894
+ > {
895
+ /** @default "hex" */
896
+ format?: MaybeAccessor<ColorFormat | undefined>;
897
+ /**
898
+ * What the page thinks of the COLOUR, checked as it is committed.
899
+ *
900
+ * The colour rather than the typed text: "#ff" is a prefix, not a colour,
901
+ * and a validator handed one has nothing to say about it.
902
+ */
903
+ validate?: ValidateFunction<Color>;
904
+ }
905
+
906
+ export interface ColorFieldResult {
907
+ labelProps: DOMProps;
908
+ inputProps: DOMProps;
909
+ descriptionProps: DOMProps;
910
+ errorMessageProps: DOMProps;
911
+ /** What is wrong with the colour, and whether the user is being told. */
912
+ validation: FormValidationState;
913
+ errors: Accessor<string[]>;
914
+ isInvalid: Accessor<boolean>;
915
+ }
916
+
917
+ /**
918
+ * A colour as text.
919
+ *
920
+ * Committed on blur and on Enter, never as you type: "#ff" is not a colour,
921
+ * and a field that reported one on every keystroke would flash the page
922
+ * through every prefix of what was typed.
923
+ */
924
+ export function colorField(
925
+ options: ColorFieldOptions,
926
+ state: { value: Accessor<Color>; setValue(value: Color): void; isDisabled: Accessor<boolean> },
927
+ ref: ElementRef<HTMLInputElement>,
928
+ ): ColorFieldResult {
929
+ const format = (): ColorFormat => access(options.format) ?? "hex";
930
+ const [text, writeText] = createSignal(state.value().toString(format()));
931
+
932
+ let live = state.value().toString(format());
933
+ // What the field SHOWS. Enter commits in the same tick as the keystroke that
934
+ // produced the text, and a signal write is not published until the flush, so
935
+ // `text()` would hand the parser the value the typing replaced.
936
+ let typed = live;
937
+ const setText = (next: string): void => {
938
+ typed = next;
939
+ writeText(next);
940
+ };
941
+
942
+ const sync = (): void => {
943
+ const formatted = state.value().toString(format());
944
+ if (formatted === live) return;
945
+ live = formatted;
946
+ setText(formatted);
947
+ };
948
+
949
+ const commit = (): void => {
950
+ try {
951
+ const parsed = parseColor(typed);
952
+ live = parsed.toString(format());
953
+ setText(live);
954
+ state.setValue(parsed);
955
+ } catch {
956
+ // Not a colour: the field goes back to what it holds rather than
957
+ // keeping text that means nothing.
958
+ setText(state.value().toString(format()));
959
+ }
960
+ };
961
+
962
+ const {
963
+ labelProps,
964
+ inputProps,
965
+ descriptionProps,
966
+ errorMessageProps,
967
+ validation,
968
+ errors,
969
+ isInvalid,
970
+ } = textField(
971
+ {
972
+ ...options,
973
+ type: "text",
974
+ value: () => {
975
+ sync();
976
+ return text();
977
+ },
978
+ // The caller validates the COLOUR; `textField` validates a string, so
979
+ // the typed text is ignored and the committed value is handed over.
980
+ validate:
981
+ options.validate === undefined
982
+ ? undefined
983
+ : () => (options.validate as ValidateFunction<Color>)(state.value()),
984
+ onChange: setText,
985
+ autoComplete: "off",
986
+ },
987
+ ref,
988
+ );
989
+
990
+ return {
991
+ labelProps,
992
+ descriptionProps,
993
+ errorMessageProps,
994
+ validation,
995
+ errors,
996
+ isInvalid,
997
+ inputProps: mergeProps(inputProps, {
998
+ autocorrect: "off",
999
+ spellcheck: "false",
1000
+ onBlur: () => {
1001
+ commit();
1002
+ validation.commitValidation();
1003
+ },
1004
+ onKeyDown: (event: KeyboardEvent) => {
1005
+ if (event.key !== "Enter") return;
1006
+ commit();
1007
+ },
1008
+ }),
1009
+ };
1010
+ }
1011
+
1012
+ export interface ColorSwatchOptions {
1013
+ color: MaybeAccessor<Color | string>;
1014
+ /** What to call it. Defaults to the colour's own description. */
1015
+ "aria-label"?: MaybeAccessor<string | undefined>;
1016
+ }
1017
+
1018
+ export interface ColorSwatchResult {
1019
+ swatchProps: DOMProps;
1020
+ color: Accessor<Color>;
1021
+ }
1022
+
1023
+ /** A square of colour, named so it is not invisible to a screen reader. */
1024
+ export function colorSwatch(options: ColorSwatchOptions): ColorSwatchResult {
1025
+ const color = createMemo(() => {
1026
+ const given = access(options.color);
1027
+ return typeof given === "string" ? parseColor(given) : given;
1028
+ });
1029
+
1030
+ const description = (): string => {
1031
+ const current = color();
1032
+ const hsl = current.toFormat("hsl");
1033
+ return `${Math.round(hsl.getChannelValue("hue"))} degrees, ${Math.round(
1034
+ hsl.getChannelValue("saturation"),
1035
+ )}% saturation, ${Math.round(hsl.getChannelValue("lightness"))}% lightness`;
1036
+ };
1037
+
1038
+ return {
1039
+ color,
1040
+ swatchProps: {
1041
+ // An image, not a button: it SHOWS a colour and does nothing.
1042
+ role: "img",
1043
+ "aria-label": () => access(options["aria-label"]) ?? description(),
1044
+ style: () => ({ "background-color": color().toString("css") }),
1045
+ },
1046
+ };
1047
+ }
1048
+
1049
+ // ---------------------------------------------------------------------------
1050
+ // Components
1051
+ // ---------------------------------------------------------------------------
1052
+
1053
+ interface ColorPickerContextValue {
1054
+ value: Accessor<Color>;
1055
+ setValue(value: Color): void;
1056
+ isDisabled: Accessor<boolean>;
1057
+ }
1058
+
1059
+ const ColorPickerContext = createContext<ColorPickerContextValue | null>(null);
1060
+
1061
+ /** The enclosing {@link ColorPicker}, if there is one. */
1062
+ export function useColorPicker(): ColorPickerContextValue | null {
1063
+ return getContext(ColorPickerContext) ?? null;
1064
+ }
1065
+
1066
+ export interface ColorPickerComponentProps extends StyleProps {
1067
+ children?: Child;
1068
+ value?: Color | string;
1069
+ defaultValue?: Color | string;
1070
+ isDisabled?: boolean;
1071
+ onChange?: (value: Color) => void;
1072
+ }
1073
+
1074
+ /**
1075
+ * One colour, shared by every control inside.
1076
+ *
1077
+ * ```tsx
1078
+ * <ColorPicker defaultValue="#7f00ff">
1079
+ * <ColorArea />
1080
+ * <ColorSlider channel="hue" />
1081
+ * <ColorSlider channel="alpha" />
1082
+ * <ColorField label="Hex" />
1083
+ * </ColorPicker>
1084
+ * ```
1085
+ */
1086
+ export function ColorPicker(props: Incoming<ColorPickerComponentProps>) {
1087
+ const [value, setValue] = controllable<Color>(
1088
+ () => asColor(props.value?.()),
1089
+ () => asColor(props.defaultValue?.()) ?? defaultColor(),
1090
+ (next) => props.onChange?.()?.(next),
1091
+ );
1092
+
1093
+ const owner = getOwner();
1094
+ if (owner !== null) {
1095
+ install(owner, ColorPickerContext, () => ({
1096
+ value,
1097
+ setValue,
1098
+ isDisabled: () => props.isDisabled?.() === true,
1099
+ }));
1100
+ }
1101
+
1102
+ const elementProps = mergeProps(
1103
+ filterDOMProps(fromProps(props), { global: true }),
1104
+ styleProps(props),
1105
+ {
1106
+ "data-testid": () => props["data-testid"]?.(),
1107
+ },
1108
+ );
1109
+
1110
+ return <div {...elementProps}>{props.children}</div>;
1111
+ }
1112
+
1113
+ export interface ColorSliderComponentProps extends StyleProps {
1114
+ channel: ColorChannel;
1115
+ label?: Child;
1116
+ value?: Color | string;
1117
+ defaultValue?: Color | string;
1118
+ /** @default "horizontal" */
1119
+ orientation?: Orientation;
1120
+ isDisabled?: boolean;
1121
+ "aria-label"?: string;
1122
+ ref?: RefTarget<HTMLDivElement>;
1123
+ onChange?: (value: Color) => void;
1124
+ onChangeEnd?: (value: Color) => void;
1125
+ }
1126
+
1127
+ /** One channel on a track: a hue, an alpha, a red. */
1128
+ export function ColorSlider(props: Incoming<ColorSliderComponentProps>) {
1129
+ const trackRef = makeRef<HTMLDivElement>();
1130
+ const inputRef = makeRef<HTMLInputElement>();
1131
+ const picker = useColorPicker();
1132
+
1133
+ const state = colorSliderState({
1134
+ channel: () => props.channel(),
1135
+ orientation: () => props.orientation?.(),
1136
+ value: () => props.value?.() ?? picker?.value(),
1137
+ defaultValue: () => props.defaultValue?.(),
1138
+ isDisabled: () => props.isDisabled?.() ?? picker?.isDisabled(),
1139
+ onChange: (value) => {
1140
+ picker?.setValue(value);
1141
+ props.onChange?.()?.(value);
1142
+ },
1143
+ onChangeEnd: (value) => props.onChangeEnd?.()?.(value),
1144
+ });
1145
+
1146
+ const { labelProps, trackProps, thumbProps, inputProps, outputProps } = colorSlider(
1147
+ {
1148
+ trackRef,
1149
+ inputRef,
1150
+ label: () => props.label?.(),
1151
+ "aria-label": () =>
1152
+ props["aria-label"]?.() ??
1153
+ (props.label?.() === undefined ? state.value().getChannelName(props.channel()) : undefined),
1154
+ },
1155
+ state,
1156
+ );
1157
+
1158
+ const { visuallyHiddenProps } = visuallyHidden();
1159
+ const { focusProps, isFocusVisible } = focusRing();
1160
+ const { hoverProps, isHovered } = hover({ isDisabled: state.isDisabled });
1161
+
1162
+ const elementProps = mergeProps(
1163
+ trackProps,
1164
+ hoverProps,
1165
+ filterDOMProps(fromProps(props), { global: true }),
1166
+ styleProps(props),
1167
+ {
1168
+ "data-orientation": state.orientation,
1169
+ "data-dragging": state.isDragging,
1170
+ "data-disabled": state.isDisabled,
1171
+ "data-testid": () => props["data-testid"]?.(),
1172
+ },
1173
+ );
1174
+
1175
+ return (
1176
+ <>
1177
+ {() => (props.label?.() === undefined ? null : <label {...labelProps}>{props.label}</label>)}
1178
+ <output {...outputProps}>{() => state.valueText()}</output>
1179
+ <div {...elementProps} ref={mergeRefs(trackRef.set, props.ref?.())}>
1180
+ <div
1181
+ {...mergeProps(thumbProps, {
1182
+ "data-focus-visible": isFocusVisible,
1183
+ "data-hovered": isHovered,
1184
+ })}
1185
+ >
1186
+ <input
1187
+ {...mergeProps(inputProps, focusProps, { style: visuallyHiddenProps.style })}
1188
+ ref={inputRef.set}
1189
+ />
1190
+ </div>
1191
+ </div>
1192
+ </>
1193
+ );
1194
+ }
1195
+
1196
+ export interface ColorAreaComponentProps extends StyleProps {
1197
+ value?: Color | string;
1198
+ defaultValue?: Color | string;
1199
+ xChannel?: ColorChannel;
1200
+ yChannel?: ColorChannel;
1201
+ isDisabled?: boolean;
1202
+ "aria-label"?: string;
1203
+ ref?: RefTarget<HTMLDivElement>;
1204
+ onChange?: (value: Color) => void;
1205
+ onChangeEnd?: (value: Color) => void;
1206
+ }
1207
+
1208
+ /** Two channels in a square: saturation across, brightness up. */
1209
+ export function ColorArea(props: Incoming<ColorAreaComponentProps>) {
1210
+ const containerRef = makeRef<HTMLDivElement>();
1211
+ const xInputRef = makeRef<HTMLInputElement>();
1212
+ const yInputRef = makeRef<HTMLInputElement>();
1213
+ const picker = useColorPicker();
1214
+
1215
+ const state = colorAreaState({
1216
+ value: () => props.value?.() ?? picker?.value(),
1217
+ defaultValue: () => props.defaultValue?.(),
1218
+ xChannel: () => props.xChannel?.(),
1219
+ yChannel: () => props.yChannel?.(),
1220
+ isDisabled: () => props.isDisabled?.() ?? picker?.isDisabled(),
1221
+ onChange: (value) => {
1222
+ picker?.setValue(value);
1223
+ props.onChange?.()?.(value);
1224
+ },
1225
+ onChangeEnd: (value) => props.onChangeEnd?.()?.(value),
1226
+ });
1227
+
1228
+ const { colorAreaProps, thumbProps, xInputProps, yInputProps } = colorArea(
1229
+ {
1230
+ containerRef,
1231
+ xInputRef,
1232
+ yInputRef,
1233
+ "aria-label": () => props["aria-label"]?.(),
1234
+ },
1235
+ state,
1236
+ );
1237
+
1238
+ const { visuallyHiddenProps } = visuallyHidden();
1239
+ const { focusProps, isFocusVisible } = focusRing();
1240
+
1241
+ const elementProps = mergeProps(
1242
+ colorAreaProps,
1243
+ filterDOMProps(fromProps(props), { global: true }),
1244
+ styleProps(props),
1245
+ {
1246
+ "data-dragging": state.isDragging,
1247
+ "data-disabled": state.isDisabled,
1248
+ "data-testid": () => props["data-testid"]?.(),
1249
+ },
1250
+ );
1251
+
1252
+ return (
1253
+ <div {...elementProps} ref={mergeRefs(containerRef.set, props.ref?.())}>
1254
+ <div {...mergeProps(thumbProps, { "data-focus-visible": isFocusVisible })}>
1255
+ <input
1256
+ {...mergeProps(xInputProps, focusProps, { style: visuallyHiddenProps.style })}
1257
+ ref={xInputRef.set}
1258
+ />
1259
+ <input
1260
+ {...mergeProps(yInputProps, { style: visuallyHiddenProps.style })}
1261
+ ref={yInputRef.set}
1262
+ />
1263
+ </div>
1264
+ </div>
1265
+ );
1266
+ }
1267
+
1268
+ export interface ColorWheelComponentProps extends StyleProps {
1269
+ value?: Color | string;
1270
+ defaultValue?: Color | string;
1271
+ /** The hole in the middle, in pixels. @default 64 */
1272
+ innerRadius?: number;
1273
+ /** The wheel's radius, in pixels. @default 80 */
1274
+ outerRadius?: number;
1275
+ isDisabled?: boolean;
1276
+ name?: string;
1277
+ form?: string;
1278
+ "aria-label"?: string;
1279
+ "aria-labelledby"?: string;
1280
+ ref?: RefTarget<HTMLDivElement>;
1281
+ onChange?: (value: Color) => void;
1282
+ onChangeEnd?: (value: Color) => void;
1283
+ }
1284
+
1285
+ /**
1286
+ * ```tsx
1287
+ * <ColorWheel defaultValue="hsl(30, 100%, 50%)" onChange={(c) => colour.set(c)} />
1288
+ * ```
1289
+ *
1290
+ * The hue on a circle. The conic gradient that makes it look like a wheel is
1291
+ * the caller's to style; what is here is the geometry, the keyboard and the
1292
+ * hidden `<input type="range">` a screen reader announces.
1293
+ */
1294
+ export function ColorWheel(props: Incoming<ColorWheelComponentProps>) {
1295
+ const trackRef = makeRef<HTMLDivElement>();
1296
+ const inputRef = makeRef<HTMLInputElement>();
1297
+ const picker = useColorPicker();
1298
+
1299
+ const state = colorWheelState({
1300
+ value: () => props.value?.() ?? picker?.value(),
1301
+ defaultValue: () => props.defaultValue?.(),
1302
+ isDisabled: () => props.isDisabled?.() ?? picker?.isDisabled(),
1303
+ onChange: (value) => {
1304
+ picker?.setValue(value);
1305
+ props.onChange?.()?.(value);
1306
+ },
1307
+ onChangeEnd: (value) => props.onChangeEnd?.()?.(value),
1308
+ });
1309
+
1310
+ const outerRadius = (): number => props.outerRadius?.() ?? 80;
1311
+ const innerRadius = (): number => props.innerRadius?.() ?? 64;
1312
+
1313
+ const { trackProps, thumbProps, inputProps } = colorWheel(
1314
+ {
1315
+ trackRef,
1316
+ inputRef,
1317
+ innerRadius,
1318
+ outerRadius,
1319
+ name: () => props.name?.(),
1320
+ form: () => props.form?.(),
1321
+ "aria-label": () => props["aria-label"]?.(),
1322
+ "aria-labelledby": () => props["aria-labelledby"]?.(),
1323
+ },
1324
+ state,
1325
+ );
1326
+
1327
+ const { focusProps, isFocusVisible } = focusRing();
1328
+ const { hoverProps, isHovered } = hover({ isDisabled: state.isDisabled });
1329
+
1330
+ const elementProps = mergeProps(
1331
+ trackProps,
1332
+ hoverProps,
1333
+ filterDOMProps(fromProps(props), { global: true }),
1334
+ styleProps(props),
1335
+ {
1336
+ "data-dragging": state.isDragging,
1337
+ "data-disabled": state.isDisabled,
1338
+ "data-testid": () => props["data-testid"]?.(),
1339
+ style: () => ({
1340
+ position: "relative",
1341
+ "touch-action": "none",
1342
+ width: `${outerRadius() * 2}px`,
1343
+ height: `${outerRadius() * 2}px`,
1344
+ }),
1345
+ },
1346
+ );
1347
+
1348
+ return (
1349
+ <div {...elementProps} ref={mergeRefs(trackRef.set, props.ref?.())}>
1350
+ <div
1351
+ {...mergeProps(thumbProps, {
1352
+ "data-focus-visible": isFocusVisible,
1353
+ "data-hovered": isHovered,
1354
+ })}
1355
+ >
1356
+ <input {...mergeProps(inputProps, focusProps)} ref={inputRef.set} />
1357
+ </div>
1358
+ </div>
1359
+ );
1360
+ }
1361
+
1362
+ export interface ColorFieldComponentProps extends StyleProps {
1363
+ label?: Child;
1364
+ description?: Child;
1365
+ errorMessage?: Child;
1366
+ value?: Color | string;
1367
+ defaultValue?: Color | string;
1368
+ /** @default "hex" */
1369
+ format?: ColorFormat;
1370
+ isDisabled?: boolean;
1371
+ isReadOnly?: boolean;
1372
+ isRequired?: boolean;
1373
+ isInvalid?: boolean;
1374
+ /** What the page thinks of the colour, checked as it is committed. */
1375
+ validate?: ValidateFunction<Color>;
1376
+ /** @default "aria" */
1377
+ validationBehavior?: ValidationBehavior;
1378
+ name?: string;
1379
+ "aria-label"?: string;
1380
+ ref?: RefTarget<HTMLInputElement>;
1381
+ onChange?: (value: Color) => void;
1382
+ }
1383
+
1384
+ /** A colour as text: `#7f00ff`, committed on blur and on Enter. */
1385
+ export function ColorField(props: Incoming<ColorFieldComponentProps>) {
1386
+ const domRef = makeRef<HTMLInputElement>();
1387
+ const picker = useColorPicker();
1388
+
1389
+ const [value, setValue] = controllable<Color>(
1390
+ () => asColor(props.value?.()) ?? picker?.value(),
1391
+ () => asColor(props.defaultValue?.()) ?? defaultColor(),
1392
+ (next) => {
1393
+ picker?.setValue(next);
1394
+ props.onChange?.()?.(next);
1395
+ },
1396
+ );
1397
+
1398
+ const state = {
1399
+ value,
1400
+ setValue,
1401
+ isDisabled: (): boolean => props.isDisabled?.() ?? picker?.isDisabled() ?? false,
1402
+ };
1403
+
1404
+ const { labelProps, inputProps, descriptionProps, errorMessageProps, errors, isInvalid } =
1405
+ colorField(
1406
+ {
1407
+ label: () => props.label?.(),
1408
+ description: () => props.description?.(),
1409
+ errorMessage: () => props.errorMessage?.(),
1410
+ format: () => props.format?.(),
1411
+ isDisabled: state.isDisabled,
1412
+ isReadOnly: () => props.isReadOnly?.(),
1413
+ isRequired: () => props.isRequired?.(),
1414
+ isInvalid: () => props.isInvalid?.(),
1415
+ validate: callback<[Color], string | string[] | true | null | undefined>(props.validate),
1416
+ validationBehavior: () => props.validationBehavior?.(),
1417
+ name: () => props.name?.(),
1418
+ "aria-label": () => props["aria-label"]?.(),
1419
+ },
1420
+ state,
1421
+ domRef,
1422
+ );
1423
+
1424
+ const { focusProps, isFocusVisible } = focusRing();
1425
+
1426
+ const elementProps = mergeProps(
1427
+ inputProps,
1428
+ focusProps,
1429
+ filterDOMProps(fromProps(props), { global: true }),
1430
+ styleProps(props),
1431
+ {
1432
+ "data-focus-visible": isFocusVisible,
1433
+ "data-invalid": isInvalid,
1434
+ "data-testid": () => props["data-testid"]?.(),
1435
+ },
1436
+ );
1437
+
1438
+ return (
1439
+ <>
1440
+ <label {...labelProps}>{props.label}</label>
1441
+ <input {...elementProps} ref={mergeRefs(domRef.set, props.ref?.())} />
1442
+ <span {...descriptionProps}>{props.description}</span>
1443
+ <span {...errorMessageProps}>
1444
+ {() => {
1445
+ const given = props.errorMessage?.();
1446
+ if (given !== undefined && given !== null && given !== "") return given;
1447
+ const found = errors();
1448
+ return found.length === 0 ? null : found.join(" ");
1449
+ }}
1450
+ </span>
1451
+ </>
1452
+ );
1453
+ }
1454
+
1455
+ export interface ColorSwatchComponentProps extends StyleProps {
1456
+ color?: Color | string;
1457
+ "aria-label"?: string;
1458
+ ref?: RefTarget<HTMLDivElement>;
1459
+ }
1460
+
1461
+ /** A square showing a colour, named with what it is. */
1462
+ export function ColorSwatch(props: Incoming<ColorSwatchComponentProps>) {
1463
+ const picker = useColorPicker();
1464
+
1465
+ const { swatchProps } = colorSwatch({
1466
+ color: () => props.color?.() ?? picker?.value() ?? defaultColor(),
1467
+ "aria-label": () => props["aria-label"]?.(),
1468
+ });
1469
+
1470
+ const elementProps = mergeProps(swatchProps, {
1471
+ class: () => props.class?.() ?? props.className?.(),
1472
+ "data-testid": () => props["data-testid"]?.(),
1473
+ });
1474
+
1475
+ return <div {...elementProps} ref={mergeRefs(props.ref?.())} />;
1476
+ }
1477
+
1478
+ export { parseColor, type Color, type ColorChannel, type ColorFormat, type ColorSpace };