Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThemeEditorPanel.tsx

1,295 lines46.8 KB

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