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

ThemeEditorPanel.tsx

1,297 lines46.8 KB

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