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

ThemeEditorPanel.tsx

1,143 lines42.0 KB

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