tuxevil-rotator 3.10.0 → 4.0.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 (53) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/README.md +22 -12
  3. package/package.json +8 -4
  4. package/src/admin-auth.ts +233 -3
  5. package/src/dashboard-app.ts +257 -0
  6. package/src/dashboard-live.ts +654 -0
  7. package/src/dashboard-types.ts +192 -0
  8. package/src/dashboard.ts +165 -732
  9. package/src/db-store.ts +43 -0
  10. package/src/exposure.ts +21 -1
  11. package/src/providers/opencode-zen/catalog.ts +2 -0
  12. package/src/providers/opencode-zen/forward.ts +18 -15
  13. package/src/providers/opencode-zen/login.ts +2 -1
  14. package/src/providers/opencode-zen/quota.ts +2 -1
  15. package/src/proxy.ts +71 -25
  16. package/src/rotator.ts +30 -30
  17. package/src/settings-repository.ts +7 -0
  18. package/src/types.ts +2 -0
  19. package/src/web/app.tsx +765 -0
  20. package/src/web/components/charts.tsx +338 -0
  21. package/src/web/components/command.tsx +279 -0
  22. package/src/web/components/icons.tsx +357 -0
  23. package/src/web/components/overlays.tsx +432 -0
  24. package/src/web/components/ui.tsx +421 -0
  25. package/src/web/lib/accounts.ts +109 -0
  26. package/src/web/lib/attention.ts +219 -0
  27. package/src/web/lib/colors.ts +103 -0
  28. package/src/web/lib/format.ts +113 -0
  29. package/src/web/lib/mask.ts +92 -0
  30. package/src/web/lib/pools.ts +199 -0
  31. package/src/web/lib/status.ts +242 -0
  32. package/src/web/lib/usage.ts +296 -0
  33. package/src/web/main.tsx +16 -0
  34. package/src/web/nav.ts +28 -0
  35. package/src/web/pages/AccountDetail.tsx +346 -0
  36. package/src/web/pages/Accounts.tsx +581 -0
  37. package/src/web/pages/Keys.tsx +431 -0
  38. package/src/web/pages/Overview.tsx +600 -0
  39. package/src/web/pages/Requests.tsx +644 -0
  40. package/src/web/pages/Settings.tsx +546 -0
  41. package/src/web/pages/Usage.tsx +346 -0
  42. package/src/web/pages/shared.ts +36 -0
  43. package/src/web/state/actions.ts +211 -0
  44. package/src/web/state/api.ts +273 -0
  45. package/src/web/state/prefs.ts +19 -0
  46. package/src/web/state/router.ts +92 -0
  47. package/src/web/state/store.ts +266 -0
  48. package/src/web/styles/app.css +5043 -0
  49. package/src/web/tsconfig.json +14 -0
  50. package/src/static/dashboard-keys.js +0 -535
  51. package/src/static/dashboard-logs.js +0 -800
  52. package/src/static/dashboard.css +0 -2741
  53. package/src/static/dashboard.js +0 -3334
@@ -0,0 +1,338 @@
1
+ // Hand-rolled SVG charts: a traffic sparkline, the stacked token chart and
2
+ // the activity heatmap. No chart library; everything follows the theme.
3
+
4
+ import { Fragment, type JSX } from "preact";
5
+ import { useLayoutEffect, useRef, useState } from "preact/hooks";
6
+ import { formatClock, formatCompact, formatCount } from "../lib/format.js";
7
+ import { modelColor } from "../lib/colors.js";
8
+ import {
9
+ barTitle,
10
+ formatAxisTokens,
11
+ niceAxis,
12
+ tickIndices,
13
+ tickLabel,
14
+ type ChartBar,
15
+ type RangeSpec,
16
+ } from "../lib/usage.js";
17
+
18
+ function useWidth<T extends HTMLElement>(fallback: number): [{ current: T | null }, number] {
19
+ const ref = useRef<T>(null);
20
+ const [width, setWidth] = useState(fallback);
21
+ useLayoutEffect(() => {
22
+ const el = ref.current;
23
+ if (!el) return;
24
+ setWidth(Math.floor(el.clientWidth) || fallback);
25
+ if (typeof ResizeObserver !== "function") return;
26
+ const observer = new ResizeObserver((entries) => {
27
+ const next = Math.floor(entries[0].contentRect.width);
28
+ if (next > 0) setWidth(next);
29
+ });
30
+ observer.observe(el);
31
+ return () => observer.disconnect();
32
+ }, []);
33
+ return [ref, width];
34
+ }
35
+
36
+ /**
37
+ * Minute-level trend with a hover cursor; the last point carries an end
38
+ * marker. With `onHover` the caller shows the readout (in a header, say)
39
+ * instead of the floating tip.
40
+ */
41
+ export function Sparkline({
42
+ values,
43
+ times,
44
+ unit,
45
+ label,
46
+ height = 44,
47
+ onHover,
48
+ }: {
49
+ values: number[];
50
+ /** Start of each point, for the hover readout. */
51
+ times?: number[];
52
+ unit: string;
53
+ label: string;
54
+ height?: number;
55
+ onHover?: (index: number | null) => void;
56
+ }): JSX.Element {
57
+ const [hover, setHoverState] = useState<number | null>(null);
58
+ const setHover = (index: number | null) => {
59
+ if (index === hover) return;
60
+ setHoverState(index);
61
+ onHover?.(index);
62
+ };
63
+ const max = Math.max(1, ...values);
64
+ const step = values.length > 1 ? 100 / (values.length - 1) : 100;
65
+ const yOf = (v: number) => height - 3 - (v / max) * (height - 8);
66
+ const points = values.map((v, i) => [i * step, yOf(v)] as const);
67
+ const line = points.map(([x, y], i) => `${i === 0 ? "M" : "L"}${x.toFixed(2)},${y.toFixed(2)}`).join(" ");
68
+ const area = `${line} L100,${height} L0,${height} Z`;
69
+ const marked = hover ?? (values.length > 0 ? values.length - 1 : null);
70
+ const markX = marked === null ? 0 : marked * step;
71
+ const markY = marked === null ? 0 : (yOf(values[marked]) / height) * 100;
72
+ return (
73
+ <div
74
+ class={`sparkline-wrap${hover !== null ? " is-hover" : ""}`}
75
+ onPointerMove={(event) => {
76
+ if (values.length === 0) return;
77
+ const rect = (event.currentTarget as HTMLElement).getBoundingClientRect();
78
+ const ratio = Math.min(1, Math.max(0, (event.clientX - rect.left) / rect.width));
79
+ setHover(Math.round(ratio * (values.length - 1)));
80
+ }}
81
+ onPointerLeave={() => setHover(null)}
82
+ >
83
+ <svg class="sparkline" viewBox={`0 0 100 ${height}`} preserveAspectRatio="none" role="img" aria-label={label}>
84
+ <path class="sparkline-area" d={area} />
85
+ <path class="sparkline-line" d={line} vector-effect="non-scaling-stroke" />
86
+ </svg>
87
+ {marked !== null && (
88
+ <>
89
+ {hover !== null && <span class="sparkline-cursor" style={{ left: `${markX}%` }} />}
90
+ <span class="sparkline-dot" style={{ left: `${markX}%`, top: `${markY}%` }} />
91
+ </>
92
+ )}
93
+ {hover !== null && !onHover && (
94
+ <span class={`sparkline-tip${markX > 55 ? " is-left" : ""}`} style={{ left: `${markX}%` }} role="tooltip">
95
+ <strong class="num">{formatCount(values[hover])}</strong> {unit}
96
+ {times?.[hover] !== undefined && <span class="sparkline-tip-time"> · {formatClock(times[hover])}</span>}
97
+ </span>
98
+ )}
99
+ </div>
100
+ );
101
+ }
102
+
103
+ /** A bar's top segment: 4px rounded data-end, square at the baseline. */
104
+ function roundedTop(x: number, y: number, w: number, h: number, r: number): string {
105
+ const radius = Math.max(0, Math.min(r, w / 2, h));
106
+ return `M${x},${y + h}V${y + radius}A${radius},${radius} 0 0 1 ${x + radius},${y}H${x + w - radius}A${radius},${radius} 0 0 1 ${x + w},${y + radius}V${y + h}Z`;
107
+ }
108
+
109
+ function stackSegments(bar: ChartBar, models: string[], axisMax: number, plotHeight: number): Array<{ model: string; h: number }> {
110
+ const out: Array<{ model: string; h: number }> = [];
111
+ for (const model of models) {
112
+ const t = bar.byModel[model];
113
+ if (!t) continue;
114
+ const h = ((t.inputTokens + t.outputTokens) / axisMax) * plotHeight;
115
+ if (h > 0) out.push({ model, h });
116
+ }
117
+ return out;
118
+ }
119
+
120
+ export function TokenChart({
121
+ bars,
122
+ models,
123
+ range,
124
+ now,
125
+ highlight,
126
+ ariaLabel,
127
+ }: {
128
+ bars: ChartBar[];
129
+ /** Visible models, largest first (bottom of each stack). */
130
+ models: string[];
131
+ range: RangeSpec;
132
+ now: number;
133
+ highlight: string | null;
134
+ ariaLabel: string;
135
+ }): JSX.Element {
136
+ const [wrapRef, width] = useWidth<HTMLDivElement>(800);
137
+ const [hover, setHover] = useState<number | null>(null);
138
+ const tipRef = useRef<HTMLDivElement>(null);
139
+ const [tipLeft, setTipLeft] = useState(0);
140
+
141
+ const totals = bars.map((bar) =>
142
+ models.reduce((sum, m) => {
143
+ const t = bar.byModel[m];
144
+ return sum + (t ? t.inputTokens + t.outputTokens : 0);
145
+ }, 0),
146
+ );
147
+ const axis = niceAxis(Math.max(0, ...totals), 5);
148
+ const left = 46;
149
+ const right = 8;
150
+ const top = 10;
151
+ const plotHeight = 180;
152
+ const bottom = top + plotHeight;
153
+ const height = bottom + 26;
154
+ const svgWidth = Math.max(width, bars.length * 8 + left + right);
155
+ const step = (svgWidth - left - right) / Math.max(1, bars.length);
156
+ const barWidth = Math.max(2, Math.min(24, step * 0.66));
157
+ const ticks = tickIndices(bars, range, step);
158
+
159
+ const gridLines: JSX.Element[] = [];
160
+ for (let v = 0; v <= axis.max + axis.step / 2; v += axis.step) {
161
+ const y = bottom - (v / axis.max) * plotHeight;
162
+ gridLines.push(
163
+ <g key={v}>
164
+ <line x1={left} x2={svgWidth - right} y1={y} y2={y} class={v === 0 ? "chart-baseline" : "chart-grid"} />
165
+ <text x={left - 8} y={y + 3} text-anchor="end" class="chart-axis">
166
+ {formatAxisTokens(v)}
167
+ </text>
168
+ </g>,
169
+ );
170
+ }
171
+
172
+ useLayoutEffect(() => {
173
+ if (hover === null || !tipRef.current || !wrapRef.current) return;
174
+ const scroller = wrapRef.current;
175
+ const cx = left + hover * step + step / 2 - scroller.scrollLeft;
176
+ const tipWidth = tipRef.current.offsetWidth;
177
+ const maxLeft = scroller.clientWidth - tipWidth - 4;
178
+ let next = cx + 14;
179
+ if (next > maxLeft) next = cx - tipWidth - 14;
180
+ setTipLeft(Math.max(4, next));
181
+ }, [hover, step]);
182
+
183
+ const hovered = hover !== null ? bars[hover] : null;
184
+ const hoverRows = hovered
185
+ ? models
186
+ .filter((m) => hovered.byModel[m])
187
+ .sort((a, b) => {
188
+ const x = hovered.byModel[a];
189
+ const y = hovered.byModel[b];
190
+ return y.inputTokens + y.outputTokens - (x.inputTokens + x.outputTokens);
191
+ })
192
+ : [];
193
+
194
+ return (
195
+ <div class="chart-wrap">
196
+ <div
197
+ class="chart-scroll"
198
+ ref={wrapRef}
199
+ onPointerLeave={() => setHover(null)}
200
+ onPointerMove={(event) => {
201
+ const target = (event.target as Element).closest?.("[data-i]");
202
+ setHover(target ? Number(target.getAttribute("data-i")) : null);
203
+ }}
204
+ >
205
+ <svg class="chart" width={svgWidth} height={height} role="img" aria-label={ariaLabel}>
206
+ {gridLines}
207
+ {bars.map((bar, i) => {
208
+ let y = bottom;
209
+ const x = left + i * step + (step - barWidth) / 2;
210
+ return (
211
+ <g key={bar.start} class={`chart-col${bar.end > now ? " is-live" : ""}${hover === i ? " is-hover" : ""}`} data-i={i}>
212
+ <rect class="chart-hit" x={left + i * step} y={top} width={step} height={plotHeight} />
213
+ {stackSegments(bar, models, axis.max, plotHeight).map((seg, k, all) => {
214
+ const isTop = k === all.length - 1;
215
+ // A 2px surface gap separates stacked segments.
216
+ const gap = !isTop && seg.h > 4 ? 2 : 0;
217
+ y -= seg.h;
218
+ const drawY = y + gap;
219
+ const drawH = Math.max(0.5, seg.h - gap);
220
+ const cls = `chart-seg${highlight && highlight !== seg.model ? " is-dim" : ""}`;
221
+ return isTop ? (
222
+ <path key={seg.model} class={cls} d={roundedTop(x, drawY, barWidth, drawH, 4)} fill={modelColor(seg.model)} />
223
+ ) : (
224
+ <rect key={seg.model} class={cls} x={x} y={drawY} width={barWidth} height={drawH} fill={modelColor(seg.model)} />
225
+ );
226
+ })}
227
+ </g>
228
+ );
229
+ })}
230
+ {ticks.map((i) => {
231
+ const cx = left + i * step + step / 2;
232
+ const anchor = cx > svgWidth - right - 34 ? "end" : cx < left + 34 ? "start" : "middle";
233
+ const tx = anchor === "end" ? Math.min(cx + step / 2, svgWidth - right) : anchor === "start" ? cx - step / 2 : cx;
234
+ return (
235
+ <g key={`t${i}`}>
236
+ <line x1={cx} x2={cx} y1={bottom} y2={bottom + 4} class="chart-tick" />
237
+ <text x={tx} y={bottom + 17} text-anchor={anchor} class="chart-axis">
238
+ {tickLabel(bars[i], range)}
239
+ </text>
240
+ </g>
241
+ );
242
+ })}
243
+ </svg>
244
+ </div>
245
+ {hovered && (
246
+ <div class="chart-tip" ref={tipRef} style={{ left: `${tipLeft}px`, top: `${top}px` }} role="tooltip">
247
+ <div class="chart-tip-head">
248
+ <strong>{barTitle(hovered, range, now)}</strong>
249
+ {hovered.end > now && <span class="chart-tip-live">in progress</span>}
250
+ </div>
251
+ {hoverRows.length === 0 ? (
252
+ <div class="chart-tip-empty">No requests</div>
253
+ ) : (
254
+ <>
255
+ {hoverRows.map((m) => {
256
+ const t = hovered.byModel[m];
257
+ return (
258
+ <div class="chart-tip-row" key={m}>
259
+ <span class="swatch" style={{ background: modelColor(m) }} />
260
+ <span class="chart-tip-model">{m}</span>
261
+ <span class="num">{formatCompact(t.inputTokens + t.outputTokens)}</span>
262
+ <span class="chart-tip-sub num">{formatCount(t.requests)} req</span>
263
+ </div>
264
+ );
265
+ })}
266
+ <div class="chart-tip-row chart-tip-total">
267
+ <span />
268
+ <span class="chart-tip-model">Total</span>
269
+ <span class="num">
270
+ {formatCompact(hoverRows.reduce((s, m) => s + hovered.byModel[m].inputTokens + hovered.byModel[m].outputTokens, 0))}
271
+ </span>
272
+ <span class="chart-tip-sub num">
273
+ {formatCount(hoverRows.reduce((s, m) => s + hovered.byModel[m].requests, 0))} req
274
+ </span>
275
+ </div>
276
+ </>
277
+ )}
278
+ </div>
279
+ )}
280
+ </div>
281
+ );
282
+ }
283
+
284
+ export function Heatmap({
285
+ days,
286
+ cells,
287
+ max,
288
+ }: {
289
+ days: Array<{ key: string; date: number }>;
290
+ cells: Map<string, number>;
291
+ max: number;
292
+ }): JSX.Element {
293
+ const level = (v: number): number => {
294
+ if (v <= 0 || max <= 0) return 0;
295
+ const t = v / max;
296
+ if (t < 0.15) return 1;
297
+ if (t < 0.35) return 2;
298
+ if (t < 0.6) return 3;
299
+ return 4;
300
+ };
301
+ const hours = Array.from({ length: 24 }, (_, h) => h);
302
+ return (
303
+ <div class="heatmap-scroll">
304
+ <div class="heatmap" style={{ gridTemplateColumns: `2.25rem repeat(${days.length}, minmax(0.6rem, 1fr))` }} role="img" aria-label="Requests per hour over the last 60 days">
305
+ <span />
306
+ {days.map((day, i) => (
307
+ <span key={day.key} class="heatmap-col-label">
308
+ {i % 7 === 0 ? new Date(day.date).toLocaleDateString([], { month: "short", day: "numeric" }) : ""}
309
+ </span>
310
+ ))}
311
+ {hours.map((hour) => (
312
+ <Fragment key={hour}>
313
+ <span class="heatmap-row-label">
314
+ {hour % 3 === 0 ? `${String(hour).padStart(2, "0")}:00` : ""}
315
+ </span>
316
+ {days.map((day) => {
317
+ const value = cells.get(`${day.key}|${hour}`) || 0;
318
+ return (
319
+ <span
320
+ key={`${day.key}|${hour}`}
321
+ class={`heatmap-cell level-${level(value)}`}
322
+ title={`${new Date(day.date).toLocaleDateString([], { weekday: "short", month: "short", day: "numeric" })} ${String(hour).padStart(2, "0")}:00 · ${formatCount(value)} requests`}
323
+ />
324
+ );
325
+ })}
326
+ </Fragment>
327
+ ))}
328
+ </div>
329
+ <div class="heatmap-legend" aria-hidden="true">
330
+ <span>Less</span>
331
+ {[0, 1, 2, 3, 4].map((l) => (
332
+ <span key={l} class={`heatmap-cell level-${l}`} />
333
+ ))}
334
+ <span>More</span>
335
+ </div>
336
+ </div>
337
+ );
338
+ }
@@ -0,0 +1,279 @@
1
+ // ⌘K command palette: jump to a page or an account, or run a quick action.
2
+
3
+ import type { JSX } from "preact";
4
+ import { useEffect, useId, useMemo, useRef, useState } from "preact/hooks";
5
+ import { accountStatus, providerIds, providerLabel } from "../lib/status.js";
6
+ import { NAV } from "../nav.js";
7
+ import { accountPath, navigate, route } from "../state/router.js";
8
+ import {
9
+ accounts,
10
+ authRequired,
11
+ masked,
12
+ masker,
13
+ paletteOpen,
14
+ railExpanded,
15
+ signOut,
16
+ theme,
17
+ } from "../state/store.js";
18
+ import { downloadUrl, openAddAccount } from "../pages/shared.js";
19
+ import { Icon, type IconName } from "./icons.js";
20
+ import { useNativeDialog } from "./overlays.js";
21
+ import { Pill } from "./ui.js";
22
+
23
+ type Group = "Pages" | "Accounts" | "Actions";
24
+
25
+ interface Command {
26
+ id: string;
27
+ group: Group;
28
+ label: string;
29
+ sub?: string;
30
+ icon: IconName;
31
+ haystack: string;
32
+ run: () => void;
33
+ trailing?: JSX.Element;
34
+ }
35
+
36
+ const GROUP_ORDER: Group[] = ["Pages", "Accounts", "Actions"];
37
+
38
+ /** The palette shortcut's modifier, as the platform labels it. */
39
+ export const MOD_KEY = /Mac|iPhone|iPad/.test(navigator.platform || navigator.userAgent) ? "⌘" : "Ctrl";
40
+ const ACCOUNT_PREVIEW = 6;
41
+
42
+ function matches(command: Command, terms: string[]): boolean {
43
+ return terms.every((term) => command.haystack.includes(term));
44
+ }
45
+
46
+ function useCommands(): Command[] {
47
+ const m = masker.value;
48
+ const current = route.value.page;
49
+ return useMemo(() => {
50
+ const pages: Command[] = NAV.map((item) => ({
51
+ id: `page-${item.id}`,
52
+ group: "Pages",
53
+ label: item.label,
54
+ icon: item.icon,
55
+ haystack: `${item.label} ${item.keywords}`.toLowerCase(),
56
+ run: () => navigate(item.href),
57
+ trailing: current === item.id ? <span class="palette-current">Current</span> : undefined,
58
+ }));
59
+ const accountCommands: Command[] = accounts.value.map((account) => {
60
+ const name = m.name(account.email);
61
+ const email = m.email(account.email);
62
+ const providers = providerIds(account).map(providerLabel);
63
+ const status = accountStatus(account.status);
64
+ return {
65
+ id: `account-${account.email}`,
66
+ group: "Accounts",
67
+ label: name,
68
+ sub: [email !== name ? email : null, ...providers].filter(Boolean).join(" · "),
69
+ icon: "user",
70
+ haystack: `${name} ${m.enabled ? "" : account.email} ${providers.join(" ")} ${status.label}`.toLowerCase(),
71
+ run: () => navigate(accountPath(account.email)),
72
+ trailing: (
73
+ <Pill tone={status.tone} title={status.description}>
74
+ {status.label}
75
+ </Pill>
76
+ ),
77
+ };
78
+ });
79
+ const themeLabel = { system: "Follow the system theme", light: "Use the light theme", dark: "Use the dark theme" } as const;
80
+ type Action = { id: string; label: string; icon: IconName; keywords: string; run: () => void };
81
+ const actions: Action[] = [
82
+ { id: "add-account", label: "Add an account", icon: "plus", keywords: "new sign in login provider", run: openAddAccount },
83
+ ...(["light", "dark", "system"] as const)
84
+ .filter((value) => value !== theme.value)
85
+ .map((value) => ({
86
+ id: `theme-${value}`,
87
+ label: themeLabel[value],
88
+ icon: (value === "light" ? "sun" : value === "dark" ? "moon" : "monitor") as IconName,
89
+ keywords: "theme appearance mode",
90
+ run: () => (theme.value = value),
91
+ })),
92
+ {
93
+ id: "mask",
94
+ label: masked.value ? "Turn off the privacy mask" : "Turn on the privacy mask",
95
+ icon: (masked.value ? "eye" : "eyeOff") as IconName,
96
+ keywords: "privacy hide names emails screenshot",
97
+ run: () => (masked.value = !masked.value),
98
+ },
99
+ {
100
+ id: "rail",
101
+ label: railExpanded.value ? "Collapse the sidebar" : "Expand the sidebar",
102
+ icon: "panelLeft" as IconName,
103
+ keywords: "sidebar rail navigation labels",
104
+ run: () => (railExpanded.value = !railExpanded.value),
105
+ },
106
+ {
107
+ id: "export-csv",
108
+ label: "Export usage as CSV",
109
+ icon: "download" as IconName,
110
+ keywords: "tokens download spreadsheet",
111
+ run: () => downloadUrl("/api/dashboard/usage/export?format=csv"),
112
+ },
113
+ ...(authRequired.value
114
+ ? [{ id: "sign-out", label: "Sign out", icon: "logout" as IconName, keywords: "log out session", run: () => void signOut() }]
115
+ : []),
116
+ ];
117
+ const actionCommands: Command[] = actions.map((action) => ({
118
+ id: action.id,
119
+ group: "Actions" as const,
120
+ label: action.label,
121
+ icon: action.icon,
122
+ haystack: `${action.label} ${action.keywords}`.toLowerCase(),
123
+ run: action.run,
124
+ }));
125
+ return [...pages, ...accountCommands, ...actionCommands];
126
+ }, [accounts.value, m, current, theme.value, masked.value, railExpanded.value, authRequired.value]);
127
+ }
128
+
129
+ export function CommandPalette(): JSX.Element {
130
+ const open = paletteOpen.value;
131
+ const ref = useNativeDialog(open);
132
+ const [text, setText] = useState("");
133
+ const [active, setActive] = useState(0);
134
+ const listRef = useRef<HTMLDivElement>(null);
135
+ const listId = useId();
136
+ const commands = useCommands();
137
+
138
+ useEffect(() => {
139
+ if (open) {
140
+ setText("");
141
+ setActive(0);
142
+ }
143
+ }, [open]);
144
+
145
+ const results = useMemo(() => {
146
+ const terms = text.trim().toLowerCase().split(/\s+/).filter(Boolean);
147
+ const found = terms.length === 0 ? commands : commands.filter((c) => matches(c, terms));
148
+ const grouped = GROUP_ORDER.map((group) => {
149
+ let items = found.filter((c) => c.group === group);
150
+ if (group === "Accounts" && terms.length === 0) items = items.slice(0, ACCOUNT_PREVIEW);
151
+ return { group, items };
152
+ }).filter((g) => g.items.length > 0);
153
+ return { grouped, flat: grouped.flatMap((g) => g.items) };
154
+ }, [commands, text]);
155
+
156
+ useEffect(() => setActive(0), [text]);
157
+
158
+ useEffect(() => {
159
+ listRef.current?.querySelector<HTMLElement>(`[data-index="${active}"]`)?.scrollIntoView({ block: "nearest" });
160
+ }, [active]);
161
+
162
+ const close = () => (paletteOpen.value = false);
163
+ const runAt = (index: number) => {
164
+ const command = results.flat[index];
165
+ if (!command) return;
166
+ close();
167
+ command.run();
168
+ };
169
+
170
+ const onKeyDown = (event: KeyboardEvent) => {
171
+ const count = results.flat.length;
172
+ if (event.key === "ArrowDown" || (event.key === "n" && event.ctrlKey)) {
173
+ event.preventDefault();
174
+ if (count) setActive((active + 1) % count);
175
+ } else if (event.key === "ArrowUp" || (event.key === "p" && event.ctrlKey)) {
176
+ event.preventDefault();
177
+ if (count) setActive((active - 1 + count) % count);
178
+ } else if (event.key === "Enter") {
179
+ event.preventDefault();
180
+ runAt(active);
181
+ }
182
+ };
183
+
184
+ let index = -1;
185
+ return (
186
+ <dialog
187
+ ref={ref}
188
+ class="palette"
189
+ aria-label="Command palette"
190
+ onClose={() => {
191
+ if (open) close();
192
+ }}
193
+ onClick={(event) => {
194
+ if (event.target === ref.current) close();
195
+ }}
196
+ >
197
+ {open && (
198
+ <div class="palette-inner">
199
+ <div class="palette-search">
200
+ <Icon name="search" size={17} />
201
+ <input
202
+ type="text"
203
+ value={text}
204
+ placeholder="Search pages, accounts and actions…"
205
+ aria-label="Search pages, accounts and actions"
206
+ role="combobox"
207
+ aria-expanded="true"
208
+ aria-controls={listId}
209
+ aria-activedescendant={results.flat[active] ? `${listId}-${active}` : undefined}
210
+ autocomplete="off"
211
+ spellcheck={false}
212
+ autofocus
213
+ onInput={(event) => setText((event.target as HTMLInputElement).value)}
214
+ onKeyDown={onKeyDown}
215
+ />
216
+ <kbd>Esc</kbd>
217
+ </div>
218
+ <div class="palette-results" id={listId} role="listbox" aria-label="Results" ref={listRef}>
219
+ {results.flat.length === 0 ? (
220
+ <div class="palette-empty">
221
+ <Icon name="search" size={18} />
222
+ <span>Nothing matches “{text.trim()}”</span>
223
+ </div>
224
+ ) : (
225
+ results.grouped.map(({ group, items }) => (
226
+ <div class="palette-group" key={group} role="presentation">
227
+ <div class="palette-group-label" role="presentation">
228
+ {group}
229
+ </div>
230
+ {items.map((command) => {
231
+ index += 1;
232
+ const i = index;
233
+ return (
234
+ <div
235
+ key={command.id}
236
+ id={`${listId}-${i}`}
237
+ data-index={i}
238
+ role="option"
239
+ aria-selected={i === active}
240
+ class={`palette-item${i === active ? " is-active" : ""}`}
241
+ onPointerMove={() => i !== active && setActive(i)}
242
+ onClick={() => runAt(i)}
243
+ >
244
+ <span class="palette-icon">
245
+ <Icon name={command.icon} size={16} />
246
+ </span>
247
+ <span class="palette-text">
248
+ <span class="palette-label">{command.label}</span>
249
+ {command.sub && <span class="palette-sub">{command.sub}</span>}
250
+ </span>
251
+ {command.trailing}
252
+ <span class="palette-enter" aria-hidden="true">
253
+ <Icon name="cornerDownLeft" size={14} />
254
+ </span>
255
+ </div>
256
+ );
257
+ })}
258
+ </div>
259
+ ))
260
+ )}
261
+ </div>
262
+ <div class="palette-foot" aria-hidden="true">
263
+ <span>
264
+ <kbd>↑</kbd>
265
+ <kbd>↓</kbd> to move
266
+ </span>
267
+ <span>
268
+ <kbd>↵</kbd> to open
269
+ </span>
270
+ <span class="palette-foot-end">
271
+ <kbd>{MOD_KEY}</kbd>
272
+ <kbd>K</kbd> anywhere
273
+ </span>
274
+ </div>
275
+ </div>
276
+ )}
277
+ </dialog>
278
+ );
279
+ }