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 <UploadIcon />
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 onDuplicate={() =>
479 openThemeEditor({
480 editingThemeId: null,
481 seedThemeId: null,
482 seedName: `${standardTheme.label} copy`,
483 initialAppearance,
484 })
485 }
486 onUse={() => persistTheme(appearanceMode === "system" ? "system" : appearanceMode)}
487 onUseMode={handlePairPick(null)}
488 theme={standardTheme}
489 />
490 ))}
491 {MAINTAINER_THEMES.map((maintainerTheme) => {
492 const card = getThemeCardDefinition(maintainerTheme);
493 return (
494 <ThemeLibraryCard
495 activeModes={pickedModesFor(maintainerTheme.id)}
496 isActive={false}
497 key={maintainerTheme.id}
498 onDuplicate={() =>
499 openThemeEditor({
500 editingThemeId: null,
501 seedThemeId: maintainerTheme.id,
502 seedName: `${maintainerTheme.label} copy`,
503 initialAppearance,
504 })
505 }
506 onUse={() => persistTheme(maintainerTheme.id)}
507 onUseMode={handlePairPick(maintainerTheme.id)}
508 theme={card}
509 />
510 );
511 })}
512 {customThemes.map((customTheme) => {
513 const card = getThemeCardDefinition(customTheme);
514 return (
515 <ThemeLibraryCard
516 activeModes={pickedModesFor(customTheme.id)}
517 isActive={false}
518 key={customTheme.id}
519 onDuplicate={() =>
520 openThemeEditor({
521 editingThemeId: null,
522 seedThemeId: customTheme.id,
523 seedName: `${customTheme.label} copy`,
524 initialAppearance,
525 })
526 }
527 onEdit={() =>
528 openThemeEditor({
529 editingThemeId: customTheme.id,
530 seedThemeId: null,
531 seedName: null,
532 initialAppearance,
533 })
534 }
535 onDownload={() =>
536 downloadThemeFile(`${customTheme.id}.json`, serializeThemeFile(customTheme))
537 }
538 onRemove={() => handleRemoveTheme(customTheme)}
539 onUse={() => {
540 const modes = getThemeModes(customTheme);
541 if (modes.length === 1) assignHalf(modes[0]!, customTheme.id);
542 else persistTheme(customTheme.id);
543 }}
544 onUseMode={handlePairPick(customTheme.id)}
545 theme={card}
546 />
547 );
548 })}
549 </div>
550 </TooltipProvider>
551 );
552
553 return (
554 <div className="space-y-3">
555 <p className="px-3 text-[13px] leading-[1.45] text-muted-foreground/80 sm:px-4">
556 Choose how T3 Code looks. Use a built-in theme or make your own.
557 </p>
558 <h3 className="px-3 text-sm font-medium tracking-[-0.005em] text-foreground sm:px-4">
559 Color scheme
560 </h3>
561 {renderModeTiles()}
562 <div className="flex min-h-8 flex-wrap items-center justify-between gap-3 px-3 pt-2 sm:px-4">
563 <h3 className="text-sm font-medium tracking-[-0.005em] text-foreground">Themes</h3>
564 <div className="flex flex-wrap items-center justify-end gap-3">
565 <Button
566 size="xs"
567 variant="outline"
568 onClick={() =>
569 openThemeEditor({
570 editingThemeId: null,
571 seedThemeId: activeThemeForAppearance?.id ?? null,
572 seedName: null,
573 initialAppearance,
574 })
575 }
576 >
577 <PlusIcon />
578 Create theme
579 </Button>
580 <Button size="xs" variant="outline" onClick={() => onImportOpenChange(true)}>
581 <DownloadIcon />
582 Import theme
583 </Button>
584 </div>
585 </div>
586 {renderPairGrid()}
587 <ThemeImportDialog
588 onImportedMany={(importedThemes, { updated }) => {
589 // An updated theme that is showing (as the base or either half)
590 // needs its palette re-applied.
591 if (
592 updated &&
593 importedThemes.some(
594 (imported) =>
595 getThemeDefinition(theme)?.id === imported.id ||
596 themeHalves?.light === imported.id ||
597 themeHalves?.dark === imported.id,
598 )
599 ) {
600 refreshTheme();
601 }
602 const verb = updated ? "updated" : "added";
603 toastManager.add(
604 stackedThreadToast({
605 type: "success",
606 title:
607 importedThemes.length === 1
608 ? `${importedThemes[0]!.label} ${verb}`
609 : `${importedThemes.length} themes ${verb}`,
610 description: importedThemes.map((imported) => imported.label).join(", "),
611 }),
612 );
613 }}
614 onImported={(importedTheme) => {
615 // Same rule as clicking the card: a one-appearance theme takes its
616 // side of the mix instead of becoming the base for both.
617 const modes = getThemeModes(importedTheme);
618 if (modes.length === 1) {
619 assignHalf(modes[0]!, importedTheme.id);
620 toastManager.add(
621 stackedThreadToast({
622 type: "success",
623 title: `${importedTheme.label} added`,
624 description: `It’s now your ${modes[0]!} theme.`,
625 }),
626 );
627 return true;
628 }
629 if (!persistTheme(importedTheme.id)) return false;
630 toastManager.add(
631 stackedThreadToast({
632 type: "success",
633 title: `${importedTheme.label} added`,
634 description: "It’s now active.",
635 }),
636 );
637 return true;
638 }}
639 onOpenChange={onImportOpenChange}
640 open={isImportOpen}
641 />
642 <AlertDialog
643 open={themeToRemove !== null}
644 onOpenChange={(open) => {
645 if (!open) setThemeToRemove(null);
646 }}
647 >
648 <AlertDialogPopup>
649 <AlertDialogHeader>
650 <AlertDialogTitle>Remove “{removeDialogTheme?.label}”?</AlertDialogTitle>
651 <AlertDialogDescription>
652 You can bring it back anytime by importing its JSON file.
653 </AlertDialogDescription>
654 </AlertDialogHeader>
655 <AlertDialogFooter>
656 <AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>
657 <Button variant="destructive" onClick={handleConfirmRemoveTheme}>
658 Remove theme
659 </Button>
660 </AlertDialogFooter>
661 </AlertDialogPopup>
662 </AlertDialog>
663 </div>
664 );
665}