@open-artifact/ui 0.10.0 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/clicks.d.ts +63 -0
- package/src/clicks.js +71 -0
- package/src/color-picker.js +31 -17
- package/src/color.d.ts +6 -0
- package/src/color.js +15 -0
- package/src/fields.d.ts +2 -2
- package/src/fields.js +4 -2
- package/src/index.d.ts +1 -0
- package/src/index.js +1 -0
- package/src/menu.d.ts +1 -1
- package/src/menu.js +6 -2
- package/src/numbers.d.ts +4 -0
- package/src/numbers.js +10 -0
- package/src/scrub-number-field.d.ts +6 -2
- package/src/scrub-number-field.js +24 -17
package/package.json
CHANGED
package/src/clicks.d.ts
ADDED
|
@@ -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
|
+
}
|
package/src/color-picker.js
CHANGED
|
@@ -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
|
-
|
|
168
|
-
|
|
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 =
|
|
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)}
|
|
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
|
-
/**
|
|
285
|
-
|
|
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 =
|
|
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 -
|
|
294
|
-
PageUp: value +
|
|
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":
|
|
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. */
|
package/src/fields.d.ts
CHANGED
|
@@ -6,8 +6,8 @@ export declare const TextInput: import("react").ForwardRefExoticComponent<InputH
|
|
|
6
6
|
/** Props of {@link CommitInput}. */
|
|
7
7
|
export interface CommitInputProps extends Omit<InputHTMLAttributes<HTMLInputElement>, 'value' | 'onChange'> {
|
|
8
8
|
value: string;
|
|
9
|
-
/** Called on Enter or blur, only when the text changed. */
|
|
10
|
-
onCommit: (value: string) => void;
|
|
9
|
+
/** Called on Enter or blur, only when the text changed. Returning `false` refuses the text: the field shows `value` again. */
|
|
10
|
+
onCommit: (value: string) => void | boolean;
|
|
11
11
|
/** Called with the draft as it is typed, and with `value` again when Escape puts it back. */
|
|
12
12
|
onDraftChange?: (draft: string) => void;
|
|
13
13
|
}
|
package/src/fields.js
CHANGED
|
@@ -35,8 +35,10 @@ export function CommitInput({ value, onCommit, onDraftChange, className, ...rest
|
|
|
35
35
|
settled.current = false;
|
|
36
36
|
return;
|
|
37
37
|
}
|
|
38
|
-
if (draft !== value)
|
|
39
|
-
|
|
38
|
+
if (draft !== value && onCommit(draft) === false) {
|
|
39
|
+
setDraft(value);
|
|
40
|
+
onDraftChange?.(value);
|
|
41
|
+
}
|
|
40
42
|
};
|
|
41
43
|
return (_jsx("input", { className: cn(INPUT_CLASS, className), value: draft, onChange: (event) => {
|
|
42
44
|
setDraft(event.target.value);
|
package/src/index.d.ts
CHANGED
|
@@ -12,6 +12,7 @@ export * from './overlays.tsx';
|
|
|
12
12
|
export * from './fields.tsx';
|
|
13
13
|
export * from './layout.tsx';
|
|
14
14
|
export * from './keys.ts';
|
|
15
|
+
export * from './clicks.ts';
|
|
15
16
|
export * from './focusables.ts';
|
|
16
17
|
export * from './scroll.tsx';
|
|
17
18
|
export * from './history.tsx';
|
package/src/index.js
CHANGED
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:
|
|
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);
|
|
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);
|
|
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
|
-
/**
|
|
60
|
-
const
|
|
61
|
-
const
|
|
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
|
-
|
|
98
|
+
settleAt(min);
|
|
92
99
|
}
|
|
93
100
|
break;
|
|
94
101
|
case 'End':
|
|
95
102
|
if (max !== undefined && !event.shiftKey) {
|
|
96
103
|
event.preventDefault();
|
|
97
|
-
|
|
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
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
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
|
|
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
|
|
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;
|