@tangible/ui 0.2.4 → 0.2.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/components/ColorPicker/ColorField.d.ts +31 -2
  2. package/components/ColorPicker/ColorField.js +100 -8
  3. package/components/Combobox/Combobox.d.ts +1 -1
  4. package/components/Combobox/Combobox.js +2 -2
  5. package/components/Combobox/types.d.ts +5 -0
  6. package/components/Field/Field.d.ts +13 -1
  7. package/components/Field/Field.js +5 -3
  8. package/components/GradientPicker/AngleDial.d.ts +14 -0
  9. package/components/GradientPicker/AngleDial.js +24 -0
  10. package/components/GradientPicker/GradientBar.d.ts +38 -0
  11. package/components/GradientPicker/GradientBar.js +130 -0
  12. package/components/GradientPicker/GradientPicker.d.ts +32 -0
  13. package/components/GradientPicker/GradientPicker.js +191 -0
  14. package/components/GradientPicker/index.d.ts +8 -0
  15. package/components/GradientPicker/index.js +8 -0
  16. package/components/GradientPicker/labels.d.ts +42 -0
  17. package/components/GradientPicker/labels.js +31 -0
  18. package/components/MultiCombobox/MultiCombobox.d.ts +1 -1
  19. package/components/MultiCombobox/MultiCombobox.js +2 -2
  20. package/components/MultiCombobox/types.d.ts +5 -0
  21. package/components/index.d.ts +2 -0
  22. package/components/index.js +1 -0
  23. package/package.json +5 -1
  24. package/styles/all.css +1 -1
  25. package/styles/all.expanded.css +253 -24
  26. package/styles/all.expanded.unlayered.css +253 -24
  27. package/styles/all.unlayered.css +1 -1
  28. package/styles/components/_bundle.scss +9 -1
  29. package/styles/components/button.scss +4 -3
  30. package/styles/components/color-picker.scss +11 -1
  31. package/styles/components/gradient-picker.scss +296 -0
  32. package/styles/components/icon-button.scss +15 -8
  33. package/styles/components/notice.scss +12 -7
  34. package/styles/core.css +1 -1
  35. package/styles/core.unlayered.css +1 -1
  36. package/styles/system/_checkerboard.scss +24 -0
  37. package/styles/system/_tokens.scss +16 -6
  38. package/styles/system/index.scss +2 -1
  39. package/tui-manifest.json +96 -5
  40. package/utils/color/gradient.d.ts +42 -0
  41. package/utils/color/gradient.js +408 -0
package/tui-manifest.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
- "version": "0.2.4",
3
- "generated": "2026-08-01T17:54:44.092Z",
2
+ "version": "0.2.6",
3
+ "generated": "2026-08-15T04:57:33.913Z",
4
4
  "components": {
5
5
  "Accordion": {
6
6
  "props": {
@@ -312,7 +312,6 @@
312
312
  "--tui-button-bg-interact",
313
313
  "--tui-button-fg-interact",
314
314
  "--tui-button-border-interact",
315
- "--tui-button-fg-active",
316
315
  "--tui-button-icon-scale",
317
316
  "--tui-control-height-xs",
318
317
  "--tui-control-height-sm",
@@ -890,7 +889,8 @@
890
889
  "--tui-color-area-thumb-size",
891
890
  "--tui-color-slider-radius",
892
891
  "--tui-color-slider-height",
893
- "--tui-color-slider-thumb-size"
892
+ "--tui-color-slider-thumb-size",
893
+ "--tui-color-field-swatch-border"
894
894
  ],
895
895
  "story": {
896
896
  "title": "Forms/ColorPicker",
@@ -958,6 +958,11 @@
958
958
  "defaultValue": "true",
959
959
  "description": "Whether to open the listbox when the input receives focus."
960
960
  },
961
+ "id": {
962
+ "type": "string",
963
+ "required": false,
964
+ "description": "Optional input ID override, applied to the inner `<input>`.\nUseful for Field integration via htmlFor — Field.Control injects this."
965
+ },
961
966
  "clearable": {
962
967
  "type": "boolean",
963
968
  "required": false,
@@ -1213,6 +1218,83 @@
1213
1218
  "use": null,
1214
1219
  "notFor": null
1215
1220
  },
1221
+ "GradientPicker": {
1222
+ "props": {
1223
+ "value": {
1224
+ "type": "string",
1225
+ "required": false,
1226
+ "description": "Controlled value — a CSS gradient string."
1227
+ },
1228
+ "onValueChange": {
1229
+ "type": "(value: string) => void",
1230
+ "required": false
1231
+ },
1232
+ "alpha": {
1233
+ "type": "boolean",
1234
+ "required": false,
1235
+ "defaultValue": "true",
1236
+ "description": "Show alpha in the per-stop colour pickers."
1237
+ },
1238
+ "formats": {
1239
+ "type": "ColorFormat[]",
1240
+ "required": false,
1241
+ "defaultValue": "all",
1242
+ "description": "Formats offered in the per-stop colour pickers."
1243
+ },
1244
+ "disabled": {
1245
+ "type": "boolean",
1246
+ "required": false
1247
+ },
1248
+ "labels": {
1249
+ "type": "GradientPickerLabels",
1250
+ "required": false,
1251
+ "description": "Override any user-facing string for i18n."
1252
+ },
1253
+ "className": {
1254
+ "type": "string",
1255
+ "required": false
1256
+ },
1257
+ "id": {
1258
+ "type": "string",
1259
+ "required": false
1260
+ },
1261
+ "style": {
1262
+ "type": "CSSProperties",
1263
+ "required": false
1264
+ },
1265
+ "title": {
1266
+ "type": "string",
1267
+ "required": false
1268
+ },
1269
+ "rel": {
1270
+ "type": "string",
1271
+ "required": false
1272
+ },
1273
+ "onClick": {
1274
+ "type": "MouseEventHandler<HTMLDivElement>",
1275
+ "required": false
1276
+ }
1277
+ },
1278
+ "cssTokens": [
1279
+ "--tui-gradient-bar-height",
1280
+ "--tui-gradient-bar-radius",
1281
+ "--tui-gradient-bar-thumb-size",
1282
+ "--tui-angle-dial-size"
1283
+ ],
1284
+ "story": {
1285
+ "title": "Forms/GradientPicker",
1286
+ "tags": [
1287
+ "autodocs"
1288
+ ]
1289
+ },
1290
+ "subcomponents": null,
1291
+ "description": null,
1292
+ "gotchas": null,
1293
+ "examples": null,
1294
+ "related": null,
1295
+ "use": null,
1296
+ "notFor": null
1297
+ },
1216
1298
  "Icon": {
1217
1299
  "props": {
1218
1300
  "name": {
@@ -1380,7 +1462,9 @@
1380
1462
  "--tui-icon-button-border",
1381
1463
  "--tui-icon-button-radius",
1382
1464
  "--tui-icon-button-bg-interact",
1383
- "--tui-icon-button-fg-interact"
1465
+ "--tui-icon-button-fg-interact",
1466
+ "--tui-icon-button-bg-pressed",
1467
+ "--tui-icon-button-fg-pressed"
1384
1468
  ],
1385
1469
  "story": {
1386
1470
  "title": "Primitives/IconButton",
@@ -1637,6 +1721,11 @@
1637
1721
  "required": false,
1638
1722
  "description": "Maximum number of selections allowed.\nWhen reached, unselected options become disabled."
1639
1723
  },
1724
+ "id": {
1725
+ "type": "string",
1726
+ "required": false,
1727
+ "description": "Optional input ID override, applied to the inner `<input>`.\nUseful for Field integration via htmlFor — Field.Control injects this."
1728
+ },
1640
1729
  "clearable": {
1641
1730
  "type": "boolean",
1642
1731
  "required": false,
@@ -1890,6 +1979,8 @@
1890
1979
  "--tui-notice-fg",
1891
1980
  "--tui-notice-radius",
1892
1981
  "--tui-notice-padding",
1982
+ "--tui-notice-gap",
1983
+ "--tui-notice-para-gap",
1893
1984
  "--tui-notice-title-size",
1894
1985
  "--tui-notice-foot-basis"
1895
1986
  ],
@@ -0,0 +1,42 @@
1
+ export type GradientType = 'linear' | 'radial' | 'conic';
2
+ export declare const GRADIENT_TYPES: GradientType[];
3
+ export type GradientStop = {
4
+ /** Any colour string parseColor accepts, or a `var(--x)` reference. */
5
+ color: string;
6
+ /** 0–100, percent along the gradient line. */
7
+ position: number;
8
+ };
9
+ export type Gradient = {
10
+ type: GradientType;
11
+ /** Linear: direction in degrees. Conic: the `from` angle (parsed and
12
+ * re-emitted so it round-trips, even while the UI has no control for it). */
13
+ angle: number;
14
+ /** Radial ellipse radii, percent of the box. */
15
+ sizeX: number;
16
+ sizeY: number;
17
+ /** Radial / conic centre, percent. */
18
+ posX: number;
19
+ posY: number;
20
+ stops: GradientStop[];
21
+ };
22
+ export type ParsedGradient = {
23
+ kind: 'gradient';
24
+ gradient: Gradient;
25
+ } | {
26
+ kind: 'invalid';
27
+ raw: string;
28
+ };
29
+ export declare const DEFAULT_GRADIENT: Gradient;
30
+ export declare function parseGradient(value: string | null | undefined): ParsedGradient;
31
+ /** Stops → the comma list used inside any gradient function. */
32
+ export declare function formatStops(stops: GradientStop[]): string;
33
+ export declare function formatGradient(g: Gradient): string;
34
+ /** Mirror the stops end-to-end (the "reverse" affordance). */
35
+ export declare function reverseStops(stops: GradientStop[]): GradientStop[];
36
+ /**
37
+ * The colour at a position along the stops, interpolated in sRGB — used to
38
+ * seed a newly added stop so it doesn't visibly change the gradient. Stops
39
+ * whose colour can't be resolved (`var(--x)`) end the maths: the nearest
40
+ * stop's colour string is returned verbatim instead.
41
+ */
42
+ export declare function colorAtPosition(stops: GradientStop[], position: number): string;
@@ -0,0 +1,408 @@
1
+ // =============================================================================
2
+ // Gradient parsing / formatting for the GradientPicker
3
+ // =============================================================================
4
+ //
5
+ // A picker value is a CSS gradient string (`linear-gradient(…)`,
6
+ // `radial-gradient(…)`, `conic-gradient(…)`). The internal model normalises the
7
+ // three types into one shape: an angle (linear direction / conic `from`), an
8
+ // ellipse size + centre position (radial / conic), and a list of colour stops
9
+ // with percentage positions.
10
+ //
11
+ // Stop colours are kept as strings and validated through parseColor, so
12
+ // anything the ColorPicker accepts works here too — including `var(--x)`
13
+ // references, which render fine in CSS without resolving in the picker.
14
+ //
15
+ // Coverage notes (v1):
16
+ // - Stop positions are percentages (conic also accepts angles, converted to %).
17
+ // Length units (px, em, …) don't fit the model and parse as invalid.
18
+ // - Double-position stops (`#f00 20% 40%`) expand into two stops — lossless.
19
+ // - Interpolation hints (a bare position between stops), `repeating-*`
20
+ // gradients, and `in <colorspace>` interpolation parse as invalid; the
21
+ // picker's text field reverts rather than destroying the value.
22
+ // - Named colours parse as invalid (parseColor doesn't accept them either).
23
+ // =============================================================================
24
+ import { parseColor, hsvToRgb, rgbToHex } from './color.js';
25
+ export const GRADIENT_TYPES = ['linear', 'radial', 'conic'];
26
+ /**
27
+ * CSS's own defaults when a prelude is absent — linear-gradient() with no
28
+ * direction means `to bottom` (180deg), conic-gradient() with no `from` means
29
+ * 0deg. Distinct from DEFAULT_GRADIENT.angle (90), which is only the picker's
30
+ * authoring seed for brand-new gradients — using it at parse time would
31
+ * silently rotate a user's gradient on their first edit.
32
+ */
33
+ const CSS_DEFAULT_ANGLE = {
34
+ linear: 180,
35
+ radial: 0,
36
+ conic: 0,
37
+ };
38
+ export const DEFAULT_GRADIENT = {
39
+ type: 'linear',
40
+ angle: 90,
41
+ sizeX: 100,
42
+ sizeY: 100,
43
+ posX: 50,
44
+ posY: 50,
45
+ stops: [
46
+ { color: '#6366F1', position: 0 },
47
+ { color: '#4338CA', position: 100 },
48
+ ],
49
+ };
50
+ const clampPct = (n) => Math.min(100, Math.max(0, n));
51
+ const mod360 = (n) => ((n % 360) + 360) % 360;
52
+ const round = (n, dp = 0) => {
53
+ const f = 10 ** dp;
54
+ return Math.round(n * f) / f;
55
+ };
56
+ // -----------------------------------------------------------------------------
57
+ // Tokenising — comma/space splitting that respects nested parentheses, so
58
+ // `rgb(99 102 241 / 0.5)` survives as one token.
59
+ // -----------------------------------------------------------------------------
60
+ function splitTopLevel(input, separator) {
61
+ const parts = [];
62
+ let depth = 0;
63
+ let current = '';
64
+ for (const ch of input) {
65
+ if (ch === '(')
66
+ depth++;
67
+ else if (ch === ')')
68
+ depth--;
69
+ const isSep = depth === 0 && (separator === ',' ? ch === ',' : /\s/.test(ch));
70
+ if (isSep) {
71
+ if (current.trim())
72
+ parts.push(current.trim());
73
+ current = '';
74
+ }
75
+ else {
76
+ current += ch;
77
+ }
78
+ }
79
+ if (current.trim())
80
+ parts.push(current.trim());
81
+ return parts;
82
+ }
83
+ // -----------------------------------------------------------------------------
84
+ // Angles and positions
85
+ // -----------------------------------------------------------------------------
86
+ /** Parse a CSS angle token to degrees; null if it isn't one. */
87
+ function parseAngle(token) {
88
+ const m = token.match(/^(-?\d*\.?\d+)(deg|grad|rad|turn)$/i);
89
+ if (!m)
90
+ return null;
91
+ const n = parseFloat(m[1]);
92
+ switch (m[2].toLowerCase()) {
93
+ case 'deg':
94
+ return n;
95
+ case 'grad':
96
+ return n * 0.9;
97
+ case 'rad':
98
+ return (n * 180) / Math.PI;
99
+ case 'turn':
100
+ return n * 360;
101
+ }
102
+ return null;
103
+ }
104
+ const TO_SIDE_ANGLES = {
105
+ top: 0,
106
+ right: 90,
107
+ bottom: 180,
108
+ left: 270,
109
+ 'right top': 45,
110
+ 'top right': 45,
111
+ 'right bottom': 135,
112
+ 'bottom right': 135,
113
+ 'left bottom': 225,
114
+ 'bottom left': 225,
115
+ 'left top': 315,
116
+ 'top left': 315,
117
+ };
118
+ /** One axis of a `<position>`: keyword or percentage → percent, else null. */
119
+ function parsePositionAxis(token, axis) {
120
+ const keywords = {
121
+ center: 50,
122
+ left: axis === 'x' ? 0 : undefined,
123
+ right: axis === 'x' ? 100 : undefined,
124
+ top: axis === 'y' ? 0 : undefined,
125
+ bottom: axis === 'y' ? 100 : undefined,
126
+ };
127
+ const kw = keywords[token.toLowerCase()];
128
+ if (kw !== undefined)
129
+ return kw;
130
+ const m = token.match(/^(-?\d*\.?\d+)%$/);
131
+ return m ? parseFloat(m[1]) : null;
132
+ }
133
+ const POSITION_KEYWORD = /^(left|right|top|bottom|center)$/i;
134
+ /** Parse the tokens after `at` into an x/y percent pair. */
135
+ function parseAtPosition(tokens) {
136
+ if (tokens.length === 0 || tokens.length > 2)
137
+ return null;
138
+ const [first, second = 'center'] = tokens;
139
+ // Percentages are strictly positional (x then y); ONLY keyword pairs may
140
+ // reorder (`top left`). Mixing them out of order (`top 30%`) is invalid CSS
141
+ // and must parse as invalid, not be silently normalised into a different
142
+ // position.
143
+ let x = parsePositionAxis(first, 'x');
144
+ let y = parsePositionAxis(second, 'y');
145
+ if ((x == null || y == null) && POSITION_KEYWORD.test(first) && POSITION_KEYWORD.test(second)) {
146
+ x = x ?? parsePositionAxis(second, 'x');
147
+ y = y ?? parsePositionAxis(first, 'y');
148
+ }
149
+ if (x == null || y == null)
150
+ return null;
151
+ return { posX: x, posY: y };
152
+ }
153
+ function parseLinearPrelude(segment) {
154
+ const angle = parseAngle(segment);
155
+ if (angle != null)
156
+ return { angle: mod360(angle) };
157
+ const to = segment.match(/^to\s+(.+)$/i);
158
+ if (to) {
159
+ const side = TO_SIDE_ANGLES[to[1].trim().toLowerCase().replace(/\s+/g, ' ')];
160
+ // Corner angles are approximations — the true angle depends on the box
161
+ // aspect ratio, which a value string can't know.
162
+ if (side !== undefined)
163
+ return { angle: side };
164
+ }
165
+ return null;
166
+ }
167
+ const RADIAL_EXTENTS = ['closest-side', 'closest-corner', 'farthest-side', 'farthest-corner'];
168
+ function parseRadialPrelude(segment) {
169
+ // `at` may open the prelude (`at top left`) or follow a shape/size part.
170
+ const atMatch = segment.match(/(?:^|\s)at\s+(.+)$/i);
171
+ const shapePart = atMatch ? segment.slice(0, atMatch.index).trim() : segment;
172
+ const out = {};
173
+ if (atMatch) {
174
+ const pos = parseAtPosition(splitTopLevel(atMatch[1], ' '));
175
+ if (!pos)
176
+ return null;
177
+ Object.assign(out, pos);
178
+ }
179
+ const tokens = splitTopLevel(shapePart, ' ');
180
+ if (tokens.length === 0 && !atMatch)
181
+ return null;
182
+ const sizes = [];
183
+ let sawShapeWord = false;
184
+ let circle = false;
185
+ for (const t of tokens) {
186
+ const lower = t.toLowerCase();
187
+ if (lower === 'circle') {
188
+ sawShapeWord = true;
189
+ circle = true;
190
+ }
191
+ else if (lower === 'ellipse' || RADIAL_EXTENTS.includes(lower)) {
192
+ // Extent keywords don't fit the explicit-size model; fall back to the
193
+ // default size rather than rejecting the whole gradient. This is the one
194
+ // deliberately LOSSY parse (a farthest-corner ellipse ≠ 100% 100%):
195
+ // rejecting would make the most common tool-emitted radial form
196
+ // uneditable, which is worse. Same spirit as the corner `to top left`
197
+ // angle approximations. (`circle N%` is likewise accepted although
198
+ // strict CSS forbids percentage circle radii — invalid in, valid out.)
199
+ sawShapeWord = true;
200
+ }
201
+ else {
202
+ // No sign — a negative radius is invalid CSS and must not round-trip.
203
+ const m = t.match(/^(\d*\.?\d+)%$/);
204
+ if (!m)
205
+ return null;
206
+ sizes.push(parseFloat(m[1]));
207
+ }
208
+ }
209
+ if (sizes.length > 2)
210
+ return null;
211
+ if (tokens.length > 0 && !sawShapeWord && sizes.length === 0)
212
+ return null;
213
+ if (sizes.length >= 1) {
214
+ out.sizeX = sizes[0];
215
+ out.sizeY = circle ? sizes[0] : sizes[1] ?? sizes[0];
216
+ }
217
+ return out;
218
+ }
219
+ function parseConicPrelude(segment) {
220
+ const out = {};
221
+ let rest = segment.trim();
222
+ const from = rest.match(/^from\s+(\S+)\s*/i);
223
+ if (from) {
224
+ const angle = parseAngle(from[1]);
225
+ if (angle == null)
226
+ return null;
227
+ out.angle = mod360(angle);
228
+ rest = rest.slice(from[0].length).trim();
229
+ }
230
+ if (rest) {
231
+ const at = rest.match(/^at\s+(.+)$/i);
232
+ if (!at)
233
+ return null;
234
+ const pos = parseAtPosition(splitTopLevel(at[1], ' '));
235
+ if (!pos)
236
+ return null;
237
+ Object.assign(out, pos);
238
+ }
239
+ return from || rest ? out : null;
240
+ }
241
+ // -----------------------------------------------------------------------------
242
+ // Stops
243
+ // -----------------------------------------------------------------------------
244
+ /** A stop's position token → percent. Conic gradients also allow angles. */
245
+ function parseStopPosition(token, type) {
246
+ const m = token.match(/^(-?\d*\.?\d+)%$/);
247
+ if (m)
248
+ return parseFloat(m[1]);
249
+ if (type === 'conic') {
250
+ const angle = parseAngle(token);
251
+ if (angle != null)
252
+ return (angle / 360) * 100;
253
+ }
254
+ return null;
255
+ }
256
+ /** One stop segment → stops (two for a double-position stop), null if invalid. */
257
+ function parseStopSegment(segment, type) {
258
+ const tokens = splitTopLevel(segment, ' ');
259
+ if (tokens.length === 0 || tokens.length > 3)
260
+ return null;
261
+ const [color, ...positions] = tokens;
262
+ if (parseColor(color).kind === 'invalid')
263
+ return null;
264
+ const parsed = positions.map((p) => parseStopPosition(p, type));
265
+ if (parsed.some((p) => p == null))
266
+ return null;
267
+ if (parsed.length === 0)
268
+ return [{ color, position: NaN }]; // resolved later
269
+ return parsed.map((position) => ({ color, position: clampPct(position) }));
270
+ }
271
+ /**
272
+ * Fill in missing stop positions the way CSS does: first defaults to 0, last
273
+ * to 100, and unpositioned runs distribute evenly between their neighbours.
274
+ * Positions are then made non-decreasing (CSS clamps to the running max).
275
+ */
276
+ function resolveStopPositions(stops) {
277
+ const out = stops.map((s) => ({ ...s }));
278
+ if (out.length === 0)
279
+ return out;
280
+ if (Number.isNaN(out[0].position))
281
+ out[0].position = 0;
282
+ if (Number.isNaN(out[out.length - 1].position))
283
+ out[out.length - 1].position = 100;
284
+ let anchor = 0;
285
+ for (let i = 1; i < out.length; i++) {
286
+ if (Number.isNaN(out[i].position))
287
+ continue;
288
+ const gap = i - anchor;
289
+ for (let j = anchor + 1; j < i; j++) {
290
+ out[j].position =
291
+ out[anchor].position + ((out[i].position - out[anchor].position) * (j - anchor)) / gap;
292
+ }
293
+ anchor = i;
294
+ }
295
+ let runningMax = 0;
296
+ for (const stop of out) {
297
+ runningMax = Math.max(runningMax, stop.position);
298
+ stop.position = round(runningMax, 1);
299
+ }
300
+ return out;
301
+ }
302
+ // -----------------------------------------------------------------------------
303
+ // Parse
304
+ // -----------------------------------------------------------------------------
305
+ export function parseGradient(value) {
306
+ const raw = String(value ?? '').trim();
307
+ const invalid = { kind: 'invalid', raw };
308
+ const fn = raw.match(/^(linear|radial|conic)-gradient\(([\s\S]*)\)$/i);
309
+ if (!fn)
310
+ return invalid;
311
+ const type = fn[1].toLowerCase();
312
+ const segments = splitTopLevel(fn[2], ',');
313
+ if (segments.length === 0)
314
+ return invalid;
315
+ const parsePrelude = type === 'linear'
316
+ ? parseLinearPrelude
317
+ : type === 'radial'
318
+ ? parseRadialPrelude
319
+ : parseConicPrelude;
320
+ // The prelude is optional — if the first segment doesn't parse as one, it
321
+ // must be a colour stop.
322
+ const prelude = parsePrelude(segments[0]);
323
+ const stopSegments = prelude ? segments.slice(1) : segments;
324
+ const stops = [];
325
+ for (const segment of stopSegments) {
326
+ const parsed = parseStopSegment(segment, type);
327
+ if (!parsed)
328
+ return invalid;
329
+ stops.push(...parsed);
330
+ }
331
+ // Double-position segments may expand, so the minimum applies after parsing.
332
+ if (stops.length < 2)
333
+ return invalid;
334
+ return {
335
+ kind: 'gradient',
336
+ gradient: {
337
+ ...DEFAULT_GRADIENT,
338
+ angle: CSS_DEFAULT_ANGLE[type],
339
+ type,
340
+ ...prelude,
341
+ stops: resolveStopPositions(stops),
342
+ },
343
+ };
344
+ }
345
+ // -----------------------------------------------------------------------------
346
+ // Format
347
+ // -----------------------------------------------------------------------------
348
+ /** Stops → the comma list used inside any gradient function. */
349
+ export function formatStops(stops) {
350
+ return stops.map((s) => `${s.color} ${round(s.position, 1)}%`).join(', ');
351
+ }
352
+ export function formatGradient(g) {
353
+ const stops = formatStops(g.stops);
354
+ switch (g.type) {
355
+ case 'linear':
356
+ return `linear-gradient(${round(g.angle, 1)}deg, ${stops})`;
357
+ case 'radial':
358
+ return `radial-gradient(${round(g.sizeX, 1)}% ${round(g.sizeY, 1)}% at ${round(g.posX, 1)}% ${round(g.posY, 1)}%, ${stops})`;
359
+ case 'conic':
360
+ return `conic-gradient(from ${round(g.angle, 1)}deg at ${round(g.posX, 1)}% ${round(g.posY, 1)}%, ${stops})`;
361
+ }
362
+ }
363
+ // -----------------------------------------------------------------------------
364
+ // Editing helpers
365
+ // -----------------------------------------------------------------------------
366
+ /** Mirror the stops end-to-end (the "reverse" affordance). */
367
+ export function reverseStops(stops) {
368
+ return stops.map((s) => ({ ...s, position: round(100 - s.position, 1) })).reverse();
369
+ }
370
+ /**
371
+ * The colour at a position along the stops, interpolated in sRGB — used to
372
+ * seed a newly added stop so it doesn't visibly change the gradient. Stops
373
+ * whose colour can't be resolved (`var(--x)`) end the maths: the nearest
374
+ * stop's colour string is returned verbatim instead.
375
+ */
376
+ export function colorAtPosition(stops, position) {
377
+ if (stops.length === 0)
378
+ return '#000000';
379
+ const sorted = [...stops].sort((a, b) => a.position - b.position);
380
+ let before = sorted[0];
381
+ let after = sorted[sorted.length - 1];
382
+ for (const stop of sorted) {
383
+ if (stop.position <= position)
384
+ before = stop;
385
+ if (stop.position >= position) {
386
+ after = stop;
387
+ break;
388
+ }
389
+ }
390
+ if (position <= sorted[0].position)
391
+ return sorted[0].color;
392
+ if (position >= sorted[sorted.length - 1].position)
393
+ return sorted[sorted.length - 1].color;
394
+ const nearest = position - before.position <= after.position - position ? before : after;
395
+ const pa = parseColor(before.color);
396
+ const pb = parseColor(after.color);
397
+ if (pa.kind !== 'color' || pb.kind !== 'color')
398
+ return nearest.color;
399
+ const t = after.position === before.position
400
+ ? 0
401
+ : (position - before.position) / (after.position - before.position);
402
+ // Lerp in sRGB and emit hex (with alpha when needed) — deliberately simple;
403
+ // this seeds an editable stop, it isn't a colour-science statement.
404
+ const ra = hsvToRgb(pa.hsva);
405
+ const rb = hsvToRgb(pb.hsva);
406
+ const lerp = (x, y) => x + (y - x) * t;
407
+ return rgbToHex({ r: lerp(ra.r, rb.r), g: lerp(ra.g, rb.g), b: lerp(ra.b, rb.b) }, lerp(pa.hsva.a, pb.hsva.a)).toUpperCase();
408
+ }