@open-artifact/ui 0.10.0 → 0.12.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.10.0",
3
+ "version": "0.12.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";
@@ -163,27 +163,37 @@ export function ColorPickerPanel({ value, onChange, onCommit, fallback, format:
163
163
  };
164
164
  /** A color typed into the text field and not committed yet: shown in the picker only. */
165
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();
166
169
  const previewText = (raw) => {
167
- const trimmed = raw.trim();
168
- const next = raw === shownText ? null : parseColor(/^[0-9a-f]{3,8}$/i.test(trimmed) ? `#${trimmed}` : trimmed);
170
+ if (raw !== shownText)
171
+ setRefused(null);
172
+ const next = raw === shownText ? null : parseColor(withHexHash(raw));
169
173
  setTyped(next ? rgbaToHsva(alpha ? next.rgba : { ...next.rgba, a: 1 }, hsva.h) : null);
170
174
  };
171
175
  const pickText = (raw) => {
172
176
  setTyped(null);
173
177
  const entered = raw.trim();
174
178
  if (!entered)
175
- return;
176
- const hexless = /^[0-9a-f]{3,8}$/i.test(entered) ? `#${entered}` : entered;
179
+ return false;
180
+ const hexless = withHexHash(entered);
177
181
  const next = parseColor(hexless);
178
182
  if (next) {
183
+ setRefused(null);
179
184
  setHsva(rgbaToHsva(alpha ? next.rgba : { ...next.rgba, a: 1 }, hsva.h));
180
185
  setFormat(editFormat(next.notation));
181
186
  commit(alpha || next.rgba.a === 1 ? hexless : formatColor({ ...next.rgba, a: 1 }, editFormat(next.notation), next.notation));
182
- return;
187
+ return true;
183
188
  }
184
189
  // Other CSS colors (`var(--x)`, `color-mix()`) pass through when the browser reads them.
185
- if (typeof CSS !== 'undefined' && CSS.supports('color', entered))
190
+ if (typeof CSS !== 'undefined' && CSS.supports('color', entered)) {
191
+ setRefused(null);
186
192
  commit(entered);
193
+ return true;
194
+ }
195
+ setRefused(colorRevertMessage(shownText));
196
+ return false;
187
197
  };
188
198
  const pickSwatch = (swatch) => {
189
199
  const next = parseColor(swatch.value);
@@ -210,7 +220,7 @@ export function ColorPickerPanel({ value, onChange, onCommit, fallback, format:
210
220
  }
211
221
  return [...out.entries()];
212
222
  }, [swatches]);
213
- 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%)`, 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: seen.a, background: `linear-gradient(to right, transparent, ${solid}), ${CHECKERBOARD}`, thumb: formatColor({ ...rgb, a: seen.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(seen), 'rgb')}, ${formatColor(hsvaToRgba(seen), 'rgb')}), ${CHECKERBOARD}` } }), _jsx(CommitInput, { "aria-label": "Color value", 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: () => {
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: () => {
214
224
  void new dropper()
215
225
  .open()
216
226
  .then((result) => {
@@ -219,7 +229,7 @@ export function ColorPickerPanel({ value, onChange, onCommit, fallback, format:
219
229
  settle(rgbaToHsva({ ...picked.rgba, a: hsva.a }, hsva.h));
220
230
  })
221
231
  .catch(() => undefined);
222
- }, 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) => {
223
233
  const next = parseColor(fix);
224
234
  if (next)
225
235
  setHsva(rgbaToHsva(next.rgba, hsva.h));
@@ -235,7 +245,7 @@ function relative(event, element) {
235
245
  y: Math.max(0, Math.min(1, (event.clientY - box.top) / Math.max(1, box.height))),
236
246
  };
237
247
  }
238
- /** Arrow-key step: 1%, Shift 10%. */
248
+ /** Arrow-key step of the area: 1%, Shift 10%. */
239
249
  const keyStep = (event) => (event.shiftKey ? 0.1 : 0.01);
240
250
  const clamp01 = (value) => Math.max(0, Math.min(1, value));
241
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)]';
@@ -281,17 +291,21 @@ function ColorArea({ hsva, onDrag, onSettle }) {
281
291
  onSettle(at(event));
282
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') } }) }));
283
293
  }
284
- /** A horizontal 0–1 slider painted with `background` (hue, opacity). */
285
- 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, }) {
286
300
  const onKeyDown = (event) => {
287
- const d = keyStep(event);
301
+ const d = event.shiftKey ? largeStep : 1 / max;
288
302
  const moves = {
289
303
  ArrowLeft: value - d,
290
304
  ArrowDown: value - d,
291
305
  ArrowRight: value + d,
292
306
  ArrowUp: value + d,
293
- PageDown: value - 0.1,
294
- PageUp: value + 0.1,
307
+ PageDown: value - largeStep,
308
+ PageUp: value + largeStep,
295
309
  Home: 0,
296
310
  End: 1,
297
311
  };
@@ -301,7 +315,7 @@ function ColorSlider({ label, value, background, thumb, valueText, onDrag, onSet
301
315
  event.preventDefault();
302
316
  onSettle(clamp01(next));
303
317
  };
304
- 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) => {
305
319
  if (event.button !== 0)
306
320
  return;
307
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. */
@@ -0,0 +1,29 @@
1
+ /**
2
+ * {@link CrashBoundary}: keeps a render error in an editor from blanking the
3
+ * page. The subtree below it is replaced by the editor's `fallback` (what
4
+ * happened, how to recover); the error still reaches the console, and any
5
+ * `window.onerror` listener, through `reportError`.
6
+ */
7
+ import { Component, type ReactNode } from 'react';
8
+ /** Props of {@link CrashBoundary}. */
9
+ export interface CrashBoundaryProps {
10
+ children: ReactNode;
11
+ /** Shown in place of `children` after they failed to render. */
12
+ fallback: ReactNode;
13
+ }
14
+ export declare class CrashBoundary extends Component<CrashBoundaryProps, {
15
+ crashed: boolean;
16
+ }> {
17
+ state: {
18
+ crashed: boolean;
19
+ };
20
+ static getDerivedStateFromError(): {
21
+ crashed: boolean;
22
+ };
23
+ /** New children after a crash (a remote change, a page switch) get another try. */
24
+ componentDidUpdate(previous: CrashBoundaryProps, previousState: {
25
+ crashed: boolean;
26
+ }): void;
27
+ componentDidCatch(error: unknown): void;
28
+ render(): ReactNode;
29
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * {@link CrashBoundary}: keeps a render error in an editor from blanking the
3
+ * page. The subtree below it is replaced by the editor's `fallback` (what
4
+ * happened, how to recover); the error still reaches the console, and any
5
+ * `window.onerror` listener, through `reportError`.
6
+ */
7
+ import { Component } from 'react';
8
+ export class CrashBoundary extends Component {
9
+ state = { crashed: false };
10
+ static getDerivedStateFromError() {
11
+ return { crashed: true };
12
+ }
13
+ /** New children after a crash (a remote change, a page switch) get another try. */
14
+ componentDidUpdate(previous, previousState) {
15
+ if (previousState.crashed && this.state.crashed && previous.children !== this.props.children)
16
+ this.setState({ crashed: false });
17
+ }
18
+ componentDidCatch(error) {
19
+ try {
20
+ if (typeof reportError === 'function')
21
+ reportError(error);
22
+ else
23
+ console.error(error);
24
+ }
25
+ catch {
26
+ // Reporting must never throw out of the boundary.
27
+ }
28
+ }
29
+ render() {
30
+ return this.state.crashed ? this.props.fallback : this.props.children;
31
+ }
32
+ }
package/src/fields.d.ts CHANGED
@@ -1,13 +1,16 @@
1
1
  import { type InputHTMLAttributes, type ReactNode } from 'react';
2
- /** Shared look of single-line inputs. */
2
+ /**
3
+ * Shared look of single-line inputs. Every field's box also carries `data-ui-field`, so a page can give the fields
4
+ * of one part of it another look (a compact inspector, say).
5
+ */
3
6
  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
7
  /** A plain text input. */
5
8
  export declare const TextInput: import("react").ForwardRefExoticComponent<InputHTMLAttributes<HTMLInputElement> & import("react").RefAttributes<HTMLInputElement>>;
6
9
  /** Props of {@link CommitInput}. */
7
10
  export interface CommitInputProps extends Omit<InputHTMLAttributes<HTMLInputElement>, 'value' | 'onChange'> {
8
11
  value: string;
9
- /** Called on Enter or blur, only when the text changed. */
10
- onCommit: (value: string) => void;
12
+ /** Called on Enter or blur, only when the text changed. Returning `false` refuses the text: the field shows `value` again. */
13
+ onCommit: (value: string) => void | boolean;
11
14
  /** Called with the draft as it is typed, and with `value` again when Escape puts it back. */
12
15
  onDraftChange?: (draft: string) => void;
13
16
  }
@@ -59,11 +62,16 @@ export interface SegmentedProps<T extends string> {
59
62
  value: T | null;
60
63
  options: Option<T>[];
61
64
  onChange: (value: T) => void;
65
+ /**
66
+ * Called with the picked option when it is pressed again (to let the pick go, say). Without it, that press does
67
+ * nothing and the pick stays.
68
+ */
69
+ onRepick?: (value: T) => void;
62
70
  className?: string;
63
71
  'aria-label'?: string;
64
72
  }
65
73
  /** A segmented control (one of a few options, all visible). */
66
- export declare function Segmented<T extends string>({ value, options, onChange, className, ...aria }: SegmentedProps<T>): import("react/jsx-runtime").JSX.Element;
74
+ export declare function Segmented<T extends string>({ value, options, onChange, onRepick, className, ...aria }: SegmentedProps<T>): import("react/jsx-runtime").JSX.Element;
67
75
  /** Props of {@link SwitchInput}. */
68
76
  export interface SwitchInputProps {
69
77
  checked: boolean;
package/src/fields.js CHANGED
@@ -14,11 +14,14 @@ import { forwardRef, useEffect, useRef, useState } from 'react';
14
14
  import { cn } from "./cn.js";
15
15
  import { isComposingKey, preventRepeatedActivation } from "./keys.js";
16
16
  import { POPUP_CLASS } from "./menu.js";
17
- /** Shared look of single-line inputs. */
17
+ /**
18
+ * Shared look of single-line inputs. Every field's box also carries `data-ui-field`, so a page can give the fields
19
+ * of one part of it another look (a compact inspector, say).
20
+ */
18
21
  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
22
  /** A plain text input. */
20
23
  export const TextInput = forwardRef(function TextInput({ className, ...rest }, ref) {
21
- return _jsx("input", { ref: ref, className: cn(INPUT_CLASS, className), ...rest });
24
+ return _jsx("input", { ref: ref, "data-ui-field": "", className: cn(INPUT_CLASS, className), ...rest });
22
25
  });
23
26
  /**
24
27
  * A text input that keeps a local draft and commits on Enter or blur; Escape
@@ -35,10 +38,12 @@ export function CommitInput({ value, onCommit, onDraftChange, className, ...rest
35
38
  settled.current = false;
36
39
  return;
37
40
  }
38
- if (draft !== value)
39
- onCommit(draft);
41
+ if (draft !== value && onCommit(draft) === false) {
42
+ setDraft(value);
43
+ onDraftChange?.(value);
44
+ }
40
45
  };
41
- return (_jsx("input", { className: cn(INPUT_CLASS, className), value: draft, onChange: (event) => {
46
+ return (_jsx("input", { "data-ui-field": "", className: cn(INPUT_CLASS, className), value: draft, onChange: (event) => {
42
47
  setDraft(event.target.value);
43
48
  onDraftChange?.(event.target.value);
44
49
  }, onBlur: commit, onKeyDown: (event) => {
@@ -61,19 +66,25 @@ export function CommitInput({ value, onCommit, onDraftChange, className, ...rest
61
66
  }
62
67
  /** A number field whose label can be dragged horizontally to scrub the value. */
63
68
  export function NumberInput({ value, onChange, onCommit, label, unit, min, max, step = 1, placeholder, className, ...aria }) {
64
- 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] }));
69
+ return (_jsxs(BaseNumberField.Root, { value: value, min: min, max: max, step: step, onValueChange: (next) => onChange?.(next), onValueCommitted: (next) => onCommit(next), "data-ui-field": "", 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'], onKeyDown: (event) => {
70
+ if (event.key === 'Enter')
71
+ event.currentTarget.blur();
72
+ }, 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] }));
65
73
  }
66
74
  /** A dropdown select. */
67
75
  export function SelectInput({ value, options, onChange, placeholder = '—', className, ...aria }) {
68
- 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))) }) }) }) })] }));
76
+ return (_jsxs(BaseSelect.Root, { value: value, onValueChange: (next) => next !== null && onChange(next), children: [_jsxs(BaseSelect.Trigger, { "aria-label": aria['aria-label'], "data-ui-field": "", 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))) }) }) }) })] }));
69
77
  }
70
78
  /** A segmented control (one of a few options, all visible). */
71
- export function Segmented({ value, options, onChange, className, ...aria }) {
79
+ export function Segmented({ value, options, onChange, onRepick, className, ...aria }) {
72
80
  return (_jsx(ToggleGroup, { value: value === null ? [] : [value], onValueChange: (next) => {
73
81
  const picked = next[0];
82
+ // Pressing the pressed option again leaves the group empty.
74
83
  if (picked !== undefined)
75
84
  onChange(picked);
76
- }, "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))) }));
85
+ else if (value !== null)
86
+ onRepick?.(value);
87
+ }, "aria-label": aria['aria-label'], "data-ui-field": "", 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 whitespace-nowrap 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))) }));
77
88
  }
78
89
  /** An on/off switch. A held Enter flips it once. */
79
90
  export function SwitchInput({ checked, onChange, disabled, ...aria }) {
package/src/index.d.ts CHANGED
@@ -12,9 +12,13 @@ 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';
19
+ export * from './crash-boundary.tsx';
20
+ export * from './link-card.ts';
21
+ export * from './link-card-view.tsx';
18
22
  export * from './color.ts';
19
23
  export * from './color-picker.tsx';
20
24
  export * from './effects.ts';
package/src/index.js CHANGED
@@ -12,9 +12,13 @@ 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";
19
+ export * from "./crash-boundary.js";
20
+ export * from "./link-card.js";
21
+ export * from "./link-card-view.js";
18
22
  export * from "./color.js";
19
23
  export * from "./color-picker.js";
20
24
  export * from "./effects.js";
package/src/layout.d.ts CHANGED
@@ -4,6 +4,8 @@ export interface TabItem<T extends string> {
4
4
  value: T;
5
5
  label: ReactNode;
6
6
  content: ReactNode;
7
+ /** Kept rendered, hidden, while another tab is on show (its content is unmounted otherwise). */
8
+ keepMounted?: boolean;
7
9
  }
8
10
  /** Props of {@link Tabs}. */
9
11
  export interface TabsProps<T extends string> {
@@ -13,9 +15,11 @@ export interface TabsProps<T extends string> {
13
15
  className?: string;
14
16
  /** Extra controls shown at the end of the tab bar. */
15
17
  trailing?: ReactNode;
18
+ /** The tab list's accessible name. */
19
+ label?: string;
16
20
  }
17
21
  /** A tab strip with panels. */
18
- export declare function Tabs<T extends string>({ value, onChange, items, className, trailing }: TabsProps<T>): import("react/jsx-runtime").JSX.Element;
22
+ export declare function Tabs<T extends string>({ value, onChange, items, className, trailing, label }: TabsProps<T>): import("react/jsx-runtime").JSX.Element;
19
23
  /** Props of {@link Section}. */
20
24
  export interface SectionProps {
21
25
  title: ReactNode;
@@ -25,9 +29,9 @@ export interface SectionProps {
25
29
  /** Collapsed state is uncontrolled; start open unless `defaultOpen` is false. */
26
30
  defaultOpen?: boolean;
27
31
  }
28
- /** A collapsible group of inspector rows. */
32
+ /** A collapsible group of inspector rows. Carries `data-ui-section` (its heading `data-ui-section-head`) for page styles. */
29
33
  export declare function Section({ title, children, actions, defaultOpen }: SectionProps): import("react/jsx-runtime").JSX.Element;
30
- /** A label + control row inside a {@link Section}. */
34
+ /** A label + control row inside a {@link Section}. Carries `data-ui-row` (its label `data-ui-row-label`) for page styles. */
31
35
  export declare function Row({ label, children, className }: {
32
36
  label?: ReactNode;
33
37
  children: ReactNode;
package/src/layout.js CHANGED
@@ -10,16 +10,16 @@ import { ChevronDown, X } from 'lucide-react';
10
10
  import { cn } from "./cn.js";
11
11
  import { guardHeldActivation } from "./keys.js";
12
12
  /** A tab strip with panels. */
13
- export function Tabs({ value, onChange, items, className, trailing }) {
14
- return (_jsxs(BaseTabs.Root, { value: value, onValueChange: (next) => onChange(next), className: cn('flex min-h-0 flex-col', className), children: [_jsxs("div", { className: "flex h-9 shrink-0 items-center gap-1 border-b border-line px-2", children: [_jsx(BaseTabs.List, { className: "relative flex items-center gap-1", children: items.map((item) => (_jsx(BaseTabs.Tab, { value: item.value, className: "h-7 rounded-md px-2 text-[13px] font-medium text-fg-muted outline-none hover:text-fg data-[active]:bg-hover data-[active]:text-fg focus-visible:outline-2 focus-visible:outline-accent", children: item.label }, item.value))) }), _jsx("div", { className: "ml-auto flex items-center gap-1", children: trailing })] }), items.map((item) => (_jsx(BaseTabs.Panel, { value: item.value, className: "min-h-0 flex-1 overflow-auto outline-none", children: item.content }, item.value)))] }));
13
+ export function Tabs({ value, onChange, items, className, trailing, label }) {
14
+ return (_jsxs(BaseTabs.Root, { value: value, onValueChange: (next) => onChange(next), className: cn('flex min-h-0 flex-col', className), children: [_jsxs("div", { className: "flex h-9 shrink-0 items-center gap-1 border-b border-line px-2", "data-ui-tabs-bar": "", children: [_jsx(BaseTabs.List, { "aria-label": label, className: "relative flex items-center gap-1", children: items.map((item) => (_jsx(BaseTabs.Tab, { value: item.value, className: "h-7 rounded-md px-2 text-[13px] font-medium text-fg-muted outline-none hover:text-fg data-[active]:bg-hover data-[active]:text-fg focus-visible:outline-2 focus-visible:outline-accent", children: item.label }, item.value))) }), _jsx("div", { className: "ml-auto flex items-center gap-1", children: trailing })] }), items.map((item) => (_jsx(BaseTabs.Panel, { value: item.value, keepMounted: item.keepMounted, className: "min-h-0 flex-1 overflow-auto outline-none", children: item.content }, item.value)))] }));
15
15
  }
16
- /** A collapsible group of inspector rows. */
16
+ /** A collapsible group of inspector rows. Carries `data-ui-section` (its heading `data-ui-section-head`) for page styles. */
17
17
  export function Section({ title, children, actions, defaultOpen = true }) {
18
- return (_jsxs(Collapsible.Root, { defaultOpen: defaultOpen, className: "border-b border-line px-3 py-2", children: [_jsxs("div", { className: "flex h-7 items-center gap-1", children: [_jsxs(Collapsible.Trigger, { className: "group flex flex-1 items-center gap-1 text-left text-xs font-semibold text-fg outline-none", children: [_jsx(ChevronDown, { className: "size-3 text-fg-subtle transition-transform group-data-[panel-open]:rotate-0 -rotate-90" }), title] }), actions] }), _jsx(Collapsible.Panel, { className: "flex flex-col gap-1.5 pb-1 pt-1", children: children })] }));
18
+ return (_jsxs(Collapsible.Root, { defaultOpen: defaultOpen, className: "border-b border-line px-3 py-2", "data-ui-section": "", children: [_jsxs("div", { className: "flex h-7 items-center gap-1", "data-ui-section-head": "", children: [_jsxs(Collapsible.Trigger, { className: "group flex flex-1 items-center gap-1 text-left text-xs font-semibold text-fg outline-none", children: [_jsx(ChevronDown, { className: "size-3 text-fg-subtle transition-transform group-data-[panel-open]:rotate-0 -rotate-90" }), title] }), actions] }), _jsx(Collapsible.Panel, { className: "flex flex-col gap-1.5 pb-1 pt-1", children: children })] }));
19
19
  }
20
- /** A label + control row inside a {@link Section}. */
20
+ /** A label + control row inside a {@link Section}. Carries `data-ui-row` (its label `data-ui-row-label`) for page styles. */
21
21
  export function Row({ label, children, className }) {
22
- return (_jsxs("div", { className: cn('flex min-w-0 items-center gap-2', className), children: [label !== undefined ? _jsx("div", { className: "w-16 shrink-0 truncate text-xs text-fg-muted", children: label }) : null, _jsx("div", { className: "flex min-w-0 flex-1 items-center gap-1.5", children: children })] }));
22
+ return (_jsxs("div", { className: cn('flex min-w-0 items-center gap-2', className), "data-ui-row": "", children: [label !== undefined ? (_jsx("div", { className: "w-16 shrink-0 truncate text-xs text-fg-muted", "data-ui-row-label": "", children: label })) : null, _jsx("div", { className: "flex min-w-0 flex-1 items-center gap-1.5", children: children })] }));
23
23
  }
24
24
  /** A floating bar (toolbars, zoom controls). */
25
25
  export function Bar({ className, ...rest }) {
@@ -0,0 +1,30 @@
1
+ /**
2
+ * {@link LinkCard}: the card under a link in rich text being edited. It shows
3
+ * the address, and Open, Copy link, Edit and Remove. Editing the address
4
+ * saves on Enter and puts it back on Escape; Escape on the card gives the
5
+ * focus back to the text.
6
+ *
7
+ * The editor brings what differs: what a typed address becomes
8
+ * (`normalize`), how it is copied and how the link changes.
9
+ */
10
+ /** Props of {@link LinkCard}. */
11
+ export interface LinkCardProps {
12
+ /** The link in the text; the card sits under it. */
13
+ link: HTMLElement;
14
+ /** The address as the document writes it: shown, copied and edited. */
15
+ target: string;
16
+ /** The address resolved, which Open goes to. */
17
+ href: string;
18
+ /** What a typed address becomes, or null when it cannot be one. */
19
+ normalize(typed: string): string | null;
20
+ /** Shown under an address `normalize` refused. */
21
+ invalidMessage?: string;
22
+ onCopy(target: string): void;
23
+ /** Writes a new address into the link; returns false when it could not. */
24
+ onEdit(target: string): boolean;
25
+ onRemove(): void;
26
+ /** Gives focus back to the text, with the caret in the link. */
27
+ onReturn(): void;
28
+ className?: string;
29
+ }
30
+ export declare function LinkCard({ link, target, href, normalize, invalidMessage, onCopy, onEdit, onRemove, onReturn, className }: LinkCardProps): import("react/jsx-runtime").JSX.Element;
@@ -0,0 +1,76 @@
1
+ import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
2
+ /**
3
+ * {@link LinkCard}: the card under a link in rich text being edited. It shows
4
+ * the address, and Open, Copy link, Edit and Remove. Editing the address
5
+ * saves on Enter and puts it back on Escape; Escape on the card gives the
6
+ * focus back to the text.
7
+ *
8
+ * The editor brings what differs: what a typed address becomes
9
+ * (`normalize`), how it is copied and how the link changes.
10
+ */
11
+ import { Copy, ExternalLink, Pencil, Unlink } from 'lucide-react';
12
+ import { useLayoutEffect, useRef, useState } from 'react';
13
+ import { IconButton } from "./button.js";
14
+ import { cn } from "./cn.js";
15
+ import { INPUT_CLASS } from "./fields.js";
16
+ import { isComposingKey } from "./keys.js";
17
+ import { canOpenLink, placeLinkCard, shownLink } from "./link-card.js";
18
+ const keepTextFocus = (event) => event.preventDefault();
19
+ export function LinkCard({ link, target, href, normalize, invalidMessage = 'Not a link address', onCopy, onEdit, onRemove, onReturn, className }) {
20
+ const card = useRef(null);
21
+ const [editing, setEditing] = useState(false);
22
+ const [draft, setDraft] = useState('');
23
+ const [invalid, setInvalid] = useState(false);
24
+ const [place, setPlace] = useState(null);
25
+ const shown = shownLink(target);
26
+ const openable = canOpenLink(href);
27
+ useLayoutEffect(() => {
28
+ const measure = () => {
29
+ if (!card.current || !link.isConnected)
30
+ return;
31
+ const box = card.current.getBoundingClientRect();
32
+ setPlace(placeLinkCard(link.getBoundingClientRect(), box, { width: window.innerWidth, height: window.innerHeight }));
33
+ };
34
+ measure();
35
+ window.addEventListener('scroll', measure, true);
36
+ window.addEventListener('resize', measure);
37
+ return () => {
38
+ window.removeEventListener('scroll', measure, true);
39
+ window.removeEventListener('resize', measure);
40
+ };
41
+ }, [link, editing]);
42
+ const startEdit = () => {
43
+ setDraft(target);
44
+ setInvalid(false);
45
+ setEditing(true);
46
+ };
47
+ const save = () => {
48
+ const next = normalize(draft);
49
+ if (next === null) {
50
+ setInvalid(true);
51
+ return;
52
+ }
53
+ if (next !== target && !onEdit(next))
54
+ return;
55
+ setEditing(false);
56
+ if (next === target)
57
+ onReturn();
58
+ };
59
+ return (_jsx("div", { ref: card, role: "dialog", "aria-label": "Link", "data-link-card": "", className: cn('fixed z-50 flex max-w-[min(420px,calc(100vw-12px))] items-center gap-1 rounded-control border border-line bg-surface p-1 text-[12px] shadow-lg', className), style: place ? { top: place.top, left: place.left } : { top: -9999, left: -9999 }, onKeyDown: (event) => {
60
+ if (event.key === 'Escape' && !isComposingKey(event.nativeEvent)) {
61
+ event.preventDefault();
62
+ event.stopPropagation();
63
+ if (editing)
64
+ setEditing(false);
65
+ onReturn();
66
+ }
67
+ }, children: editing ? (_jsxs(_Fragment, { children: [_jsx("input", { autoFocus: true, "aria-label": "Link address", "aria-invalid": invalid || undefined, value: draft, spellCheck: false, className: cn(INPUT_CLASS, 'h-7 w-72 font-mono text-[12px]', invalid && 'border-danger'), onChange: (event) => {
68
+ setDraft(event.target.value);
69
+ setInvalid(false);
70
+ }, onKeyDown: (event) => {
71
+ if (event.key !== 'Enter' || isComposingKey(event.nativeEvent))
72
+ return;
73
+ event.preventDefault();
74
+ save();
75
+ } }), invalid ? _jsx("span", { role: "alert", className: "px-1 text-danger", children: invalidMessage }) : null] })) : (_jsxs(_Fragment, { children: [_jsxs("span", { className: "min-w-0 flex-1 truncate px-1.5", title: target, children: [_jsx("span", { className: "text-fg", children: shown.site }), _jsx("span", { className: "text-fg-subtle", children: shown.rest })] }), openable ? (_jsx(IconButton, { size: "sm", label: "Open link", icon: _jsx(ExternalLink, { className: "size-3.5" }), onMouseDown: keepTextFocus, onClick: () => window.open(href, '_blank', 'noopener,noreferrer') })) : null, _jsx(IconButton, { size: "sm", label: "Copy link", icon: _jsx(Copy, { className: "size-3.5" }), onMouseDown: keepTextFocus, onClick: () => onCopy(target) }), _jsx(IconButton, { size: "sm", label: "Edit link", icon: _jsx(Pencil, { className: "size-3.5" }), onClick: startEdit }), _jsx(IconButton, { size: "sm", label: "Remove link", icon: _jsx(Unlink, { className: "size-3.5" }), onMouseDown: keepTextFocus, onClick: onRemove })] })) }));
76
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * How the link card shows an address, what it may open and where it goes.
3
+ * What a typed address becomes is the editor's own rule (see {@link LinkCard}).
4
+ */
5
+ /** The address split for display: the site in front, the rest after it. */
6
+ export declare function shownLink(target: string): {
7
+ site: string;
8
+ rest: string;
9
+ };
10
+ /** Whether a resolved address may be opened from the card. */
11
+ export declare function canOpenLink(resolved: string): boolean;
12
+ /** Where the card goes: below the link, or above it when below would leave the window. */
13
+ export declare function placeLinkCard(link: {
14
+ top: number;
15
+ bottom: number;
16
+ left: number;
17
+ }, card: {
18
+ width: number;
19
+ height: number;
20
+ }, window: {
21
+ width: number;
22
+ height: number;
23
+ }, gap?: number): {
24
+ top: number;
25
+ left: number;
26
+ };
@@ -0,0 +1,37 @@
1
+ /**
2
+ * How the link card shows an address, what it may open and where it goes.
3
+ * What a typed address becomes is the editor's own rule (see {@link LinkCard}).
4
+ */
5
+ /** The address split for display: the site in front, the rest after it. */
6
+ export function shownLink(target) {
7
+ const web = /^https?:\/\/([^/?#]+)(.*)$/i.exec(target);
8
+ if (web)
9
+ return { site: web[1].replace(/^www\./i, ''), rest: web[2] === '/' ? '' : web[2] };
10
+ const mail = /^mailto:(.*)$/i.exec(target);
11
+ if (mail) {
12
+ try {
13
+ return { site: decodeURIComponent(mail[1]), rest: '' };
14
+ }
15
+ catch {
16
+ return { site: mail[1], rest: '' };
17
+ }
18
+ }
19
+ return { site: target, rest: '' };
20
+ }
21
+ /** Whether a resolved address may be opened from the card. */
22
+ export function canOpenLink(resolved) {
23
+ try {
24
+ return ['http:', 'https:', 'mailto:'].includes(new URL(resolved).protocol);
25
+ }
26
+ catch {
27
+ return false;
28
+ }
29
+ }
30
+ /** Where the card goes: below the link, or above it when below would leave the window. */
31
+ export function placeLinkCard(link, card, window, gap = 6) {
32
+ const below = link.bottom + gap;
33
+ const above = link.top - gap - card.height;
34
+ const top = below + card.height <= window.height - gap || above < gap ? below : above;
35
+ const left = Math.max(gap, Math.min(link.left, window.width - card.width - gap));
36
+ return { top, left };
37
+ }
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
  };
@@ -145,7 +151,7 @@ export function ScrubNumberField({ value, mixed = false, onChange, onCommit, lab
145
151
  if (typing instanceof HTMLElement && typing !== inputRef.current && (typing.matches('input, textarea') || typing.isContentEditable))
146
152
  typing.blur();
147
153
  event.currentTarget.setPointerCapture(event.pointerId);
148
- const start = mixed || value === null ? (min ?? 0) : value;
154
+ const start = mixed || value === null ? stepStart(min, max) : value;
149
155
  scrub.current = { start, current: start, travel: 0, carry: 0, pointerId: event.pointerId };
150
156
  };
151
157
  const onPointerMove = (event) => {
@@ -164,7 +170,8 @@ export function ScrubNumberField({ value, mixed = false, onChange, onCommit, lab
164
170
  return;
165
171
  state.carry -= steps * pixelsPerStep;
166
172
  const unitStep = event.shiftKey ? big : event.altKey ? small : step;
167
- const next = fit(state.current + steps * unitStep);
173
+ const moved = state.current + steps * unitStep;
174
+ const next = fit(event.altKey ? moved : snapToStep(moved, step));
168
175
  if (next === state.current)
169
176
  return;
170
177
  state.current = next;
@@ -187,7 +194,7 @@ export function ScrubNumberField({ value, mixed = false, onChange, onCommit, lab
187
194
  // eslint-disable-next-line react-hooks/exhaustive-deps
188
195
  }, [scrubbing]);
189
196
  const numeric = value !== null && !mixed ? roundTo(value, decimals) : undefined;
190
- return (_jsxs("div", { className: cn('flex h-7 min-w-0 items-center rounded-control border border-line bg-surface-2 text-[13px] text-fg focus-within:border-accent focus-within:bg-surface', disabled && 'opacity-50', scrubbing && 'border-accent', className), children: [label !== undefined ? (_jsx("span", { "aria-hidden": "true", "data-scrub-for": inputId, title: title ?? 'Drag to change', onPointerDown: onPointerDown, onPointerMove: onPointerMove, onPointerUp: (event) => endScrub(event.currentTarget, true), onPointerCancel: (event) => endScrub(event.currentTarget, false), onLostPointerCapture: (event) => scrub.current && endScrub(event.currentTarget, true), className: cn('flex h-full min-w-6 shrink-0 select-none items-center justify-center px-1 text-[11px] text-fg-subtle touch-none', disabled ? 'cursor-default' : 'cursor-ew-resize hover:text-fg'), children: label })) : null, _jsx("input", { ref: inputRef, id: inputId, role: "spinbutton", inputMode: "decimal", autoComplete: "off", spellCheck: false, "aria-label": aria['aria-label'], "aria-valuenow": numeric, "aria-valuemin": min, "aria-valuemax": max, "aria-valuetext": mixed ? 'Mixed' : numeric !== undefined ? `${formatNumber(numeric, decimals)}${unit ?? ''}` : undefined, disabled: disabled, value: draft, placeholder: mixed ? 'Mixed' : placeholder, onFocus: (event) => event.currentTarget.select(), onChange: (event) => {
197
+ return (_jsxs("div", { "data-ui-field": "", className: cn('flex h-7 min-w-0 items-center rounded-control border border-line bg-surface-2 text-[13px] text-fg focus-within:border-accent focus-within:bg-surface', disabled && 'opacity-50', scrubbing && 'border-accent', className), children: [label !== undefined ? (_jsx("span", { "aria-hidden": "true", "data-scrub-for": inputId, title: title ?? 'Drag to change', onPointerDown: onPointerDown, onPointerMove: onPointerMove, onPointerUp: (event) => endScrub(event.currentTarget, true), onPointerCancel: (event) => endScrub(event.currentTarget, false), onLostPointerCapture: (event) => scrub.current && endScrub(event.currentTarget, true), className: cn('flex h-full min-w-6 shrink-0 select-none items-center justify-center px-1 text-[11px] text-fg-subtle touch-none', disabled ? 'cursor-default' : 'cursor-ew-resize hover:text-fg'), children: label })) : null, _jsx("input", { ref: inputRef, id: inputId, role: "spinbutton", inputMode: "decimal", autoComplete: "off", spellCheck: false, "aria-label": aria['aria-label'], "aria-valuenow": numeric, "aria-valuemin": min, "aria-valuemax": max, "aria-valuetext": mixed ? 'Mixed' : numeric !== undefined ? `${formatNumber(numeric, decimals)}${unit ?? ''}` : undefined, disabled: disabled, value: draft, placeholder: mixed ? 'Mixed' : placeholder, onFocus: (event) => event.currentTarget.select(), onChange: (event) => {
191
198
  editing.current = true;
192
199
  setDraft(event.target.value);
193
200
  }, onBlur: commitText, onKeyDown: onKeyDown, className: cn('h-full w-full min-w-0 bg-transparent tabular-nums outline-none placeholder:text-fg-subtle', label === undefined && 'pl-2', !unit && 'pr-2') }), unit ? _jsx("span", { className: "shrink-0 pr-2 text-[11px] text-fg-subtle", children: unit }) : null] }));