@human-kit/ui 1.0.0-beta.8 → 1.0.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 (134) hide show
  1. package/README.md +27 -60
  2. package/dist/FOCUS_STATE_CONTRACT.md +1 -0
  3. package/dist/color-picker/README.md +78 -0
  4. package/dist/color-picker/area/color-picker-area.svelte +195 -0
  5. package/dist/color-picker/area/color-picker-area.svelte.d.ts +4 -0
  6. package/dist/color-picker/area-thumb/color-picker-area-thumb.svelte +231 -0
  7. package/dist/color-picker/area-thumb/color-picker-area-thumb.svelte.d.ts +4 -0
  8. package/dist/color-picker/channel-field/color-picker-channel-field.svelte +95 -0
  9. package/dist/color-picker/channel-field/color-picker-channel-field.svelte.d.ts +4 -0
  10. package/dist/color-picker/eye-dropper/color-picker-eye-dropper.svelte +79 -0
  11. package/dist/color-picker/eye-dropper/color-picker-eye-dropper.svelte.d.ts +4 -0
  12. package/dist/color-picker/hex-field/color-picker-hex-field.svelte +105 -0
  13. package/dist/color-picker/hex-field/color-picker-hex-field.svelte.d.ts +4 -0
  14. package/dist/color-picker/index.d.ts +16 -0
  15. package/dist/color-picker/index.js +15 -0
  16. package/dist/color-picker/index.parts.d.ts +12 -0
  17. package/dist/color-picker/index.parts.js +12 -0
  18. package/dist/color-picker/label/color-picker-label.svelte +34 -0
  19. package/dist/color-picker/label/color-picker-label.svelte.d.ts +4 -0
  20. package/dist/color-picker/preview/color-picker-preview.svelte +43 -0
  21. package/dist/color-picker/preview/color-picker-preview.svelte.d.ts +4 -0
  22. package/dist/color-picker/root/color-picker-root.svelte +365 -0
  23. package/dist/color-picker/root/color-picker-root.svelte.d.ts +4 -0
  24. package/dist/color-picker/root/color.d.ts +68 -0
  25. package/dist/color-picker/root/color.js +266 -0
  26. package/dist/color-picker/root/context.d.ts +127 -0
  27. package/dist/color-picker/root/context.js +44 -0
  28. package/dist/color-picker/slider/color-picker-slider.svelte +188 -0
  29. package/dist/color-picker/slider/color-picker-slider.svelte.d.ts +4 -0
  30. package/dist/color-picker/slider-thumb/color-picker-slider-thumb.svelte +208 -0
  31. package/dist/color-picker/slider-thumb/color-picker-slider-thumb.svelte.d.ts +4 -0
  32. package/dist/color-picker/swatch/color-picker-swatch.svelte +149 -0
  33. package/dist/color-picker/swatch/color-picker-swatch.svelte.d.ts +4 -0
  34. package/dist/color-picker/swatch-list/color-picker-swatch-list.svelte +133 -0
  35. package/dist/color-picker/swatch-list/color-picker-swatch-list.svelte.d.ts +4 -0
  36. package/dist/color-picker/types.d.ts +176 -0
  37. package/dist/color-picker/types.js +1 -0
  38. package/dist/index.d.ts +10 -0
  39. package/dist/index.js +10 -0
  40. package/dist/internal/localized-strings.d.ts +176 -0
  41. package/dist/internal/localized-strings.js +176 -0
  42. package/dist/pin-input/README.md +55 -0
  43. package/dist/pin-input/cell/pin-input-cell.svelte +210 -0
  44. package/dist/pin-input/cell/pin-input-cell.svelte.d.ts +4 -0
  45. package/dist/pin-input/index.d.ts +6 -0
  46. package/dist/pin-input/index.js +5 -0
  47. package/dist/pin-input/index.parts.d.ts +3 -0
  48. package/dist/pin-input/index.parts.js +3 -0
  49. package/dist/pin-input/label/pin-input-label.svelte +43 -0
  50. package/dist/pin-input/label/pin-input-label.svelte.d.ts +4 -0
  51. package/dist/pin-input/root/context.d.ts +70 -0
  52. package/dist/pin-input/root/context.js +15 -0
  53. package/dist/pin-input/root/pin-input-root.svelte +337 -0
  54. package/dist/pin-input/root/pin-input-root.svelte.d.ts +4 -0
  55. package/dist/pin-input/root/pin-input-utils.d.ts +18 -0
  56. package/dist/pin-input/root/pin-input-utils.js +44 -0
  57. package/dist/pin-input/types.d.ts +84 -0
  58. package/dist/pin-input/types.js +1 -0
  59. package/dist/primitives/aria-hide-outside.d.ts +13 -0
  60. package/dist/primitives/aria-hide-outside.js +7 -1
  61. package/dist/primitives/focus-trap.d.ts +2 -0
  62. package/dist/primitives/focus-trap.js +7 -1
  63. package/dist/primitives/presence.svelte.js +6 -1
  64. package/dist/rating/README.md +58 -0
  65. package/dist/rating/index.d.ts +7 -0
  66. package/dist/rating/index.js +6 -0
  67. package/dist/rating/index.parts.d.ts +4 -0
  68. package/dist/rating/index.parts.js +4 -0
  69. package/dist/rating/item/rating-item.svelte +177 -0
  70. package/dist/rating/item/rating-item.svelte.d.ts +4 -0
  71. package/dist/rating/label/rating-label.svelte +42 -0
  72. package/dist/rating/label/rating-label.svelte.d.ts +4 -0
  73. package/dist/rating/output/rating-output.svelte +38 -0
  74. package/dist/rating/output/rating-output.svelte.d.ts +4 -0
  75. package/dist/rating/root/context.d.ts +87 -0
  76. package/dist/rating/root/context.js +15 -0
  77. package/dist/rating/root/rating-root.svelte +521 -0
  78. package/dist/rating/root/rating-root.svelte.d.ts +4 -0
  79. package/dist/rating/root/rating-utils.d.ts +28 -0
  80. package/dist/rating/root/rating-utils.js +53 -0
  81. package/dist/rating/types.d.ts +124 -0
  82. package/dist/rating/types.js +1 -0
  83. package/dist/search-field/README.md +29 -0
  84. package/dist/search-field/clear/README.md +5 -0
  85. package/dist/search-field/clear/search-field-clear.svelte +99 -0
  86. package/dist/search-field/clear/search-field-clear.svelte.d.ts +10 -0
  87. package/dist/search-field/index.d.ts +15 -0
  88. package/dist/search-field/index.js +6 -0
  89. package/dist/search-field/index.parts.d.ts +4 -0
  90. package/dist/search-field/index.parts.js +4 -0
  91. package/dist/search-field/input/README.md +5 -0
  92. package/dist/search-field/input/search-field-input.svelte +158 -0
  93. package/dist/search-field/input/search-field-input.svelte.d.ts +14 -0
  94. package/dist/search-field/label/README.md +3 -0
  95. package/dist/search-field/label/search-field-label.svelte +27 -0
  96. package/dist/search-field/label/search-field-label.svelte.d.ts +7 -0
  97. package/dist/search-field/root/README.md +5 -0
  98. package/dist/search-field/root/context.d.ts +28 -0
  99. package/dist/search-field/root/context.js +15 -0
  100. package/dist/search-field/root/search-field-root.svelte +230 -0
  101. package/dist/search-field/root/search-field-root.svelte.d.ts +33 -0
  102. package/dist/toast/README.md +75 -0
  103. package/dist/toast/action/toast-action.svelte +42 -0
  104. package/dist/toast/action/toast-action.svelte.d.ts +4 -0
  105. package/dist/toast/close/toast-close.svelte +41 -0
  106. package/dist/toast/close/toast-close.svelte.d.ts +4 -0
  107. package/dist/toast/content/toast-content.svelte +24 -0
  108. package/dist/toast/content/toast-content.svelte.d.ts +4 -0
  109. package/dist/toast/description/toast-description.svelte +41 -0
  110. package/dist/toast/description/toast-description.svelte.d.ts +4 -0
  111. package/dist/toast/index.d.ts +34 -0
  112. package/dist/toast/index.js +15 -0
  113. package/dist/toast/index.parts.d.ts +9 -0
  114. package/dist/toast/index.parts.js +9 -0
  115. package/dist/toast/positioner/toast-positioner.svelte +75 -0
  116. package/dist/toast/positioner/toast-positioner.svelte.d.ts +4 -0
  117. package/dist/toast/provider/context.d.ts +36 -0
  118. package/dist/toast/provider/context.js +22 -0
  119. package/dist/toast/provider/toast-manager.svelte.d.ts +113 -0
  120. package/dist/toast/provider/toast-manager.svelte.js +210 -0
  121. package/dist/toast/provider/toast-provider.svelte +98 -0
  122. package/dist/toast/provider/toast-provider.svelte.d.ts +4 -0
  123. package/dist/toast/root/context.d.ts +18 -0
  124. package/dist/toast/root/context.js +15 -0
  125. package/dist/toast/root/toast-root.svelte +296 -0
  126. package/dist/toast/root/toast-root.svelte.d.ts +4 -0
  127. package/dist/toast/title/toast-title.svelte +38 -0
  128. package/dist/toast/title/toast-title.svelte.d.ts +4 -0
  129. package/dist/toast/types.d.ts +100 -0
  130. package/dist/toast/types.js +1 -0
  131. package/dist/toast/viewport/toast-viewport.svelte +389 -0
  132. package/dist/toast/viewport/toast-viewport.svelte.d.ts +4 -0
  133. package/dist/tooltip/root/tooltip-root.svelte +16 -11
  134. package/package.json +26 -1
@@ -0,0 +1,365 @@
1
+ <script lang="ts">
2
+ import { untrack } from 'svelte';
3
+ import { readable } from 'svelte/store';
4
+ import { dev } from '../../internal/environment';
5
+ import {
6
+ resolveLocalizedString,
7
+ type LocalizedStringKey
8
+ } from '../../internal/localized-strings';
9
+ import { getLocaleContext } from '../../locale-provider/context';
10
+ import type { ColorPickerRootProps } from '../types';
11
+ import {
12
+ setColorPickerContext,
13
+ type ColorPickerChangeDetails,
14
+ type ColorPickerContext
15
+ } from './context';
16
+ import {
17
+ BLACK,
18
+ COLOR_CHANNEL_RANGES,
19
+ clampColor,
20
+ colorsAreEqual,
21
+ formatColor,
22
+ getColorChannel,
23
+ getRoundedChannel,
24
+ parseColor,
25
+ toCssColor,
26
+ withColorChannel,
27
+ type Color,
28
+ type ColorChannel
29
+ } from './color';
30
+
31
+ /**
32
+ * ColorPicker.Root — the color, and the context of each control.
33
+ *
34
+ * The color is held as hue, saturation and brightness: the square of `ColorPicker.Area` keeps
35
+ * its shape at each hue in that model, and it does not in red-green-blue. The value that goes
36
+ * out is text, in the format of `format`. A color without a hue, black or a gray, keeps the
37
+ * hue it had, thus a thumb in the square does not jump back to the corner.
38
+ */
39
+ const generatedId = $props.id();
40
+
41
+ let {
42
+ id: idProp,
43
+ value = $bindable(),
44
+ defaultValue,
45
+ controlledValue = false,
46
+ onChange,
47
+ onChangeEnd,
48
+ format = 'hex',
49
+ alpha = false,
50
+ disabled = false,
51
+ readonly = false,
52
+ invalid = false,
53
+ name,
54
+ form,
55
+ 'aria-label': ariaLabel,
56
+ 'aria-labelledby': ariaLabelledBy,
57
+ 'aria-describedby': ariaDescribedBy,
58
+ children,
59
+ class: className = '',
60
+ element = $bindable<HTMLDivElement | null>(null),
61
+ context = $bindable(),
62
+ style,
63
+ ...restProps
64
+ }: ColorPickerRootProps = $props();
65
+
66
+ const localeStore = getLocaleContext()?.locale ?? readable<string | undefined>(undefined);
67
+
68
+ const instanceId = untrack(() => idProp) ?? generatedId;
69
+ const rootId = `color-picker-${instanceId}`;
70
+
71
+ let rootRef: HTMLDivElement | null = $state(null);
72
+ let hiddenInputRef: HTMLInputElement | null = $state(null);
73
+ let labelId: string | null = $state(null);
74
+
75
+ const resolvedLocale = $derived($localeStore);
76
+
77
+ $effect(() => {
78
+ element = rootRef;
79
+ });
80
+
81
+ // Read one time: the component writes the value back, thus a check that follows the value
82
+ // would report the echo of its own write.
83
+ if (dev && untrack(() => value !== undefined && defaultValue !== undefined)) {
84
+ console.warn(
85
+ '[ColorPicker]: Both "value" and "defaultValue" are provided. ' +
86
+ 'Use "value" for controlled mode or "defaultValue" for uncontrolled mode, not both.'
87
+ );
88
+ }
89
+
90
+ // --- Color --------------------------------------------------------------------------------
91
+
92
+ const initialColor =
93
+ parseColor(untrack(() => value) ?? untrack(() => defaultValue) ?? '') ?? BLACK;
94
+ let colorInternal = $state<Color>(initialColor);
95
+
96
+ // The text that goes out last. A `bind:value` sends it back, and a hue of 360, a black and a
97
+ // gray do not survive the way out and back: the color that made the text is the true one.
98
+ let lastText = untrack(() => formatColor(initialColor, format, alpha));
99
+
100
+ // The text of the value is not a color: two texts of the same color are the same color, and
101
+ // a text that names no color leaves the one that is there. Thus the color of the prop is
102
+ // read, and the hue of a black kept, instead of a replacement of the state on each write.
103
+ const controlled = $derived(controlledValue || value !== undefined);
104
+ const currentColor = $derived.by(() => {
105
+ if (!controlled) return colorInternal;
106
+ if (value === lastText) return colorInternal;
107
+ const parsed = parseColor(value ?? '');
108
+ if (!parsed) return colorInternal;
109
+ if (colorsAreEqual(parsed, colorInternal)) return colorInternal;
110
+ // A text of a black or a gray says nothing about the hue: the one on the screen stays.
111
+ return parsed.s === 0 || parsed.b === 0
112
+ ? {
113
+ ...parsed,
114
+ h: parsed.h || colorInternal.h,
115
+ s: parsed.b === 0 ? colorInternal.s : parsed.s
116
+ }
117
+ : parsed;
118
+ });
119
+
120
+ const text = $derived(formatColor(currentColor, format, alpha));
121
+ const cssColor = $derived(toCssColor(currentColor));
122
+ const hueColor = $derived(toCssColor({ h: currentColor.h, s: 100, b: 100, a: 1 }));
123
+
124
+ // A `bind:value` that starts undefined gets the value at mount, thus the parent reads the
125
+ // default without a first change.
126
+ $effect(() => {
127
+ if (controlledValue) return;
128
+ untrack(() => {
129
+ if (value === undefined) value = text;
130
+ });
131
+ });
132
+
133
+ // A change of `format` or of `alpha` is a change of the text, and of nothing else. The value
134
+ // goes out again, thus the parent does not hold the text of the format that is gone.
135
+ $effect(() => {
136
+ const next = text;
137
+ if (controlledValue || next === lastText) return;
138
+ untrack(() => {
139
+ lastText = next;
140
+ value = next;
141
+ });
142
+ });
143
+
144
+ function setColor(next: Color, details: ColorPickerChangeDetails): boolean {
145
+ if (disabled || readonly) return false;
146
+ const clamped = clampColor(next);
147
+ if (colorsAreEqual(clamped, currentColor)) return false;
148
+ const nextText = formatColor(clamped, format, alpha);
149
+ colorInternal = clamped;
150
+ lastText = nextText;
151
+ if (!controlledValue) value = nextText;
152
+ onChange?.(nextText, details);
153
+ return true;
154
+ }
155
+
156
+ function setChannel(
157
+ channel: ColorChannel,
158
+ channelValue: number,
159
+ details: ColorPickerChangeDetails
160
+ ): boolean {
161
+ return setColor(withColorChannel(currentColor, channel, channelValue), {
162
+ ...details,
163
+ channel
164
+ });
165
+ }
166
+
167
+ function stepChannel(
168
+ channel: ColorChannel,
169
+ direction: -1 | 1,
170
+ options: { large?: boolean; event?: Event }
171
+ ): boolean {
172
+ const range = COLOR_CHANNEL_RANGES[channel];
173
+ const step = options.large ? range.largeStep : range.step;
174
+ const current = getColorChannel(currentColor, channel);
175
+ let next = current + direction * step;
176
+ // The hue is a circle: one step past the end is one step past the start.
177
+ if (channel === 'hue') next = next < 0 ? next + 360 : next > 360 ? next - 360 : next;
178
+ return setChannel(channel, next, { reason: 'keyboard', event: options.event });
179
+ }
180
+
181
+ function setText(nextText: string, details: ColorPickerChangeDetails): boolean {
182
+ const parsed = parseColor(nextText);
183
+ if (!parsed) return false;
184
+ // A text without an alpha in a picker that holds one keeps the alpha that is there.
185
+ const next =
186
+ alpha && !/^(#([\da-f]{4}|[\da-f]{8})|rgba|hsla|hsba|hsva)/i.test(nextText.trim())
187
+ ? { ...parsed, a: currentColor.a }
188
+ : parsed;
189
+ setColor(next, details);
190
+ return true;
191
+ }
192
+
193
+ function commit(details: ColorPickerChangeDetails) {
194
+ onChangeEnd?.(text, details);
195
+ }
196
+
197
+ // --- Form reset ---------------------------------------------------------------------------
198
+
199
+ $effect(() => {
200
+ const formElement = hiddenInputRef?.form;
201
+ if (!formElement) return;
202
+
203
+ const handleFormReset = () => {
204
+ // The browser resets the native inputs after the `reset` event; re-sync afterwards.
205
+ queueMicrotask(() => {
206
+ if (colorsAreEqual(currentColor, initialColor)) return;
207
+ colorInternal = initialColor;
208
+ const initialText = formatColor(initialColor, format, alpha);
209
+ lastText = initialText;
210
+ if (!controlledValue) value = initialText;
211
+ onChange?.(initialText, { reason: 'form-reset' });
212
+ });
213
+ };
214
+
215
+ formElement.addEventListener('reset', handleFormReset);
216
+ return () => formElement.removeEventListener('reset', handleFormReset);
217
+ });
218
+
219
+ // --- Text of the channels -------------------------------------------------------------------
220
+
221
+ const CHANNEL_KEYS: Record<ColorChannel, LocalizedStringKey> = {
222
+ hue: 'colorPicker.hue',
223
+ saturation: 'colorPicker.saturation',
224
+ brightness: 'colorPicker.brightness',
225
+ lightness: 'colorPicker.lightness',
226
+ alpha: 'colorPicker.alpha',
227
+ red: 'colorPicker.red',
228
+ green: 'colorPicker.green',
229
+ blue: 'colorPicker.blue'
230
+ };
231
+
232
+ function channelLabel(channel: ColorChannel): string {
233
+ return resolveLocalizedString(resolvedLocale, CHANNEL_KEYS[channel]);
234
+ }
235
+
236
+ function channelValueText(channel: ColorChannel): string {
237
+ const channelValue = getRoundedChannel(currentColor, channel);
238
+ if (channel === 'hue') return `${channelValue}°`;
239
+ if (channel === 'alpha') return `${Math.round(channelValue * 100)}%`;
240
+ if (channel === 'red' || channel === 'green' || channel === 'blue') return String(channelValue);
241
+ return `${channelValue}%`;
242
+ }
243
+
244
+ function channelPercent(channel: ColorChannel): number {
245
+ const range = COLOR_CHANNEL_RANGES[channel];
246
+ const channelValue = getColorChannel(currentColor, channel);
247
+ // The percent goes into the CSS: a number with the noise of the binary fractions in it is a
248
+ // value of a custom property that reads as broken.
249
+ return Math.round(((channelValue - range.min) / (range.max - range.min)) * 10000) / 100;
250
+ }
251
+
252
+ // --- Context ------------------------------------------------------------------------------
253
+
254
+ const pickerContext: ColorPickerContext = {
255
+ instanceId,
256
+ rootId,
257
+ get labelId() {
258
+ return labelId;
259
+ },
260
+ get color() {
261
+ return currentColor;
262
+ },
263
+ get text() {
264
+ return text;
265
+ },
266
+ get cssColor() {
267
+ return cssColor;
268
+ },
269
+ get hueColor() {
270
+ return hueColor;
271
+ },
272
+ get format() {
273
+ return format;
274
+ },
275
+ get hasAlpha() {
276
+ return alpha;
277
+ },
278
+ get isDisabled() {
279
+ return disabled;
280
+ },
281
+ get isReadOnly() {
282
+ return readonly;
283
+ },
284
+ get isInvalid() {
285
+ return invalid;
286
+ },
287
+ get ariaLabel() {
288
+ return ariaLabel;
289
+ },
290
+ get ariaLabelledBy() {
291
+ return ariaLabelledBy;
292
+ },
293
+ get ariaDescribedBy() {
294
+ return ariaDescribedBy;
295
+ },
296
+ registerLabel(id) {
297
+ labelId = id;
298
+ return () => {
299
+ if (labelId === id) labelId = null;
300
+ };
301
+ },
302
+ getPartId(part) {
303
+ return `${rootId}-${part}`;
304
+ },
305
+ getChannelRange(channel) {
306
+ return COLOR_CHANNEL_RANGES[channel];
307
+ },
308
+ getChannelValue(channel) {
309
+ return getRoundedChannel(currentColor, channel);
310
+ },
311
+ getChannelPercent: channelPercent,
312
+ getChannelLabel: channelLabel,
313
+ getChannelValueText: channelValueText,
314
+ getChannelColor(channel, channelValue) {
315
+ return toCssColor(withColorChannel(currentColor, channel, channelValue));
316
+ },
317
+ setChannel,
318
+ stepChannel,
319
+ setColor,
320
+ setText,
321
+ commit
322
+ };
323
+
324
+ setColorPickerContext(pickerContext);
325
+ context = pickerContext;
326
+
327
+ const defaultLabel = $derived(resolveLocalizedString(resolvedLocale, 'colorPicker.label'));
328
+ const labelledBy = $derived(ariaLabelledBy ?? labelId ?? undefined);
329
+ const inlineStyle = $derived(
330
+ `--color-picker-value: ${cssColor}; --color-picker-hue: ${Math.round(currentColor.h)};` +
331
+ ` --color-picker-hue-color: ${hueColor}; --color-picker-alpha: ${currentColor.a};` +
332
+ `${style ? ` ${style}` : ''}`
333
+ );
334
+ </script>
335
+
336
+ <div
337
+ {...restProps}
338
+ bind:this={rootRef}
339
+ id={rootId}
340
+ role="group"
341
+ aria-labelledby={labelledBy}
342
+ aria-label={labelledBy ? undefined : (ariaLabel ?? defaultLabel)}
343
+ aria-describedby={ariaDescribedBy}
344
+ aria-disabled={disabled || undefined}
345
+ class={className}
346
+ style={inlineStyle}
347
+ data-color-picker-root="true"
348
+ data-format={format}
349
+ data-alpha={alpha || undefined}
350
+ data-disabled={disabled || undefined}
351
+ data-readonly={readonly || undefined}
352
+ data-invalid={invalid || undefined}
353
+ >
354
+ {#if name}
355
+ <input
356
+ bind:this={hiddenInputRef}
357
+ type="hidden"
358
+ {name}
359
+ {form}
360
+ value={text}
361
+ data-color-picker-value="true"
362
+ />
363
+ {/if}
364
+ {@render children?.()}
365
+ </div>
@@ -0,0 +1,4 @@
1
+ import type { ColorPickerRootProps } from '../types';
2
+ declare const ColorPickerRoot: import("svelte").Component<ColorPickerRootProps, {}, "value" | "element" | "context">;
3
+ type ColorPickerRoot = ReturnType<typeof ColorPickerRoot>;
4
+ export default ColorPickerRoot;
@@ -0,0 +1,68 @@
1
+ /**
2
+ * The color math of the picker.
3
+ *
4
+ * The color is held as hue, saturation and brightness, with an alpha. That is the model the
5
+ * square and the hue slider move in: a square of saturation against brightness keeps its shape
6
+ * at each hue, and red-green-blue does not. Each other model is a conversion of this one.
7
+ */
8
+ /** The channels a slider or a field can move. */
9
+ export type ColorChannel = 'hue' | 'saturation' | 'brightness' | 'lightness' | 'alpha' | 'red' | 'green' | 'blue';
10
+ /** The text format of the value. */
11
+ export type ColorFormat = 'hex' | 'rgb' | 'hsl' | 'hsb';
12
+ /** Hue from 0 to 360, saturation and brightness from 0 to 100, alpha from 0 to 1. */
13
+ export type Color = {
14
+ h: number;
15
+ s: number;
16
+ b: number;
17
+ a: number;
18
+ };
19
+ export type ColorChannelRange = {
20
+ min: number;
21
+ max: number;
22
+ step: number;
23
+ /** The step of `PageUp`, `PageDown` and `Shift` with an arrow. */
24
+ largeStep: number;
25
+ };
26
+ export declare const COLOR_CHANNEL_RANGES: Record<ColorChannel, ColorChannelRange>;
27
+ export declare const BLACK: Color;
28
+ /**
29
+ * The hue is a circle, thus each hue past the end comes back to the start. 360 is the one value
30
+ * that stays: it is the end of the track of a hue slider, and the color there is the color at 0.
31
+ */
32
+ export declare function normalizeHue(hue: number): number;
33
+ export declare function clampColor(color: Color): Color;
34
+ export declare function colorsAreEqual(a: Color, b: Color): boolean;
35
+ export type Rgb = {
36
+ r: number;
37
+ g: number;
38
+ b: number;
39
+ };
40
+ export declare function hsbToRgb(color: Color): Rgb;
41
+ export declare function rgbToHsb(rgb: Rgb, alpha?: number): Color;
42
+ export type Hsl = {
43
+ h: number;
44
+ s: number;
45
+ l: number;
46
+ };
47
+ export declare function hsbToHsl(color: Color): Hsl;
48
+ export declare function hslToHsb(hsl: Hsl, alpha?: number): Color;
49
+ export declare function getColorChannel(color: Color, channel: ColorChannel): number;
50
+ /**
51
+ * The color with one channel at a new value. A color without a hue, black or a gray, keeps the
52
+ * hue and the saturation it had: they are the position of the thumb in the square, and a thumb
53
+ * that goes back to the corner on each move is a thumb the user cannot aim.
54
+ */
55
+ export declare function withColorChannel(color: Color, channel: ColorChannel, value: number): Color;
56
+ /** Reads a text into a color. It answers null for a text that names no color. */
57
+ export declare function parseColor(text: string): Color | null;
58
+ /**
59
+ * The text of a color. With `alpha` off, the text holds only the three color channels: a picker
60
+ * without an alpha slider must not answer a fourth number nobody can change.
61
+ */
62
+ export declare function formatColor(color: Color, format: ColorFormat, alpha?: boolean): string;
63
+ /** The color as CSS, always with its alpha: it is what the parts paint with. */
64
+ export declare function toCssColor(color: Color): string;
65
+ /** The text of the hex field: six digits, or eight with an alpha. */
66
+ export declare function toHexText(color: Color, alpha?: boolean): string;
67
+ /** The value of one channel, rounded as the field and the screen reader show it. */
68
+ export declare function getRoundedChannel(color: Color, channel: ColorChannel): number;
@@ -0,0 +1,266 @@
1
+ /**
2
+ * The color math of the picker.
3
+ *
4
+ * The color is held as hue, saturation and brightness, with an alpha. That is the model the
5
+ * square and the hue slider move in: a square of saturation against brightness keeps its shape
6
+ * at each hue, and red-green-blue does not. Each other model is a conversion of this one.
7
+ */
8
+ export const COLOR_CHANNEL_RANGES = {
9
+ hue: { min: 0, max: 360, step: 1, largeStep: 15 },
10
+ saturation: { min: 0, max: 100, step: 1, largeStep: 10 },
11
+ brightness: { min: 0, max: 100, step: 1, largeStep: 10 },
12
+ lightness: { min: 0, max: 100, step: 1, largeStep: 10 },
13
+ alpha: { min: 0, max: 1, step: 0.01, largeStep: 0.1 },
14
+ red: { min: 0, max: 255, step: 1, largeStep: 16 },
15
+ green: { min: 0, max: 255, step: 1, largeStep: 16 },
16
+ blue: { min: 0, max: 255, step: 1, largeStep: 16 }
17
+ };
18
+ export const BLACK = { h: 0, s: 0, b: 0, a: 1 };
19
+ function clamp(value, min, max) {
20
+ return Math.min(Math.max(value, min), max);
21
+ }
22
+ function round(value, decimals = 0) {
23
+ const factor = 10 ** decimals;
24
+ return Math.round(value * factor) / factor;
25
+ }
26
+ /**
27
+ * The hue is a circle, thus each hue past the end comes back to the start. 360 is the one value
28
+ * that stays: it is the end of the track of a hue slider, and the color there is the color at 0.
29
+ */
30
+ export function normalizeHue(hue) {
31
+ if (!Number.isFinite(hue))
32
+ return 0;
33
+ if (hue === 360)
34
+ return 360;
35
+ return ((hue % 360) + 360) % 360;
36
+ }
37
+ export function clampColor(color) {
38
+ return {
39
+ h: normalizeHue(color.h),
40
+ s: clamp(color.s, 0, 100),
41
+ b: clamp(color.b, 0, 100),
42
+ a: clamp(color.a, 0, 1)
43
+ };
44
+ }
45
+ export function colorsAreEqual(a, b) {
46
+ return (round(a.h, 2) === round(b.h, 2) &&
47
+ round(a.s, 2) === round(b.s, 2) &&
48
+ round(a.b, 2) === round(b.b, 2) &&
49
+ round(a.a, 3) === round(b.a, 3));
50
+ }
51
+ export function hsbToRgb(color) {
52
+ const h = (((color.h % 360) + 360) % 360) / 60;
53
+ const s = clamp(color.s, 0, 100) / 100;
54
+ const v = clamp(color.b, 0, 100) / 100;
55
+ const chroma = v * s;
56
+ const second = chroma * (1 - Math.abs((h % 2) - 1));
57
+ const match = v - chroma;
58
+ let rgb;
59
+ if (h < 1)
60
+ rgb = [chroma, second, 0];
61
+ else if (h < 2)
62
+ rgb = [second, chroma, 0];
63
+ else if (h < 3)
64
+ rgb = [0, chroma, second];
65
+ else if (h < 4)
66
+ rgb = [0, second, chroma];
67
+ else if (h < 5)
68
+ rgb = [second, 0, chroma];
69
+ else
70
+ rgb = [chroma, 0, second];
71
+ return {
72
+ r: Math.round((rgb[0] + match) * 255),
73
+ g: Math.round((rgb[1] + match) * 255),
74
+ b: Math.round((rgb[2] + match) * 255)
75
+ };
76
+ }
77
+ export function rgbToHsb(rgb, alpha = 1) {
78
+ const r = clamp(rgb.r, 0, 255) / 255;
79
+ const g = clamp(rgb.g, 0, 255) / 255;
80
+ const b = clamp(rgb.b, 0, 255) / 255;
81
+ const max = Math.max(r, g, b);
82
+ const min = Math.min(r, g, b);
83
+ const chroma = max - min;
84
+ let hue = 0;
85
+ if (chroma !== 0) {
86
+ if (max === r)
87
+ hue = ((g - b) / chroma) % 6;
88
+ else if (max === g)
89
+ hue = (b - r) / chroma + 2;
90
+ else
91
+ hue = (r - g) / chroma + 4;
92
+ hue *= 60;
93
+ if (hue < 0)
94
+ hue += 360;
95
+ }
96
+ return {
97
+ h: hue,
98
+ s: max === 0 ? 0 : (chroma / max) * 100,
99
+ b: max * 100,
100
+ a: clamp(alpha, 0, 1)
101
+ };
102
+ }
103
+ export function hsbToHsl(color) {
104
+ const s = clamp(color.s, 0, 100) / 100;
105
+ const v = clamp(color.b, 0, 100) / 100;
106
+ const l = v * (1 - s / 2);
107
+ const saturation = l === 0 || l === 1 ? 0 : (v - l) / Math.min(l, 1 - l);
108
+ return { h: normalizeHue(color.h), s: saturation * 100, l: l * 100 };
109
+ }
110
+ export function hslToHsb(hsl, alpha = 1) {
111
+ const s = clamp(hsl.s, 0, 100) / 100;
112
+ const l = clamp(hsl.l, 0, 100) / 100;
113
+ const v = l + s * Math.min(l, 1 - l);
114
+ return {
115
+ h: normalizeHue(hsl.h),
116
+ s: (v === 0 ? 0 : 2 * (1 - l / v)) * 100,
117
+ b: v * 100,
118
+ a: clamp(alpha, 0, 1)
119
+ };
120
+ }
121
+ // --- Channels ---------------------------------------------------------------------------------
122
+ export function getColorChannel(color, channel) {
123
+ switch (channel) {
124
+ case 'hue':
125
+ return color.h;
126
+ case 'saturation':
127
+ return color.s;
128
+ case 'brightness':
129
+ return color.b;
130
+ case 'alpha':
131
+ return color.a;
132
+ case 'lightness':
133
+ return hsbToHsl(color).l;
134
+ case 'red':
135
+ return hsbToRgb(color).r;
136
+ case 'green':
137
+ return hsbToRgb(color).g;
138
+ case 'blue':
139
+ return hsbToRgb(color).b;
140
+ }
141
+ }
142
+ /**
143
+ * The color with one channel at a new value. A color without a hue, black or a gray, keeps the
144
+ * hue and the saturation it had: they are the position of the thumb in the square, and a thumb
145
+ * that goes back to the corner on each move is a thumb the user cannot aim.
146
+ */
147
+ export function withColorChannel(color, channel, value) {
148
+ const range = COLOR_CHANNEL_RANGES[channel];
149
+ const next = clamp(value, range.min, range.max);
150
+ switch (channel) {
151
+ case 'hue':
152
+ return { ...color, h: normalizeHue(next) };
153
+ case 'saturation':
154
+ return { ...color, s: next };
155
+ case 'brightness':
156
+ return { ...color, b: next };
157
+ case 'alpha':
158
+ return { ...color, a: next };
159
+ case 'lightness': {
160
+ const hsl = hsbToHsl(color);
161
+ return keepPosition(hslToHsb({ ...hsl, l: next }, color.a), color);
162
+ }
163
+ default: {
164
+ const rgb = hsbToRgb(color);
165
+ const key = channel === 'red' ? 'r' : channel === 'green' ? 'g' : 'b';
166
+ return keepPosition(rgbToHsb({ ...rgb, [key]: next }, color.a), color);
167
+ }
168
+ }
169
+ }
170
+ /** Keeps the hue, and the saturation, of a color that no longer says what they are. */
171
+ function keepPosition(next, previous) {
172
+ const color = { ...next };
173
+ if (color.b === 0 || color.s === 0)
174
+ color.h = previous.h;
175
+ if (color.b === 0)
176
+ color.s = previous.s;
177
+ return color;
178
+ }
179
+ // --- Text -------------------------------------------------------------------------------------
180
+ const HEX = /^#?([\da-f]{3,8})$/i;
181
+ const FUNCTIONAL = /^(rgba?|hsla?|hsba?|hsva?)\(([^)]+)\)$/i;
182
+ function parseNumbers(body) {
183
+ return body
184
+ .split(/[\s,/]+/)
185
+ .map((part) => part.trim())
186
+ .filter(Boolean)
187
+ .map((part) => (part.endsWith('%') ? Number(part.slice(0, -1)) : Number(part)));
188
+ }
189
+ /** Reads a text into a color. It answers null for a text that names no color. */
190
+ export function parseColor(text) {
191
+ const value = text.trim();
192
+ if (!value)
193
+ return null;
194
+ const hex = HEX.exec(value);
195
+ if (hex) {
196
+ const digits = hex[1];
197
+ if (digits.length === 3 || digits.length === 4) {
198
+ const parts = digits.split('').map((digit) => Number.parseInt(digit + digit, 16));
199
+ return rgbToHsb({ r: parts[0], g: parts[1], b: parts[2] }, parts[3] === undefined ? 1 : parts[3] / 255);
200
+ }
201
+ if (digits.length === 6 || digits.length === 8) {
202
+ const parts = (digits.match(/.{2}/g) ?? []).map((pair) => Number.parseInt(pair, 16));
203
+ return rgbToHsb({ r: parts[0], g: parts[1], b: parts[2] }, parts[3] === undefined ? 1 : parts[3] / 255);
204
+ }
205
+ return null;
206
+ }
207
+ const functional = FUNCTIONAL.exec(value);
208
+ if (!functional)
209
+ return null;
210
+ const name = functional[1].toLowerCase();
211
+ const numbers = parseNumbers(functional[2]);
212
+ if (numbers.length < 3 || numbers.some((number) => Number.isNaN(number)))
213
+ return null;
214
+ const alpha = numbers[3] === undefined ? 1 : clamp(numbers[3], 0, 1);
215
+ if (name.startsWith('rgb')) {
216
+ return rgbToHsb({ r: numbers[0], g: numbers[1], b: numbers[2] }, alpha);
217
+ }
218
+ if (name.startsWith('hsl')) {
219
+ return hslToHsb({ h: numbers[0], s: numbers[1], l: numbers[2] }, alpha);
220
+ }
221
+ return clampColor({ h: numbers[0], s: numbers[1], b: numbers[2], a: alpha });
222
+ }
223
+ function toHexPair(value) {
224
+ return Math.round(clamp(value, 0, 255))
225
+ .toString(16)
226
+ .padStart(2, '0');
227
+ }
228
+ /**
229
+ * The text of a color. With `alpha` off, the text holds only the three color channels: a picker
230
+ * without an alpha slider must not answer a fourth number nobody can change.
231
+ */
232
+ export function formatColor(color, format, alpha = false) {
233
+ const withAlpha = alpha && color.a < 1;
234
+ if (format === 'hex') {
235
+ const rgb = hsbToRgb(color);
236
+ const base = `#${toHexPair(rgb.r)}${toHexPair(rgb.g)}${toHexPair(rgb.b)}`;
237
+ return withAlpha ? `${base}${toHexPair(color.a * 255)}` : base;
238
+ }
239
+ if (format === 'rgb') {
240
+ const rgb = hsbToRgb(color);
241
+ return withAlpha
242
+ ? `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, ${round(color.a, 2)})`
243
+ : `rgb(${rgb.r}, ${rgb.g}, ${rgb.b})`;
244
+ }
245
+ if (format === 'hsl') {
246
+ const hsl = hsbToHsl(color);
247
+ const base = `${round(hsl.h)}, ${round(hsl.s)}%, ${round(hsl.l)}%`;
248
+ return withAlpha ? `hsla(${base}, ${round(color.a, 2)})` : `hsl(${base})`;
249
+ }
250
+ const base = `${round(color.h)}, ${round(color.s)}%, ${round(color.b)}%`;
251
+ return withAlpha ? `hsba(${base}, ${round(color.a, 2)})` : `hsb(${base})`;
252
+ }
253
+ /** The color as CSS, always with its alpha: it is what the parts paint with. */
254
+ export function toCssColor(color) {
255
+ const rgb = hsbToRgb(color);
256
+ return `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, ${round(color.a, 3)})`;
257
+ }
258
+ /** The text of the hex field: six digits, or eight with an alpha. */
259
+ export function toHexText(color, alpha = false) {
260
+ return formatColor(color, 'hex', alpha);
261
+ }
262
+ /** The value of one channel, rounded as the field and the screen reader show it. */
263
+ export function getRoundedChannel(color, channel) {
264
+ const value = getColorChannel(color, channel);
265
+ return channel === 'alpha' ? round(value, 2) : Math.round(value);
266
+ }