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

ThemeEditorPanel.tsx

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