@tangible/ui 0.2.3 → 0.2.5

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 (52) 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/Pager/Pager.d.ts +8 -1
  22. package/components/Pager/Pager.js +10 -6
  23. package/components/SearchInput/SearchInput.d.ts +11 -0
  24. package/components/SearchInput/SearchInput.js +76 -0
  25. package/components/SearchInput/index.d.ts +2 -0
  26. package/components/SearchInput/index.js +1 -0
  27. package/components/SearchInput/types.d.ts +69 -0
  28. package/components/SearchInput/types.js +1 -0
  29. package/components/index.d.ts +4 -0
  30. package/components/index.js +2 -0
  31. package/icons/icons.svg +16 -16
  32. package/icons/lms/index.js +13 -13
  33. package/icons/system/index.js +3 -3
  34. package/package.json +9 -1
  35. package/styles/all.css +1 -1
  36. package/styles/all.expanded.css +332 -19
  37. package/styles/all.expanded.unlayered.css +332 -19
  38. package/styles/all.unlayered.css +1 -1
  39. package/styles/components/_bundle.scss +11 -1
  40. package/styles/components/button.scss +4 -3
  41. package/styles/components/card.scss +21 -0
  42. package/styles/components/color-picker.scss +18 -2
  43. package/styles/components/dropdown.scss +1 -0
  44. package/styles/components/gradient-picker.scss +296 -0
  45. package/styles/components/icon-button.scss +15 -8
  46. package/styles/components/pager.scss +11 -5
  47. package/styles/components/search-input.scss +104 -0
  48. package/styles/system/_checkerboard.scss +24 -0
  49. package/styles/system/index.scss +2 -1
  50. package/tui-manifest.json +199 -5
  51. package/utils/color/gradient.d.ts +42 -0
  52. package/utils/color/gradient.js +408 -0
@@ -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
+ }