Open History to see the last commit
1import { ChevronDownIcon, ChevronUpIcon, MousePointer2Icon, PlusIcon, XIcon } from "lucide-react";
2import {
3 useCallback,
4 useEffect,
5 useRef,
6 useState,
7 type PointerEvent as ReactPointerEvent,
8} from "react";
9import {
10 applyThemeColorPreview,
11 THEME_COLOR_ROLES,
12 THEME_FILE_VERSION,
13 createVividThemeColors,
14 getCustomThemes,
15 getStandardThemeColors,
16 getThemeColorsForMode,
17 getThemeModes,
18 installCustomTheme,
19 isThemeColor,
20 parseThemeFile,
21 removeCustomTheme,
22 themeIdFromName,
23 updateThemeColorFamily,
24 updateCustomTheme,
25 type ThemeAppearance,
26 type ThemeColors,
27 type ThemeColorRole,
28 type ThemeDefinition,
29} from "../../themePalette";
30import { cn } from "../../lib/utils";
31import { Button } from "../ui/button";
32import { Input } from "../ui/input";
33import { Switch } from "../ui/switch";
34import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
35import { getThemeRoleLabel, ThemeColorField } from "./ThemeColorPicker";
36import {
37 clearThemeInspectorHover,
38 clearThemeInspectorHighlights,
39 highlightThemeRoleUsage,
40 inspectThemeRoleAtElement,
41 inspectThemeRoleFromUtilitiesAtElement,
42 refreshThemeInspectorSpotlight,
43 showThemeInspectorHover,
44 type ThemeElementInspection,
45} from "./themeInspector";
46
47const THEME_EDITOR_SIMPLE_ROLES: ReadonlyArray<ThemeColorRole> = ["canvas", "accent"];
48
49type ThemeEditorColorFamily = Readonly<{
50 id: string;
51 label: string;
52 role: ThemeColorRole;
53 roles: ReadonlyArray<ThemeColorRole>;
54}>;
55
56const THEME_EDITOR_ROLE_GROUPS: ReadonlyArray<{
57 id: string;
58 title: string;
59 families: ReadonlyArray<ThemeEditorColorFamily>;
60}> = [
61 {
62 id: "foundation",
63 title: "Foundation",
64 families: [
65 {
66 id: "background",
67 label: "Background",
68 role: "canvas",
69 roles: ["canvas", "chrome", "toolbar"],
70 },
71 { id: "surface", label: "Surface", role: "surface", roles: ["surface"] },
72 {
73 id: "raised-surface",
74 label: "Raised surface",
75 role: "surfaceRaised",
76 roles: ["surfaceRaised"],
77 },
78 {
79 id: "overlay",
80 label: "Overlay",
81 role: "surfaceOverlay",
82 roles: ["surfaceOverlay"],
83 },
84 {
85 id: "text",
86 label: "Text",
87 role: "text",
88 roles: ["text", "toolbarForeground", "toolbarControlForeground"],
89 },
90 {
91 id: "muted-text",
92 label: "Muted text",
93 role: "mutedForeground",
94 roles: [
95 "textMuted",
96 "mutedForeground",
97 "placeholder",
98 "secondaryLabel",
99 "iconMuted",
100 "sidebarMutedForeground",
101 ],
102 },
103 {
104 id: "border",
105 label: "Border",
106 role: "border",
107 roles: ["border", "toolbarBorder", "sidebarBorder"],
108 },
109 { id: "input", label: "Input", role: "input", roles: ["input"] },
110 ],
111 },
112 {
113 id: "brand-content",
114 title: "Brand & content",
115 families: [
116 {
117 id: "subtle-surface",
118 label: "Subtle surface",
119 role: "secondary",
120 roles: ["secondary", "secondaryForeground", "muted", "toolbarControl"],
121 },
122 {
123 id: "highlight-surface",
124 label: "Highlight surface",
125 role: "accentSurface",
126 roles: ["accentSurface", "accentSurfaceForeground", "toolbarControlHover"],
127 },
128 {
129 id: "accent",
130 label: "Accent",
131 role: "accent",
132 roles: [
133 "accent",
134 "accentForeground",
135 "focus",
136 "update",
137 "updateForeground",
138 "updateSurface",
139 "terminalCursor",
140 ],
141 },
142 {
143 id: "action",
144 label: "Action",
145 role: "messageAction",
146 roles: ["messageAction", "messageActionForeground", "messageActionHover"],
147 },
148 {
149 id: "message-surface",
150 label: "Message surface",
151 role: "messageSurface",
152 roles: ["messageSurface", "messageForeground"],
153 },
154 {
155 id: "code-surface",
156 label: "Code surface",
157 role: "codeBackground",
158 roles: ["codeBackground", "codeForeground"],
159 },
160 ],
161 },
162 {
163 id: "context",
164 title: "Context",
165 families: [
166 {
167 id: "sidebar-background",
168 label: "Sidebar background",
169 role: "sidebar",
170 roles: ["sidebar", "sidebarForeground"],
171 },
172 {
173 id: "sidebar-controls",
174 label: "Sidebar controls",
175 role: "sidebarControlSurface",
176 roles: ["sidebarControlSurface"],
177 },
178 {
179 id: "sidebar-selection",
180 label: "Sidebar selection",
181 role: "sidebarRowSelected",
182 roles: ["sidebarRowHover", "sidebarRowActive", "sidebarRowSelected"],
183 },
184 {
185 id: "terminal-background",
186 label: "Terminal background",
187 role: "terminalBackground",
188 roles: [
189 "terminalBackground",
190 "terminalForeground",
191 "terminalSelection",
192 "terminalScrollbar",
193 "terminalScrollbarHover",
194 ],
195 },
196 ],
197 },
198 {
199 id: "status",
200 title: "Status",
201 families: [
202 {
203 id: "error",
204 label: "Error",
205 role: "error",
206 roles: ["error", "errorForeground", "errorSurface"],
207 },
208 {
209 id: "warning",
210 label: "Warning",
211 role: "warning",
212 roles: ["warning", "warningForeground", "warningSurface"],
213 },
214 ],
215 },
216];
217
218const THEME_EDITOR_COLOR_FAMILIES = THEME_EDITOR_ROLE_GROUPS.flatMap((group) => group.families);
219const THEME_EDITOR_COLOR_FAMILY_BY_ROLE = new Map(
220 THEME_EDITOR_COLOR_FAMILIES.flatMap((family) =>
221 family.roles.map((role) => [role, family] as const),
222 ),
223);
224
225function getThemeEditorColorFamily(role: ThemeColorRole): ThemeEditorColorFamily | null {
226 return THEME_EDITOR_COLOR_FAMILY_BY_ROLE.get(role) ?? null;
227}
228
229type ThemeEditorColors = ThemeColors;
230type ThemeEditorColorsByAppearance = Record<ThemeAppearance, ThemeEditorColors>;
231
232// A draft with no source theme starts as the standard T3 Code look — the
233// palette on screen when no theme is installed — so creating from the default
234// theme changes nothing until the user edits a color.
235function getThemeEditorDefaults(appearance: ThemeAppearance): ThemeEditorColors {
236 return { ...getStandardThemeColors(appearance) };
237}
238
239function getThemeEditorColorsByAppearance(): ThemeEditorColorsByAppearance {
240 return {
241 light: getThemeEditorDefaults("light"),
242 dark: getThemeEditorDefaults("dark"),
243 };
244}
245
246function isThemeEditorColor(value: string): boolean {
247 return isThemeColor(value.trim());
248}
249
250function getManagedEditorColors(
251 appearance: ThemeAppearance,
252 colors: ThemeEditorColors,
253): ThemeEditorColors {
254 const defaults = getStandardThemeColors(appearance);
255 // The editor keeps the user's exact picks and derives the rest through the
256 // perceptual vivid engine, so a two-color theme carries its own identity.
257 return createVividThemeColors(
258 appearance,
259 isThemeEditorColor(colors.canvas) ? colors.canvas : defaults.canvas,
260 isThemeEditorColor(colors.accent) ? colors.accent : defaults.accent,
261 );
262}
263
264export function ThemeEditorPanel({
265 open,
266 onOpenChange,
267 onSaved,
268 editingTheme,
269 initialAppearance,
270 seedTheme,
271 seedName,
272 restoreTheme,
273}: {
274 open: boolean;
275 onOpenChange: (open: boolean) => void;
276 onSaved: (
277 theme: ThemeDefinition,
278 context: {
279 created: boolean;
280 /** Set when a create merged its palette into an existing theme. */
281 mergedAppearance?: ThemeAppearance;
282 },
283 ) => boolean;
284 editingTheme: ThemeDefinition | null;
285 initialAppearance: ThemeAppearance;
286 /** The theme a new theme starts from, so tuning what you already use is a
287 * matter of editing rather than rebuilding. Null starts from the defaults. */
288 seedTheme?: ThemeDefinition | null;
289 /** Prefilled name for an explicit duplicate; a plain create stays unnamed. */
290 seedName?: string | undefined;
291 /** Reapplies the stored theme once the draft stops being previewed. */
292 restoreTheme: () => void;
293}) {
294 const isEditing = editingTheme !== null;
295 const [name, setName] = useState("");
296 const [activeAppearance, setActiveAppearance] = useState<ThemeAppearance>(initialAppearance);
297 const [isAdvanced, setIsAdvanced] = useState(false);
298 const [colorsByAppearance, setColorsByAppearance] = useState<ThemeEditorColorsByAppearance>(() =>
299 getThemeEditorColorsByAppearance(),
300 );
301 const [simpleColorsDirtyByAppearance, setSimpleColorsDirtyByAppearance] = useState<
302 Record<ThemeAppearance, boolean>
303 >({ light: false, dark: false });
304 const [error, setError] = useState<string | null>(null);
305 const [isMinimized, setIsMinimized] = useState(false);
306 const [roleQuery, setRoleQuery] = useState("");
307 const [isInspecting, setIsInspecting] = useState(false);
308 const [selectedRole, setSelectedRole] = useState<ThemeColorRole | null>(null);
309 const [usageCount, setUsageCount] = useState<number | null>(null);
310 // Null parks the panel at its default corner; a value is a dragged spot,
311 // kept clamped so the header can always be grabbed again.
312 const [position, setPosition] = useState<{ x: number; y: number } | null>(null);
313 // Null keeps the responsive default size; a value is a corner-grip resize.
314 const [size, setSize] = useState<{ width: number; height: number } | null>(null);
315 const panelRef = useRef<HTMLDivElement>(null);
316 const dragOffsetRef = useRef<{ dx: number; dy: number } | null>(null);
317 const resizeStartRef = useRef<{
318 pointerX: number;
319 pointerY: number;
320 // Where the panel's top-left sits: the grip only moves the opposite
321 // corner, so the room to grow is measured from here.
322 left: number;
323 top: number;
324 width: number;
325 height: number;
326 } | null>(null);
327 useEffect(() => {
328 if (!open) return;
329 // A panel sized wider than the window can no longer be clamped back into
330 // view by position alone -- its right edge (close, minimize, the grip)
331 // stays off screen. So the size shrinks to fit first, then the position
332 // is re-clamped against the new size.
333 const clamp = () => {
334 const margin = 8;
335 let clampedWidth: number | undefined;
336 let clampedHeight: number | undefined;
337 setSize((current) => {
338 if (!current) return current;
339 clampedWidth = Math.max(280, Math.min(current.width, window.innerWidth - margin * 2));
340 clampedHeight = Math.max(220, Math.min(current.height, window.innerHeight - margin * 2));
341 return { width: clampedWidth, height: clampedHeight };
342 });
343 setPosition((current) => {
344 if (!current) return current;
345 const clamped = clampPosition(current.x, current.y, clampedWidth);
346 // Dragging may park the panel with only its header showing, but a
347 // window resize should pull the whole thing back into view when it
348 // fits -- otherwise the grip ends up below the fold. Minimized, the
349 // stored height is not applied (the panel hugs its header), so the
350 // rendered height is what has to fit.
351 const height = isMinimized
352 ? (panelRef.current?.offsetHeight ?? 0)
353 : (clampedHeight ?? panelRef.current?.offsetHeight ?? 0);
354 const maxY = Math.max(margin, window.innerHeight - height - margin);
355 return { x: clamped.x, y: Math.min(clamped.y, maxY) };
356 });
357 };
358 window.addEventListener("resize", clamp);
359 return () => window.removeEventListener("resize", clamp);
360 }, [isMinimized, open]);
361
362 // The draft only reaches the live app once this open has been seeded;
363 // previewing in the seeding commit would paint the previous session's
364 // colors for a frame.
365 const [isDraftSeeded, setIsDraftSeeded] = useState(false);
366 const previousOpenRef = useRef(false);
367
368 useEffect(() => {
369 if (open && !previousOpenRef.current) {
370 // Editing works on the theme itself; creating starts from the theme
371 // that is currently in use, so tuning what you already run is an edit
372 // away instead of a rebuild from the defaults.
373 const sourceTheme = editingTheme ?? seedTheme ?? null;
374 const nextColors = getThemeEditorColorsByAppearance();
375 const nextAppearance = sourceTheme
376 ? getThemeColorsForMode(sourceTheme, initialAppearance)
377 ? initialAppearance
378 : sourceTheme.appearance
379 : initialAppearance;
380 if (sourceTheme) {
381 nextColors[sourceTheme.appearance] = { ...sourceTheme.colors };
382 for (const appearance of ["light", "dark"] as const) {
383 const variantColors = sourceTheme.variants?.[appearance];
384 if (variantColors) nextColors[appearance] = { ...variantColors };
385 }
386 }
387
388 setName(editingTheme?.label ?? seedName ?? "");
389 setActiveAppearance(nextAppearance);
390 // Themes saved by the guided editor carry the managed flag; anything
391 // else (imports, hand-edited files, older saves) opens in advanced mode
392 // so guided regeneration cannot silently discard hand-tuned colors. A
393 // seeded new theme follows the same rule: its palette is only safe to
394 // regenerate when the guided editor produced it.
395 setIsAdvanced(sourceTheme !== null && sourceTheme.managed !== true);
396 setSimpleColorsDirtyByAppearance({ light: false, dark: false });
397 setColorsByAppearance(nextColors);
398 setSelectedRole(null);
399 setUsageCount(null);
400 setIsInspecting(false);
401 setError(null);
402 setIsDraftSeeded(true);
403 }
404 if (!open && isDraftSeeded) setIsDraftSeeded(false);
405 previousOpenRef.current = open;
406 }, [editingTheme, initialAppearance, isDraftSeeded, open, seedName, seedTheme]);
407
408 // A name an installed theme already uses combines instead of failing:
409 // creating adds the new palette to that theme, and renaming an existing
410 // theme onto it folds the edited palette in and retires the old entry —
411 // light "My Theme" plus a dark "My Theme" become one theme with both modes.
412 // Labels are matched as well as derived ids: a rename keeps a theme's
413 // original id, so its label is the only name a user can see and retype.
414 const nameTargetId = themeIdFromName(name);
415 const normalizedName = name.trim().toLowerCase();
416 const mergeTarget =
417 normalizedName === ""
418 ? null
419 : (getCustomThemes().find(
420 (theme) =>
421 theme.id !== editingTheme?.id &&
422 (theme.id === nameTargetId || theme.label.trim().toLowerCase() === normalizedName),
423 ) ?? null);
424 const takenAppearances = mergeTarget ? getThemeModes(mergeTarget) : [];
425 const editableAppearances = editingTheme ? getThemeModes(editingTheme) : null;
426
427 // The appearance a mode button would produce can be blocked two ways: the
428 // merge target already has that palette, or the theme being edited never
429 // had it (adding one is a create-with-same-name away).
430 const appearanceLockReason = (appearance: ThemeAppearance): string | null => {
431 if (editableAppearances && !editableAppearances.includes(appearance)) {
432 return `“${editingTheme?.label}” has no ${appearance} palette. Create a theme with the same name to add one.`;
433 }
434 if (!isEditing && takenAppearances.includes(appearance)) {
435 return `“${mergeTarget?.label}” already has a ${appearance} palette.`;
436 }
437 return null;
438 };
439
440 // Typing a name whose theme already owns the selected appearance flips the
441 // draft to the free side, so the merge affordance works without a manual
442 // toggle. Both sides taken leaves the selection alone; save is blocked with
443 // an explanation instead.
444 const mergeTargetId = mergeTarget?.id ?? null;
445 const takenAppearancesKey = takenAppearances.join(",");
446 useEffect(() => {
447 if (isEditing || mergeTargetId === null) return;
448 const taken = takenAppearancesKey.split(",").filter(Boolean) as ThemeAppearance[];
449 if (taken.length !== 1) return;
450 setActiveAppearance((current) => {
451 if (!taken.includes(current)) return current;
452 return taken[0] === "light" ? "dark" : "light";
453 });
454 }, [isEditing, mergeTargetId, takenAppearancesKey]);
455
456 // The whole app wears the draft while the editor is open, so a role change
457 // is judged on the real interface rather than a miniature. The stored theme
458 // comes back when the editor closes, including on cancel.
459 useEffect(() => {
460 if (!open || !isDraftSeeded) return;
461 applyThemeColorPreview(colorsByAppearance[activeAppearance], activeAppearance);
462 }, [activeAppearance, colorsByAppearance, isDraftSeeded, open]);
463
464 useEffect(() => {
465 if (!open) return;
466 return () => {
467 restoreTheme();
468 };
469 }, [open, restoreTheme]);
470
471 const updateColor = useCallback(
472 (role: ThemeColorRole, value: string) => {
473 setColorsByAppearance((current) => {
474 const nextColors = { ...current[activeAppearance], [role]: value };
475 const shouldManageColors =
476 !isAdvanced && THEME_EDITOR_SIMPLE_ROLES.includes(role) && isThemeEditorColor(value);
477
478 return {
479 ...current,
480 [activeAppearance]: isAdvanced
481 ? updateThemeColorFamily(activeAppearance, current[activeAppearance], role, value)
482 : shouldManageColors
483 ? getManagedEditorColors(activeAppearance, nextColors)
484 : nextColors,
485 };
486 });
487 if (!isAdvanced && THEME_EDITOR_SIMPLE_ROLES.includes(role) && isThemeEditorColor(value)) {
488 setSimpleColorsDirtyByAppearance((current) => ({
489 ...current,
490 [activeAppearance]: true,
491 }));
492 }
493 },
494 [activeAppearance, isAdvanced],
495 );
496
497 const selectThemeRole = useCallback((role: ThemeColorRole, reveal = false) => {
498 const visibleRole = getThemeEditorColorFamily(role)?.role ?? role;
499 setSelectedRole(visibleRole);
500 if (!THEME_EDITOR_SIMPLE_ROLES.includes(visibleRole)) {
501 setIsAdvanced(true);
502 setRoleQuery("");
503 }
504 if (!reveal) return;
505
506 requestAnimationFrame(() => {
507 panelRef.current
508 ?.querySelector(`[data-theme-color-role="${visibleRole}"]`)
509 ?.scrollIntoView({ behavior: "smooth", block: "nearest" });
510 });
511 }, []);
512
513 const toggleThemeRole = useCallback((role: ThemeColorRole) => {
514 setSelectedRole((current) => (current === role ? null : role));
515 }, []);
516
517 const clearInspectorSelection = useCallback(() => {
518 setSelectedRole(null);
519 setUsageCount(null);
520 setIsInspecting(false);
521 }, []);
522
523 const selectedHighlightRoles = selectedRole
524 ? isAdvanced
525 ? (getThemeEditorColorFamily(selectedRole)?.roles ?? [selectedRole])
526 : THEME_EDITOR_SIMPLE_ROLES.includes(selectedRole)
527 ? THEME_COLOR_ROLES.filter(
528 (role) =>
529 colorsByAppearance[activeAppearance][role].trim().toLowerCase() ===
530 colorsByAppearance[activeAppearance][selectedRole].trim().toLowerCase(),
531 )
532 : [selectedRole]
533 : [];
534 const selectedHighlightRolesKey = selectedHighlightRoles.join(",");
535
536 useEffect(() => {
537 clearThemeInspectorHighlights();
538 if (!open || selectedRole === null) {
539 setUsageCount(null);
540 return;
541 }
542 // Picking a new element needs the unobscured app, so suspend the existing
543 // spotlight while the picker is armed.
544 if (isInspecting) return;
545
546 const highlightedRoles = selectedHighlightRolesKey.split(",") as Array<ThemeColorRole>;
547 const refreshHighlights = () => setUsageCount(highlightThemeRoleUsage(highlightedRoles));
548 refreshHighlights();
549 // A refresh snapshots computed styles for the whole tree twice, so it is
550 // throttled rather than run per frame: a streaming reply or a virtualized
551 // list mutates the DOM continuously and would otherwise stall the main
552 // thread for as long as the inspector is open.
553 const MIN_REFRESH_INTERVAL_MS = 500;
554 let refreshFrame: number | null = null;
555 let refreshTimer: ReturnType<typeof setTimeout> | null = null;
556 let lastRefreshAt = performance.now();
557 const scheduleRefresh = () => {
558 if (refreshFrame !== null || refreshTimer !== null) return;
559 const wait = Math.max(0, MIN_REFRESH_INTERVAL_MS - (performance.now() - lastRefreshAt));
560 const run = () => {
561 refreshFrame = null;
562 refreshTimer = null;
563 lastRefreshAt = performance.now();
564 refreshHighlights();
565 };
566 if (wait === 0) refreshFrame = requestAnimationFrame(run);
567 else refreshTimer = setTimeout(run, wait);
568 };
569 const observer = new MutationObserver((mutations) => {
570 if (
571 mutations.every(
572 (mutation) =>
573 mutation.target instanceof Element &&
574 (mutation.target.closest("#theme-inspector-spotlight") ||
575 mutation.target.closest("[data-theme-editor-panel]")),
576 )
577 ) {
578 return;
579 }
580 scheduleRefresh();
581 });
582 observer.observe(document.body, { childList: true, subtree: true });
583 let spotlightFrame: number | null = null;
584 const scheduleSpotlightRefresh = () => {
585 spotlightFrame ??= requestAnimationFrame(() => {
586 spotlightFrame = null;
587 refreshThemeInspectorSpotlight();
588 });
589 };
590 window.addEventListener("resize", scheduleSpotlightRefresh);
591 window.addEventListener("scroll", scheduleSpotlightRefresh, true);
592 return () => {
593 observer.disconnect();
594 if (refreshFrame !== null) cancelAnimationFrame(refreshFrame);
595 if (refreshTimer !== null) clearTimeout(refreshTimer);
596 if (spotlightFrame !== null) cancelAnimationFrame(spotlightFrame);
597 window.removeEventListener("resize", scheduleSpotlightRefresh);
598 window.removeEventListener("scroll", scheduleSpotlightRefresh, true);
599 clearThemeInspectorHighlights();
600 };
601 }, [isInspecting, open, selectedHighlightRolesKey, selectedRole]);
602
603 useEffect(() => {
604 if (!open || !isInspecting) {
605 clearThemeInspectorHover();
606 return;
607 }
608
609 let shouldDisarmAfterClick = false;
610 let hoverTarget: Element | null = null;
611 let hoverInspection: ThemeElementInspection | null = null;
612 let hoverTimer: number | null = null;
613 let hoverFrame: number | null = null;
614 const clearHoverTimer = () => {
615 if (hoverTimer === null) return;
616 window.clearTimeout(hoverTimer);
617 hoverTimer = null;
618 };
619 const clearHover = () => {
620 clearHoverTimer();
621 hoverTarget = null;
622 hoverInspection = null;
623 clearThemeInspectorHover();
624 };
625 const showInspection = (inspection: ThemeElementInspection) => {
626 hoverInspection = inspection;
627 showThemeInspectorHover(
628 inspection,
629 getThemeEditorColorFamily(inspection.role)?.label ?? getThemeRoleLabel(inspection.role),
630 );
631 };
632 const handlePointerOver = (event: PointerEvent) => {
633 const target = event.target;
634 if (!(target instanceof Element) || target.closest("[data-theme-editor-panel]")) {
635 clearHover();
636 return;
637 }
638
639 clearHoverTimer();
640 hoverTarget = target;
641 hoverInspection = null;
642 const utilityInspection = inspectThemeRoleFromUtilitiesAtElement(target);
643 if (utilityInspection) {
644 showInspection(utilityInspection);
645 return;
646 }
647
648 clearThemeInspectorHover();
649 hoverTimer = window.setTimeout(() => {
650 hoverTimer = null;
651 if (hoverTarget !== target || !target.isConnected) return;
652 const inspection = inspectThemeRoleAtElement(target);
653 if (inspection) showInspection(inspection);
654 }, 140);
655 };
656 const handlePointerOut = (event: PointerEvent) => {
657 if (event.relatedTarget === null) clearHover();
658 };
659 const handlePointerDown = (event: PointerEvent) => {
660 const target = event.target;
661 if (!(target instanceof Element) || target.closest("[data-theme-editor-panel]")) return;
662 event.preventDefault();
663 event.stopPropagation();
664 clearHoverTimer();
665 const inspection =
666 hoverTarget === target && hoverInspection
667 ? hoverInspection
668 : inspectThemeRoleAtElement(target);
669 if (!inspection) return;
670 clearHover();
671 selectThemeRole(inspection.role, true);
672 shouldDisarmAfterClick = true;
673 };
674 const blockInspectedClick = (event: MouseEvent) => {
675 const target = event.target;
676 if (!(target instanceof Element) || target.closest("[data-theme-editor-panel]")) return;
677 event.preventDefault();
678 event.stopPropagation();
679 if (shouldDisarmAfterClick) setIsInspecting(false);
680 shouldDisarmAfterClick = false;
681 };
682 const cancelInspection = (event: KeyboardEvent) => {
683 if (event.key !== "Escape") return;
684 event.preventDefault();
685 clearHover();
686 clearInspectorSelection();
687 };
688 const refreshHover = () => {
689 if (!hoverInspection) return;
690 hoverFrame ??= requestAnimationFrame(() => {
691 hoverFrame = null;
692 if (hoverInspection) {
693 showThemeInspectorHover(
694 hoverInspection,
695 getThemeEditorColorFamily(hoverInspection.role)?.label ??
696 getThemeRoleLabel(hoverInspection.role),
697 );
698 }
699 });
700 };
701 const clearHoverOnScroll = () => clearHover();
702
703 document.addEventListener("pointerover", handlePointerOver, true);
704 document.addEventListener("pointerout", handlePointerOut, true);
705 document.addEventListener("pointerdown", handlePointerDown, true);
706 document.addEventListener("click", blockInspectedClick, true);
707 document.addEventListener("keydown", cancelInspection, true);
708 window.addEventListener("resize", refreshHover);
709 window.addEventListener("scroll", clearHoverOnScroll, true);
710 return () => {
711 document.removeEventListener("pointerover", handlePointerOver, true);
712 document.removeEventListener("pointerout", handlePointerOut, true);
713 document.removeEventListener("pointerdown", handlePointerDown, true);
714 document.removeEventListener("click", blockInspectedClick, true);
715 document.removeEventListener("keydown", cancelInspection, true);
716 window.removeEventListener("resize", refreshHover);
717 window.removeEventListener("scroll", clearHoverOnScroll, true);
718 clearHoverTimer();
719 if (hoverFrame !== null) cancelAnimationFrame(hoverFrame);
720 clearThemeInspectorHover();
721 };
722 }, [clearInspectorSelection, isInspecting, open, selectThemeRole]);
723
724 const handleAdvancedChange = useCallback(
725 (checked: boolean) => {
726 setIsAdvanced(checked);
727 if (checked) return;
728 if (selectedRole && !THEME_EDITOR_SIMPLE_ROLES.includes(selectedRole)) {
729 setSelectedRole(null);
730 }
731
732 // Regenerate every appearance the theme will save, not just the visible
733 // one, so the palettes shown after toggling match what gets saved.
734 const managedAppearances: ReadonlyArray<ThemeAppearance> =
735 editingTheme && getThemeModes(editingTheme).length > 1
736 ? ["light", "dark"]
737 : [activeAppearance];
738 setSimpleColorsDirtyByAppearance((current) => {
739 const next = { ...current };
740 for (const appearance of managedAppearances) next[appearance] = true;
741 return next;
742 });
743 setColorsByAppearance((current) => {
744 const next = { ...current };
745 for (const appearance of managedAppearances) {
746 next[appearance] = getManagedEditorColors(appearance, current[appearance]);
747 }
748 return next;
749 });
750 },
751 [activeAppearance, editingTheme, selectedRole],
752 );
753
754 const handleSubmit = () => {
755 if (!name.trim()) {
756 setError("Name your theme first.");
757 return;
758 }
759
760 try {
761 // Only regenerate palettes the user actually touched in guided mode, so
762 // untouched appearances save exactly what the editor displayed.
763 const colorsForSave = !isAdvanced
764 ? {
765 light: simpleColorsDirtyByAppearance.light
766 ? getManagedEditorColors("light", colorsByAppearance.light)
767 : colorsByAppearance.light,
768 dark: simpleColorsDirtyByAppearance.dark
769 ? getManagedEditorColors("dark", colorsByAppearance.dark)
770 : colorsByAppearance.dark,
771 }
772 : colorsByAppearance;
773
774 let savedTheme: ThemeDefinition;
775 let mergedAppearance: ThemeAppearance | null = null;
776 let retiredTheme: ThemeDefinition | null = null;
777 if (editingTheme && mergeTarget) {
778 // Renamed onto another installed theme: this theme's palettes fold
779 // into it and the edited entry retires, so both cards become one.
780 // Colliding palettes cannot merge — neither side should be silently
781 // overwritten.
782 const editedModes = getThemeModes(editingTheme);
783 const collision = editedModes.find((mode) => takenAppearances.includes(mode));
784 if (collision) {
785 setError(`“${mergeTarget.label}” already has a ${collision} palette. Pick another name.`);
786 return;
787 }
788 mergedAppearance = editedModes[0] ?? null;
789 savedTheme = updateCustomTheme({
790 ...parseThemeFile({
791 version: THEME_FILE_VERSION,
792 id: mergeTarget.id,
793 name: mergeTarget.label,
794 appearance: mergeTarget.appearance,
795 colors: mergeTarget.colors,
796 variants: {
797 ...mergeTarget.variants,
798 ...Object.fromEntries(editedModes.map((mode) => [mode, colorsForSave[mode]])),
799 },
800 ...(mergeTarget.managed === true && !isAdvanced ? { managed: true } : {}),
801 }),
802 ...(mergeTarget.collection ? { collection: mergeTarget.collection } : {}),
803 });
804 retiredTheme = editingTheme;
805 try {
806 removeCustomTheme(editingTheme.id);
807 } catch (cause) {
808 // The merge already persisted. Leaving it while the edited theme
809 // survives would collide on every retry, so the target goes back to
810 // its pre-merge palettes before the failure surfaces.
811 try {
812 updateCustomTheme(mergeTarget);
813 } catch {
814 // Storage is failing wholesale; the rethrow below reports it.
815 }
816 throw cause;
817 }
818 } else if (editingTheme) {
819 const baseAppearance = editingTheme.appearance;
820 const variantAppearance = baseAppearance === "light" ? "dark" : "light";
821 savedTheme = updateCustomTheme({
822 ...parseThemeFile({
823 version: THEME_FILE_VERSION,
824 id: editingTheme.id,
825 name,
826 appearance: baseAppearance,
827 colors: colorsForSave[baseAppearance],
828 ...(getThemeModes(editingTheme).length > 1
829 ? { variants: { [variantAppearance]: colorsForSave[variantAppearance] } }
830 : {}),
831 ...(isAdvanced ? {} : { managed: true }),
832 }),
833 ...(editingTheme.collection ? { collection: editingTheme.collection } : {}),
834 });
835 } else if (mergeTarget) {
836 if (takenAppearances.includes(activeAppearance)) {
837 setError(
838 `“${mergeTarget.label}” already has light and dark palettes. Pick another name.`,
839 );
840 return;
841 }
842 // The new palette joins the existing theme as its other mode; its
843 // stored palettes are untouched. The guided (managed) flag only
844 // survives when every palette in the theme came from the guided
845 // editor.
846 mergedAppearance = activeAppearance;
847 savedTheme = updateCustomTheme({
848 ...parseThemeFile({
849 version: THEME_FILE_VERSION,
850 id: mergeTarget.id,
851 name: mergeTarget.label,
852 appearance: mergeTarget.appearance,
853 colors: mergeTarget.colors,
854 variants: {
855 ...mergeTarget.variants,
856 [activeAppearance]: colorsForSave[activeAppearance],
857 },
858 ...(mergeTarget.managed === true && !isAdvanced ? { managed: true } : {}),
859 }),
860 ...(mergeTarget.collection ? { collection: mergeTarget.collection } : {}),
861 });
862 } else {
863 savedTheme = installCustomTheme(
864 parseThemeFile({
865 version: THEME_FILE_VERSION,
866 name,
867 appearance: activeAppearance,
868 colors: colorsForSave[activeAppearance],
869 ...(isAdvanced ? {} : { managed: true }),
870 }),
871 );
872 }
873 if (
874 !onSaved(savedTheme, {
875 created: editingTheme === null && mergedAppearance === null,
876 ...(mergedAppearance ? { mergedAppearance } : {}),
877 })
878 ) {
879 if (!editingTheme && mergedAppearance === null) {
880 // Roll the install back so a retry can run it again instead of
881 // failing on the already-taken theme id.
882 try {
883 removeCustomTheme(savedTheme.id);
884 } catch {
885 // Storage is failing wholesale; the error below covers it.
886 }
887 } else if (mergeTarget && mergedAppearance !== null) {
888 // Put the pre-merge definitions back for the same reason.
889 try {
890 updateCustomTheme(mergeTarget);
891 if (retiredTheme) installCustomTheme(retiredTheme);
892 } catch {
893 // Storage is failing wholesale; the error below covers it.
894 }
895 }
896 setError("Theme saved, but it could not be made active. Try again.");
897 return;
898 }
899 onOpenChange(false);
900 } catch (cause) {
901 setError(
902 cause instanceof Error
903 ? cause.message
904 : isEditing
905 ? "Could not save the theme."
906 : "Could not create the theme.",
907 );
908 }
909 };
910
911 const renderNameField = () => (
912 <label className="grid grid-cols-[minmax(0,1fr)_minmax(0,2fr)] items-center gap-3">
913 <span className="text-sm font-medium">Theme name</span>
914 <Input
915 autoFocus
916 onChange={(event) => {
917 setName(event.currentTarget.value);
918 // Most save failures are name collisions; retyping is the fix, so
919 // the stale message goes with the old name.
920 setError(null);
921 }}
922 placeholder={isEditing ? "Theme name" : "e.g. Aurora"}
923 value={name}
924 />
925 </label>
926 );
927
928 const renderAppearanceButton = (appearance: ThemeAppearance) => {
929 const isActive = activeAppearance === appearance;
930 const lockReason = appearanceLockReason(appearance);
931 // A locked mode stays hoverable so the tooltip can say why it is off;
932 // a real disabled attribute would swallow the pointer events.
933 const button = (
934 <Button
935 aria-disabled={lockReason !== null}
936 aria-pressed={isActive}
937 className={lockReason !== null ? "opacity-50" : undefined}
938 style={isActive ? { boxShadow: "inset 0 0 0 1px var(--ring)" } : undefined}
939 variant={isActive ? "secondary" : "outline"}
940 onClick={() => {
941 if (lockReason === null) setActiveAppearance(appearance);
942 }}
943 >
944 {appearance === "light" ? "Light" : "Dark"}
945 </Button>
946 );
947 if (lockReason === null) return button;
948 return (
949 <Tooltip>
950 <TooltipTrigger render={button} />
951 <TooltipPopup>{lockReason}</TooltipPopup>
952 </Tooltip>
953 );
954 };
955
956 const renderAppearanceButtons = () => (
957 <div className="grid grid-cols-[minmax(0,1fr)_minmax(0,2fr)] items-center gap-3">
958 <span className="text-sm font-medium">Appearance</span>
959 <div aria-label="Theme appearance" className="grid grid-cols-2 gap-2" role="group">
960 {renderAppearanceButton("light")}
961 {renderAppearanceButton("dark")}
962 </div>
963 </div>
964 );
965
966 const renderColorsHeader = () => (
967 <div className="grid grid-cols-[minmax(0,1fr)_minmax(0,2fr)] items-start gap-3">
968 <div>
969 <h3 className="text-sm font-medium">Colors</h3>
970 {isAdvanced ? null : (
971 <p className="text-xs text-muted-foreground">Two colors, rest derived</p>
972 )}
973 </div>
974 <div className="flex min-w-0 items-start gap-3">
975 {isAdvanced ? (
976 <Input
977 aria-label="Filter colors"
978 className="min-w-0 flex-1"
979 onChange={(event) => setRoleQuery(event.currentTarget.value)}
980 placeholder="Filter colors"
981 size="sm"
982 value={roleQuery}
983 />
984 ) : null}
985 <label className="ml-auto flex shrink-0 cursor-pointer items-center gap-2 pt-0.5 text-sm font-medium">
986 <span>Advanced</span>
987 <Switch
988 aria-label="Use advanced theme colors"
989 checked={isAdvanced}
990 onCheckedChange={(checked) => handleAdvancedChange(Boolean(checked))}
991 />
992 </label>
993 </div>
994 </div>
995 );
996
997 const renderRoleFields = (
998 families: ReadonlyArray<ThemeEditorColorFamily>,
999 gridClassName = "grid gap-2 sm:grid-cols-2",
1000 ) => (
1001 <div className={gridClassName}>
1002 {families.map((family) => (
1003 <ThemeColorField
1004 key={family.id}
1005 label={family.label}
1006 onChange={updateColor}
1007 onSelect={selectThemeRole}
1008 onToggleSelected={toggleThemeRole}
1009 role={family.role}
1010 selected={selectedRole === family.role}
1011 value={colorsByAppearance[activeAppearance][family.role]}
1012 />
1013 ))}
1014 </div>
1015 );
1016
1017 const renderColorFields = () => {
1018 const query = roleQuery.trim().toLowerCase();
1019 const groups = THEME_EDITOR_ROLE_GROUPS.map((group) => ({
1020 ...group,
1021 families: group.families.filter(
1022 (family) =>
1023 !query ||
1024 [family.label, ...family.roles.map((role) => getThemeRoleLabel(role))]
1025 .join(" ")
1026 .toLowerCase()
1027 .includes(query),
1028 ),
1029 })).filter((group) => group.families.length > 0);
1030 return isAdvanced ? (
1031 <div className="space-y-5">
1032 {groups.map((group) => (
1033 <section className="space-y-2" key={group.id}>
1034 <h4 className="text-sm font-medium text-foreground">{group.title}</h4>
1035 {renderRoleFields(group.families, "grid gap-1")}
1036 </section>
1037 ))}
1038 {groups.length === 0 ? <p className="text-xs text-muted-foreground">No matches.</p> : null}
1039 </div>
1040 ) : (
1041 <div className="grid gap-1">
1042 {THEME_EDITOR_SIMPLE_ROLES.map((role) => (
1043 <ThemeColorField
1044 key={role}
1045 onChange={updateColor}
1046 onSelect={selectThemeRole}
1047 onToggleSelected={toggleThemeRole}
1048 role={role}
1049 label={role === "canvas" ? "Background" : "Accent"}
1050 selected={selectedRole === role}
1051 value={colorsByAppearance[activeAppearance][role]}
1052 />
1053 ))}
1054 </div>
1055 );
1056 };
1057
1058 const clampPosition = (x: number, y: number, widthOverride?: number) => {
1059 const panel = panelRef.current;
1060 const margin = 8;
1061 // The caller passes a width when it has just shrunk the panel: the DOM
1062 // still reports the old one until React commits.
1063 const width = widthOverride ?? panel?.offsetWidth ?? 0;
1064 return {
1065 x: Math.min(Math.max(x, margin), Math.max(margin, window.innerWidth - width - margin)),
1066 // Keep at least the header on screen even when dragged far down.
1067 y: Math.min(Math.max(y, margin), Math.max(margin, window.innerHeight - 48)),
1068 };
1069 };
1070
1071 const handleDragPointerDown = (event: ReactPointerEvent<HTMLDivElement>) => {
1072 // Buttons in the header keep their own behavior.
1073 if ((event.target as HTMLElement).closest("button, input, a")) return;
1074 const rect = panelRef.current?.getBoundingClientRect();
1075 if (!rect) return;
1076 dragOffsetRef.current = { dx: event.clientX - rect.x, dy: event.clientY - rect.y };
1077 event.currentTarget.setPointerCapture(event.pointerId);
1078 };
1079
1080 const handleDragPointerMove = (event: ReactPointerEvent<HTMLDivElement>) => {
1081 const offset = dragOffsetRef.current;
1082 if (!offset) return;
1083 setPosition(clampPosition(event.clientX - offset.dx, event.clientY - offset.dy));
1084 };
1085
1086 const endDrag = () => {
1087 dragOffsetRef.current = null;
1088 };
1089
1090 const handleResizePointerDown = (event: ReactPointerEvent<HTMLDivElement>) => {
1091 const rect = panelRef.current?.getBoundingClientRect();
1092 if (!rect) return;
1093 event.preventDefault();
1094 // The grip drags the bottom-right corner, so the top-left must hold
1095 // still; the default parking spot is anchored bottom-right and would
1096 // slide, so it converts to an explicit position first.
1097 if (position === null) setPosition(clampPosition(rect.x, rect.y));
1098 resizeStartRef.current = {
1099 pointerX: event.clientX,
1100 pointerY: event.clientY,
1101 left: rect.x,
1102 top: rect.y,
1103 width: rect.width,
1104 height: rect.height,
1105 };
1106 event.currentTarget.setPointerCapture(event.pointerId);
1107 };
1108
1109 const handleResizePointerMove = (event: ReactPointerEvent<HTMLDivElement>) => {
1110 const start = resizeStartRef.current;
1111 if (!start) return;
1112 const margin = 8;
1113 const MIN_WIDTH = 280;
1114 const MIN_HEIGHT = 220;
1115 // Grow only into the space right of and below the panel's own corner,
1116 // otherwise a panel parked away from the top-left pushes its far edges
1117 // (and this grip) off screen.
1118 const maxWidth = Math.max(MIN_WIDTH, window.innerWidth - margin - start.left);
1119 const maxHeight = Math.max(MIN_HEIGHT, window.innerHeight - margin - start.top);
1120 setSize({
1121 width: Math.min(Math.max(start.width + event.clientX - start.pointerX, MIN_WIDTH), maxWidth),
1122 height: Math.min(
1123 Math.max(start.height + event.clientY - start.pointerY, MIN_HEIGHT),
1124 maxHeight,
1125 ),
1126 });
1127 };
1128
1129 const endResize = () => {
1130 resizeStartRef.current = null;
1131 };
1132
1133 return (
1134 <div
1135 aria-label={isEditing ? "Edit theme" : "Create theme"}
1136 className={cn(
1137 "dialog-glass fixed z-[110] flex max-h-[min(42rem,calc(100dvh-6rem))] w-[min(26rem,calc(100vw-2rem))] flex-col overflow-hidden rounded-xl border text-popover-foreground",
1138 position === null && "bottom-4 right-4",
1139 isMinimized && "max-h-none",
1140 )}
1141 data-theme-editor-panel
1142 ref={panelRef}
1143 role="dialog"
1144 style={{
1145 ...(position ? { left: position.x, top: position.y } : {}),
1146 ...(size ? { width: size.width } : {}),
1147 // A chosen height only applies expanded; minimized keeps hugging the
1148 // header. The viewport stays the ceiling either way.
1149 ...(size && !isMinimized ? { height: size.height, maxHeight: "calc(100dvh - 1rem)" } : {}),
1150 }}
1151 >
1152 <div
1153 className="flex cursor-grab touch-none select-none items-center gap-1 border-b border-border/70 px-3 py-2 active:cursor-grabbing"
1154 onPointerCancel={endDrag}
1155 onPointerDown={handleDragPointerDown}
1156 onPointerMove={handleDragPointerMove}
1157 onPointerUp={endDrag}
1158 >
1159 <div className="flex min-w-0 flex-1 items-baseline gap-2">
1160 <h2 className="shrink-0 truncate text-sm font-medium">
1161 {isEditing ? "Edit theme" : "Create theme"}
1162 </h2>
1163 {isMinimized ? null : (
1164 <p className="truncate text-xs text-muted-foreground">
1165 {isInspecting
1166 ? "Select an element · Esc to cancel"
1167 : selectedRole
1168 ? `${isAdvanced ? (getThemeEditorColorFamily(selectedRole)?.label ?? getThemeRoleLabel(selectedRole)) : getThemeRoleLabel(selectedRole)} · ${usageCount ?? 0} ${usageCount === 1 ? "use" : "uses"}`
1169 : "Select a color below"}
1170 </p>
1171 )}
1172 </div>
1173 <Tooltip>
1174 <TooltipTrigger
1175 render={
1176 <Button
1177 aria-label={isInspecting ? "Cancel inspecting app colors" : "Inspect app colors"}
1178 aria-pressed={isInspecting}
1179 size="xs"
1180 variant={isInspecting ? "secondary" : "ghost"}
1181 onClick={() => {
1182 if (isInspecting) {
1183 clearInspectorSelection();
1184 return;
1185 }
1186 setIsInspecting(true);
1187 }}
1188 >
1189 <MousePointer2Icon />
1190 {isInspecting ? "Cancel" : "Inspect"}
1191 </Button>
1192 }
1193 />
1194 <TooltipPopup data-theme-editor-panel="">
1195 {isInspecting ? "Cancel and clear the selection" : "Pick a color from the app"}
1196 </TooltipPopup>
1197 </Tooltip>
1198 <Button
1199 aria-label={isMinimized ? "Expand the theme editor" : "Minimize the theme editor"}
1200 size="icon-xs"
1201 variant="ghost"
1202 onClick={() => setIsMinimized(!isMinimized)}
1203 >
1204 {isMinimized ? <ChevronUpIcon /> : <ChevronDownIcon />}
1205 </Button>
1206 <Button
1207 aria-label="Close the theme editor"
1208 size="icon-xs"
1209 variant="ghost"
1210 onClick={() => onOpenChange(false)}
1211 >
1212 <XIcon />
1213 </Button>
1214 </div>
1215
1216 {isMinimized ? null : (
1217 <>
1218 <div className="min-h-0 flex-1 space-y-3 overflow-y-auto py-3 pl-3 pr-1.5">
1219 {renderNameField()}
1220 {/* Inline and above the color list: the panel scrolls, and an
1221 error parked below every role would go unseen. */}
1222 {error ? (
1223 <p aria-live="polite" className="text-sm text-destructive">
1224 {error}
1225 </p>
1226 ) : null}
1227 {renderAppearanceButtons()}
1228 <div className="space-y-3">
1229 {renderColorsHeader()}
1230 {renderColorFields()}
1231 </div>
1232 </div>
1233 <div className="flex items-center justify-end gap-2 border-t border-border/70 px-3 py-2">
1234 <Button size="sm" variant="ghost" onClick={() => onOpenChange(false)}>
1235 Cancel
1236 </Button>
1237 <Button disabled={!name.trim()} size="sm" onClick={handleSubmit}>
1238 {isEditing ? (
1239 mergeTarget ? (
1240 `Merge into “${mergeTarget.label}”`
1241 ) : (
1242 "Save changes"
1243 )
1244 ) : mergeTarget ? (
1245 <>
1246 <PlusIcon />
1247 {`Add ${activeAppearance} palette`}
1248 </>
1249 ) : (
1250 <>
1251 <PlusIcon />
1252 Create theme
1253 </>
1254 )}
1255 </Button>
1256 </div>
1257 <div
1258 aria-hidden
1259 className="absolute bottom-0 right-0 z-10 flex size-5 cursor-se-resize touch-none select-none items-end justify-end p-1 text-muted-foreground/70"
1260 onPointerCancel={endResize}
1261 onPointerDown={handleResizePointerDown}
1262 onPointerMove={handleResizePointerMove}
1263 onPointerUp={endResize}
1264 >
1265 <svg
1266 className="size-2.5"
1267 fill="none"
1268 stroke="currentColor"
1269 strokeLinecap="round"
1270 strokeWidth="1.2"
1271 viewBox="0 0 8 8"
1272 >
1273 <path d="M7 1 1 7M7 4.5 4.5 7" />
1274 </svg>
1275 </div>
1276 </>
1277 )}
1278 </div>
1279 );
1280}