@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
|
@@ -0,0 +1,370 @@
|
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
/**
|
|
3
|
+
* Color picking: {@link ColorPicker} (a trigger and popover) and
|
|
4
|
+
* {@link ColorPickerPanel} (the popover's body, for embedding): a
|
|
5
|
+
* saturation/brightness area, hue and alpha sliders, a format switcher
|
|
6
|
+
* (hex, rgb, hsl, oklch), a text field, the browser's eyedropper, swatches
|
|
7
|
+
* (design tokens) and recent colors, and an optional WCAG contrast check.
|
|
8
|
+
*/
|
|
9
|
+
import { Popover as BasePopover } from '@base-ui/react/popover';
|
|
10
|
+
import { Pipette, X } from 'lucide-react';
|
|
11
|
+
import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore, } from 'react';
|
|
12
|
+
import { cn } from "./cn.js";
|
|
13
|
+
import { contrastLevel, contrastRatio, contrastTarget, editFormat, formatColor, hsvaToRgba, parseColor, readableShade, rgbaToHsva, sameColor, } from "./color.js";
|
|
14
|
+
import { CommitInput, Segmented } from "./fields.js";
|
|
15
|
+
import { preventRepeatedActivation } from "./keys.js";
|
|
16
|
+
import { POPUP_CLASS } from "./menu.js";
|
|
17
|
+
/** A checkerboard, under translucent colors. */
|
|
18
|
+
export const CHECKERBOARD = 'repeating-conic-gradient(#d4d4d4 0% 25%, #ffffff 0% 50%) 0 0 / 8px 8px';
|
|
19
|
+
/* ------------------------------ recent colors ----------------------------- */
|
|
20
|
+
const RECENT_KEY = 'open-artifact.recent-colors';
|
|
21
|
+
const RECENT_MAX = 12;
|
|
22
|
+
let recent = null;
|
|
23
|
+
const recentListeners = new Set();
|
|
24
|
+
function readRecent() {
|
|
25
|
+
if (recent)
|
|
26
|
+
return recent;
|
|
27
|
+
recent = [];
|
|
28
|
+
try {
|
|
29
|
+
const stored = JSON.parse(globalThis.localStorage?.getItem(RECENT_KEY) ?? '[]');
|
|
30
|
+
if (Array.isArray(stored))
|
|
31
|
+
recent = stored.filter((item) => typeof item === 'string').slice(0, RECENT_MAX);
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
// Storage may be blocked; recents then last for the page.
|
|
35
|
+
}
|
|
36
|
+
return recent;
|
|
37
|
+
}
|
|
38
|
+
/** Adds a color to the shared recent colors (most recent first, no repeats, 12 kept). */
|
|
39
|
+
export function pushRecentColor(color) {
|
|
40
|
+
const text = color.trim();
|
|
41
|
+
if (!text)
|
|
42
|
+
return;
|
|
43
|
+
const list = readRecent();
|
|
44
|
+
recent = [text, ...list.filter((item) => !sameColor(item, text))].slice(0, RECENT_MAX);
|
|
45
|
+
try {
|
|
46
|
+
globalThis.localStorage?.setItem(RECENT_KEY, JSON.stringify(recent));
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
// Ignored: see readRecent.
|
|
50
|
+
}
|
|
51
|
+
recentListeners.forEach((listener) => listener());
|
|
52
|
+
}
|
|
53
|
+
/** The shared recent colors (kept in local storage per browser). */
|
|
54
|
+
export function useRecentColors() {
|
|
55
|
+
return useSyncExternalStore((listener) => {
|
|
56
|
+
recentListeners.add(listener);
|
|
57
|
+
return () => recentListeners.delete(listener);
|
|
58
|
+
}, readRecent, () => []);
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* The contrast of `color` on `against`: "Contrast 7.2:1" with the WCAG level
|
|
62
|
+
* reached, or "Contrast poor, 2.1:1" and a fix when below the target.
|
|
63
|
+
* Renders nothing when either color cannot be read (a `var()`).
|
|
64
|
+
*/
|
|
65
|
+
export function ContrastBadge({ color, against, level = 'AA', large = false, onFix, className }) {
|
|
66
|
+
const ratio = contrastRatio(color, against);
|
|
67
|
+
if (ratio === null)
|
|
68
|
+
return null;
|
|
69
|
+
const target = contrastTarget(level, large);
|
|
70
|
+
const reached = contrastLevel(ratio, large);
|
|
71
|
+
const passes = ratio >= target;
|
|
72
|
+
const shown = `${(Math.floor(ratio * 100) / 100).toFixed(2).replace(/\.?0+$/, '')}:1`;
|
|
73
|
+
const fix = !passes && onFix ? readableShade(color, against, target) : null;
|
|
74
|
+
return (_jsxs("div", { className: cn('flex min-w-0 items-center gap-2 text-xs', className), role: "status", children: [_jsx("span", { "aria-hidden": "true", className: "flex size-5 shrink-0 items-center justify-center rounded-[4px] text-[11px] font-semibold shadow-[inset_0_0_0_1px_rgb(0_0_0/0.12)]", style: { background: `linear-gradient(${against}, ${against}), ${CHECKERBOARD}`, color }, children: "Aa" }), _jsx("span", { className: cn('min-w-0 flex-1 truncate', passes ? 'text-fg-muted' : 'text-warning'), children: passes ? `Contrast ${shown}` : `Contrast poor, ${shown}` }), _jsx("span", { className: cn('shrink-0 rounded px-1 py-px text-[10px] font-semibold', passes ? 'bg-accent-soft text-accent' : 'bg-hover text-warning'), title: `WCAG ${level}${large ? ' (large text)' : ''} needs ${target}:1`, children: reached === 'Fail' ? 'Fail' : reached }), fix ? (_jsx("button", { type: "button", onClick: () => onFix?.(fix), onKeyDown: preventRepeatedActivation, className: "shrink-0 rounded px-1 text-accent outline-none hover:underline focus-visible:outline-2 focus-visible:outline-accent", title: `Use ${fix}`, children: "Fix" })) : null] }));
|
|
75
|
+
}
|
|
76
|
+
/** Calls `fn` at most once per animation frame with the latest value. */
|
|
77
|
+
function useFrameThrottle(fn) {
|
|
78
|
+
const latest = useRef(null);
|
|
79
|
+
const frame = useRef(null);
|
|
80
|
+
const fnRef = useRef(fn);
|
|
81
|
+
fnRef.current = fn;
|
|
82
|
+
useEffect(() => () => {
|
|
83
|
+
if (frame.current !== null)
|
|
84
|
+
cancelAnimationFrame(frame.current);
|
|
85
|
+
}, []);
|
|
86
|
+
const flush = useCallback(() => {
|
|
87
|
+
if (frame.current !== null)
|
|
88
|
+
cancelAnimationFrame(frame.current);
|
|
89
|
+
frame.current = null;
|
|
90
|
+
if (latest.current)
|
|
91
|
+
fnRef.current(latest.current.value);
|
|
92
|
+
latest.current = null;
|
|
93
|
+
}, []);
|
|
94
|
+
const call = useCallback((value) => {
|
|
95
|
+
latest.current = { value };
|
|
96
|
+
if (frame.current !== null)
|
|
97
|
+
return;
|
|
98
|
+
frame.current = requestAnimationFrame(() => {
|
|
99
|
+
frame.current = null;
|
|
100
|
+
if (latest.current)
|
|
101
|
+
fnRef.current(latest.current.value);
|
|
102
|
+
latest.current = null;
|
|
103
|
+
});
|
|
104
|
+
}, []);
|
|
105
|
+
return { call, flush };
|
|
106
|
+
}
|
|
107
|
+
const FORMAT_OPTIONS = [
|
|
108
|
+
{ value: 'hex', label: 'HEX', title: 'Hex' },
|
|
109
|
+
{ value: 'rgb', label: 'RGB', title: 'RGB' },
|
|
110
|
+
{ value: 'hsl', label: 'HSL', title: 'HSL' },
|
|
111
|
+
{ value: 'oklch', label: 'OKLCH', title: 'OKLCH' },
|
|
112
|
+
];
|
|
113
|
+
const BLACK_HSVA = { h: 0, s: 0, v: 0, a: 1 };
|
|
114
|
+
/** The picker body: area, sliders, format, text, eyedropper, swatches, recents, contrast. */
|
|
115
|
+
export function ColorPickerPanel({ value, onChange, onCommit, fallback, format: formatProp, alpha = true, swatches, recent: recentProp, contrastAgainst, contrastLevel: level = 'AA', largeText = false, onClear, className, }) {
|
|
116
|
+
const parsed = useMemo(() => (value ? parseColor(value) : null), [value]);
|
|
117
|
+
const [format, setFormat] = useState(() => (parsed ? editFormat(parsed.notation) : (formatProp ?? 'hex')));
|
|
118
|
+
/** Notation details kept while the format stays the value's own (commas, hex case). */
|
|
119
|
+
const notation = parsed && editFormat(parsed.notation) === format && parsed.notation.format !== 'named' ? parsed.notation : {};
|
|
120
|
+
const [hsva, setHsva] = useState(() => {
|
|
121
|
+
const start = parsed ?? (fallback ? parseColor(fallback) : null);
|
|
122
|
+
return start ? rgbaToHsva(start.rgba) : BLACK_HSVA;
|
|
123
|
+
});
|
|
124
|
+
/** The last text this panel emitted, so its own echo does not reset the hue. */
|
|
125
|
+
const emitted = useRef(null);
|
|
126
|
+
const sharedRecent = useRecentColors();
|
|
127
|
+
const recentColors = recentProp === false ? [] : (recentProp ?? sharedRecent);
|
|
128
|
+
// Follow outside edits (undo, a token picked elsewhere).
|
|
129
|
+
useEffect(() => {
|
|
130
|
+
if (value !== null && value === emitted.current)
|
|
131
|
+
return;
|
|
132
|
+
const next = parsed ?? (fallback ? parseColor(fallback) : null);
|
|
133
|
+
if (!next)
|
|
134
|
+
return;
|
|
135
|
+
setHsva((current) => (sameColor(hsvaToRgba(current), next.rgba) ? current : rgbaToHsva(next.rgba, current.h)));
|
|
136
|
+
if (parsed)
|
|
137
|
+
setFormat(editFormat(parsed.notation));
|
|
138
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
139
|
+
}, [value]);
|
|
140
|
+
const text = (next, fmt = format) => formatColor(hsvaToRgba(alpha ? next : { ...next, a: 1 }), fmt, fmt === format ? notation : {});
|
|
141
|
+
const live = useFrameThrottle((next) => onChange(next));
|
|
142
|
+
const commit = (next) => {
|
|
143
|
+
live.flush();
|
|
144
|
+
emitted.current = next;
|
|
145
|
+
onChange(next);
|
|
146
|
+
onCommit?.(next);
|
|
147
|
+
if (recentProp === undefined)
|
|
148
|
+
pushRecentColor(next);
|
|
149
|
+
};
|
|
150
|
+
/** A drag step: update the picker and emit live. */
|
|
151
|
+
const drag = (next) => {
|
|
152
|
+
const fixed = alpha ? next : { ...next, a: 1 };
|
|
153
|
+
setHsva(fixed);
|
|
154
|
+
const out = text(fixed);
|
|
155
|
+
emitted.current = out;
|
|
156
|
+
live.call(out);
|
|
157
|
+
};
|
|
158
|
+
/** A keyboard step or a release: update and commit. */
|
|
159
|
+
const settle = (next) => {
|
|
160
|
+
const fixed = alpha ? next : { ...next, a: 1 };
|
|
161
|
+
setHsva(fixed);
|
|
162
|
+
commit(text(fixed));
|
|
163
|
+
};
|
|
164
|
+
const pickText = (raw) => {
|
|
165
|
+
const typed = raw.trim();
|
|
166
|
+
if (!typed)
|
|
167
|
+
return;
|
|
168
|
+
const hexless = /^[0-9a-f]{3,8}$/i.test(typed) ? `#${typed}` : typed;
|
|
169
|
+
const next = parseColor(hexless);
|
|
170
|
+
if (next) {
|
|
171
|
+
setHsva(rgbaToHsva(alpha ? next.rgba : { ...next.rgba, a: 1 }, hsva.h));
|
|
172
|
+
setFormat(editFormat(next.notation));
|
|
173
|
+
commit(alpha || next.rgba.a === 1 ? hexless : formatColor({ ...next.rgba, a: 1 }, editFormat(next.notation), next.notation));
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
// Other CSS colors (`var(--x)`, `color-mix()`) pass through when the browser reads them.
|
|
177
|
+
if (typeof CSS !== 'undefined' && CSS.supports('color', typed))
|
|
178
|
+
commit(typed);
|
|
179
|
+
};
|
|
180
|
+
const pickSwatch = (swatch) => {
|
|
181
|
+
const next = parseColor(swatch.value);
|
|
182
|
+
if (next)
|
|
183
|
+
setHsva(rgbaToHsva(next.rgba, hsva.h));
|
|
184
|
+
commit(swatch.css ?? swatch.value);
|
|
185
|
+
};
|
|
186
|
+
const switchFormat = (next) => {
|
|
187
|
+
setFormat(next);
|
|
188
|
+
if (value === null || parsed)
|
|
189
|
+
commit(formatColor(hsvaToRgba(alpha ? hsva : { ...hsva, a: 1 }), next, {}, next === 'oklch' && parsed?.notation.format === 'oklch' ? parsed.oklch : undefined));
|
|
190
|
+
};
|
|
191
|
+
const dropper = typeof window !== 'undefined' && 'EyeDropper' in window ? window.EyeDropper : null;
|
|
192
|
+
const rgb = hsvaToRgba({ ...hsva, a: 1 });
|
|
193
|
+
const solid = formatColor(rgb, 'hex');
|
|
194
|
+
const shownText = value !== null && !parsed ? value : text(hsva);
|
|
195
|
+
const current = value ?? null;
|
|
196
|
+
const groups = useMemo(() => {
|
|
197
|
+
const out = new Map();
|
|
198
|
+
for (const swatch of swatches ?? []) {
|
|
199
|
+
const key = swatch.group ?? '';
|
|
200
|
+
out.set(key, [...(out.get(key) ?? []), swatch]);
|
|
201
|
+
}
|
|
202
|
+
return [...out.entries()];
|
|
203
|
+
}, [swatches]);
|
|
204
|
+
return (_jsxs("div", { className: cn('flex w-60 flex-col gap-3', className), children: [_jsx(ColorArea, { hsva: hsva, onDrag: drag, onSettle: settle }), _jsx(ColorSlider, { label: "Hue", value: hsva.h / 360, background: "linear-gradient(to right, #f00 0%, #ff0 16.67%, #0f0 33.33%, #0ff 50%, #00f 66.67%, #f0f 83.33%, #f00 100%)", thumb: `hsl(${hsva.h} 100% 50%)`, valueText: `${Math.round(hsva.h)} degrees`, onDrag: (t) => drag({ ...hsva, h: Math.min(359.9, t * 360) }), onSettle: (t) => settle({ ...hsva, h: Math.min(359.9, t * 360) }) }), alpha ? (_jsx(ColorSlider, { label: "Opacity", value: hsva.a, background: `linear-gradient(to right, transparent, ${solid}), ${CHECKERBOARD}`, thumb: formatColor({ ...rgb, a: hsva.a }, 'rgb'), valueText: `${Math.round(hsva.a * 100)}%`, onDrag: (t) => drag({ ...hsva, a: Math.round(t * 100) / 100 }), onSettle: (t) => settle({ ...hsva, a: Math.round(t * 100) / 100 }) })) : null, _jsx(Segmented, { "aria-label": "Color format", value: parsed || value === null ? format : null, options: FORMAT_OPTIONS, onChange: switchFormat, className: "text-[11px]" }), _jsxs("div", { className: "flex items-center gap-1.5", children: [_jsx("span", { "aria-hidden": "true", className: "size-7 shrink-0 rounded-control shadow-[inset_0_0_0_1px_rgb(0_0_0/0.12)]", style: { background: `linear-gradient(${formatColor(hsvaToRgba(hsva), 'rgb')}, ${formatColor(hsvaToRgba(hsva), 'rgb')}), ${CHECKERBOARD}` } }), _jsx(CommitInput, { "aria-label": "Color value", value: shownText, onCommit: pickText, spellCheck: false, className: "font-mono text-[12px]" }), dropper ? (_jsx("button", { type: "button", "aria-label": "Pick a color from the screen", title: "Pick a color from the screen", onKeyDown: preventRepeatedActivation, onClick: () => {
|
|
205
|
+
void new dropper()
|
|
206
|
+
.open()
|
|
207
|
+
.then((result) => {
|
|
208
|
+
const picked = parseColor(result.sRGBHex);
|
|
209
|
+
if (picked)
|
|
210
|
+
settle(rgbaToHsva({ ...picked.rgba, a: hsva.a }, hsva.h));
|
|
211
|
+
})
|
|
212
|
+
.catch(() => undefined);
|
|
213
|
+
}, className: "flex size-7 shrink-0 items-center justify-center rounded-control text-fg-muted outline-none hover:bg-hover hover:text-fg focus-visible:outline-2 focus-visible:outline-accent", children: _jsx(Pipette, { className: "size-4" }) })) : null, onClear ? (_jsx("button", { type: "button", "aria-label": "No color", title: "No color", onKeyDown: preventRepeatedActivation, onClick: onClear, className: "flex size-7 shrink-0 items-center justify-center rounded-control text-fg-muted outline-none hover:bg-hover hover:text-fg focus-visible:outline-2 focus-visible:outline-accent", children: _jsx(X, { className: "size-4" }) })) : null] }), contrastAgainst ? (_jsx(ContrastBadge, { color: value !== null && !parsed ? value : text(hsva), against: contrastAgainst, level: level, large: largeText, onFix: (fix) => {
|
|
214
|
+
const next = parseColor(fix);
|
|
215
|
+
if (next)
|
|
216
|
+
setHsva(rgbaToHsva(next.rgba, hsva.h));
|
|
217
|
+
commit(fix);
|
|
218
|
+
} })) : null, groups.map(([group, items]) => (_jsx(SwatchGrid, { title: group || (groups.length > 1 || recentColors.length ? 'Colors' : undefined), label: group || 'Swatches', children: items.map((swatch) => (_jsx(SwatchButton, { name: swatch.name, color: swatch.value, selected: current !== null && (current === swatch.css || (swatch.css === undefined && sameColor(current, swatch.value))), onPick: () => pickSwatch(swatch) }, `${swatch.name}:${swatch.css ?? swatch.value}`))) }, group || '_'))), recentColors.length ? (_jsx(SwatchGrid, { title: "Recent", label: "Recent colors", children: recentColors.map((color) => (_jsx(SwatchButton, { name: color, color: color, selected: false, onPick: () => pickSwatch({ value: color }) }, color))) })) : null] }));
|
|
219
|
+
}
|
|
220
|
+
/* ------------------------------ area & sliders ----------------------------- */
|
|
221
|
+
/** Pointer position inside `element`, 0–1 on both axes. */
|
|
222
|
+
function relative(event, element) {
|
|
223
|
+
const box = element.getBoundingClientRect();
|
|
224
|
+
return {
|
|
225
|
+
x: Math.max(0, Math.min(1, (event.clientX - box.left) / Math.max(1, box.width))),
|
|
226
|
+
y: Math.max(0, Math.min(1, (event.clientY - box.top) / Math.max(1, box.height))),
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
/** Arrow-key step: 1%, Shift 10%. */
|
|
230
|
+
const keyStep = (event) => (event.shiftKey ? 0.1 : 0.01);
|
|
231
|
+
const clamp01 = (value) => Math.max(0, Math.min(1, value));
|
|
232
|
+
const THUMB = 'pointer-events-none absolute size-3.5 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-white shadow-[0_0_0_1px_rgb(0_0_0/0.3),0_1px_3px_rgb(0_0_0/0.3)]';
|
|
233
|
+
/** The saturation (x) / brightness (y) area at the current hue. */
|
|
234
|
+
function ColorArea({ hsva, onDrag, onSettle }) {
|
|
235
|
+
const last = useRef(hsva);
|
|
236
|
+
last.current = hsva;
|
|
237
|
+
const at = (event) => {
|
|
238
|
+
const { x, y } = relative(event, event.currentTarget);
|
|
239
|
+
return { ...last.current, s: x, v: 1 - y };
|
|
240
|
+
};
|
|
241
|
+
const onKeyDown = (event) => {
|
|
242
|
+
const d = keyStep(event);
|
|
243
|
+
const moves = {
|
|
244
|
+
ArrowLeft: { s: hsva.s - d },
|
|
245
|
+
ArrowRight: { s: hsva.s + d },
|
|
246
|
+
ArrowUp: { v: hsva.v + d },
|
|
247
|
+
ArrowDown: { v: hsva.v - d },
|
|
248
|
+
Home: { s: 0 },
|
|
249
|
+
End: { s: 1 },
|
|
250
|
+
PageUp: { v: hsva.v + 0.1 },
|
|
251
|
+
PageDown: { v: hsva.v - 0.1 },
|
|
252
|
+
};
|
|
253
|
+
const move = moves[event.key];
|
|
254
|
+
if (!move)
|
|
255
|
+
return;
|
|
256
|
+
event.preventDefault();
|
|
257
|
+
onSettle({ ...hsva, s: clamp01(move.s ?? hsva.s), v: clamp01(move.v ?? hsva.v) });
|
|
258
|
+
};
|
|
259
|
+
return (_jsx("div", { role: "slider", tabIndex: 0, "aria-label": "Saturation and brightness", "aria-valuemin": 0, "aria-valuemax": 100, "aria-valuenow": Math.round(hsva.s * 100), "aria-valuetext": `Saturation ${Math.round(hsva.s * 100)}%, brightness ${Math.round(hsva.v * 100)}%`, className: "relative aspect-[3/2] w-full cursor-crosshair touch-none rounded-[6px] outline-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-accent", style: { background: `linear-gradient(to top, #000, transparent), linear-gradient(to right, #fff, transparent), hsl(${hsva.h} 100% 50%)` }, onPointerDown: (event) => {
|
|
260
|
+
if (event.button !== 0)
|
|
261
|
+
return;
|
|
262
|
+
event.currentTarget.setPointerCapture(event.pointerId);
|
|
263
|
+
event.currentTarget.focus();
|
|
264
|
+
onDrag(at(event));
|
|
265
|
+
}, onPointerMove: (event) => {
|
|
266
|
+
if (event.currentTarget.hasPointerCapture(event.pointerId))
|
|
267
|
+
onDrag(at(event));
|
|
268
|
+
}, onPointerUp: (event) => {
|
|
269
|
+
if (!event.currentTarget.hasPointerCapture(event.pointerId))
|
|
270
|
+
return;
|
|
271
|
+
event.currentTarget.releasePointerCapture(event.pointerId);
|
|
272
|
+
onSettle(at(event));
|
|
273
|
+
}, onKeyDown: onKeyDown, children: _jsx("span", { className: THUMB, style: { left: `${hsva.s * 100}%`, top: `${(1 - hsva.v) * 100}%`, background: formatColor(hsvaToRgba({ ...hsva, a: 1 }), 'hex') } }) }));
|
|
274
|
+
}
|
|
275
|
+
/** A horizontal 0–1 slider painted with `background` (hue, opacity). */
|
|
276
|
+
function ColorSlider({ label, value, background, thumb, valueText, onDrag, onSettle, }) {
|
|
277
|
+
const onKeyDown = (event) => {
|
|
278
|
+
const d = keyStep(event);
|
|
279
|
+
const moves = {
|
|
280
|
+
ArrowLeft: value - d,
|
|
281
|
+
ArrowDown: value - d,
|
|
282
|
+
ArrowRight: value + d,
|
|
283
|
+
ArrowUp: value + d,
|
|
284
|
+
PageDown: value - 0.1,
|
|
285
|
+
PageUp: value + 0.1,
|
|
286
|
+
Home: 0,
|
|
287
|
+
End: 1,
|
|
288
|
+
};
|
|
289
|
+
const next = moves[event.key];
|
|
290
|
+
if (next === undefined)
|
|
291
|
+
return;
|
|
292
|
+
event.preventDefault();
|
|
293
|
+
onSettle(clamp01(next));
|
|
294
|
+
};
|
|
295
|
+
return (_jsx("div", { role: "slider", tabIndex: 0, "aria-label": label, "aria-valuemin": 0, "aria-valuemax": 100, "aria-valuenow": Math.round(value * 100), "aria-valuetext": valueText, className: "relative h-3 w-full cursor-pointer touch-none rounded-full shadow-[inset_0_0_0_1px_rgb(0_0_0/0.1)] outline-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-accent", style: { background }, onPointerDown: (event) => {
|
|
296
|
+
if (event.button !== 0)
|
|
297
|
+
return;
|
|
298
|
+
event.currentTarget.setPointerCapture(event.pointerId);
|
|
299
|
+
event.currentTarget.focus();
|
|
300
|
+
onDrag(relative(event, event.currentTarget).x);
|
|
301
|
+
}, onPointerMove: (event) => {
|
|
302
|
+
if (event.currentTarget.hasPointerCapture(event.pointerId))
|
|
303
|
+
onDrag(relative(event, event.currentTarget).x);
|
|
304
|
+
}, onPointerUp: (event) => {
|
|
305
|
+
if (!event.currentTarget.hasPointerCapture(event.pointerId))
|
|
306
|
+
return;
|
|
307
|
+
event.currentTarget.releasePointerCapture(event.pointerId);
|
|
308
|
+
onSettle(relative(event, event.currentTarget).x);
|
|
309
|
+
}, onKeyDown: onKeyDown, children: _jsx("span", { className: cn(THUMB, 'top-1/2'), style: { left: `${value * 100}%`, background: `linear-gradient(${thumb}, ${thumb}), ${CHECKERBOARD}` } }) }));
|
|
310
|
+
}
|
|
311
|
+
/* --------------------------------- swatches -------------------------------- */
|
|
312
|
+
/**
|
|
313
|
+
* A titled grid of swatches with one tab stop: arrow keys move between
|
|
314
|
+
* them, Home/End jump to the ends.
|
|
315
|
+
*/
|
|
316
|
+
function SwatchGrid({ title, label, children }) {
|
|
317
|
+
const onKeyDown = (event) => {
|
|
318
|
+
const buttons = [...event.currentTarget.querySelectorAll('button[data-swatch]')];
|
|
319
|
+
const at = buttons.indexOf(document.activeElement);
|
|
320
|
+
if (at < 0)
|
|
321
|
+
return;
|
|
322
|
+
const perRow = Math.max(1, Math.round(event.currentTarget.clientWidth / 24));
|
|
323
|
+
const moves = { ArrowLeft: at - 1, ArrowRight: at + 1, ArrowUp: at - perRow, ArrowDown: at + perRow, Home: 0, End: buttons.length - 1 };
|
|
324
|
+
const next = moves[event.key];
|
|
325
|
+
if (next === undefined)
|
|
326
|
+
return;
|
|
327
|
+
event.preventDefault();
|
|
328
|
+
const target = buttons[Math.max(0, Math.min(buttons.length - 1, next))];
|
|
329
|
+
buttons.forEach((button) => (button.tabIndex = button === target ? 0 : -1));
|
|
330
|
+
target?.focus();
|
|
331
|
+
};
|
|
332
|
+
// The first swatch (or the selected one) is the group's tab stop.
|
|
333
|
+
const ref = useCallback((element) => {
|
|
334
|
+
if (!element)
|
|
335
|
+
return;
|
|
336
|
+
const buttons = [...element.querySelectorAll('button[data-swatch]')];
|
|
337
|
+
const stop = buttons.find((button) => button.getAttribute('aria-pressed') === 'true') ?? buttons[0];
|
|
338
|
+
buttons.forEach((button) => (button.tabIndex = button === stop ? 0 : -1));
|
|
339
|
+
}, []);
|
|
340
|
+
return (_jsxs("div", { className: "flex flex-col gap-1.5", children: [title ? _jsx("div", { className: "text-[11px] font-medium text-fg-subtle", children: title }) : null, _jsx("div", { ref: ref, role: "group", "aria-label": label, onKeyDown: onKeyDown, className: "flex flex-wrap gap-1", children: children })] }));
|
|
341
|
+
}
|
|
342
|
+
function SwatchButton({ name, color, selected, onPick }) {
|
|
343
|
+
return (_jsx("button", { type: "button", "data-swatch": "", title: name, "aria-label": name, "aria-pressed": selected, onClick: onPick, onKeyDown: preventRepeatedActivation, className: cn('size-5 rounded-[4px] shadow-[inset_0_0_0_1px_rgb(0_0_0/0.12)] outline-none focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-accent', selected && 'outline-2 outline-offset-1 outline-fg'), style: { background: `linear-gradient(${color}, ${color}), ${CHECKERBOARD}` } }));
|
|
344
|
+
}
|
|
345
|
+
const MIXED_SWATCH = 'linear-gradient(135deg, #ffffff 50%, #1c1c1a 50%)';
|
|
346
|
+
/** What the trigger's swatch paints. */
|
|
347
|
+
function swatchPaint(value, fallback, mixed) {
|
|
348
|
+
if (mixed)
|
|
349
|
+
return MIXED_SWATCH;
|
|
350
|
+
const color = value ?? fallback;
|
|
351
|
+
return color ? `linear-gradient(${color}, ${color}), ${CHECKERBOARD}` : CHECKERBOARD;
|
|
352
|
+
}
|
|
353
|
+
/**
|
|
354
|
+
* A color control: a trigger (a field showing the swatch and value, or a
|
|
355
|
+
* swatch alone) that opens {@link ColorPickerPanel} in a popover.
|
|
356
|
+
*/
|
|
357
|
+
export function ColorPicker({ trigger = 'field', placeholder = 'None', mixed = false, disabled, side = 'bottom', align = 'start', open, onOpenChange, triggerClassName, ...panel }) {
|
|
358
|
+
const { value, fallback, swatches } = panel;
|
|
359
|
+
const label = panel['aria-label'];
|
|
360
|
+
const token = value ? swatches?.find((swatch) => swatch.css === value || (swatch.css === undefined && swatch.value === value)) : undefined;
|
|
361
|
+
const text = mixed ? 'Mixed' : value === null ? placeholder : (token?.name ?? value);
|
|
362
|
+
const alphaText = (() => {
|
|
363
|
+
if (mixed || !value)
|
|
364
|
+
return null;
|
|
365
|
+
const a = parseColor(value)?.rgba.a;
|
|
366
|
+
return a !== undefined && a < 1 ? `${Math.round(a * 100)}%` : null;
|
|
367
|
+
})();
|
|
368
|
+
const element = typeof trigger === 'object' ? (trigger) : trigger === 'swatch' ? (_jsx("button", { type: "button", "aria-label": `${label}: ${text}`, title: text, className: cn('size-5 shrink-0 rounded-[4px] shadow-[inset_0_0_0_1px_rgb(0_0_0/0.15)] outline-none focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-accent disabled:opacity-45', triggerClassName), style: { background: swatchPaint(value, fallback, mixed) } })) : (_jsxs("button", { type: "button", "aria-label": `${label}: ${text}`, className: cn('flex h-7 w-full min-w-0 items-center gap-1.5 rounded-control border border-line bg-surface-2 pl-1 pr-2 text-left text-[13px] text-fg outline-none', 'focus-visible:border-accent data-[popup-open]:border-accent disabled:opacity-45', triggerClassName), children: [_jsx("span", { className: "size-5 shrink-0 rounded-[4px] shadow-[inset_0_0_0_1px_rgb(0_0_0/0.12)]", style: { background: swatchPaint(value, fallback, mixed) } }), _jsx("span", { className: cn('min-w-0 flex-1 truncate', (value === null || mixed) && 'text-fg-subtle', !token && 'font-mono text-[12px]'), children: text }), alphaText ? _jsx("span", { className: "shrink-0 text-[11px] tabular-nums text-fg-subtle", children: alphaText }) : null] }));
|
|
369
|
+
return (_jsxs(BasePopover.Root, { open: open, onOpenChange: onOpenChange ? (next) => onOpenChange(next) : undefined, children: [_jsx(BasePopover.Trigger, { render: element, disabled: disabled, onKeyDown: preventRepeatedActivation }), _jsx(BasePopover.Portal, { children: _jsx(BasePopover.Positioner, { side: side, align: align, sideOffset: 6, collisionPadding: 8, className: "z-[1000]", children: _jsx(BasePopover.Popup, { "aria-label": `${label} color`, className: cn(POPUP_CLASS, 'p-3'), children: _jsx(ColorPickerPanel, { ...panel, value: mixed ? null : value }) }) }) })] }));
|
|
370
|
+
}
|
package/src/color.d.ts
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Color math for the editors' color controls, with no DOM: parsing and
|
|
3
|
+
* formatting CSS colors (hex, `rgb()`/`rgba()`, `hsl()`/`hsla()`,
|
|
4
|
+
* `oklch()`, named colors), conversion to and from HSV, HSL and OKLCH, and
|
|
5
|
+
* WCAG 2 contrast.
|
|
6
|
+
*
|
|
7
|
+
* Channels: {@link Rgba} holds sRGB `r`, `g`, `b` in 0–255 (fractions kept)
|
|
8
|
+
* and alpha in 0–1. Hue is in degrees everywhere.
|
|
9
|
+
*/
|
|
10
|
+
/** An sRGB color: channels 0–255, alpha 0–1. */
|
|
11
|
+
export interface Rgba {
|
|
12
|
+
r: number;
|
|
13
|
+
g: number;
|
|
14
|
+
b: number;
|
|
15
|
+
a: number;
|
|
16
|
+
}
|
|
17
|
+
/** Hue (degrees), saturation and value (0–1), alpha (0–1). The picker's model. */
|
|
18
|
+
export interface Hsva {
|
|
19
|
+
h: number;
|
|
20
|
+
s: number;
|
|
21
|
+
v: number;
|
|
22
|
+
a: number;
|
|
23
|
+
}
|
|
24
|
+
/** Hue (degrees), saturation and lightness (0–1), alpha (0–1). */
|
|
25
|
+
export interface Hsla {
|
|
26
|
+
h: number;
|
|
27
|
+
s: number;
|
|
28
|
+
l: number;
|
|
29
|
+
a: number;
|
|
30
|
+
}
|
|
31
|
+
/** OKLCH: lightness 0–1, chroma (0 to about 0.4), hue in degrees, alpha 0–1. */
|
|
32
|
+
export interface Oklch {
|
|
33
|
+
l: number;
|
|
34
|
+
c: number;
|
|
35
|
+
h: number;
|
|
36
|
+
a: number;
|
|
37
|
+
}
|
|
38
|
+
/** The notations {@link formatColor} writes. */
|
|
39
|
+
export type ColorFormat = 'hex' | 'rgb' | 'hsl' | 'oklch';
|
|
40
|
+
/** How a color was written, so an edit can be written back the same way. */
|
|
41
|
+
export interface ColorNotation {
|
|
42
|
+
/** The notation; a named color reports `'named'`. */
|
|
43
|
+
format: ColorFormat | 'named';
|
|
44
|
+
/** `rgba(255, 0, 0, 0.5)` style commas rather than `rgb(255 0 0 / 0.5)`. */
|
|
45
|
+
legacy?: boolean;
|
|
46
|
+
/** `rgba(`/`hsla(` rather than `rgb(`/`hsl(` (legacy notation only). */
|
|
47
|
+
alphaName?: boolean;
|
|
48
|
+
/** Uppercase hex digits. */
|
|
49
|
+
upper?: boolean;
|
|
50
|
+
/** Short hex (`#f80`) when the color allows it. */
|
|
51
|
+
short?: boolean;
|
|
52
|
+
}
|
|
53
|
+
/** A parsed CSS color. */
|
|
54
|
+
export interface ParsedColor {
|
|
55
|
+
rgba: Rgba;
|
|
56
|
+
notation: ColorNotation;
|
|
57
|
+
/** The exact OKLCH channels when the text was `oklch()` (no sRGB clipping). */
|
|
58
|
+
oklch?: Oklch;
|
|
59
|
+
}
|
|
60
|
+
/** The CSS named colors (lowercase name → `#rrggbb`). */
|
|
61
|
+
export declare const NAMED_COLORS: Readonly<Record<string, string>>;
|
|
62
|
+
/** The name of a color that is exactly a named color (opaque), else null. `transparent` for alpha 0. */
|
|
63
|
+
export declare function colorName(rgba: Rgba): string | null;
|
|
64
|
+
/** Clamps every channel into range (alpha too). */
|
|
65
|
+
export declare function clampRgba(rgba: Rgba): Rgba;
|
|
66
|
+
/**
|
|
67
|
+
* Parses a CSS color: `#rgb[a]`, `#rrggbb[aa]`, `rgb()`/`rgba()` (comma or
|
|
68
|
+
* space syntax, numbers or percentages), `hsl()`/`hsla()`, `oklch()`, a named
|
|
69
|
+
* color or `transparent`. Returns null for anything else (`var()`,
|
|
70
|
+
* `currentcolor`, `color-mix()`…).
|
|
71
|
+
*/
|
|
72
|
+
export declare function parseColor(input: string): ParsedColor | null;
|
|
73
|
+
/** The sRGB channels of a CSS color, or null when {@link parseColor} cannot read it. */
|
|
74
|
+
export declare function toRgba(input: string): Rgba | null;
|
|
75
|
+
/** True when {@link parseColor} reads `input`. */
|
|
76
|
+
export declare function isColor(input: string): boolean;
|
|
77
|
+
/** `#rrggbb`, or `#rrggbbaa` when translucent. */
|
|
78
|
+
export declare function formatHex(rgba: Rgba, options?: {
|
|
79
|
+
upper?: boolean;
|
|
80
|
+
short?: boolean;
|
|
81
|
+
}): string;
|
|
82
|
+
/**
|
|
83
|
+
* Writes `rgba` in `format`. `notation` keeps the details of how the original
|
|
84
|
+
* was written (comma syntax, `rgba(`, hex case). For `oklch`, pass `oklch`
|
|
85
|
+
* to write exact channels instead of converting `rgba`.
|
|
86
|
+
*/
|
|
87
|
+
export declare function formatColor(rgba: Rgba, format: ColorFormat, notation?: Omit<ColorNotation, 'format'>, oklch?: Oklch): string;
|
|
88
|
+
/** The format an edit of a color written as `notation` should come back in (named colors become hex). */
|
|
89
|
+
export declare function editFormat(notation: ColorNotation | undefined): ColorFormat;
|
|
90
|
+
/**
|
|
91
|
+
* Writes `rgba` the way `original` is written: same notation, comma syntax
|
|
92
|
+
* and hex case; a named original stays named when the new color is a named
|
|
93
|
+
* color, else becomes hex. An unreadable original gives hex.
|
|
94
|
+
*/
|
|
95
|
+
export declare function formatLike(original: string, rgba: Rgba): string;
|
|
96
|
+
/**
|
|
97
|
+
* Re-writes the color `text` in `format` (hex, rgb, hsl, oklch). Returns
|
|
98
|
+
* null when `text` is not a color.
|
|
99
|
+
*/
|
|
100
|
+
export declare function convertColor(text: string, format: ColorFormat): string | null;
|
|
101
|
+
/** True when two colors render the same (channels within half a step, alpha within 1%). */
|
|
102
|
+
export declare function sameColor(a: string | Rgba | null | undefined, b: string | Rgba | null | undefined): boolean;
|
|
103
|
+
/** sRGB to HSV. `hue` is kept for grays, which have none of their own. */
|
|
104
|
+
export declare function rgbaToHsva(rgba: Rgba, hue?: number): Hsva;
|
|
105
|
+
/** HSV to sRGB. */
|
|
106
|
+
export declare function hsvaToRgba(hsva: Hsva): Rgba;
|
|
107
|
+
/** sRGB to HSL. `hue` is kept for grays. */
|
|
108
|
+
export declare function rgbaToHsla(rgba: Rgba, hue?: number): Hsla;
|
|
109
|
+
/** HSL to sRGB. */
|
|
110
|
+
export declare function hslaToRgba(hsla: Hsla): Rgba;
|
|
111
|
+
/** sRGB to OKLCH. `hue` is kept for grays. */
|
|
112
|
+
export declare function rgbaToOklch(rgba: Rgba, hue?: number): Oklch;
|
|
113
|
+
/** True when an OKLCH color fits in sRGB. */
|
|
114
|
+
export declare function oklchInGamut(o: Oklch): boolean;
|
|
115
|
+
/**
|
|
116
|
+
* OKLCH to sRGB. Colors outside sRGB are brought in by lowering chroma
|
|
117
|
+
* (keeping lightness and hue), as CSS Color 4 gamut mapping does.
|
|
118
|
+
*/
|
|
119
|
+
export declare function oklchToRgba(o: Oklch): Rgba;
|
|
120
|
+
/** Paints `top` over `bottom` (straight alpha). */
|
|
121
|
+
export declare function composite(top: Rgba, bottom: Rgba): Rgba;
|
|
122
|
+
/** WCAG 2 relative luminance of an opaque color, 0–1. */
|
|
123
|
+
export declare function relativeLuminance(rgba: Rgba): number;
|
|
124
|
+
/**
|
|
125
|
+
* WCAG 2 contrast ratio (1–21) of `foreground` on `background`. A
|
|
126
|
+
* translucent background is taken over white, then a translucent foreground
|
|
127
|
+
* over that. Null when either is not a readable color.
|
|
128
|
+
*/
|
|
129
|
+
export declare function contrastRatio(foreground: string | Rgba, background: string | Rgba): number | null;
|
|
130
|
+
/** The WCAG level a contrast ratio meets. */
|
|
131
|
+
export type ContrastLevel = 'AAA' | 'AA' | 'AA Large' | 'Fail';
|
|
132
|
+
/**
|
|
133
|
+
* The best WCAG 2 level `ratio` meets: AAA ≥ 7, AA ≥ 4.5, AA Large ≥ 3 (large
|
|
134
|
+
* text and UI). With `large`, AAA is ≥ 4.5 and AA ≥ 3.
|
|
135
|
+
*/
|
|
136
|
+
export declare function contrastLevel(ratio: number, large?: boolean): ContrastLevel;
|
|
137
|
+
/** The ratio a level needs: AA 4.5 (3 for large text), AAA 7 (4.5 for large text). */
|
|
138
|
+
export declare function contrastTarget(level?: 'AA' | 'AAA', large?: boolean): number;
|
|
139
|
+
/**
|
|
140
|
+
* The shade of `color` nearest in OKLCH lightness (same hue and chroma,
|
|
141
|
+
* gamut-mapped) that reaches `target` contrast on `background`, written like
|
|
142
|
+
* `color`. Null when `color` already passes or no shade does.
|
|
143
|
+
*/
|
|
144
|
+
export declare function readableShade(color: string, background: string, target?: number): string | null;
|