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