Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

feat: custom theme editor and sharing

ogsamrat302a609ccc93
diff --git a/apps/app/src/react-app/domains/settings/appearance/custom-theme-editor.tsx b/apps/app/src/react-app/domains/settings/appearance/custom-theme-editor.tsx
new file mode 100644
index 00000000..a79eb04e
--- /dev/null
+++ b/apps/app/src/react-app/domains/settings/appearance/custom-theme-editor.tsx
@@ -0,0 +1,446 @@
+/** @jsxImportSource react */
+import { AlertTriangle, Check } from "lucide-react";
+import { useEffect, useId, useMemo, useState, type ReactNode } from "react";
+import { Button } from "@/components/ui/button";
+import { cn } from "@/lib/utils";
+import {
+ contrastRatio,
+ contrastWarnings,
+ readPath,
+ textBackgrounds,
+ worstRatio,
+ type ContrastWarning,
+} from "@/app/themes/contrast";
+import {
+ ANSI_KEYS,
+ FONT_SIZE_RANGE,
+ RADIUS_RANGE,
+ SYNTAX_KEYS,
+ type CustomTheme,
+ type ThemeVariant,
+ type ThemeVariantMode,
+} from "@/app/themes/types";
+import { MAX_NAME_LENGTH } from "@/app/themes/share";
+import { ThemeLivePreview } from "./theme-preview";
+import { cloneTheme } from "./theme-state";
+
+const HEX = /^#?([0-9a-fA-F]{6})$/;
+
+const TOKEN_LABELS: Record<string, string> = {
+ accent: "Accent",
+ accentText: "Text on accent",
+ background: "Background",
+ surface: "Surface",
+ surfaceRaised: "Raised surface",
+ border: "Border",
+ text: "Text",
+ textMuted: "Muted text",
+ success: "Success",
+ warn: "Warning",
+ danger: "Error",
+ "code.bg": "Code background",
+ "code.fg": "Code text",
+ "terminal.bg": "Terminal background",
+ "terminal.fg": "Terminal text",
+ "terminal.cursor": "Terminal cursor",
+};
+
+const SYNTAX_LABELS: Record<string, string> = {
+ keyword: "keyword",
+ string: "string",
+ number: "number",
+ function: "function",
+ type: "type",
+ variable: "variable",
+ comment: "comment",
+ punctuation: "punct.",
+};
+
+function labelFor(token: string): string {
+ if (TOKEN_LABELS[token]) return TOKEN_LABELS[token]!;
+ const [group, key] = token.split(".");
+ if (group === "code") return `Syntax ${key}`;
+ if (group === "terminal") return `Terminal ${key?.replace(/^bright([A-Z])/, (_, c: string) => `bright ${c.toLowerCase()}`)}`;
+ return token;
+}
+
+function writePath(v: ThemeVariant, path: string, value: string): ThemeVariant {
+ const next = cloneTheme(v);
+ const [head, tail] = path.split(".") as [string, string | undefined];
+ if (tail) (next as unknown as Record<string, Record<string, string>>)[head]![tail] = value;
+ else (next as unknown as Record<string, string>)[head] = value;
+ return next;
+}
+
+function countChanged(a: ThemeVariant | undefined, b: ThemeVariant | undefined): number {
+ if (!a || !b) return 0;
+ const flat = (v: ThemeVariant) => {
+ const out: Record<string, string> = {};
+ for (const [k, val] of Object.entries(v)) {
+ if (typeof val === "string") out[k] = val;
+ else for (const [kk, vv] of Object.entries(val as Record<string, string>)) out[`${k}.${kk}`] = vv;
+ }
+ return out;
+ };
+ const fa = flat(a);
+ const fb = flat(b);
+ return Object.keys({ ...fa, ...fb }).filter((key) => fa[key] !== fb[key]).length;
+}
+
+/** Native colour picker behind a swatch, plus a hex field. */
+function ColourInput(props: {
+ label: string;
+ value: string;
+ onChange: (value: string) => void;
+ compact?: boolean;
+ testId?: string;
+}) {
+ const [text, setText] = useState(props.value);
+ useEffect(() => setText(props.value), [props.value]);
+ const commit = (raw: string) => {
+ const match = HEX.exec(raw.trim());
+ if (match) props.onChange(`#${match[1]!.toLowerCase()}`);
+ else setText(props.value);
+ };
+ const swatch = (
+ <label
+ className={cn(
+ "relative block shrink-0 cursor-pointer overflow-hidden rounded-md border border-border",
+ props.compact ? "size-6" : "size-5",
+ )}
+ style={{ backgroundColor: props.value }}
+ title={`${props.label} ${props.value}`}
+ >
+ <input
+ type="color"
+ aria-label={`${props.label} colour`}
+ value={props.value}
+ onChange={(event) => props.onChange(event.target.value.toLowerCase())}
+ className="absolute inset-0 size-full cursor-pointer opacity-0"
+ data-testid={props.testId ? `${props.testId}-picker` : undefined}
+ />
+ </label>
+ );
+ if (props.compact) return swatch;
+ return (
+ <div className="flex w-36 items-center gap-2 rounded-lg border border-border bg-background px-2 py-1">
+ {swatch}
+ <input
+ aria-label={`${props.label} hex`}
+ value={text}
+ spellCheck={false}
+ maxLength={7}
+ onChange={(event) => {
+ setText(event.target.value);
+ if (HEX.test(event.target.value.trim())) commit(event.target.value);
+ }}
+ onBlur={(event) => commit(event.target.value)}
+ onKeyDown={(event) => {
+ if (event.key === "Enter") commit((event.target as HTMLInputElement).value);
+ }}
+ className="w-full min-w-0 bg-transparent font-mono text-xs text-foreground outline-none"
+ data-testid={props.testId}
+ />
+ </div>
+ );
+}
+
+function RatioNote(props: { ratio: number; target: number; text: string }) {
+ const pass = props.ratio >= props.target;
+ return (
+ <span className={cn("flex items-center gap-1 text-xs", pass ? "text-muted-foreground" : "text-warning")}>
+ {pass ? <Check className="size-3" /> : <AlertTriangle className="size-3" />}
+ {props.ratio.toFixed(1)}:1{pass ? ` ${props.text}` : ""}
+ </span>
+ );
+}
+
+function WarningBox(props: { warning: ContrastWarning; onUse: (token: string, colour: string) => void }) {
+ const w = props.warning;
+ const lowest = w.rows.reduce((min, row) => (row.ratio < min.ratio ? row : min), w.rows[0]!);
+ const isUi = w.target < 4.5;
+ return (
+ <div
+ role="alert"
+ data-testid={`theme-contrast-warning-${w.token}`}
+ className="flex gap-2 rounded-lg border border-warning/50 bg-warning/10 px-3 py-2 text-xs text-foreground"
+ >
+ <AlertTriangle className="mt-0.5 size-3.5 shrink-0 text-warning" />
+ <div>
+ <b>
+ {labelFor(w.token)} on {lowest.label.split(" / ")[1]?.replace(" (UI)", "")} is {lowest.ratio.toFixed(1)}:1, below{" "}
+ {w.target}:1.
+ </b>{" "}
+ {isUi ? "It will be hard to see." : "Small text will be hard to read."}{" "}
+ <button
+ type="button"
+ className="font-medium text-foreground underline underline-offset-2"
+ onClick={() => props.onUse(w.token, w.suggestion)}
+ data-testid={`theme-contrast-use-${w.token}`}
+ >
+ Use {w.suggestion}
+ </button>
+ : same hue, passes on {w.token === "accent" ? "its text and backgrounds" : "every background it is used on"}.
+ </div>
+ </div>
+ );
+}
+
+function Row(props: { label: string; children: ReactNode; note?: ReactNode; sub?: string }) {
+ return (
+ <div className="grid grid-cols-[8.5rem_1fr] items-center gap-3 border-b border-border/60 py-2 last:border-b-0">
+ <div className="text-sm text-foreground">
+ {props.label}
+ {props.sub ? <div className="text-xs text-muted-foreground">{props.sub}</div> : null}
+ </div>
+ <div className="flex flex-wrap items-center gap-3">
+ {props.children}
+ {props.note}
+ </div>
+ </div>
+ );
+}
+
+export type CustomThemeEditorProps = {
+ /** The theme being edited (saved custom theme, a preset copy or an imported theme). */
+ initial: CustomTheme;
+ /** What it started from, shown in the header ("Rose", "a theme code"). */
+ startedFrom: string;
+ /** Whether Apply should be enabled without edits (new or imported theme). */
+ unsavedFromStart: boolean;
+ preferredMode: ThemeVariantMode;
+ onPreview: (theme: CustomTheme) => void;
+ onApply: (theme: CustomTheme) => void;
+ onRevert: () => void;
+};
+
+export function CustomThemeEditor(props: CustomThemeEditorProps) {
+ const [draft, setDraft] = useState<CustomTheme>(() => cloneTheme(props.initial));
+ const [mode, setMode] = useState<ThemeVariantMode>(() =>
+ props.initial.modes.includes(props.preferredMode) ? props.preferredMode : props.initial.modes[0]!,
+ );
+ const nameId = useId();
+ const variant = draft[mode]!;
+
+ const update = (next: CustomTheme) => {
+ setDraft(next);
+ props.onPreview(next);
+ };
+ const setColour = (path: string, value: string) => update({ ...draft, [mode]: writePath(variant, path, value) });
+
+ const warnings = useMemo(() => contrastWarnings(variant), [variant]);
+ const warningFor = (token: string) => warnings.find((w) => w.token === token);
+ const changed = countChanged(props.initial[mode], variant);
+ const otherMode: ThemeVariantMode = mode === "light" ? "dark" : "light";
+ const changedOther = countChanged(props.initial[otherMode], draft[otherMode]);
+ const metaChanged =
+ draft.name !== props.initial.name ||
+ draft.radiusPx !== props.initial.radiusPx ||
+ draft.fontSizePx !== props.initial.fontSizePx;
+ const dirty = props.unsavedFromStart || changed > 0 || changedOther > 0 || metaChanged;
+ const allWarnings = draft.modes.reduce((sum, m) => sum + contrastWarnings(draft[m]!).length, 0);
+
+ const field = (token: string, note?: ReactNode) => {
+ const warning = warningFor(token);
+ return (
+ <div key={token}>
+ <Row label={labelFor(token)} note={note}>
+ <ColourInput
+ label={labelFor(token)}
+ value={readPath(variant, token)}
+ onChange={(value) => setColour(token, value)}
+ testId={`theme-field-${token}`}
+ />
+ </Row>
+ {warning ? (
+ <div className="pb-2 pl-[9.25rem]">
+ <WarningBox warning={warning} onUse={setColour} />
+ </div>
+ ) : null}
+ </div>
+ );
+ };
+
+ const rowTokens = new Set([
+ "accent",
+ "accentText",
+ "background",
+ "surface",
+ "surfaceRaised",
+ "border",
+ "text",
+ "textMuted",
+ "code.bg",
+ ]);
+ const syntaxWarnings = warnings.filter((w) => w.token.startsWith("code.") && w.token !== "code.bg");
+ const terminalWarnings = warnings.filter((w) => w.token.startsWith("terminal."));
+ const otherWarnings = warnings.filter(
+ (w) => !rowTokens.has(w.token) && !w.token.startsWith("code.") && !w.token.startsWith("terminal."),
+ );
+
+ return (
+ <section aria-label="Custom theme editor" className="flex flex-col gap-4" data-testid="custom-theme-editor">
+ <div className="flex flex-wrap items-start justify-between gap-3">
+ <div>
+ <h4 className="text-sm font-medium text-foreground">Custom theme · {draft.name}</h4>
+ <p className="max-w-xl text-sm text-muted-foreground">
+ Started from {props.startedFrom}. Editing the <b>{mode}</b> version. Changes show live in this window and are
+ saved only when you press Apply.
+ </p>
+ </div>
+ {draft.modes.length > 1 ? (
+ <div role="tablist" aria-label="Version" className="flex rounded-lg border border-border p-0.5 text-sm">
+ {draft.modes.map((m) => (
+ <button
+ key={m}
+ type="button"
+ role="tab"
+ aria-selected={mode === m}
+ onClick={() => setMode(m)}
+ data-testid={`theme-edit-${m}`}
+ className={cn(
+ "rounded-md px-3 py-1 text-muted-foreground",
+ mode === m && "bg-muted text-foreground",
+ )}
+ >
+ {m === "light" ? "Light version" : "Dark version"}
+ </button>
+ ))}
+ </div>
+ ) : null}
+ </div>
+
+ <div className="grid gap-6 @3xl/settings:grid-cols-[minmax(0,1fr)_17rem]">
+ <div className="min-w-0">
+ <Row label="Name">
+ <input
+ id={nameId}
+ aria-label="Theme name"
+ value={draft.name}
+ maxLength={MAX_NAME_LENGTH}
+ onChange={(event) => update({ ...draft, name: event.target.value.replace(/[\p{C}]/gu, "") })}
+ onBlur={() => {
+ if (!draft.name.trim()) update({ ...draft, name: "My theme" });
+ }}
+ className="w-56 rounded-lg border border-border bg-background px-2 py-1 text-sm text-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ data-testid="theme-field-name"
+ />
+ </Row>
+ {field("accent", <RatioNote ratio={contrastRatio(variant.accentText, variant.accent)} target={4.5} text="text on accent" />)}
+ {field("accentText")}
+ {field("background")}
+ {field("surface")}
+ {field("surfaceRaised")}
+ {field("border")}
+ {field("text", <RatioNote ratio={worstRatio(variant.text, textBackgrounds(variant))} target={4.5} text="lowest of 4 backgrounds" />)}
+ {field("textMuted", <RatioNote ratio={worstRatio(variant.textMuted, textBackgrounds(variant))} target={4.5} text="lowest of 4 backgrounds" />)}
+ {field("code.bg", <RatioNote ratio={contrastRatio(variant.code.fg, variant.code.bg)} target={4.5} text="code text" />)}
+ <Row label="Syntax">
+ <div className="flex flex-wrap gap-2">
+ {SYNTAX_KEYS.map((key) => (
+ <div key={key} className="flex w-12 flex-col items-center gap-0.5 text-[10px] text-muted-foreground">
+ <ColourInput compact label={`Syntax ${key}`} value={variant.code[key]} onChange={(value) => setColour(`code.${key}`, value)} testId={`theme-field-code.${key}`} />
+ {SYNTAX_LABELS[key]}
+ </div>
+ ))}
+ </div>
+ </Row>
+ {syntaxWarnings.map((w) => (
+ <div key={w.token} className="pb-2 pl-[9.25rem]">
+ <WarningBox warning={w} onUse={setColour} />
+ </div>
+ ))}
+ <Row label="Terminal" sub="normal / bright">
+ <div className="grid grid-cols-8 gap-2">
+ {ANSI_KEYS.map((key) => (
+ <div key={key} className="flex w-11 flex-col items-center gap-0.5 text-[10px] text-muted-foreground">
+ <ColourInput compact label={`Terminal ${key}`} value={variant.terminal[key]} onChange={(value) => setColour(`terminal.${key}`, value)} testId={`theme-field-terminal.${key}`} />
+ {key.replace(/^bright/, "").toLowerCase()}
+ </div>
+ ))}
+ </div>
+ </Row>
+ <Row label="Terminal text">
+ <div className="flex gap-2">
+ {(["fg", "bg", "cursor"] as const).map((key) => (
+ <div key={key} className="flex w-11 flex-col items-center gap-0.5 text-[10px] text-muted-foreground">
+ <ColourInput compact label={`Terminal ${key}`} value={variant.terminal[key]} onChange={(value) => setColour(`terminal.${key}`, value)} testId={`theme-field-terminal.${key}`} />
+ {key}
+ </div>
+ ))}
+ </div>
+ </Row>
+ {terminalWarnings.map((w) => (
+ <div key={w.token} className="pb-2 pl-[9.25rem]">
+ <WarningBox warning={w} onUse={setColour} />
+ </div>
+ ))}
+ {otherWarnings.map((w) => (
+ <div key={w.token} className="pb-2 pl-[9.25rem]">
+ <WarningBox warning={w} onUse={setColour} />
+ </div>
+ ))}
+ <Row label="Corner radius">
+ <input
+ type="range"
+ aria-label="Corner radius"
+ min={RADIUS_RANGE.min}
+ max={RADIUS_RANGE.max}
+ step={1}
+ value={draft.radiusPx}
+ onChange={(event) => update({ ...draft, radiusPx: Number(event.target.value) })}
+ className="w-40 accent-foreground"
+ data-testid="theme-field-radius"
+ />
+ <span className="font-mono text-xs text-muted-foreground">
+ {Math.round(draft.radiusPx)} px ({RADIUS_RANGE.min}–{RADIUS_RANGE.max})
+ </span>
+ </Row>
+ <Row label="Font size">
+ <input
+ type="range"
+ aria-label="Font size"
+ min={FONT_SIZE_RANGE.min}
+ max={FONT_SIZE_RANGE.max}
+ step={1}
+ value={draft.fontSizePx}
+ onChange={(event) => update({ ...draft, fontSizePx: Number(event.target.value) })}
+ className="w-40 accent-foreground"
+ data-testid="theme-field-font-size"
+ />
+ <span className="font-mono text-xs text-muted-foreground">
+ {draft.fontSizePx} px ({FONT_SIZE_RANGE.min}–{FONT_SIZE_RANGE.max})
+ </span>
+ </Row>
+ </div>
+ <div className="@3xl/settings:sticky @3xl/settings:top-4 self-start">
+ <ThemeLivePreview variant={variant} radiusPx={draft.radiusPx} fontSizePx={draft.fontSizePx} />
+ </div>
+ </div>
+
+ <div
+ className="sticky bottom-2 z-10 flex flex-wrap items-center gap-3 rounded-xl border border-border bg-popover px-4 py-2.5 text-sm shadow-sm"
+ data-testid="theme-unsaved-bar"
+ >
+ <span className={cn("size-2 rounded-full", dirty ? "bg-warning" : "bg-muted-foreground/40")} />
+ <span className="min-w-0 flex-1 text-muted-foreground">
+ <b className="text-foreground">{dirty ? "Unsaved changes" : "No changes"}</b>
+ {changed > 0 ? ` · ${changed} colour${changed === 1 ? "" : "s"} changed in the ${mode} version` : ""}
+ {changedOther > 0 ? ` · ${changedOther} in the ${otherMode} version` : ""}
+ {allWarnings > 0 ? ` · ${allWarnings} contrast warning${allWarnings === 1 ? "" : "s"}` : ""}
+ </span>
+ <Button variant="outline" size="sm" onClick={props.onRevert} data-testid="theme-revert">
+ Revert
+ </Button>
+ <Button
+ size="sm"
+ disabled={!dirty}
+ onClick={() => props.onApply({ ...draft, name: draft.name.trim() || "My theme" })}
+ data-testid="theme-apply"
+ >
+ Apply
+ </Button>
+ </div>
+ </section>
+ );
+}
diff --git a/apps/app/src/react-app/domains/settings/appearance/theme-presets-section.tsx b/apps/app/src/react-app/domains/settings/appearance/theme-presets-section.tsx
new file mode 100644
index 00000000..644b207e
--- /dev/null
+++ b/apps/app/src/react-app/domains/settings/appearance/theme-presets-section.tsx
@@ -0,0 +1,151 @@
+/** @jsxImportSource react */
+import { Check, Moon, Pencil, Plus } from "lucide-react";
+import type { ReactNode } from "react";
+import { cn } from "@/lib/utils";
+import { THEME_PRESETS } from "@/app/themes/presets";
+import { presetModes } from "@/app/themes/palette";
+import type { CustomTheme, ThemeVariant } from "@/app/themes/types";
+import {
+ LayoutSectionItem,
+ LayoutSectionItemDescription,
+ LayoutSectionItemHeader,
+ LayoutSectionItemTitle,
+} from "../settings-layout";
+import { ThemeVariantThumb } from "./theme-preview";
+
+type Props = {
+ busy: boolean;
+ /** Selected preset id, or "custom" for My theme. */
+ selectedId: string;
+ customTheme: CustomTheme | null;
+ note: string | null;
+ onPickPreset: (id: string) => void;
+ onPickCustom: () => void;
+ onEditCustom: () => void;
+ onNewCustom: () => void;
+};
+
+const modesLabel = (modes: readonly string[]) =>
+ modes.length === 2 ? "Light / Dark" : modes[0] === "dark" ? "Dark only" : "Light only";
+
+function swatchesOf(v: ThemeVariant) {
+ return [v.accent, v.surface, v.code.string, v.code.function];
+}
+
+function Thumbs(props: { light?: ThemeVariant; dark?: ThemeVariant }) {
+ if (props.light && props.dark) {
+ return (
+ <div className="grid h-full grid-cols-2">
+ <ThemeVariantThumb variant={props.light} swatches={swatchesOf(props.light)} />
+ <ThemeVariantThumb variant={props.dark} swatches={swatchesOf(props.dark)} />
+ </div>
+ );
+ }
+ const only = (props.light ?? props.dark)!;
+ return <ThemeVariantThumb variant={only} swatches={swatchesOf(only)} />;
+}
+
+function Card(props: {
+ selected: boolean;
+ label: string;
+ meta: string;
+ disabled: boolean;
+ onClick: () => void;
+ children: ReactNode;
+ action?: ReactNode;
+ testId: string;
+}) {
+ return (
+ <div className="relative">
+ <button
+ type="button"
+ role="radio"
+ aria-checked={props.selected}
+ disabled={props.disabled}
+ onClick={props.onClick}
+ data-testid={props.testId}
+ className={cn(
+ "group flex w-full flex-col gap-2 rounded-xl border border-border bg-card p-1.5 text-left outline-none transition-shadow hover:border-foreground/25 focus-visible:ring-2 focus-visible:ring-ring",
+ props.selected && "border-foreground ring-1 ring-foreground",
+ )}
+ >
+ <div className="h-16 w-full overflow-hidden rounded-lg border border-border">{props.children}</div>
+ <div className="flex items-center justify-between gap-2 px-1 pb-0.5 text-xs">
+ <span className="flex min-w-0 items-center gap-1 font-medium text-foreground">
+ {props.selected ? <Check className="size-3 shrink-0" /> : null}
+ <span className="truncate">{props.label}</span>
+ </span>
+ <span className="shrink-0 text-muted-foreground">{props.meta}</span>
+ </div>
+ </button>
+ {props.action}
+ </div>
+ );
+}
+
+export function ThemePresetsSection(props: Props) {
+ return (
+ <LayoutSectionItem>
+ <LayoutSectionItemHeader className="w-full">
+ <LayoutSectionItemTitle>Theme</LayoutSectionItemTitle>
+ <LayoutSectionItemDescription>
+ Each preset has a light and a dark version (Midnight is dark only); the mode above picks which one you see.
+ </LayoutSectionItemDescription>
+ </LayoutSectionItemHeader>
+ <div role="radiogroup" aria-label="Theme" className="grid grid-cols-2 gap-3 @2xl/settings:grid-cols-4">
+ {THEME_PRESETS.map((preset) => (
+ <Card
+ key={preset.id}
+ testId={`theme-preset-${preset.id}`}
+ selected={props.selectedId === preset.id}
+ label={preset.name}
+ meta={modesLabel(presetModes(preset))}
+ disabled={props.busy}
+ onClick={() => props.onPickPreset(preset.id)}
+ >
+ <Thumbs light={preset.variants.light} dark={preset.variants.dark} />
+ </Card>
+ ))}
+ {props.customTheme ? (
+ <Card
+ testId="theme-preset-custom"
+ selected={props.selectedId === "custom"}
+ label={props.customTheme.name}
+ meta={modesLabel(props.customTheme.modes)}
+ disabled={props.busy}
+ onClick={props.onPickCustom}
+ action={
+ <button
+ type="button"
+ onClick={props.onEditCustom}
+ aria-label="Edit custom theme"
+ data-testid="theme-edit-custom"
+ className="absolute right-3 top-3 flex size-6 items-center justify-center rounded-md border border-border bg-popover text-foreground shadow-xs hover:bg-muted"
+ >
+ <Pencil className="size-3" />
+ </button>
+ }
+ >
+ <Thumbs light={props.customTheme.light} dark={props.customTheme.dark} />
+ </Card>
+ ) : null}
+ <button
+ type="button"
+ onClick={props.onNewCustom}
+ disabled={props.busy}
+ data-testid="theme-new-custom"
+ className="flex flex-col gap-2 rounded-xl border border-dashed border-border p-1.5 text-left text-xs text-muted-foreground outline-none hover:border-foreground/25 hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ <span className="flex h-16 w-full items-center justify-center rounded-lg border border-dashed border-border">
+ <Plus className="size-4" />
+ </span>
+ <span className="px-1 pb-0.5 font-medium">{props.customTheme ? "Edit custom theme" : "New custom theme"}</span>
+ </button>
+ </div>
+ <p className="flex items-center gap-1.5 text-xs text-muted-foreground" data-testid="theme-mode-note" role="status">
+ <Moon className="size-3 shrink-0" />
+ {props.note ?? "Midnight is dark only. Choosing it while Mode is Light switches Mode to Dark."}
+ </p>
+ </LayoutSectionItem>
+ );
+}
diff --git a/apps/app/src/react-app/domains/settings/appearance/theme-preview.tsx b/apps/app/src/react-app/domains/settings/appearance/theme-preview.tsx
new file mode 100644
index 00000000..59391a65
--- /dev/null
+++ b/apps/app/src/react-app/domains/settings/appearance/theme-preview.tsx
@@ -0,0 +1,135 @@
+/** @jsxImportSource react */
+import { cn } from "@/lib/utils";
+import { textSafeAccent } from "@/app/themes/contrast";
+import type { ThemeVariant } from "@/app/themes/types";
+
+/**
+ * Small picture of a theme variant for the preset cards: sidebar lines, a
+ * message line, a code line and swatches. Colours come from validated theme
+ * data and are set through React style props only.
+ */
+export function ThemeVariantThumb(props: { variant: ThemeVariant; className?: string; swatches?: string[] }) {
+ const v = props.variant;
+ const swatches = props.swatches ?? [v.accent, v.surface, v.code.string, v.code.function];
+ return (
+ <div
+ aria-hidden="true"
+ className={cn("flex h-full min-h-14 flex-col justify-between p-2", props.className)}
+ style={{ backgroundColor: v.background }}
+ >
+ <div className="flex flex-col gap-1">
+ <span className="block h-1 w-3/5 rounded-full" style={{ backgroundColor: v.text }} />
+ <span className="block h-1 w-2/5 rounded-full" style={{ backgroundColor: v.textMuted }} />
+ </div>
+ <div className="flex items-center gap-1">
+ {swatches.map((colour, index) => (
+ <span
+ key={index}
+ className="block size-2.5 rounded-[3px]"
+ style={{ backgroundColor: colour, boxShadow: `inset 0 0 0 1px ${v.border}` }}
+ />
+ ))}
+ </div>
+ </div>
+ );
+}
+
+/** The labelled, non-interactive sample shown next to the custom theme editor. */
+export function ThemeLivePreview(props: { variant: ThemeVariant; radiusPx: number; fontSizePx: number }) {
+ const v = props.variant;
+ const c = v.code;
+ const t = v.terminal;
+ const radius = `${props.radiusPx}px`;
+ const box = { borderRadius: radius, border: `1px solid ${v.border}` };
+ return (
+ <figure
+ aria-label="Live preview (sample, not clickable)"
+ className="m-0 overflow-hidden text-left"
+ style={{ ...box, backgroundColor: v.background, color: v.text, fontSize: `${props.fontSizePx}px` }}
+ data-testid="theme-live-preview"
+ >
+ <figcaption
+ className="flex items-center justify-between px-3 py-2 text-xs"
+ style={{ borderBottom: `1px solid ${v.border}`, backgroundColor: v.surface }}
+ >
+ <span style={{ color: v.text }}>Live preview</span>
+ <span style={{ color: v.textMuted }}>sample · not clickable</span>
+ </figcaption>
+ <div inert className="flex select-none flex-col gap-2.5 p-3">
+ <div className="self-end px-3 py-1.5" style={{ ...box, backgroundColor: v.surfaceRaised }}>
+ Add a retry to the request?
+ </div>
+ <div>
+ Done: three tries with backoff. <span style={{ color: v.textMuted }}>Tests pass.</span>
+ </div>
+ <pre
+ className="m-0 overflow-hidden px-3 py-2 font-mono text-[0.85em] leading-relaxed"
+ style={{ ...box, backgroundColor: c.bg, color: c.fg }}
+ >
+ <span style={{ color: c.comment, fontStyle: "italic" }}>{"// retry with backoff"}</span>
+ {"\n"}
+ <span style={{ color: c.keyword }}>for</span>
+ <span style={{ color: c.punctuation }}>{" ("}</span>
+ <span style={{ color: c.keyword }}>let</span>
+ <span style={{ color: c.variable }}> i </span>
+ <span style={{ color: c.punctuation }}>= </span>
+ <span style={{ color: c.number }}>0</span>
+ <span style={{ color: c.punctuation }}>; i &lt; </span>
+ <span style={{ color: c.number }}>3</span>
+ <span style={{ color: c.punctuation }}>{"; i++) {"}</span>
+ {"\n "}
+ <span style={{ color: c.keyword }}>if</span>
+ <span style={{ color: c.punctuation }}>{" ("}</span>
+ <span style={{ color: c.keyword }}>await </span>
+ <span style={{ color: c.function }}>send</span>
+ <span style={{ color: c.punctuation }}>(</span>
+ <span style={{ color: c.type }}>file</span>
+ <span style={{ color: c.punctuation }}>)) </span>
+ <span style={{ color: c.keyword }}>return </span>
+ <span style={{ color: c.string }}>"ok"</span>
+ <span style={{ color: c.punctuation }}>;</span>
+ {"\n"}
+ <span style={{ color: c.punctuation }}>{"}"}</span>
+ </pre>
+ <pre
+ className="m-0 overflow-hidden px-3 py-2 font-mono text-[0.85em] leading-relaxed"
+ style={{ ...box, backgroundColor: t.bg, color: t.fg }}
+ >
+ <span style={{ color: t.brightBlack }}>$ </span>pnpm test
+ {"\n"}
+ <span style={{ color: t.green }}>✓ 42 passed</span>
+ <span style={{ color: t.yellow }}> ! 1 skipped</span>
+ <span style={{ color: t.red }}> ✗ 0 failed</span>
+ {"\n"}
+ <span style={{ color: t.blue }}>info</span>
+ <span style={{ color: t.magenta }}> watch</span>
+ <span style={{ color: t.cyan }}> src/api </span>
+ <span className="inline-block h-[1em] w-[0.5em] align-text-bottom" style={{ backgroundColor: t.cursor }} />
+ </pre>
+ <div className="text-[0.75em] uppercase tracking-wide" style={{ color: v.textMuted }}>
+ Sample controls
+ </div>
+ <div className="flex flex-wrap items-center gap-2">
+ <span className="px-3 py-1" style={{ borderRadius: radius, backgroundColor: v.accent, color: v.accentText }}>
+ Primary
+ </span>
+ <span className="px-3 py-1" style={{ ...box, backgroundColor: v.surface, color: v.text }}>
+ Secondary
+ </span>
+ <span
+ className="ml-auto px-2 py-0.5 text-[0.8em] font-semibold"
+ style={{ borderRadius: radius, border: `1px solid ${v.border}`, backgroundColor: v.surfaceRaised }}
+ >
+ Badge
+ </span>
+ </div>
+ <div className="flex flex-wrap gap-3 text-[0.85em]">
+ <span style={{ color: v.success }}>● Success</span>
+ <span style={{ color: v.warn }}>● Warning</span>
+ <span style={{ color: v.danger }}>● Error</span>
+ <span style={{ color: textSafeAccent(v) }}>Link</span>
+ </div>
+ </div>
+ </figure>
+ );
+}
diff --git a/apps/app/src/react-app/domains/settings/appearance/theme-section.tsx b/apps/app/src/react-app/domains/settings/appearance/theme-section.tsx
index 3d86bc7f..89d5f7b7 100644
--- a/apps/app/src/react-app/domains/settings/appearance/theme-section.tsx
+++ b/apps/app/src/react-app/domains/settings/appearance/theme-section.tsx
@@ -1,13 +1,11 @@
/** @jsxImportSource react */
+import { Monitor, Moon, Sun } from "lucide-react";
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
-import { cn } from "@/lib/utils";
-import type { ReactNode } from "react";
import { t } from "@/i18n";
import type { AppearanceViewProps } from "../pages/appearance-view";
import {
LayoutSectionItem,
LayoutSectionItemDescription,
- LayoutSectionItemFootnote,
LayoutSectionItemHeader,
LayoutSectionItemTitle,
} from "../settings-layout";
@@ -17,121 +15,41 @@ type ThemeMode = AppearanceViewProps["themeMode"];
interface ThemeSectionProps
extends Pick<AppearanceViewProps, "busy" | "themeMode" | "setThemeMode"> {}
+/** Mode: light, dark or follow the system. The theme below picks the colours for each. */
export function ThemeSection(props: ThemeSectionProps) {
+ const items: Array<{ value: ThemeMode; label: string; icon: typeof Sun }> = [
+ { value: "light", label: t("settings.theme_light"), icon: Sun },
+ { value: "dark", label: t("settings.theme_dark"), icon: Moon },
+ { value: "system", label: t("settings.theme_system"), icon: Monitor },
+ ];
return (
- <LayoutSectionItem className="items-center">
+ <LayoutSectionItem>
<LayoutSectionItemHeader className="w-full">
- <LayoutSectionItemTitle>{t("settings.theme_title")}</LayoutSectionItemTitle>
- <LayoutSectionItemDescription>{t("settings.appearance_hint")}</LayoutSectionItemDescription>
+ <LayoutSectionItemTitle>Mode</LayoutSectionItemTitle>
+ <LayoutSectionItemDescription>System follows your computer's light or dark setting.</LayoutSectionItemDescription>
</LayoutSectionItemHeader>
-
- <ThemePicker
- className="pt-1"
- busy={props.busy}
- themeMode={props.themeMode}
- setThemeMode={props.setThemeMode}
- />
-
- <LayoutSectionItemFootnote>{t("settings.theme_system_hint")}</LayoutSectionItemFootnote>
- </LayoutSectionItem>
- );
-}
-
-interface ThemePickerProps {
- className?: string;
- busy: boolean;
- themeMode: ThemeMode;
- setThemeMode: (value: ThemeMode) => void;
-}
-
-function ThemePicker(props: ThemePickerProps) {
- return (
- <ToggleGroup
- value={[props.themeMode]}
- onValueChange={(value) => {
- if (value[0] === null) {
- return;
- }
-
- props.setThemeMode(value[0] as ThemeMode);
- }}
- disabled={props.busy}
- className={cn("w-full gap-6 max-w-xl", props.className)}
- >
- <ThemePickerItem
- value="system"
- label={t("settings.theme_system")}
- >
- <ThemePreview value="system" />
- <ThemePickerLabel>{t("settings.theme_system")}</ThemePickerLabel>
- </ThemePickerItem>
- <ThemePickerItem
- value="light"
- label={t("settings.theme_light")}
- >
- <ThemePreview value="light" className="bg-white" />
- <ThemePickerLabel>{t("settings.theme_light")}</ThemePickerLabel>
- </ThemePickerItem>
- <ThemePickerItem
- value="dark"
- label={t("settings.theme_dark")}
+ <ToggleGroup
+ value={[props.themeMode]}
+ onValueChange={(value) => {
+ if (!value[0]) return;
+ props.setThemeMode(value[0] as ThemeMode);
+ }}
+ disabled={props.busy}
+ aria-label="Mode"
+ className="w-fit gap-0.5 rounded-lg border border-border bg-muted/40 p-0.5"
>
- <ThemePreview value="dark" className="bg-black" />
- <ThemePickerLabel>{t("settings.theme_dark")}</ThemePickerLabel>
- </ThemePickerItem>
- </ToggleGroup>
- );
-}
-
-interface ThemePickerItemProps {
- value: ThemeMode;
- label: string;
- children: ReactNode;
-}
-
-function ThemePickerItem(props: ThemePickerItemProps) {
- return (
- <ToggleGroupItem
- value={props.value}
- aria-label={props.label}
- className="group/theme h-auto flex-1 flex-col gap-3 rounded-sm p-0 hover:bg-transparent aria-pressed:bg-transparent"
- >
- {props.children}
- </ToggleGroupItem>
- );
-}
-
-interface ThemePreviewProps {
- value: ThemeMode;
- className?: string;
-}
-
-function ThemePreview(props: ThemePreviewProps) {
- return (
- <div
- className={cn(
- "aspect-4/3 w-full overflow-hidden rounded-md border transition-shadow group-data-pressed/theme:ring-2 group-data-pressed/theme:ring-primary group-data-pressed/theme:ring-offset-2 group-data-pressed/theme:ring-offset-background group-hover/theme:ring-1 group-hover/theme:ring-primary/40 group-hover/theme:ring-offset-2 group-hover/theme:ring-offset-background",
- props.className,
- )}
- >
- {props.value === "system" && (
- <div className="flex h-full">
- <div className="w-1/2 bg-white" />
- <div className="w-1/2 bg-black" />
- </div>
- )}
- </div>
- );
-}
-
-interface ThemePickerLabelProps {
- children: string;
-}
-
-function ThemePickerLabel(props: ThemePickerLabelProps) {
- return (
- <span className="text-sm text-muted-foreground group-data-pressed/theme:text-foreground">
- {props.children}
- </span>
+ {items.map((item) => (
+ <ToggleGroupItem
+ key={item.value}
+ value={item.value}
+ aria-label={item.label}
+ className="h-7 gap-1.5 rounded-md px-3 text-sm text-muted-foreground aria-pressed:bg-background aria-pressed:text-foreground aria-pressed:shadow-xs"
+ >
+ <item.icon className="size-3.5" />
+ {item.label}
+ </ToggleGroupItem>
+ ))}
+ </ToggleGroup>
+ </LayoutSectionItem>
);
}
diff --git a/apps/app/src/react-app/domains/settings/appearance/theme-share-section.tsx b/apps/app/src/react-app/domains/settings/appearance/theme-share-section.tsx
new file mode 100644
index 00000000..df41acee
--- /dev/null
+++ b/apps/app/src/react-app/domains/settings/appearance/theme-share-section.tsx
@@ -0,0 +1,317 @@
+/** @jsxImportSource react */
+import { AlertTriangle, Check, Copy, Download, ExternalLink, MessageCircle, Palette, Upload } from "lucide-react";
+import { useEffect, useRef, useState } from "react";
+import { Button } from "@/components/ui/button";
+import { downloadTextAsFile } from "@/app/lib/download";
+import { contrastRows } from "@/app/themes/contrast";
+import {
+ MAX_THEME_BYTES,
+ decodeShareCode,
+ encodeShareCode,
+ parseThemeJson,
+ serializeTheme,
+ themeFileName,
+ type ThemeImportResult,
+} from "@/app/themes/share";
+import type { CustomTheme } from "@/app/themes/types";
+import { usePlatform } from "@/react-app/kernel/platform";
+import {
+ LayoutSectionItem,
+ LayoutSectionItemDescription,
+ LayoutSectionItemHeader,
+ LayoutSectionItemTitle,
+} from "../settings-layout";
+import { ThemeVariantThumb } from "./theme-preview";
+
+export const DISCORD_SHOWCASE_URL = "https://discord.com/channels/1554572994326827069/1556709953916641280";
+export const DISCORD_INVITE_URL = "https://discord.gg/HWMqU2Twp";
+
+type Props = {
+ customTheme: CustomTheme | null;
+ /** The theme being previewed after an import, if any. */
+ importing: { theme: CustomTheme; source: string } | null;
+ onImportPreview: (theme: CustomTheme, source: string) => void;
+ onKeep: () => void;
+ onEditFirst: () => void;
+ onCancelImport: () => void;
+};
+
+/** Pairs checked and failing across every version of a theme. */
+export function themeContrastSummary(theme: CustomTheme) {
+ let checked = 0;
+ const failing: Array<{ mode: string; label: string; ratio: number; target: number }> = [];
+ for (const mode of theme.modes) {
+ for (const row of contrastRows(theme[mode]!)) {
+ checked += 1;
+ if (!row.pass) failing.push({ mode, label: row.label, ratio: row.ratio, target: row.target });
+ }
+ }
+ return { checked, failing };
+}
+
+function ImportPreviewCard(props: Pick<Props, "onKeep" | "onEditFirst" | "onCancelImport"> & { theme: CustomTheme; source: string; replaces: boolean }) {
+ const summary = themeContrastSummary(props.theme);
+ const modes = props.theme.modes.join(" + ");
+ return (
+ <div className="flex flex-col gap-3" data-testid="theme-import-preview">
+ <div className="flex gap-2 rounded-lg border border-border bg-muted/40 px-3 py-2 text-sm">
+ <Palette className="mt-0.5 size-4 shrink-0 text-muted-foreground" />
+ <div>
+ <b className="text-foreground">Previewing “{props.theme.name}”</b>
+ <span className="text-muted-foreground"> · {modes} · from {props.source}</span>
+ <div className="text-xs text-muted-foreground">The whole window shows it now. Nothing is saved yet.</div>
+ </div>
+ </div>
+ <div className="grid grid-cols-2 gap-2">
+ {props.theme.modes.map((mode) => (
+ <div key={mode} className="h-16 overflow-hidden rounded-lg border border-border">
+ <ThemeVariantThumb variant={props.theme[mode]!} />
+ </div>
+ ))}
+ </div>
+ {summary.failing.length === 0 ? (
+ <p className="flex items-center gap-1.5 text-xs text-muted-foreground">
+ <Check className="size-3" /> All {summary.checked} contrast pairs pass
+ {props.theme.modes.length > 1 ? " in both modes" : ""}
+ </p>
+ ) : (
+ <div className="rounded-lg border border-warning/50 bg-warning/10 px-3 py-2 text-xs" role="alert" data-testid="theme-import-contrast">
+ <b className="flex items-center gap-1.5 text-foreground">
+ <AlertTriangle className="size-3.5 text-warning" />
+ {summary.failing.length} of {summary.checked} contrast pairs fail
+ </b>
+ <ul className="mt-1 list-disc pl-5 text-muted-foreground">
+ {summary.failing.slice(0, 6).map((row, index) => (
+ <li key={index}>
+ {row.mode}: {row.label} {row.ratio.toFixed(1)}:1 (needs {row.target}:1)
+ </li>
+ ))}
+ {summary.failing.length > 6 ? <li>and {summary.failing.length - 6} more</li> : null}
+ </ul>
+ </div>
+ )}
+ <div className="flex flex-wrap gap-2">
+ {summary.failing.length === 0 ? (
+ <>
+ <Button size="sm" onClick={props.onKeep} data-testid="theme-import-keep">
+ Keep theme
+ </Button>
+ <Button size="sm" variant="outline" onClick={props.onEditFirst} data-testid="theme-import-edit">
+ Edit first
+ </Button>
+ </>
+ ) : (
+ <Button size="sm" onClick={props.onEditFirst} data-testid="theme-import-edit">
+ Fix in editor
+ </Button>
+ )}
+ <Button size="sm" variant="ghost" onClick={props.onCancelImport} data-testid="theme-import-cancel">
+ Cancel
+ </Button>
+ </div>
+ {props.replaces ? <p className="text-xs text-muted-foreground">Keeping it replaces your current custom theme.</p> : null}
+ </div>
+ );
+}
+
+export function ThemeShareSection(props: Props) {
+ const platform = usePlatform();
+ const [code, setCode] = useState("");
+ const [copied, setCopied] = useState(false);
+ const [input, setInput] = useState("");
+ const [error, setError] = useState<string | null>(null);
+ const fileRef = useRef<HTMLInputElement>(null);
+
+ useEffect(() => {
+ let cancelled = false;
+ if (!props.customTheme) {
+ setCode("");
+ return;
+ }
+ void encodeShareCode(props.customTheme).then((value) => {
+ if (!cancelled) setCode(value);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [props.customTheme]);
+
+ const handleResult = (result: ThemeImportResult, source: string) => {
+ if (!result.ok) {
+ setError(result.error);
+ return;
+ }
+ setError(null);
+ props.onImportPreview(result.theme, source);
+ };
+
+ const copy = async () => {
+ if (!code) return;
+ try {
+ await navigator.clipboard.writeText(code);
+ setCopied(true);
+ window.setTimeout(() => setCopied(false), 1600);
+ } catch {
+ setCopied(false);
+ }
+ };
+
+ const openFile = async (file: File | undefined) => {
+ if (!file) return;
+ if (file.size > MAX_THEME_BYTES) {
+ setError("the theme is larger than 8 KB");
+ return;
+ }
+ handleResult(parseThemeJson(await file.text()), "a theme file");
+ };
+
+ return (
+ <LayoutSectionItem>
+ <LayoutSectionItemHeader className="w-full">
+ <LayoutSectionItemTitle>Share and import</LayoutSectionItemTitle>
+ <LayoutSectionItemDescription>
+ A theme code holds the whole custom theme: both versions, corner radius and font size. Nothing else from your
+ settings is included.
+ </LayoutSectionItemDescription>
+ </LayoutSectionItemHeader>
+
+ <div className="flex flex-wrap items-center gap-2 rounded-xl border border-border p-3">
+ <span className="w-14 text-sm font-medium text-foreground">Export</span>
+ <input
+ readOnly
+ aria-label="Theme code"
+ value={code || "Create a custom theme to get a code."}
+ onFocus={(event) => event.currentTarget.select()}
+ className="min-w-0 flex-1 truncate rounded-lg border border-border bg-background px-2 py-1.5 font-mono text-xs text-muted-foreground outline-none"
+ data-testid="theme-export-code"
+ />
+ <Button size="sm" disabled={!code} onClick={() => void copy()} data-testid="theme-copy-code">
+ {copied ? <Check /> : <Copy />}
+ {copied ? "Copied" : "Copy theme code"}
+ </Button>
+ <Button
+ size="sm"
+ variant="outline"
+ disabled={!props.customTheme}
+ onClick={() => {
+ if (props.customTheme) {
+ downloadTextAsFile(themeFileName(props.customTheme), serializeTheme(props.customTheme, true), "application/json");
+ }
+ }}
+ data-testid="theme-save-file"
+ >
+ <Download />
+ Save file…
+ </Button>
+ </div>
+
+ <div className="grid gap-3 @2xl/settings:grid-cols-2">
+ <div className="flex flex-col gap-2 rounded-xl border border-border p-3">
+ <span className="text-sm font-medium text-foreground">Import</span>
+ <form
+ className="flex gap-2"
+ onSubmit={(event) => {
+ event.preventDefault();
+ void decodeShareCode(input).then((result) => handleResult(result, "a theme code"));
+ }}
+ >
+ <input
+ aria-label="Paste a theme code"
+ placeholder="omnirush-theme:1:…"
+ value={input}
+ onChange={(event) => {
+ setInput(event.target.value);
+ setError(null);
+ }}
+ aria-invalid={error ? true : undefined}
+ className="min-w-0 flex-1 rounded-lg border border-border bg-background px-2 py-1.5 font-mono text-xs text-foreground outline-none aria-invalid:border-destructive focus-visible:ring-2 focus-visible:ring-ring"
+ data-testid="theme-import-input"
+ />
+ <Button size="sm" variant="outline" type="submit" disabled={!input.trim()} data-testid="theme-import-preview-button">
+ Preview
+ </Button>
+ </form>
+ {error ? (
+ <p className="flex items-start gap-1.5 text-xs text-destructive" role="alert" data-testid="theme-import-error">
+ <AlertTriangle className="mt-0.5 size-3 shrink-0" />
+ <span>
+ <b>This isn't a valid theme:</b> {error}. Nothing was changed.
+ </span>
+ </p>
+ ) : null}
+ <div>
+ <input
+ ref={fileRef}
+ type="file"
+ accept=".json,application/json"
+ className="hidden"
+ data-testid="theme-import-file"
+ onChange={(event) => {
+ void openFile(event.target.files?.[0]);
+ event.target.value = "";
+ }}
+ />
+ <Button size="sm" variant="outline" onClick={() => fileRef.current?.click()}>
+ <Upload />
+ Open file…
+ </Button>
+ </div>
+ <div className="text-xs text-muted-foreground">
+ <b className="text-foreground">What a theme code can contain</b>
+ <ul className="mt-1 list-disc pl-5">
+ <li>Starts with omnirush-theme:1: (version 1)</li>
+ <li>Colours are #rrggbb hex only</li>
+ <li>Unknown keys are rejected, nothing is guessed</li>
+ <li>At most 8 KB once decoded</li>
+ <li>Corner radius 0–16 px, font size 12–16 px</li>
+ <li>One or both modes, listed in modes</li>
+ </ul>
+ </div>
+ </div>
+ <div className="flex flex-col gap-2 rounded-xl border border-border p-3">
+ <span className="text-sm font-medium text-foreground">Preview, then confirm</span>
+ {props.importing ? (
+ <ImportPreviewCard
+ theme={props.importing.theme}
+ source={props.importing.source}
+ replaces={Boolean(props.customTheme)}
+ onKeep={props.onKeep}
+ onEditFirst={props.onEditFirst}
+ onCancelImport={props.onCancelImport}
+ />
+ ) : (
+ <p className="text-xs text-muted-foreground">
+ Paste a code or open a file. The theme shows in the whole window before you decide to keep it.
+ </p>
+ )}
+ </div>
+ </div>
+
+ <p className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted-foreground">
+ <span className="flex items-center gap-1.5">
+ <MessageCircle className="size-3.5" />
+ <button
+ type="button"
+ className="text-foreground underline underline-offset-2"
+ onClick={() => platform.openLink(DISCORD_SHOWCASE_URL)}
+ data-testid="theme-discord-showcase"
+ >
+ Share your theme in #showcase on Discord
+ </button>
+ <ExternalLink className="size-3" />
+ </span>
+ <span>
+ Not a member yet?{" "}
+ <button
+ type="button"
+ className="text-foreground underline underline-offset-2"
+ onClick={() => platform.openLink(DISCORD_INVITE_URL)}
+ data-testid="theme-discord-join"
+ >
+ Join our Discord
+ </button>
+ </span>
+ </p>
+ </LayoutSectionItem>
+ );
+}
diff --git a/apps/app/src/react-app/domains/settings/appearance/theme-state.ts b/apps/app/src/react-app/domains/settings/appearance/theme-state.ts
new file mode 100644
index 00000000..fb9d9b04
--- /dev/null
+++ b/apps/app/src/react-app/domains/settings/appearance/theme-state.ts
@@ -0,0 +1,53 @@
+import { useSyncExternalStore } from "react";
+import { captureAnalyticsEvent } from "@/app/lib/analytics";
+import {
+ getActiveTheme,
+ getCustomTheme,
+ getThemeSelection,
+ subscribeToTheme,
+ type ThemeMode,
+} from "@/app/theme";
+import { findPreset, presetModes } from "@/app/themes/palette";
+import { DEFAULT_FONT_SIZE_PX, DEFAULT_RADIUS_PX, type CustomTheme, type ThemePreset } from "@/app/themes/types";
+
+export function useActiveTheme() {
+ return useSyncExternalStore(subscribeToTheme, getActiveTheme, getActiveTheme);
+}
+
+export function useThemeSelection() {
+ return useSyncExternalStore(subscribeToTheme, getThemeSelection, getThemeSelection);
+}
+
+export function useSavedCustomTheme() {
+ return useSyncExternalStore(subscribeToTheme, getCustomTheme, getCustomTheme);
+}
+
+/**
+ * theme_changed: sent on a preset pick or when a custom theme is applied/kept.
+ * Never carries colours or the custom theme's name.
+ */
+export function trackThemeChanged(
+ input: { kind: "preset"; preset: string; mode: ThemeMode } | { kind: "custom"; mode: ThemeMode },
+) {
+ if (input.kind === "preset") {
+ captureAnalyticsEvent("theme_changed", { kind: "preset", preset: input.preset, mode: input.mode });
+ } else {
+ captureAnalyticsEvent("theme_changed", { kind: "custom", mode: input.mode });
+ }
+}
+
+const clone = <T,>(value: T): T => JSON.parse(JSON.stringify(value)) as T;
+
+/** A new custom theme ("My theme") starting from a preset's versions. */
+export function customThemeFromPreset(preset: ThemePreset, name = "My theme"): CustomTheme {
+ const modes = presetModes(preset);
+ const theme: CustomTheme = { v: 1, name, modes, radiusPx: DEFAULT_RADIUS_PX, fontSizePx: DEFAULT_FONT_SIZE_PX };
+ for (const mode of modes) theme[mode] = clone(preset.variants[mode]!);
+ return theme;
+}
+
+export function presetName(id: string): string {
+ return findPreset(id)?.name ?? id;
+}
+
+export const cloneTheme = clone;
diff --git a/apps/app/src/react-app/domains/settings/pages/appearance-view.tsx b/apps/app/src/react-app/domains/settings/pages/appearance-view.tsx
index 12a54c02..17a05cad 100644
--- a/apps/app/src/react-app/domains/settings/pages/appearance-view.tsx
+++ b/apps/app/src/react-app/domains/settings/pages/appearance-view.tsx
@@ -1,9 +1,29 @@
/** @jsxImportSource react */
+import { useEffect, useState } from "react";
import { isDesktopRuntime } from "@/app/utils";
import type { Language } from "@/i18n";
import { Separator } from "@/components/ui/separator";
+import {
+ modeSwitchFor,
+ saveCustomTheme,
+ setThemePreview,
+ setThemeSelection,
+} from "@/app/theme";
+import { findPreset, presetModes } from "@/app/themes/palette";
+import type { CustomTheme } from "@/app/themes/types";
+import { CustomThemeEditor } from "../appearance/custom-theme-editor";
import { LanguageSection } from "../appearance/language-section";
+import { ThemePresetsSection } from "../appearance/theme-presets-section";
import { ThemeSection } from "../appearance/theme-section";
+import { ThemeShareSection } from "../appearance/theme-share-section";
+import {
+ customThemeFromPreset,
+ presetName,
+ trackThemeChanged,
+ useActiveTheme,
+ useSavedCustomTheme,
+ useThemeSelection,
+} from "../appearance/theme-state";
import { WindowSection } from "../appearance/window-section";
import { LayoutStack } from "../settings-layout";
@@ -17,11 +37,129 @@ export type AppearanceViewProps = {
toggleHideTitlebar: () => void;
};
+type EditorState = { initial: CustomTheme; startedFrom: string; unsavedFromStart: boolean; key: number };
+
export function AppearanceView(props: AppearanceViewProps) {
+ const selection = useThemeSelection();
+ const customTheme = useSavedCustomTheme();
+ const active = useActiveTheme();
+ const [editor, setEditor] = useState<EditorState | null>(null);
+ const [importing, setImporting] = useState<{ theme: CustomTheme; source: string } | null>(null);
+ const [note, setNote] = useState<string | null>(null);
+
+ // Leaving Appearance ends any unsaved preview.
+ useEffect(() => () => setThemePreview(null), []);
+
+ const selectedId = selection.kind === "custom" ? "custom" : selection.id;
+
+ /** Single-mode themes (Midnight) switch Mode instead of silently showing the other mode. */
+ const followModes = (name: string, modes: readonly ("light" | "dark")[]) => {
+ const target = modeSwitchFor(modes, props.themeMode);
+ if (target) {
+ props.setThemeMode(target);
+ setNote(`${name} is ${target} only, so Mode is now ${target === "dark" ? "Dark" : "Light"}.`);
+ return target;
+ }
+ setNote(null);
+ return props.themeMode;
+ };
+
+ const closeEditing = () => {
+ setEditor(null);
+ setImporting(null);
+ setThemePreview(null);
+ };
+
+ const pickPreset = (id: string) => {
+ const preset = findPreset(id);
+ if (!preset) return;
+ closeEditing();
+ const mode = followModes(preset.name, presetModes(preset));
+ setThemeSelection({ kind: "preset", id });
+ trackThemeChanged({ kind: "preset", preset: id, mode });
+ };
+
+ const pickCustom = () => {
+ if (!customTheme) return;
+ closeEditing();
+ const mode = followModes(customTheme.name, customTheme.modes);
+ setThemeSelection({ kind: "custom" });
+ trackThemeChanged({ kind: "custom", mode });
+ };
+
+ const openEditor = (initial: CustomTheme, startedFrom: string, unsavedFromStart: boolean) => {
+ setImporting(null);
+ setEditor({ initial, startedFrom, unsavedFromStart, key: Date.now() });
+ setThemePreview(initial);
+ };
+
+ const editCustom = () => {
+ if (customTheme) openEditor(customTheme, "your saved theme", false);
+ };
+
+ const newCustom = () => {
+ if (customTheme && selection.kind === "custom") {
+ editCustom();
+ return;
+ }
+ const baseId = selection.kind === "preset" ? selection.id : "default";
+ const preset = findPreset(baseId) ?? findPreset("default")!;
+ openEditor(customThemeFromPreset(preset), presetName(preset.id), true);
+ };
+
+ const keepTheme = (theme: CustomTheme) => {
+ saveCustomTheme(theme);
+ setThemePreview(null);
+ const mode = followModes(theme.name, theme.modes);
+ setThemeSelection({ kind: "custom" });
+ trackThemeChanged({ kind: "custom", mode });
+ setEditor(null);
+ setImporting(null);
+ };
+
return (
- <LayoutStack>
+ <LayoutStack className="max-w-5xl">
<ThemeSection {...props} />
<Separator />
+ <ThemePresetsSection
+ busy={props.busy}
+ selectedId={selectedId}
+ customTheme={customTheme}
+ note={note}
+ onPickPreset={pickPreset}
+ onPickCustom={pickCustom}
+ onEditCustom={editCustom}
+ onNewCustom={newCustom}
+ />
+ {editor ? (
+ <>
+ <Separator />
+ <CustomThemeEditor
+ key={editor.key}
+ initial={editor.initial}
+ startedFrom={editor.startedFrom}
+ unsavedFromStart={editor.unsavedFromStart}
+ preferredMode={active.mode}
+ onPreview={(theme) => setThemePreview(theme)}
+ onApply={keepTheme}
+ onRevert={closeEditing}
+ />
+ </>
+ ) : null}
+ <Separator />
+ <ThemeShareSection
+ customTheme={customTheme}
+ importing={importing}
+ onImportPreview={(theme, source) => {
+ setEditor(null);
+ setImporting({ theme, source });
+ setThemePreview(theme);
+ }}
+ onKeep={() => importing && keepTheme(importing.theme)}
+ onEditFirst={() => importing && openEditor(importing.theme, importing.source, true)}
+ onCancelImport={closeEditing}
+ />
+ <Separator />
<LanguageSection {...props} />
{isDesktopRuntime() ? (
<>