@open-artifact/ui 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/NOTICE +5 -0
- package/README.md +5 -2
- package/package.json +48 -4
- package/src/button.d.ts +30 -0
- package/src/button.js +28 -0
- package/src/cn.d.ts +3 -0
- package/src/cn.js +5 -0
- package/src/color-picker.d.ts +98 -0
- package/src/color-picker.js +370 -0
- package/src/color.d.ts +144 -0
- package/src/color.js +528 -0
- package/src/data/google-fonts.json +1775 -0
- package/src/effect-editors.d.ts +48 -0
- package/src/effect-editors.js +230 -0
- package/src/effects.d.ts +118 -0
- package/src/effects.js +425 -0
- package/src/fields.d.ts +105 -0
- package/src/fields.js +77 -0
- package/src/focusables.d.ts +26 -0
- package/src/focusables.js +42 -0
- package/src/font-picker.d.ts +62 -0
- package/src/font-picker.js +238 -0
- package/src/fonts.d.ts +121 -0
- package/src/fonts.js +273 -0
- package/src/history-diff.d.ts +64 -0
- package/src/history-diff.js +151 -0
- package/src/history.d.ts +95 -0
- package/src/history.js +160 -0
- package/src/index.d.ts +25 -0
- package/src/index.js +25 -0
- package/src/keys.d.ts +60 -0
- package/src/keys.js +78 -0
- package/src/layout.d.ts +55 -0
- package/src/layout.js +64 -0
- package/src/menu.d.ts +50 -0
- package/src/menu.js +36 -0
- package/src/numbers.d.ts +24 -0
- package/src/numbers.js +114 -0
- package/src/overlays.d.ts +38 -0
- package/src/overlays.js +26 -0
- package/src/scroll.d.ts +24 -0
- package/src/scroll.js +111 -0
- package/src/scrub-number-field.d.ts +56 -0
- package/src/scrub-number-field.js +190 -0
- package/src/styles.css +122 -0
- package/src/tooltip.d.ts +18 -0
- package/src/tooltip.js +10 -0
package/src/effects.js
ADDED
|
@@ -0,0 +1,425 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Parsing and writing the CSS values the effect editors edit: gradients
|
|
3
|
+
* (`linear-gradient()`, `radial-gradient()` and their `repeating-` forms),
|
|
4
|
+
* `box-shadow` lists and `filter` chains. No DOM.
|
|
5
|
+
*
|
|
6
|
+
* Each parser returns null for a value it cannot represent faithfully (a
|
|
7
|
+
* `var()`, a length in `em`, a color hint…), so an editor can fall back to
|
|
8
|
+
* a plain text field instead of silently rewriting it.
|
|
9
|
+
*/
|
|
10
|
+
import { formatLike, toRgba } from "./color.js";
|
|
11
|
+
/* --------------------------------- tokens --------------------------------- */
|
|
12
|
+
/**
|
|
13
|
+
* Splits `text` at top-level separators (outside parentheses): commas, or
|
|
14
|
+
* runs of whitespace. Empty pieces are dropped for whitespace and kept for
|
|
15
|
+
* commas (so `a,,b` can be rejected).
|
|
16
|
+
*/
|
|
17
|
+
export function splitTopLevel(text, separator) {
|
|
18
|
+
const parts = [];
|
|
19
|
+
let depth = 0;
|
|
20
|
+
let current = '';
|
|
21
|
+
for (const ch of text) {
|
|
22
|
+
if (ch === '(')
|
|
23
|
+
depth++;
|
|
24
|
+
else if (ch === ')')
|
|
25
|
+
depth = Math.max(0, depth - 1);
|
|
26
|
+
const splits = depth === 0 && (separator === ',' ? ch === ',' : /\s/.test(ch));
|
|
27
|
+
if (splits) {
|
|
28
|
+
if (separator === ',' || current.trim())
|
|
29
|
+
parts.push(current.trim());
|
|
30
|
+
current = '';
|
|
31
|
+
continue;
|
|
32
|
+
}
|
|
33
|
+
current += ch;
|
|
34
|
+
}
|
|
35
|
+
if (separator === ',' || current.trim())
|
|
36
|
+
parts.push(current.trim());
|
|
37
|
+
return parts;
|
|
38
|
+
}
|
|
39
|
+
const LENGTH = /^([+-]?(?:\d+\.?\d*|\.\d+))(px)?$/i;
|
|
40
|
+
/** A px length (or a bare 0), else null. */
|
|
41
|
+
function px(text) {
|
|
42
|
+
const match = LENGTH.exec(text);
|
|
43
|
+
if (!match)
|
|
44
|
+
return null;
|
|
45
|
+
const value = Number(match[1]);
|
|
46
|
+
if (!match[2] && value !== 0)
|
|
47
|
+
return null;
|
|
48
|
+
return value;
|
|
49
|
+
}
|
|
50
|
+
/** Rounds for output, without `-0`. */
|
|
51
|
+
const num = (value, digits = 2) => {
|
|
52
|
+
const out = Math.round(value * 10 ** digits) / 10 ** digits;
|
|
53
|
+
return Object.is(out, -0) ? 0 : out;
|
|
54
|
+
};
|
|
55
|
+
const pxText = (value) => `${num(value)}px`;
|
|
56
|
+
/** True for text that can stand as a color in a shadow or stop (a color, `var()`, `currentcolor`). */
|
|
57
|
+
function isColorToken(text) {
|
|
58
|
+
return toRgba(text) !== null || /^(?:var|color-mix|color|light-dark|hwb|lab|lch|oklab)\(.*\)$/i.test(text) || text.toLowerCase() === 'currentcolor';
|
|
59
|
+
}
|
|
60
|
+
/** A new shadow layer: a soft drop shadow. */
|
|
61
|
+
export const DEFAULT_SHADOW = { x: 0, y: 4, blur: 12, spread: 0, color: 'rgb(0 0 0 / 0.15)', inset: false };
|
|
62
|
+
/** Parses one shadow. `full` allows spread and `inset` (box-shadow). */
|
|
63
|
+
function parseShadow(text, full) {
|
|
64
|
+
const lengths = [];
|
|
65
|
+
const colors = [];
|
|
66
|
+
let inset = false;
|
|
67
|
+
let lengthsDone = false;
|
|
68
|
+
for (const part of splitTopLevel(text, 'space')) {
|
|
69
|
+
const length = px(part);
|
|
70
|
+
if (length !== null) {
|
|
71
|
+
if (lengthsDone)
|
|
72
|
+
return null;
|
|
73
|
+
lengths.push(length);
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
if (lengths.length)
|
|
77
|
+
lengthsDone = true;
|
|
78
|
+
if (part.toLowerCase() === 'inset') {
|
|
79
|
+
if (!full || inset)
|
|
80
|
+
return null;
|
|
81
|
+
inset = true;
|
|
82
|
+
continue;
|
|
83
|
+
}
|
|
84
|
+
if (!isColorToken(part) || colors.length)
|
|
85
|
+
return null;
|
|
86
|
+
colors.push(part);
|
|
87
|
+
}
|
|
88
|
+
if (lengths.length < 2 || lengths.length > (full ? 4 : 3))
|
|
89
|
+
return null;
|
|
90
|
+
const [x, y, blur = 0, spread = 0] = lengths;
|
|
91
|
+
if (blur < 0)
|
|
92
|
+
return null;
|
|
93
|
+
return { x, y, blur, spread, color: colors[0] ?? 'currentcolor', inset };
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Parses a `box-shadow` value into layers (front first). `none` or empty
|
|
97
|
+
* gives `[]`; null when a layer is not `[inset] x y [blur [spread]] [color]`
|
|
98
|
+
* in px.
|
|
99
|
+
*/
|
|
100
|
+
export function parseBoxShadow(css) {
|
|
101
|
+
const text = css.trim();
|
|
102
|
+
if (!text || text.toLowerCase() === 'none')
|
|
103
|
+
return [];
|
|
104
|
+
const layers = [];
|
|
105
|
+
for (const part of splitTopLevel(text, ',')) {
|
|
106
|
+
const layer = part ? parseShadow(part, true) : null;
|
|
107
|
+
if (!layer)
|
|
108
|
+
return null;
|
|
109
|
+
layers.push(layer);
|
|
110
|
+
}
|
|
111
|
+
return layers;
|
|
112
|
+
}
|
|
113
|
+
/** Writes one box-shadow layer: `[inset] x y blur spread color`. */
|
|
114
|
+
export function formatShadowLayer(layer) {
|
|
115
|
+
const parts = [pxText(layer.x), pxText(layer.y), pxText(layer.blur), pxText(layer.spread), layer.color];
|
|
116
|
+
return (layer.inset ? ['inset', ...parts] : parts).join(' ');
|
|
117
|
+
}
|
|
118
|
+
/** Writes a `box-shadow` value; `none` for no layers. */
|
|
119
|
+
export function formatBoxShadow(layers) {
|
|
120
|
+
return layers.length ? layers.map(formatShadowLayer).join(', ') : 'none';
|
|
121
|
+
}
|
|
122
|
+
/** Parses the argument of `drop-shadow()` (or one `text-shadow` layer). */
|
|
123
|
+
export function parseDropShadow(text) {
|
|
124
|
+
const layer = parseShadow(text, false);
|
|
125
|
+
return layer ? { x: layer.x, y: layer.y, blur: layer.blur, color: layer.color } : null;
|
|
126
|
+
}
|
|
127
|
+
/** Writes the argument of `drop-shadow()`: `x y blur color`. */
|
|
128
|
+
export function formatDropShadow(shadow) {
|
|
129
|
+
return `${pxText(shadow.x)} ${pxText(shadow.y)} ${pxText(shadow.blur)} ${shadow.color}`;
|
|
130
|
+
}
|
|
131
|
+
/** Field settings of the numeric filters, in menu order. */
|
|
132
|
+
export const FILTER_SPECS = {
|
|
133
|
+
blur: { label: 'Blur', unit: 'px', min: 0, max: 200, step: 1, identity: 0, initial: 4 },
|
|
134
|
+
brightness: { label: 'Brightness', unit: '%', min: 0, max: 500, step: 1, identity: 100, initial: 120 },
|
|
135
|
+
contrast: { label: 'Contrast', unit: '%', min: 0, max: 500, step: 1, identity: 100, initial: 120 },
|
|
136
|
+
grayscale: { label: 'Grayscale', unit: '%', min: 0, max: 100, step: 1, identity: 0, initial: 100 },
|
|
137
|
+
saturate: { label: 'Saturate', unit: '%', min: 0, max: 500, step: 1, identity: 100, initial: 150 },
|
|
138
|
+
'hue-rotate': { label: 'Hue rotate', unit: 'deg', min: -360, max: 360, step: 1, identity: 0, initial: 90 },
|
|
139
|
+
invert: { label: 'Invert', unit: '%', min: 0, max: 100, step: 1, identity: 0, initial: 100 },
|
|
140
|
+
sepia: { label: 'Sepia', unit: '%', min: 0, max: 100, step: 1, identity: 0, initial: 100 },
|
|
141
|
+
opacity: { label: 'Opacity', unit: '%', min: 0, max: 100, step: 1, identity: 100, initial: 50 },
|
|
142
|
+
};
|
|
143
|
+
/** The drop shadow a newly added `drop-shadow()` starts as. */
|
|
144
|
+
export const DEFAULT_DROP_SHADOW = { x: 0, y: 4, blur: 8, color: 'rgb(0 0 0 / 0.25)' };
|
|
145
|
+
/** A new filter function of `kind` at its initial value. */
|
|
146
|
+
export function newFilter(kind) {
|
|
147
|
+
return kind === 'drop-shadow' ? { kind, shadow: { ...DEFAULT_DROP_SHADOW } } : { kind, value: FILTER_SPECS[kind].initial };
|
|
148
|
+
}
|
|
149
|
+
const ANGLE = /^([+-]?(?:\d+\.?\d*|\.\d+))(deg|grad|rad|turn)?$/i;
|
|
150
|
+
/** Degrees of an angle (a bare 0 allowed). */
|
|
151
|
+
function degrees(text) {
|
|
152
|
+
const match = ANGLE.exec(text);
|
|
153
|
+
if (!match)
|
|
154
|
+
return null;
|
|
155
|
+
const value = Number(match[1]);
|
|
156
|
+
switch ((match[2] ?? '').toLowerCase()) {
|
|
157
|
+
case '':
|
|
158
|
+
return value === 0 ? 0 : null;
|
|
159
|
+
case 'deg':
|
|
160
|
+
return value;
|
|
161
|
+
case 'grad':
|
|
162
|
+
return (value * 360) / 400;
|
|
163
|
+
case 'rad':
|
|
164
|
+
return (value * 180) / Math.PI;
|
|
165
|
+
default:
|
|
166
|
+
return value * 360;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
/** A number-or-percentage amount as a percentage. */
|
|
170
|
+
function percent(text) {
|
|
171
|
+
const match = /^([+-]?(?:\d+\.?\d*|\.\d+))(%)?$/.exec(text);
|
|
172
|
+
if (!match)
|
|
173
|
+
return null;
|
|
174
|
+
const value = Number(match[1]);
|
|
175
|
+
if (value < 0)
|
|
176
|
+
return null;
|
|
177
|
+
return match[2] ? value : value * 100;
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* Parses a `filter` chain. `none` or empty gives `[]`; null for `url()`,
|
|
181
|
+
* unknown functions or arguments it cannot read.
|
|
182
|
+
*/
|
|
183
|
+
export function parseFilter(css) {
|
|
184
|
+
const text = css.trim();
|
|
185
|
+
if (!text || text.toLowerCase() === 'none')
|
|
186
|
+
return [];
|
|
187
|
+
const out = [];
|
|
188
|
+
for (const part of splitTopLevel(text, 'space')) {
|
|
189
|
+
const match = /^([a-z-]+)\(([\s\S]*)\)$/i.exec(part);
|
|
190
|
+
if (!match)
|
|
191
|
+
return null;
|
|
192
|
+
const kind = match[1].toLowerCase();
|
|
193
|
+
const arg = match[2].trim();
|
|
194
|
+
if (kind === 'drop-shadow') {
|
|
195
|
+
const shadow = parseDropShadow(arg);
|
|
196
|
+
if (!shadow)
|
|
197
|
+
return null;
|
|
198
|
+
out.push({ kind, shadow });
|
|
199
|
+
continue;
|
|
200
|
+
}
|
|
201
|
+
if (!(kind in FILTER_SPECS))
|
|
202
|
+
return null;
|
|
203
|
+
const amountKind = kind;
|
|
204
|
+
const spec = FILTER_SPECS[amountKind];
|
|
205
|
+
let value;
|
|
206
|
+
if (!arg)
|
|
207
|
+
value = amountKind === 'blur' || amountKind === 'hue-rotate' ? 0 : 100;
|
|
208
|
+
else if (amountKind === 'blur')
|
|
209
|
+
value = px(arg);
|
|
210
|
+
else if (amountKind === 'hue-rotate')
|
|
211
|
+
value = degrees(arg);
|
|
212
|
+
else
|
|
213
|
+
value = percent(arg);
|
|
214
|
+
if (value === null || (amountKind === 'blur' && value < 0))
|
|
215
|
+
return null;
|
|
216
|
+
// CSS clamps these at 100%.
|
|
217
|
+
if (spec.max === 100 && spec.unit === '%')
|
|
218
|
+
value = Math.min(100, value);
|
|
219
|
+
out.push({ kind: amountKind, value });
|
|
220
|
+
}
|
|
221
|
+
return out;
|
|
222
|
+
}
|
|
223
|
+
/** Writes one filter function. */
|
|
224
|
+
export function formatFilterFunction(fn) {
|
|
225
|
+
if (fn.kind === 'drop-shadow')
|
|
226
|
+
return `drop-shadow(${formatDropShadow(fn.shadow)})`;
|
|
227
|
+
const unit = FILTER_SPECS[fn.kind].unit;
|
|
228
|
+
return `${fn.kind}(${num(fn.value)}${unit})`;
|
|
229
|
+
}
|
|
230
|
+
/** Writes a `filter` value; `none` for an empty chain. */
|
|
231
|
+
export function formatFilter(chain) {
|
|
232
|
+
return chain.length ? chain.map(formatFilterFunction).join(' ') : 'none';
|
|
233
|
+
}
|
|
234
|
+
/** A new gradient: left-to-right, from `from` to `to`. */
|
|
235
|
+
export function defaultGradient(from = '#000000', to = '#ffffff') {
|
|
236
|
+
return { type: 'linear', repeating: false, angle: 90, shape: 'ellipse', stops: [{ color: from, position: 0 }, { color: to, position: 100 }] };
|
|
237
|
+
}
|
|
238
|
+
const SIDE_ANGLES = {
|
|
239
|
+
top: 0,
|
|
240
|
+
right: 90,
|
|
241
|
+
bottom: 180,
|
|
242
|
+
left: 270,
|
|
243
|
+
'top right': 45,
|
|
244
|
+
'right top': 45,
|
|
245
|
+
'bottom right': 135,
|
|
246
|
+
'right bottom': 135,
|
|
247
|
+
'bottom left': 225,
|
|
248
|
+
'left bottom': 225,
|
|
249
|
+
'top left': 315,
|
|
250
|
+
'left top': 315,
|
|
251
|
+
};
|
|
252
|
+
const RADIAL_SIZES = new Set(['closest-side', 'closest-corner', 'farthest-side', 'farthest-corner']);
|
|
253
|
+
/** Fills in missing stop positions the way CSS does: ends at 0/100, never backwards, gaps spread evenly. */
|
|
254
|
+
function resolvePositions(raw) {
|
|
255
|
+
const out = [...raw];
|
|
256
|
+
if (out[0] == null)
|
|
257
|
+
out[0] = 0;
|
|
258
|
+
if (out[out.length - 1] == null)
|
|
259
|
+
out[out.length - 1] = Math.max(100, ...out.filter((p) => p != null));
|
|
260
|
+
let max = -Infinity;
|
|
261
|
+
for (let i = 0; i < out.length; i++) {
|
|
262
|
+
if (out[i] != null) {
|
|
263
|
+
max = Math.max(max, out[i]);
|
|
264
|
+
out[i] = max;
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
for (let i = 1; i < out.length; i++) {
|
|
268
|
+
if (out[i] != null)
|
|
269
|
+
continue;
|
|
270
|
+
let j = i;
|
|
271
|
+
while (out[j] == null)
|
|
272
|
+
j++;
|
|
273
|
+
const start = out[i - 1];
|
|
274
|
+
const end = out[j];
|
|
275
|
+
for (let k = i; k < j; k++)
|
|
276
|
+
out[k] = start + ((end - start) * (k - i + 1)) / (j - i + 1);
|
|
277
|
+
i = j;
|
|
278
|
+
}
|
|
279
|
+
return out;
|
|
280
|
+
}
|
|
281
|
+
/** Parses the stops; null when one is a color hint or uses a non-% position. */
|
|
282
|
+
function parseStops(parts) {
|
|
283
|
+
const colors = [];
|
|
284
|
+
const positions = [];
|
|
285
|
+
for (const part of parts) {
|
|
286
|
+
const tokens = splitTopLevel(part, 'space');
|
|
287
|
+
const [color, ...rest] = tokens;
|
|
288
|
+
if (!color || !isColorToken(color) || rest.length > 2)
|
|
289
|
+
return null;
|
|
290
|
+
const at = rest.map((token) => {
|
|
291
|
+
const match = /^([+-]?(?:\d+\.?\d*|\.\d+))(%)?$/.exec(token);
|
|
292
|
+
if (!match || (!match[2] && Number(match[1]) !== 0))
|
|
293
|
+
return null;
|
|
294
|
+
return Number(match[1]);
|
|
295
|
+
});
|
|
296
|
+
if (at.some((p) => p === null))
|
|
297
|
+
return null;
|
|
298
|
+
if (at.length === 0) {
|
|
299
|
+
colors.push(color);
|
|
300
|
+
positions.push(null);
|
|
301
|
+
}
|
|
302
|
+
for (const p of at) {
|
|
303
|
+
colors.push(color);
|
|
304
|
+
positions.push(p);
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
if (colors.length < 2)
|
|
308
|
+
return null;
|
|
309
|
+
const resolved = resolvePositions(positions);
|
|
310
|
+
return colors.map((color, i) => ({ color, position: num(resolved[i], 4) }));
|
|
311
|
+
}
|
|
312
|
+
/**
|
|
313
|
+
* Parses a `linear-gradient()` / `radial-gradient()` (or `repeating-`) value.
|
|
314
|
+
* Null for other images, color hints, stop positions not in %, or a value
|
|
315
|
+
* with several layers. `to <side>` directions become angles (corners as 45°
|
|
316
|
+
* steps, which matches CSS for square boxes).
|
|
317
|
+
*/
|
|
318
|
+
export function parseGradient(css) {
|
|
319
|
+
const match = /^(repeating-)?(linear|radial)-gradient\(([\s\S]*)\)$/i.exec(css.trim());
|
|
320
|
+
if (!match)
|
|
321
|
+
return null;
|
|
322
|
+
// Reject `a-gradient(...), b-gradient(...)`: the body must balance.
|
|
323
|
+
let depth = 0;
|
|
324
|
+
for (const ch of match[3]) {
|
|
325
|
+
if (ch === '(')
|
|
326
|
+
depth++;
|
|
327
|
+
else if (ch === ')' && --depth < 0)
|
|
328
|
+
return null;
|
|
329
|
+
}
|
|
330
|
+
if (depth !== 0)
|
|
331
|
+
return null;
|
|
332
|
+
const type = match[2].toLowerCase();
|
|
333
|
+
const parts = splitTopLevel(match[3], ',');
|
|
334
|
+
if (parts.some((part) => !part))
|
|
335
|
+
return null;
|
|
336
|
+
const gradient = { type, repeating: Boolean(match[1]), angle: 180, shape: 'ellipse', stops: [] };
|
|
337
|
+
const first = parts[0];
|
|
338
|
+
const firstTokens = splitTopLevel(first, 'space');
|
|
339
|
+
let stopParts = parts;
|
|
340
|
+
if (type === 'linear') {
|
|
341
|
+
const angle = firstTokens.length === 1 ? degrees(first) : null;
|
|
342
|
+
if (angle !== null) {
|
|
343
|
+
gradient.angle = num(((angle % 360) + 360) % 360, 4);
|
|
344
|
+
stopParts = parts.slice(1);
|
|
345
|
+
}
|
|
346
|
+
else if (firstTokens[0]?.toLowerCase() === 'to') {
|
|
347
|
+
const side = SIDE_ANGLES[firstTokens.slice(1).join(' ').toLowerCase()];
|
|
348
|
+
if (side === undefined)
|
|
349
|
+
return null;
|
|
350
|
+
gradient.angle = side;
|
|
351
|
+
stopParts = parts.slice(1);
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
else if (!isColorToken(firstTokens[0] ?? '')) {
|
|
355
|
+
const at = firstTokens.findIndex((t) => t.toLowerCase() === 'at');
|
|
356
|
+
const head = at < 0 ? firstTokens : firstTokens.slice(0, at);
|
|
357
|
+
const sizes = [];
|
|
358
|
+
for (const t of head) {
|
|
359
|
+
const lower = t.toLowerCase();
|
|
360
|
+
if (lower === 'circle' || lower === 'ellipse')
|
|
361
|
+
gradient.shape = lower;
|
|
362
|
+
else if (RADIAL_SIZES.has(lower) || /^[\d.]+(?:px|%|em|rem|vw|vh)$/.test(lower))
|
|
363
|
+
sizes.push(t);
|
|
364
|
+
else
|
|
365
|
+
return null;
|
|
366
|
+
}
|
|
367
|
+
if (sizes.length && !(sizes.length === 1 && sizes[0].toLowerCase() === 'farthest-corner'))
|
|
368
|
+
gradient.size = sizes.join(' ');
|
|
369
|
+
if (at >= 0) {
|
|
370
|
+
const position = firstTokens.slice(at + 1).join(' ');
|
|
371
|
+
if (!position)
|
|
372
|
+
return null;
|
|
373
|
+
if (position.toLowerCase() !== 'center' && position !== '50% 50%')
|
|
374
|
+
gradient.position = position;
|
|
375
|
+
}
|
|
376
|
+
stopParts = parts.slice(1);
|
|
377
|
+
}
|
|
378
|
+
const stops = parseStops(stopParts);
|
|
379
|
+
if (!stops)
|
|
380
|
+
return null;
|
|
381
|
+
gradient.stops = stops;
|
|
382
|
+
return gradient;
|
|
383
|
+
}
|
|
384
|
+
/** Writes a gradient as CSS; stops are written in position order. */
|
|
385
|
+
export function formatGradient(gradient) {
|
|
386
|
+
const stops = sortStops(gradient.stops).map((stop) => `${stop.color} ${num(stop.position)}%`);
|
|
387
|
+
const name = `${gradient.repeating ? 'repeating-' : ''}${gradient.type}-gradient`;
|
|
388
|
+
if (gradient.type === 'linear')
|
|
389
|
+
return `${name}(${num(gradient.angle)}deg, ${stops.join(', ')})`;
|
|
390
|
+
const head = [gradient.shape === 'circle' ? 'circle' : null, gradient.size ?? null, gradient.position ? `at ${gradient.position}` : null].filter(Boolean);
|
|
391
|
+
return `${name}(${head.length ? `${head.join(' ')}, ` : ''}${stops.join(', ')})`;
|
|
392
|
+
}
|
|
393
|
+
/** Stops sorted by position (stable). */
|
|
394
|
+
export function sortStops(stops) {
|
|
395
|
+
return stops.map((stop, i) => ({ stop, i })).sort((a, b) => a.stop.position - b.stop.position || a.i - b.i).map(({ stop }) => stop);
|
|
396
|
+
}
|
|
397
|
+
const lerp = (a, b, t) => a + (b - a) * t;
|
|
398
|
+
/**
|
|
399
|
+
* The color the gradient shows at `position` (percent), interpolated in
|
|
400
|
+
* premultiplied sRGB like browsers do by default, written like the nearer
|
|
401
|
+
* stop. Stops whose colors cannot be read (a `var()`) are taken as-is.
|
|
402
|
+
*/
|
|
403
|
+
export function colorAtPosition(stops, position) {
|
|
404
|
+
const sorted = sortStops(stops);
|
|
405
|
+
if (!sorted.length)
|
|
406
|
+
return '#000000';
|
|
407
|
+
if (position <= sorted[0].position)
|
|
408
|
+
return sorted[0].color;
|
|
409
|
+
const last = sorted[sorted.length - 1];
|
|
410
|
+
if (position >= last.position)
|
|
411
|
+
return last.color;
|
|
412
|
+
const right = sorted.findIndex((stop) => stop.position >= position);
|
|
413
|
+
const a = sorted[right - 1];
|
|
414
|
+
const b = sorted[right];
|
|
415
|
+
const t = b.position === a.position ? 0 : (position - a.position) / (b.position - a.position);
|
|
416
|
+
const ca = toRgba(a.color);
|
|
417
|
+
const cb = toRgba(b.color);
|
|
418
|
+
const near = t < 0.5 ? a : b;
|
|
419
|
+
if (!ca || !cb)
|
|
420
|
+
return near.color;
|
|
421
|
+
const alpha = lerp(ca.a, cb.a, t);
|
|
422
|
+
const channel = (x, y) => (alpha === 0 ? 0 : lerp(x * ca.a, y * cb.a, t) / alpha);
|
|
423
|
+
const mixed = { r: channel(ca.r, cb.r), g: channel(ca.g, cb.g), b: channel(ca.b, cb.b), a: alpha };
|
|
424
|
+
return formatLike(near.color, mixed);
|
|
425
|
+
}
|
package/src/fields.d.ts
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { type InputHTMLAttributes, type ReactNode } from 'react';
|
|
2
|
+
/** Shared look of single-line inputs. */
|
|
3
|
+
export declare const INPUT_CLASS = "h-7 w-full min-w-0 rounded-control border border-line bg-surface-2 px-2 text-[13px] text-fg outline-none placeholder:text-fg-subtle focus:border-accent focus:bg-surface";
|
|
4
|
+
/** A plain text input. */
|
|
5
|
+
export declare const TextInput: import("react").ForwardRefExoticComponent<InputHTMLAttributes<HTMLInputElement> & import("react").RefAttributes<HTMLInputElement>>;
|
|
6
|
+
/** Props of {@link CommitInput}. */
|
|
7
|
+
export interface CommitInputProps extends Omit<InputHTMLAttributes<HTMLInputElement>, 'value' | 'onChange'> {
|
|
8
|
+
value: string;
|
|
9
|
+
/** Called on Enter or blur, only when the text changed. */
|
|
10
|
+
onCommit: (value: string) => void;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* A text input that keeps a local draft and commits on Enter or blur; Escape
|
|
14
|
+
* restores the last committed value. Inspector edits use it so every
|
|
15
|
+
* keystroke does not become a document write.
|
|
16
|
+
*/
|
|
17
|
+
export declare function CommitInput({ value, onCommit, className, ...rest }: CommitInputProps): import("react/jsx-runtime").JSX.Element;
|
|
18
|
+
/** Props of {@link NumberInput}. */
|
|
19
|
+
export interface NumberInputProps {
|
|
20
|
+
value: number | null;
|
|
21
|
+
/** Live updates while scrubbing or typing. */
|
|
22
|
+
onChange?: (value: number | null) => void;
|
|
23
|
+
/** Final value after typing (blur), scrub release or a step. */
|
|
24
|
+
onCommit: (value: number | null) => void;
|
|
25
|
+
/** Short label drawn in the scrub area, e.g. `W`, `X` or an icon. */
|
|
26
|
+
label?: ReactNode;
|
|
27
|
+
unit?: string;
|
|
28
|
+
min?: number;
|
|
29
|
+
max?: number;
|
|
30
|
+
step?: number;
|
|
31
|
+
placeholder?: string;
|
|
32
|
+
className?: string;
|
|
33
|
+
'aria-label'?: string;
|
|
34
|
+
}
|
|
35
|
+
/** A number field whose label can be dragged horizontally to scrub the value. */
|
|
36
|
+
export declare function NumberInput({ value, onChange, onCommit, label, unit, min, max, step, placeholder, className, ...aria }: NumberInputProps): import("react/jsx-runtime").JSX.Element;
|
|
37
|
+
/** One option of {@link SelectInput} and {@link Segmented}. */
|
|
38
|
+
export interface Option<T extends string> {
|
|
39
|
+
value: T;
|
|
40
|
+
label: ReactNode;
|
|
41
|
+
/** Icon-only segments need an accessible name. */
|
|
42
|
+
title?: string;
|
|
43
|
+
}
|
|
44
|
+
/** Props of {@link SelectInput}. */
|
|
45
|
+
export interface SelectInputProps<T extends string> {
|
|
46
|
+
value: T | null;
|
|
47
|
+
options: Option<T>[];
|
|
48
|
+
onChange: (value: T) => void;
|
|
49
|
+
placeholder?: string;
|
|
50
|
+
className?: string;
|
|
51
|
+
'aria-label'?: string;
|
|
52
|
+
}
|
|
53
|
+
/** A dropdown select. */
|
|
54
|
+
export declare function SelectInput<T extends string>({ value, options, onChange, placeholder, className, ...aria }: SelectInputProps<T>): import("react/jsx-runtime").JSX.Element;
|
|
55
|
+
/** Props of {@link Segmented}. */
|
|
56
|
+
export interface SegmentedProps<T extends string> {
|
|
57
|
+
value: T | null;
|
|
58
|
+
options: Option<T>[];
|
|
59
|
+
onChange: (value: T) => void;
|
|
60
|
+
className?: string;
|
|
61
|
+
'aria-label'?: string;
|
|
62
|
+
}
|
|
63
|
+
/** A segmented control (one of a few options, all visible). */
|
|
64
|
+
export declare function Segmented<T extends string>({ value, options, onChange, className, ...aria }: SegmentedProps<T>): import("react/jsx-runtime").JSX.Element;
|
|
65
|
+
/** Props of {@link SwitchInput}. */
|
|
66
|
+
export interface SwitchInputProps {
|
|
67
|
+
checked: boolean;
|
|
68
|
+
onChange: (checked: boolean) => void;
|
|
69
|
+
'aria-label'?: string;
|
|
70
|
+
disabled?: boolean;
|
|
71
|
+
}
|
|
72
|
+
/** An on/off switch. A held Enter flips it once. */
|
|
73
|
+
export declare function SwitchInput({ checked, onChange, disabled, ...aria }: SwitchInputProps): import("react/jsx-runtime").JSX.Element;
|
|
74
|
+
/** Props of {@link SliderInput}. */
|
|
75
|
+
export interface SliderInputProps {
|
|
76
|
+
value: number;
|
|
77
|
+
min: number;
|
|
78
|
+
max: number;
|
|
79
|
+
step?: number;
|
|
80
|
+
onChange: (value: number) => void;
|
|
81
|
+
onCommit?: (value: number) => void;
|
|
82
|
+
'aria-label'?: string;
|
|
83
|
+
}
|
|
84
|
+
/** A horizontal slider. */
|
|
85
|
+
export declare function SliderInput({ value, min, max, step, onChange, onCommit, ...aria }: SliderInputProps): import("react/jsx-runtime").JSX.Element;
|
|
86
|
+
/** Props of {@link ColorInput}. */
|
|
87
|
+
export interface ColorInputProps {
|
|
88
|
+
/** Any CSS color string, or `null` for "not set". */
|
|
89
|
+
value: string | null;
|
|
90
|
+
onCommit: (value: string) => void;
|
|
91
|
+
/** Swatches offered above the text field (e.g. design-system tokens). */
|
|
92
|
+
swatches?: {
|
|
93
|
+
label: string;
|
|
94
|
+
value: string;
|
|
95
|
+
css?: string;
|
|
96
|
+
}[];
|
|
97
|
+
/** Text shown while no color is set (default "none"). */
|
|
98
|
+
placeholder?: string;
|
|
99
|
+
'aria-label'?: string;
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* A color field: a swatch opening the browser's picker, a text field for any
|
|
103
|
+
* CSS color (hex, rgb, oklch, `var(--token)`), and optional token swatches.
|
|
104
|
+
*/
|
|
105
|
+
export declare function ColorInput({ value, onCommit, swatches, placeholder, ...aria }: ColorInputProps): import("react/jsx-runtime").JSX.Element;
|
package/src/fields.js
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
/**
|
|
3
|
+
* Form controls used by inspectors: text, number (with scrubbing), select,
|
|
4
|
+
* switch, slider, segmented control and color.
|
|
5
|
+
*/
|
|
6
|
+
import { NumberField as BaseNumberField } from '@base-ui/react/number-field';
|
|
7
|
+
import { Select as BaseSelect } from '@base-ui/react/select';
|
|
8
|
+
import { Slider as BaseSlider } from '@base-ui/react/slider';
|
|
9
|
+
import { Switch as BaseSwitch } from '@base-ui/react/switch';
|
|
10
|
+
import { ToggleGroup } from '@base-ui/react/toggle-group';
|
|
11
|
+
import { Toggle } from '@base-ui/react/toggle';
|
|
12
|
+
import { Check, ChevronDown } from 'lucide-react';
|
|
13
|
+
import { forwardRef, useEffect, useState } from 'react';
|
|
14
|
+
import { cn } from "./cn.js";
|
|
15
|
+
import { preventRepeatedActivation } from "./keys.js";
|
|
16
|
+
import { POPUP_CLASS } from "./menu.js";
|
|
17
|
+
/** Shared look of single-line inputs. */
|
|
18
|
+
export const INPUT_CLASS = 'h-7 w-full min-w-0 rounded-control border border-line bg-surface-2 px-2 text-[13px] text-fg outline-none placeholder:text-fg-subtle focus:border-accent focus:bg-surface';
|
|
19
|
+
/** A plain text input. */
|
|
20
|
+
export const TextInput = forwardRef(function TextInput({ className, ...rest }, ref) {
|
|
21
|
+
return _jsx("input", { ref: ref, className: cn(INPUT_CLASS, className), ...rest });
|
|
22
|
+
});
|
|
23
|
+
/**
|
|
24
|
+
* A text input that keeps a local draft and commits on Enter or blur; Escape
|
|
25
|
+
* restores the last committed value. Inspector edits use it so every
|
|
26
|
+
* keystroke does not become a document write.
|
|
27
|
+
*/
|
|
28
|
+
export function CommitInput({ value, onCommit, className, ...rest }) {
|
|
29
|
+
const [draft, setDraft] = useState(value);
|
|
30
|
+
useEffect(() => setDraft(value), [value]);
|
|
31
|
+
const commit = () => {
|
|
32
|
+
if (draft !== value)
|
|
33
|
+
onCommit(draft);
|
|
34
|
+
};
|
|
35
|
+
return (_jsx("input", { className: cn(INPUT_CLASS, className), value: draft, onChange: (event) => setDraft(event.target.value), onBlur: commit, onKeyDown: (event) => {
|
|
36
|
+
if (event.key === 'Enter') {
|
|
37
|
+
commit();
|
|
38
|
+
event.target.blur();
|
|
39
|
+
}
|
|
40
|
+
else if (event.key === 'Escape') {
|
|
41
|
+
setDraft(value);
|
|
42
|
+
event.target.blur();
|
|
43
|
+
}
|
|
44
|
+
}, ...rest }));
|
|
45
|
+
}
|
|
46
|
+
/** A number field whose label can be dragged horizontally to scrub the value. */
|
|
47
|
+
export function NumberInput({ value, onChange, onCommit, label, unit, min, max, step = 1, placeholder, className, ...aria }) {
|
|
48
|
+
return (_jsxs(BaseNumberField.Root, { value: value, min: min, max: max, step: step, onValueChange: (next) => onChange?.(next), onValueCommitted: (next) => onCommit(next), className: cn('flex h-7 min-w-0 items-center rounded-control border border-line bg-surface-2 focus-within:border-accent', className), children: [label !== undefined ? (_jsxs(BaseNumberField.ScrubArea, { className: "flex h-full w-6 shrink-0 cursor-ew-resize items-center justify-center text-[11px] text-fg-subtle", children: [label, _jsx(BaseNumberField.ScrubAreaCursor, {})] })) : null, _jsx(BaseNumberField.Input, { placeholder: placeholder, "aria-label": aria['aria-label'], className: cn('h-full w-full min-w-0 bg-transparent text-[13px] text-fg outline-none', label === undefined && 'pl-2') }), unit ? _jsx("span", { className: "pr-2 text-[11px] text-fg-subtle", children: unit }) : null] }));
|
|
49
|
+
}
|
|
50
|
+
/** A dropdown select. */
|
|
51
|
+
export function SelectInput({ value, options, onChange, placeholder = '—', className, ...aria }) {
|
|
52
|
+
return (_jsxs(BaseSelect.Root, { value: value, onValueChange: (next) => next !== null && onChange(next), children: [_jsxs(BaseSelect.Trigger, { "aria-label": aria['aria-label'], className: cn(INPUT_CLASS, 'flex items-center justify-between gap-1 text-left', className), children: [_jsx(BaseSelect.Value, { children: (current) => options.find((option) => option.value === current)?.label ?? _jsx("span", { className: "text-fg-subtle", children: placeholder }) }), _jsx(BaseSelect.Icon, { children: _jsx(ChevronDown, { className: "size-3.5 text-fg-subtle" }) })] }), _jsx(BaseSelect.Portal, { children: _jsx(BaseSelect.Positioner, { sideOffset: 4, className: "z-[1000]", alignItemWithTrigger: false, children: _jsx(BaseSelect.Popup, { className: cn(POPUP_CLASS, 'max-h-80 overflow-auto'), children: _jsx(BaseSelect.List, { children: options.map((option) => (_jsxs(BaseSelect.Item, { value: option.value, className: "flex h-7 min-w-32 cursor-default select-none items-center gap-2 rounded-md px-2 outline-none data-[highlighted]:bg-hover", children: [_jsx("span", { className: "flex size-4 items-center justify-center", children: _jsx(BaseSelect.ItemIndicator, { children: _jsx(Check, { className: "size-3.5" }) }) }), _jsx(BaseSelect.ItemText, { children: option.label })] }, option.value))) }) }) }) })] }));
|
|
53
|
+
}
|
|
54
|
+
/** A segmented control (one of a few options, all visible). */
|
|
55
|
+
export function Segmented({ value, options, onChange, className, ...aria }) {
|
|
56
|
+
return (_jsx(ToggleGroup, { value: value === null ? [] : [value], onValueChange: (next) => {
|
|
57
|
+
const picked = next[0];
|
|
58
|
+
if (picked !== undefined)
|
|
59
|
+
onChange(picked);
|
|
60
|
+
}, "aria-label": aria['aria-label'], className: cn('flex h-7 items-center gap-0.5 rounded-control bg-surface-2 p-0.5', className), children: options.map((option) => (_jsx(Toggle, { value: option.value, "aria-label": option.title, title: option.title, className: "flex h-full flex-1 items-center justify-center rounded-[4px] px-1.5 text-fg-muted outline-none hover:text-fg data-[pressed]:bg-surface data-[pressed]:text-fg data-[pressed]:shadow-sm focus-visible:outline-2 focus-visible:outline-accent", children: option.label }, option.value))) }));
|
|
61
|
+
}
|
|
62
|
+
/** An on/off switch. A held Enter flips it once. */
|
|
63
|
+
export function SwitchInput({ checked, onChange, disabled, ...aria }) {
|
|
64
|
+
return (_jsx(BaseSwitch.Root, { checked: checked, disabled: disabled, onCheckedChange: (next) => onChange(next), onKeyDown: preventRepeatedActivation, "aria-label": aria['aria-label'], className: "relative inline-flex h-4 w-7 shrink-0 items-center rounded-full bg-line-strong p-0.5 transition-colors data-[checked]:bg-accent disabled:opacity-40", children: _jsx(BaseSwitch.Thumb, { className: "size-3 rounded-full bg-white shadow transition-transform data-[checked]:translate-x-3" }) }));
|
|
65
|
+
}
|
|
66
|
+
/** A horizontal slider. */
|
|
67
|
+
export function SliderInput({ value, min, max, step = 1, onChange, onCommit, ...aria }) {
|
|
68
|
+
return (_jsx(BaseSlider.Root, { value: value, min: min, max: max, step: step, onValueChange: (next) => onChange(Array.isArray(next) ? (next[0] ?? min) : next), onValueCommitted: (next) => onCommit?.(Array.isArray(next) ? (next[0] ?? min) : next), className: "flex h-7 w-full items-center", children: _jsx(BaseSlider.Control, { className: "flex h-4 w-full items-center", children: _jsxs(BaseSlider.Track, { className: "h-1 w-full rounded-full bg-line-strong", children: [_jsx(BaseSlider.Indicator, { className: "rounded-full bg-accent" }), _jsx(BaseSlider.Thumb, { "aria-label": aria['aria-label'], className: "size-3.5 rounded-full border border-line-strong bg-white shadow outline-none focus-visible:outline-2 focus-visible:outline-accent" })] }) }) }));
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* A color field: a swatch opening the browser's picker, a text field for any
|
|
72
|
+
* CSS color (hex, rgb, oklch, `var(--token)`), and optional token swatches.
|
|
73
|
+
*/
|
|
74
|
+
export function ColorInput({ value, onCommit, swatches, placeholder = 'none', ...aria }) {
|
|
75
|
+
const hex = value && /^#[0-9a-f]{6}$/i.test(value) ? value : '#000000';
|
|
76
|
+
return (_jsxs("div", { className: "flex min-w-0 flex-col gap-1.5", children: [_jsxs("div", { className: "flex min-w-0 items-center gap-1.5", children: [_jsx("label", { className: "relative size-7 shrink-0 overflow-hidden rounded-control border border-line", style: { background: value ?? 'transparent' }, title: "Pick a color", children: _jsx("input", { type: "color", value: hex, "aria-label": aria['aria-label'] ? `${aria['aria-label']} picker` : 'Color picker', onChange: (event) => onCommit(event.target.value), className: "absolute inset-0 cursor-pointer opacity-0" }) }), _jsx(CommitInput, { value: value ?? '', onCommit: onCommit, placeholder: placeholder, "aria-label": aria['aria-label'] })] }), swatches && swatches.length ? (_jsx("div", { className: "flex flex-wrap gap-1", children: swatches.map((swatch) => (_jsx("button", { type: "button", title: swatch.label, "aria-label": swatch.label, onClick: () => onCommit(swatch.css ?? swatch.value), className: "size-5 rounded-[4px] border border-line", style: { background: swatch.value } }, swatch.label))) })) : null] }));
|
|
77
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Which descendants a keyboard user can Tab to, and whether a box scrolls.
|
|
3
|
+
* {@link ScrollBody} uses both to give a scrolling region with no tab stop
|
|
4
|
+
* of its own one, so it can be scrolled from the keyboard.
|
|
5
|
+
*/
|
|
6
|
+
/** Elements that may be tab stops. */
|
|
7
|
+
export declare const TABBABLE_CANDIDATE_SELECTOR: string;
|
|
8
|
+
/** True when `element` is a tab stop: enabled, shown, not hidden from assistive technology. */
|
|
9
|
+
export declare function isTabbable(element: HTMLElement): boolean;
|
|
10
|
+
/** The tab stops inside `root`, in document order. */
|
|
11
|
+
export declare function tabbableElements(root: ParentNode): HTMLElement[];
|
|
12
|
+
/** The sizes and overflow styles {@link scrollsOverflow} reads. */
|
|
13
|
+
export interface ScrollMetrics {
|
|
14
|
+
scrollWidth: number;
|
|
15
|
+
clientWidth: number;
|
|
16
|
+
scrollHeight: number;
|
|
17
|
+
clientHeight: number;
|
|
18
|
+
overflowX: string;
|
|
19
|
+
overflowY: string;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* True when the content overflows an axis that scrolls (`auto` or
|
|
23
|
+
* `scroll`; `visible`, `hidden` and `clip` do not). A pixel of rounding is
|
|
24
|
+
* ignored.
|
|
25
|
+
*/
|
|
26
|
+
export declare function scrollsOverflow(metrics: ScrollMetrics): boolean;
|