@open-artifact/ui 0.0.0-stage → 0.1.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/history.js ADDED
@@ -0,0 +1,160 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ /**
3
+ * The version history panel every editor can mount: versions grouped by day
4
+ * and author, what each changed, a line diff per file, a preview hook, and
5
+ * restoring a whole version or one file (after a confirm).
6
+ *
7
+ * It takes the page's `history` capability (`window.openartifact.history`
8
+ * from `@open-artifact/runtime`) structurally, so this package keeps no
9
+ * dependency on the runtime:
10
+ *
11
+ * ```tsx
12
+ * const history = openartifact.capabilities.history;
13
+ * {history ? <HistoryPanel history={history} viewerId={me.id} onPreview={setPreview} previewing={preview} /> : null}
14
+ * ```
15
+ */
16
+ import { ArrowLeft, Eye, FileMinus, FilePen, FilePlus, History as HistoryIcon, RotateCcw, TriangleAlert, X } from 'lucide-react';
17
+ import { useCallback, useEffect, useMemo, useState } from 'react';
18
+ import { Button, IconButton } from "./button.js";
19
+ import { cn } from "./cn.js";
20
+ import { diffHunks, diffLines, diffStats, groupVersions } from "./history-diff.js";
21
+ import { EmptyState, toast } from "./layout.js";
22
+ import { ConfirmDialog } from "./overlays.js";
23
+ import { ScrollBody } from "./scroll.js";
24
+ export * from "./history-diff.js";
25
+ /* --------------------------------- Helpers --------------------------------- */
26
+ function defaultFormatPath(path) {
27
+ return path.replace(/^(project|db)\//, '');
28
+ }
29
+ function authorName(author, viewerId) {
30
+ if (author.kind === 'system')
31
+ return 'Original';
32
+ if (author.kind === 'agent')
33
+ return author.name || 'Agent';
34
+ if (viewerId && author.id === viewerId)
35
+ return 'You';
36
+ return author.name || 'Someone';
37
+ }
38
+ const timeFormat = new Intl.DateTimeFormat(undefined, { hour: 'numeric', minute: '2-digit' });
39
+ const dateFormat = new Intl.DateTimeFormat(undefined, { weekday: 'short', month: 'short', day: 'numeric' });
40
+ const yearFormat = new Intl.DateTimeFormat(undefined, { year: 'numeric', month: 'short', day: 'numeric' });
41
+ function dayLabel(date) {
42
+ const today = new Date();
43
+ const start = (d) => new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();
44
+ const days = Math.round((start(today) - start(date)) / 86_400_000);
45
+ if (days === 0)
46
+ return 'Today';
47
+ if (days === 1)
48
+ return 'Yesterday';
49
+ return date.getFullYear() === today.getFullYear() ? dateFormat.format(date) : yearFormat.format(date);
50
+ }
51
+ function timeRange(version) {
52
+ const first = timeFormat.format(new Date(version.first));
53
+ const last = timeFormat.format(new Date(version.at));
54
+ return first === last ? last : `${first} – ${last}`;
55
+ }
56
+ const OP_ICON = { added: FilePlus, edited: FilePen, deleted: FileMinus };
57
+ const OP_TONE = { added: 'text-success', edited: 'text-fg-muted', deleted: 'text-danger' };
58
+ function summary(version, formatPath) {
59
+ if (version.restoredFrom !== undefined)
60
+ return `Restored version ${version.restoredFrom}`;
61
+ const files = version.files;
62
+ if (files.length === 1)
63
+ return `${files[0].op === 'edited' ? 'Edited' : files[0].op === 'added' ? 'Added' : 'Deleted'} ${formatPath(files[0].path)}`;
64
+ return `${files.length} changes`;
65
+ }
66
+ /* ------------------------------------ Diff ----------------------------------- */
67
+ function DiffRow({ line }) {
68
+ return (_jsxs("div", { className: cn('flex min-w-max', line.op === '+' && 'bg-success/10 text-fg', line.op === '-' && 'bg-danger/10 text-fg', line.op === ' ' && 'text-fg-muted'), children: [_jsx("span", { className: "w-9 shrink-0 select-none pr-1 text-right text-fg-subtle", children: line.before ?? '' }), _jsx("span", { className: "w-9 shrink-0 select-none pr-1 text-right text-fg-subtle", children: line.after ?? '' }), _jsx("span", { className: cn('w-4 shrink-0 select-none text-center', line.op === '+' ? 'text-success' : line.op === '-' ? 'text-danger' : ''), children: line.op === ' ' ? '' : line.op }), _jsx("span", { className: "whitespace-pre pr-3", children: line.text || ' ' })] }));
69
+ }
70
+ /** A file's line diff, changed parts with three lines of context. */
71
+ export function HistoryDiffView({ diff }) {
72
+ const lines = useMemo(() => (diff.binary || diff.tooLarge ? [] : diffLines(diff.before, diff.after)), [diff]);
73
+ const hunks = useMemo(() => diffHunks(lines), [lines]);
74
+ if (diff.binary)
75
+ return _jsx("p", { className: "p-3 text-xs text-fg-muted", children: "A binary file: no text to compare." });
76
+ if (diff.tooLarge)
77
+ return _jsx("p", { className: "p-3 text-xs text-fg-muted", children: "Too large to compare here." });
78
+ if (!hunks.length)
79
+ return _jsx("p", { className: "p-3 text-xs text-fg-muted", children: "No line changes (only whitespace at the end, or an empty file)." });
80
+ const stats = diffStats(lines);
81
+ return (_jsxs("div", { className: "flex flex-col gap-2 p-2", children: [_jsxs("div", { className: "px-1 text-xs text-fg-muted", children: [_jsxs("span", { className: "text-success", children: ["+", stats.added] }), " ", _jsxs("span", { className: "text-danger", children: ["\u2212", stats.removed] })] }), hunks.map((hunk, index) => (_jsxs("div", { className: "overflow-x-auto rounded-control border border-line font-mono text-[11px] leading-[18px]", children: [hunk.skippedBefore > 0 ? (_jsxs("div", { className: "border-b border-line bg-surface-2 px-2 text-fg-subtle", children: ["\u22EF ", hunk.skippedBefore, " unchanged line", hunk.skippedBefore === 1 ? '' : 's'] })) : null, hunk.lines.map((line, i) => (_jsx(DiffRow, { line: line }, i)))] }, index)))] }));
82
+ }
83
+ /* ----------------------------------- Panel ----------------------------------- */
84
+ /** The version history of the open artifact. */
85
+ export function HistoryPanel({ history, viewerId, onPreview, previewing = null, onRestored, onClose, formatPath = defaultFormatPath, className }) {
86
+ const [listing, setListing] = useState(null);
87
+ const [error, setError] = useState(null);
88
+ const [open, setOpen] = useState(null);
89
+ const [file, setFile] = useState(null);
90
+ const [diff, setDiff] = useState(null);
91
+ const [pending, setPending] = useState(null);
92
+ const [busy, setBusy] = useState(false);
93
+ const reload = useCallback(async () => {
94
+ try {
95
+ setListing(await history.list());
96
+ setError(null);
97
+ }
98
+ catch (e) {
99
+ setError(e instanceof Error ? e.message : String(e));
100
+ }
101
+ }, [history]);
102
+ useEffect(() => {
103
+ void reload();
104
+ return history.onChange(() => void reload());
105
+ }, [history, reload]);
106
+ useEffect(() => {
107
+ if (!file)
108
+ return setDiff(null);
109
+ let live = true;
110
+ setDiff(null);
111
+ history.diff(file.n, file.path).then((d) => live && setDiff(d), (e) => live && toast.add({ title: 'Could not load the change', description: e instanceof Error ? e.message : String(e) }));
112
+ return () => {
113
+ live = false;
114
+ };
115
+ }, [history, file]);
116
+ const days = useMemo(() => groupVersions(listing?.versions ?? []), [listing]);
117
+ const byN = useMemo(() => new Map((listing?.versions ?? []).map((v) => [v.n, v])), [listing]);
118
+ const restore = async ({ n, paths }) => {
119
+ setBusy(true);
120
+ try {
121
+ const result = await history.restore(n, paths);
122
+ if (result.version === null)
123
+ toast.add({ title: 'Nothing to restore', description: `Already the same as version ${n}.` });
124
+ else {
125
+ toast.add({ title: `Restored version ${n}`, description: `${result.changed.length} change${result.changed.length === 1 ? '' : 's'}.` });
126
+ onRestored?.(result, n);
127
+ if (previewing !== null)
128
+ onPreview?.(null);
129
+ }
130
+ await reload();
131
+ }
132
+ catch (e) {
133
+ toast.add({ title: 'Could not restore', description: e instanceof Error ? e.message : String(e) });
134
+ }
135
+ finally {
136
+ setBusy(false);
137
+ }
138
+ };
139
+ const header = (title, back) => (_jsxs("div", { className: "flex h-10 shrink-0 items-center gap-1 border-b border-line px-2", children: [back ? _jsx(IconButton, { label: "Back", size: "sm", icon: _jsx(ArrowLeft, { className: "size-4" }), onClick: back }) : null, _jsx("div", { className: "min-w-0 flex-1 truncate px-1 text-[13px] font-semibold text-fg", children: title }), onClose ? _jsx(IconButton, { label: "Close", size: "sm", icon: _jsx(X, { className: "size-4" }), onClick: onClose }) : null] }));
140
+ const confirm = pending ? (_jsx(ConfirmDialog, { open: true, onOpenChange: (next) => !next && setPending(null), title: pending.paths ? `Restore ${formatPath(pending.paths[0])}?` : `Restore version ${pending.n}?`, description: pending.paths
141
+ ? `It goes back to how version ${pending.n} left it. The current content stays in the history.`
142
+ : `Every file goes back to how version ${pending.n} left it. The current files stay in the history, so this can be undone.`, confirmLabel: "Restore", onConfirm: () => {
143
+ const request = pending;
144
+ setPending(null);
145
+ void restore(request);
146
+ } })) : null;
147
+ /* One file's diff. */
148
+ if (file) {
149
+ const version = byN.get(file.n);
150
+ return (_jsxs("div", { className: cn('flex h-full min-h-0 flex-col bg-surface', className), children: [header(formatPath(file.path), () => setFile(null)), _jsxs("div", { className: "flex shrink-0 items-center gap-2 border-b border-line px-3 py-2 text-xs text-fg-muted", children: [_jsxs("span", { className: "min-w-0 flex-1 truncate", children: ["Version ", file.n, version ? ` · ${authorName(version.author, viewerId)} · ${timeRange(version)}` : ''] }), listing?.canRestore && !version?.current ? (_jsx(Button, { size: "sm", disabled: busy, icon: _jsx(RotateCcw, { className: "size-3.5" }), onClick: () => setPending({ n: file.n, paths: [file.path] }), children: "Restore file" })) : null] }), _jsx(ScrollBody, { className: "min-h-0 flex-1 overflow-auto", label: "Changes", children: diff ? _jsx(HistoryDiffView, { diff: diff }) : _jsx("p", { className: "p-3 text-xs text-fg-subtle", children: "Loading\u2026" }) }), confirm] }));
151
+ }
152
+ return (_jsxs("div", { className: cn('flex h-full min-h-0 flex-col bg-surface', className), children: [header('Version history'), listing?.notices.length ? (_jsx("div", { className: "flex shrink-0 flex-col gap-1 border-b border-line p-2", children: listing.notices.map((notice) => (_jsxs("div", { className: "flex gap-2 rounded-control bg-surface-2 p-2 text-xs text-fg", children: [_jsx(TriangleAlert, { className: "mt-0.5 size-3.5 shrink-0 text-warning" }), _jsxs("div", { className: "flex min-w-0 flex-1 flex-col gap-1.5", children: [_jsxs("div", { children: [_jsx("span", { className: "font-medium", children: authorName(notice.author, viewerId) }), " changed", ' ', _jsx("span", { className: "font-medium", children: formatPath(notice.path) }), " right after you, undoing part of your change."] }), _jsxs("div", { className: "flex gap-1", children: [listing.canRestore ? (_jsx(Button, { size: "sm", variant: "primary", disabled: busy, onClick: () => void restore({ n: notice.lost.n, paths: [notice.path] }), children: "Bring mine back" })) : null, _jsx(Button, { size: "sm", variant: "ghost", onClick: () => setFile({ n: notice.n, path: notice.path }), children: "See change" }), _jsx(Button, { size: "sm", variant: "ghost", onClick: () => void history.dismissNotice(notice.id).then(reload), children: "Dismiss" })] })] })] }, notice.id))) })) : null, _jsx(ScrollBody, { className: "min-h-0 flex-1 overflow-auto", label: "Versions", children: error ? (_jsx(EmptyState, { title: "History unavailable", children: error })) : !listing ? (_jsx("p", { className: "p-3 text-xs text-fg-subtle", children: "Loading\u2026" })) : !listing.versions.length ? (_jsx(EmptyState, { icon: _jsx(HistoryIcon, { className: "size-6" }), title: "No versions yet", children: "Changes show up here as they are saved." })) : (days.map((day) => (_jsxs("section", { className: "pb-1", children: [_jsx("h3", { className: "sticky top-0 z-[1] bg-surface px-3 pb-1 pt-3 text-[11px] font-semibold uppercase tracking-wide text-fg-subtle", children: dayLabel(day.date) }), day.runs.map((run) => (_jsxs("div", { className: "mx-2 mb-1", children: [_jsx("div", { className: "px-1 pb-0.5 pt-1 text-xs font-medium text-fg", children: authorName(run.author, viewerId) }), run.versions.map((version) => {
153
+ const expanded = open === version.n;
154
+ const isPreview = previewing === version.n;
155
+ return (_jsxs("div", { className: cn('rounded-control', expanded && 'bg-surface-2', isPreview && 'ring-1 ring-accent'), children: [_jsxs("button", { type: "button", "aria-expanded": expanded, className: "flex w-full min-w-0 items-center gap-2 rounded-control px-2 py-1.5 text-left text-xs hover:bg-hover", onClick: () => setOpen(expanded ? null : version.n), children: [_jsx("span", { className: "w-12 shrink-0 text-fg-subtle", children: timeFormat.format(new Date(version.at)) }), _jsx("span", { className: "min-w-0 flex-1 truncate text-fg", children: summary(version, formatPath) }), version.overwrote?.length ? _jsx(TriangleAlert, { className: "size-3 shrink-0 text-warning", "aria-label": "Undid a recent change" }) : null, version.current ? _jsx("span", { className: "shrink-0 rounded bg-accent-soft px-1.5 text-[10px] font-medium text-accent", children: "Current" }) : null, isPreview ? _jsx("span", { className: "shrink-0 text-[10px] font-medium text-accent", children: "Previewing" }) : null] }), expanded ? (_jsxs("div", { className: "flex flex-col gap-1 px-2 pb-2", children: [_jsxs("div", { className: "text-[11px] text-fg-subtle", children: ["Version ", version.n, " \u00B7 ", timeRange(version)] }), _jsx("ul", { className: "flex flex-col", children: version.files.map((change) => {
156
+ const Icon = OP_ICON[change.op];
157
+ return (_jsxs("li", { className: "group flex items-center gap-1", children: [_jsxs("button", { type: "button", className: "flex min-w-0 flex-1 items-center gap-1.5 rounded-control px-1 py-1 text-left text-xs hover:bg-hover", onClick: () => setFile({ n: version.n, path: change.path }), title: "Show what changed", children: [_jsx(Icon, { className: cn('size-3.5 shrink-0', OP_TONE[change.op]) }), _jsx("span", { className: "min-w-0 flex-1 truncate text-fg", children: formatPath(change.path) }), _jsx("span", { className: "shrink-0 text-[10px] text-fg-subtle", children: change.op })] }), listing.canRestore && !version.current ? (_jsx(IconButton, { label: `Restore ${formatPath(change.path)} from this version`, size: "sm", className: "opacity-0 group-hover:opacity-100 focus-visible:opacity-100", icon: _jsx(RotateCcw, { className: "size-3.5" }), disabled: busy, onClick: () => setPending({ n: version.n, paths: [change.path] }) })) : null] }, change.path));
158
+ }) }), version.overwrote?.length ? (_jsxs("div", { className: "text-[11px] text-warning", children: ["Undid part of", ' ', version.overwrote.map((o) => `${authorName(o.author, viewerId)}’s change to ${formatPath(o.path)}`).join(', '), "."] })) : null, _jsxs("div", { className: "flex flex-wrap gap-1 pt-1", children: [onPreview && !version.current ? (_jsx(Button, { size: "sm", icon: _jsx(Eye, { className: "size-3.5" }), onClick: () => onPreview(isPreview ? null : version.n), children: isPreview ? 'Stop preview' : 'Preview' })) : null, listing.canRestore && !version.current ? (_jsx(Button, { size: "sm", disabled: busy, icon: _jsx(RotateCcw, { className: "size-3.5" }), onClick: () => setPending({ n: version.n }), children: "Restore this version" })) : null] })] })) : null] }, version.n));
159
+ })] }, run.versions[0].n)))] }, day.key)))) }), confirm] }));
160
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,25 @@
1
+ /**
2
+ * `@open-artifact/ui`: the editors' shared UI kit.
3
+ *
4
+ * Unstyled, accessible primitives from Base UI, styled with Tailwind CSS
5
+ * against the semantic tokens in `styles.css`; icons come from lucide.
6
+ */
7
+ export * from './cn.ts';
8
+ export * from './button.tsx';
9
+ export * from './tooltip.tsx';
10
+ export * from './menu.tsx';
11
+ export * from './overlays.tsx';
12
+ export * from './fields.tsx';
13
+ export * from './layout.tsx';
14
+ export * from './keys.ts';
15
+ export * from './focusables.ts';
16
+ export * from './scroll.tsx';
17
+ export * from './history.tsx';
18
+ export * from './color.ts';
19
+ export * from './color-picker.tsx';
20
+ export * from './effects.ts';
21
+ export * from './effect-editors.tsx';
22
+ export * from './numbers.ts';
23
+ export * from './scrub-number-field.tsx';
24
+ export * from './fonts.ts';
25
+ export * from './font-picker.tsx';
package/src/index.js ADDED
@@ -0,0 +1,25 @@
1
+ /**
2
+ * `@open-artifact/ui`: the editors' shared UI kit.
3
+ *
4
+ * Unstyled, accessible primitives from Base UI, styled with Tailwind CSS
5
+ * against the semantic tokens in `styles.css`; icons come from lucide.
6
+ */
7
+ export * from "./cn.js";
8
+ export * from "./button.js";
9
+ export * from "./tooltip.js";
10
+ export * from "./menu.js";
11
+ export * from "./overlays.js";
12
+ export * from "./fields.js";
13
+ export * from "./layout.js";
14
+ export * from "./keys.js";
15
+ export * from "./focusables.js";
16
+ export * from "./scroll.js";
17
+ export * from "./history.js";
18
+ export * from "./color.js";
19
+ export * from "./color-picker.js";
20
+ export * from "./effects.js";
21
+ export * from "./effect-editors.js";
22
+ export * from "./numbers.js";
23
+ export * from "./scrub-number-field.js";
24
+ export * from "./fonts.js";
25
+ export * from "./font-picker.js";
package/src/keys.d.ts ADDED
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Keyboard guards shared by the kit's controls.
3
+ *
4
+ * A key held down auto-repeats: without a guard, holding Enter on a button,
5
+ * a menu row that keeps its menu open or a switch presses it again and again,
6
+ * and a press that moves focus (closing a toast, opening a dialog) lands the
7
+ * repeats on whatever gets focus next.
8
+ */
9
+ /** The fields of a keyboard event the guards read. */
10
+ export interface KeyLike {
11
+ key: string;
12
+ repeat: boolean;
13
+ }
14
+ /** True for an auto-repeated Enter or Space. */
15
+ export declare function isRepeatedActivation(event: KeyLike): boolean;
16
+ /** A keydown event as the guards see it. */
17
+ export type GuardedKeyEvent = KeyLike & {
18
+ target: unknown;
19
+ currentTarget: unknown;
20
+ preventDefault(): void;
21
+ };
22
+ /**
23
+ * A keydown handler that keeps a held Enter or Space from pressing the
24
+ * focused control again: the repeats have their default (the native click,
25
+ * or Base UI's activation) prevented.
26
+ */
27
+ export declare function preventRepeatedActivation(event: GuardedKeyEvent): void;
28
+ /**
29
+ * Wraps a keydown handler so a held Enter or Space presses the control once:
30
+ * the repeats have their default (the native click, or Base UI's activation)
31
+ * prevented. The wrapped handler still runs (and sees `defaultPrevented`).
32
+ */
33
+ export declare function withRepeatGuard<E extends GuardedKeyEvent>(handler?: (event: E) => void): (event: E) => void;
34
+ /** The parts of a window {@link guardHeldActivation} listens on. */
35
+ export interface KeyGuardWindow {
36
+ addEventListener(type: 'keydown' | 'keyup', listener: (event: KeyGuardEvent) => void, capture: boolean): void;
37
+ removeEventListener(type: 'keydown' | 'keyup', listener: (event: KeyGuardEvent) => void, capture: boolean): void;
38
+ setTimeout(callback: () => void, ms: number): number;
39
+ clearTimeout(id: number): void;
40
+ }
41
+ /** The parts of a keyboard event {@link guardHeldActivation} reads. */
42
+ export interface KeyGuardEvent extends KeyLike {
43
+ type: string;
44
+ target: unknown;
45
+ preventDefault(): void;
46
+ stopImmediatePropagation(): void;
47
+ }
48
+ /** How long the guard stays after the first key is released. */
49
+ export declare const HELD_KEY_SETTLE_MS = 200;
50
+ /** The guard never lasts longer than this. */
51
+ export declare const HELD_KEY_GUARD_MAX_MS = 2000;
52
+ /**
53
+ * After an Enter or Space press that closes something (a toast's close
54
+ * button), keeps the activation keys from pressing what gets focus next:
55
+ * until the pressed key is released, plus a short settle, Enter and Space
56
+ * keydowns outside `isInside` are swallowed at the window, and so are Space
57
+ * keyups (a native button acts on Space's keyup). Lasts at most 2 s.
58
+ * Returns a function that ends the guard early.
59
+ */
60
+ export declare function guardHeldActivation(win: KeyGuardWindow, firstKey: string, isInside: (target: unknown) => boolean): () => void;
package/src/keys.js ADDED
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Keyboard guards shared by the kit's controls.
3
+ *
4
+ * A key held down auto-repeats: without a guard, holding Enter on a button,
5
+ * a menu row that keeps its menu open or a switch presses it again and again,
6
+ * and a press that moves focus (closing a toast, opening a dialog) lands the
7
+ * repeats on whatever gets focus next.
8
+ */
9
+ /** True for an auto-repeated Enter or Space. */
10
+ export function isRepeatedActivation(event) {
11
+ return event.repeat && (event.key === 'Enter' || event.key === ' ');
12
+ }
13
+ /**
14
+ * A keydown handler that keeps a held Enter or Space from pressing the
15
+ * focused control again: the repeats have their default (the native click,
16
+ * or Base UI's activation) prevented.
17
+ */
18
+ export function preventRepeatedActivation(event) {
19
+ if (isRepeatedActivation(event) && event.target === event.currentTarget)
20
+ event.preventDefault();
21
+ }
22
+ /**
23
+ * Wraps a keydown handler so a held Enter or Space presses the control once:
24
+ * the repeats have their default (the native click, or Base UI's activation)
25
+ * prevented. The wrapped handler still runs (and sees `defaultPrevented`).
26
+ */
27
+ export function withRepeatGuard(handler) {
28
+ if (!handler)
29
+ return preventRepeatedActivation;
30
+ return (event) => {
31
+ preventRepeatedActivation(event);
32
+ handler(event);
33
+ };
34
+ }
35
+ /** How long the guard stays after the first key is released. */
36
+ export const HELD_KEY_SETTLE_MS = 200;
37
+ /** The guard never lasts longer than this. */
38
+ export const HELD_KEY_GUARD_MAX_MS = 2000;
39
+ /**
40
+ * After an Enter or Space press that closes something (a toast's close
41
+ * button), keeps the activation keys from pressing what gets focus next:
42
+ * until the pressed key is released, plus a short settle, Enter and Space
43
+ * keydowns outside `isInside` are swallowed at the window, and so are Space
44
+ * keyups (a native button acts on Space's keyup). Lasts at most 2 s.
45
+ * Returns a function that ends the guard early.
46
+ */
47
+ export function guardHeldActivation(win, firstKey, isInside) {
48
+ let settling = null;
49
+ let ended = false;
50
+ const end = () => {
51
+ if (ended)
52
+ return;
53
+ ended = true;
54
+ win.removeEventListener('keydown', onKey, true);
55
+ win.removeEventListener('keyup', onKey, true);
56
+ win.clearTimeout(limit);
57
+ if (settling !== null)
58
+ win.clearTimeout(settling);
59
+ };
60
+ const onKey = (event) => {
61
+ const activation = event.key === 'Enter' || event.key === ' ';
62
+ if (event.type === 'keyup') {
63
+ if (event.key === ' ' && !isInside(event.target))
64
+ event.preventDefault();
65
+ if (event.key === firstKey && settling === null)
66
+ settling = win.setTimeout(end, HELD_KEY_SETTLE_MS);
67
+ return;
68
+ }
69
+ if (activation && !isInside(event.target)) {
70
+ event.preventDefault();
71
+ event.stopImmediatePropagation();
72
+ }
73
+ };
74
+ const limit = win.setTimeout(end, HELD_KEY_GUARD_MAX_MS);
75
+ win.addEventListener('keydown', onKey, true);
76
+ win.addEventListener('keyup', onKey, true);
77
+ return end;
78
+ }
@@ -0,0 +1,55 @@
1
+ import type { HTMLAttributes, ReactNode } from 'react';
2
+ /** One tab of {@link Tabs}. */
3
+ export interface TabItem<T extends string> {
4
+ value: T;
5
+ label: ReactNode;
6
+ content: ReactNode;
7
+ }
8
+ /** Props of {@link Tabs}. */
9
+ export interface TabsProps<T extends string> {
10
+ value: T;
11
+ onChange: (value: T) => void;
12
+ items: TabItem<T>[];
13
+ className?: string;
14
+ /** Extra controls shown at the end of the tab bar. */
15
+ trailing?: ReactNode;
16
+ }
17
+ /** 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;
19
+ /** Props of {@link Section}. */
20
+ export interface SectionProps {
21
+ title: ReactNode;
22
+ children: ReactNode;
23
+ /** Controls at the right of the heading (add, reset…). */
24
+ actions?: ReactNode;
25
+ /** Collapsed state is uncontrolled; start open unless `defaultOpen` is false. */
26
+ defaultOpen?: boolean;
27
+ }
28
+ /** A collapsible group of inspector rows. */
29
+ export declare function Section({ title, children, actions, defaultOpen }: SectionProps): import("react/jsx-runtime").JSX.Element;
30
+ /** A label + control row inside a {@link Section}. */
31
+ export declare function Row({ label, children, className }: {
32
+ label?: ReactNode;
33
+ children: ReactNode;
34
+ className?: string;
35
+ }): import("react/jsx-runtime").JSX.Element;
36
+ /** A floating bar (toolbars, zoom controls). */
37
+ export declare function Bar({ className, ...rest }: HTMLAttributes<HTMLDivElement>): import("react/jsx-runtime").JSX.Element;
38
+ /** A thin vertical divider for bars. */
39
+ export declare function BarDivider(): import("react/jsx-runtime").JSX.Element;
40
+ /** A keyboard key hint. */
41
+ export declare function Kbd({ children }: {
42
+ children: ReactNode;
43
+ }): import("react/jsx-runtime").JSX.Element;
44
+ /** A centered empty or loading state. */
45
+ export declare function EmptyState({ icon, title, children }: {
46
+ icon?: ReactNode;
47
+ title: ReactNode;
48
+ children?: ReactNode;
49
+ }): import("react/jsx-runtime").JSX.Element;
50
+ /** The app-wide toast manager: `toast.add({ title, description })`. */
51
+ export declare const toast: import("@base-ui/react").ToastManager<any>;
52
+ /** Mount once near the app root to show toasts. */
53
+ export declare function Toaster({ children }: {
54
+ children?: ReactNode;
55
+ }): import("react/jsx-runtime").JSX.Element;
package/src/layout.js ADDED
@@ -0,0 +1,64 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ /**
3
+ * Layout pieces: tabs, inspector sections and rows, the toolbar shell,
4
+ * keyboard hints, toasts and a few small helpers.
5
+ */
6
+ import { Collapsible } from '@base-ui/react/collapsible';
7
+ import { Tabs as BaseTabs } from '@base-ui/react/tabs';
8
+ import { Toast } from '@base-ui/react/toast';
9
+ import { ChevronDown, X } from 'lucide-react';
10
+ import { cn } from "./cn.js";
11
+ import { guardHeldActivation } from "./keys.js";
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)))] }));
15
+ }
16
+ /** A collapsible group of inspector rows. */
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 })] }));
19
+ }
20
+ /** A label + control row inside a {@link Section}. */
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 })] }));
23
+ }
24
+ /** A floating bar (toolbars, zoom controls). */
25
+ export function Bar({ className, ...rest }) {
26
+ return (_jsx("div", { className: cn('flex items-center gap-0.5 rounded-xl bg-surface p-1 shadow-popup', className), ...rest }));
27
+ }
28
+ /** A thin vertical divider for bars. */
29
+ export function BarDivider() {
30
+ return _jsx("div", { className: "mx-1 h-5 w-px bg-line", "aria-hidden": "true" });
31
+ }
32
+ /** A keyboard key hint. */
33
+ export function Kbd({ children }) {
34
+ return _jsx("kbd", { className: "rounded border border-line bg-surface-2 px-1 font-mono text-[11px] text-fg-muted", children: children });
35
+ }
36
+ /** A centered empty or loading state. */
37
+ export function EmptyState({ icon, title, children }) {
38
+ return (_jsxs("div", { className: "flex h-full flex-col items-center justify-center gap-2 p-8 text-center text-fg-muted", children: [icon ? _jsx("div", { className: "text-fg-subtle", children: icon }) : null, _jsx("div", { className: "text-[15px] font-semibold text-fg", children: title }), children ? _jsx("div", { className: "max-w-sm", children: children }) : null] }));
39
+ }
40
+ /* --------------------------------- Toasts --------------------------------- */
41
+ /** The app-wide toast manager: `toast.add({ title, description })`. */
42
+ export const toast = Toast.createToastManager();
43
+ /**
44
+ * Enter or Space on a toast's close button closes it and focus moves on:
45
+ * until the key is released, Enter and Space must not press whatever gets
46
+ * focus next.
47
+ */
48
+ function guardToastClose(event) {
49
+ if (event.repeat || (event.key !== 'Enter' && event.key !== ' '))
50
+ return;
51
+ const toastElement = event.currentTarget.closest('[data-toast]') ?? event.currentTarget;
52
+ const view = toastElement.ownerDocument.defaultView;
53
+ if (!view)
54
+ return;
55
+ guardHeldActivation(view, event.key, (target) => target instanceof view.Node && toastElement.contains(target));
56
+ }
57
+ function ToastList() {
58
+ const { toasts } = Toast.useToastManager();
59
+ return toasts.map((item) => (_jsxs(Toast.Root, { toast: item, "data-toast": "", className: "pointer-events-auto flex w-80 items-start gap-3 rounded-lg bg-surface p-3 text-fg shadow-popup transition-[opacity,transform] data-[starting-style]:translate-y-2 data-[starting-style]:opacity-0 data-[ending-style]:opacity-0", children: [_jsxs(Toast.Content, { className: "flex min-w-0 flex-1 flex-col gap-0.5", children: [_jsx(Toast.Title, { className: "text-[13px] font-semibold" }), _jsx(Toast.Description, { className: "text-xs text-fg-muted" })] }), _jsx(Toast.Close, { "aria-label": "Dismiss", onKeyDown: guardToastClose, className: "rounded p-0.5 text-fg-muted hover:bg-hover", children: _jsx(X, { className: "size-3.5" }) })] }, item.id)));
60
+ }
61
+ /** Mount once near the app root to show toasts. */
62
+ export function Toaster({ children }) {
63
+ return (_jsxs(Toast.Provider, { toastManager: toast, timeout: 4000, children: [children, _jsx(Toast.Portal, { children: _jsx(Toast.Viewport, { className: "pointer-events-none fixed bottom-4 right-4 z-[1100] flex flex-col gap-2", children: _jsx(ToastList, {}) }) })] }));
64
+ }
package/src/menu.d.ts ADDED
@@ -0,0 +1,50 @@
1
+ import type { ReactElement, ReactNode } from 'react';
2
+ /** Shared popup look of menus, popovers and selects. */
3
+ export declare const POPUP_CLASS = "rounded-lg bg-surface p-1 text-[13px] text-fg shadow-popup outline-none origin-[var(--transform-origin)] transition-[opacity,transform] duration-100 data-[starting-style]:opacity-0 data-[starting-style]:scale-95 data-[ending-style]:opacity-0";
4
+ /** Props of {@link Menu}. */
5
+ export interface MenuProps {
6
+ /** The element that opens the menu (rendered via Base UI's `render`). */
7
+ trigger: ReactElement<Record<string, unknown>>;
8
+ children: ReactNode;
9
+ side?: 'top' | 'bottom' | 'left' | 'right';
10
+ align?: 'start' | 'center' | 'end';
11
+ open?: boolean;
12
+ onOpenChange?: (open: boolean) => void;
13
+ }
14
+ /**
15
+ * A dropdown menu. Base UI gives it keyboard navigation and typeahead (a
16
+ * Space typed mid-search is part of the search). A held Enter or Space
17
+ * presses the trigger and each row once.
18
+ */
19
+ export declare function Menu({ trigger, children, side, align, open, onOpenChange }: MenuProps): import("react/jsx-runtime").JSX.Element;
20
+ /** Props of {@link MenuItem}. */
21
+ export interface MenuItemProps {
22
+ children: ReactNode;
23
+ onSelect?: () => void;
24
+ icon?: ReactNode;
25
+ shortcut?: string;
26
+ disabled?: boolean;
27
+ danger?: boolean;
28
+ }
29
+ /** One action row. */
30
+ export declare function MenuItem({ children, onSelect, icon, shortcut, disabled, danger }: MenuItemProps): import("react/jsx-runtime").JSX.Element;
31
+ /** A toggle row with a check mark. */
32
+ export declare function MenuCheckboxItem({ children, checked, onCheckedChange, closeOnClick, }: {
33
+ children: ReactNode;
34
+ checked: boolean;
35
+ onCheckedChange: (checked: boolean) => void;
36
+ /** Close the menu on click (for a pick among options rather than a toggle). */
37
+ closeOnClick?: boolean;
38
+ }): import("react/jsx-runtime").JSX.Element;
39
+ /** A thin rule between groups of items. */
40
+ export declare function MenuSeparator(): import("react/jsx-runtime").JSX.Element;
41
+ /** A non-interactive heading or note inside a menu. */
42
+ export declare function MenuLabel({ children }: {
43
+ children: ReactNode;
44
+ }): import("react/jsx-runtime").JSX.Element;
45
+ /** A nested menu opened from a row. */
46
+ export declare function MenuSubmenu({ label, icon, children }: {
47
+ label: ReactNode;
48
+ icon?: ReactNode;
49
+ children: ReactNode;
50
+ }): import("react/jsx-runtime").JSX.Element;
package/src/menu.js ADDED
@@ -0,0 +1,36 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { Menu as BaseMenu } from '@base-ui/react/menu';
3
+ import { Check, ChevronRight } from 'lucide-react';
4
+ import { cn } from "./cn.js";
5
+ import { preventRepeatedActivation } from "./keys.js";
6
+ /** Shared popup look of menus, popovers and selects. */
7
+ export const POPUP_CLASS = 'rounded-lg bg-surface p-1 text-[13px] text-fg shadow-popup outline-none origin-[var(--transform-origin)] transition-[opacity,transform] duration-100 data-[starting-style]:opacity-0 data-[starting-style]:scale-95 data-[ending-style]:opacity-0';
8
+ const ITEM_CLASS = 'flex h-7 min-w-40 cursor-default select-none items-center gap-2 rounded-md px-2 outline-none data-[highlighted]:bg-hover data-[disabled]:opacity-40';
9
+ /**
10
+ * A dropdown menu. Base UI gives it keyboard navigation and typeahead (a
11
+ * Space typed mid-search is part of the search). A held Enter or Space
12
+ * presses the trigger and each row once.
13
+ */
14
+ export function Menu({ trigger, children, side = 'bottom', align = 'start', open, onOpenChange }) {
15
+ 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
+ /** One action row. */
18
+ 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
+ }
21
+ /** A toggle row with a check mark. */
22
+ export function MenuCheckboxItem({ children, checked, onCheckedChange, closeOnClick = false, }) {
23
+ return (_jsxs(BaseMenu.CheckboxItem, { className: ITEM_CLASS, checked: checked, closeOnClick: closeOnClick, onCheckedChange: (next) => onCheckedChange(next), onKeyDown: preventRepeatedActivation, children: [_jsx("span", { className: "flex size-4 items-center justify-center", children: _jsx(BaseMenu.CheckboxItemIndicator, { children: _jsx(Check, { className: "size-3.5" }) }) }), _jsx("span", { className: "flex-1", children: children })] }));
24
+ }
25
+ /** A thin rule between groups of items. */
26
+ export function MenuSeparator() {
27
+ return _jsx(BaseMenu.Separator, { className: "mx-1 my-1 h-px bg-line" });
28
+ }
29
+ /** A non-interactive heading or note inside a menu. */
30
+ export function MenuLabel({ children }) {
31
+ return _jsx("div", { className: "px-2 py-1 text-xs text-fg-subtle", children: children });
32
+ }
33
+ /** A nested menu opened from a row. */
34
+ export function MenuSubmenu({ label, icon, children }) {
35
+ return (_jsxs(BaseMenu.SubmenuRoot, { children: [_jsxs(BaseMenu.SubmenuTrigger, { className: ITEM_CLASS, onKeyDown: preventRepeatedActivation, children: [_jsx("span", { className: "flex size-4 items-center justify-center text-fg-muted", children: icon }), _jsx("span", { className: "flex-1", children: label }), _jsx(ChevronRight, { className: "size-3.5 text-fg-subtle" })] }), _jsx(BaseMenu.Portal, { children: _jsx(BaseMenu.Positioner, { sideOffset: 4, className: "z-[1000]", children: _jsx(BaseMenu.Popup, { className: POPUP_CLASS, children: children }) }) })] }));
36
+ }
@@ -0,0 +1,24 @@
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
+ /** A typed number and the unit typed after it, if any. */
6
+ export interface TypedNumber {
7
+ value: number;
8
+ /** The unit written after the number (`px`, `%`…), or undefined. */
9
+ unit?: string;
10
+ }
11
+ /**
12
+ * Reads typed text: `12`, `12px`, `-4.5`, `.5`, or arithmetic with `+ - * /`
13
+ * and parentheses (`10 + 4`, `100/3`, `(8+2)*2px`). A unit may follow the
14
+ * whole expression or its first number. Null when the text is not that.
15
+ */
16
+ export declare function evaluateNumberInput(text: string): TypedNumber | null;
17
+ /** Decimals needed to show multiples of `step` (0.25 → 2). */
18
+ export declare function stepDecimals(step: number): number;
19
+ /** Rounds `value` to `decimals` places, without `-0`. */
20
+ export declare function roundTo(value: number, decimals: number): number;
21
+ /** Clamps into `[min, max]` (either bound optional). */
22
+ export declare function clampNumber(value: number, min?: number, max?: number): number;
23
+ /** Formats a value for a number field: rounded, no trailing zeros. */
24
+ export declare function formatNumber(value: number, decimals: number): string;