@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/README.md CHANGED
@@ -31,32 +31,67 @@ pnpm add react react-dom lucide-react
31
31
 
32
32
  ## Setup
33
33
 
34
- The components ship as Tailwind CSS 4 token consumers. They reference HSL CSS variables (`--background`, `--primary`, `--border`, etc.) which your project must define.
34
+ The package ships three CSS entry points. Pick one:
35
35
 
36
- **Tailwind v4 (recommended)**
36
+ **Zero config — pre-compiled bundle**
37
37
 
38
- In your global CSS, define the design tokens with `@theme` and import the components:
38
+ Import the pre-built stylesheet once at your root. It bundles Tailwind, every design token
39
+ (on `:root`, flipped under `.dark`), and the base reset, so components render fully styled
40
+ with no build wiring:
41
+
42
+ ```tsx
43
+ import "@nextlyhq/ui/styles.css";
44
+ import { Button } from "@nextlyhq/ui";
45
+
46
+ <Button variant="outline">Click me</Button>;
47
+ ```
48
+
49
+ **Bring your own Tailwind v4 build**
50
+
51
+ If you already run Tailwind v4, import just the tokens and let your pipeline compile the
52
+ utilities the components use:
39
53
 
40
54
  ```css
41
55
  /* app/globals.css */
42
56
  @import "tailwindcss";
43
-
44
- @theme {
45
- --color-background: hsl(0 0% 100%);
46
- --color-foreground: hsl(222 47% 11%);
47
- --color-primary: hsl(221 83% 53%);
48
- --color-primary-foreground: hsl(0 0% 100%);
49
- /* ...the rest. See `uiPreset` for the full token contract. */
50
- }
57
+ @import "@nextlyhq/ui/theme.css";
58
+ @source "../node_modules/@nextlyhq/ui/dist";
51
59
  ```
52
60
 
53
- The exported `uiPreset` is the reference contract: it lists every token name the components expect. Use it to write the matching `@theme` block (or import it directly if you are still on Tailwind v3).
61
+ `theme.css` defines the tokens as complete OKLCH color values (`--nx-background`, `--nx-primary`,
62
+ `--nx-border`, …) with `@theme inline` mappings and the dark-mode overrides. Reference tokens
63
+ directly (`var(--nx-primary)`) — never wrap them in `hsl()`.
64
+
65
+ **Bring your own Tailwind v3 build**
66
+
67
+ `uiPreset` from `@nextlyhq/ui/tailwind-preset` maps the same tokens to v3 utilities:
68
+
69
+ ```js
70
+ // tailwind.config.js
71
+ const { uiPreset } = require("@nextlyhq/ui/tailwind-preset");
72
+
73
+ module.exports = {
74
+ presets: [uiPreset],
75
+ content: [
76
+ "./src/**/*.{js,jsx,ts,tsx}",
77
+ // Required. Tailwind generates a utility only for a class it has SEEN, and
78
+ // the classes these components write live in the published bundle rather
79
+ // than in your source. Omit this path and the components render with their
80
+ // utilities missing — no error, just unstyled markup.
81
+ "./node_modules/@nextlyhq/ui/dist/**/*.{js,mjs,cjs}",
82
+ ],
83
+ };
84
+ ```
54
85
 
55
- ```tsx
56
- import { Button } from "@nextlyhq/ui";
86
+ Import `@nextlyhq/ui/theme.css` alongside it. The preset carries tokens and the utilities
87
+ derived from them; a handful of components also write their own classes — `nx-page-shell`,
88
+ `nx-bleed`, `nx-form-section-rows` — and the rules behind those classes are CSS, shipped in
89
+ `theme.css` for every consumer alike. Scanning a component finds the class it writes, never
90
+ the rule, so a build with the preset and no stylesheet renders those components unstyled
91
+ without erroring.
57
92
 
58
- <Button variant="outline">Click me</Button>;
59
- ```
93
+ > Inside a Nextly admin plugin you need neither import — the admin already provides the
94
+ > tokens. See the [**Plugin UI authoring guide**](./docs/plugin-ui-authoring.md).
60
95
 
61
96
  ## Components
62
97
 
@@ -64,23 +99,93 @@ import { Button } from "@nextlyhq/ui";
64
99
  **Display:** `Badge`, `Card`, `Alert`, `Separator`, `Skeleton`, `Progress`
65
100
  **Toggles:** `Checkbox`, `RadioGroup`, `Switch`, `Collapsible`
66
101
  **Layout and disclosure:** `Accordion`, `Avatar`, `Tabs`, `Tooltip`, `Popover`
102
+ **Resizable regions:** `ResizablePanelGroup`, `ResizablePanel`, `ResizableHandle`
103
+ **Hierarchies:** `TreeView` (virtualized, keyboard-operable)
67
104
  **Overlays:** `Dialog`, `AlertDialog`, `Sheet`
68
- **Menus and command palette:** `DropdownMenu`, `Select`, `Command`
105
+ **Menus and command palette:** `DropdownMenu`, `ContextMenu`, `Select`, `Command`
69
106
  **Feedback:** `Spinner`, `Toaster` (with `toast()` helper)
70
107
  **Tables:** `Table` primitives, `ResponsiveTable`, `TableSearch`, `TablePagination`, `TableSkeleton`, `TableEmpty`, `TableError`, `TableLoading`
71
108
  **Providers:** `PortalProvider`, `usePortalContainer`
72
- **Utilities:** `cn`, `uiPreset`
109
+
110
+ > Which of these carry a stability guarantee is recorded in
111
+ > [STABILITY.md](https://github.com/nextlyhq/nextly/blob/main/packages/ui/STABILITY.md). A component becomes `@public` once a first-party
112
+ > plugin depends on it; everything else is `@experimental` and may change in any
113
+ > release.
114
+
115
+ **Utilities:** `cn` (from `@nextlyhq/ui/utils`), `uiPreset` (from `@nextlyhq/ui/tailwind-preset`)
116
+
117
+ > Both ship from their own subpaths rather than the root: the root bundle is
118
+ > published with `"use client"`, and neither of these contains a React runtime,
119
+ > so a server component or a Tailwind config can import them safely.
120
+
121
+ ## Stylesheets
122
+
123
+ | Import | Use when |
124
+ | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
125
+ | `@nextlyhq/ui/styles.css` | The app is yours end to end. Styles the whole document, Tailwind preflight included. |
126
+ | `@nextlyhq/ui/styles.scoped.css` | Dropping a few components into an existing app. Every rule is confined to `.nextly-ui`, so the rest of the page keeps its own styles. |
127
+ | `@nextlyhq/ui/theme.css` | You compile Tailwind yourself. Carries the token contract and the component rules; required on both the v4 and the v3-preset path. |
128
+
129
+ The scoped sheet needs a wrapper element, and dark mode goes on the same element:
130
+
131
+ ```tsx
132
+ import "@nextlyhq/ui/styles.scoped.css";
133
+
134
+ <div className="nextly-ui">
135
+ <Button>Save</Button>
136
+ </div>;
137
+ ```
138
+
139
+ It keeps preflight rather than dropping it — these components are designed against a
140
+ normalised baseline — but confines it to the wrapper, so your headings, lists and form
141
+ controls outside it are untouched. Three things CSS resolves globally are namespaced
142
+ along with the selectors, so the sheet cannot reach outside the wrapper through them
143
+ either: animation names (it will not displace a `spin` or `fade-in` you define),
144
+ Tailwind's internal `--tw-*` registrations, and the ancestor classes `dark:` and
145
+ `group-*:` variants look for. Dark mode is therefore driven by the wrapper, not by a
146
+ `dark` class higher up your page.
147
+
148
+ ### Overlays need a portal container
149
+
150
+ AlertDialog, Command, ContextMenu, Dialog, DropdownMenu, Popover, Select, Sheet and
151
+ Tooltip render
152
+ their overlay through a portal, which defaults to `document.body` — outside the wrapper,
153
+ where the scoped rules and tokens do not reach. Triggers would look right and the menus
154
+ they open would not. Point them back inside with `PortalProvider`:
155
+
156
+ ```tsx
157
+ import { useState } from "react";
158
+ import { PortalProvider } from "@nextlyhq/ui";
159
+ import "@nextlyhq/ui/styles.scoped.css";
160
+
161
+ function Kit({ children }: { children: React.ReactNode }) {
162
+ const [container, setContainer] = useState<HTMLElement | null>(null);
163
+
164
+ return (
165
+ <div className="nextly-ui" ref={setContainer}>
166
+ <PortalProvider container={container}>{children}</PortalProvider>
167
+ </div>
168
+ );
169
+ }
170
+ ```
171
+
172
+ A callback ref rather than `useRef` because the container has to be a state value: on the
173
+ first render it is still `null`, and the overlays need a re-render once the element exists.
174
+
175
+ This does not apply to `styles.css`, where the rules are document-wide and
176
+ `document.body` is already covered.
73
177
 
74
178
  ## Compatibility
75
179
 
76
- | Tool | Version |
77
- | -------------- | ---------------------------------------------------------------- |
78
- | React | 18 or 19 |
79
- | Tailwind CSS | 4+ (the `uiPreset` JS export also works as a Tailwind v3 preset) |
80
- | `lucide-react` | 0.400+ |
180
+ | Tool | Version |
181
+ | -------------- | ---------------------------------------------------------------------------------------- |
182
+ | React | 18 or 19 |
183
+ | Tailwind CSS | 4+ (`@nextlyhq/ui/tailwind-preset` also works as a Tailwind v3 preset, with `theme.css`) |
184
+ | `lucide-react` | 0.400+ |
81
185
 
82
186
  ## Documentation
83
187
 
188
+ - [**Plugin UI authoring guide**](./docs/plugin-ui-authoring.md): the token contract, dark mode, container queries, and the design lint guard
84
189
  - [**Admin customization**](https://nextlyhq.com/docs/admin/customization): theming, branding, and custom field UIs
85
190
 
86
191
  ## Related packages
package/dist/color.cjs ADDED
@@ -0,0 +1,472 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ // src/lib/color/convert.ts
3
+ const clamp01$2 = (n) => n < 0 ? 0 : n > 1 ? 1 : n;
4
+ /**
5
+ * A chroma no displayable sRGB colour exceeds.
6
+ *
7
+ * The most saturated sRGB primaries sit near 0.37 in OKLCH; this leaves headroom above that and
8
+ * gives the gamut search a fixed bracket, so its error is absolute rather than proportional to
9
+ * whatever the caller asked for.
10
+ */
11
+ const MAX_SRGB_CHROMA = .5;
12
+ /**
13
+ * Wrap a hue into [0, 360), so -30 and 330 are the same angle.
14
+ *
15
+ * @experimental
16
+ */
17
+ function normalizeHue(hue) {
18
+ if (!Number.isFinite(hue)) return 0;
19
+ const wrapped = hue % 360;
20
+ return wrapped < 0 ? wrapped + 360 : wrapped;
21
+ }
22
+ /**
23
+ * HSV to sRGB.
24
+ * Saturation and value are clamped rather than rejected: a picker drags them, and a drag that
25
+ * overshoots by a rounding error should saturate rather than throw.
26
+ *
27
+ * @experimental
28
+ */
29
+ function hsvToRgb({ h, s, v }) {
30
+ const hue = normalizeHue(h);
31
+ const sat = clamp01$2(s);
32
+ const val = clamp01$2(v);
33
+ const sector = hue / 60;
34
+ const chroma = val * sat;
35
+ const x = chroma * (1 - Math.abs(sector % 2 - 1));
36
+ const base = val - chroma;
37
+ let rgb;
38
+ if (sector < 1) rgb = [
39
+ chroma,
40
+ x,
41
+ 0
42
+ ];
43
+ else if (sector < 2) rgb = [
44
+ x,
45
+ chroma,
46
+ 0
47
+ ];
48
+ else if (sector < 3) rgb = [
49
+ 0,
50
+ chroma,
51
+ x
52
+ ];
53
+ else if (sector < 4) rgb = [
54
+ 0,
55
+ x,
56
+ chroma
57
+ ];
58
+ else if (sector < 5) rgb = [
59
+ x,
60
+ 0,
61
+ chroma
62
+ ];
63
+ else rgb = [
64
+ chroma,
65
+ 0,
66
+ x
67
+ ];
68
+ return {
69
+ r: rgb[0] + base,
70
+ g: rgb[1] + base,
71
+ b: rgb[2] + base
72
+ };
73
+ }
74
+ /**
75
+ * sRGB to HSV.
76
+ * Hue is UNDEFINED for a grey and value is undefined for black, and this returns 0 for both. A
77
+ * picker must not take that 0 as the user's hue: it is the absence of one. Holding hue across a
78
+ * drag to zero saturation is the caller's job, which is why a picker keeps HSV as its state
79
+ * rather than deriving it from the colour each render.
80
+ *
81
+ * @experimental
82
+ */
83
+ function rgbToHsv({ r, g, b }) {
84
+ const red = clamp01$2(r);
85
+ const green = clamp01$2(g);
86
+ const blue = clamp01$2(b);
87
+ const max = Math.max(red, green, blue);
88
+ const chroma = max - Math.min(red, green, blue);
89
+ let hue = 0;
90
+ if (chroma !== 0) {
91
+ if (max === red) hue = (green - blue) / chroma % 6;
92
+ else if (max === green) hue = (blue - red) / chroma + 2;
93
+ else hue = (red - green) / chroma + 4;
94
+ hue *= 60;
95
+ }
96
+ return {
97
+ h: normalizeHue(hue),
98
+ s: max === 0 ? 0 : chroma / max,
99
+ v: max
100
+ };
101
+ }
102
+ /** The sRGB transfer function, gamma-encoded to linear light. */
103
+ function toLinear(channel) {
104
+ return channel <= .04045 ? channel / 12.92 : Math.pow((channel + .055) / 1.055, 2.4);
105
+ }
106
+ /** The inverse transfer function, linear light back to gamma-encoded. */
107
+ function toGamma(channel) {
108
+ return channel <= .0031308 ? channel * 12.92 : 1.055 * Math.pow(channel, 1 / 2.4) - .055;
109
+ }
110
+ /**
111
+ * Linear sRGB to OKLab.
112
+ *
113
+ * The two matrices and the cube root between them are the definition of OKLab, given in CSS
114
+ * Color 4. They are transcribed rather than derived.
115
+ */
116
+ function linearRgbToOklab(r, g, b) {
117
+ const l = .4122214708 * r + .5363325363 * g + .0514459929 * b;
118
+ const m = .2119034982 * r + .6806995451 * g + .1073969566 * b;
119
+ const s = .0883024619 * r + .2817188376 * g + .6299787005 * b;
120
+ const l_ = Math.cbrt(l);
121
+ const m_ = Math.cbrt(m);
122
+ const s_ = Math.cbrt(s);
123
+ return [
124
+ .2104542553 * l_ + .793617785 * m_ - .0040720468 * s_,
125
+ 1.9779984951 * l_ - 2.428592205 * m_ + .4505937099 * s_,
126
+ .0259040371 * l_ + .7827717662 * m_ - .808675766 * s_
127
+ ];
128
+ }
129
+ /** OKLab back to linear sRGB, the inverse of {@link linearRgbToOklab}. */
130
+ function oklabToLinearRgb(L, a, b) {
131
+ const l_ = L + .3963377774 * a + .2158037573 * b;
132
+ const m_ = L - .1055613458 * a - .0638541728 * b;
133
+ const s_ = L - .0894841775 * a - 1.291485548 * b;
134
+ const l = l_ * l_ * l_;
135
+ const m = m_ * m_ * m_;
136
+ const s = s_ * s_ * s_;
137
+ return [
138
+ 4.0767416621 * l - 3.3077115913 * m + .2309699292 * s,
139
+ -1.2684380046 * l + 2.6097574011 * m - .3413193965 * s,
140
+ -.0041960863 * l - .7034186147 * m + 1.707614701 * s
141
+ ];
142
+ }
143
+ /**
144
+ * sRGB to OKLCH.
145
+ *
146
+ * @experimental
147
+ */
148
+ function rgbToOklch({ r, g, b }) {
149
+ const [L, A, B] = linearRgbToOklab(toLinear(clamp01$2(r)), toLinear(clamp01$2(g)), toLinear(clamp01$2(b)));
150
+ const chroma = Math.sqrt(A * A + B * B);
151
+ return {
152
+ l: L,
153
+ c: chroma,
154
+ h: chroma < 1e-6 ? 0 : normalizeHue(Math.atan2(B, A) * 180 / Math.PI)
155
+ };
156
+ }
157
+ /** Whether every channel of a linear triple lies within the displayable range. */
158
+ function inGamut([r, g, b]) {
159
+ return r >= -0 && r <= 1 && g >= -0 && g <= 1 && b >= -0 && b <= 1;
160
+ }
161
+ /**
162
+ * OKLCH to sRGB, reducing chroma until the colour fits on screen.
163
+ * OKLCH can name colours a display cannot show. Clamping the channels independently is the
164
+ * obvious response and the wrong one: clipping red without clipping green changes the ratio
165
+ * between them, so the colour that appears is a DIFFERENT HUE from the one asked for. Lightness
166
+ * and hue are what a person chose; chroma is the part they will not miss, so chroma is what is
167
+ * given up.
168
+ * The search is a bisection on chroma, which converges to well under a perceptible step in the
169
+ * fixed number of rounds below — no loop that might not terminate.
170
+ *
171
+ * **The gamut is not always monotonic along this ray, and that is a deliberate trade.** At some
172
+ * lightness and hue pairs the boundary is crossed more than once: at `l = 0.2, h = 264.1` the ray
173
+ * is inside up to c ≈ 0.1192, outside until c ≈ 0.1368, briefly inside again to c ≈ 0.1386. A
174
+ * bisection therefore finds the FIRST boundary rather than the outermost reachable chroma.
175
+ *
176
+ * That is the intended behaviour rather than a limitation. Those islands span roughly a tenth of
177
+ * a degree of hue, so preferring the outermost value would make chroma jump by about 0.021
178
+ * between h = 264.05 and h = 264.10 — a visible step while dragging a hue slider, over a change
179
+ * no one can aim at. Taking the first boundary gives 0.1160, 0.1175, 0.1192, 0.1255, 0.1383
180
+ * across the same sweep: continuous, and one step less saturated at worst. It is also what the
181
+ * CSS Color 4 gamut-mapping algorithm does.
182
+ *
183
+ * @experimental
184
+ */
185
+ function oklchToRgb({ l, c, h }) {
186
+ const lightness = clamp01$2(l);
187
+ const hueRadians = normalizeHue(h) * Math.PI / 180;
188
+ const at = (chroma) => oklabToLinearRgb(lightness, chroma * Math.cos(hueRadians), chroma * Math.sin(hueRadians));
189
+ const requested = Math.max(0, c);
190
+ let fitting = at(requested);
191
+ if (!inGamut(fitting)) {
192
+ let low = 0;
193
+ let high = Math.min(requested, MAX_SRGB_CHROMA);
194
+ for (let i = 0; i < 20; i++) {
195
+ const mid = (low + high) / 2;
196
+ if (inGamut(at(mid))) low = mid;
197
+ else high = mid;
198
+ }
199
+ fitting = at(low);
200
+ }
201
+ return {
202
+ r: clamp01$2(toGamma(fitting[0])),
203
+ g: clamp01$2(toGamma(fitting[1])),
204
+ b: clamp01$2(toGamma(fitting[2]))
205
+ };
206
+ }
207
+ // src/lib/color/hex.ts
208
+ /** `#rgb`, `#rgba`, `#rrggbb` or `#rrggbbaa`, with the hash optional and case ignored. */
209
+ const HEX = /^#?(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i;
210
+ const clamp01$1 = (n) => n < 0 ? 0 : n > 1 ? 1 : n;
211
+ /** A channel byte as a two-digit lowercase pair. */
212
+ function pair(channel) {
213
+ const value = Number.isFinite(channel) ? clamp01$1(channel) : 0;
214
+ return Math.round(value * 255).toString(16).padStart(2, "0");
215
+ }
216
+ /**
217
+ * Read a hex colour, or `null` if the input is not one.
218
+ *
219
+ * Returns `null` rather than throwing or substituting black: this reads what someone is part-way
220
+ * through typing, where "not a colour yet" is the ordinary case and neither an exception nor a
221
+ * silent black is a useful answer. A caller decides whether to hold the last good value, show a
222
+ * message, or wait.
223
+ *
224
+ * Both short forms are accepted because both are what people paste. `#abc` expands by REPEATING
225
+ * each digit rather than padding with zero — `#abc` is `#aabbcc`, not `#a0b0c0` — which is what CSS
226
+ * does and the only expansion under which `#fff` is white.
227
+ *
228
+ * @experimental
229
+ */
230
+ function parseHex(input) {
231
+ const text = input.trim();
232
+ if (!HEX.test(text)) return null;
233
+ const digits = text.replace("#", "");
234
+ const short = digits.length < 6;
235
+ const size = short ? 1 : 2;
236
+ const channel = (index) => {
237
+ const slice = digits.slice(index * size, index * size + size);
238
+ return parseInt(short ? slice + slice : slice, 16) / 255;
239
+ };
240
+ const hasAlpha = digits.length === 4 || digits.length === 8;
241
+ return {
242
+ r: channel(0),
243
+ g: channel(1),
244
+ b: channel(2),
245
+ alpha: hasAlpha ? channel(3) : 1
246
+ };
247
+ }
248
+ /**
249
+ * Write a colour as `#rrggbb`, or `#rrggbbaa` when it is not fully opaque.
250
+ *
251
+ * The alpha pair is omitted at 1 rather than always written, because `#3b82f6ff` is the same colour
252
+ * and the shorter form is what someone expects to see in a field they typed `#3b82f6` into.
253
+ *
254
+ * Channels outside [0, 1] are clamped, so the result is always a valid six- or eight-digit hex
255
+ * string whatever a caller passes. Not for floating-point drift, which rounds to the right byte on
256
+ * its own: it is for a value that is wrong by a lot — a channel still in 0-255, or a computation
257
+ * that overshot — where the alternative is emitting `#17f00-80`, a string nothing downstream can
258
+ * parse and no error explains.
259
+ *
260
+ * @experimental
261
+ */
262
+ function toHex(color, alpha = 1) {
263
+ const opacity = Number.isFinite(alpha) ? clamp01$1(alpha) : 1;
264
+ const opaque = `#${pair(color.r)}${pair(color.g)}${pair(color.b)}`;
265
+ return opacity === 1 ? opaque : `${opaque}${pair(opacity)}`;
266
+ }
267
+ // src/lib/color/wcag.ts
268
+ /** Linearize one gamma-encoded sRGB channel (the WCAG 2.x transfer function). */
269
+ function channelToLinear(c) {
270
+ return c <= .04045 ? c / 12.92 : Math.pow((c + .055) / 1.055, 2.4);
271
+ }
272
+ /** WCAG 2.x relative luminance of a gamma-encoded sRGB colour. */
273
+ function relativeLuminance(rgb) {
274
+ return .2126 * channelToLinear(rgb.r) + .7152 * channelToLinear(rgb.g) + .0722 * channelToLinear(rgb.b);
275
+ }
276
+ /**
277
+ * WCAG 2.x contrast ratio between two OPAQUE colours, from 1:1 to 21:1. A
278
+ * translucent colour must be composited over its surface first.
279
+ */
280
+ function contrastRatio(a, b) {
281
+ const la = relativeLuminance(a);
282
+ const lb = relativeLuminance(b);
283
+ return (Math.max(la, lb) + .05) / (Math.min(la, lb) + .05);
284
+ }
285
+ // src/lib/color/readable-on.ts
286
+ /**
287
+ * A colour made readable on the surfaces it is drawn on, by its lightness
288
+ * alone.
289
+ *
290
+ * For colours that are not known when the theme is built, such as a tenant's
291
+ * brand colours drawn as chart marks, and so cannot be held to a contrast
292
+ * minimum by the theme's own test. The colour is never refused: one that
293
+ * already reads is returned exactly as given, and one that does not keeps the
294
+ * hue and chroma the tenant chose and moves its OKLCH lightness, as little as
295
+ * it takes, until it reads on every surface. OKLCH because its lightness is
296
+ * perceptual, so the smallest step there is the smallest change a reader sees.
297
+ *
298
+ * @module lib/color/readable-on
299
+ */
300
+ /** The step the lightness search takes, small beside what a reader can tell apart. */
301
+ const STEP = .001;
302
+ /**
303
+ * The colour as it will be drawn: each channel rounded to the 8 bits a hex
304
+ * value carries. The ratio is checked on THIS, so a colour written out as hex
305
+ * keeps the ratio it was found at.
306
+ */
307
+ function asDrawn(rgb) {
308
+ const round = (channel) => Math.round(channel * 255) / 255;
309
+ return {
310
+ r: round(rgb.r),
311
+ g: round(rgb.g),
312
+ b: round(rgb.b)
313
+ };
314
+ }
315
+ /** The lowest ratio `color` has against any of `surfaces`. */
316
+ function lowestRatio(color, surfaces) {
317
+ let lowest = Number.POSITIVE_INFINITY;
318
+ for (const surface of surfaces) lowest = Math.min(lowest, contrastRatio(color, surface));
319
+ return lowest;
320
+ }
321
+ /**
322
+ * `color`, or the nearest colour of its hue and chroma that reaches `minimum`
323
+ * against every one of `surfaces`.
324
+ *
325
+ * Searches outward from the colour's own lightness, one step each way at a
326
+ * time, and takes the first lightness that reads; where both directions read
327
+ * at the same distance, the one reading better. Should no lightness reach the
328
+ * minimum on every surface, it returns the one that comes closest: a brand
329
+ * colour is adjusted, never refused.
330
+ *
331
+ * Chroma is reduced only where the display cannot show it at the new
332
+ * lightness, which is `oklchToRgb`'s own rule; hue is kept.
333
+ *
334
+ * @experimental
335
+ */
336
+ function readableOn(color, surfaces, minimum = 3) {
337
+ if (surfaces.length === 0 || lowestRatio(color, surfaces) >= minimum) return color;
338
+ const oklch = rgbToOklch(color);
339
+ const drawn = asDrawn(color);
340
+ let best = {
341
+ rgb: drawn,
342
+ ratio: lowestRatio(drawn, surfaces)
343
+ };
344
+ const steps = Math.ceil(1 / STEP);
345
+ for (let i = 1; i <= steps; i += 1) {
346
+ const candidates = candidatesAt(oklch, i * STEP, surfaces);
347
+ best = betterOf(best, candidates);
348
+ const reading = candidates.filter((c) => c.ratio >= minimum);
349
+ const [first] = reading;
350
+ if (first !== void 0) return betterOf(first, reading).rgb;
351
+ }
352
+ return best.rgb;
353
+ }
354
+ /**
355
+ * The colours `distance` either side of `oklch`'s lightness, darker first, as
356
+ * drawn and with their lowest ratio; none past black or white.
357
+ */
358
+ function candidatesAt(oklch, distance, surfaces) {
359
+ return [oklch.l - distance, oklch.l + distance].filter((lightness) => lightness >= 0 && lightness <= 1).map((lightness) => {
360
+ const rgb = asDrawn(oklchToRgb({
361
+ ...oklch,
362
+ l: lightness
363
+ }));
364
+ return {
365
+ rgb,
366
+ ratio: lowestRatio(rgb, surfaces)
367
+ };
368
+ });
369
+ }
370
+ /** The best-reading of `current` and `candidates`, the earlier one on a tie. */
371
+ function betterOf(current, candidates) {
372
+ return candidates.reduce((kept, next) => next.ratio > kept.ratio ? next : kept, current);
373
+ }
374
+ // src/lib/color/picker-geometry.ts
375
+ const clamp01 = (n) => n < 0 ? 0 : n > 1 ? 1 : n;
376
+ /**
377
+ * A pointer position as a fraction of a surface.
378
+ *
379
+ * Clamped, because a drag that begins inside the surface continues to report
380
+ * while the pointer leaves it — which is the interaction people actually use to
381
+ * reach full saturation, and without clamping it produces values outside the
382
+ * colour space rather than the corner they are aiming at.
383
+ *
384
+ * A zero-sized surface answers the top-left rather than dividing by zero. That
385
+ * happens in a test environment and on the first frame before layout.
386
+ *
387
+ * @experimental
388
+ */
389
+ function pointOnSurface(clientX, clientY, rect) {
390
+ return {
391
+ x: rect.width === 0 ? 0 : clamp01((clientX - rect.left) / rect.width),
392
+ y: rect.height === 0 ? 0 : clamp01((clientY - rect.top) / rect.height)
393
+ };
394
+ }
395
+ /**
396
+ * The saturation and value a point on the square stands for.
397
+ *
398
+ * Value runs UPWARD while a surface's y runs downward, so the vertical axis is
399
+ * inverted here. Getting that wrong produces a picker that looks correct and
400
+ * selects the colour vertically mirrored from the one under the cursor.
401
+ *
402
+ * @experimental
403
+ */
404
+ function saturationValueAt(point) {
405
+ return {
406
+ s: clamp01(point.x),
407
+ v: 1 - clamp01(point.y)
408
+ };
409
+ }
410
+ /**
411
+ * Where the handle sits for a given saturation and value — the inverse of
412
+ * {@link saturationValueAt}.
413
+ *
414
+ * Derived from that function's own inversion rather than written independently,
415
+ * so the two cannot disagree about which way the axis runs.
416
+ *
417
+ * @experimental
418
+ */
419
+ function surfacePointFor(s, v) {
420
+ return {
421
+ x: clamp01(s),
422
+ y: 1 - clamp01(v)
423
+ };
424
+ }
425
+ /**
426
+ * The hue a horizontal position stands for, in [0, 360).
427
+ *
428
+ * The upper bound is exclusive: 360 and 0 are the same hue, and returning 360
429
+ * lets a handle at the far end read back as a position outside the strip.
430
+ *
431
+ * @experimental
432
+ */
433
+ function hueAt(fraction) {
434
+ const hue = clamp01(fraction) * 360;
435
+ return hue >= 360 ? 0 : hue;
436
+ }
437
+ /** Where the hue handle sits, as a fraction of the strip. @experimental */
438
+ function huePosition(hue) {
439
+ return (hue % 360 + 360) % 360 / 360;
440
+ }
441
+ /**
442
+ * The integer step a hue occupies on a strip whose last step is `max`.
443
+ *
444
+ * Rounding is what makes this more than a multiplication. A hue just below 360
445
+ * — `#ff0001` is about 359.76 — rounds UP to a step past the end of the strip,
446
+ * and the obvious repair of wrapping it with a modulo sends it to 0: the far
447
+ * LEFT, the opposite end from where that colour belongs. The handle then sits
448
+ * on the wrong side and any keyboard adjustment starts from there. Held at the
449
+ * last step instead, which is where it visually belongs.
450
+ *
451
+ * @experimental
452
+ */
453
+ function hueSliderValue(hue, max) {
454
+ const step = Math.round(huePosition(hue) * (max + 1));
455
+ return step > max ? max : step;
456
+ }
457
+ exports.hsvToRgb = hsvToRgb;
458
+ exports.hueAt = hueAt;
459
+ exports.huePosition = huePosition;
460
+ exports.hueSliderValue = hueSliderValue;
461
+ exports.normalizeHue = normalizeHue;
462
+ exports.oklchToRgb = oklchToRgb;
463
+ exports.parseHex = parseHex;
464
+ exports.pointOnSurface = pointOnSurface;
465
+ exports.readableOn = readableOn;
466
+ exports.rgbToHsv = rgbToHsv;
467
+ exports.rgbToOklch = rgbToOklch;
468
+ exports.saturationValueAt = saturationValueAt;
469
+ exports.surfacePointFor = surfacePointFor;
470
+ exports.toHex = toHex;
471
+
472
+ //# sourceMappingURL=color.cjs.map