@open-artifact/ui 0.9.2 → 0.11.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-artifact/ui",
3
- "version": "0.9.2",
3
+ "version": "0.11.0",
4
4
  "description": "Shared editor UI kit: Base UI primitives styled with Tailwind CSS, lucide icons, light and dark themes.",
5
5
  "type": "module",
6
6
  "exports": {
@@ -0,0 +1,63 @@
1
+ /**
2
+ * A guard for the rest of a double or triple click.
3
+ *
4
+ * A press that closes something (a menu row, the press outside a popover)
5
+ * takes away what was under the pointer: the second and third clicks of
6
+ * the same double or triple click then land on whatever is beneath, a board
7
+ * that adds text on a double click, a row of another list. For a short
8
+ * while after such a press, presses at the same spot are swallowed.
9
+ */
10
+ /** How long after the closing press its follow-up clicks are swallowed. */
11
+ export declare const FOLLOW_UP_CLICK_MS = 500;
12
+ /** How far from the closing press a follow-up click may land, px. */
13
+ export declare const FOLLOW_UP_CLICK_SLOP_PX = 8;
14
+ /** Where and when the closing press happened. */
15
+ export interface PressPoint {
16
+ x: number;
17
+ y: number;
18
+ /** Milliseconds, on the clock passed to the guard. */
19
+ at: number;
20
+ }
21
+ /** The pointer fields of an event the guard reads. */
22
+ export interface PointLike {
23
+ clientX: number;
24
+ clientY: number;
25
+ }
26
+ /** True when a press at `point`, `now`, is part of the same multi-click as `origin`. */
27
+ export declare function isFollowUpPress(origin: PressPoint, point: PointLike, now: number): boolean;
28
+ /** The pointer and mouse events the guard swallows. */
29
+ export declare const FOLLOW_UP_EVENTS: readonly ["pointerdown", "mousedown", "pointerup", "mouseup", "click", "dblclick"];
30
+ /** One of {@link FOLLOW_UP_EVENTS}. */
31
+ export type FollowUpEventType = (typeof FOLLOW_UP_EVENTS)[number];
32
+ /** The parts of an event {@link guardFollowUpClicks} reads. */
33
+ export interface FollowUpEvent extends PointLike {
34
+ type: string;
35
+ preventDefault(): void;
36
+ stopImmediatePropagation(): void;
37
+ }
38
+ /** The parts of a window {@link guardFollowUpClicks} listens on. */
39
+ export interface ClickGuardWindow {
40
+ addEventListener(type: FollowUpEventType, listener: (event: FollowUpEvent) => void, capture: boolean): void;
41
+ removeEventListener(type: FollowUpEventType, listener: (event: FollowUpEvent) => void, capture: boolean): void;
42
+ setTimeout(callback: () => void, ms: number): number;
43
+ clearTimeout(id: number): void;
44
+ }
45
+ /**
46
+ * Swallows, at the window, the presses that follow the closing press at
47
+ * `origin` within {@link FOLLOW_UP_CLICK_MS} and {@link FOLLOW_UP_CLICK_SLOP_PX}.
48
+ * A press swallowed near the end keeps the guard until its own release and
49
+ * click have been swallowed too. Returns a function that ends it early.
50
+ */
51
+ export declare function guardFollowUpClicks(win: ClickGuardWindow, origin: PressPoint, now?: () => number): () => void;
52
+ /** The fields of a native click (or press) the closing control passes. */
53
+ export interface ClosingClick extends PointLike {
54
+ /** The click count: 0 for a click made with the keyboard. */
55
+ detail: number;
56
+ view: ClickGuardWindow | null;
57
+ }
58
+ /**
59
+ * Starts {@link guardFollowUpClicks} on the event's window for a pointer
60
+ * click that closed something. Keyboard clicks (`detail` 0) have no
61
+ * follow-up and start nothing.
62
+ */
63
+ export declare function swallowFollowUpClicks(click: ClosingClick): void;
package/src/clicks.js ADDED
@@ -0,0 +1,71 @@
1
+ /**
2
+ * A guard for the rest of a double or triple click.
3
+ *
4
+ * A press that closes something (a menu row, the press outside a popover)
5
+ * takes away what was under the pointer: the second and third clicks of
6
+ * the same double or triple click then land on whatever is beneath, a board
7
+ * that adds text on a double click, a row of another list. For a short
8
+ * while after such a press, presses at the same spot are swallowed.
9
+ */
10
+ /** How long after the closing press its follow-up clicks are swallowed. */
11
+ export const FOLLOW_UP_CLICK_MS = 500;
12
+ /** How far from the closing press a follow-up click may land, px. */
13
+ export const FOLLOW_UP_CLICK_SLOP_PX = 8;
14
+ /** True when a press at `point`, `now`, is part of the same multi-click as `origin`. */
15
+ export function isFollowUpPress(origin, point, now) {
16
+ if (now < origin.at || now - origin.at > FOLLOW_UP_CLICK_MS)
17
+ return false;
18
+ return Math.hypot(point.clientX - origin.x, point.clientY - origin.y) <= FOLLOW_UP_CLICK_SLOP_PX;
19
+ }
20
+ /** The pointer and mouse events the guard swallows. */
21
+ export const FOLLOW_UP_EVENTS = ['pointerdown', 'mousedown', 'pointerup', 'mouseup', 'click', 'dblclick'];
22
+ /**
23
+ * Swallows, at the window, the presses that follow the closing press at
24
+ * `origin` within {@link FOLLOW_UP_CLICK_MS} and {@link FOLLOW_UP_CLICK_SLOP_PX}.
25
+ * A press swallowed near the end keeps the guard until its own release and
26
+ * click have been swallowed too. Returns a function that ends it early.
27
+ */
28
+ export function guardFollowUpClicks(win, origin, now = Date.now) {
29
+ let pressed = false;
30
+ let ended = false;
31
+ let timer = 0;
32
+ const end = () => {
33
+ if (ended)
34
+ return;
35
+ ended = true;
36
+ win.clearTimeout(timer);
37
+ for (const type of FOLLOW_UP_EVENTS)
38
+ win.removeEventListener(type, onEvent, true);
39
+ };
40
+ const settle = () => {
41
+ if (pressed)
42
+ timer = win.setTimeout(settle, FOLLOW_UP_CLICK_MS);
43
+ else
44
+ end();
45
+ };
46
+ const onEvent = (event) => {
47
+ const down = event.type === 'pointerdown' || event.type === 'mousedown';
48
+ if (!(pressed && !down) && !isFollowUpPress(origin, event, now()))
49
+ return;
50
+ event.preventDefault();
51
+ event.stopImmediatePropagation();
52
+ if (down)
53
+ pressed = true;
54
+ else if (event.type === 'click' || event.type === 'dblclick')
55
+ pressed = false;
56
+ };
57
+ for (const type of FOLLOW_UP_EVENTS)
58
+ win.addEventListener(type, onEvent, true);
59
+ timer = win.setTimeout(settle, Math.max(0, FOLLOW_UP_CLICK_MS - (now() - origin.at)));
60
+ return end;
61
+ }
62
+ /**
63
+ * Starts {@link guardFollowUpClicks} on the event's window for a pointer
64
+ * click that closed something. Keyboard clicks (`detail` 0) have no
65
+ * follow-up and start nothing.
66
+ */
67
+ export function swallowFollowUpClicks(click) {
68
+ if (click.detail < 1 || !click.view)
69
+ return;
70
+ guardFollowUpClicks(click.view, { x: click.clientX, y: click.clientY, at: Date.now() });
71
+ }
@@ -8,9 +8,9 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
8
8
  */
9
9
  import { Popover as BasePopover } from '@base-ui/react/popover';
10
10
  import { Pipette, X } from 'lucide-react';
11
- import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore, } from 'react';
11
+ import { useCallback, useEffect, useId, useMemo, useRef, useState, useSyncExternalStore, } from 'react';
12
12
  import { cn } from "./cn.js";
13
- import { contrastLevel, contrastRatio, contrastTarget, editFormat, formatColor, hsvaToRgba, parseColor, readableShade, rgbaToHsva, sameColor, } from "./color.js";
13
+ import { colorRevertMessage, contrastLevel, contrastRatio, contrastTarget, editFormat, formatColor, hsvaToRgba, hueName, parseColor, readableShade, rgbaToHsva, sameColor, withHexHash, } from "./color.js";
14
14
  import { CommitInput, Segmented } from "./fields.js";
15
15
  import { preventRepeatedActivation } from "./keys.js";
16
16
  import { POPUP_CLASS } from "./menu.js";
@@ -161,21 +161,39 @@ export function ColorPickerPanel({ value, onChange, onCommit, fallback, format:
161
161
  setHsva(fixed);
162
162
  commit(text(fixed));
163
163
  };
164
+ /** A color typed into the text field and not committed yet: shown in the picker only. */
165
+ const [typed, setTyped] = useState(null);
166
+ /** Why the last text entered went back (not a color), until the next edit. */
167
+ const [refused, setRefused] = useState(null);
168
+ const refusedId = useId();
169
+ const previewText = (raw) => {
170
+ if (raw !== shownText)
171
+ setRefused(null);
172
+ const next = raw === shownText ? null : parseColor(withHexHash(raw));
173
+ setTyped(next ? rgbaToHsva(alpha ? next.rgba : { ...next.rgba, a: 1 }, hsva.h) : null);
174
+ };
164
175
  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;
176
+ setTyped(null);
177
+ const entered = raw.trim();
178
+ if (!entered)
179
+ return false;
180
+ const hexless = withHexHash(entered);
169
181
  const next = parseColor(hexless);
170
182
  if (next) {
183
+ setRefused(null);
171
184
  setHsva(rgbaToHsva(alpha ? next.rgba : { ...next.rgba, a: 1 }, hsva.h));
172
185
  setFormat(editFormat(next.notation));
173
186
  commit(alpha || next.rgba.a === 1 ? hexless : formatColor({ ...next.rgba, a: 1 }, editFormat(next.notation), next.notation));
174
- return;
187
+ return true;
175
188
  }
176
189
  // 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);
190
+ if (typeof CSS !== 'undefined' && CSS.supports('color', entered)) {
191
+ setRefused(null);
192
+ commit(entered);
193
+ return true;
194
+ }
195
+ setRefused(colorRevertMessage(shownText));
196
+ return false;
179
197
  };
180
198
  const pickSwatch = (swatch) => {
181
199
  const next = parseColor(swatch.value);
@@ -189,7 +207,8 @@ export function ColorPickerPanel({ value, onChange, onCommit, fallback, format:
189
207
  commit(formatColor(hsvaToRgba(alpha ? hsva : { ...hsva, a: 1 }), next, {}, next === 'oklch' && parsed?.notation.format === 'oklch' ? parsed.oklch : undefined));
190
208
  };
191
209
  const dropper = typeof window !== 'undefined' && 'EyeDropper' in window ? window.EyeDropper : null;
192
- const rgb = hsvaToRgba({ ...hsva, a: 1 });
210
+ const seen = typed ?? hsva;
211
+ const rgb = hsvaToRgba({ ...seen, a: 1 });
193
212
  const solid = formatColor(rgb, 'hex');
194
213
  const shownText = value !== null && !parsed ? value : text(hsva);
195
214
  const current = value ?? null;
@@ -201,7 +220,7 @@ export function ColorPickerPanel({ value, onChange, onCommit, fallback, format:
201
220
  }
202
221
  return [...out.entries()];
203
222
  }, [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: () => {
223
+ return (_jsxs("div", { className: cn('flex w-60 flex-col gap-3', className), children: [_jsx(ColorArea, { hsva: seen, onDrag: drag, onSettle: settle }), _jsx(ColorSlider, { label: "Hue", value: seen.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(${seen.h} 100% 50%)`, max: 360, largeStep: 10 / 360, valueText: `${Math.round(hsva.h)}°, ${hueName(hsva.h)}`, 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: seen.a, background: `linear-gradient(to right, transparent, ${solid}), ${CHECKERBOARD}`, thumb: formatColor({ ...rgb, a: seen.a }, 'rgb'), valueText: `${Math.round(hsva.a * 100)}% opaque`, 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(seen), 'rgb')}, ${formatColor(hsvaToRgba(seen), 'rgb')}), ${CHECKERBOARD}` } }), _jsx(CommitInput, { "aria-label": "Color value", "aria-invalid": refused ? true : undefined, "aria-describedby": refused ? refusedId : undefined, value: shownText, onCommit: pickText, onDraftChange: previewText, 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
224
  void new dropper()
206
225
  .open()
207
226
  .then((result) => {
@@ -210,7 +229,7 @@ export function ColorPickerPanel({ value, onChange, onCommit, fallback, format:
210
229
  settle(rgbaToHsva({ ...picked.rgba, a: hsva.a }, hsva.h));
211
230
  })
212
231
  .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) => {
232
+ }, 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] }), refused ? (_jsx("p", { id: refusedId, role: "status", className: "-mt-1.5 text-[11px] text-warning", children: refused })) : null, contrastAgainst ? (_jsx(ContrastBadge, { color: value !== null && !parsed ? value : text(hsva), against: contrastAgainst, level: level, large: largeText, onFix: (fix) => {
214
233
  const next = parseColor(fix);
215
234
  if (next)
216
235
  setHsva(rgbaToHsva(next.rgba, hsva.h));
@@ -226,7 +245,7 @@ function relative(event, element) {
226
245
  y: Math.max(0, Math.min(1, (event.clientY - box.top) / Math.max(1, box.height))),
227
246
  };
228
247
  }
229
- /** Arrow-key step: 1%, Shift 10%. */
248
+ /** Arrow-key step of the area: 1%, Shift 10%. */
230
249
  const keyStep = (event) => (event.shiftKey ? 0.1 : 0.01);
231
250
  const clamp01 = (value) => Math.max(0, Math.min(1, value));
232
251
  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)]';
@@ -272,17 +291,21 @@ function ColorArea({ hsva, onDrag, onSettle }) {
272
291
  onSettle(at(event));
273
292
  }, 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
293
  }
275
- /** A horizontal 0–1 slider painted with `background` (hue, opacity). */
276
- function ColorSlider({ label, value, background, thumb, valueText, onDrag, onSettle, }) {
294
+ /**
295
+ * A horizontal 0–1 slider painted with `background` (hue, opacity). It reads
296
+ * as 0–`max` (100 for percents, 360 for degrees); an arrow moves one of
297
+ * those units, Shift + arrow and Page Up/Down move `largeStep`.
298
+ */
299
+ function ColorSlider({ label, value, max = 100, largeStep = 0.1, background, thumb, valueText, onDrag, onSettle, }) {
277
300
  const onKeyDown = (event) => {
278
- const d = keyStep(event);
301
+ const d = event.shiftKey ? largeStep : 1 / max;
279
302
  const moves = {
280
303
  ArrowLeft: value - d,
281
304
  ArrowDown: value - d,
282
305
  ArrowRight: value + d,
283
306
  ArrowUp: value + d,
284
- PageDown: value - 0.1,
285
- PageUp: value + 0.1,
307
+ PageDown: value - largeStep,
308
+ PageUp: value + largeStep,
286
309
  Home: 0,
287
310
  End: 1,
288
311
  };
@@ -292,7 +315,7 @@ function ColorSlider({ label, value, background, thumb, valueText, onDrag, onSet
292
315
  event.preventDefault();
293
316
  onSettle(clamp01(next));
294
317
  };
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) => {
318
+ return (_jsx("div", { role: "slider", tabIndex: 0, "aria-label": label, "aria-valuemin": 0, "aria-valuemax": max, "aria-valuenow": Math.round(value * max), "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
319
  if (event.button !== 0)
297
320
  return;
298
321
  event.currentTarget.setPointerCapture(event.pointerId);
package/src/color.d.ts CHANGED
@@ -74,6 +74,12 @@ export declare function parseColor(input: string): ParsedColor | null;
74
74
  export declare function toRgba(input: string): Rgba | null;
75
75
  /** True when {@link parseColor} reads `input`. */
76
76
  export declare function isColor(input: string): boolean;
77
+ /** Typed text with the `#` added when it is bare hex digits of a color (`abc`, `abcd`, `aabbcc`, `aabbccdd`). */
78
+ export declare function withHexHash(input: string): string;
79
+ /** What a color field says when typed text is not a color and the field went back to `previous`. */
80
+ export declare function colorRevertMessage(previous: string): string;
81
+ /** A plain name for a hue in degrees (the nearest of twelve, 30° apart), for screen readers. */
82
+ export declare function hueName(degrees: number): string;
77
83
  /** `#rrggbb`, or `#rrggbbaa` when translucent. */
78
84
  export declare function formatHex(rgba: Rgba, options?: {
79
85
  upper?: boolean;
package/src/color.js CHANGED
@@ -249,6 +249,21 @@ export function toRgba(input) {
249
249
  export function isColor(input) {
250
250
  return parseColor(input) !== null;
251
251
  }
252
+ /** Typed text with the `#` added when it is bare hex digits of a color (`abc`, `abcd`, `aabbcc`, `aabbccdd`). */
253
+ export function withHexHash(input) {
254
+ const text = input.trim();
255
+ return /^(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(text) ? `#${text}` : text;
256
+ }
257
+ /** What a color field says when typed text is not a color and the field went back to `previous`. */
258
+ export function colorRevertMessage(previous) {
259
+ const text = previous.trim();
260
+ return text ? `Not a color, so it went back to ${text}.` : 'Not a color, so the field stayed empty.';
261
+ }
262
+ const HUE_NAMES = ['red', 'orange', 'yellow', 'yellow-green', 'green', 'spring green', 'cyan', 'sky blue', 'blue', 'violet', 'magenta', 'pink'];
263
+ /** A plain name for a hue in degrees (the nearest of twelve, 30° apart), for screen readers. */
264
+ export function hueName(degrees) {
265
+ return HUE_NAMES[Math.round(wrapHue(degrees) / 30) % HUE_NAMES.length];
266
+ }
252
267
  /* -------------------------------- formatting ------------------------------ */
253
268
  const hex2 = (n) => Math.round(clamp(n, 0, 255)).toString(16).padStart(2, '0');
254
269
  /** `#rrggbb`, or `#rrggbbaa` when translucent. */
package/src/fields.d.ts CHANGED
@@ -6,15 +6,17 @@ export declare const TextInput: import("react").ForwardRefExoticComponent<InputH
6
6
  /** Props of {@link CommitInput}. */
7
7
  export interface CommitInputProps extends Omit<InputHTMLAttributes<HTMLInputElement>, 'value' | 'onChange'> {
8
8
  value: string;
9
- /** Called on Enter or blur, only when the text changed. */
10
- onCommit: (value: string) => void;
9
+ /** Called on Enter or blur, only when the text changed. Returning `false` refuses the text: the field shows `value` again. */
10
+ onCommit: (value: string) => void | boolean;
11
+ /** Called with the draft as it is typed, and with `value` again when Escape puts it back. */
12
+ onDraftChange?: (draft: string) => void;
11
13
  }
12
14
  /**
13
15
  * A text input that keeps a local draft and commits on Enter or blur; Escape
14
16
  * restores the last committed value. Inspector edits use it so every
15
17
  * keystroke does not become a document write.
16
18
  */
17
- export declare function CommitInput({ value, onCommit, className, ...rest }: CommitInputProps): import("react/jsx-runtime").JSX.Element;
19
+ export declare function CommitInput({ value, onCommit, onDraftChange, className, ...rest }: CommitInputProps): import("react/jsx-runtime").JSX.Element;
18
20
  /** Props of {@link NumberInput}. */
19
21
  export interface NumberInputProps {
20
22
  value: number | null;
package/src/fields.js CHANGED
@@ -10,9 +10,9 @@ import { Switch as BaseSwitch } from '@base-ui/react/switch';
10
10
  import { ToggleGroup } from '@base-ui/react/toggle-group';
11
11
  import { Toggle } from '@base-ui/react/toggle';
12
12
  import { Check, ChevronDown } from 'lucide-react';
13
- import { forwardRef, useEffect, useState } from 'react';
13
+ import { forwardRef, useEffect, useRef, useState } from 'react';
14
14
  import { cn } from "./cn.js";
15
- import { preventRepeatedActivation } from "./keys.js";
15
+ import { isComposingKey, preventRepeatedActivation } from "./keys.js";
16
16
  import { POPUP_CLASS } from "./menu.js";
17
17
  /** Shared look of single-line inputs. */
18
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';
@@ -25,21 +25,39 @@ export const TextInput = forwardRef(function TextInput({ className, ...rest }, r
25
25
  * restores the last committed value. Inspector edits use it so every
26
26
  * keystroke does not become a document write.
27
27
  */
28
- export function CommitInput({ value, onCommit, className, ...rest }) {
28
+ export function CommitInput({ value, onCommit, onDraftChange, className, ...rest }) {
29
29
  const [draft, setDraft] = useState(value);
30
30
  useEffect(() => setDraft(value), [value]);
31
+ /** Set by Enter and Escape, which already decided: the blur they cause commits nothing more. */
32
+ const settled = useRef(false);
31
33
  const commit = () => {
32
- if (draft !== value)
33
- onCommit(draft);
34
+ if (settled.current) {
35
+ settled.current = false;
36
+ return;
37
+ }
38
+ if (draft !== value && onCommit(draft) === false) {
39
+ setDraft(value);
40
+ onDraftChange?.(value);
41
+ }
34
42
  };
35
- return (_jsx("input", { className: cn(INPUT_CLASS, className), value: draft, onChange: (event) => setDraft(event.target.value), onBlur: commit, onKeyDown: (event) => {
43
+ return (_jsx("input", { className: cn(INPUT_CLASS, className), value: draft, onChange: (event) => {
44
+ setDraft(event.target.value);
45
+ onDraftChange?.(event.target.value);
46
+ }, onBlur: commit, onKeyDown: (event) => {
47
+ if (isComposingKey(event.nativeEvent))
48
+ return;
36
49
  if (event.key === 'Enter') {
37
50
  commit();
51
+ settled.current = true;
38
52
  event.target.blur();
53
+ settled.current = false;
39
54
  }
40
55
  else if (event.key === 'Escape') {
56
+ settled.current = true;
41
57
  setDraft(value);
58
+ onDraftChange?.(value);
42
59
  event.target.blur();
60
+ settled.current = false;
43
61
  }
44
62
  }, ...rest }));
45
63
  }
package/src/index.d.ts CHANGED
@@ -12,6 +12,7 @@ export * from './overlays.tsx';
12
12
  export * from './fields.tsx';
13
13
  export * from './layout.tsx';
14
14
  export * from './keys.ts';
15
+ export * from './clicks.ts';
15
16
  export * from './focusables.ts';
16
17
  export * from './scroll.tsx';
17
18
  export * from './history.tsx';
package/src/index.js CHANGED
@@ -12,6 +12,7 @@ export * from "./overlays.js";
12
12
  export * from "./fields.js";
13
13
  export * from "./layout.js";
14
14
  export * from "./keys.js";
15
+ export * from "./clicks.js";
15
16
  export * from "./focusables.js";
16
17
  export * from "./scroll.js";
17
18
  export * from "./history.js";
package/src/keys.d.ts CHANGED
@@ -11,6 +11,18 @@ export interface KeyLike {
11
11
  key: string;
12
12
  repeat: boolean;
13
13
  }
14
+ /** The fields of a keyboard event that tell an input method is composing. */
15
+ export interface ComposingLike {
16
+ isComposing?: boolean;
17
+ keyCode?: number;
18
+ }
19
+ /**
20
+ * True while an input method composes (Chinese, Japanese, Korean…): the
21
+ * Enter or Escape it sees picks or drops the candidate, so a field must not
22
+ * also commit or cancel on it. Safari reports the end of a composition as
23
+ * key code 229 with `isComposing` already false.
24
+ */
25
+ export declare function isComposingKey(event: ComposingLike): boolean;
14
26
  /** True for an auto-repeated Enter or Space. */
15
27
  export declare function isRepeatedActivation(event: KeyLike): boolean;
16
28
  /** A keydown event as the guards see it. */
package/src/keys.js CHANGED
@@ -6,6 +6,15 @@
6
6
  * and a press that moves focus (closing a toast, opening a dialog) lands the
7
7
  * repeats on whatever gets focus next.
8
8
  */
9
+ /**
10
+ * True while an input method composes (Chinese, Japanese, Korean…): the
11
+ * Enter or Escape it sees picks or drops the candidate, so a field must not
12
+ * also commit or cancel on it. Safari reports the end of a composition as
13
+ * key code 229 with `isComposing` already false.
14
+ */
15
+ export function isComposingKey(event) {
16
+ return Boolean(event.isComposing) || event.keyCode === 229;
17
+ }
9
18
  /** True for an auto-repeated Enter or Space. */
10
19
  export function isRepeatedActivation(event) {
11
20
  return event.repeat && (event.key === 'Enter' || event.key === ' ');
package/src/menu.d.ts CHANGED
@@ -26,7 +26,7 @@ export interface MenuItemProps {
26
26
  disabled?: boolean;
27
27
  danger?: boolean;
28
28
  }
29
- /** One action row. */
29
+ /** One action row. The rest of a double click on it does not reach what the closed menu uncovers. */
30
30
  export declare function MenuItem({ children, onSelect, icon, shortcut, disabled, danger }: MenuItemProps): import("react/jsx-runtime").JSX.Element;
31
31
  /** A toggle row with a check mark. */
32
32
  export declare function MenuCheckboxItem({ children, checked, onCheckedChange, closeOnClick, }: {
package/src/menu.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { Menu as BaseMenu } from '@base-ui/react/menu';
3
3
  import { Check, ChevronRight } from 'lucide-react';
4
+ import { swallowFollowUpClicks } from "./clicks.js";
4
5
  import { cn } from "./cn.js";
5
6
  import { preventRepeatedActivation } from "./keys.js";
6
7
  /** Shared popup look of menus, popovers and selects. */
@@ -14,9 +15,12 @@ const ITEM_CLASS = 'flex h-7 min-w-40 cursor-default select-none items-center ga
14
15
  export function Menu({ trigger, children, side = 'bottom', align = 'start', open, onOpenChange }) {
15
16
  return (_jsxs(BaseMenu.Root, { open: open, onOpenChange: onOpenChange ? (next) => onOpenChange(next) : undefined, children: [_jsx(BaseMenu.Trigger, { render: trigger, onKeyDown: preventRepeatedActivation }), _jsx(BaseMenu.Portal, { children: _jsx(BaseMenu.Positioner, { side: side, align: align, sideOffset: 6, className: "z-[1000]", children: _jsx(BaseMenu.Popup, { className: POPUP_CLASS, children: children }) }) })] }));
16
17
  }
17
- /** One action row. */
18
+ /** One action row. The rest of a double click on it does not reach what the closed menu uncovers. */
18
19
  export function MenuItem({ children, onSelect, icon, shortcut, disabled, danger }) {
19
- return (_jsxs(BaseMenu.Item, { className: cn(ITEM_CLASS, danger && 'text-danger'), disabled: disabled, onClick: onSelect, onKeyDown: preventRepeatedActivation, children: [_jsx("span", { className: "flex size-4 items-center justify-center text-fg-muted", children: icon }), _jsx("span", { className: "flex-1", children: children }), shortcut ? _jsx("span", { className: "ml-4 text-xs text-fg-subtle", children: shortcut }) : null] }));
20
+ return (_jsxs(BaseMenu.Item, { className: cn(ITEM_CLASS, danger && 'text-danger'), disabled: disabled, onClick: (event) => {
21
+ swallowFollowUpClicks(event.nativeEvent);
22
+ onSelect?.();
23
+ }, onKeyDown: preventRepeatedActivation, children: [_jsx("span", { className: "flex size-4 items-center justify-center text-fg-muted", children: icon }), _jsx("span", { className: "flex-1", children: children }), shortcut ? _jsx("span", { className: "ml-4 text-xs text-fg-subtle", children: shortcut }) : null] }));
20
24
  }
21
25
  /** A toggle row with a check mark. */
22
26
  export function MenuCheckboxItem({ children, checked, onCheckedChange, closeOnClick = false, }) {
package/src/numbers.d.ts CHANGED
@@ -20,5 +20,9 @@ export declare function stepDecimals(step: number): number;
20
20
  export declare function roundTo(value: number, decimals: number): number;
21
21
  /** Clamps into `[min, max]` (either bound optional). */
22
22
  export declare function clampNumber(value: number, min?: number, max?: number): number;
23
+ /** The nearest multiple of `step` (no snapping for a step that is not a positive number). */
24
+ export declare function snapToStep(value: number, step: number): number;
25
+ /** Where stepping starts in an empty (or mixed) field: 0, kept inside `[min, max]`. */
26
+ export declare function stepStart(min?: number, max?: number): number;
23
27
  /** Formats a value for a number field: rounded, no trailing zeros. */
24
28
  export declare function formatNumber(value: number, decimals: number): string;
package/src/numbers.js CHANGED
@@ -108,6 +108,16 @@ export function clampNumber(value, min, max) {
108
108
  out = max;
109
109
  return out;
110
110
  }
111
+ /** The nearest multiple of `step` (no snapping for a step that is not a positive number). */
112
+ export function snapToStep(value, step) {
113
+ if (!Number.isFinite(step) || step <= 0)
114
+ return value;
115
+ return Math.round(value / step) * step;
116
+ }
117
+ /** Where stepping starts in an empty (or mixed) field: 0, kept inside `[min, max]`. */
118
+ export function stepStart(min, max) {
119
+ return clampNumber(0, min, max);
120
+ }
111
121
  /** Formats a value for a number field: rounded, no trailing zeros. */
112
122
  export function formatNumber(value, decimals) {
113
123
  return String(roundTo(value, decimals));
@@ -46,9 +46,13 @@ export interface ScrubNumberFieldProps {
46
46
  * A number field with a drag-to-scrub label.
47
47
  *
48
48
  * - Drag the label sideways to scrub (Shift: large steps, Alt: small
49
- * steps); Escape during a drag puts the value back.
49
+ * steps); values land on multiples of `step` unless Alt is held. Escape
50
+ * during a drag puts the value back; the end of a drag leaves the field
51
+ * focused with its text selected. Pressing the label commits any other
52
+ * field being typed in first.
50
53
  * - Arrow Up/Down step (Shift ×10, Alt ÷10), Page Up/Down take large
51
- * steps, Home/End go to `min`/`max`.
54
+ * steps, Home/End go to `min`/`max`. An empty or mixed field steps
55
+ * from 0 (kept within `min`/`max`).
52
56
  * - Typing accepts arithmetic (`12*2`, `100/3`) and a unit; Enter or blur
53
57
  * commits, Escape reverts.
54
58
  * - `mixed` shows "Mixed" until something is entered.
@@ -5,14 +5,18 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
5
5
  */
6
6
  import { useEffect, useId, useRef, useState } from 'react';
7
7
  import { cn } from "./cn.js";
8
- import { clampNumber, evaluateNumberInput, formatNumber, roundTo, stepDecimals } from "./numbers.js";
8
+ import { clampNumber, evaluateNumberInput, formatNumber, roundTo, snapToStep, stepDecimals, stepStart } from "./numbers.js";
9
9
  /**
10
10
  * A number field with a drag-to-scrub label.
11
11
  *
12
12
  * - Drag the label sideways to scrub (Shift: large steps, Alt: small
13
- * steps); Escape during a drag puts the value back.
13
+ * steps); values land on multiples of `step` unless Alt is held. Escape
14
+ * during a drag puts the value back; the end of a drag leaves the field
15
+ * focused with its text selected. Pressing the label commits any other
16
+ * field being typed in first.
14
17
  * - Arrow Up/Down step (Shift ×10, Alt ÷10), Page Up/Down take large
15
- * steps, Home/End go to `min`/`max`.
18
+ * steps, Home/End go to `min`/`max`. An empty or mixed field steps
19
+ * from 0 (kept within `min`/`max`).
16
20
  * - Typing accepts arithmetic (`12*2`, `100/3`) and a unit; Enter or blur
17
21
  * commits, Escape reverts.
18
22
  * - `mixed` shows "Mixed" until something is entered.
@@ -56,16 +60,19 @@ export function ScrubNumberField({ value, mixed = false, onChange, onCommit, lab
56
60
  if (next !== value || mixed || otherUnit)
57
61
  onCommit(next, otherUnit);
58
62
  };
59
- /** Steps from the current value (or 0 / min when empty or mixed). */
60
- const stepBy = (delta) => {
61
- const typed = editing.current ? evaluateNumberInput(draft) : null;
62
- const base = typed?.value ?? (mixed || value === null ? (min ?? 0) : value);
63
- const next = fit(base + delta);
63
+ /** Puts `target` (fitted) in the field and commits it. */
64
+ const settleAt = (target) => {
65
+ const next = fit(target);
64
66
  editing.current = false;
65
67
  setDraft(formatNumber(next, decimals));
66
68
  onChange?.(next);
67
69
  onCommit(next);
68
70
  };
71
+ /** Steps from the text being typed, else the value, else {@link stepStart}. */
72
+ const stepBy = (delta) => {
73
+ const typed = editing.current ? evaluateNumberInput(draft) : null;
74
+ settleAt((typed?.value ?? (mixed || value === null ? stepStart(min, max) : value)) + delta);
75
+ };
69
76
  const onKeyDown = (event) => {
70
77
  const unitStep = event.shiftKey ? big : event.altKey ? small : step;
71
78
  switch (event.key) {
@@ -88,13 +95,13 @@ export function ScrubNumberField({ value, mixed = false, onChange, onCommit, lab
88
95
  case 'Home':
89
96
  if (min !== undefined && !event.shiftKey) {
90
97
  event.preventDefault();
91
- stepBy(min - (value ?? 0));
98
+ settleAt(min);
92
99
  }
93
100
  break;
94
101
  case 'End':
95
102
  if (max !== undefined && !event.shiftKey) {
96
103
  event.preventDefault();
97
- stepBy(max - (value ?? 0));
104
+ settleAt(max);
98
105
  }
99
106
  break;
100
107
  case 'Enter':
@@ -127,12 +134,11 @@ export function ScrubNumberField({ value, mixed = false, onChange, onCommit, lab
127
134
  onChange?.(state.start);
128
135
  return;
129
136
  }
130
- if (state.travel < pixelsPerStep) {
131
- // A click on the label focuses the field.
132
- inputRef.current?.focus();
133
- inputRef.current?.select();
137
+ // A click on the label, or the end of a drag, leaves the field focused and selected.
138
+ inputRef.current?.focus();
139
+ inputRef.current?.select();
140
+ if (state.travel < pixelsPerStep)
134
141
  return;
135
- }
136
142
  if (state.current !== state.start || mixed)
137
143
  onCommit(state.current);
138
144
  };
@@ -140,8 +146,12 @@ export function ScrubNumberField({ value, mixed = false, onChange, onCommit, lab
140
146
  if (disabled || event.button !== 0)
141
147
  return;
142
148
  event.preventDefault();
149
+ // A field typed into elsewhere commits before the scrub writes its own value.
150
+ const typing = document.activeElement;
151
+ if (typing instanceof HTMLElement && typing !== inputRef.current && (typing.matches('input, textarea') || typing.isContentEditable))
152
+ typing.blur();
143
153
  event.currentTarget.setPointerCapture(event.pointerId);
144
- const start = mixed || value === null ? (min ?? 0) : value;
154
+ const start = mixed || value === null ? stepStart(min, max) : value;
145
155
  scrub.current = { start, current: start, travel: 0, carry: 0, pointerId: event.pointerId };
146
156
  };
147
157
  const onPointerMove = (event) => {
@@ -160,7 +170,8 @@ export function ScrubNumberField({ value, mixed = false, onChange, onCommit, lab
160
170
  return;
161
171
  state.carry -= steps * pixelsPerStep;
162
172
  const unitStep = event.shiftKey ? big : event.altKey ? small : step;
163
- const next = fit(state.current + steps * unitStep);
173
+ const moved = state.current + steps * unitStep;
174
+ const next = fit(event.altKey ? moved : snapToStep(moved, step));
164
175
  if (next === state.current)
165
176
  return;
166
177
  state.current = next;