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 = () => {
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 ...(mergeTarget.collection ? { collection: mergeTarget.collection } : {}),
662 });
663 retiredTheme = editingTheme;
664 try {
665 removeCustomTheme(editingTheme.id);
666 } catch (cause) {
667 // The merge already persisted. Leaving it while the edited theme
668 // survives would collide on every retry, so the target goes back to
669 // its pre-merge palettes before the failure surfaces.
670 try {
671 updateCustomTheme(mergeTarget);
672 } catch {
673 // Storage is failing wholesale; the rethrow below reports it.
674 }
675 throw cause;
676 }
677 } else if (editingTheme) {
678 const baseAppearance = editingTheme.appearance;
679 const variantAppearance = baseAppearance === "light" ? "dark" : "light";
680 savedTheme = updateCustomTheme({
681 ...parseThemeFile({
682 version: THEME_FILE_VERSION,
683 id: editingTheme.id,
684 name,
685 appearance: baseAppearance,
686 colors: colorsForSave[baseAppearance],
687 ...(getThemeModes(editingTheme).length > 1
688 ? { variants: { [variantAppearance]: colorsForSave[variantAppearance] } }
689 : {}),
690 ...(isAdvanced ? {} : { managed: true }),
691 }),
692 ...(editingTheme.collection ? { collection: editingTheme.collection } : {}),
693 });
694 } else if (mergeTarget) {
695 if (takenAppearances.includes(activeAppearance)) {
696 setError(
697 `“${mergeTarget.label}” already has light and dark palettes. Pick another name.`,
698 );
699 return;
700 }
701 // The new palette joins the existing theme as its other mode; its
702 // stored palettes are untouched. The guided (managed) flag only
703 // survives when every palette in the theme came from the guided
704 // editor.
705 mergedAppearance = activeAppearance;
706 savedTheme = updateCustomTheme({
707 ...parseThemeFile({
708 version: THEME_FILE_VERSION,
709 id: mergeTarget.id,
710 name: mergeTarget.label,
711 appearance: mergeTarget.appearance,
712 colors: mergeTarget.colors,
713 variants: {
714 ...mergeTarget.variants,
715 [activeAppearance]: colorsForSave[activeAppearance],
716 },
717 ...(mergeTarget.managed === true && !isAdvanced ? { managed: true } : {}),
718 }),
719 ...(mergeTarget.collection ? { collection: mergeTarget.collection } : {}),
720 });
721 } else {
722 savedTheme = installCustomTheme(
723 parseThemeFile({
724 version: THEME_FILE_VERSION,
725 name,
726 appearance: activeAppearance,
727 colors: colorsForSave[activeAppearance],
728 ...(isAdvanced ? {} : { managed: true }),
729 }),
730 );
731 }
732 if (
733 !onSaved(savedTheme, {
734 created: editingTheme === null && mergedAppearance === null,
735 ...(mergedAppearance ? { mergedAppearance } : {}),
736 })
737 ) {
738 if (!editingTheme && mergedAppearance === null) {
739 // Roll the install back so a retry can run it again instead of
740 // failing on the already-taken theme id.
741 try {
742 removeCustomTheme(savedTheme.id);
743 } catch {
744 // Storage is failing wholesale; the error below covers it.
745 }
746 } else if (mergeTarget && mergedAppearance !== null) {
747 // Put the pre-merge definitions back for the same reason.
748 try {
749 updateCustomTheme(mergeTarget);
750 if (retiredTheme) installCustomTheme(retiredTheme);
751 } catch {
752 // Storage is failing wholesale; the error below covers it.
753 }
754 }
755 setError("Theme saved, but it could not be made active. Try again.");
756 return;
757 }
758 onOpenChange(false);
759 } catch (cause) {
760 setError(
761 cause instanceof Error
762 ? cause.message
763 : isEditing
764 ? "Could not save the theme."
765 : "Could not create the theme.",
766 );
767 }
768 };
769
770 const renderNameField = () => (
771 <label className="grid grid-cols-[minmax(0,1fr)_minmax(0,2fr)] items-center gap-3">
772 <span className="text-sm font-medium">Theme name</span>
773 <Input
774 autoFocus
775 onChange={(event) => {
776 setName(event.currentTarget.value);
777 // Most save failures are name collisions; retyping is the fix, so
778 // the stale message goes with the old name.
779 setError(null);
780 }}
781 placeholder={isEditing ? "Theme name" : "e.g. Aurora"}
782 value={name}
783 />
784 </label>
785 );
786
787 const renderAppearanceButton = (appearance: ThemeAppearance) => {
788 const isActive = activeAppearance === appearance;
789 const lockReason = appearanceLockReason(appearance);
790 // A locked mode stays hoverable so the tooltip can say why it is off;
791 // a real disabled attribute would swallow the pointer events.
792 const button = (
793 <Button
794 aria-disabled={lockReason !== null}
795 aria-pressed={isActive}
796 className={lockReason !== null ? "opacity-50" : undefined}
797 style={isActive ? { boxShadow: "inset 0 0 0 1px var(--ring)" } : undefined}
798 variant={isActive ? "secondary" : "outline"}
799 onClick={() => {
800 if (lockReason === null) setActiveAppearance(appearance);
801 }}
802 >
803 {appearance === "light" ? "Light" : "Dark"}
804 </Button>
805 );
806 if (lockReason === null) return button;
807 return (
808 <Tooltip>
809 <TooltipTrigger render={button} />
810 <TooltipPopup>{lockReason}</TooltipPopup>
811 </Tooltip>
812 );
813 };
814
815 const renderAppearanceButtons = () => (
816 <div className="grid grid-cols-[minmax(0,1fr)_minmax(0,2fr)] items-center gap-3">
817 <span className="text-sm font-medium">Appearance</span>
818 <div aria-label="Theme appearance" className="grid grid-cols-2 gap-2" role="group">
819 {renderAppearanceButton("light")}
820 {renderAppearanceButton("dark")}
821 </div>
822 </div>
823 );
824
825 const renderColorsHeader = () => (
826 <div className="grid grid-cols-[minmax(0,1fr)_minmax(0,2fr)] items-start gap-3">
827 <div>
828 <h3 className="text-sm font-medium">Colors</h3>
829 {isAdvanced ? null : (
830 <p className="text-xs text-muted-foreground">Two colors, rest derived</p>
831 )}
832 </div>
833 <div className="flex min-w-0 items-start gap-3">
834 {isAdvanced ? (
835 <Input
836 aria-label="Filter colors"
837 className="min-w-0 flex-1"
838 onChange={(event) => setRoleQuery(event.currentTarget.value)}
839 placeholder="Filter colors"
840 size="sm"
841 value={roleQuery}
842 />
843 ) : null}
844 <label className="ml-auto flex shrink-0 cursor-pointer items-center gap-2 pt-0.5 text-sm font-medium">
845 <span>Advanced</span>
846 <Switch
847 aria-label="Use advanced theme colors"
848 checked={isAdvanced}
849 onCheckedChange={(checked) => handleAdvancedChange(Boolean(checked))}
850 />
851 </label>
852 </div>
853 </div>
854 );
855
856 const renderRoleFields = (
857 roles: ReadonlyArray<ThemeColorRole>,
858 gridClassName = "grid gap-2 sm:grid-cols-2",
859 ) => (
860 <div className={gridClassName}>
861 {roles.map((role) => (
862 <ThemeColorField
863 key={role}
864 onChange={updateColor}
865 onSelect={selectThemeRole}
866 onToggleSelected={toggleThemeRole}
867 role={role}
868 selected={selectedRole === role}
869 value={colorsByAppearance[activeAppearance][role]}
870 />
871 ))}
872 </div>
873 );
874
875 const renderColorFields = () => {
876 const query = roleQuery.trim().toLowerCase();
877 const groups = THEME_EDITOR_ROLE_GROUPS.map((group) => ({
878 ...group,
879 roles: group.roles.filter(
880 (role) => !query || getThemeRoleLabel(role).toLowerCase().includes(query),
881 ),
882 })).filter((group) => group.roles.length > 0);
883 return isAdvanced ? (
884 <div className="space-y-5">
885 {groups.map((group) => (
886 <section className="space-y-2" key={group.id}>
887 <h4 className="text-sm font-medium text-foreground">{group.title}</h4>
888 {renderRoleFields(group.roles, "grid gap-1")}
889 </section>
890 ))}
891 {groups.length === 0 ? <p className="text-xs text-muted-foreground">No matches.</p> : null}
892 </div>
893 ) : (
894 <div className="grid gap-1">
895 {THEME_EDITOR_SIMPLE_ROLES.map((role) => (
896 <ThemeColorField
897 key={role}
898 onChange={updateColor}
899 onSelect={selectThemeRole}
900 onToggleSelected={toggleThemeRole}
901 role={role}
902 label={role === "canvas" ? "Background" : "Accent"}
903 selected={selectedRole === role}
904 value={colorsByAppearance[activeAppearance][role]}
905 />
906 ))}
907 </div>
908 );
909 };
910
911 const clampPosition = (x: number, y: number, widthOverride?: number) => {
912 const panel = panelRef.current;
913 const margin = 8;
914 // The caller passes a width when it has just shrunk the panel: the DOM
915 // still reports the old one until React commits.
916 const width = widthOverride ?? panel?.offsetWidth ?? 0;
917 return {
918 x: Math.min(Math.max(x, margin), Math.max(margin, window.innerWidth - width - margin)),
919 // Keep at least the header on screen even when dragged far down.
920 y: Math.min(Math.max(y, margin), Math.max(margin, window.innerHeight - 48)),
921 };
922 };
923
924 const handleDragPointerDown = (event: ReactPointerEvent<HTMLDivElement>) => {
925 // Buttons in the header keep their own behavior.
926 if ((event.target as HTMLElement).closest("button, input, a")) return;
927 const rect = panelRef.current?.getBoundingClientRect();
928 if (!rect) return;
929 dragOffsetRef.current = { dx: event.clientX - rect.x, dy: event.clientY - rect.y };
930 event.currentTarget.setPointerCapture(event.pointerId);
931 };
932
933 const handleDragPointerMove = (event: ReactPointerEvent<HTMLDivElement>) => {
934 const offset = dragOffsetRef.current;
935 if (!offset) return;
936 setPosition(clampPosition(event.clientX - offset.dx, event.clientY - offset.dy));
937 };
938
939 const endDrag = () => {
940 dragOffsetRef.current = null;
941 };
942
943 const handleResizePointerDown = (event: ReactPointerEvent<HTMLDivElement>) => {
944 const rect = panelRef.current?.getBoundingClientRect();
945 if (!rect) return;
946 event.preventDefault();
947 // The grip drags the bottom-right corner, so the top-left must hold
948 // still; the default parking spot is anchored bottom-right and would
949 // slide, so it converts to an explicit position first.
950 if (position === null) setPosition(clampPosition(rect.x, rect.y));
951 resizeStartRef.current = {
952 pointerX: event.clientX,
953 pointerY: event.clientY,
954 left: rect.x,
955 top: rect.y,
956 width: rect.width,
957 height: rect.height,
958 };
959 event.currentTarget.setPointerCapture(event.pointerId);
960 };
961
962 const handleResizePointerMove = (event: ReactPointerEvent<HTMLDivElement>) => {
963 const start = resizeStartRef.current;
964 if (!start) return;
965 const margin = 8;
966 const MIN_WIDTH = 280;
967 const MIN_HEIGHT = 220;
968 // Grow only into the space right of and below the panel's own corner,
969 // otherwise a panel parked away from the top-left pushes its far edges
970 // (and this grip) off screen.
971 const maxWidth = Math.max(MIN_WIDTH, window.innerWidth - margin - start.left);
972 const maxHeight = Math.max(MIN_HEIGHT, window.innerHeight - margin - start.top);
973 setSize({
974 width: Math.min(Math.max(start.width + event.clientX - start.pointerX, MIN_WIDTH), maxWidth),
975 height: Math.min(
976 Math.max(start.height + event.clientY - start.pointerY, MIN_HEIGHT),
977 maxHeight,
978 ),
979 });
980 };
981
982 const endResize = () => {
983 resizeStartRef.current = null;
984 };
985
986 return (
987 <div
988 aria-label={isEditing ? "Edit theme" : "Create theme"}
989 className={cn(
990 "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",
991 position === null && "bottom-4 right-4",
992 isMinimized && "max-h-none",
993 )}
994 data-theme-editor-panel
995 ref={panelRef}
996 role="dialog"
997 style={{
998 ...(position ? { left: position.x, top: position.y } : {}),
999 ...(size ? { width: size.width } : {}),
1000 // A chosen height only applies expanded; minimized keeps hugging the
1001 // header. The viewport stays the ceiling either way.
1002 ...(size && !isMinimized ? { height: size.height, maxHeight: "calc(100dvh - 1rem)" } : {}),
1003 }}
1004 >
1005 <div
1006 className="flex cursor-grab touch-none select-none items-center gap-1 border-b border-border/70 px-3 py-2 active:cursor-grabbing"
1007 onPointerCancel={endDrag}
1008 onPointerDown={handleDragPointerDown}
1009 onPointerMove={handleDragPointerMove}
1010 onPointerUp={endDrag}
1011 >
1012 <div className="flex min-w-0 flex-1 items-baseline gap-2">
1013 <h2 className="shrink-0 truncate text-sm font-medium">
1014 {isEditing ? "Edit theme" : "Create theme"}
1015 </h2>
1016 {isMinimized ? null : (
1017 <p className="truncate text-xs text-muted-foreground">
1018 {isInspecting
1019 ? "Select an element · Esc to cancel"
1020 : selectedRole
1021 ? `${getThemeRoleLabel(selectedRole)} · ${usageCount ?? 0} ${usageCount === 1 ? "use" : "uses"}`
1022 : "Select a color below"}
1023 </p>
1024 )}
1025 </div>
1026 <Tooltip>
1027 <TooltipTrigger
1028 render={
1029 <Button
1030 aria-label={isInspecting ? "Cancel inspecting app colors" : "Inspect app colors"}
1031 aria-pressed={isInspecting}
1032 size="xs"
1033 variant={isInspecting ? "secondary" : "ghost"}
1034 onClick={() => {
1035 if (isInspecting) {
1036 clearInspectorSelection();
1037 return;
1038 }
1039 setIsInspecting(true);
1040 }}
1041 >
1042 <MousePointer2Icon />
1043 {isInspecting ? "Cancel" : "Inspect"}
1044 </Button>
1045 }
1046 />
1047 <TooltipPopup data-theme-editor-panel="">
1048 {isInspecting ? "Cancel and clear the selection" : "Pick a color from the app"}
1049 </TooltipPopup>
1050 </Tooltip>
1051 <Button
1052 aria-label={isMinimized ? "Expand the theme editor" : "Minimize the theme editor"}
1053 size="icon-xs"
1054 variant="ghost"
1055 onClick={() => setIsMinimized(!isMinimized)}
1056 >
1057 {isMinimized ? <ChevronUpIcon /> : <ChevronDownIcon />}
1058 </Button>
1059 <Button
1060 aria-label="Close the theme editor"
1061 size="icon-xs"
1062 variant="ghost"
1063 onClick={() => onOpenChange(false)}
1064 >
1065 <XIcon />
1066 </Button>
1067 </div>
1068
1069 {isMinimized ? null : (
1070 <>
1071 <div className="min-h-0 flex-1 space-y-3 overflow-y-auto py-3 pl-3 pr-1.5">
1072 {renderNameField()}
1073 {/* Inline and above the color list: the panel scrolls, and an
1074 error parked below every role would go unseen. */}
1075 {error ? (
1076 <p aria-live="polite" className="text-sm text-destructive">
1077 {error}
1078 </p>
1079 ) : null}
1080 {renderAppearanceButtons()}
1081 <div className="space-y-3">
1082 {renderColorsHeader()}
1083 {renderColorFields()}
1084 </div>
1085 </div>
1086 <div className="flex items-center justify-end gap-2 border-t border-border/70 px-3 py-2">
1087 <Button size="sm" variant="ghost" onClick={() => onOpenChange(false)}>
1088 Cancel
1089 </Button>
1090 <Button disabled={!name.trim()} size="sm" onClick={handleSubmit}>
1091 {isEditing ? (
1092 mergeTarget ? (
1093 `Merge into “${mergeTarget.label}”`
1094 ) : (
1095 "Save changes"
1096 )
1097 ) : mergeTarget ? (
1098 <>
1099 <PlusIcon />
1100 {`Add ${activeAppearance} palette`}
1101 </>
1102 ) : (
1103 <>
1104 <PlusIcon />
1105 Create theme
1106 </>
1107 )}
1108 </Button>
1109 </div>
1110 <div
1111 aria-hidden
1112 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"
1113 onPointerCancel={endResize}
1114 onPointerDown={handleResizePointerDown}
1115 onPointerMove={handleResizePointerMove}
1116 onPointerUp={endResize}
1117 >
1118 <svg
1119 className="size-2.5"
1120 fill="none"
1121 stroke="currentColor"
1122 strokeLinecap="round"
1123 strokeWidth="1.2"
1124 viewBox="0 0 8 8"
1125 >
1126 <path d="M7 1 1 7M7 4.5 4.5 7" />
1127 </svg>
1128 </div>
1129 </>
1130 )}
1131 </div>
1132 );
1133}