Open History to see the last commit
1import {
2 CheckIcon,
3 CopyIcon,
4 MoonIcon,
5 PaintbrushIcon,
6 PenLineIcon,
7 PlusIcon,
8 SunIcon,
9 Trash2Icon,
10 UploadIcon,
11} from "lucide-react";
12import { useState, type ReactElement } from "react";
13import { useEnvironmentThemeDefinitions } from "../../hooks/useEnvironmentTheme";
14import { readThemeHalvesRaw } from "../../hooks/useTheme";
15import { cn } from "../../lib/utils";
16import {
17 getThemeDefinition,
18 singleAppearanceOf,
19 getThemeModes,
20 removeCustomThemes,
21 serializeThemeFile,
22 type ThemeAppearance,
23 type ThemeDefinition,
24 type ThemeHalves,
25 T3_CHAT_THEME,
26 EMBER_THEME,
27 GROVE_THEME,
28 IRIS_THEME,
29 OCEAN_THEME,
30} from "../../themePalette";
31import {
32 AlertDialog,
33 AlertDialogClose,
34 AlertDialogDescription,
35 AlertDialogFooter,
36 AlertDialogHeader,
37 AlertDialogPopup,
38 AlertDialogTitle,
39} from "../ui/alert-dialog";
40import { Button } from "../ui/button";
41import { stackedThreadToast, toastManager } from "../ui/toast";
42import { Tooltip, TooltipPopup, TooltipProvider, TooltipTrigger } from "../ui/tooltip";
43import { ThemeImportDialog } from "./ThemeImportDialog";
44import { searchableSetting } from "./settingsSearch";
45import { useThemeEditorStore } from "./themeEditorStore";
46import {
47 STANDARD_THEME_CARDS,
48 getThemeCardDefinition,
49 previewColorsOf,
50 ThemePreviewCircles,
51 ThemePreviewCircle,
52 type ThemeCardDefinition,
53 type ThemeMode,
54} from "./ThemePreviewCircles";
55import { ThemeWireframe } from "./ThemeWireframe";
56
57const MAINTAINER_THEMES: ReadonlyArray<ThemeDefinition> = [
58 T3_CHAT_THEME,
59 GROVE_THEME,
60 OCEAN_THEME,
61 EMBER_THEME,
62 IRIS_THEME,
63];
64
65function collectionVariantLabels(themes: ReadonlyArray<ThemeDefinition>): ReadonlyArray<string> {
66 if (themes.length === 0) return [];
67 const words = themes.map((theme) => theme.label.trim().split(/\s+/));
68 const firstWords = words[0]!;
69 const sharedWordCount = firstWords.findIndex((word, index) =>
70 words.some((labelWords) => labelWords[index]?.toLocaleLowerCase() !== word.toLocaleLowerCase()),
71 );
72 const prefixLength = sharedWordCount === -1 ? firstWords.length - 1 : sharedWordCount;
73
74 return themes.map((theme, index) => {
75 const shortLabel = words[index]?.slice(Math.max(0, prefixLength)).join(" ").trim();
76 return shortLabel || theme.label;
77 });
78}
79
80function downloadThemeFile(filename: string, contents: string): void {
81 const url = URL.createObjectURL(new Blob([contents], { type: "application/json" }));
82 const anchor = document.createElement("a");
83 anchor.href = url;
84 anchor.download = filename;
85 anchor.click();
86 // Revoking synchronously can abort the download in some browsers; give the
87 // browser time to open the stream first.
88 setTimeout(() => URL.revokeObjectURL(url), 30_000);
89}
90
91function ThemeVariantTooltip({ label, children }: { label: string; children: ReactElement }) {
92 return (
93 <Tooltip>
94 <TooltipTrigger render={children} />
95 <TooltipPopup>{label}</TooltipPopup>
96 </Tooltip>
97 );
98}
99
100function ThemeLibraryCard({
101 theme,
102 isActive,
103 onUse,
104 onUseMode,
105 activeModes,
106 onEdit,
107 onDuplicate,
108 onDownload,
109 onRemove,
110 variantNavigation,
111}: {
112 theme: ThemeCardDefinition;
113 isActive: boolean;
114 onUse: () => void;
115 onUseMode: (mode: ThemeMode) => void;
116 activeModes: ReadonlyArray<ThemeMode>;
117 onEdit?: () => void;
118 onDuplicate?: () => void;
119 onDownload?: () => void;
120 onRemove?: () => void;
121 variantNavigation?: {
122 collectionLabel: string;
123 options: ReadonlyArray<{
124 themeIndex: number;
125 label: string;
126 activeModes: ReadonlyArray<ThemeMode>;
127 preview: ThemeCardDefinition["previews"][number];
128 }>;
129 onSelectAndUse: (themeIndex: number, mode: ThemeAppearance) => void;
130 };
131}) {
132 const cardModes = theme.previews.map((preview) => preview.mode);
133 const [radialModeOpen, setRadialModeOpen] = useState<ThemeAppearance | null>(null);
134 const radialModeGroups = (["light", "dark"] as const).map((mode) => {
135 const options =
136 variantNavigation?.options.flatMap((option) => {
137 const preview = option.preview;
138 return preview.mode === mode ? [{ option, preview }] : [];
139 }) ?? [];
140 return {
141 mode,
142 options,
143 selected: options.find(({ option }) => option.activeModes.includes(mode)) ?? options[0],
144 };
145 });
146 return (
147 <Tooltip>
148 <TooltipTrigger
149 render={
150 <div
151 className={cn(
152 "cursor-pointer overflow-hidden rounded-xl border border-border/70 bg-card/60 transition-colors hover:bg-accent/10",
153 isActive && "bg-accent/30",
154 )}
155 data-theme-library-card={theme.id}
156 onClick={onUse}
157 style={isActive ? { boxShadow: "inset 0 0 0 1px var(--ring)" } : undefined}
158 >
159 <div className="relative">
160 {variantNavigation ? (
161 <div
162 aria-label="Light and dark theme variants"
163 className="relative h-20"
164 role="group"
165 onBlurCapture={(event) => {
166 const nextTarget = event.relatedTarget;
167 if (
168 !(nextTarget instanceof Node) ||
169 !event.currentTarget.contains(nextTarget)
170 ) {
171 setRadialModeOpen(null);
172 }
173 }}
174 onKeyDown={(event) => {
175 if (event.key === "Escape") setRadialModeOpen(null);
176 }}
177 onMouseLeave={() => setRadialModeOpen(null)}
178 >
179 {radialModeGroups.map(({ mode, options, selected }) => {
180 if (!selected) return null;
181 const rootOffsetX = mode === "light" ? -52 : 52;
182 const isOpen = radialModeOpen === mode;
183 const isActive = selected.option.activeModes.includes(mode);
184 const modeLabel = mode === "light" ? "Light" : "Dark";
185 return (
186 <div className="contents" key={mode}>
187 <ThemeVariantTooltip label={`${modeLabel}: ${selected.option.label}`}>
188 <button
189 aria-label={
190 options.length > 1
191 ? `Choose ${mode} variant, ${options.length} options, currently ${selected.option.label}`
192 : `Use ${mode} variant, currently ${selected.option.label}`
193 }
194 aria-pressed={isActive}
195 className="absolute left-1/2 top-2 z-20 flex size-14 items-center justify-center rounded-full outline-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:-outline-offset-2 focus-visible:outline-ring"
196 style={{
197 transform: `translateX(calc(-50% + ${rootOffsetX}px))`,
198 }}
199 type="button"
200 onClick={(event) => {
201 event.stopPropagation();
202 variantNavigation.onSelectAndUse(selected.option.themeIndex, mode);
203 }}
204 onFocus={() => setRadialModeOpen(mode)}
205 onMouseEnter={() => setRadialModeOpen(mode)}
206 >
207 <ThemePreviewCircle
208 colors={selected.preview.colors}
209 mode={selected.preview.mode}
210 />
211 {isActive ? (
212 <span
213 aria-hidden
214 className="pointer-events-none absolute inset-0 rounded-full ring-2 ring-inset ring-ring"
215 />
216 ) : null}
217 {isActive ? (
218 <span className="pointer-events-none absolute -bottom-0.5 -right-0.5 flex size-4 items-center justify-center rounded-full border border-border/70 bg-background text-foreground shadow-sm">
219 {mode === "light" ? (
220 <SunIcon className="size-2.5" />
221 ) : (
222 <MoonIcon className="size-2.5" />
223 )}
224 </span>
225 ) : null}
226 </button>
227 </ThemeVariantTooltip>
228 <span
229 className="pointer-events-none absolute bottom-0 left-1/2 inline-flex max-w-24 -translate-x-1/2 items-center gap-1 text-2xs font-medium text-foreground"
230 style={{ marginLeft: rootOffsetX }}
231 >
232 <span className="truncate">{selected.option.label}</span>
233 {options.length > 1 ? (
234 <span className="shrink-0 rounded-full bg-muted px-1 text-3xs text-muted-foreground">
235 +{options.length - 1}
236 </span>
237 ) : null}
238 </span>
239 {options.length > 1
240 ? options.map(({ option, preview }, optionIndex) => {
241 const progress = optionIndex / (options.length - 1) - 0.5;
242 const childOffsetX = rootOffsetX + progress * 68;
243 const childOffsetY = Math.abs(progress) * 10;
244 const optionIsActive = option.activeModes.includes(mode);
245 return (
246 <ThemeVariantTooltip
247 key={option.label}
248 label={`Use ${option.label} for ${mode} mode`}
249 >
250 <button
251 aria-label={`Use ${option.label} for ${mode} mode${optionIsActive ? ", currently active" : ""}`}
252 aria-pressed={optionIsActive}
253 className={cn(
254 "absolute left-1/2 top-1 z-30 flex size-7 items-center justify-center rounded-full bg-background shadow-sm outline-none transition-[opacity,transform] duration-200 ease-out motion-reduce:transition-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",
255 optionIsActive
256 ? "ring-2 ring-inset ring-ring"
257 : "ring-1 ring-border/70",
258 )}
259 style={{
260 opacity: isOpen ? 1 : 0,
261 pointerEvents: isOpen ? "auto" : "none",
262 transform: `translate(calc(-50% + ${isOpen ? childOffsetX : rootOffsetX}px), ${isOpen ? childOffsetY : 28}px) scale(${isOpen ? 1 : 0.55})`,
263 transitionDelay: isOpen ? `${optionIndex * 35}ms` : "0ms",
264 }}
265 type="button"
266 onClick={(event) => {
267 event.stopPropagation();
268 variantNavigation.onSelectAndUse(option.themeIndex, mode);
269 }}
270 onFocus={() => setRadialModeOpen(mode)}
271 onMouseEnter={() => setRadialModeOpen(mode)}
272 >
273 <span className="pointer-events-none scale-[0.43]">
274 <ThemePreviewCircle
275 colors={preview.colors}
276 mode={preview.mode}
277 />
278 </span>
279 </button>
280 </ThemeVariantTooltip>
281 );
282 })
283 : null}
284 </div>
285 );
286 })}
287 </div>
288 ) : (
289 <ThemePreviewCircles
290 label={theme.label}
291 activeModes={activeModes}
292 onSelectMode={onUseMode}
293 previews={theme.previews}
294 />
295 )}
296 </div>
297 <div className="flex items-center gap-2 px-3 pb-3 pt-2">
298 <div className="min-w-0 flex-1">
299 <div className="flex items-center gap-1.5">
300 <button
301 aria-label={`Use ${variantNavigation ? `${variantNavigation.collectionLabel}, ${theme.label} variant` : `${theme.label} theme`}${isActive ? ", currently active" : ""}`}
302 aria-pressed={isActive}
303 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-inset focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-card"
304 type="button"
305 onClick={(event) => {
306 event.stopPropagation();
307 onUse();
308 }}
309 >
310 {variantNavigation?.collectionLabel ?? theme.label}
311 </button>
312 </div>
313 </div>
314 {onEdit || onDuplicate || onDownload || onRemove ? (
315 <div className="flex shrink-0 items-center gap-1">
316 {onDuplicate ? (
317 <Tooltip>
318 <TooltipTrigger
319 render={
320 <Button
321 aria-label={`Duplicate ${theme.label}`}
322 size="icon-xs"
323 variant="ghost"
324 onClick={(event) => {
325 event.stopPropagation();
326 onDuplicate();
327 }}
328 >
329 <CopyIcon />
330 </Button>
331 }
332 />
333 <TooltipPopup>Duplicate theme</TooltipPopup>
334 </Tooltip>
335 ) : null}
336 {onEdit ? (
337 <Tooltip>
338 <TooltipTrigger
339 render={
340 <Button
341 aria-label={`Edit ${theme.label}`}
342 size="icon-xs"
343 variant="ghost"
344 onClick={(event) => {
345 event.stopPropagation();
346 onEdit();
347 }}
348 >
349 <PenLineIcon />
350 </Button>
351 }
352 />
353 <TooltipPopup>Edit theme</TooltipPopup>
354 </Tooltip>
355 ) : null}
356 {onDownload ? (
357 <Tooltip>
358 <TooltipTrigger
359 render={
360 <Button
361 aria-label={`Export ${theme.label}`}
362 size="icon-xs"
363 variant="ghost"
364 onClick={(event) => {
365 event.stopPropagation();
366 onDownload();
367 }}
368 >
369 <UploadIcon />
370 </Button>
371 }
372 />
373 <TooltipPopup>Export theme file</TooltipPopup>
374 </Tooltip>
375 ) : null}
376 {onRemove ? (
377 <Tooltip>
378 <TooltipTrigger
379 render={
380 <Button
381 aria-label={
382 variantNavigation
383 ? `Remove themes from ${variantNavigation.collectionLabel}`
384 : `Remove ${theme.label}`
385 }
386 size="icon-xs"
387 variant="ghost-destructive"
388 onClick={(event) => {
389 event.stopPropagation();
390 onRemove();
391 }}
392 >
393 <Trash2Icon />
394 </Button>
395 }
396 />
397 <TooltipPopup>
398 {variantNavigation ? "Remove themes" : "Remove theme"}
399 </TooltipPopup>
400 </Tooltip>
401 ) : null}
402 </div>
403 ) : null}
404 </div>
405 </div>
406 }
407 />
408 <TooltipPopup>
409 {variantNavigation
410 ? "Use the first variants for light and dark"
411 : cardModes.length > 1
412 ? "Use for both light and dark"
413 : `Use for ${cardModes[0]} mode only`}
414 </TooltipPopup>
415 </Tooltip>
416 );
417}
418
419function CustomThemeCollectionCard({
420 themes,
421 activeModesFor,
422 onUse,
423 onUseMode,
424 onDuplicate,
425 onEdit,
426 onDownload,
427 onRemove,
428}: {
429 themes: ReadonlyArray<ThemeDefinition>;
430 activeModesFor: (themeId: string) => ReadonlyArray<ThemeMode>;
431 onUse: (theme: ThemeDefinition) => void;
432 onUseMode: (theme: ThemeDefinition, mode: ThemeMode) => void;
433 onDuplicate: (theme: ThemeDefinition) => void;
434 onEdit: (theme: ThemeDefinition) => void;
435 onDownload: (theme: ThemeDefinition) => void;
436 onRemove: (theme: ThemeDefinition) => void;
437}) {
438 const [variantIndex, setVariantIndex] = useState(() => {
439 const activeIndex = themes.findIndex((theme) => activeModesFor(theme.id).length > 0);
440 return activeIndex < 0 ? 0 : activeIndex;
441 });
442 const safeIndex = Math.min(variantIndex, themes.length - 1);
443 const theme = themes[safeIndex];
444
445 if (variantIndex !== safeIndex) setVariantIndex(safeIndex);
446
447 if (!theme) return null;
448 const collectionLabel = theme.collection?.label ?? theme.label;
449 const variantLabels = collectionVariantLabels(themes);
450 const defaultLightTheme = themes.find((candidate) => getThemeModes(candidate).includes("light"));
451 const defaultDarkTheme = themes.find((candidate) => getThemeModes(candidate).includes("dark"));
452 const selectCollectionDefaults = () => {
453 if (themes.length === 1) {
454 onUse(theme);
455 return;
456 }
457 if (defaultLightTheme) onUseMode(defaultLightTheme, "light");
458 if (defaultDarkTheme) onUseMode(defaultDarkTheme, "dark");
459 setVariantIndex(0);
460 };
461
462 return (
463 <ThemeLibraryCard
464 activeModes={activeModesFor(theme.id)}
465 isActive={false}
466 onDownload={() => onDownload(theme)}
467 onDuplicate={() => onDuplicate(theme)}
468 onEdit={() => onEdit(theme)}
469 onRemove={() => onRemove(theme)}
470 onUse={selectCollectionDefaults}
471 onUseMode={(mode) => onUseMode(theme, mode)}
472 theme={getThemeCardDefinition(theme)}
473 {...(themes.length > 1
474 ? {
475 variantNavigation: {
476 collectionLabel,
477 options: themes.flatMap((variant, themeIndex) =>
478 getThemeCardDefinition(variant).previews.map((preview) => ({
479 themeIndex,
480 label: variantLabels[themeIndex] ?? variant.label,
481 activeModes: activeModesFor(variant.id),
482 preview,
483 })),
484 ),
485 onSelectAndUse: (themeIndex, mode) => {
486 const selectedTheme = themes[themeIndex];
487 if (!selectedTheme) return;
488 setVariantIndex(themeIndex);
489 onUseMode(selectedTheme, mode);
490 },
491 },
492 }
493 : {})}
494 />
495 );
496}
497
498export function ThemeLibrary({
499 theme,
500 setTheme,
501 appearanceMode,
502 setAppearanceMode,
503 customThemes,
504 initialAppearance,
505 refreshTheme,
506 isImportOpen,
507 onImportOpenChange,
508 themeHalves,
509 setThemeHalf,
510}: {
511 theme: string;
512 setTheme: (theme: string) => boolean;
513 appearanceMode: ThemeMode;
514 setAppearanceMode: (mode: ThemeMode) => boolean;
515 customThemes: ReadonlyArray<ThemeDefinition>;
516 initialAppearance: ThemeAppearance;
517 refreshTheme: () => void;
518 isImportOpen: boolean;
519 onImportOpenChange: (open: boolean) => void;
520 themeHalves: ThemeHalves | null;
521 setThemeHalf: (appearance: ThemeAppearance, themeId: string | null) => boolean;
522}) {
523 const openThemeEditor = useThemeEditorStore((store) => store.openThemeEditor);
524 const environmentThemes = useEnvironmentThemeDefinitions();
525 const [themeRemovalTarget, setThemeRemovalTarget] = useState<{
526 theme: ThemeDefinition;
527 collectionThemes: ReadonlyArray<ThemeDefinition>;
528 } | null>(null);
529 const [isThemeRemovalOpen, setIsThemeRemovalOpen] = useState(false);
530 const [themeIdsToRemove, setThemeIdsToRemove] = useState<ReadonlyArray<string>>([]);
531 const themeIdsToRemoveSet = new Set(themeIdsToRemove);
532 const removeDialogTheme = themeRemovalTarget?.theme;
533 const removeDialogCollectionThemes = themeRemovalTarget?.collectionThemes ?? [];
534 const canRemoveCollection = removeDialogCollectionThemes.length > 1;
535 const removeDialogCollectionLabel =
536 removeDialogTheme?.collection?.label ?? removeDialogTheme?.label;
537
538 const notifyThemeSaveFailure = () => {
539 toastManager.add(
540 stackedThreadToast({
541 type: "error",
542 title: "Couldn’t save theme selection",
543 description: "Try again.",
544 }),
545 );
546 };
547
548 const notifyThemeRemovalFailure = () => {
549 toastManager.add(
550 stackedThreadToast({
551 type: "error",
552 title: "Couldn’t remove theme",
553 description: "Try again.",
554 }),
555 );
556 };
557
558 const persistTheme = (nextTheme: string) => {
559 const didSave = setTheme(nextTheme);
560 if (!didSave) notifyThemeSaveFailure();
561 return didSave;
562 };
563
564 const handleRemoveTheme = (
565 customTheme: ThemeDefinition,
566 collectionThemes: ReadonlyArray<ThemeDefinition>,
567 ) => {
568 setThemeRemovalTarget({ theme: customTheme, collectionThemes });
569 setThemeIdsToRemove(collectionThemes.length > 1 ? [] : [customTheme.id]);
570 setIsThemeRemovalOpen(true);
571 };
572
573 const handleConfirmRemoveTheme = () => {
574 if (!themeRemovalTarget) return;
575 const removedIds = new Set(themeIdsToRemove);
576 if (removedIds.size === 0) return;
577 const removesBase = removedIds.has(getThemeDefinition(theme)?.id ?? "");
578 // Captured raw before persistTheme clears the mix: a half naming a
579 // published theme whose set has not streamed in yet is pruned from the
580 // `themeHalves` prop, and rebuilding from that would drop it.
581 const storedHalves = readThemeHalvesRaw();
582 if (removesBase && !persistTheme(appearanceMode === "system" ? "system" : appearanceMode)) {
583 return;
584 }
585 for (const appearance of ["light", "dark"] as const) {
586 const half = storedHalves[appearance];
587 if (half === undefined) continue;
588 const next = half && removedIds.has(half) ? null : removesBase ? half : undefined;
589 if (next !== undefined && !setThemeHalf(appearance, next)) {
590 notifyThemeRemovalFailure();
591 return;
592 }
593 }
594 try {
595 removeCustomThemes([...removedIds]);
596 } catch {
597 notifyThemeRemovalFailure();
598 return;
599 }
600 setIsThemeRemovalOpen(false);
601 };
602
603 const baseCardId = getThemeDefinition(theme)?.id ?? null;
604 const lightOwner = themeHalves?.light ?? baseCardId;
605 const darkOwner = themeHalves?.dark ?? baseCardId;
606
607 const assignHalf = (appearance: ThemeAppearance, cardId: string | null) => {
608 const otherAppearance = appearance === "light" ? "dark" : "light";
609 // Picking the default over a themed base cannot be stored as a half:
610 // the base would still own that appearance. Convert the base into an
611 // explicit half on the other side so this side falls back to default.
612 if (cardId === null && baseCardId !== null) {
613 // Read raw, before persistTheme clears the mix: the other half may
614 // name a published theme that has not streamed in yet, and falling
615 // back to the base would silently rewrite it.
616 const otherOwner = readThemeHalvesRaw()[otherAppearance] ?? baseCardId;
617 if (!persistTheme(appearanceMode === "system" ? "system" : appearanceMode)) return;
618 if (!setThemeHalf(otherAppearance, otherOwner)) {
619 setTheme(theme);
620 notifyThemeSaveFailure();
621 }
622 return;
623 }
624 if (!setThemeHalf(appearance, cardId)) {
625 notifyThemeSaveFailure();
626 }
627 };
628
629 const activeThemeForAppearance =
630 getThemeDefinition((initialAppearance === "light" ? lightOwner : darkOwner) ?? "") ?? null;
631
632 const cardDefById = (id: string | null): ThemeCardDefinition => {
633 if (id === null) return STANDARD_THEME_CARDS[0]!;
634 const definition = getThemeDefinition(id);
635 return definition ? getThemeCardDefinition(definition) : STANDARD_THEME_CARDS[0]!;
636 };
637
638 const pickColors = (id: string | null, appearance: ThemeAppearance) => {
639 const card = cardDefById(id);
640 return previewColorsOf(card, appearance) ?? card.previews[0]!.colors;
641 };
642
643 const setMode = (mode: ThemeMode) => {
644 if (!setAppearanceMode(mode)) notifyThemeSaveFailure();
645 };
646
647 const handlePairPick = (cardId: string | null) => (mode: ThemeMode) => {
648 if (mode === "system") return;
649 assignHalf(mode, cardId);
650 };
651
652 const pickedModesFor = (cardId: string | null): ThemeMode[] => {
653 const rings: ThemeMode[] = [];
654 if (lightOwner === cardId) rings.push("light");
655 if (darkOwner === cardId) rings.push("dark");
656 return rings;
657 };
658
659 const wireframeColors = (appearance: ThemeAppearance) =>
660 pickColors(appearance === "light" ? lightOwner : darkOwner, appearance);
661
662 const renderWireframe = (mode: ThemeMode) => (
663 <ThemeWireframe
664 className="h-[8.75rem]"
665 panes={
666 mode === "system"
667 ? [
668 { clip: "left", colors: wireframeColors("light") },
669 { clip: "right", colors: wireframeColors("dark") },
670 ]
671 : [{ colors: wireframeColors(mode === "dark" ? "dark" : "light") }]
672 }
673 />
674 );
675
676 const renderModeTiles = () => (
677 <div aria-label="Appearance mode" className="grid w-full grid-cols-3 gap-3" role="group">
678 {(["system", "light", "dark"] as const).map((mode) => {
679 const isActive = appearanceMode === mode;
680 return (
681 <button
682 aria-label={mode === "system" ? "Follow the system appearance" : `Use ${mode} mode`}
683 aria-pressed={isActive}
684 className={cn(
685 "flex cursor-pointer flex-col items-stretch gap-1.5 rounded-xl border p-2 outline-none transition-colors focus-visible:outline-2 focus-visible:outline-solid focus-visible:-outline-offset-2 focus-visible:outline-ring",
686 isActive
687 ? "border-transparent bg-accent/30"
688 : "border-border/70 bg-card/60 hover:bg-accent/10",
689 )}
690 key={mode}
691 style={isActive ? { boxShadow: "inset 0 0 0 1px var(--ring)" } : undefined}
692 onClick={() => setMode(mode)}
693 type="button"
694 >
695 {renderWireframe(mode)}
696 <span
697 className={cn(
698 "flex items-center justify-center text-xs font-medium",
699 isActive ? "text-foreground" : "text-muted-foreground",
700 )}
701 >
702 {mode === "system" ? "System" : mode === "light" ? "Light" : "Dark"}
703 </span>
704 </button>
705 );
706 })}
707 </div>
708 );
709
710 const customThemeCollections = [
711 ...customThemes
712 .reduce((groups, customTheme) => {
713 const groupId = customTheme.collection
714 ? `collection:${customTheme.collection.id}`
715 : `theme:${customTheme.id}`;
716 const group = groups.get(groupId);
717 if (group) group.push(customTheme);
718 else groups.set(groupId, [customTheme]);
719 return groups;
720 }, new Map<string, ThemeDefinition[]>())
721 .entries(),
722 ];
723
724 const renderPairGrid = () => (
725 <TooltipProvider>
726 <div
727 className="grid w-full gap-2"
728 style={{ gridTemplateColumns: "repeat(auto-fit, minmax(min(100%, 16rem), 1fr))" }}
729 >
730 {STANDARD_THEME_CARDS.map((standardTheme) => (
731 <ThemeLibraryCard
732 activeModes={pickedModesFor(null)}
733 isActive={false}
734 key={standardTheme.id}
735 onDuplicate={() =>
736 openThemeEditor({
737 editingThemeId: null,
738 seedThemeId: null,
739 seedName: `${standardTheme.label} copy`,
740 initialAppearance,
741 })
742 }
743 onUse={() => persistTheme(appearanceMode === "system" ? "system" : appearanceMode)}
744 onUseMode={handlePairPick(null)}
745 theme={standardTheme}
746 />
747 ))}
748 {MAINTAINER_THEMES.map((maintainerTheme) => {
749 const card = getThemeCardDefinition(maintainerTheme);
750 return (
751 <ThemeLibraryCard
752 activeModes={pickedModesFor(maintainerTheme.id)}
753 isActive={false}
754 key={maintainerTheme.id}
755 onDuplicate={() =>
756 openThemeEditor({
757 editingThemeId: null,
758 seedThemeId: maintainerTheme.id,
759 seedName: `${maintainerTheme.label} copy`,
760 initialAppearance,
761 })
762 }
763 onUse={() => persistTheme(maintainerTheme.id)}
764 onUseMode={handlePairPick(maintainerTheme.id)}
765 theme={card}
766 />
767 );
768 })}
769 {environmentThemes
770 .filter(
771 // A saved theme with the same id wins resolution, so its card is
772 // the one that must show; rendering both would also collide keys.
773 (environmentTheme) => !customThemes.some((theme) => theme.id === environmentTheme.id),
774 )
775 .map((environmentTheme) => (
776 <ThemeLibraryCard
777 activeModes={pickedModesFor(environmentTheme.id)}
778 isActive={false}
779 key={environmentTheme.id}
780 onDuplicate={() =>
781 openThemeEditor({
782 editingThemeId: null,
783 seedThemeId: environmentTheme.id,
784 seedName: `${environmentTheme.label} copy`,
785 initialAppearance,
786 })
787 }
788 onUse={() => {
789 const half = singleAppearanceOf(environmentTheme);
790 if (half === null) persistTheme(environmentTheme.id);
791 else assignHalf(half, environmentTheme.id);
792 }}
793 onUseMode={handlePairPick(environmentTheme.id)}
794 theme={getThemeCardDefinition(environmentTheme)}
795 />
796 ))}
797 {customThemeCollections.map(([collectionId, themes]) => (
798 <CustomThemeCollectionCard
799 activeModesFor={pickedModesFor}
800 key={collectionId}
801 onDownload={(customTheme) =>
802 downloadThemeFile(`${customTheme.id}.json`, serializeThemeFile(customTheme))
803 }
804 onDuplicate={(customTheme) =>
805 openThemeEditor({
806 editingThemeId: null,
807 seedThemeId: customTheme.id,
808 seedName: `${customTheme.label} copy`,
809 initialAppearance,
810 })
811 }
812 onEdit={(customTheme) =>
813 openThemeEditor({
814 editingThemeId: customTheme.id,
815 seedThemeId: null,
816 seedName: null,
817 initialAppearance,
818 })
819 }
820 onRemove={(customTheme) => handleRemoveTheme(customTheme, themes)}
821 onUse={(customTheme) => {
822 const modes = getThemeModes(customTheme);
823 if (modes.length === 1) assignHalf(modes[0]!, customTheme.id);
824 else persistTheme(customTheme.id);
825 }}
826 onUseMode={(customTheme, mode) => handlePairPick(customTheme.id)(mode)}
827 themes={themes}
828 />
829 ))}
830 </div>
831 </TooltipProvider>
832 );
833
834 return (
835 <div className="space-y-3">
836 <h3 className="px-3 text-sm font-normal text-foreground/70 sm:px-4">
837 {searchableSetting("color-scheme").title}
838 </h3>
839 {renderModeTiles()}
840 <div className="flex min-h-8 flex-wrap items-center justify-between gap-3 px-3 pt-2 sm:px-4">
841 <h3 className="text-sm font-normal text-foreground/70">
842 {searchableSetting("theme").title}
843 </h3>
844 <div className="flex flex-wrap items-center justify-end gap-2">
845 <Button
846 size="xs"
847 variant="outline"
848 onClick={() =>
849 openThemeEditor({
850 editingThemeId: null,
851 seedThemeId: activeThemeForAppearance?.id ?? null,
852 seedName: null,
853 initialAppearance,
854 })
855 }
856 >
857 <PaintbrushIcon />
858 Create theme
859 </Button>
860 <Button size="xs" variant="outline" onClick={() => onImportOpenChange(true)}>
861 <PlusIcon />
862 Add theme
863 </Button>
864 </div>
865 </div>
866 {renderPairGrid()}
867 <ThemeImportDialog
868 onImportedMany={(importedThemes, { updated }) => {
869 if (updated) refreshTheme();
870 const verb = updated ? "updated" : "added";
871 toastManager.add(
872 stackedThreadToast({
873 type: "success",
874 title:
875 importedThemes.length === 1
876 ? `${importedThemes[0]!.label} ${verb}`
877 : `${importedThemes.length} themes ${verb}`,
878 description: importedThemes.map((imported) => imported.label).join(", "),
879 }),
880 );
881 }}
882 onImported={(importedTheme) => {
883 const modes = getThemeModes(importedTheme);
884 if (modes.length === 1) {
885 assignHalf(modes[0]!, importedTheme.id);
886 toastManager.add(
887 stackedThreadToast({
888 type: "success",
889 title: `${importedTheme.label} added`,
890 description: `It’s now your ${modes[0]!} theme.`,
891 }),
892 );
893 return true;
894 }
895 if (!persistTheme(importedTheme.id)) return false;
896 toastManager.add(
897 stackedThreadToast({
898 type: "success",
899 title: `${importedTheme.label} added`,
900 description: "It’s now active.",
901 }),
902 );
903 return true;
904 }}
905 onOpenChange={onImportOpenChange}
906 open={isImportOpen}
907 />
908 <AlertDialog open={isThemeRemovalOpen} onOpenChange={setIsThemeRemovalOpen}>
909 <AlertDialogPopup>
910 <AlertDialogHeader>
911 <AlertDialogTitle>
912 {canRemoveCollection
913 ? `Remove themes from “${removeDialogCollectionLabel}”?`
914 : `Remove “${removeDialogTheme?.label}”?`}
915 </AlertDialogTitle>
916 <AlertDialogDescription>
917 {canRemoveCollection
918 ? "Select the variants you want to remove. You can restore them by importing the extension again."
919 : "You can bring it back anytime by importing its JSON file."}
920 </AlertDialogDescription>
921 </AlertDialogHeader>
922 {canRemoveCollection ? (
923 <div className="grid max-h-72 grid-cols-1 gap-2 overflow-y-auto px-6 pb-6 sm:grid-cols-2">
924 {removeDialogCollectionThemes.map((customTheme) => {
925 const checked = themeIdsToRemoveSet.has(customTheme.id);
926 const card = getThemeCardDefinition(customTheme);
927 const checkboxId = `remove-theme-${customTheme.id}`;
928 return (
929 <label
930 className="group relative flex min-h-28 cursor-pointer flex-col items-center justify-center gap-2 rounded-lg border border-border/70 bg-muted/25 p-3 has-checked:border-ring has-checked:bg-accent/20 hover:bg-muted/40"
931 htmlFor={checkboxId}
932 key={customTheme.id}
933 >
934 <span className="absolute right-2 top-2 inline-grid size-5 grid-cols-1 sm:size-4">
935 <input
936 checked={checked}
937 className="col-start-1 row-start-1 size-full appearance-none rounded-sm border border-input bg-background outline-none checked:border-primary checked:bg-primary focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring checked:focus-visible:inset-ring-3 checked:focus-visible:inset-ring-background dark:not-checked:bg-input/32 forced-colors:appearance-auto"
938 id={checkboxId}
939 name="themes-to-remove"
940 type="checkbox"
941 onChange={(event) => {
942 const shouldRemove = event.currentTarget.checked;
943 setThemeIdsToRemove((current) =>
944 shouldRemove
945 ? [...current, customTheme.id]
946 : current.filter((themeId) => themeId !== customTheme.id),
947 );
948 }}
949 />
950 <CheckIcon className="pointer-events-none col-start-1 row-start-1 size-3.5 shrink-0 self-center justify-self-center stroke-primary-foreground opacity-0 group-has-checked:opacity-100 sm:size-3" />
951 </span>
952 <span className="flex min-h-12 items-center justify-center gap-1">
953 {card.previews.map((preview) => (
954 <span
955 className="flex size-11 shrink-0 items-center justify-center"
956 key={preview.mode}
957 >
958 <span className="flex scale-75">
959 <ThemePreviewCircle colors={preview.colors} mode={preview.mode} />
960 </span>
961 </span>
962 ))}
963 </span>
964 <p className="max-w-full truncate text-center text-base font-medium text-foreground sm:text-sm">
965 {customTheme.label}
966 </p>
967 </label>
968 );
969 })}
970 </div>
971 ) : null}
972 <AlertDialogFooter>
973 <AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>
974 <Button
975 disabled={themeIdsToRemove.length === 0}
976 variant="destructive"
977 onClick={handleConfirmRemoveTheme}
978 >
979 {canRemoveCollection
980 ? `Remove selected${themeIdsToRemove.length > 0 ? ` (${themeIdsToRemove.length})` : ""}`
981 : "Remove theme"}
982 </Button>
983 </AlertDialogFooter>
984 </AlertDialogPopup>
985 </AlertDialog>
986 </div>
987 );
988}