@nextlyhq/ui 0.0.2-alpha.7 → 0.0.2-alpha.70

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.mjs ADDED
@@ -0,0 +1,458 @@
1
+ // src/lib/color/convert.ts
2
+ const clamp01$2 = (n) => n < 0 ? 0 : n > 1 ? 1 : n;
3
+ /**
4
+ * A chroma no displayable sRGB colour exceeds.
5
+ *
6
+ * The most saturated sRGB primaries sit near 0.37 in OKLCH; this leaves headroom above that and
7
+ * gives the gamut search a fixed bracket, so its error is absolute rather than proportional to
8
+ * whatever the caller asked for.
9
+ */
10
+ const MAX_SRGB_CHROMA = .5;
11
+ /**
12
+ * Wrap a hue into [0, 360), so -30 and 330 are the same angle.
13
+ *
14
+ * @experimental
15
+ */
16
+ function normalizeHue(hue) {
17
+ if (!Number.isFinite(hue)) return 0;
18
+ const wrapped = hue % 360;
19
+ return wrapped < 0 ? wrapped + 360 : wrapped;
20
+ }
21
+ /**
22
+ * HSV to sRGB.
23
+ * Saturation and value are clamped rather than rejected: a picker drags them, and a drag that
24
+ * overshoots by a rounding error should saturate rather than throw.
25
+ *
26
+ * @experimental
27
+ */
28
+ function hsvToRgb({ h, s, v }) {
29
+ const hue = normalizeHue(h);
30
+ const sat = clamp01$2(s);
31
+ const val = clamp01$2(v);
32
+ const sector = hue / 60;
33
+ const chroma = val * sat;
34
+ const x = chroma * (1 - Math.abs(sector % 2 - 1));
35
+ const base = val - chroma;
36
+ let rgb;
37
+ if (sector < 1) rgb = [
38
+ chroma,
39
+ x,
40
+ 0
41
+ ];
42
+ else if (sector < 2) rgb = [
43
+ x,
44
+ chroma,
45
+ 0
46
+ ];
47
+ else if (sector < 3) rgb = [
48
+ 0,
49
+ chroma,
50
+ x
51
+ ];
52
+ else if (sector < 4) rgb = [
53
+ 0,
54
+ x,
55
+ chroma
56
+ ];
57
+ else if (sector < 5) rgb = [
58
+ x,
59
+ 0,
60
+ chroma
61
+ ];
62
+ else rgb = [
63
+ chroma,
64
+ 0,
65
+ x
66
+ ];
67
+ return {
68
+ r: rgb[0] + base,
69
+ g: rgb[1] + base,
70
+ b: rgb[2] + base
71
+ };
72
+ }
73
+ /**
74
+ * sRGB to HSV.
75
+ * Hue is UNDEFINED for a grey and value is undefined for black, and this returns 0 for both. A
76
+ * picker must not take that 0 as the user's hue: it is the absence of one. Holding hue across a
77
+ * drag to zero saturation is the caller's job, which is why a picker keeps HSV as its state
78
+ * rather than deriving it from the colour each render.
79
+ *
80
+ * @experimental
81
+ */
82
+ function rgbToHsv({ r, g, b }) {
83
+ const red = clamp01$2(r);
84
+ const green = clamp01$2(g);
85
+ const blue = clamp01$2(b);
86
+ const max = Math.max(red, green, blue);
87
+ const chroma = max - Math.min(red, green, blue);
88
+ let hue = 0;
89
+ if (chroma !== 0) {
90
+ if (max === red) hue = (green - blue) / chroma % 6;
91
+ else if (max === green) hue = (blue - red) / chroma + 2;
92
+ else hue = (red - green) / chroma + 4;
93
+ hue *= 60;
94
+ }
95
+ return {
96
+ h: normalizeHue(hue),
97
+ s: max === 0 ? 0 : chroma / max,
98
+ v: max
99
+ };
100
+ }
101
+ /** The sRGB transfer function, gamma-encoded to linear light. */
102
+ function toLinear(channel) {
103
+ return channel <= .04045 ? channel / 12.92 : Math.pow((channel + .055) / 1.055, 2.4);
104
+ }
105
+ /** The inverse transfer function, linear light back to gamma-encoded. */
106
+ function toGamma(channel) {
107
+ return channel <= .0031308 ? channel * 12.92 : 1.055 * Math.pow(channel, 1 / 2.4) - .055;
108
+ }
109
+ /**
110
+ * Linear sRGB to OKLab.
111
+ *
112
+ * The two matrices and the cube root between them are the definition of OKLab, given in CSS
113
+ * Color 4. They are transcribed rather than derived.
114
+ */
115
+ function linearRgbToOklab(r, g, b) {
116
+ const l = .4122214708 * r + .5363325363 * g + .0514459929 * b;
117
+ const m = .2119034982 * r + .6806995451 * g + .1073969566 * b;
118
+ const s = .0883024619 * r + .2817188376 * g + .6299787005 * b;
119
+ const l_ = Math.cbrt(l);
120
+ const m_ = Math.cbrt(m);
121
+ const s_ = Math.cbrt(s);
122
+ return [
123
+ .2104542553 * l_ + .793617785 * m_ - .0040720468 * s_,
124
+ 1.9779984951 * l_ - 2.428592205 * m_ + .4505937099 * s_,
125
+ .0259040371 * l_ + .7827717662 * m_ - .808675766 * s_
126
+ ];
127
+ }
128
+ /** OKLab back to linear sRGB, the inverse of {@link linearRgbToOklab}. */
129
+ function oklabToLinearRgb(L, a, b) {
130
+ const l_ = L + .3963377774 * a + .2158037573 * b;
131
+ const m_ = L - .1055613458 * a - .0638541728 * b;
132
+ const s_ = L - .0894841775 * a - 1.291485548 * b;
133
+ const l = l_ * l_ * l_;
134
+ const m = m_ * m_ * m_;
135
+ const s = s_ * s_ * s_;
136
+ return [
137
+ 4.0767416621 * l - 3.3077115913 * m + .2309699292 * s,
138
+ -1.2684380046 * l + 2.6097574011 * m - .3413193965 * s,
139
+ -.0041960863 * l - .7034186147 * m + 1.707614701 * s
140
+ ];
141
+ }
142
+ /**
143
+ * sRGB to OKLCH.
144
+ *
145
+ * @experimental
146
+ */
147
+ function rgbToOklch({ r, g, b }) {
148
+ const [L, A, B] = linearRgbToOklab(toLinear(clamp01$2(r)), toLinear(clamp01$2(g)), toLinear(clamp01$2(b)));
149
+ const chroma = Math.sqrt(A * A + B * B);
150
+ return {
151
+ l: L,
152
+ c: chroma,
153
+ h: chroma < 1e-6 ? 0 : normalizeHue(Math.atan2(B, A) * 180 / Math.PI)
154
+ };
155
+ }
156
+ /** Whether every channel of a linear triple lies within the displayable range. */
157
+ function inGamut([r, g, b]) {
158
+ return r >= -0 && r <= 1 && g >= -0 && g <= 1 && b >= -0 && b <= 1;
159
+ }
160
+ /**
161
+ * OKLCH to sRGB, reducing chroma until the colour fits on screen.
162
+ * OKLCH can name colours a display cannot show. Clamping the channels independently is the
163
+ * obvious response and the wrong one: clipping red without clipping green changes the ratio
164
+ * between them, so the colour that appears is a DIFFERENT HUE from the one asked for. Lightness
165
+ * and hue are what a person chose; chroma is the part they will not miss, so chroma is what is
166
+ * given up.
167
+ * The search is a bisection on chroma, which converges to well under a perceptible step in the
168
+ * fixed number of rounds below — no loop that might not terminate.
169
+ *
170
+ * **The gamut is not always monotonic along this ray, and that is a deliberate trade.** At some
171
+ * lightness and hue pairs the boundary is crossed more than once: at `l = 0.2, h = 264.1` the ray
172
+ * is inside up to c ≈ 0.1192, outside until c ≈ 0.1368, briefly inside again to c ≈ 0.1386. A
173
+ * bisection therefore finds the FIRST boundary rather than the outermost reachable chroma.
174
+ *
175
+ * That is the intended behaviour rather than a limitation. Those islands span roughly a tenth of
176
+ * a degree of hue, so preferring the outermost value would make chroma jump by about 0.021
177
+ * between h = 264.05 and h = 264.10 — a visible step while dragging a hue slider, over a change
178
+ * no one can aim at. Taking the first boundary gives 0.1160, 0.1175, 0.1192, 0.1255, 0.1383
179
+ * across the same sweep: continuous, and one step less saturated at worst. It is also what the
180
+ * CSS Color 4 gamut-mapping algorithm does.
181
+ *
182
+ * @experimental
183
+ */
184
+ function oklchToRgb({ l, c, h }) {
185
+ const lightness = clamp01$2(l);
186
+ const hueRadians = normalizeHue(h) * Math.PI / 180;
187
+ const at = (chroma) => oklabToLinearRgb(lightness, chroma * Math.cos(hueRadians), chroma * Math.sin(hueRadians));
188
+ const requested = Math.max(0, c);
189
+ let fitting = at(requested);
190
+ if (!inGamut(fitting)) {
191
+ let low = 0;
192
+ let high = Math.min(requested, MAX_SRGB_CHROMA);
193
+ for (let i = 0; i < 20; i++) {
194
+ const mid = (low + high) / 2;
195
+ if (inGamut(at(mid))) low = mid;
196
+ else high = mid;
197
+ }
198
+ fitting = at(low);
199
+ }
200
+ return {
201
+ r: clamp01$2(toGamma(fitting[0])),
202
+ g: clamp01$2(toGamma(fitting[1])),
203
+ b: clamp01$2(toGamma(fitting[2]))
204
+ };
205
+ }
206
+ // src/lib/color/hex.ts
207
+ /** `#rgb`, `#rgba`, `#rrggbb` or `#rrggbbaa`, with the hash optional and case ignored. */
208
+ const HEX = /^#?(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i;
209
+ const clamp01$1 = (n) => n < 0 ? 0 : n > 1 ? 1 : n;
210
+ /** A channel byte as a two-digit lowercase pair. */
211
+ function pair(channel) {
212
+ const value = Number.isFinite(channel) ? clamp01$1(channel) : 0;
213
+ return Math.round(value * 255).toString(16).padStart(2, "0");
214
+ }
215
+ /**
216
+ * Read a hex colour, or `null` if the input is not one.
217
+ *
218
+ * Returns `null` rather than throwing or substituting black: this reads what someone is part-way
219
+ * through typing, where "not a colour yet" is the ordinary case and neither an exception nor a
220
+ * silent black is a useful answer. A caller decides whether to hold the last good value, show a
221
+ * message, or wait.
222
+ *
223
+ * Both short forms are accepted because both are what people paste. `#abc` expands by REPEATING
224
+ * each digit rather than padding with zero — `#abc` is `#aabbcc`, not `#a0b0c0` — which is what CSS
225
+ * does and the only expansion under which `#fff` is white.
226
+ *
227
+ * @experimental
228
+ */
229
+ function parseHex(input) {
230
+ const text = input.trim();
231
+ if (!HEX.test(text)) return null;
232
+ const digits = text.replace("#", "");
233
+ const short = digits.length < 6;
234
+ const size = short ? 1 : 2;
235
+ const channel = (index) => {
236
+ const slice = digits.slice(index * size, index * size + size);
237
+ return parseInt(short ? slice + slice : slice, 16) / 255;
238
+ };
239
+ const hasAlpha = digits.length === 4 || digits.length === 8;
240
+ return {
241
+ r: channel(0),
242
+ g: channel(1),
243
+ b: channel(2),
244
+ alpha: hasAlpha ? channel(3) : 1
245
+ };
246
+ }
247
+ /**
248
+ * Write a colour as `#rrggbb`, or `#rrggbbaa` when it is not fully opaque.
249
+ *
250
+ * The alpha pair is omitted at 1 rather than always written, because `#3b82f6ff` is the same colour
251
+ * and the shorter form is what someone expects to see in a field they typed `#3b82f6` into.
252
+ *
253
+ * Channels outside [0, 1] are clamped, so the result is always a valid six- or eight-digit hex
254
+ * string whatever a caller passes. Not for floating-point drift, which rounds to the right byte on
255
+ * its own: it is for a value that is wrong by a lot — a channel still in 0-255, or a computation
256
+ * that overshot — where the alternative is emitting `#17f00-80`, a string nothing downstream can
257
+ * parse and no error explains.
258
+ *
259
+ * @experimental
260
+ */
261
+ function toHex(color, alpha = 1) {
262
+ const opacity = Number.isFinite(alpha) ? clamp01$1(alpha) : 1;
263
+ const opaque = `#${pair(color.r)}${pair(color.g)}${pair(color.b)}`;
264
+ return opacity === 1 ? opaque : `${opaque}${pair(opacity)}`;
265
+ }
266
+ // src/lib/color/wcag.ts
267
+ /** Linearize one gamma-encoded sRGB channel (the WCAG 2.x transfer function). */
268
+ function channelToLinear(c) {
269
+ return c <= .04045 ? c / 12.92 : Math.pow((c + .055) / 1.055, 2.4);
270
+ }
271
+ /** WCAG 2.x relative luminance of a gamma-encoded sRGB colour. */
272
+ function relativeLuminance(rgb) {
273
+ return .2126 * channelToLinear(rgb.r) + .7152 * channelToLinear(rgb.g) + .0722 * channelToLinear(rgb.b);
274
+ }
275
+ /**
276
+ * WCAG 2.x contrast ratio between two OPAQUE colours, from 1:1 to 21:1. A
277
+ * translucent colour must be composited over its surface first.
278
+ */
279
+ function contrastRatio(a, b) {
280
+ const la = relativeLuminance(a);
281
+ const lb = relativeLuminance(b);
282
+ return (Math.max(la, lb) + .05) / (Math.min(la, lb) + .05);
283
+ }
284
+ // src/lib/color/readable-on.ts
285
+ /**
286
+ * A colour made readable on the surfaces it is drawn on, by its lightness
287
+ * alone.
288
+ *
289
+ * For colours that are not known when the theme is built, such as a tenant's
290
+ * brand colours drawn as chart marks, and so cannot be held to a contrast
291
+ * minimum by the theme's own test. The colour is never refused: one that
292
+ * already reads is returned exactly as given, and one that does not keeps the
293
+ * hue and chroma the tenant chose and moves its OKLCH lightness, as little as
294
+ * it takes, until it reads on every surface. OKLCH because its lightness is
295
+ * perceptual, so the smallest step there is the smallest change a reader sees.
296
+ *
297
+ * @module lib/color/readable-on
298
+ */
299
+ /** The step the lightness search takes, small beside what a reader can tell apart. */
300
+ const STEP = .001;
301
+ /**
302
+ * The colour as it will be drawn: each channel rounded to the 8 bits a hex
303
+ * value carries. The ratio is checked on THIS, so a colour written out as hex
304
+ * keeps the ratio it was found at.
305
+ */
306
+ function asDrawn(rgb) {
307
+ const round = (channel) => Math.round(channel * 255) / 255;
308
+ return {
309
+ r: round(rgb.r),
310
+ g: round(rgb.g),
311
+ b: round(rgb.b)
312
+ };
313
+ }
314
+ /** The lowest ratio `color` has against any of `surfaces`. */
315
+ function lowestRatio(color, surfaces) {
316
+ let lowest = Number.POSITIVE_INFINITY;
317
+ for (const surface of surfaces) lowest = Math.min(lowest, contrastRatio(color, surface));
318
+ return lowest;
319
+ }
320
+ /**
321
+ * `color`, or the nearest colour of its hue and chroma that reaches `minimum`
322
+ * against every one of `surfaces`.
323
+ *
324
+ * Searches outward from the colour's own lightness, one step each way at a
325
+ * time, and takes the first lightness that reads; where both directions read
326
+ * at the same distance, the one reading better. Should no lightness reach the
327
+ * minimum on every surface, it returns the one that comes closest: a brand
328
+ * colour is adjusted, never refused.
329
+ *
330
+ * Chroma is reduced only where the display cannot show it at the new
331
+ * lightness, which is `oklchToRgb`'s own rule; hue is kept.
332
+ *
333
+ * @experimental
334
+ */
335
+ function readableOn(color, surfaces, minimum = 3) {
336
+ if (surfaces.length === 0 || lowestRatio(color, surfaces) >= minimum) return color;
337
+ const oklch = rgbToOklch(color);
338
+ const drawn = asDrawn(color);
339
+ let best = {
340
+ rgb: drawn,
341
+ ratio: lowestRatio(drawn, surfaces)
342
+ };
343
+ const steps = Math.ceil(1 / STEP);
344
+ for (let i = 1; i <= steps; i += 1) {
345
+ const candidates = candidatesAt(oklch, i * STEP, surfaces);
346
+ best = betterOf(best, candidates);
347
+ const reading = candidates.filter((c) => c.ratio >= minimum);
348
+ const [first] = reading;
349
+ if (first !== void 0) return betterOf(first, reading).rgb;
350
+ }
351
+ return best.rgb;
352
+ }
353
+ /**
354
+ * The colours `distance` either side of `oklch`'s lightness, darker first, as
355
+ * drawn and with their lowest ratio; none past black or white.
356
+ */
357
+ function candidatesAt(oklch, distance, surfaces) {
358
+ return [oklch.l - distance, oklch.l + distance].filter((lightness) => lightness >= 0 && lightness <= 1).map((lightness) => {
359
+ const rgb = asDrawn(oklchToRgb({
360
+ ...oklch,
361
+ l: lightness
362
+ }));
363
+ return {
364
+ rgb,
365
+ ratio: lowestRatio(rgb, surfaces)
366
+ };
367
+ });
368
+ }
369
+ /** The best-reading of `current` and `candidates`, the earlier one on a tie. */
370
+ function betterOf(current, candidates) {
371
+ return candidates.reduce((kept, next) => next.ratio > kept.ratio ? next : kept, current);
372
+ }
373
+ // src/lib/color/picker-geometry.ts
374
+ const clamp01 = (n) => n < 0 ? 0 : n > 1 ? 1 : n;
375
+ /**
376
+ * A pointer position as a fraction of a surface.
377
+ *
378
+ * Clamped, because a drag that begins inside the surface continues to report
379
+ * while the pointer leaves it — which is the interaction people actually use to
380
+ * reach full saturation, and without clamping it produces values outside the
381
+ * colour space rather than the corner they are aiming at.
382
+ *
383
+ * A zero-sized surface answers the top-left rather than dividing by zero. That
384
+ * happens in a test environment and on the first frame before layout.
385
+ *
386
+ * @experimental
387
+ */
388
+ function pointOnSurface(clientX, clientY, rect) {
389
+ return {
390
+ x: rect.width === 0 ? 0 : clamp01((clientX - rect.left) / rect.width),
391
+ y: rect.height === 0 ? 0 : clamp01((clientY - rect.top) / rect.height)
392
+ };
393
+ }
394
+ /**
395
+ * The saturation and value a point on the square stands for.
396
+ *
397
+ * Value runs UPWARD while a surface's y runs downward, so the vertical axis is
398
+ * inverted here. Getting that wrong produces a picker that looks correct and
399
+ * selects the colour vertically mirrored from the one under the cursor.
400
+ *
401
+ * @experimental
402
+ */
403
+ function saturationValueAt(point) {
404
+ return {
405
+ s: clamp01(point.x),
406
+ v: 1 - clamp01(point.y)
407
+ };
408
+ }
409
+ /**
410
+ * Where the handle sits for a given saturation and value — the inverse of
411
+ * {@link saturationValueAt}.
412
+ *
413
+ * Derived from that function's own inversion rather than written independently,
414
+ * so the two cannot disagree about which way the axis runs.
415
+ *
416
+ * @experimental
417
+ */
418
+ function surfacePointFor(s, v) {
419
+ return {
420
+ x: clamp01(s),
421
+ y: 1 - clamp01(v)
422
+ };
423
+ }
424
+ /**
425
+ * The hue a horizontal position stands for, in [0, 360).
426
+ *
427
+ * The upper bound is exclusive: 360 and 0 are the same hue, and returning 360
428
+ * lets a handle at the far end read back as a position outside the strip.
429
+ *
430
+ * @experimental
431
+ */
432
+ function hueAt(fraction) {
433
+ const hue = clamp01(fraction) * 360;
434
+ return hue >= 360 ? 0 : hue;
435
+ }
436
+ /** Where the hue handle sits, as a fraction of the strip. @experimental */
437
+ function huePosition(hue) {
438
+ return (hue % 360 + 360) % 360 / 360;
439
+ }
440
+ /**
441
+ * The integer step a hue occupies on a strip whose last step is `max`.
442
+ *
443
+ * Rounding is what makes this more than a multiplication. A hue just below 360
444
+ * — `#ff0001` is about 359.76 — rounds UP to a step past the end of the strip,
445
+ * and the obvious repair of wrapping it with a modulo sends it to 0: the far
446
+ * LEFT, the opposite end from where that colour belongs. The handle then sits
447
+ * on the wrong side and any keyboard adjustment starts from there. Held at the
448
+ * last step instead, which is where it visually belongs.
449
+ *
450
+ * @experimental
451
+ */
452
+ function hueSliderValue(hue, max) {
453
+ const step = Math.round(huePosition(hue) * (max + 1));
454
+ return step > max ? max : step;
455
+ }
456
+ export { hsvToRgb, hueAt, huePosition, hueSliderValue, normalizeHue, oklchToRgb, parseHex, pointOnSurface, readableOn, rgbToHsv, rgbToOklch, saturationValueAt, surfacePointFor, toHex };
457
+
458
+ //# sourceMappingURL=color.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"color.mjs","names":["clamp01","clamp01"],"sources":["../src/lib/color/convert.ts","../src/lib/color/hex.ts","../src/lib/color/wcag.ts","../src/lib/color/readable-on.ts","../src/lib/color/picker-geometry.ts"],"sourcesContent":["/**\n * Conversions between the colour models an editing surface needs.\n *\n * ## Why each model is here\n *\n * - **sRGB** is what a screen displays and what `#rrggbb` encodes. Everything ends here.\n * - **HSV** is what a colour picker is: a square of saturation against value, beside a hue\n * strip. No other model puts those three controls in the shape people expect.\n * - **OKLCH** is what this product's own theme is written in — every token in `theme.css` is an\n * `oklch()` value. A picker that cannot read it cannot edit the theme.\n *\n * ## Why the maths is here rather than in a library\n *\n * These are fixed, published transforms: the sRGB transfer function and the OKLab matrices are\n * specified in CSS Color 4 and do not change. The package ships no runtime colour dependency, and\n * this module keeps it that way. `culori` remains a DEV dependency used as a test oracle — the\n * conversions here are cross-checked against it rather than trusted on their own.\n *\n * ## The part that is genuinely hard\n *\n * OKLCH describes more colours than a screen can show. Converting one that falls outside sRGB has\n * no correct answer, only choices, and the naive choice — clamp each channel independently — is\n * the wrong one: it shifts hue, because clipping red without clipping green changes the ratio\n * between them. {@link oklchToRgb} reduces chroma instead, holding lightness and hue, which is the\n * approach CSS Color 4 describes for gamut mapping.\n *\n * @module lib/color/convert\n */\n\n/**\n * An sRGB colour with channels in [0, 1]. Alpha is carried separately.\n *\n * @experimental\n */\nexport interface Rgb {\n r: number;\n g: number;\n b: number;\n}\n\n/**\n * Hue in [0, 360), saturation and value in [0, 1].\n *\n * @experimental\n */\nexport interface Hsv {\n h: number;\n s: number;\n v: number;\n}\n\n/**\n * Perceptual lightness in [0, 1], chroma from 0, hue in [0, 360).\n *\n * @experimental\n */\nexport interface Oklch {\n l: number;\n c: number;\n h: number;\n}\n\nconst clamp01 = (n: number): number => (n < 0 ? 0 : n > 1 ? 1 : n);\n\n/**\n * A chroma no displayable sRGB colour exceeds.\n *\n * The most saturated sRGB primaries sit near 0.37 in OKLCH; this leaves headroom above that and\n * gives the gamut search a fixed bracket, so its error is absolute rather than proportional to\n * whatever the caller asked for.\n */\nconst MAX_SRGB_CHROMA = 0.5;\n\n/**\n * Wrap a hue into [0, 360), so -30 and 330 are the same angle.\n *\n * @experimental\n */\nexport function normalizeHue(hue: number): number {\n if (!Number.isFinite(hue)) return 0;\n const wrapped = hue % 360;\n return wrapped < 0 ? wrapped + 360 : wrapped;\n}\n\n/**\n * HSV to sRGB.\n * Saturation and value are clamped rather than rejected: a picker drags them, and a drag that\n * overshoots by a rounding error should saturate rather than throw.\n *\n * @experimental\n */\nexport function hsvToRgb({ h, s, v }: Hsv): Rgb {\n const hue = normalizeHue(h);\n const sat = clamp01(s);\n const val = clamp01(v);\n\n const sector = hue / 60;\n const chroma = val * sat;\n // The second-largest component, which falls as the hue moves away from a primary.\n const x = chroma * (1 - Math.abs((sector % 2) - 1));\n const base = val - chroma;\n\n let rgb: [number, number, number];\n if (sector < 1) rgb = [chroma, x, 0];\n else if (sector < 2) rgb = [x, chroma, 0];\n else if (sector < 3) rgb = [0, chroma, x];\n else if (sector < 4) rgb = [0, x, chroma];\n else if (sector < 5) rgb = [x, 0, chroma];\n else rgb = [chroma, 0, x];\n\n return { r: rgb[0] + base, g: rgb[1] + base, b: rgb[2] + base };\n}\n\n/**\n * sRGB to HSV.\n * Hue is UNDEFINED for a grey and value is undefined for black, and this returns 0 for both. A\n * picker must not take that 0 as the user's hue: it is the absence of one. Holding hue across a\n * drag to zero saturation is the caller's job, which is why a picker keeps HSV as its state\n * rather than deriving it from the colour each render.\n *\n * @experimental\n */\nexport function rgbToHsv({ r, g, b }: Rgb): Hsv {\n const red = clamp01(r);\n const green = clamp01(g);\n const blue = clamp01(b);\n\n const max = Math.max(red, green, blue);\n const min = Math.min(red, green, blue);\n const chroma = max - min;\n\n let hue = 0;\n if (chroma !== 0) {\n if (max === red) hue = ((green - blue) / chroma) % 6;\n else if (max === green) hue = (blue - red) / chroma + 2;\n else hue = (red - green) / chroma + 4;\n hue *= 60;\n }\n\n return {\n h: normalizeHue(hue),\n s: max === 0 ? 0 : chroma / max,\n v: max,\n };\n}\n\n/** The sRGB transfer function, gamma-encoded to linear light. */\nfunction toLinear(channel: number): number {\n return channel <= 0.04045\n ? channel / 12.92\n : Math.pow((channel + 0.055) / 1.055, 2.4);\n}\n\n/** The inverse transfer function, linear light back to gamma-encoded. */\nfunction toGamma(channel: number): number {\n return channel <= 0.0031308\n ? channel * 12.92\n : 1.055 * Math.pow(channel, 1 / 2.4) - 0.055;\n}\n\n/**\n * Linear sRGB to OKLab.\n *\n * The two matrices and the cube root between them are the definition of OKLab, given in CSS\n * Color 4. They are transcribed rather than derived.\n */\nfunction linearRgbToOklab(\n r: number,\n g: number,\n b: number\n): [number, number, number] {\n const l = 0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b;\n const m = 0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b;\n const s = 0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b;\n\n const l_ = Math.cbrt(l);\n const m_ = Math.cbrt(m);\n const s_ = Math.cbrt(s);\n\n return [\n 0.2104542553 * l_ + 0.793617785 * m_ - 0.0040720468 * s_,\n 1.9779984951 * l_ - 2.428592205 * m_ + 0.4505937099 * s_,\n 0.0259040371 * l_ + 0.7827717662 * m_ - 0.808675766 * s_,\n ];\n}\n\n/** OKLab back to linear sRGB, the inverse of {@link linearRgbToOklab}. */\nfunction oklabToLinearRgb(\n L: number,\n a: number,\n b: number\n): [number, number, number] {\n const l_ = L + 0.3963377774 * a + 0.2158037573 * b;\n const m_ = L - 0.1055613458 * a - 0.0638541728 * b;\n const s_ = L - 0.0894841775 * a - 1.291485548 * b;\n\n const l = l_ * l_ * l_;\n const m = m_ * m_ * m_;\n const s = s_ * s_ * s_;\n\n return [\n 4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,\n -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,\n -0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s,\n ];\n}\n\n/**\n * sRGB to OKLCH.\n *\n * @experimental\n */\nexport function rgbToOklch({ r, g, b }: Rgb): Oklch {\n const [L, A, B] = linearRgbToOklab(\n toLinear(clamp01(r)),\n toLinear(clamp01(g)),\n toLinear(clamp01(b))\n );\n const chroma = Math.sqrt(A * A + B * B);\n // Below this the hue angle is numerical noise rather than a colour, so it is reported as 0\n // instead of whatever direction the rounding happened to point.\n const hue =\n chroma < 1e-6 ? 0 : normalizeHue((Math.atan2(B, A) * 180) / Math.PI);\n return { l: L, c: chroma, h: hue };\n}\n\n/** Whether every channel of a linear triple lies within the displayable range. */\nfunction inGamut([r, g, b]: [number, number, number]): boolean {\n // No tolerance at all: the point must be GENUINELY inside the gamut.\n //\n // Any fixed tolerance is eventually comparable to the channel values themselves, because those\n // shrink without bound as lightness falls — 1e-6 broke the hue at l=0.01, and 1e-12 still broke\n // it at l=0.0001. A tolerance exists to absorb the cube roots' error for a colour sitting\n // exactly ON the boundary, and the cost of not absorbing it is that such a colour comes back\n // with its chroma reduced by less than one part in a million, which nothing can display. The\n // cost of absorbing it is a channel that must then be clamped, and clamping is precisely what\n // moves the hue this function promises to keep.\n const epsilon = 0;\n return (\n r >= -epsilon &&\n r <= 1 + epsilon &&\n g >= -epsilon &&\n g <= 1 + epsilon &&\n b >= -epsilon &&\n b <= 1 + epsilon\n );\n}\n\n/**\n * OKLCH to sRGB, reducing chroma until the colour fits on screen.\n * OKLCH can name colours a display cannot show. Clamping the channels independently is the\n * obvious response and the wrong one: clipping red without clipping green changes the ratio\n * between them, so the colour that appears is a DIFFERENT HUE from the one asked for. Lightness\n * and hue are what a person chose; chroma is the part they will not miss, so chroma is what is\n * given up.\n * The search is a bisection on chroma, which converges to well under a perceptible step in the\n * fixed number of rounds below — no loop that might not terminate.\n *\n * **The gamut is not always monotonic along this ray, and that is a deliberate trade.** At some\n * lightness and hue pairs the boundary is crossed more than once: at `l = 0.2, h = 264.1` the ray\n * is inside up to c ≈ 0.1192, outside until c ≈ 0.1368, briefly inside again to c ≈ 0.1386. A\n * bisection therefore finds the FIRST boundary rather than the outermost reachable chroma.\n *\n * That is the intended behaviour rather than a limitation. Those islands span roughly a tenth of\n * a degree of hue, so preferring the outermost value would make chroma jump by about 0.021\n * between h = 264.05 and h = 264.10 — a visible step while dragging a hue slider, over a change\n * no one can aim at. Taking the first boundary gives 0.1160, 0.1175, 0.1192, 0.1255, 0.1383\n * across the same sweep: continuous, and one step less saturated at worst. It is also what the\n * CSS Color 4 gamut-mapping algorithm does.\n *\n * @experimental\n */\nexport function oklchToRgb({ l, c, h }: Oklch): Rgb {\n const lightness = clamp01(l);\n const hueRadians = (normalizeHue(h) * Math.PI) / 180;\n\n const at = (chroma: number): [number, number, number] =>\n oklabToLinearRgb(\n lightness,\n chroma * Math.cos(hueRadians),\n chroma * Math.sin(hueRadians)\n );\n\n const requested = Math.max(0, c);\n let fitting = at(requested);\n\n if (!inGamut(fitting)) {\n let low = 0;\n // Bracketed against an ABSOLUTE ceiling rather than the requested chroma. Halving an\n // unbounded input a fixed number of times converges on a fraction OF THAT INPUT, so a\n // sufficiently large chroma leaves the interval far above the gamut and the search returns\n // zero — discarding the hue entirely and answering grey for a colour that has one. No sRGB\n // colour exceeds a chroma of roughly 0.37, so this ceiling cannot exclude a reachable one.\n let high = Math.min(requested, MAX_SRGB_CHROMA);\n // Halvings of a fixed interval, so the remaining error is absolute: 0.5 / 2^20 is far below\n // anything a screen or an eye resolves.\n for (let i = 0; i < 20; i++) {\n const mid = (low + high) / 2;\n if (inGamut(at(mid))) low = mid;\n else high = mid;\n }\n fitting = at(low);\n }\n\n return {\n r: clamp01(toGamma(fitting[0])),\n g: clamp01(toGamma(fitting[1])),\n b: clamp01(toGamma(fitting[2])),\n };\n}\n","/**\n * Hex is the notation people type, so it is the picker's front door.\n *\n * It lives beside the conversions rather than in the component that reads it, for the same reason\n * they do: parsing `#3b82f6` is arithmetic on a string, a server rendering a token swatch needs it\n * as much as an editing surface does, and pulling it into client code would put it behind the\n * `\"use client\"` boundary for no benefit.\n *\n * @module lib/color/hex\n */\n\nimport type { Rgb } from \"./convert\";\n\n/**\n * An sRGB colour with its alpha, which is what a hex string can carry and {@link Rgb} cannot.\n *\n * `alpha` is in [0, 1] like the channels, rather than 0-255, so it composes with the conversions\n * without a second unit in play.\n *\n * @experimental\n */\nexport interface Rgba extends Rgb {\n alpha: number;\n}\n\n/** `#rgb`, `#rgba`, `#rrggbb` or `#rrggbbaa`, with the hash optional and case ignored. */\nconst HEX = /^#?(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i;\n\nconst clamp01 = (n: number): number => (n < 0 ? 0 : n > 1 ? 1 : n);\n\n/** A channel byte as a two-digit lowercase pair. */\nfunction pair(channel: number): string {\n // A non-finite channel becomes 0 rather than passing through. `clamp01(NaN)` is NaN, because\n // both of its comparisons are false, and formatting that yields the three characters \"NaN\" —\n // producing `#NaN0000`, which is exactly the string this module documents itself as never\n // returning.\n const value = Number.isFinite(channel) ? clamp01(channel) : 0;\n return Math.round(value * 255)\n .toString(16)\n .padStart(2, \"0\");\n}\n\n/**\n * Read a hex colour, or `null` if the input is not one.\n *\n * Returns `null` rather than throwing or substituting black: this reads what someone is part-way\n * through typing, where \"not a colour yet\" is the ordinary case and neither an exception nor a\n * silent black is a useful answer. A caller decides whether to hold the last good value, show a\n * message, or wait.\n *\n * Both short forms are accepted because both are what people paste. `#abc` expands by REPEATING\n * each digit rather than padding with zero — `#abc` is `#aabbcc`, not `#a0b0c0` — which is what CSS\n * does and the only expansion under which `#fff` is white.\n *\n * @experimental\n */\nexport function parseHex(input: string): Rgba | null {\n const text = input.trim();\n if (!HEX.test(text)) return null;\n\n const digits = text.replace(\"#\", \"\");\n const short = digits.length < 6;\n const size = short ? 1 : 2;\n const channel = (index: number): number => {\n const slice = digits.slice(index * size, index * size + size);\n return parseInt(short ? slice + slice : slice, 16) / 255;\n };\n\n const hasAlpha = digits.length === 4 || digits.length === 8;\n return {\n r: channel(0),\n g: channel(1),\n b: channel(2),\n alpha: hasAlpha ? channel(3) : 1,\n };\n}\n\n/**\n * Write a colour as `#rrggbb`, or `#rrggbbaa` when it is not fully opaque.\n *\n * The alpha pair is omitted at 1 rather than always written, because `#3b82f6ff` is the same colour\n * and the shorter form is what someone expects to see in a field they typed `#3b82f6` into.\n *\n * Channels outside [0, 1] are clamped, so the result is always a valid six- or eight-digit hex\n * string whatever a caller passes. Not for floating-point drift, which rounds to the right byte on\n * its own: it is for a value that is wrong by a lot — a channel still in 0-255, or a computation\n * that overshot — where the alternative is emitting `#17f00-80`, a string nothing downstream can\n * parse and no error explains.\n *\n * @experimental\n */\nexport function toHex(color: Rgb, alpha = 1): string {\n // A non-finite alpha falls back to 1, not to 0 as a channel does. Both are \"nothing was\n // specified\", and for alpha that is this parameter's own default — where treating it as 0 would\n // turn a colour invisible on a stray NaN, silently and with no way to tell from the output.\n const opacity = Number.isFinite(alpha) ? clamp01(alpha) : 1;\n const opaque = `#${pair(color.r)}${pair(color.g)}${pair(color.b)}`;\n return opacity === 1 ? opaque : `${opaque}${pair(opacity)}`;\n}\n","/**\n * The WCAG 2.x contrast ratio, the one implementation of it in this package.\n *\n * Not exported from `@nextlyhq/ui/color`: which formula, which compositing\n * rule and which gamut-edge behaviour a contrast check uses are decisions this\n * package may need to revise, and publishing them would freeze them. It lives\n * here, with no imports, so the theme's build-time contrast check and the\n * runtime adjustment of brand colours ({@link readableOn}) read the same\n * formula rather than two copies of it.\n *\n * @module lib/color/wcag\n */\n\nimport type { Rgb } from \"./convert\";\n\n/** Linearize one gamma-encoded sRGB channel (the WCAG 2.x transfer function). */\nfunction channelToLinear(c: number): number {\n return c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4);\n}\n\n/** WCAG 2.x relative luminance of a gamma-encoded sRGB colour. */\nexport function relativeLuminance(rgb: Rgb): number {\n return (\n 0.2126 * channelToLinear(rgb.r) +\n 0.7152 * channelToLinear(rgb.g) +\n 0.0722 * channelToLinear(rgb.b)\n );\n}\n\n/**\n * WCAG 2.x contrast ratio between two OPAQUE colours, from 1:1 to 21:1. A\n * translucent colour must be composited over its surface first.\n */\nexport function contrastRatio(a: Rgb, b: Rgb): number {\n const la = relativeLuminance(a);\n const lb = relativeLuminance(b);\n return (Math.max(la, lb) + 0.05) / (Math.min(la, lb) + 0.05);\n}\n","/**\n * A colour made readable on the surfaces it is drawn on, by its lightness\n * alone.\n *\n * For colours that are not known when the theme is built, such as a tenant's\n * brand colours drawn as chart marks, and so cannot be held to a contrast\n * minimum by the theme's own test. The colour is never refused: one that\n * already reads is returned exactly as given, and one that does not keeps the\n * hue and chroma the tenant chose and moves its OKLCH lightness, as little as\n * it takes, until it reads on every surface. OKLCH because its lightness is\n * perceptual, so the smallest step there is the smallest change a reader sees.\n *\n * @module lib/color/readable-on\n */\n\nimport { oklchToRgb, rgbToOklch, type Oklch, type Rgb } from \"./convert\";\nimport { contrastRatio } from \"./wcag\";\n\n/** The step the lightness search takes, small beside what a reader can tell apart. */\nconst STEP = 0.001;\n\n/**\n * The colour as it will be drawn: each channel rounded to the 8 bits a hex\n * value carries. The ratio is checked on THIS, so a colour written out as hex\n * keeps the ratio it was found at.\n */\nfunction asDrawn(rgb: Rgb): Rgb {\n const round = (channel: number) => Math.round(channel * 255) / 255;\n return { r: round(rgb.r), g: round(rgb.g), b: round(rgb.b) };\n}\n\n/** The lowest ratio `color` has against any of `surfaces`. */\nfunction lowestRatio(color: Rgb, surfaces: readonly Rgb[]): number {\n let lowest = Number.POSITIVE_INFINITY;\n for (const surface of surfaces) {\n lowest = Math.min(lowest, contrastRatio(color, surface));\n }\n return lowest;\n}\n\n/**\n * `color`, or the nearest colour of its hue and chroma that reaches `minimum`\n * against every one of `surfaces`.\n *\n * Searches outward from the colour's own lightness, one step each way at a\n * time, and takes the first lightness that reads; where both directions read\n * at the same distance, the one reading better. Should no lightness reach the\n * minimum on every surface, it returns the one that comes closest: a brand\n * colour is adjusted, never refused.\n *\n * Chroma is reduced only where the display cannot show it at the new\n * lightness, which is `oklchToRgb`'s own rule; hue is kept.\n *\n * @experimental\n */\nexport function readableOn(\n color: Rgb,\n surfaces: readonly Rgb[],\n minimum: number = 3\n): Rgb {\n if (surfaces.length === 0 || lowestRatio(color, surfaces) >= minimum) {\n return color;\n }\n const oklch = rgbToOklch(color);\n const drawn = asDrawn(color);\n let best: Candidate = { rgb: drawn, ratio: lowestRatio(drawn, surfaces) };\n const steps = Math.ceil(1 / STEP);\n for (let i = 1; i <= steps; i += 1) {\n const candidates = candidatesAt(oklch, i * STEP, surfaces);\n best = betterOf(best, candidates);\n const reading = candidates.filter(c => c.ratio >= minimum);\n const [first] = reading;\n if (first !== undefined) return betterOf(first, reading).rgb;\n }\n return best.rgb;\n}\n\n/** A colour as drawn, with the lowest ratio it reaches on the surfaces. */\ninterface Candidate {\n rgb: Rgb;\n ratio: number;\n}\n\n/**\n * The colours `distance` either side of `oklch`'s lightness, darker first, as\n * drawn and with their lowest ratio; none past black or white.\n */\nfunction candidatesAt(\n oklch: Oklch,\n distance: number,\n surfaces: readonly Rgb[]\n): Candidate[] {\n return [oklch.l - distance, oklch.l + distance]\n .filter(lightness => lightness >= 0 && lightness <= 1)\n .map(lightness => {\n const rgb = asDrawn(oklchToRgb({ ...oklch, l: lightness }));\n return { rgb, ratio: lowestRatio(rgb, surfaces) };\n });\n}\n\n/** The best-reading of `current` and `candidates`, the earlier one on a tie. */\nfunction betterOf(\n current: Candidate,\n candidates: readonly Candidate[]\n): Candidate {\n return candidates.reduce(\n (kept, next) => (next.ratio > kept.ratio ? next : kept),\n current\n );\n}\n","/**\n * The mapping between a pointer on a picker surface and a colour.\n *\n * Kept apart from the component for two reasons. It is arithmetic on numbers,\n * so it belongs on the server-safe side with the rest of `@nextlyhq/ui/color`;\n * and a saturation square is the one part of a picker that cannot be checked by\n * rendering it — jsdom reports every element as zero-sized, so a component test\n * measures nothing and passes. Measured here instead, against known corners.\n *\n * @module lib/color/picker-geometry\n */\n\n/** A position on a surface, each axis in [0, 1] from the top-left. */\nexport interface SurfacePoint {\n x: number;\n y: number;\n}\n\nconst clamp01 = (n: number): number => (n < 0 ? 0 : n > 1 ? 1 : n);\n\n/**\n * A pointer position as a fraction of a surface.\n *\n * Clamped, because a drag that begins inside the surface continues to report\n * while the pointer leaves it — which is the interaction people actually use to\n * reach full saturation, and without clamping it produces values outside the\n * colour space rather than the corner they are aiming at.\n *\n * A zero-sized surface answers the top-left rather than dividing by zero. That\n * happens in a test environment and on the first frame before layout.\n *\n * @experimental\n */\nexport function pointOnSurface(\n clientX: number,\n clientY: number,\n rect: { left: number; top: number; width: number; height: number }\n): SurfacePoint {\n return {\n x: rect.width === 0 ? 0 : clamp01((clientX - rect.left) / rect.width),\n y: rect.height === 0 ? 0 : clamp01((clientY - rect.top) / rect.height),\n };\n}\n\n/**\n * The saturation and value a point on the square stands for.\n *\n * Value runs UPWARD while a surface's y runs downward, so the vertical axis is\n * inverted here. Getting that wrong produces a picker that looks correct and\n * selects the colour vertically mirrored from the one under the cursor.\n *\n * @experimental\n */\nexport function saturationValueAt(point: SurfacePoint): {\n s: number;\n v: number;\n} {\n return { s: clamp01(point.x), v: 1 - clamp01(point.y) };\n}\n\n/**\n * Where the handle sits for a given saturation and value — the inverse of\n * {@link saturationValueAt}.\n *\n * Derived from that function's own inversion rather than written independently,\n * so the two cannot disagree about which way the axis runs.\n *\n * @experimental\n */\nexport function surfacePointFor(s: number, v: number): SurfacePoint {\n return { x: clamp01(s), y: 1 - clamp01(v) };\n}\n\n/**\n * The hue a horizontal position stands for, in [0, 360).\n *\n * The upper bound is exclusive: 360 and 0 are the same hue, and returning 360\n * lets a handle at the far end read back as a position outside the strip.\n *\n * @experimental\n */\nexport function hueAt(fraction: number): number {\n const hue = clamp01(fraction) * 360;\n return hue >= 360 ? 0 : hue;\n}\n\n/** Where the hue handle sits, as a fraction of the strip. @experimental */\nexport function huePosition(hue: number): number {\n const wrapped = ((hue % 360) + 360) % 360;\n return wrapped / 360;\n}\n\n/**\n * The integer step a hue occupies on a strip whose last step is `max`.\n *\n * Rounding is what makes this more than a multiplication. A hue just below 360\n * — `#ff0001` is about 359.76 — rounds UP to a step past the end of the strip,\n * and the obvious repair of wrapping it with a modulo sends it to 0: the far\n * LEFT, the opposite end from where that colour belongs. The handle then sits\n * on the wrong side and any keyboard adjustment starts from there. Held at the\n * last step instead, which is where it visually belongs.\n *\n * @experimental\n */\nexport function hueSliderValue(hue: number, max: number): number {\n const step = Math.round(huePosition(hue) * (max + 1));\n return step > max ? max : step;\n}\n"],"mappings":";AA8DA,MAAMA,aAAW,MAAuB,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI;;;;;;;;AAShE,MAAM,kBAAkB;;;;;;AAOxB,SAAgB,aAAa,KAAqB;CAChD,IAAI,CAAC,OAAO,SAAS,GAAG,GAAG,OAAO;CAClC,MAAM,UAAU,MAAM;CACtB,OAAO,UAAU,IAAI,UAAU,MAAM;AACvC;;;;;;;;AASA,SAAgB,SAAS,EAAE,GAAG,GAAG,KAAe;CAC9C,MAAM,MAAM,aAAa,CAAC;CAC1B,MAAM,MAAMA,UAAQ,CAAC;CACrB,MAAM,MAAMA,UAAQ,CAAC;CAErB,MAAM,SAAS,MAAM;CACrB,MAAM,SAAS,MAAM;CAErB,MAAM,IAAI,UAAU,IAAI,KAAK,IAAK,SAAS,IAAK,CAAC;CACjD,MAAM,OAAO,MAAM;CAEnB,IAAI;CACJ,IAAI,SAAS,GAAG,MAAM;EAAC;EAAQ;EAAG;CAAC;MAC9B,IAAI,SAAS,GAAG,MAAM;EAAC;EAAG;EAAQ;CAAC;MACnC,IAAI,SAAS,GAAG,MAAM;EAAC;EAAG;EAAQ;CAAC;MACnC,IAAI,SAAS,GAAG,MAAM;EAAC;EAAG;EAAG;CAAM;MACnC,IAAI,SAAS,GAAG,MAAM;EAAC;EAAG;EAAG;CAAM;MACnC,MAAM;EAAC;EAAQ;EAAG;CAAC;CAExB,OAAO;EAAE,GAAG,IAAI,KAAK;EAAM,GAAG,IAAI,KAAK;EAAM,GAAG,IAAI,KAAK;CAAK;AAChE;;;;;;;;;;AAWA,SAAgB,SAAS,EAAE,GAAG,GAAG,KAAe;CAC9C,MAAM,MAAMA,UAAQ,CAAC;CACrB,MAAM,QAAQA,UAAQ,CAAC;CACvB,MAAM,OAAOA,UAAQ,CAAC;CAEtB,MAAM,MAAM,KAAK,IAAI,KAAK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,CAAC;CAAE;AAC5C;;;;;;;;;AAUA,SAAgB,MAAM,UAA0B;CAC9C,MAAM,MAAM,QAAQ,QAAQ,IAAI;CAChC,OAAO,OAAO,MAAM,IAAI;AAC1B;;AAGA,SAAgB,YAAY,KAAqB;CAE/C,QADkB,MAAM,MAAO,OAAO,MACrB;AACnB;;;;;;;;;;;;;AAcA,SAAgB,eAAe,KAAa,KAAqB;CAC/D,MAAM,OAAO,KAAK,MAAM,YAAY,GAAG,KAAK,MAAM,EAAE;CACpD,OAAO,OAAO,MAAM,MAAM;AAC5B"}
@@ -0,0 +1,77 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ // src/lib/format/number.ts
3
+ const COMPACT_FROM = 1e3;
4
+ const groupedCache = /* @__PURE__ */ new Map();
5
+ const compactCache = /* @__PURE__ */ new Map();
6
+ function grouped(locale) {
7
+ let f = groupedCache.get(locale);
8
+ if (!f) {
9
+ f = new Intl.NumberFormat(locale);
10
+ groupedCache.set(locale, f);
11
+ }
12
+ return f;
13
+ }
14
+ function compact(locale) {
15
+ let f = compactCache.get(locale);
16
+ if (!f) {
17
+ f = new Intl.NumberFormat(locale, {
18
+ notation: "compact",
19
+ maximumFractionDigits: 1
20
+ });
21
+ compactCache.set(locale, f);
22
+ }
23
+ return f;
24
+ }
25
+ /**
26
+ * @experimental Format a count, total or chart value.
27
+ *
28
+ * Compact form ("1.2k", "3.4M") only in the small tier and only from 1,000; the thousands
29
+ * suffix is lowercased and the larger ones keep their capitals, so "M" (million) cannot be
30
+ * read as "m" (metres, or milli). The accessible name is always the full grouped value.
31
+ *
32
+ * @example
33
+ * formatCount(1248, { tier: "small" }) // { text: "1.2k", label: "1,248" }
34
+ * formatCount(1248, { tier: "medium" }) // { text: "1,248", label: "1,248" }
35
+ * formatCount(100, { floor: true }) // { text: "100+", label: "100 or more" }
36
+ */
37
+ function formatCount(value, options = {}) {
38
+ const locale = options.locale ?? "en-US";
39
+ const full = grouped(locale).format(value);
40
+ const shown = options.tier === "small" && Math.abs(value) >= COMPACT_FROM ? compact(locale).format(value).replace(/K$/, "k") : full;
41
+ return options.floor ? {
42
+ text: `${shown}+`,
43
+ label: `${full} or more`
44
+ } : {
45
+ text: shown,
46
+ label: full
47
+ };
48
+ }
49
+ /**
50
+ * @experimental Format a change against an earlier period.
51
+ *
52
+ * The direction is carried by an arrow AND a sign, so it reads without colour (WCAG 1.4.1):
53
+ * "↑ +18", "↓ −18", "→ ±0". The accessible name says it in words: "up 18", "down 18",
54
+ * "no change". The minus is U+2212, which screen readers and typography both treat as a minus
55
+ * rather than a hyphen.
56
+ */
57
+ function formatChange(delta, options = {}) {
58
+ const magnitude = formatCount(Math.abs(delta), options);
59
+ if (delta === 0) return {
60
+ text: "→ ±0",
61
+ label: "no change",
62
+ direction: "none"
63
+ };
64
+ return delta > 0 ? {
65
+ text: `↑ +${magnitude.text}`,
66
+ label: `up ${magnitude.label}`,
67
+ direction: "up"
68
+ } : {
69
+ text: `↓ −${magnitude.text}`,
70
+ label: `down ${magnitude.label}`,
71
+ direction: "down"
72
+ };
73
+ }
74
+ exports.formatChange = formatChange;
75
+ exports.formatCount = formatCount;
76
+
77
+ //# sourceMappingURL=format.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"format.cjs","names":[],"sources":["../src/lib/format/number.ts"],"sourcesContent":["/**\n * The one number formatter for dashboard cards.\n *\n * Every figure a card shows -- a count, a chart value, a tooltip, a table cell, a text\n * alternative -- goes through here, so the same number reads the same everywhere it appears.\n * Two figures for one value that disagree (\"1.2k\" in a chart, \"1,248\" in its table, \"1248\" in\n * its description) are what this exists to make impossible.\n *\n * It is pure arithmetic on numbers with `Intl.NumberFormat`: no React, no DOM, so a server can\n * format the same way the admin does.\n *\n * @module lib/format/number\n */\n\n/**\n * @experimental The size a card is drawn at, from its own width. Compact numbers appear only in the small\n * tier, where a full grouped value would not fit; everywhere else the exact value fits and is\n * shown.\n */\nexport type SizeTier = \"small\" | \"medium\" | \"large\";\n\n/** @experimental How a count is formatted: its locale, its card's tier, and whether it is a floor. */\nexport interface FormatCountOptions {\n /** The admin's locale. Defaults to `en-US`, the admin's own default. */\n locale?: string;\n /** The tier the figure is drawn in. Only `small` compacts. */\n tier?: SizeTier;\n /**\n * The value is a lower bound: a source that stops counting at a limit knows only \"at\n * least this many\". Shown as \"N+\" and named \"N or more\".\n */\n floor?: boolean;\n}\n\n/** @experimental What a figure looks like, and what assistive technology hears for it. */\nexport interface FormattedNumber {\n /** Drawn on screen: \"1,248\", \"1.2k\", \"100+\". */\n text: string;\n /**\n * The accessible name: always the full grouped value, so \"1.2k\" is heard as \"1,248\"; a\n * floor is heard as \"100 or more\", never as a bare \"100\".\n */\n label: string;\n}\n\nconst COMPACT_FROM = 1000;\n\n// Intl formatters are costly to build and a dashboard formats hundreds of figures, so one of\n// each kind is kept per locale.\nconst groupedCache = new Map<string, Intl.NumberFormat>();\nconst compactCache = new Map<string, Intl.NumberFormat>();\n\nfunction grouped(locale: string): Intl.NumberFormat {\n let f = groupedCache.get(locale);\n if (!f) {\n f = new Intl.NumberFormat(locale);\n groupedCache.set(locale, f);\n }\n return f;\n}\n\nfunction compact(locale: string): Intl.NumberFormat {\n let f = compactCache.get(locale);\n if (!f) {\n f = new Intl.NumberFormat(locale, {\n notation: \"compact\",\n maximumFractionDigits: 1,\n });\n compactCache.set(locale, f);\n }\n return f;\n}\n\n/**\n * @experimental Format a count, total or chart value.\n *\n * Compact form (\"1.2k\", \"3.4M\") only in the small tier and only from 1,000; the thousands\n * suffix is lowercased and the larger ones keep their capitals, so \"M\" (million) cannot be\n * read as \"m\" (metres, or milli). The accessible name is always the full grouped value.\n *\n * @example\n * formatCount(1248, { tier: \"small\" }) // { text: \"1.2k\", label: \"1,248\" }\n * formatCount(1248, { tier: \"medium\" }) // { text: \"1,248\", label: \"1,248\" }\n * formatCount(100, { floor: true }) // { text: \"100+\", label: \"100 or more\" }\n */\nexport function formatCount(\n value: number,\n options: FormatCountOptions = {}\n): FormattedNumber {\n const locale = options.locale ?? \"en-US\";\n const full = grouped(locale).format(value);\n const shown =\n options.tier === \"small\" && Math.abs(value) >= COMPACT_FROM\n ? compact(locale)\n .format(value)\n // \"1.2K\" -> \"1.2k\"; \"3.4M\" and \"1.2B\" keep their capitals.\n .replace(/K$/, \"k\")\n : full;\n return options.floor\n ? { text: `${shown}+`, label: `${full} or more` }\n : { text: shown, label: full };\n}\n\n/** @experimental Which way a change goes, for styling; never the only signal (the arrow and sign are). */\nexport type ChangeDirection = \"up\" | \"down\" | \"none\";\n\n/** @experimental A formatted change, with its direction. */\nexport interface FormattedChange extends FormattedNumber {\n direction: ChangeDirection;\n}\n\n/**\n * @experimental Format a change against an earlier period.\n *\n * The direction is carried by an arrow AND a sign, so it reads without colour (WCAG 1.4.1):\n * \"↑ +18\", \"↓ −18\", \"→ ±0\". The accessible name says it in words: \"up 18\", \"down 18\",\n * \"no change\". The minus is U+2212, which screen readers and typography both treat as a minus\n * rather than a hyphen.\n */\nexport function formatChange(\n delta: number,\n options: Omit<FormatCountOptions, \"floor\"> = {}\n): FormattedChange {\n const magnitude = formatCount(Math.abs(delta), options);\n if (delta === 0) {\n return { text: \"→ ±0\", label: \"no change\", direction: \"none\" };\n }\n return delta > 0\n ? {\n text: `↑ +${magnitude.text}`,\n label: `up ${magnitude.label}`,\n direction: \"up\",\n }\n : {\n text: `↓ −${magnitude.text}`,\n label: `down ${magnitude.label}`,\n direction: \"down\",\n };\n}\n"],"mappings":";;AA6CA,MAAM,eAAe;AAIrB,MAAM,+BAAe,IAAI,IAA+B;AACxD,MAAM,+BAAe,IAAI,IAA+B;AAExD,SAAS,QAAQ,QAAmC;CAClD,IAAI,IAAI,aAAa,IAAI,MAAM;CAC/B,IAAI,CAAC,GAAG;EACN,IAAI,IAAI,KAAK,aAAa,MAAM;EAChC,aAAa,IAAI,QAAQ,CAAC;CAC5B;CACA,OAAO;AACT;AAEA,SAAS,QAAQ,QAAmC;CAClD,IAAI,IAAI,aAAa,IAA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