Open History to see the last commit
1import {
2 CopyIcon,
3 DownloadIcon,
4 PenLineIcon,
5 PlusIcon,
6 Trash2Icon,
7 UploadIcon,
8} from "lucide-react";
9import { useCallback, useEffect, useRef, useState } from "react";
10import { cn } from "../../lib/utils";
11import {
12 getThemeDefinition,
13 getThemeModes,
14 removeCustomTheme,
15 serializeThemeFile,
16 type ThemeAppearance,
17 type ThemeDefinition,
18 type ThemeHalves,
19 T3_CHAT_THEME,
20 EMBER_THEME,
21 GROVE_THEME,
22 IRIS_THEME,
23 OCEAN_THEME,
24} from "../../themePalette";
25import {
26 AlertDialog,
27 AlertDialogClose,
28 AlertDialogDescription,
29 AlertDialogFooter,
30 AlertDialogHeader,
31 AlertDialogPopup,
32 AlertDialogTitle,
33} from "../ui/alert-dialog";
34import { Button } from "../ui/button";
35import { stackedThreadToast, toastManager } from "../ui/toast";
36import { Tooltip, TooltipPopup, TooltipProvider, TooltipTrigger } from "../ui/tooltip";
37import { ThemeImportDialog } from "./ThemeImportDialog";
38import { useThemeEditorStore } from "./themeEditorStore";
39import {
40 STANDARD_THEME_CARDS,
41 getThemeCardDefinition,
42 previewColorsOf,
43 ThemePreviewCircles,
44 type ThemeCardDefinition,
45 type ThemeMode,
46} from "./ThemePreviewCircles";
47import { ThemeWireframe } from "./ThemeWireframe";
48
49const MAINTAINER_THEMES: ReadonlyArray<ThemeDefinition> = [
50 T3_CHAT_THEME,
51 GROVE_THEME,
52 OCEAN_THEME,
53 EMBER_THEME,
54 IRIS_THEME,
55];
56
57function downloadThemeFile(filename: string, contents: string): void {
58 const url = URL.createObjectURL(new Blob([contents], { type: "application/json" }));
59 const anchor = document.createElement("a");
60 anchor.href = url;
61 anchor.download = filename;
62 anchor.click();
63 // Revoking synchronously can abort the download in some browsers; give the
64 // browser time to open the stream first.
65 setTimeout(() => URL.revokeObjectURL(url), 30_000);
66}
67
68function ThemeLibraryCard({
69 theme,
70 isActive,
71 onUse,
72 onUseMode,
73 activeModes,
74 onEdit,
75 onDuplicate,
76 onDownload,
77 onRemove,
78}: {
79 theme: ThemeCardDefinition;
80 isActive: boolean;
81 onUse: () => void;
82 onUseMode: (mode: ThemeMode) => void;
83 activeModes: ReadonlyArray<ThemeMode>;
84 onEdit?: () => void;
85 onDuplicate?: () => void;
86 onDownload?: () => void;
87 onRemove?: () => void;
88}) {
89 // A one-appearance theme can only take its own side of the mix, so the card
90 // tooltip promises exactly what clicking it does.
91 const cardModes = theme.previews.map((preview) => preview.mode);
92 return (
93 // The card surface stays a plain div (buttons cannot nest inside a button
94 // role); the title button and mode circles carry the accessible actions,
95 // while the card click is a pointer-only convenience.
96 <Tooltip>
97 <TooltipTrigger
98 render={
99 <div
100 className={cn(
101 "cursor-pointer overflow-hidden rounded-xl border border-border/70 bg-card/60 transition-colors hover:bg-accent/10",
102 isActive && "bg-accent/30",
103 )}
104 data-theme-library-card={theme.id}
105 onClick={onUse}
106 style={isActive ? { boxShadow: "inset 0 0 0 1px var(--ring)" } : undefined}
107 >
108 <ThemePreviewCircles
109 label={theme.label}
110 activeModes={activeModes}
111 onSelectMode={onUseMode}
112 previews={theme.previews}
113 />
114 <div className="flex items-center gap-2 px-3 pb-3 pt-2">
115 <div className="min-w-0 flex-1">
116 <div className="flex items-center gap-1.5">
117 <button
118 aria-label={`Use ${theme.label} theme${isActive ? ", currently active" : ""}`}
119 aria-pressed={isActive}
120 className="min-w-0 cursor-pointer truncate rounded-sm text-left text-sm font-medium text-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-card"
121 type="button"
122 onClick={(event) => {
123 event.stopPropagation();
124 onUse();
125 }}
126 >
127 {theme.label}
128 </button>
129 </div>
130 </div>
131 {onEdit || onDuplicate || onDownload || onRemove ? (
132 <div className="flex shrink-0 items-center gap-1">
133 {onDuplicate ? (
134 <Tooltip>
135 <TooltipTrigger
136 render={
137 <Button
138 aria-label={`Duplicate ${theme.label}`}
139 size="icon-xs"
140 variant="ghost"
141 onClick={(event) => {
142 event.stopPropagation();
143 onDuplicate();
144 }}
145 >
146 <CopyIcon />
147 </Button>
148 }
149 />
150 <TooltipPopup>Duplicate theme</TooltipPopup>
151 </Tooltip>
152 ) : null}
153 {onEdit ? (
154 <Tooltip>
155 <TooltipTrigger
156 render={
157 <Button
158 aria-label={`Edit ${theme.label}`}
159 size="icon-xs"
160 variant="ghost"
161 onClick={(event) => {
162 event.stopPropagation();
163 onEdit();
164 }}
165 >
166 <PenLineIcon />
167 </Button>
168 }
169 />
170 <TooltipPopup>Edit theme</TooltipPopup>
171 </Tooltip>
172 ) : null}
173 {onDownload ? (
174 <Tooltip>
175 <TooltipTrigger
176 render={
177 <Button
178 aria-label={`Export ${theme.label}`}
179 size="icon-xs"
180 variant="ghost"
181 onClick={(event) => {
182 event.stopPropagation();
183 onDownload();
184 }}
185 >
186 <DownloadIcon />
187 </Button>
188 }
189 />
190 <TooltipPopup>Export theme file</TooltipPopup>
191 </Tooltip>
192 ) : null}
193 {onRemove ? (
194 <Tooltip>
195 <TooltipTrigger
196 render={
197 <Button
198 aria-label={`Remove ${theme.label}`}
199 size="icon-xs"
200 variant="ghost"
201 className="text-muted-foreground hover:text-destructive"
202 onClick={(event) => {
203 event.stopPropagation();
204 onRemove();
205 }}
206 >
207 <Trash2Icon />
208 </Button>
209 }
210 />
211 <TooltipPopup>Remove theme</TooltipPopup>
212 </Tooltip>
213 ) : null}
214 </div>
215 ) : null}
216 </div>
217 </div>
218 }
219 />
220 <TooltipPopup>
221 {cardModes.length > 1 ? "Use for both light and dark" : `Use for ${cardModes[0]} mode only`}
222 </TooltipPopup>
223 </Tooltip>
224 );
225}
226
227export function ThemeLibrary({
228 theme,
229 setTheme,
230 appearanceMode,
231 setAppearanceMode,
232 customThemes,
233 initialAppearance,
234 refreshTheme,
235 isImportOpen,
236 onImportOpenChange,
237 themeHalves,
238 setThemeHalf,
239}: {
240 theme: string;
241 setTheme: (theme: string) => boolean;
242 appearanceMode: ThemeMode;
243 setAppearanceMode: (mode: ThemeMode) => boolean;
244 customThemes: ReadonlyArray<ThemeDefinition>;
245 initialAppearance: ThemeAppearance;
246 refreshTheme: () => void;
247 isImportOpen: boolean;
248 onImportOpenChange: (open: boolean) => void;
249 themeHalves: ThemeHalves | null;
250 setThemeHalf: (appearance: ThemeAppearance, themeId: string | null) => boolean;
251}) {
252 const openThemeEditor = useThemeEditorStore((store) => store.openThemeEditor);
253 const [themeToRemove, setThemeToRemove] = useState<ThemeDefinition | null>(null);
254 // Keep the last removal target so the dialog title stays populated while the
255 // close animation plays after confirming.
256 const lastThemeToRemoveRef = useRef<ThemeDefinition | null>(null);
257 useEffect(() => {
258 if (themeToRemove) lastThemeToRemoveRef.current = themeToRemove;
259 }, [themeToRemove]);
260 const removeDialogTheme = themeToRemove ?? lastThemeToRemoveRef.current;
261
262 const notifyThemeSaveFailure = useCallback(() => {
263 toastManager.add(
264 stackedThreadToast({
265 type: "error",
266 title: "Couldn’t save theme selection",
267 description: "Try again.",
268 }),
269 );
270 }, []);
271
272 const notifyThemeRemovalFailure = useCallback(() => {
273 toastManager.add(
274 stackedThreadToast({
275 type: "error",
276 title: "Couldn’t remove theme",
277 description: "Try again.",
278 }),
279 );
280 }, []);
281
282 const persistTheme = useCallback(
283 (nextTheme: string) => {
284 const didSave = setTheme(nextTheme);
285 if (!didSave) notifyThemeSaveFailure();
286 return didSave;
287 },
288 [notifyThemeSaveFailure, setTheme],
289 );
290
291 const handleRemoveTheme = useCallback((customTheme: ThemeDefinition) => {
292 setThemeToRemove(customTheme);
293 }, []);
294
295 const handleConfirmRemoveTheme = useCallback(() => {
296 if (!themeToRemove) return;
297 const removesBase = getThemeDefinition(theme)?.id === themeToRemove.id;
298 // Keep the theme installed if we cannot move the selection off it; the
299 // dialog stays open so the user can retry or cancel.
300 if (removesBase && !persistTheme(appearanceMode === "system" ? "system" : appearanceMode)) {
301 return;
302 }
303 for (const appearance of ["light", "dark"] as const) {
304 const half = themeHalves?.[appearance];
305 if (half === undefined) continue;
306 // Writing a base preference clears the whole mix, so halves that name a
307 // surviving theme are written back; halves on the removed theme fall
308 // back to the base.
309 const next = half === themeToRemove.id ? null : removesBase ? half : undefined;
310 if (next !== undefined && !setThemeHalf(appearance, next)) {
311 notifyThemeRemovalFailure();
312 return;
313 }
314 }
315 try {
316 removeCustomTheme(themeToRemove.id);
317 } catch {
318 notifyThemeRemovalFailure();
319 return;
320 }
321 setThemeToRemove(null);
322 }, [
323 appearanceMode,
324 notifyThemeRemovalFailure,
325 persistTheme,
326 setThemeHalf,
327 theme,
328 themeHalves,
329 themeToRemove,
330 ]);
331
332 // ----- Automatic-mode mixing -------------------------------------------
333 // The pair model: one theme owns light, one owns dark, and the global
334 // appearance mode (light / dark / auto) decides which is showing.
335 const baseCardId = getThemeDefinition(theme)?.id ?? null;
336 const lightOwner = themeHalves?.light ?? baseCardId;
337 const darkOwner = themeHalves?.dark ?? baseCardId;
338
339 const assignHalf = useCallback(
340 (appearance: ThemeAppearance, cardId: string | null) => {
341 const otherAppearance = appearance === "light" ? "dark" : "light";
342 // Picking the default over a themed base cannot be stored as a half:
343 // the base would still own that appearance. Convert the base into an
344 // explicit half on the other side so this side falls back to default.
345 if (cardId === null && baseCardId !== null) {
346 const otherOwner = themeHalves?.[otherAppearance] ?? baseCardId;
347 if (!persistTheme(appearanceMode === "system" ? "system" : appearanceMode)) return;
348 if (!setThemeHalf(otherAppearance, otherOwner)) {
349 // Best-effort rollback: restore the whole-theme selection rather
350 // than leaving the user with no theme at all.
351 setTheme(theme);
352 notifyThemeSaveFailure();
353 }
354 return;
355 }
356 if (!setThemeHalf(appearance, cardId)) {
357 notifyThemeSaveFailure();
358 }
359 },
360 [
361 appearanceMode,
362 baseCardId,
363 notifyThemeSaveFailure,
364 persistTheme,
365 setTheme,
366 setThemeHalf,
367 theme,
368 themeHalves,
369 ],
370 );
371
372 // "Create theme" starts from whatever is on screen for the appearance being
373 // edited, so tuning the theme you already use never means rebuilding it.
374 const activeThemeForAppearance =
375 getThemeDefinition((initialAppearance === "light" ? lightOwner : darkOwner) ?? "") ?? null;
376
377 const cardDefById = (id: string | null): ThemeCardDefinition => {
378 if (id === null) return STANDARD_THEME_CARDS[0]!;
379 const definition = getThemeDefinition(id);
380 return definition ? getThemeCardDefinition(definition) : STANDARD_THEME_CARDS[0]!;
381 };
382
383 const pickColors = (id: string | null, appearance: ThemeAppearance) => {
384 const card = cardDefById(id);
385 return previewColorsOf(card, appearance) ?? card.previews[0]!.colors;
386 };
387
388 const setMode = (mode: ThemeMode) => {
389 if (!setAppearanceMode(mode)) notifyThemeSaveFailure();
390 };
391
392 // ----- Wireframe tiles on top, two-ball cards below --------------------
393 const handlePairPick = (cardId: string | null) => (mode: ThemeMode) => {
394 if (mode === "system") return;
395 assignHalf(mode, cardId);
396 };
397
398 // Rings always show the effective owner of each appearance: an unpicked
399 // half belongs to the default card (a null owner), so a fresh install
400 // shows T3 Code selected instead of nothing.
401 const pickedModesFor = (cardId: string | null): ThemeMode[] => {
402 const rings: ThemeMode[] = [];
403 if (lightOwner === cardId) rings.push("light");
404 if (darkOwner === cardId) rings.push("dark");
405 return rings;
406 };
407
408 const wireframeColors = (appearance: ThemeAppearance) =>
409 pickColors(appearance === "light" ? lightOwner : darkOwner, appearance);
410
411 const renderWireframe = (mode: ThemeMode) => (
412 <ThemeWireframe
413 className="h-[8.75rem]"
414 panes={
415 mode === "system"
416 ? [
417 { clip: "left", colors: wireframeColors("light") },
418 { clip: "right", colors: wireframeColors("dark") },
419 ]
420 : [{ colors: wireframeColors(mode === "dark" ? "dark" : "light") }]
421 }
422 />
423 );
424
425 const renderModeTiles = () => (
426 <div
427 aria-label="Appearance mode"
428 className="mx-auto grid w-full max-w-[56rem] grid-cols-3 gap-3 px-3 sm:px-4"
429 role="group"
430 >
431 {(["system", "light", "dark"] as const).map((mode) => {
432 const isActive = appearanceMode === mode;
433 return (
434 <button
435 aria-label={mode === "system" ? "Follow the system appearance" : `Use ${mode} mode`}
436 aria-pressed={isActive}
437 className={cn(
438 "flex cursor-pointer flex-col items-stretch gap-1.5 rounded-xl border p-2 outline-none transition-colors focus-visible:ring-2 focus-visible:ring-ring",
439 isActive
440 ? "border-transparent bg-accent/30"
441 : "border-border/70 bg-card/60 hover:bg-accent/10",
442 )}
443 key={mode}
444 style={isActive ? { boxShadow: "inset 0 0 0 1px var(--ring)" } : undefined}
445 onClick={() => setMode(mode)}
446 type="button"
447 >
448 {renderWireframe(mode)}
449 <span
450 className={cn(
451 "flex items-center justify-center text-xs font-medium",
452 isActive ? "text-foreground" : "text-muted-foreground",
453 )}
454 >
455 {mode === "system" ? "System" : mode === "light" ? "Light" : "Dark"}
456 </span>
457 </button>
458 );
459 })}
460 </div>
461 );
462
463 const renderPairGrid = () => (
464 // One shared provider so every tooltip in the grid hands off instantly to
465 // the next hovered trigger instead of stacking on top of it. The card
466 // tooltip briefly showing while crossing between a card's two circles is
467 // accepted — scoping the group tighter makes the handoffs feel sluggish.
468 <TooltipProvider>
469 <div
470 className="mx-auto grid w-full max-w-[56rem] gap-2 px-3 sm:px-4"
471 style={{ gridTemplateColumns: "repeat(auto-fit, minmax(min(100%, 17rem), 1fr))" }}
472 >
473 {STANDARD_THEME_CARDS.map((standardTheme) => (
474 <ThemeLibraryCard
475 activeModes={pickedModesFor(null)}
476 isActive={false}
477 key={standardTheme.id}
478 onUse={() => persistTheme(appearanceMode === "system" ? "system" : appearanceMode)}
479 onUseMode={handlePairPick(null)}
480 theme={standardTheme}
481 />
482 ))}
483 {MAINTAINER_THEMES.map((maintainerTheme) => {
484 const card = getThemeCardDefinition(maintainerTheme);
485 return (
486 <ThemeLibraryCard
487 activeModes={pickedModesFor(maintainerTheme.id)}
488 isActive={false}
489 key={maintainerTheme.id}
490 onDuplicate={() =>
491 openThemeEditor({
492 editingThemeId: null,
493 seedThemeId: maintainerTheme.id,
494 seedName: `${maintainerTheme.label} copy`,
495 initialAppearance,
496 })
497 }
498 onUse={() => persistTheme(maintainerTheme.id)}
499 onUseMode={handlePairPick(maintainerTheme.id)}
500 theme={card}
501 />
502 );
503 })}
504 {customThemes.map((customTheme) => {
505 const card = getThemeCardDefinition(customTheme);
506 return (
507 <ThemeLibraryCard
508 activeModes={pickedModesFor(customTheme.id)}
509 isActive={false}
510 key={customTheme.id}
511 onDuplicate={() =>
512 openThemeEditor({
513 editingThemeId: null,
514 seedThemeId: customTheme.id,
515 seedName: `${customTheme.label} copy`,
516 initialAppearance,
517 })
518 }
519 onEdit={() =>
520 openThemeEditor({
521 editingThemeId: customTheme.id,
522 seedThemeId: null,
523 seedName: null,
524 initialAppearance,
525 })
526 }
527 onDownload={() =>
528 downloadThemeFile(`${customTheme.id}.json`, serializeThemeFile(customTheme))
529 }
530 onRemove={() => handleRemoveTheme(customTheme)}
531 onUse={() => {
532 const modes = getThemeModes(customTheme);
533 if (modes.length === 1) assignHalf(modes[0]!, customTheme.id);
534 else persistTheme(customTheme.id);
535 }}
536 onUseMode={handlePairPick(customTheme.id)}
537 theme={card}
538 />
539 );
540 })}
541 </div>
542 </TooltipProvider>
543 );
544
545 return (
546 <div className="space-y-3">
547 <p className="px-3 text-[13px] leading-[1.45] text-muted-foreground/80 sm:px-4">
548 Choose how T3 Code looks. Use a built-in theme or make your own.
549 </p>
550 <h3 className="px-3 text-sm font-medium tracking-[-0.005em] text-foreground sm:px-4">
551 Color scheme
552 </h3>
553 {renderModeTiles()}
554 <div className="flex min-h-8 flex-wrap items-center justify-between gap-3 px-3 pt-2 sm:px-4">
555 <h3 className="text-sm font-medium tracking-[-0.005em] text-foreground">Themes</h3>
556 <div className="flex flex-wrap items-center justify-end gap-3">
557 <Button
558 className="h-7 rounded-md border border-border/70 bg-muted/30 px-2 text-xs font-medium text-foreground shadow-none hover:bg-accent/40"
559 size="xs"
560 variant="ghost"
561 onClick={() =>
562 openThemeEditor({
563 editingThemeId: null,
564 seedThemeId: activeThemeForAppearance?.id ?? null,
565 seedName: null,
566 initialAppearance,
567 })
568 }
569 >
570 <PlusIcon />
571 Create theme
572 </Button>
573 <Button size="xs" variant="ghost" onClick={() => onImportOpenChange(true)}>
574 <UploadIcon />
575 Import theme
576 </Button>
577 </div>
578 </div>
579 {renderPairGrid()}
580 <ThemeImportDialog
581 onImportedMany={(importedThemes, { updated }) => {
582 // An updated theme that is showing (as the base or either half)
583 // needs its palette re-applied.
584 if (
585 updated &&
586 importedThemes.some(
587 (imported) =>
588 getThemeDefinition(theme)?.id === imported.id ||
589 themeHalves?.light === imported.id ||
590 themeHalves?.dark === imported.id,
591 )
592 ) {
593 refreshTheme();
594 }
595 const verb = updated ? "updated" : "added";
596 toastManager.add(
597 stackedThreadToast({
598 type: "success",
599 title:
600 importedThemes.length === 1
601 ? `${importedThemes[0]!.label} ${verb}`
602 : `${importedThemes.length} themes ${verb}`,
603 description: importedThemes.map((imported) => imported.label).join(", "),
604 }),
605 );
606 }}
607 onImported={(importedTheme) => {
608 // Same rule as clicking the card: a one-appearance theme takes its
609 // side of the mix instead of becoming the base for both.
610 const modes = getThemeModes(importedTheme);
611 if (modes.length === 1) {
612 assignHalf(modes[0]!, importedTheme.id);
613 toastManager.add(
614 stackedThreadToast({
615 type: "success",
616 title: `${importedTheme.label} added`,
617 description: `It’s now your ${modes[0]!} theme.`,
618 }),
619 );
620 return true;
621 }
622 if (!persistTheme(importedTheme.id)) return false;
623 toastManager.add(
624 stackedThreadToast({
625 type: "success",
626 title: `${importedTheme.label} added`,
627 description: "It’s now active.",
628 }),
629 );
630 return true;
631 }}
632 onOpenChange={onImportOpenChange}
633 open={isImportOpen}
634 />
635 <AlertDialog
636 open={themeToRemove !== null}
637 onOpenChange={(open) => {
638 if (!open) setThemeToRemove(null);
639 }}
640 >
641 <AlertDialogPopup>
642 <AlertDialogHeader>
643 <AlertDialogTitle>Remove “{removeDialogTheme?.label}”?</AlertDialogTitle>
644 <AlertDialogDescription>
645 You can bring it back anytime by importing its JSON file.
646 </AlertDialogDescription>
647 </AlertDialogHeader>
648 <AlertDialogFooter>
649 <AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>
650 <Button variant="destructive" onClick={handleConfirmRemoveTheme}>
651 Remove theme
652 </Button>
653 </AlertDialogFooter>
654 </AlertDialogPopup>
655 </AlertDialog>
656 </div>
657 );
658}