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