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

ThemeEditorPanel.tsx

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