@open-artifact/ui 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +5 -0
  3. package/README.md +5 -2
  4. package/package.json +48 -4
  5. package/src/button.d.ts +30 -0
  6. package/src/button.js +28 -0
  7. package/src/cn.d.ts +3 -0
  8. package/src/cn.js +5 -0
  9. package/src/color-picker.d.ts +98 -0
  10. package/src/color-picker.js +370 -0
  11. package/src/color.d.ts +144 -0
  12. package/src/color.js +528 -0
  13. package/src/data/google-fonts.json +1775 -0
  14. package/src/effect-editors.d.ts +48 -0
  15. package/src/effect-editors.js +230 -0
  16. package/src/effects.d.ts +118 -0
  17. package/src/effects.js +425 -0
  18. package/src/fields.d.ts +105 -0
  19. package/src/fields.js +77 -0
  20. package/src/focusables.d.ts +26 -0
  21. package/src/focusables.js +42 -0
  22. package/src/font-picker.d.ts +62 -0
  23. package/src/font-picker.js +238 -0
  24. package/src/fonts.d.ts +121 -0
  25. package/src/fonts.js +273 -0
  26. package/src/history-diff.d.ts +64 -0
  27. package/src/history-diff.js +151 -0
  28. package/src/history.d.ts +95 -0
  29. package/src/history.js +160 -0
  30. package/src/index.d.ts +25 -0
  31. package/src/index.js +25 -0
  32. package/src/keys.d.ts +60 -0
  33. package/src/keys.js +78 -0
  34. package/src/layout.d.ts +55 -0
  35. package/src/layout.js +64 -0
  36. package/src/menu.d.ts +50 -0
  37. package/src/menu.js +36 -0
  38. package/src/numbers.d.ts +24 -0
  39. package/src/numbers.js +114 -0
  40. package/src/overlays.d.ts +38 -0
  41. package/src/overlays.js +26 -0
  42. package/src/scroll.d.ts +24 -0
  43. package/src/scroll.js +111 -0
  44. package/src/scrub-number-field.d.ts +56 -0
  45. package/src/scrub-number-field.js +190 -0
  46. package/src/styles.css +122 -0
  47. package/src/tooltip.d.ts +18 -0
  48. package/src/tooltip.js +10 -0
package/src/numbers.js ADDED
@@ -0,0 +1,114 @@
1
+ /**
2
+ * Number text for {@link ScrubNumberField}: reading what was typed (a
3
+ * number, a unit, simple arithmetic) and rounding to a step. No DOM.
4
+ */
5
+ /**
6
+ * Reads typed text: `12`, `12px`, `-4.5`, `.5`, or arithmetic with `+ - * /`
7
+ * and parentheses (`10 + 4`, `100/3`, `(8+2)*2px`). A unit may follow the
8
+ * whole expression or its first number. Null when the text is not that.
9
+ */
10
+ export function evaluateNumberInput(text) {
11
+ const source = text.trim().replace(/,/g, '.');
12
+ if (!source)
13
+ return null;
14
+ // Units: letters or % after a number; all of them must be the same.
15
+ let unit;
16
+ const bare = source.replace(/(\d|\.)\s*([a-z]+|%)/gi, (_match, digit, u) => {
17
+ const lower = u.toLowerCase();
18
+ if (unit !== undefined && unit !== lower)
19
+ unit = '\u0000';
20
+ else
21
+ unit = lower;
22
+ return digit;
23
+ });
24
+ if (unit === '\u0000')
25
+ return null;
26
+ if (!/^[\d.\s+\-*/()]+$/.test(bare))
27
+ return null;
28
+ let at = 0;
29
+ const peek = () => {
30
+ while (bare[at] === ' ')
31
+ at++;
32
+ return bare[at];
33
+ };
34
+ const number = () => {
35
+ const match = /^(?:\d+\.?\d*|\.\d+)/.exec(bare.slice(at));
36
+ if (!match)
37
+ return null;
38
+ at += match[0].length;
39
+ return Number(match[0]);
40
+ };
41
+ const factor = () => {
42
+ const ch = peek();
43
+ if (ch === '-' || ch === '+') {
44
+ at++;
45
+ const inner = factor();
46
+ return inner === null ? null : ch === '-' ? -inner : inner;
47
+ }
48
+ if (ch === '(') {
49
+ at++;
50
+ const inner = sum();
51
+ if (inner === null || peek() !== ')')
52
+ return null;
53
+ at++;
54
+ return inner;
55
+ }
56
+ return number();
57
+ };
58
+ const product = () => {
59
+ let left = factor();
60
+ while (left !== null && (peek() === '*' || peek() === '/')) {
61
+ const op = bare[at++];
62
+ const right = factor();
63
+ if (right === null)
64
+ return null;
65
+ left = op === '*' ? left * right : left / right;
66
+ }
67
+ return left;
68
+ };
69
+ const sum = () => {
70
+ let left = product();
71
+ while (left !== null && (peek() === '+' || peek() === '-')) {
72
+ const op = bare[at++];
73
+ const right = product();
74
+ if (right === null)
75
+ return null;
76
+ left = op === '+' ? left + right : left - right;
77
+ }
78
+ return left;
79
+ };
80
+ const value = sum();
81
+ if (value === null || peek() !== undefined || !Number.isFinite(value))
82
+ return null;
83
+ return unit === undefined ? { value } : { value, unit };
84
+ }
85
+ /** Decimals needed to show multiples of `step` (0.25 → 2). */
86
+ export function stepDecimals(step) {
87
+ if (!Number.isFinite(step) || step <= 0)
88
+ return 0;
89
+ const text = String(step);
90
+ const exp = /e-(\d+)$/.exec(text);
91
+ if (exp)
92
+ return Number(exp[1]);
93
+ const dot = text.indexOf('.');
94
+ return dot < 0 ? 0 : text.length - dot - 1;
95
+ }
96
+ /** Rounds `value` to `decimals` places, without `-0`. */
97
+ export function roundTo(value, decimals) {
98
+ const factor = 10 ** decimals;
99
+ const out = Math.round(value * factor) / factor;
100
+ return Object.is(out, -0) ? 0 : out;
101
+ }
102
+ /** Clamps into `[min, max]` (either bound optional). */
103
+ export function clampNumber(value, min, max) {
104
+ let out = value;
105
+ if (min !== undefined && out < min)
106
+ out = min;
107
+ if (max !== undefined && out > max)
108
+ out = max;
109
+ return out;
110
+ }
111
+ /** Formats a value for a number field: rounded, no trailing zeros. */
112
+ export function formatNumber(value, decimals) {
113
+ return String(roundTo(value, decimals));
114
+ }
@@ -0,0 +1,38 @@
1
+ import type { ReactElement, ReactNode } from 'react';
2
+ /** Props of {@link Popover}. */
3
+ export interface PopoverProps {
4
+ trigger: ReactElement<Record<string, unknown>>;
5
+ children: ReactNode;
6
+ side?: 'top' | 'bottom' | 'left' | 'right';
7
+ align?: 'start' | 'center' | 'end';
8
+ open?: boolean;
9
+ onOpenChange?: (open: boolean) => void;
10
+ className?: string;
11
+ }
12
+ /** A floating panel anchored to a trigger, on any of its four sides. A held Enter opens it once. */
13
+ export declare function Popover({ trigger, children, side, align, open, onOpenChange, className }: PopoverProps): import("react/jsx-runtime").JSX.Element;
14
+ /** Props of {@link Dialog}. */
15
+ export interface DialogProps {
16
+ open: boolean;
17
+ onOpenChange: (open: boolean) => void;
18
+ title: ReactNode;
19
+ description?: ReactNode;
20
+ children?: ReactNode;
21
+ /** Footer buttons; defaults to none. */
22
+ footer?: ReactNode;
23
+ className?: string;
24
+ }
25
+ /** A modal dialog. */
26
+ export declare function Dialog({ open, onOpenChange, title, description, children, footer, className }: DialogProps): import("react/jsx-runtime").JSX.Element;
27
+ /** Props of {@link ConfirmDialog}. */
28
+ export interface ConfirmDialogProps {
29
+ open: boolean;
30
+ onOpenChange: (open: boolean) => void;
31
+ title: ReactNode;
32
+ description?: ReactNode;
33
+ confirmLabel?: string;
34
+ danger?: boolean;
35
+ onConfirm: () => void;
36
+ }
37
+ /** A yes/no dialog. */
38
+ export declare function ConfirmDialog({ open, onOpenChange, title, description, confirmLabel, danger, onConfirm }: ConfirmDialogProps): import("react/jsx-runtime").JSX.Element;
@@ -0,0 +1,26 @@
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ /**
3
+ * Popover and dialog wrappers.
4
+ */
5
+ import { Dialog as BaseDialog } from '@base-ui/react/dialog';
6
+ import { Popover as BasePopover } from '@base-ui/react/popover';
7
+ import { X } from 'lucide-react';
8
+ import { Button } from "./button.js";
9
+ import { cn } from "./cn.js";
10
+ import { preventRepeatedActivation } from "./keys.js";
11
+ import { POPUP_CLASS } from "./menu.js";
12
+ /** A floating panel anchored to a trigger, on any of its four sides. A held Enter opens it once. */
13
+ export function Popover({ trigger, children, side = 'bottom', align = 'center', open, onOpenChange, className }) {
14
+ return (_jsxs(BasePopover.Root, { open: open, onOpenChange: onOpenChange ? (next) => onOpenChange(next) : undefined, children: [_jsx(BasePopover.Trigger, { render: trigger, onKeyDown: preventRepeatedActivation }), _jsx(BasePopover.Portal, { children: _jsx(BasePopover.Positioner, { side: side, align: align, sideOffset: 8, className: "z-[1000]", children: _jsx(BasePopover.Popup, { className: cn(POPUP_CLASS, 'p-3', className), children: children }) }) })] }));
15
+ }
16
+ /** A modal dialog. */
17
+ export function Dialog({ open, onOpenChange, title, description, children, footer, className }) {
18
+ return (_jsx(BaseDialog.Root, { open: open, onOpenChange: (next) => onOpenChange(next), children: _jsxs(BaseDialog.Portal, { children: [_jsx(BaseDialog.Backdrop, { className: "fixed inset-0 z-[900] bg-black/30 transition-opacity data-[starting-style]:opacity-0 data-[ending-style]:opacity-0" }), _jsxs(BaseDialog.Popup, { className: cn('fixed left-1/2 top-1/2 z-[901] w-[min(28rem,calc(100vw-2rem))] -translate-x-1/2 -translate-y-1/2 rounded-xl bg-surface p-5 text-fg shadow-popup outline-none', 'transition-[opacity,transform] data-[starting-style]:scale-95 data-[starting-style]:opacity-0 data-[ending-style]:opacity-0', className), children: [_jsxs("div", { className: "mb-3 flex items-start gap-3", children: [_jsxs("div", { className: "flex-1", children: [_jsx(BaseDialog.Title, { className: "text-[15px] font-semibold", children: title }), description ? _jsx(BaseDialog.Description, { className: "mt-1 text-fg-muted", children: description }) : null] }), _jsx(BaseDialog.Close, { "aria-label": "Close", className: "rounded-md p-1 text-fg-muted hover:bg-hover", children: _jsx(X, { className: "size-4" }) })] }), children, footer ? _jsx("div", { className: "mt-4 flex justify-end gap-2", children: footer }) : null] })] }) }));
19
+ }
20
+ /** A yes/no dialog. */
21
+ export function ConfirmDialog({ open, onOpenChange, title, description, confirmLabel = 'Confirm', danger, onConfirm }) {
22
+ return (_jsx(Dialog, { open: open, onOpenChange: onOpenChange, title: title, description: description, footer: _jsxs(_Fragment, { children: [_jsx(Button, { onClick: () => onOpenChange(false), children: "Cancel" }), _jsx(Button, { variant: danger ? 'danger' : 'primary', onClick: () => {
23
+ onConfirm();
24
+ onOpenChange(false);
25
+ }, children: confirmLabel })] }) }));
26
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Scrolling regions that keyboard users can reach.
3
+ */
4
+ import { type HTMLAttributes, type RefObject } from 'react';
5
+ /**
6
+ * Whether the element's content overflows an axis that scrolls, kept current
7
+ * as the element or its children resize and as children come and go.
8
+ */
9
+ export declare function useHasScrollOverflow(ref: RefObject<HTMLElement | null>): boolean;
10
+ /** Props of {@link ScrollBody}. */
11
+ export interface ScrollBodyProps extends HTMLAttributes<HTMLDivElement> {
12
+ /**
13
+ * Accessible name used when the region becomes a tab stop. Defaults to the
14
+ * enclosing dialog's title, else "Panel content".
15
+ */
16
+ label?: string;
17
+ }
18
+ /**
19
+ * A scrolling region (give it a max height and `overflow-auto`). When its
20
+ * content overflows and holds no tab stop of its own, it becomes a named,
21
+ * focusable group so keyboard users can Tab to it and scroll it; otherwise
22
+ * it stays out of the tab order.
23
+ */
24
+ export declare const ScrollBody: import("react").ForwardRefExoticComponent<ScrollBodyProps & import("react").RefAttributes<HTMLDivElement>>;
package/src/scroll.js ADDED
@@ -0,0 +1,111 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ /**
3
+ * Scrolling regions that keyboard users can reach.
4
+ */
5
+ import { forwardRef, useCallback, useLayoutEffect, useRef, useState } from 'react';
6
+ import { cn } from "./cn.js";
7
+ import { scrollsOverflow, tabbableElements } from "./focusables.js";
8
+ /**
9
+ * Whether the element's content overflows an axis that scrolls, kept current
10
+ * as the element or its children resize and as children come and go.
11
+ */
12
+ export function useHasScrollOverflow(ref) {
13
+ const [overflowing, setOverflowing] = useState(false);
14
+ useLayoutEffect(() => {
15
+ const element = ref.current;
16
+ const view = element?.ownerDocument.defaultView;
17
+ if (!element || !view)
18
+ return;
19
+ const measure = () => {
20
+ const style = view.getComputedStyle(element);
21
+ setOverflowing(scrollsOverflow({
22
+ scrollWidth: element.scrollWidth,
23
+ clientWidth: element.clientWidth,
24
+ scrollHeight: element.scrollHeight,
25
+ clientHeight: element.clientHeight,
26
+ overflowX: style.overflowX,
27
+ overflowY: style.overflowY,
28
+ }));
29
+ };
30
+ measure();
31
+ if (typeof view.ResizeObserver !== 'function')
32
+ return;
33
+ const resize = new view.ResizeObserver(measure);
34
+ const watched = new Set();
35
+ const watch = (node) => {
36
+ if (node.nodeType !== 1)
37
+ return;
38
+ const child = node;
39
+ // `display: contents` boxes have no size of their own; watch what they hold.
40
+ if (view.getComputedStyle(child).display === 'contents') {
41
+ child.childNodes.forEach(watch);
42
+ return;
43
+ }
44
+ if (!watched.has(child)) {
45
+ watched.add(child);
46
+ resize.observe(child);
47
+ }
48
+ };
49
+ resize.observe(element);
50
+ element.childNodes.forEach(watch);
51
+ const mutations = new view.MutationObserver((records) => {
52
+ for (const record of records)
53
+ record.addedNodes.forEach(watch);
54
+ for (const child of watched) {
55
+ if (!element.contains(child)) {
56
+ resize.unobserve(child);
57
+ watched.delete(child);
58
+ }
59
+ }
60
+ measure();
61
+ });
62
+ mutations.observe(element, { childList: true, subtree: true, characterData: true });
63
+ return () => {
64
+ resize.disconnect();
65
+ mutations.disconnect();
66
+ };
67
+ }, [ref]);
68
+ return overflowing;
69
+ }
70
+ /**
71
+ * A scrolling region (give it a max height and `overflow-auto`). When its
72
+ * content overflows and holds no tab stop of its own, it becomes a named,
73
+ * focusable group so keyboard users can Tab to it and scroll it; otherwise
74
+ * it stays out of the tab order.
75
+ */
76
+ export const ScrollBody = forwardRef(function ScrollBody({ label, className, ...rest }, forwardedRef) {
77
+ const ref = useRef(null);
78
+ const setRef = useCallback((node) => {
79
+ ref.current = node;
80
+ if (typeof forwardedRef === 'function')
81
+ forwardedRef(node);
82
+ else if (forwardedRef)
83
+ forwardedRef.current = node;
84
+ }, [forwardedRef]);
85
+ const overflowing = useHasScrollOverflow(ref);
86
+ const [needsStop, setNeedsStop] = useState(false);
87
+ const [labelledBy, setLabelledBy] = useState(null);
88
+ useLayoutEffect(() => {
89
+ const body = ref.current;
90
+ const view = body?.ownerDocument.defaultView;
91
+ if (!overflowing || !body || !view)
92
+ return;
93
+ const update = () => {
94
+ setNeedsStop(tabbableElements(body).length === 0);
95
+ setLabelledBy(body.closest('[role="dialog"], [role="alertdialog"]')?.getAttribute('aria-labelledby') ?? null);
96
+ };
97
+ update();
98
+ const observer = new view.MutationObserver(update);
99
+ observer.observe(body, { childList: true, subtree: true, attributes: true, attributeFilter: ['tabindex', 'disabled', 'hidden', 'href', 'contenteditable'] });
100
+ return () => observer.disconnect();
101
+ }, [overflowing]);
102
+ const focusable = overflowing && needsStop;
103
+ return (_jsx("div", { ref: setRef, ...(focusable
104
+ ? {
105
+ role: 'group',
106
+ tabIndex: 0,
107
+ 'aria-labelledby': label === undefined ? (labelledBy ?? undefined) : undefined,
108
+ 'aria-label': label ?? (labelledBy === null ? 'Panel content' : undefined),
109
+ }
110
+ : {}), className: cn(focusable && 'focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-accent', className), ...rest }));
111
+ });
@@ -0,0 +1,56 @@
1
+ /**
2
+ * {@link ScrubNumberField}: a number field whose label is dragged sideways
3
+ * to change the value, the way design tools do it.
4
+ */
5
+ import { type ReactNode } from 'react';
6
+ /** Props of {@link ScrubNumberField}. */
7
+ export interface ScrubNumberFieldProps {
8
+ /** The value; null shows the field empty (with `placeholder`). */
9
+ value: number | null;
10
+ /** Several selected things differ: show "Mixed" until a value is entered. */
11
+ mixed?: boolean;
12
+ /** Live value while scrubbing or stepping with held keys. */
13
+ onChange?: (value: number) => void;
14
+ /**
15
+ * Final value: typed and committed (Enter or blur), stepped with a key, or
16
+ * at the end of a scrub. `unit` is set when the user typed one of `units`.
17
+ */
18
+ onCommit: (value: number, unit?: string) => void;
19
+ /** Accessible name (required: the label may be an icon). */
20
+ 'aria-label': string;
21
+ /** The drag handle at the start: a letter (`W`, `X`) or an icon. Without it the field has no scrub handle. */
22
+ label?: ReactNode;
23
+ /** Unit shown after the number (`px`, `%`, `°`). Typing it is allowed. */
24
+ unit?: string;
25
+ /** Other units the user may type (`em`, `rem`); a typed one is passed to `onCommit`. */
26
+ units?: readonly string[];
27
+ min?: number;
28
+ max?: number;
29
+ /** Arrow-key and scrub step (default 1). */
30
+ step?: number;
31
+ /** Shift + arrow and Page Up/Down step (default 10 × step). */
32
+ largeStep?: number;
33
+ /** Alt + arrow step (default step / 10). */
34
+ smallStep?: number;
35
+ /** Decimals kept (default: those of the smallest step). */
36
+ precision?: number;
37
+ /** Pixels of drag per step (default 2). */
38
+ pixelsPerStep?: number;
39
+ placeholder?: string;
40
+ disabled?: boolean;
41
+ className?: string;
42
+ /** Tooltip of the drag handle. */
43
+ title?: string;
44
+ }
45
+ /**
46
+ * A number field with a drag-to-scrub label.
47
+ *
48
+ * - Drag the label sideways to scrub (Shift: large steps, Alt: small
49
+ * steps); Escape during a drag puts the value back.
50
+ * - Arrow Up/Down step (Shift ×10, Alt ÷10), Page Up/Down take large
51
+ * steps, Home/End go to `min`/`max`.
52
+ * - Typing accepts arithmetic (`12*2`, `100/3`) and a unit; Enter or blur
53
+ * commits, Escape reverts.
54
+ * - `mixed` shows "Mixed" until something is entered.
55
+ */
56
+ export declare function ScrubNumberField({ value, mixed, onChange, onCommit, label, unit, units, min, max, step, largeStep, smallStep, precision, pixelsPerStep, placeholder, disabled, className, title, ...aria }: ScrubNumberFieldProps): import("react/jsx-runtime").JSX.Element;
@@ -0,0 +1,190 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ /**
3
+ * {@link ScrubNumberField}: a number field whose label is dragged sideways
4
+ * to change the value, the way design tools do it.
5
+ */
6
+ import { useEffect, useId, useRef, useState } from 'react';
7
+ import { cn } from "./cn.js";
8
+ import { clampNumber, evaluateNumberInput, formatNumber, roundTo, stepDecimals } from "./numbers.js";
9
+ /**
10
+ * A number field with a drag-to-scrub label.
11
+ *
12
+ * - Drag the label sideways to scrub (Shift: large steps, Alt: small
13
+ * steps); Escape during a drag puts the value back.
14
+ * - Arrow Up/Down step (Shift ×10, Alt ÷10), Page Up/Down take large
15
+ * steps, Home/End go to `min`/`max`.
16
+ * - Typing accepts arithmetic (`12*2`, `100/3`) and a unit; Enter or blur
17
+ * commits, Escape reverts.
18
+ * - `mixed` shows "Mixed" until something is entered.
19
+ */
20
+ export function ScrubNumberField({ value, mixed = false, onChange, onCommit, label, unit, units, min, max, step = 1, largeStep, smallStep, precision, pixelsPerStep = 2, placeholder, disabled, className, title, ...aria }) {
21
+ const big = largeStep ?? step * 10;
22
+ const small = smallStep ?? step / 10;
23
+ const decimals = precision ?? Math.max(stepDecimals(step), stepDecimals(small));
24
+ const shown = (v) => (v === null || mixed ? '' : formatNumber(v, decimals));
25
+ const [draft, setDraft] = useState(() => shown(value));
26
+ const [scrubbing, setScrubbing] = useState(false);
27
+ const editing = useRef(false);
28
+ const inputRef = useRef(null);
29
+ const inputId = useId();
30
+ /** The value at the start of a scrub, and the drag so far. */
31
+ const scrub = useRef(null);
32
+ // Follow outside changes unless the user is typing.
33
+ useEffect(() => {
34
+ if (!editing.current)
35
+ setDraft(shown(value));
36
+ // eslint-disable-next-line react-hooks/exhaustive-deps
37
+ }, [value, mixed, decimals]);
38
+ const fit = (v) => roundTo(clampNumber(v, min, max), decimals);
39
+ const commitText = () => {
40
+ editing.current = false;
41
+ const text = draft.trim();
42
+ if (!text) {
43
+ setDraft(shown(value));
44
+ return;
45
+ }
46
+ const typed = evaluateNumberInput(text);
47
+ const typedUnit = typed?.unit;
48
+ const allowed = typedUnit === undefined || typedUnit === unit?.toLowerCase() || units?.some((u) => u.toLowerCase() === typedUnit);
49
+ if (!typed || !allowed) {
50
+ setDraft(shown(value));
51
+ return;
52
+ }
53
+ const next = fit(typed.value);
54
+ const otherUnit = typedUnit !== undefined && typedUnit !== unit?.toLowerCase() ? typedUnit : undefined;
55
+ setDraft(formatNumber(next, decimals));
56
+ if (next !== value || mixed || otherUnit)
57
+ onCommit(next, otherUnit);
58
+ };
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);
64
+ editing.current = false;
65
+ setDraft(formatNumber(next, decimals));
66
+ onChange?.(next);
67
+ onCommit(next);
68
+ };
69
+ const onKeyDown = (event) => {
70
+ const unitStep = event.shiftKey ? big : event.altKey ? small : step;
71
+ switch (event.key) {
72
+ case 'ArrowUp':
73
+ event.preventDefault();
74
+ stepBy(unitStep);
75
+ break;
76
+ case 'ArrowDown':
77
+ event.preventDefault();
78
+ stepBy(-unitStep);
79
+ break;
80
+ case 'PageUp':
81
+ event.preventDefault();
82
+ stepBy(big);
83
+ break;
84
+ case 'PageDown':
85
+ event.preventDefault();
86
+ stepBy(-big);
87
+ break;
88
+ case 'Home':
89
+ if (min !== undefined && !event.shiftKey) {
90
+ event.preventDefault();
91
+ stepBy(min - (value ?? 0));
92
+ }
93
+ break;
94
+ case 'End':
95
+ if (max !== undefined && !event.shiftKey) {
96
+ event.preventDefault();
97
+ stepBy(max - (value ?? 0));
98
+ }
99
+ break;
100
+ case 'Enter':
101
+ event.preventDefault();
102
+ commitText();
103
+ event.currentTarget.select();
104
+ break;
105
+ case 'Escape':
106
+ if (editing.current) {
107
+ event.preventDefault();
108
+ event.stopPropagation();
109
+ editing.current = false;
110
+ setDraft(shown(value));
111
+ }
112
+ break;
113
+ }
114
+ };
115
+ /* --------------------------------- scrub -------------------------------- */
116
+ const endScrub = (target, commit) => {
117
+ const state = scrub.current;
118
+ if (!state)
119
+ return;
120
+ scrub.current = null;
121
+ setScrubbing(false);
122
+ if (target.hasPointerCapture(state.pointerId))
123
+ target.releasePointerCapture(state.pointerId);
124
+ if (!commit) {
125
+ setDraft(shown(value));
126
+ if (state.current !== state.start)
127
+ onChange?.(state.start);
128
+ return;
129
+ }
130
+ if (state.travel < pixelsPerStep) {
131
+ // A click on the label focuses the field.
132
+ inputRef.current?.focus();
133
+ inputRef.current?.select();
134
+ return;
135
+ }
136
+ if (state.current !== state.start || mixed)
137
+ onCommit(state.current);
138
+ };
139
+ const onPointerDown = (event) => {
140
+ if (disabled || event.button !== 0)
141
+ return;
142
+ event.preventDefault();
143
+ event.currentTarget.setPointerCapture(event.pointerId);
144
+ const start = mixed || value === null ? (min ?? 0) : value;
145
+ scrub.current = { start, current: start, travel: 0, carry: 0, pointerId: event.pointerId };
146
+ };
147
+ const onPointerMove = (event) => {
148
+ const state = scrub.current;
149
+ if (!state || event.pointerId !== state.pointerId)
150
+ return;
151
+ state.travel += Math.abs(event.movementX);
152
+ // Movement below a step carries over, so slow drags still move.
153
+ state.carry += event.movementX;
154
+ if (state.travel < pixelsPerStep)
155
+ return;
156
+ if (!scrubbing)
157
+ setScrubbing(true);
158
+ const steps = Math.trunc(state.carry / pixelsPerStep);
159
+ if (steps === 0)
160
+ return;
161
+ state.carry -= steps * pixelsPerStep;
162
+ const unitStep = event.shiftKey ? big : event.altKey ? small : step;
163
+ const next = fit(state.current + steps * unitStep);
164
+ if (next === state.current)
165
+ return;
166
+ state.current = next;
167
+ setDraft(formatNumber(next, decimals));
168
+ onChange?.(next);
169
+ };
170
+ useEffect(() => {
171
+ if (!scrubbing)
172
+ return;
173
+ const onKey = (event) => {
174
+ if (event.key !== 'Escape' || !scrub.current)
175
+ return;
176
+ event.preventDefault();
177
+ const handle = document.querySelector(`[data-scrub-for="${CSS.escape(inputId)}"]`);
178
+ if (handle)
179
+ endScrub(handle, false);
180
+ };
181
+ window.addEventListener('keydown', onKey, true);
182
+ return () => window.removeEventListener('keydown', onKey, true);
183
+ // eslint-disable-next-line react-hooks/exhaustive-deps
184
+ }, [scrubbing]);
185
+ const numeric = value !== null && !mixed ? roundTo(value, decimals) : undefined;
186
+ 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) => {
187
+ editing.current = true;
188
+ setDraft(event.target.value);
189
+ }, 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] }));
190
+ }