react-smart-copy 1.15.0 → 1.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/color.cjs ADDED
@@ -0,0 +1,927 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ //#region src/color/convert.ts
3
+ const color = (r, g, b, alpha = 1) => Object.freeze({
4
+ r,
5
+ g,
6
+ b,
7
+ alpha
8
+ });
9
+ const mul = (m, [x, y, z]) => [
10
+ m[0][0] * x + m[0][1] * y + m[0][2] * z,
11
+ m[1][0] * x + m[1][1] * y + m[1][2] * z,
12
+ m[2][0] * x + m[2][1] * y + m[2][2] * z
13
+ ];
14
+ /** The sRGB (and Display P3) transfer function, extended to negative values by symmetry. */
15
+ const toLinear = (c) => {
16
+ const abs = Math.abs(c);
17
+ return abs <= .04045 ? c / 12.92 : Math.sign(c) * ((abs + .055) / 1.055) ** 2.4;
18
+ };
19
+ const fromLinear = (c) => {
20
+ const abs = Math.abs(c);
21
+ return abs > .0031308 ? Math.sign(c) * (1.055 * abs ** (1 / 2.4) - .055) : 12.92 * c;
22
+ };
23
+ const linearRgb = (c) => [
24
+ toLinear(c.r),
25
+ toLinear(c.g),
26
+ toLinear(c.b)
27
+ ];
28
+ const fromLinearRgb = ([r, g, b], alpha) => color(fromLinear(r), fromLinear(g), fromLinear(b), alpha);
29
+ const SRGB_TO_XYZ = [
30
+ [
31
+ .41239079926595934,
32
+ .357584339383878,
33
+ .1804807884018343
34
+ ],
35
+ [
36
+ .21263900587151027,
37
+ .715168678767756,
38
+ .07219231536073371
39
+ ],
40
+ [
41
+ .01933081871559182,
42
+ .11919477979462598,
43
+ .9505321522496607
44
+ ]
45
+ ];
46
+ const XYZ_TO_SRGB = [
47
+ [
48
+ 3.2409699419045226,
49
+ -1.537383177570094,
50
+ -.4986107602930034
51
+ ],
52
+ [
53
+ -.9692436362808796,
54
+ 1.8759675015077202,
55
+ .04155505740717559
56
+ ],
57
+ [
58
+ .05563007969699366,
59
+ -.20397695888897652,
60
+ 1.0569715142428786
61
+ ]
62
+ ];
63
+ const P3_TO_XYZ = [
64
+ [
65
+ .4865709486482162,
66
+ .26566769316909306,
67
+ .1982172852343625
68
+ ],
69
+ [
70
+ .2289745640697488,
71
+ .6917385218365064,
72
+ .079286914093745
73
+ ],
74
+ [
75
+ 0,
76
+ .04511338185890264,
77
+ 1.043944368900976
78
+ ]
79
+ ];
80
+ const XYZ_TO_P3 = [
81
+ [
82
+ 2.493496911941425,
83
+ -.9313836179191239,
84
+ -.40271078445071684
85
+ ],
86
+ [
87
+ -.8294889695615747,
88
+ 1.7626640603183463,
89
+ .023624685841943577
90
+ ],
91
+ [
92
+ .03584583024378447,
93
+ -.07617238926804182,
94
+ .9568845240076872
95
+ ]
96
+ ];
97
+ /** Bradford chromatic adaptation between the D65 and D50 white points (Lab and LCH use D50). */
98
+ const D65_TO_D50 = [
99
+ [
100
+ 1.0479297925449969,
101
+ .022946870601609652,
102
+ -.05019226628920524
103
+ ],
104
+ [
105
+ .02962780877005599,
106
+ .9904344267538799,
107
+ -.017073799063418826
108
+ ],
109
+ [
110
+ -.009243040646204504,
111
+ .015055191490298152,
112
+ .7518742814281371
113
+ ]
114
+ ];
115
+ const D50_TO_D65 = [
116
+ [
117
+ .955473421488075,
118
+ -.02309845494876471,
119
+ .06325924320057072
120
+ ],
121
+ [
122
+ -.0283697093338637,
123
+ 1.0099953980813041,
124
+ .021041441191917323
125
+ ],
126
+ [
127
+ .012314014864481998,
128
+ -.020507649298898964,
129
+ 1.330365926242124
130
+ ]
131
+ ];
132
+ /** Linear sRGB to OKLab's cone responses, and back. */
133
+ const LRGB_TO_LMS = [
134
+ [
135
+ .412221469470763,
136
+ .5363325372617348,
137
+ .0514459932675022
138
+ ],
139
+ [
140
+ .2119034958178252,
141
+ .6806995506452344,
142
+ .1073969535369406
143
+ ],
144
+ [
145
+ .0883024591900564,
146
+ .2817188391361215,
147
+ .6299787016738222
148
+ ]
149
+ ];
150
+ const LMS_TO_LRGB = [
151
+ [
152
+ 4.076741636075957,
153
+ -3.3077115392580616,
154
+ .2309699031821044
155
+ ],
156
+ [
157
+ -1.2684379732850317,
158
+ 2.6097573492876887,
159
+ -.3413193760026573
160
+ ],
161
+ [
162
+ -.0041960761386756,
163
+ -.7034186179359362,
164
+ 1.7076146940746117
165
+ ]
166
+ ];
167
+ const LMS_TO_OKLAB = [
168
+ [
169
+ .210454268309314,
170
+ .7936177747023054,
171
+ -.0040720430116193
172
+ ],
173
+ [
174
+ 1.9779985324311684,
175
+ -2.42859224204858,
176
+ .450593709617411
177
+ ],
178
+ [
179
+ .0259040424655478,
180
+ .7827717124575296,
181
+ -.8086757549230774
182
+ ]
183
+ ];
184
+ const OKLAB_TO_LMS = [
185
+ [
186
+ 1,
187
+ .3963377773761749,
188
+ .2158037573099136
189
+ ],
190
+ [
191
+ 1,
192
+ -.1055613458156586,
193
+ -.0638541728258133
194
+ ],
195
+ [
196
+ 1,
197
+ -.0894841775298119,
198
+ -1.2914855480194092
199
+ ]
200
+ ];
201
+ const toXyz = (c) => mul(SRGB_TO_XYZ, linearRgb(c));
202
+ const fromXyz = (xyz, alpha) => fromLinearRgb(mul(XYZ_TO_SRGB, xyz), alpha);
203
+ /** Display P3 channels (gamma-encoded, 0 to 1 inside P3). */
204
+ const toP3 = (c) => mul(XYZ_TO_P3, toXyz(c)).map(fromLinear);
205
+ const fromP3 = (p3, alpha) => fromXyz(mul(P3_TO_XYZ, p3.map(toLinear)), alpha);
206
+ const fromXyzD50 = (xyz, alpha) => fromXyz(mul(D50_TO_D65, xyz), alpha);
207
+ /** OKLab: L in [0, 1], a and b around ±0.4. */
208
+ const toOklab = (c) => mul(LMS_TO_OKLAB, mul(LRGB_TO_LMS, linearRgb(c)).map(Math.cbrt));
209
+ const fromOklab = (lab, alpha) => fromLinearRgb(mul(LMS_TO_LRGB, mul(OKLAB_TO_LMS, lab).map((v) => v ** 3)), alpha);
210
+ const D50_WHITE = [
211
+ .3457 / .3585,
212
+ 1,
213
+ .2958 / .3585
214
+ ];
215
+ const KAPPA = 24389 / 27;
216
+ const EPSILON = 216 / 24389;
217
+ /** CIE Lab (D50): L in [0, 100], a and b around ±125. */
218
+ const toLab = (c) => {
219
+ const [x, y, z] = mul(D65_TO_D50, toXyz(c)).map((v, i) => v / D50_WHITE[i]);
220
+ const f = (v) => v > EPSILON ? Math.cbrt(v) : (KAPPA * v + 16) / 116;
221
+ const [fx, fy, fz] = [
222
+ f(x),
223
+ f(y),
224
+ f(z)
225
+ ];
226
+ return [
227
+ 116 * fy - 16,
228
+ 500 * (fx - fy),
229
+ 200 * (fy - fz)
230
+ ];
231
+ };
232
+ const fromLab = ([l, a, b], alpha) => {
233
+ const fy = (l + 16) / 116;
234
+ const fx = a / 500 + fy;
235
+ const fz = fy - b / 200;
236
+ const xyz = [
237
+ fx ** 3 > EPSILON ? fx ** 3 : (116 * fx - 16) / KAPPA,
238
+ l > KAPPA * EPSILON ? fy ** 3 : l / KAPPA,
239
+ fz ** 3 > EPSILON ? fz ** 3 : (116 * fz - 16) / KAPPA
240
+ ];
241
+ return fromXyzD50(xyz.map((v, i) => v * D50_WHITE[i]), alpha);
242
+ };
243
+ /** Lab-like to its polar form: lightness, chroma, and hue in degrees from 0 to 360. */
244
+ const toPolar = ([l, a, b]) => [
245
+ l,
246
+ Math.hypot(a, b),
247
+ (Math.atan2(b, a) * 180 / Math.PI + 360) % 360
248
+ ];
249
+ const fromPolar = ([l, c, h]) => [
250
+ l,
251
+ c * Math.cos(h * Math.PI / 180),
252
+ c * Math.sin(h * Math.PI / 180)
253
+ ];
254
+ /** Hue, saturation and lightness of a colour inside sRGB (hue 0 for greys), with s and l in [0, 1]. */
255
+ function toHsl(c) {
256
+ const max = Math.max(c.r, c.g, c.b);
257
+ const min = Math.min(c.r, c.g, c.b);
258
+ const l = (max + min) / 2;
259
+ const d = max - min;
260
+ if (d === 0) return [
261
+ 0,
262
+ 0,
263
+ l
264
+ ];
265
+ const s = (max - l) / Math.min(l, 1 - l);
266
+ let h;
267
+ if (max === c.r) h = (c.g - c.b) / d + (c.g < c.b ? 6 : 0);
268
+ else if (max === c.g) h = (c.b - c.r) / d + 2;
269
+ else h = (c.r - c.g) / d + 4;
270
+ return [
271
+ h * 60,
272
+ s,
273
+ l
274
+ ];
275
+ }
276
+ function fromHsl(h, s, l, alpha) {
277
+ const hue = (h % 360 + 360) % 360;
278
+ const f = (n) => {
279
+ const k = (n + hue / 30) % 12;
280
+ return l - s * Math.min(l, 1 - l) * Math.max(-1, Math.min(k - 3, 9 - k, 1));
281
+ };
282
+ return color(f(0), f(8), f(4), alpha);
283
+ }
284
+ function fromHwb(h, w, b, alpha) {
285
+ if (w + b >= 1) {
286
+ const grey = w / (w + b);
287
+ return color(grey, grey, grey, alpha);
288
+ }
289
+ const pure = fromHsl(h, 1, .5, 1);
290
+ const scale = (v) => v * (1 - w - b) + w;
291
+ return color(scale(pure.r), scale(pure.g), scale(pure.b), alpha);
292
+ }
293
+ /** Hue, whiteness and blackness of an sRGB colour, with w and b in [0, 1]. */
294
+ function toHwb(c) {
295
+ const [h] = toHsl(c);
296
+ return [
297
+ h,
298
+ Math.min(c.r, c.g, c.b),
299
+ 1 - Math.max(c.r, c.g, c.b)
300
+ ];
301
+ }
302
+ /** Distance in OKLab: about 0.02 is the smallest difference people notice. */
303
+ const deltaEOK = (a, b) => {
304
+ const [l1, a1, b1] = toOklab(a);
305
+ const [l2, a2, b2] = toOklab(b);
306
+ return Math.hypot(l1 - l2, a1 - a2, b1 - b2);
307
+ };
308
+ const channels = (c, gamut) => gamut === "srgb" ? [
309
+ c.r,
310
+ c.g,
311
+ c.b
312
+ ] : toP3(c);
313
+ const clip01 = (v) => Math.min(1, Math.max(0, v));
314
+ const clipTo = (c, gamut) => {
315
+ const [x, y, z] = channels(c, gamut).map(clip01);
316
+ return gamut === "srgb" ? color(x, y, z, c.alpha) : fromP3([
317
+ x,
318
+ y,
319
+ z
320
+ ], c.alpha);
321
+ };
322
+ /** Whether a colour is inside a gamut, within rounding error. */
323
+ function inGamut(c, gamut = "srgb") {
324
+ return channels(c, gamut).every((v) => v >= -1e-6 && v <= 1 + 1e-6);
325
+ }
326
+ /**
327
+ * The colour inside `gamut` that looks closest: the CSS Color 4 gamut mapping
328
+ * algorithm, which keeps lightness and hue and reduces chroma in OKLCH until
329
+ * clipping is no longer visible (`"map"`), or plain clipping of each channel (`"clip"`).
330
+ */
331
+ function toGamut(c, gamut = "srgb", method = "map") {
332
+ if (inGamut(c, gamut)) return clipTo(c, gamut);
333
+ if (method === "clip") return clipTo(c, gamut);
334
+ const [l, chroma, hue] = toPolar(toOklab(c));
335
+ if (l >= 1 - 1e-7) return clipTo(color(1, 1, 1, c.alpha), gamut);
336
+ if (l <= 1e-7) return clipTo(color(0, 0, 0, c.alpha), gamut);
337
+ const JND = .02;
338
+ let low = 0;
339
+ let high = chroma;
340
+ let lowInGamut = true;
341
+ let current = c;
342
+ let clipped = clipTo(current, gamut);
343
+ if (deltaEOK(clipped, current) < JND) return clipped;
344
+ while (high - low > 1e-4) {
345
+ const mid = (low + high) / 2;
346
+ current = fromOklab(fromPolar([
347
+ l,
348
+ mid,
349
+ hue
350
+ ]), c.alpha);
351
+ if (lowInGamut && inGamut(current, gamut)) {
352
+ low = mid;
353
+ continue;
354
+ }
355
+ clipped = clipTo(current, gamut);
356
+ const e = deltaEOK(clipped, current);
357
+ if (e < JND) {
358
+ if (JND - e < 1e-4) return clipped;
359
+ lowInGamut = false;
360
+ low = mid;
361
+ } else high = mid;
362
+ }
363
+ return clipped;
364
+ }
365
+ //#endregion
366
+ //#region src/core/errors.ts
367
+ function createCopyError(type, message, cause) {
368
+ return cause === void 0 ? {
369
+ type,
370
+ message
371
+ } : {
372
+ type,
373
+ message,
374
+ cause
375
+ };
376
+ }
377
+ /**
378
+ * Branded (not `instanceof`) so failures stay recognisable even when the core
379
+ * is bundled twice, e.g. `react-smart-copy` and `react-smart-copy/core` together.
380
+ */
381
+ const COPY_FAILURE_BRAND = Symbol.for("react-smart-copy.CopyFailure");
382
+ /** Error thrown by adapters to carry a fully classified {@link CopyError}. */
383
+ var CopyFailure = class extends Error {
384
+ constructor(copyError) {
385
+ super(copyError.message);
386
+ this[COPY_FAILURE_BRAND] = true;
387
+ this.name = "CopyFailure";
388
+ this.copyError = copyError;
389
+ }
390
+ };
391
+ /** Shorthand for throwing a classified failure. */
392
+ function copyFailure(type, message, cause) {
393
+ return new CopyFailure(createCopyError(type, message, cause));
394
+ }
395
+ //#endregion
396
+ //#region src/color/names.ts
397
+ /**
398
+ * The 148 named colours of CSS Color 4, as "name rrggbb" pairs. Parsed into a map
399
+ * the first time a name is looked up, so the table costs nothing until then.
400
+ */
401
+ const NAMED = [
402
+ "aliceblue f0f8ff antiquewhite faebd7 aqua 00ffff aquamarine 7fffd4 azure f0ffff beige f5f5dc bisque ffe4c4",
403
+ "black 000000 blanchedalmond ffebcd blue 0000ff blueviolet 8a2be2 brown a52a2a burlywood deb887",
404
+ "cadetblue 5f9ea0 chartreuse 7fff00 chocolate d2691e coral ff7f50 cornflowerblue 6495ed cornsilk fff8dc",
405
+ "crimson dc143c cyan 00ffff darkblue 00008b darkcyan 008b8b darkgoldenrod b8860b darkgray a9a9a9",
406
+ "darkgreen 006400 darkgrey a9a9a9 darkkhaki bdb76b darkmagenta 8b008b darkolivegreen 556b2f darkorange ff8c00",
407
+ "darkorchid 9932cc darkred 8b0000 darksalmon e9967a darkseagreen 8fbc8f darkslateblue 483d8b",
408
+ "darkslategray 2f4f4f darkslategrey 2f4f4f darkturquoise 00ced1 darkviolet 9400d3 deeppink ff1493",
409
+ "deepskyblue 00bfff dimgray 696969 dimgrey 696969 dodgerblue 1e90ff firebrick b22222 floralwhite fffaf0",
410
+ "forestgreen 228b22 fuchsia ff00ff gainsboro dcdcdc ghostwhite f8f8ff gold ffd700 goldenrod daa520 gray 808080",
411
+ "green 008000 greenyellow adff2f grey 808080 honeydew f0fff0 hotpink ff69b4 indianred cd5c5c indigo 4b0082",
412
+ "ivory fffff0 khaki f0e68c lavender e6e6fa lavenderblush fff0f5 lawngreen 7cfc00 lemonchiffon fffacd",
413
+ "lightblue add8e6 lightcoral f08080 lightcyan e0ffff lightgoldenrodyellow fafad2 lightgray d3d3d3",
414
+ "lightgreen 90ee90 lightgrey d3d3d3 lightpink ffb6c1 lightsalmon ffa07a lightseagreen 20b2aa",
415
+ "lightskyblue 87cefa lightslategray 778899 lightslategrey 778899 lightsteelblue b0c4de lightyellow ffffe0",
416
+ "lime 00ff00 limegreen 32cd32 linen faf0e6 magenta ff00ff maroon 800000 mediumaquamarine 66cdaa",
417
+ "mediumblue 0000cd mediumorchid ba55d3 mediumpurple 9370db mediumseagreen 3cb371 mediumslateblue 7b68ee",
418
+ "mediumspringgreen 00fa9a mediumturquoise 48d1cc mediumvioletred c71585 midnightblue 191970 mintcream f5fffa",
419
+ "mistyrose ffe4e1 moccasin ffe4b5 navajowhite ffdead navy 000080 oldlace fdf5e6 olive 808000 olivedrab 6b8e23",
420
+ "orange ffa500 orangered ff4500 orchid da70d6 palegoldenrod eee8aa palegreen 98fb98 paleturquoise afeeee",
421
+ "palevioletred db7093 papayawhip ffefd5 peachpuff ffdab9 peru cd853f pink ffc0cb plum dda0dd powderblue b0e0e6",
422
+ "purple 800080 rebeccapurple 663399 red ff0000 rosybrown bc8f8f royalblue 4169e1 saddlebrown 8b4513",
423
+ "salmon fa8072 sandybrown f4a460 seagreen 2e8b57 seashell fff5ee sienna a0522d silver c0c0c0 skyblue 87ceeb",
424
+ "slateblue 6a5acd slategray 708090 slategrey 708090 snow fffafa springgreen 00ff7f steelblue 4682b4 tan d2b48c",
425
+ "teal 008080 thistle d8bfd8 tomato ff6347 turquoise 40e0d0 violet ee82ee wheat f5deb3 white ffffff",
426
+ "whitesmoke f5f5f5 yellow ffff00 yellowgreen 9acd32"
427
+ ].join(" ");
428
+ let table;
429
+ /** The colour for a CSS colour name (lowercase), as 0xrrggbb, or `undefined`. */
430
+ function namedColor(name) {
431
+ if (table === void 0) {
432
+ table = /* @__PURE__ */ new Map();
433
+ const parts = NAMED.split(" ");
434
+ for (let i = 0; i < parts.length; i += 2) table.set(parts[i], parseInt(parts[i + 1], 16));
435
+ }
436
+ return table.get(name);
437
+ }
438
+ //#endregion
439
+ //#region src/color/parse.ts
440
+ /** Longer input is not a colour: parsing stays cheap whatever is pasted. */
441
+ const MAX_LENGTH = 256;
442
+ const NUMBER = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/;
443
+ const HEX = /^#([\da-f]{3,4}|[\da-f]{6}|[\da-f]{8})$/;
444
+ const FUNCTION = /^([a-z][a-z\d-]*)\(([^()]*)\)$/;
445
+ const ANGLE_UNITS = {
446
+ deg: 1,
447
+ grad: .9,
448
+ rad: 180 / Math.PI,
449
+ turn: 360
450
+ };
451
+ /** One component: a number, a percentage, an angle (in degrees) or `none`. */
452
+ function token(text) {
453
+ if (text === "none") return {
454
+ kind: "none",
455
+ value: 0
456
+ };
457
+ if (text.endsWith("%")) {
458
+ const body = text.slice(0, -1);
459
+ return NUMBER.test(body) ? {
460
+ kind: "percent",
461
+ value: Number(body)
462
+ } : null;
463
+ }
464
+ const unit = /[a-z]+$/.exec(text)?.[0];
465
+ if (unit !== void 0) {
466
+ const factor = ANGLE_UNITS[unit];
467
+ const body = text.slice(0, -unit.length);
468
+ return factor === void 0 || !NUMBER.test(body) ? null : {
469
+ kind: "angle",
470
+ value: Number(body) * factor
471
+ };
472
+ }
473
+ return NUMBER.test(text) ? {
474
+ kind: "number",
475
+ value: Number(text)
476
+ } : null;
477
+ }
478
+ const clamp = (v, min, max) => Math.min(max, Math.max(min, v));
479
+ /** A component's value: numbers as they are, percentages scaled so 100% is `full`. */
480
+ function amount(t, full, allowed) {
481
+ if (t.kind === "none") return 0;
482
+ if (!allowed.includes(t.kind)) return null;
483
+ return t.kind === "percent" ? t.value / 100 * full : t.value;
484
+ }
485
+ const hueOf = (t) => amount(t, 0, ["number", "angle"]);
486
+ const alphaOf = (t) => {
487
+ if (t === void 0) return 1;
488
+ const value = amount(t, 1, ["number", "percent"]);
489
+ return value === null ? null : clamp(value, 0, 1);
490
+ };
491
+ /** Splits arguments into three components and an optional alpha; `legacy` for the comma syntax. */
492
+ function split(args) {
493
+ const legacy = args.includes(",");
494
+ let main;
495
+ let alphaText;
496
+ if (legacy) {
497
+ const list = args.split(",").map((part) => part.trim());
498
+ if (list.length < 3 || list.length > 4) return null;
499
+ main = list.slice(0, 3);
500
+ alphaText = list[3];
501
+ } else {
502
+ const [body, rest, extra] = args.split("/");
503
+ if (extra !== void 0) return null;
504
+ main = body.trim().split(/\s+/);
505
+ alphaText = rest?.trim();
506
+ if (main.length !== 3 || alphaText === "") return null;
507
+ }
508
+ const parts = main.map(token);
509
+ if (parts.some((part) => part === null)) return null;
510
+ const alpha = alphaText === void 0 ? void 0 : token(alphaText);
511
+ if (alpha === null) return null;
512
+ if (legacy && [...parts, alpha].some((part) => part?.kind === "none")) return null;
513
+ return {
514
+ parts,
515
+ alpha,
516
+ legacy
517
+ };
518
+ }
519
+ function rgb(parts, legacy) {
520
+ if (legacy && new Set(parts.map((part) => part.kind)).size !== 1) return null;
521
+ const values = parts.map((part) => amount(part, 255, ["number", "percent"]));
522
+ return values.some((v) => v === null) ? null : values.map((v) => clamp(v, 0, 255) / 255);
523
+ }
524
+ const PREDEFINED = {
525
+ srgb: ([r, g, b], alpha) => color(r, g, b, alpha),
526
+ "srgb-linear": fromLinearRgb,
527
+ "display-p3": fromP3,
528
+ xyz: fromXyz,
529
+ "xyz-d65": fromXyz,
530
+ "xyz-d50": fromXyzD50
531
+ };
532
+ /** `color(space c1 c2 c3 / alpha)`. */
533
+ function predefined(args) {
534
+ const match = /^([a-z\d-]+)\s+(.*)$/.exec(args.trim());
535
+ if (match === null) return null;
536
+ const convert = PREDEFINED[match[1]];
537
+ const parsed = split(match[2]);
538
+ if (convert === void 0 || parsed === null || parsed.legacy) return null;
539
+ const values = parsed.parts.map((part) => amount(part, 1, ["number", "percent"]));
540
+ const alpha = alphaOf(parsed.alpha);
541
+ return values.some((v) => v === null) || alpha === null ? null : convert(values, alpha);
542
+ }
543
+ function functional(name, args) {
544
+ if (name === "color") return predefined(args);
545
+ const parsed = split(args);
546
+ if (parsed === null) return null;
547
+ const { parts, legacy } = parsed;
548
+ const [a, b, c] = parts;
549
+ const alpha = alphaOf(parsed.alpha);
550
+ if (alpha === null) return null;
551
+ switch (name) {
552
+ case "rgb":
553
+ case "rgba": {
554
+ const values = rgb(parts, legacy);
555
+ return values === null ? null : color(values[0], values[1], values[2], alpha);
556
+ }
557
+ case "hsl":
558
+ case "hsla": {
559
+ const hue = hueOf(a);
560
+ const kinds = legacy ? ["percent"] : ["number", "percent"];
561
+ const s = amount(b, 100, kinds);
562
+ const l = amount(c, 100, kinds);
563
+ if (hue === null || s === null || l === null) return null;
564
+ return fromHsl(hue, clamp(s, 0, 100) / 100, clamp(l, 0, 100) / 100, alpha);
565
+ }
566
+ case "hwb": {
567
+ const hue = hueOf(a);
568
+ const w = amount(b, 100, ["number", "percent"]);
569
+ const k = amount(c, 100, ["number", "percent"]);
570
+ if (legacy || hue === null || w === null || k === null) return null;
571
+ return fromHwb(hue, clamp(w, 0, 100) / 100, clamp(k, 0, 100) / 100, alpha);
572
+ }
573
+ default: return legacy ? null : lab(name, a, b, c, alpha);
574
+ }
575
+ }
576
+ /** lab(), lch(), oklab() and oklch(). */
577
+ function lab(name, a, b, c, alpha) {
578
+ const ok = name.startsWith("ok");
579
+ const polar = name.endsWith("ch");
580
+ if (![
581
+ "lab",
582
+ "lch",
583
+ "oklab",
584
+ "oklch"
585
+ ].includes(name)) return null;
586
+ const lightMax = ok ? 1 : 100;
587
+ const l = amount(a, lightMax, ["number", "percent"]);
588
+ const second = amount(b, ok ? .4 : polar ? 150 : 125, ["number", "percent"]);
589
+ const third = polar ? hueOf(c) : amount(c, ok ? .4 : 125, ["number", "percent"]);
590
+ if (l === null || second === null || third === null) return null;
591
+ const lightness = clamp(l, 0, lightMax);
592
+ const values = polar ? fromPolar([
593
+ lightness,
594
+ Math.max(0, second),
595
+ third
596
+ ]) : [
597
+ lightness,
598
+ second,
599
+ third
600
+ ];
601
+ return ok ? fromOklab(values, alpha) : fromLab(values, alpha);
602
+ }
603
+ /**
604
+ * Parses a CSS colour, or returns `null`: hex (`#rgb`, `#rgba`, `#rrggbb`,
605
+ * `#rrggbbaa`), the 148 named colours and `transparent`, `rgb()` and `hsl()` in
606
+ * both syntaxes, `hwb()`, `lab()`, `lch()`, `oklab()`, `oklch()`, and `color()`
607
+ * in `srgb`, `srgb-linear`, `display-p3`, `xyz`, `xyz-d65` and `xyz-d50`.
608
+ * Never throws. Colours outside sRGB keep their exact value.
609
+ *
610
+ * Not colours on their own: `currentcolor`, system colours, `var()`, `calc()`,
611
+ * `color-mix()` and relative colours.
612
+ *
613
+ * @example
614
+ * parseColor('oklch(62.8% 0.258 29.23)'); // { r: 1, g: 0, b: 0, alpha: 1 } (rounded)
615
+ */
616
+ function parseColor(input) {
617
+ if (typeof input !== "string" || input.length > MAX_LENGTH) return null;
618
+ const text = input.trim().toLowerCase();
619
+ const hex = HEX.exec(text)?.[1];
620
+ if (hex !== void 0) {
621
+ const full = hex.length <= 4 ? hex.replace(/./g, (digit) => digit + digit) : hex;
622
+ const byte = (i) => parseInt(full.slice(i, i + 2), 16) / 255;
623
+ return color(byte(0), byte(2), byte(4), full.length === 8 ? byte(6) : 1);
624
+ }
625
+ if (text === "transparent") return color(0, 0, 0, 0);
626
+ const named = namedColor(text);
627
+ if (named !== void 0) return color((named >> 16 & 255) / 255, (named >> 8 & 255) / 255, (named & 255) / 255);
628
+ const match = FUNCTION.exec(text);
629
+ return match === null ? null : functional(match[1], match[2].trim());
630
+ }
631
+ //#endregion
632
+ //#region src/color/format.ts
633
+ const COLOR_FORMATS = /* @__PURE__ */ Object.freeze([
634
+ "hex",
635
+ "rgb",
636
+ "hsl",
637
+ "hwb",
638
+ "oklch",
639
+ "oklab",
640
+ "lab",
641
+ "lch",
642
+ "p3"
643
+ ]);
644
+ const isColor = (value) => typeof value === "object" && value !== null && [
645
+ "r",
646
+ "g",
647
+ "b",
648
+ "alpha"
649
+ ].every((key) => Number.isFinite(value[key]));
650
+ /** Resolves a colour input, throwing a typed error for anything that is not one. */
651
+ function toColor(input) {
652
+ if (typeof input === "string") {
653
+ const parsed = parseColor(input);
654
+ if (parsed === null) throw copyFailure("invalid-payload", `Not a colour: ${JSON.stringify(input.slice(0, 100))}.`);
655
+ return parsed;
656
+ }
657
+ if (!isColor(input)) throw copyFailure("invalid-payload", "A colour must be a CSS colour string or an { r, g, b, alpha } object with finite numbers.");
658
+ return input;
659
+ }
660
+ /** Rounds to `places` decimals, without trailing zeros or `-0`. */
661
+ function num(value, places) {
662
+ const factor = 10 ** places;
663
+ const rounded = Math.round(value * factor) / factor;
664
+ return String(Object.is(rounded, -0) ? 0 : rounded);
665
+ }
666
+ /** A hue in degrees, with 360 written as 0. */
667
+ const hue = (value, places) => {
668
+ const text = num(value, places);
669
+ return text === "360" ? "0" : text;
670
+ };
671
+ const byte = (v) => Math.round(Math.min(1, Math.max(0, v)) * 255);
672
+ /** The alpha suffix of a functional notation: nothing when opaque. */
673
+ const alphaPart = (alpha, legacy, places) => alpha >= 1 ? "" : legacy ? `, ${num(alpha, places)}` : ` / ${num(alpha, places)}`;
674
+ /**
675
+ * Writes a colour in a CSS format. Text is parsed first, so this also converts
676
+ * between formats.
677
+ *
678
+ * @example
679
+ * formatColor('rgb(255 0 0)', 'oklch'); // 'oklch(62.8% 0.2577 29.23)'
680
+ * formatColor('color(display-p3 1 0 0)', 'hex'); // '#ff0000' after gamut mapping, never a wrong hue
681
+ */
682
+ function formatColor(input, format = "hex", options = {}) {
683
+ const c = toColor(input);
684
+ const { gamut = "map", legacy = false, uppercase = false, precision } = options;
685
+ const method = gamut;
686
+ if (method !== "map" && method !== "clip") throw copyFailure("invalid-payload", "`gamut` must be \"map\" or \"clip\".");
687
+ if (precision !== void 0 && !(Number.isInteger(precision) && precision >= 0 && precision <= 10)) throw copyFailure("invalid-payload", "`precision` must be an integer from 0 to 10.");
688
+ const dp = (fallback) => precision ?? fallback;
689
+ const a = c.alpha;
690
+ switch (format) {
691
+ case "hex": {
692
+ const s = toGamut(c, "srgb", gamut);
693
+ const digits = [
694
+ s.r,
695
+ s.g,
696
+ s.b,
697
+ ...a < 1 ? [a] : []
698
+ ].map((v) => byte(v).toString(16).padStart(2, "0")).join("");
699
+ return `#${uppercase ? digits.toUpperCase() : digits}`;
700
+ }
701
+ case "rgb": {
702
+ const s = toGamut(c, "srgb", gamut);
703
+ const [r, g, b] = [
704
+ s.r,
705
+ s.g,
706
+ s.b
707
+ ].map(byte);
708
+ return legacy ? `${a < 1 ? "rgba" : "rgb"}(${String(r)}, ${String(g)}, ${String(b)}${alphaPart(a, true, dp(3))})` : `rgb(${String(r)} ${String(g)} ${String(b)}${alphaPart(a, false, dp(3))})`;
709
+ }
710
+ case "hsl": {
711
+ const [h, s, l] = toHsl(toGamut(c, "srgb", gamut));
712
+ const [hh, ss, ll] = [
713
+ hue(h, dp(2)),
714
+ `${num(s * 100, dp(2))}%`,
715
+ `${num(l * 100, dp(2))}%`
716
+ ];
717
+ return legacy ? `${a < 1 ? "hsla" : "hsl"}(${hh}, ${ss}, ${ll}${alphaPart(a, true, dp(3))})` : `hsl(${hh} ${ss} ${ll}${alphaPart(a, false, dp(3))})`;
718
+ }
719
+ case "hwb": {
720
+ const [h, w, b] = toHwb(toGamut(c, "srgb", gamut));
721
+ return `hwb(${hue(h, dp(2))} ${num(w * 100, dp(2))}% ${num(b * 100, dp(2))}%${alphaPart(a, false, dp(3))})`;
722
+ }
723
+ case "oklab": {
724
+ const [l, x, y] = toOklab(c);
725
+ return `oklab(${num(l * 100, dp(2))}% ${num(x, dp(5))} ${num(y, dp(5))}${alphaPart(a, false, dp(3))})`;
726
+ }
727
+ case "oklch": {
728
+ const [l, ch, h] = toPolar(toOklab(c));
729
+ const chroma = num(ch, dp(5));
730
+ return `oklch(${num(l * 100, dp(2))}% ${chroma} ${chroma === "0" ? "0" : hue(h, dp(2))}${alphaPart(a, false, dp(3))})`;
731
+ }
732
+ case "lab": {
733
+ const [l, x, y] = toLab(c);
734
+ return `lab(${num(l, dp(2))} ${num(x, dp(2))} ${num(y, dp(2))}${alphaPart(a, false, dp(3))})`;
735
+ }
736
+ case "lch": {
737
+ const [l, ch, h] = toPolar(toLab(c));
738
+ const chroma = num(ch, dp(2));
739
+ return `lch(${num(l, dp(2))} ${chroma} ${chroma === "0" ? "0" : hue(h, dp(2))}${alphaPart(a, false, dp(3))})`;
740
+ }
741
+ case "p3": {
742
+ const [r, g, b] = toP3(toGamut(c, "p3", gamut));
743
+ return `color(display-p3 ${num(r, dp(4))} ${num(g, dp(4))} ${num(b, dp(4))}${alphaPart(a, false, dp(3))})`;
744
+ }
745
+ default: throw copyFailure("invalid-payload", `Unknown colour format ${JSON.stringify(String(format))}: use one of ${COLOR_FORMATS.join(", ")}.`);
746
+ }
747
+ }
748
+ //#endregion
749
+ //#region src/color/contrast.ts
750
+ const WHITE = /* @__PURE__ */ color(1, 1, 1);
751
+ /** `top` drawn over `bottom`, both made opaque first. */
752
+ function over(top, bottom) {
753
+ const mix = (a, b) => a * top.alpha + b * (1 - top.alpha);
754
+ return color(mix(top.r, bottom.r), mix(top.g, bottom.g), mix(top.b, bottom.b));
755
+ }
756
+ /** WCAG 2 relative luminance of an opaque sRGB colour. */
757
+ function luminance(c) {
758
+ const lin = (v) => v <= .04045 ? v / 12.92 : ((v + .055) / 1.055) ** 2.4;
759
+ return .2126 * lin(c.r) + .7152 * lin(c.g) + .0722 * lin(c.b);
760
+ }
761
+ /**
762
+ * The WCAG 2 contrast ratio of text over a background, from 1 to 21. Colours are
763
+ * mapped into sRGB, a translucent background is drawn over white, and translucent
764
+ * text over the background, as a browser would show them. Never rounded: 4.499 is
765
+ * not 4.5.
766
+ *
767
+ * @example
768
+ * contrastRatio('#767676', '#fff'); // 4.54
769
+ */
770
+ function contrastRatio(text, background) {
771
+ const bg = over(toGamut(toColor(background)), WHITE);
772
+ const [light, dark] = [luminance(over(toGamut(toColor(text)), bg)), luminance(bg)].sort((a, b) => b - a);
773
+ return (light + .05) / (dark + .05);
774
+ }
775
+ /** The WCAG 2 level met by a contrast ratio (`contrastRatio`), for normal or large text. */
776
+ function contrastLevel(ratio, options = {}) {
777
+ if (!Number.isFinite(ratio) || ratio < 1) throw copyFailure("invalid-payload", "A contrast ratio is a number from 1 to 21.");
778
+ const [aa, aaa] = options.large === true ? [3, 4.5] : [4.5, 7];
779
+ if (ratio >= aaa) return "AAA";
780
+ return ratio >= aa ? "AA" : "fail";
781
+ }
782
+ //#endregion
783
+ //#region src/core/text-field.ts
784
+ const TEXT_INPUTS = /* @__PURE__ */ new Set([
785
+ "text",
786
+ "search",
787
+ "url",
788
+ "tel",
789
+ "password"
790
+ ]);
791
+ function asTextField(target) {
792
+ if (typeof target !== "object" || target === null) return null;
793
+ const element = target;
794
+ if (element.nodeName === "TEXTAREA") return target;
795
+ if (element.nodeName === "INPUT" && typeof element.type === "string" && TEXT_INPUTS.has(element.type)) return target;
796
+ return null;
797
+ }
798
+ /**
799
+ * Inserts text at the cursor of a `<textarea>` or text `<input>`, replacing the
800
+ * selection, as typing or pasting would: the browser's undo (Ctrl/⌘+Z) still
801
+ * works, `input` events fire (so React and other frameworks see the change),
802
+ * and `maxlength` is respected. Returns `false` for disabled or read-only fields.
803
+ */
804
+ function insertText(field, text) {
805
+ if (field.disabled || field.readOnly) return false;
806
+ const value = field.nodeName === "INPUT" ? text.replace(/[ \t]*(?:\r\n|\r|\n)+[ \t]*/g, " ") : text;
807
+ const doc = field.ownerDocument;
808
+ field.focus();
809
+ const start = field.selectionStart;
810
+ const end = field.selectionEnd;
811
+ try {
812
+ if (start !== null && end !== null) field.setSelectionRange(start, end);
813
+ if (doc.activeElement === field && doc.execCommand("insertText", false, value)) return true;
814
+ } catch {}
815
+ const from = start ?? field.value.length;
816
+ const to = end ?? from;
817
+ let insert = value;
818
+ if (field.maxLength >= 0) {
819
+ const room = Math.max(0, field.maxLength - (field.value.length - (to - from)));
820
+ insert = insert.slice(0, room);
821
+ if (/[\ud800-\udbff]$/.test(insert)) insert = insert.slice(0, -1);
822
+ }
823
+ if (start === null) setNativeValue(field, field.value + insert);
824
+ else field.setRangeText(insert, from, to, "end");
825
+ const view = doc.defaultView;
826
+ const event = view !== null && typeof view.InputEvent === "function" ? new view.InputEvent("input", {
827
+ bubbles: true,
828
+ inputType: "insertFromPaste",
829
+ data: insert
830
+ }) : new Event("input", { bubbles: true });
831
+ field.dispatchEvent(event);
832
+ return true;
833
+ }
834
+ /**
835
+ * Sets a field's value through the prototype's setter. React tracks the value
836
+ * set on the element itself; going around it lets React see the change and
837
+ * call `onChange` for the `input` event that follows.
838
+ */
839
+ function setNativeValue(field, next) {
840
+ const setter = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(field), "value")?.set;
841
+ if (setter) setter.call(field, next);
842
+ else field.value = next;
843
+ }
844
+ //#endregion
845
+ //#region src/color/payload.ts
846
+ /** The sRGB hex of a colour for the swatch's inline style: always generated here, never user text. */
847
+ const swatchColor = (c) => formatColor(toGamut(c), "hex");
848
+ /**
849
+ * A colour to copy: its value in a CSS format as the plain text, and with
850
+ * `swatch` (default) a small coloured square next to the value for rich-text apps.
851
+ *
852
+ * @example
853
+ * copy(() => colorPayload('#3b82f6', { format: 'oklch' }));
854
+ * // text: 'oklch(62.31% 0.188 259.81)', plus a blue swatch in Docs and Slack
855
+ */
856
+ function colorPayload(input, options = {}) {
857
+ const { format = "hex", swatch = true, ...formatOptions } = options;
858
+ const c = toColor(input);
859
+ const value = formatColor(c, format, formatOptions);
860
+ const withSwatch = swatch;
861
+ if (typeof withSwatch !== "boolean") throw copyFailure("invalid-payload", "`swatch` must be a boolean.");
862
+ if (!withSwatch) return {
863
+ kind: "text",
864
+ value
865
+ };
866
+ const escaped = value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
867
+ return {
868
+ kind: "html",
869
+ html: `<span style="${`display:inline-block;width:0.9em;height:0.9em;vertical-align:-0.1em;border:1px solid rgba(0,0,0,0.25);border-radius:2px;background:${swatchColor(c)}`}"></span>&nbsp;<code>${escaped}</code>`,
870
+ text: value
871
+ };
872
+ }
873
+ /** `name: value;` as copied from a stylesheet or the browser's developer tools. */
874
+ const DECLARATION = /^(?:--)?[a-z][\w-]*\s*:\s*(.+?)\s*(?:!important\s*)?;?$/i;
875
+ /**
876
+ * The one colour that pasted text holds, or `null`: any CSS colour `parseColor`
877
+ * reads, also as a declaration copied from a stylesheet or developer tools
878
+ * (`background: #fff;`, `--brand: oklch(…)`). Never throws for content.
879
+ *
880
+ * @example
881
+ * readColor(' rgb(59, 130, 246) '); // a Color
882
+ * readColor('color: #3b82f6 !important;'); // a Color
883
+ */
884
+ function readColor(source, options = {}) {
885
+ const raw = typeof source === "string" ? source : source.text;
886
+ if (typeof raw !== "string" || raw.length > 512) return null;
887
+ const text = raw.trim();
888
+ const value = DECLARATION.exec(text)?.[1] ?? text;
889
+ const direct = parseColor(value);
890
+ if (direct !== null || options.bareHex !== true) return direct;
891
+ return /^(?:[\da-f]{3}|[\da-f]{6}|[\da-f]{8})$/i.test(value) ? parseColor(`#${value}`) : null;
892
+ }
893
+ /**
894
+ * A paste handler for colour fields: a pasted colour in any CSS format (or a
895
+ * declaration copied from developer tools) is inserted in the field's format,
896
+ * so `rgb(59 130 246)` pasted into a hex field becomes `#3b82f6`. Anything else
897
+ * is left to the browser, and the browser's undo still works. Returns whether
898
+ * it handled the paste.
899
+ *
900
+ * @example
901
+ * <input value={hex} onChange={…} onPaste={(event) => pasteAsColor(event, { format: 'hex' })} />
902
+ */
903
+ function pasteAsColor(event, options = {}) {
904
+ const { format = "hex", onColor, bareHex, ...formatOptions } = options;
905
+ formatColor("#000", format, formatOptions);
906
+ if (event.defaultPrevented || event.clipboardData === null) return false;
907
+ const field = asTextField(event.currentTarget) ?? asTextField(event.target);
908
+ if (field === null || field.disabled || field.readOnly) return false;
909
+ const pasted = readColor(event.clipboardData.getData("text/plain"), bareHex === void 0 ? {} : { bareHex });
910
+ if (pasted === null || onColor?.(pasted) === false) return false;
911
+ event.preventDefault();
912
+ return insertText(field, formatColor(pasted, format, formatOptions));
913
+ }
914
+ //#endregion
915
+ exports.COLOR_FORMATS = COLOR_FORMATS;
916
+ exports.colorPayload = colorPayload;
917
+ exports.contrastLevel = contrastLevel;
918
+ exports.contrastRatio = contrastRatio;
919
+ exports.formatColor = formatColor;
920
+ exports.inGamut = inGamut;
921
+ exports.insertText = insertText;
922
+ exports.parseColor = parseColor;
923
+ exports.pasteAsColor = pasteAsColor;
924
+ exports.readColor = readColor;
925
+ exports.toGamut = toGamut;
926
+
927
+ //# sourceMappingURL=color.cjs.map