@open-artifact/ui 0.0.0-stage → 0.2.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 (48) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +5 -0
  3. package/README.md +5 -2
  4. package/package.json +48 -4
  5. package/src/button.d.ts +30 -0
  6. package/src/button.js +28 -0
  7. package/src/cn.d.ts +3 -0
  8. package/src/cn.js +5 -0
  9. package/src/color-picker.d.ts +98 -0
  10. package/src/color-picker.js +370 -0
  11. package/src/color.d.ts +144 -0
  12. package/src/color.js +528 -0
  13. package/src/data/google-fonts.json +1775 -0
  14. package/src/effect-editors.d.ts +48 -0
  15. package/src/effect-editors.js +230 -0
  16. package/src/effects.d.ts +118 -0
  17. package/src/effects.js +425 -0
  18. package/src/fields.d.ts +105 -0
  19. package/src/fields.js +77 -0
  20. package/src/focusables.d.ts +26 -0
  21. package/src/focusables.js +42 -0
  22. package/src/font-picker.d.ts +62 -0
  23. package/src/font-picker.js +238 -0
  24. package/src/fonts.d.ts +121 -0
  25. package/src/fonts.js +273 -0
  26. package/src/history-diff.d.ts +64 -0
  27. package/src/history-diff.js +151 -0
  28. package/src/history.d.ts +95 -0
  29. package/src/history.js +160 -0
  30. package/src/index.d.ts +25 -0
  31. package/src/index.js +25 -0
  32. package/src/keys.d.ts +60 -0
  33. package/src/keys.js +78 -0
  34. package/src/layout.d.ts +55 -0
  35. package/src/layout.js +64 -0
  36. package/src/menu.d.ts +50 -0
  37. package/src/menu.js +36 -0
  38. package/src/numbers.d.ts +24 -0
  39. package/src/numbers.js +114 -0
  40. package/src/overlays.d.ts +38 -0
  41. package/src/overlays.js +26 -0
  42. package/src/scroll.d.ts +24 -0
  43. package/src/scroll.js +111 -0
  44. package/src/scrub-number-field.d.ts +56 -0
  45. package/src/scrub-number-field.js +190 -0
  46. package/src/styles.css +122 -0
  47. package/src/tooltip.d.ts +18 -0
  48. package/src/tooltip.js +10 -0
package/src/color.js ADDED
@@ -0,0 +1,528 @@
1
+ /**
2
+ * Color math for the editors' color controls, with no DOM: parsing and
3
+ * formatting CSS colors (hex, `rgb()`/`rgba()`, `hsl()`/`hsla()`,
4
+ * `oklch()`, named colors), conversion to and from HSV, HSL and OKLCH, and
5
+ * WCAG 2 contrast.
6
+ *
7
+ * Channels: {@link Rgba} holds sRGB `r`, `g`, `b` in 0–255 (fractions kept)
8
+ * and alpha in 0–1. Hue is in degrees everywhere.
9
+ */
10
+ /* --------------------------------- named ---------------------------------- */
11
+ /** The CSS named colors (lowercase name → `#rrggbb`). */
12
+ export const NAMED_COLORS = {
13
+ aliceblue: '#f0f8ff', antiquewhite: '#faebd7', aqua: '#00ffff', aquamarine: '#7fffd4', azure: '#f0ffff',
14
+ beige: '#f5f5dc', bisque: '#ffe4c4', black: '#000000', blanchedalmond: '#ffebcd', blue: '#0000ff',
15
+ blueviolet: '#8a2be2', brown: '#a52a2a', burlywood: '#deb887', cadetblue: '#5f9ea0', chartreuse: '#7fff00',
16
+ chocolate: '#d2691e', coral: '#ff7f50', cornflowerblue: '#6495ed', cornsilk: '#fff8dc', crimson: '#dc143c',
17
+ cyan: '#00ffff', darkblue: '#00008b', darkcyan: '#008b8b', darkgoldenrod: '#b8860b', darkgray: '#a9a9a9',
18
+ darkgreen: '#006400', darkgrey: '#a9a9a9', darkkhaki: '#bdb76b', darkmagenta: '#8b008b', darkolivegreen: '#556b2f',
19
+ darkorange: '#ff8c00', darkorchid: '#9932cc', darkred: '#8b0000', darksalmon: '#e9967a', darkseagreen: '#8fbc8f',
20
+ darkslateblue: '#483d8b', darkslategray: '#2f4f4f', darkslategrey: '#2f4f4f', darkturquoise: '#00ced1', darkviolet: '#9400d3',
21
+ deeppink: '#ff1493', deepskyblue: '#00bfff', dimgray: '#696969', dimgrey: '#696969', dodgerblue: '#1e90ff',
22
+ firebrick: '#b22222', floralwhite: '#fffaf0', forestgreen: '#228b22', fuchsia: '#ff00ff', gainsboro: '#dcdcdc',
23
+ ghostwhite: '#f8f8ff', gold: '#ffd700', goldenrod: '#daa520', gray: '#808080', green: '#008000',
24
+ greenyellow: '#adff2f', grey: '#808080', honeydew: '#f0fff0', hotpink: '#ff69b4', indianred: '#cd5c5c',
25
+ indigo: '#4b0082', ivory: '#fffff0', khaki: '#f0e68c', lavender: '#e6e6fa', lavenderblush: '#fff0f5',
26
+ lawngreen: '#7cfc00', lemonchiffon: '#fffacd', lightblue: '#add8e6', lightcoral: '#f08080', lightcyan: '#e0ffff',
27
+ lightgoldenrodyellow: '#fafad2', lightgray: '#d3d3d3', lightgreen: '#90ee90', lightgrey: '#d3d3d3', lightpink: '#ffb6c1',
28
+ lightsalmon: '#ffa07a', lightseagreen: '#20b2aa', lightskyblue: '#87cefa', lightslategray: '#778899', lightslategrey: '#778899',
29
+ lightsteelblue: '#b0c4de', lightyellow: '#ffffe0', lime: '#00ff00', limegreen: '#32cd32', linen: '#faf0e6',
30
+ magenta: '#ff00ff', maroon: '#800000', mediumaquamarine: '#66cdaa', mediumblue: '#0000cd', mediumorchid: '#ba55d3',
31
+ mediumpurple: '#9370db', mediumseagreen: '#3cb371', mediumslateblue: '#7b68ee', mediumspringgreen: '#00fa9a', mediumturquoise: '#48d1cc',
32
+ mediumvioletred: '#c71585', midnightblue: '#191970', mintcream: '#f5fffa', mistyrose: '#ffe4e1', moccasin: '#ffe4b5',
33
+ navajowhite: '#ffdead', navy: '#000080', oldlace: '#fdf5e6', olive: '#808000', olivedrab: '#6b8e23',
34
+ orange: '#ffa500', orangered: '#ff4500', orchid: '#da70d6', palegoldenrod: '#eee8aa', palegreen: '#98fb98',
35
+ paleturquoise: '#afeeee', palevioletred: '#db7093', papayawhip: '#ffefd5', peachpuff: '#ffdab9', peru: '#cd853f',
36
+ pink: '#ffc0cb', plum: '#dda0dd', powderblue: '#b0e0e6', purple: '#800080', rebeccapurple: '#663399',
37
+ red: '#ff0000', rosybrown: '#bc8f8f', royalblue: '#4169e1', saddlebrown: '#8b4513', salmon: '#fa8072',
38
+ sandybrown: '#f4a460', seagreen: '#2e8b57', seashell: '#fff5ee', sienna: '#a0522d', silver: '#c0c0c0',
39
+ skyblue: '#87ceeb', slateblue: '#6a5acd', slategray: '#708090', slategrey: '#708090', snow: '#fffafa',
40
+ springgreen: '#00ff7f', steelblue: '#4682b4', tan: '#d2b48c', teal: '#008080', thistle: '#d8bfd8',
41
+ tomato: '#ff6347', turquoise: '#40e0d0', violet: '#ee82ee', wheat: '#f5deb3', white: '#ffffff',
42
+ whitesmoke: '#f5f5f5', yellow: '#ffff00', yellowgreen: '#9acd32',
43
+ };
44
+ /** The name of a color that is exactly a named color (opaque), else null. `transparent` for alpha 0. */
45
+ export function colorName(rgba) {
46
+ if (rgba.a === 0)
47
+ return 'transparent';
48
+ if (rgba.a < 1)
49
+ return null;
50
+ const hex = formatHex(rgba);
51
+ for (const [name, value] of Object.entries(NAMED_COLORS))
52
+ if (value === hex)
53
+ return name;
54
+ return null;
55
+ }
56
+ /* --------------------------------- helpers -------------------------------- */
57
+ const clamp = (value, min, max) => Math.min(max, Math.max(min, value));
58
+ /** Rounds to `digits` decimals, without `-0`. */
59
+ const round = (value, digits = 0) => {
60
+ const factor = 10 ** digits;
61
+ const out = Math.round(value * factor) / factor;
62
+ return Object.is(out, -0) ? 0 : out;
63
+ };
64
+ /** Hue into [0, 360). */
65
+ const wrapHue = (h) => (h >= 0 && h < 360 ? h : ((h % 360) + 360) % 360);
66
+ /** Clamps every channel into range (alpha too). */
67
+ export function clampRgba(rgba) {
68
+ return { r: clamp(rgba.r, 0, 255), g: clamp(rgba.g, 0, 255), b: clamp(rgba.b, 0, 255), a: clamp(rgba.a, 0, 1) };
69
+ }
70
+ const NUMBER = /^([+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?)(%|deg|grad|rad|turn)?$/i;
71
+ function token(text) {
72
+ if (text.toLowerCase() === 'none')
73
+ return { value: 0, unit: '' };
74
+ const match = NUMBER.exec(text);
75
+ return match ? { value: Number(match[1]), unit: (match[2] ?? '').toLowerCase() } : null;
76
+ }
77
+ /** Degrees of a hue token (bare numbers are degrees). */
78
+ function hueOf(t) {
79
+ switch (t.unit) {
80
+ case '':
81
+ case 'deg':
82
+ return t.value;
83
+ case 'grad':
84
+ return (t.value * 360) / 400;
85
+ case 'rad':
86
+ return (t.value * 180) / Math.PI;
87
+ case 'turn':
88
+ return t.value * 360;
89
+ default:
90
+ return null;
91
+ }
92
+ }
93
+ /** Alpha of a token: a number or a percentage. */
94
+ function alphaOf(t) {
95
+ if (!t)
96
+ return 1;
97
+ if (t.unit === '%')
98
+ return clamp(t.value / 100, 0, 1);
99
+ if (t.unit === '')
100
+ return clamp(t.value, 0, 1);
101
+ return null;
102
+ }
103
+ /**
104
+ * Splits the arguments of a color function. Returns the channel tokens, the
105
+ * alpha token and whether commas were used.
106
+ */
107
+ function splitArgs(body) {
108
+ const text = body.trim();
109
+ if (text.includes(',')) {
110
+ const parts = text.split(',').map((part) => part.trim());
111
+ if (parts.some((part) => !part || /\s/.test(part)) || parts.length < 3 || parts.length > 4)
112
+ return null;
113
+ return { channels: parts.slice(0, 3), alpha: parts[3], legacy: true };
114
+ }
115
+ const [main, alpha, ...rest] = text.split('/');
116
+ if (rest.length || main === undefined)
117
+ return null;
118
+ const channels = main.trim().split(/\s+/).filter(Boolean);
119
+ if (channels.length !== 3)
120
+ return null;
121
+ const a = alpha?.trim();
122
+ if (alpha !== undefined && !a)
123
+ return null;
124
+ return { channels, alpha: a, legacy: false };
125
+ }
126
+ function parseHex(text) {
127
+ const digits = text.slice(1);
128
+ if (!/^[0-9a-f]+$/i.test(digits) || ![3, 4, 6, 8].includes(digits.length))
129
+ return null;
130
+ const full = digits.length <= 4 ? [...digits].map((d) => d + d).join('') : digits;
131
+ const channel = (i) => Number.parseInt(full.slice(i * 2, i * 2 + 2), 16);
132
+ const rgba = { r: channel(0), g: channel(1), b: channel(2), a: full.length === 8 ? channel(3) / 255 : 1 };
133
+ const upper = /[A-F]/.test(digits) && !/[a-f]/.test(digits);
134
+ return { rgba, notation: { format: 'hex', upper, short: digits.length <= 4 } };
135
+ }
136
+ function parseRgb(name, body) {
137
+ const args = splitArgs(body);
138
+ if (!args)
139
+ return null;
140
+ const tokens = args.channels.map(token);
141
+ if (tokens.some((t) => t === null))
142
+ return null;
143
+ const units = new Set(tokens.map((t) => t.unit));
144
+ // Mixing numbers and percentages is allowed in modern syntax only.
145
+ if ([...units].some((u) => u !== '' && u !== '%') || (args.legacy && units.size > 1))
146
+ return null;
147
+ const [r, g, b] = tokens.map((t) => (t.unit === '%' ? (t.value * 255) / 100 : t.value));
148
+ const at = args.alpha === undefined ? undefined : token(args.alpha);
149
+ if (at === null)
150
+ return null;
151
+ const a = alphaOf(at);
152
+ if (a === null)
153
+ return null;
154
+ return {
155
+ rgba: clampRgba({ r, g, b, a }),
156
+ notation: { format: 'rgb', legacy: args.legacy, alphaName: args.legacy && name === 'rgba' },
157
+ };
158
+ }
159
+ function parseHsl(name, body) {
160
+ const args = splitArgs(body);
161
+ if (!args)
162
+ return null;
163
+ const [ht, st, lt] = args.channels.map(token);
164
+ if (!ht || !st || !lt)
165
+ return null;
166
+ const h = hueOf(ht);
167
+ if (h === null)
168
+ return null;
169
+ // Legacy syntax needs percentages; modern syntax also takes bare numbers (0–100).
170
+ if (args.legacy && (st.unit !== '%' || lt.unit !== '%'))
171
+ return null;
172
+ if ((st.unit !== '%' && st.unit !== '') || (lt.unit !== '%' && lt.unit !== ''))
173
+ return null;
174
+ const at = args.alpha === undefined ? undefined : token(args.alpha);
175
+ if (at === null)
176
+ return null;
177
+ const a = alphaOf(at);
178
+ if (a === null)
179
+ return null;
180
+ const hsla = { h, s: clamp(st.value / 100, 0, 1), l: clamp(lt.value / 100, 0, 1), a };
181
+ return {
182
+ rgba: hslaToRgba(hsla),
183
+ notation: { format: 'hsl', legacy: args.legacy, alphaName: args.legacy && name === 'hsla' },
184
+ };
185
+ }
186
+ function parseOklch(body) {
187
+ const args = splitArgs(body);
188
+ if (!args || args.legacy)
189
+ return null;
190
+ const [lt, ct, ht] = args.channels.map(token);
191
+ if (!lt || !ct || !ht)
192
+ return null;
193
+ if ((lt.unit !== '' && lt.unit !== '%') || (ct.unit !== '' && ct.unit !== '%'))
194
+ return null;
195
+ const h = hueOf(ht);
196
+ if (h === null)
197
+ return null;
198
+ const at = args.alpha === undefined ? undefined : token(args.alpha);
199
+ if (at === null)
200
+ return null;
201
+ const a = alphaOf(at);
202
+ if (a === null)
203
+ return null;
204
+ const oklch = {
205
+ l: clamp(lt.unit === '%' ? lt.value / 100 : lt.value, 0, 1),
206
+ // 100% chroma is 0.4.
207
+ c: Math.max(0, ct.unit === '%' ? (ct.value / 100) * 0.4 : ct.value),
208
+ h: wrapHue(h),
209
+ a,
210
+ };
211
+ return { rgba: oklchToRgba(oklch), notation: { format: 'oklch' }, oklch };
212
+ }
213
+ /**
214
+ * Parses a CSS color: `#rgb[a]`, `#rrggbb[aa]`, `rgb()`/`rgba()` (comma or
215
+ * space syntax, numbers or percentages), `hsl()`/`hsla()`, `oklch()`, a named
216
+ * color or `transparent`. Returns null for anything else (`var()`,
217
+ * `currentcolor`, `color-mix()`…).
218
+ */
219
+ export function parseColor(input) {
220
+ const text = input.trim();
221
+ if (!text)
222
+ return null;
223
+ const lower = text.toLowerCase();
224
+ if (text.startsWith('#'))
225
+ return parseHex(text);
226
+ if (lower === 'transparent')
227
+ return { rgba: { r: 0, g: 0, b: 0, a: 0 }, notation: { format: 'named' } };
228
+ const named = NAMED_COLORS[lower];
229
+ if (named)
230
+ return { ...parseHex(named), notation: { format: 'named' } };
231
+ const fn = /^([a-z]+)\(([^()]*)\)$/i.exec(text);
232
+ if (!fn)
233
+ return null;
234
+ const name = fn[1].toLowerCase();
235
+ const body = fn[2];
236
+ if (name === 'rgb' || name === 'rgba')
237
+ return parseRgb(name, body);
238
+ if (name === 'hsl' || name === 'hsla')
239
+ return parseHsl(name, body);
240
+ if (name === 'oklch')
241
+ return parseOklch(body);
242
+ return null;
243
+ }
244
+ /** The sRGB channels of a CSS color, or null when {@link parseColor} cannot read it. */
245
+ export function toRgba(input) {
246
+ return parseColor(input)?.rgba ?? null;
247
+ }
248
+ /** True when {@link parseColor} reads `input`. */
249
+ export function isColor(input) {
250
+ return parseColor(input) !== null;
251
+ }
252
+ /* -------------------------------- formatting ------------------------------ */
253
+ const hex2 = (n) => Math.round(clamp(n, 0, 255)).toString(16).padStart(2, '0');
254
+ /** `#rrggbb`, or `#rrggbbaa` when translucent. */
255
+ export function formatHex(rgba, options = {}) {
256
+ let digits = hex2(rgba.r) + hex2(rgba.g) + hex2(rgba.b);
257
+ const alpha = Math.round(clamp(rgba.a, 0, 1) * 255);
258
+ if (alpha < 255)
259
+ digits += hex2(alpha);
260
+ if (options.short && /^(?:([0-9a-f])\1)+$/.test(digits))
261
+ digits = digits.replace(/(.)\1/g, '$1');
262
+ return `#${options.upper ? digits.toUpperCase() : digits}`;
263
+ }
264
+ /** Alpha as written in a function: `0.5`, three decimals at most. */
265
+ const alphaText = (a) => String(round(clamp(a, 0, 1), 3));
266
+ /**
267
+ * Writes `rgba` in `format`. `notation` keeps the details of how the original
268
+ * was written (comma syntax, `rgba(`, hex case). For `oklch`, pass `oklch`
269
+ * to write exact channels instead of converting `rgba`.
270
+ */
271
+ export function formatColor(rgba, format, notation = {}, oklch) {
272
+ const c = clampRgba(rgba);
273
+ const translucent = c.a < 1;
274
+ switch (format) {
275
+ case 'hex':
276
+ return formatHex(c, notation);
277
+ case 'rgb': {
278
+ const [r, g, b] = [c.r, c.g, c.b].map((n) => round(n));
279
+ if (notation.legacy) {
280
+ const name = translucent || notation.alphaName ? 'rgba' : 'rgb';
281
+ return translucent || notation.alphaName ? `${name}(${r}, ${g}, ${b}, ${alphaText(c.a)})` : `${name}(${r}, ${g}, ${b})`;
282
+ }
283
+ return translucent ? `rgb(${r} ${g} ${b} / ${alphaText(c.a)})` : `rgb(${r} ${g} ${b})`;
284
+ }
285
+ case 'hsl': {
286
+ const hsl = rgbaToHsla(c);
287
+ const [h, s, l] = [round(hsl.h, 1), round(hsl.s * 100, 1), round(hsl.l * 100, 1)];
288
+ if (notation.legacy) {
289
+ const name = translucent || notation.alphaName ? 'hsla' : 'hsl';
290
+ return translucent || notation.alphaName ? `${name}(${h}, ${s}%, ${l}%, ${alphaText(c.a)})` : `${name}(${h}, ${s}%, ${l}%)`;
291
+ }
292
+ return translucent ? `hsl(${h} ${s}% ${l}% / ${alphaText(c.a)})` : `hsl(${h} ${s}% ${l}%)`;
293
+ }
294
+ case 'oklch': {
295
+ const o = oklch ?? rgbaToOklch(c);
296
+ const l = round(o.l * 100, 2);
297
+ const ch = round(o.c, 4);
298
+ // An achromatic color has no meaningful hue.
299
+ const h = ch === 0 ? 0 : round(wrapHue(o.h), 2);
300
+ const a = oklch ? clamp(oklch.a, 0, 1) : c.a;
301
+ return a < 1 ? `oklch(${l}% ${ch} ${h} / ${alphaText(a)})` : `oklch(${l}% ${ch} ${h})`;
302
+ }
303
+ }
304
+ }
305
+ /** The format an edit of a color written as `notation` should come back in (named colors become hex). */
306
+ export function editFormat(notation) {
307
+ return !notation || notation.format === 'named' ? 'hex' : notation.format;
308
+ }
309
+ /**
310
+ * Writes `rgba` the way `original` is written: same notation, comma syntax
311
+ * and hex case; a named original stays named when the new color is a named
312
+ * color, else becomes hex. An unreadable original gives hex.
313
+ */
314
+ export function formatLike(original, rgba) {
315
+ const parsed = parseColor(original);
316
+ if (!parsed)
317
+ return formatHex(rgba);
318
+ const { notation } = parsed;
319
+ if (notation.format === 'named')
320
+ return colorName(rgba) ?? formatHex(rgba);
321
+ return formatColor(rgba, notation.format, notation);
322
+ }
323
+ /**
324
+ * Re-writes the color `text` in `format` (hex, rgb, hsl, oklch). Returns
325
+ * null when `text` is not a color.
326
+ */
327
+ export function convertColor(text, format) {
328
+ const parsed = parseColor(text);
329
+ if (!parsed)
330
+ return null;
331
+ return formatColor(parsed.rgba, format, {}, format === 'oklch' ? parsed.oklch : undefined);
332
+ }
333
+ /** True when two colors render the same (channels within half a step, alpha within 1%). */
334
+ export function sameColor(a, b) {
335
+ if (a == null || b == null)
336
+ return a == b;
337
+ const x = typeof a === 'string' ? toRgba(a) : a;
338
+ const y = typeof b === 'string' ? toRgba(b) : b;
339
+ if (!x || !y)
340
+ return typeof a === 'string' && typeof b === 'string' && a.trim().toLowerCase() === b.trim().toLowerCase();
341
+ if (x.a === 0 && y.a === 0)
342
+ return true;
343
+ return Math.abs(x.r - y.r) < 0.5 && Math.abs(x.g - y.g) < 0.5 && Math.abs(x.b - y.b) < 0.5 && Math.abs(x.a - y.a) < 0.01;
344
+ }
345
+ /* ------------------------------- conversions ------------------------------ */
346
+ /** sRGB to HSV. `hue` is kept for grays, which have none of their own. */
347
+ export function rgbaToHsva(rgba, hue = 0) {
348
+ const r = rgba.r / 255;
349
+ const g = rgba.g / 255;
350
+ const b = rgba.b / 255;
351
+ const max = Math.max(r, g, b);
352
+ const min = Math.min(r, g, b);
353
+ const d = max - min;
354
+ let h = hue;
355
+ if (d > 1e-9) {
356
+ if (max === r)
357
+ h = 60 * (((g - b) / d) % 6);
358
+ else if (max === g)
359
+ h = 60 * ((b - r) / d + 2);
360
+ else
361
+ h = 60 * ((r - g) / d + 4);
362
+ h = wrapHue(h);
363
+ }
364
+ return { h, s: max === 0 ? 0 : d / max, v: max, a: rgba.a };
365
+ }
366
+ /** HSV to sRGB. */
367
+ export function hsvaToRgba(hsva) {
368
+ const h = wrapHue(hsva.h) / 60;
369
+ const s = clamp(hsva.s, 0, 1);
370
+ const v = clamp(hsva.v, 0, 1);
371
+ const c = v * s;
372
+ const x = c * (1 - Math.abs((h % 2) - 1));
373
+ const m = v - c;
374
+ const [r, g, b] = h < 1 ? [c, x, 0] : h < 2 ? [x, c, 0] : h < 3 ? [0, c, x] : h < 4 ? [0, x, c] : h < 5 ? [x, 0, c] : [c, 0, x];
375
+ return { r: (r + m) * 255, g: (g + m) * 255, b: (b + m) * 255, a: clamp(hsva.a, 0, 1) };
376
+ }
377
+ /** sRGB to HSL. `hue` is kept for grays. */
378
+ export function rgbaToHsla(rgba, hue = 0) {
379
+ const { h, s: sv, v } = rgbaToHsva(rgba, hue);
380
+ const l = v * (1 - sv / 2);
381
+ const s = l === 0 || l === 1 ? 0 : (v - l) / Math.min(l, 1 - l);
382
+ return { h, s, l, a: rgba.a };
383
+ }
384
+ /** HSL to sRGB. */
385
+ export function hslaToRgba(hsla) {
386
+ const l = clamp(hsla.l, 0, 1);
387
+ const s = clamp(hsla.s, 0, 1);
388
+ const v = l + s * Math.min(l, 1 - l);
389
+ return hsvaToRgba({ h: hsla.h, s: v === 0 ? 0 : 2 * (1 - l / v), v, a: hsla.a });
390
+ }
391
+ const toLinear = (c) => (c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4);
392
+ const fromLinear = (c) => (c <= 0.0031308 ? 12.92 * c : 1.055 * c ** (1 / 2.4) - 0.055);
393
+ /** sRGB to OKLCH. `hue` is kept for grays. */
394
+ export function rgbaToOklch(rgba, hue = 0) {
395
+ const r = toLinear(rgba.r / 255);
396
+ const g = toLinear(rgba.g / 255);
397
+ const b = toLinear(rgba.b / 255);
398
+ const l_ = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b);
399
+ const m_ = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b);
400
+ const s_ = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b);
401
+ const L = 0.2104542553 * l_ + 0.793617785 * m_ - 0.0040720468 * s_;
402
+ const A = 1.9779984951 * l_ - 2.428592205 * m_ + 0.4505937099 * s_;
403
+ const B = 0.0259040371 * l_ + 0.7827717662 * m_ - 0.808675766 * s_;
404
+ const c = Math.hypot(A, B);
405
+ return { l: L, c: c < 1e-6 ? 0 : c, h: c < 1e-6 ? hue : wrapHue((Math.atan2(B, A) * 180) / Math.PI), a: rgba.a };
406
+ }
407
+ /** OKLCH to linear-light sRGB, unclipped. */
408
+ function oklchToLinear(o) {
409
+ const hr = (o.h * Math.PI) / 180;
410
+ const A = o.c * Math.cos(hr);
411
+ const B = o.c * Math.sin(hr);
412
+ const l = (o.l + 0.3963377774 * A + 0.2158037573 * B) ** 3;
413
+ const m = (o.l - 0.1055613458 * A - 0.0638541728 * B) ** 3;
414
+ const s = (o.l - 0.0894841775 * A - 1.291485548 * B) ** 3;
415
+ return [
416
+ 4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,
417
+ -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,
418
+ -0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s,
419
+ ];
420
+ }
421
+ const inGamut = (linear) => linear.every((c) => c >= -1e-4 && c <= 1 + 1e-4);
422
+ /** True when an OKLCH color fits in sRGB. */
423
+ export function oklchInGamut(o) {
424
+ return inGamut(oklchToLinear(o));
425
+ }
426
+ /**
427
+ * OKLCH to sRGB. Colors outside sRGB are brought in by lowering chroma
428
+ * (keeping lightness and hue), as CSS Color 4 gamut mapping does.
429
+ */
430
+ export function oklchToRgba(o) {
431
+ let target = { ...o, l: clamp(o.l, 0, 1), c: Math.max(0, o.c) };
432
+ if (!inGamut(oklchToLinear(target))) {
433
+ let lo = 0;
434
+ let hi = target.c;
435
+ for (let i = 0; i < 20; i++) {
436
+ const mid = (lo + hi) / 2;
437
+ if (inGamut(oklchToLinear({ ...target, c: mid })))
438
+ lo = mid;
439
+ else
440
+ hi = mid;
441
+ }
442
+ target = { ...target, c: lo };
443
+ }
444
+ const [r, g, b] = oklchToLinear(target).map((c) => clamp(fromLinear(clamp(c, 0, 1)), 0, 1) * 255);
445
+ return { r, g, b, a: clamp(o.a, 0, 1) };
446
+ }
447
+ /* -------------------------------- contrast -------------------------------- */
448
+ /** Paints `top` over `bottom` (straight alpha). */
449
+ export function composite(top, bottom) {
450
+ const a = top.a + bottom.a * (1 - top.a);
451
+ if (a === 0)
452
+ return { r: 0, g: 0, b: 0, a: 0 };
453
+ const mix = (t, u) => (t * top.a + u * bottom.a * (1 - top.a)) / a;
454
+ return { r: mix(top.r, bottom.r), g: mix(top.g, bottom.g), b: mix(top.b, bottom.b), a };
455
+ }
456
+ /** WCAG 2 relative luminance of an opaque color, 0–1. */
457
+ export function relativeLuminance(rgba) {
458
+ return 0.2126 * toLinear(rgba.r / 255) + 0.7152 * toLinear(rgba.g / 255) + 0.0722 * toLinear(rgba.b / 255);
459
+ }
460
+ const WHITE = { r: 255, g: 255, b: 255, a: 1 };
461
+ /**
462
+ * WCAG 2 contrast ratio (1–21) of `foreground` on `background`. A
463
+ * translucent background is taken over white, then a translucent foreground
464
+ * over that. Null when either is not a readable color.
465
+ */
466
+ export function contrastRatio(foreground, background) {
467
+ const fg = typeof foreground === 'string' ? toRgba(foreground) : foreground;
468
+ const bgRaw = typeof background === 'string' ? toRgba(background) : background;
469
+ if (!fg || !bgRaw)
470
+ return null;
471
+ const bg = bgRaw.a < 1 ? composite(bgRaw, WHITE) : bgRaw;
472
+ const front = fg.a < 1 ? composite(fg, bg) : fg;
473
+ const l1 = relativeLuminance(front);
474
+ const l2 = relativeLuminance(bg);
475
+ return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
476
+ }
477
+ /**
478
+ * The best WCAG 2 level `ratio` meets: AAA ≥ 7, AA ≥ 4.5, AA Large ≥ 3 (large
479
+ * text and UI). With `large`, AAA is ≥ 4.5 and AA ≥ 3.
480
+ */
481
+ export function contrastLevel(ratio, large = false) {
482
+ if (large)
483
+ return ratio >= 4.5 ? 'AAA' : ratio >= 3 ? 'AA' : 'Fail';
484
+ return ratio >= 7 ? 'AAA' : ratio >= 4.5 ? 'AA' : ratio >= 3 ? 'AA Large' : 'Fail';
485
+ }
486
+ /** The ratio a level needs: AA 4.5 (3 for large text), AAA 7 (4.5 for large text). */
487
+ export function contrastTarget(level = 'AA', large = false) {
488
+ if (level === 'AAA')
489
+ return large ? 4.5 : 7;
490
+ return large ? 3 : 4.5;
491
+ }
492
+ /**
493
+ * The shade of `color` nearest in OKLCH lightness (same hue and chroma,
494
+ * gamut-mapped) that reaches `target` contrast on `background`, written like
495
+ * `color`. Null when `color` already passes or no shade does.
496
+ */
497
+ export function readableShade(color, background, target = 4.5) {
498
+ const parsed = parseColor(color);
499
+ const bg = toRgba(background);
500
+ if (!parsed || !bg)
501
+ return null;
502
+ const ratio = contrastRatio(parsed.rgba, bg);
503
+ if (ratio === null || ratio >= target)
504
+ return null;
505
+ const base = parsed.oklch ?? rgbaToOklch(parsed.rgba);
506
+ let best = null;
507
+ for (const direction of [-1, 1]) {
508
+ // Walk lightness away from the start until it passes; keep the closer of the two directions.
509
+ for (let step = 1; step <= 100; step++) {
510
+ const l = base.l + direction * step * 0.01;
511
+ if (l < 0 || l > 1)
512
+ break;
513
+ const candidate = { ...base, l };
514
+ const r = contrastRatio(oklchToRgba(candidate), bg);
515
+ if (r !== null && r >= target) {
516
+ if (!best || Math.abs(l - base.l) < Math.abs(best.l - base.l))
517
+ best = candidate;
518
+ break;
519
+ }
520
+ }
521
+ }
522
+ if (!best)
523
+ return null;
524
+ const { notation } = parsed;
525
+ if (notation.format === 'oklch')
526
+ return formatColor(oklchToRgba(best), 'oklch', notation, best);
527
+ return formatColor(oklchToRgba(best), editFormat(notation), notation.format === 'named' ? {} : notation);
528
+ }