diff --git a/docs/reference.md b/docs/reference.md index 852bf87..c539eff 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -192,7 +192,7 @@ Open them from the command palette (`Settings`). `j`/`k` move, `enter` or a clic | `diffIgnoreWhitespace` | `true`, `false` | `true` | | `notificationMode` | `off`, `sound` (bell), `notifications` (desktop), `notifications-and-sound` | `sound` | | `inAppNotificationsEnabled` | `true`, `false` | `true` | -| `theme` | `auto` (match the terminal), `dark`, `light`; applies from the next start | `auto` | +| `theme` | `auto` (dark or light, from the terminal's background), `dark`, `light`, or `terminal` (built from the terminal's own background, text and 16 ANSI colours); applies from the next start. Terminals that don't report their colours get `dark`. | `auto` | They have the same names as the app's settings. The app keeps its settings in the browser, so t3tui keeps its own, and turns the two alert settings on by default where the app leaves them off. diff --git a/src/bin.ts b/src/bin.ts index a08591b..4bc6f2f 100755 --- a/src/bin.ts +++ b/src/bin.ts @@ -162,9 +162,14 @@ async function runUi(attachNeedle?: string) { setInterval(() => { if (Date.now() - lastInput > 5_000) Bun.gc(true); }, 30_000).unref(); - const { applyTheme } = await import("./ui/theme.ts"); - // Terminals that don't say what their background is get the dark palette. - applyTheme(config.theme === "auto" ? ((await renderer.waitForThemeMode(300)) ?? "dark") : config.theme); + const { applyTheme, terminalPalette, themeModeOf } = await import("./ui/theme.ts"); + if (config.theme === "dark" || config.theme === "light") applyTheme(config.theme); + else { + // The terminal's colours through OSC 4, 10 and 11; terminals that don't answer get the dark palette. + const detected = await renderer.getPalette({ timeout: 300, size: 16 }).catch(() => null); + const mode = themeModeOf(detected) ?? renderer.themeMode ?? "dark"; + applyTheme(config.theme === "terminal" ? (terminalPalette(detected) ?? mode) : mode); + } createRoot(renderer).render(createElement(App, { session, config, layout, ...(attachThreadId ? { attachThreadId } : {}) })); } diff --git a/src/config.ts b/src/config.ts index c46007b..97cd38c 100644 --- a/src/config.ts +++ b/src/config.ts @@ -18,8 +18,8 @@ export interface T3tuiConfig { readonly notificationMode: "off" | "notifications" | "sound" | "notifications-and-sound"; /** As the web's in-app toasts: a line at the bottom for threads you aren't looking at. */ readonly inAppNotificationsEnabled: boolean; - /** auto follows the terminal's background colour. */ - readonly theme: "auto" | "dark" | "light"; + /** auto picks dark or light from the terminal's background; terminal builds the palette from its colours. */ + readonly theme: "auto" | "dark" | "light" | "terminal"; } export const DEFAULT_CONFIG: T3tuiConfig = { followUpBehavior: "steer", sendShortcut: "enter", timestampFormat: "locale", diffIgnoreWhitespace: true, notificationMode: "sound", inAppNotificationsEnabled: true, theme: "auto" }; @@ -32,7 +32,7 @@ export const CONFIG_CHOICES: { readonly [K in keyof T3tuiConfig]: readonly T3tui diffIgnoreWhitespace: [true, false], notificationMode: ["off", "sound", "notifications", "notifications-and-sound"], inAppNotificationsEnabled: [true, false], - theme: ["auto", "dark", "light"], + theme: ["auto", "dark", "light", "terminal"], }; export const configPath = () => join(configDir(), "config.json"); diff --git a/src/model/settings.ts b/src/model/settings.ts index fae78b3..c5c4092 100644 --- a/src/model/settings.ts +++ b/src/model/settings.ts @@ -21,7 +21,7 @@ const LABELS: { readonly [K in keyof T3tuiConfig]: { readonly label: string; rea values: { off: "off", sound: "bell", notifications: "desktop notifications", "notifications-and-sound": "bell and desktop notifications" }, }, inAppNotificationsEnabled: { label: "In-app alerts", help: "a line at the bottom for other threads", values: { true: "on", false: "off" } }, - theme: { label: "Colours", help: "from the next start", values: { auto: "match the terminal", dark: "dark", light: "light" } }, + theme: { label: "Colours", help: "from the next start", values: { auto: "dark or light, as the terminal is", dark: "dark", light: "light", terminal: "the terminal's own colours" } }, }; /** t3tui's own settings, in display order, each cycled with enter. */ diff --git a/src/ui/theme.ts b/src/ui/theme.ts index 025f60a..e09a6fb 100644 --- a/src/ui/theme.ts +++ b/src/ui/theme.ts @@ -1,4 +1,4 @@ -import { type NativeResourceOwner, SyntaxStyle, type ThemeMode } from "@opentui/core"; +import { type NativeResourceOwner, SyntaxStyle, type TerminalColors, type ThemeMode } from "@opentui/core"; import { useRenderer } from "@opentui/react"; import type { StatusTone } from "../model/threads.ts"; @@ -79,11 +79,83 @@ const LIGHT: Palette = { /** The palette in use. Read at render time, so applyTheme before the first frame sets it everywhere. */ export const colors: Palette = { ...DARK }; -export function applyTheme(mode: ThemeMode): void { - Object.assign(colors, mode === "light" ? LIGHT : DARK); +/** Sets the palette: the dark or light one, or one built with terminalPalette. */ +export function applyTheme(theme: ThemeMode | Palette): void { + Object.assign(colors, theme === "light" ? LIGHT : theme === "dark" ? DARK : theme); markdownStyles = new WeakMap(); } +/** Dark or light, by the background's luminance; null if the terminal didn't say. */ +export function themeModeOf(terminal: TerminalColors | null): ThemeMode | null { + const background = rgb(terminal?.defaultBackground ?? null); + if (!background) return null; + const [r, g, b] = background; + return 0.2126 * r + 0.7152 * g + 0.0722 * b > 127 ? "light" : "dark"; +} + +/** + * The terminal's own colours as a palette: panels and raised blocks a few small steps off + * its background, text from its foreground, status hues from its ANSI colours. Null without + * a background and foreground; colours it didn't report come from the dark or light palette. + */ +export function terminalPalette(terminal: TerminalColors | null): Palette | null { + const mode = themeModeOf(terminal); + const bg = terminal?.defaultBackground; + const text = terminal?.defaultForeground; + if (!mode || !bg || !text || !rgb(text)) return null; + const base = mode === "light" ? LIGHT : DARK; + const ansi = (index: number, fallback: string) => (rgb(terminal.palette[index] ?? null) ? terminal.palette[index]! : fallback); + // Lighter steps on a dark background, darker on a light one. + const step = (amount: number) => mix(bg, mode === "dark" ? "#ffffff" : "#000000", amount); + const accent = ansi(12, ansi(4, base.accent)); + const good = ansi(2, base.good); + const bad = ansi(1, base.bad); + const cyan = ansi(6, base.info); + return { + bg, + panel: step(0.04), + element: step(0.08), + elementHover: step(0.12), + border: mix(bg, text, 0.22), + borderFocused: accent, + text, + muted: mix(text, bg, 0.4), + faint: mix(text, bg, 0.6), + accent, + user: cyan, + userBg: step(0.08), + good, + bad, + warn: ansi(3, base.warn), + selectedBg: mix(bg, accent, 0.22), + hoverBg: step(0.06), + buttonBg: step(0.08), + info: cyan, + input: ansi(5, base.input), + plan: ansi(11, ansi(3, base.plan)), + diffAddedBg: mix(bg, good, 0.14), + diffRemovedBg: mix(bg, bad, 0.14), + diffGutterBg: step(0.03), + diffAddedGutterBg: mix(bg, good, 0.26), + diffRemovedGutterBg: mix(bg, bad, 0.26), + diffAddedSign: good, + diffRemovedSign: bad, + }; +} + +/** A `#rrggbb` colour's channels, or null for anything else. */ +function rgb(hex: string | null): [number, number, number] | null { + const match = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(hex ?? ""); + return match ? [Number.parseInt(match[1]!, 16), Number.parseInt(match[2]!, 16), Number.parseInt(match[3]!, 16)] : null; +} + +/** `amount` of the way from one colour to another. */ +function mix(from: string, to: string, amount: number): string { + const a = rgb(from)!; + const b = rgb(to)!; + return `#${a.map((channel, index) => Math.round(channel + (b[index]! - channel) * amount).toString(16).padStart(2, "0")).join("")}`; +} + const STATUS_COLORS: Record = { info: "info", muted: "muted", warn: "warn", input: "input", bad: "bad", good: "good" }; export const statusColor = (tone: StatusTone): string => colors[STATUS_COLORS[tone]]; diff --git a/test/app/app.test.tsx b/test/app/app.test.tsx index d889618..c9f7553 100644 --- a/test/app/app.test.tsx +++ b/test/app/app.test.tsx @@ -128,6 +128,17 @@ describe("palette and pickers", () => { expect(app.hints()).toStartWith("j/k threads"); }); + test("settings offer the terminal's own colours", async () => { + const app = await open({ config: { theme: "light" } }); + await app.press("k", { ctrl: true }); + await app.type("settings"); + await app.press("return"); + const row = app.find("Colours"); + expect(app.frame()).toMatch(/Colours\s+light/); + await app.click(row.x, row.y); + expect(app.frame()).toMatch(/Colours\s+the terminal's own colours/); + }); + test(". opens the thread's actions, and choosing one runs it", async () => { const app = await open(); await app.press("."); diff --git a/test/theme.test.ts b/test/theme.test.ts index c75f865..0c06fb9 100644 --- a/test/theme.test.ts +++ b/test/theme.test.ts @@ -1,6 +1,6 @@ import { afterEach, expect, test } from "bun:test"; -import { applyTheme, colors, statusColor, toneColor } from "../src/ui/theme.ts"; +import { applyTheme, colors, statusColor, terminalPalette, themeModeOf, toneColor } from "../src/ui/theme.ts"; afterEach(() => applyTheme("dark")); @@ -13,3 +13,46 @@ test("the light palette replaces every colour, and the tone maps follow it", () applyTheme("dark"); expect(colors).toEqual(dark); }); + +const terminal = (background: string | null, foreground: string | null, palette: (string | null)[] = []) => + ({ palette, defaultForeground: foreground, defaultBackground: background, cursorColor: null, mouseForeground: null, mouseBackground: null, tekForeground: null, tekBackground: null, highlightBackground: null, highlightForeground: null }) as const; +const ansi = ["#000000", "#cc0000", "#00aa00", "#aaaa00", "#0000cc", "#aa00aa", "#00aaaa", "#cccccc", "#555555", "#ff5555", "#55ff55", "#ffff55", "#5555ff", "#ff55ff", "#55ffff", "#ffffff"]; + +test("auto reads dark or light from the terminal's background, and nothing without one", () => { + expect(themeModeOf(terminal("#1d1f21", "#c5c8c6"))).toBe("dark"); + expect(themeModeOf(terminal("#fdf6e3", "#657b83"))).toBe("light"); + expect(themeModeOf(terminal(null, null))).toBeNull(); + expect(themeModeOf(null)).toBeNull(); +}); + +test("the terminal palette steps off the terminal's background and takes its ANSI hues", () => { + const palette = terminalPalette(terminal("#202020", "#d0d0d0", ansi))!; + expect(palette.bg).toBe("#202020"); + expect(palette.text).toBe("#d0d0d0"); + // Small steps lighter, in order. + const lightness = (hex: string) => Number.parseInt(hex.slice(1, 3), 16); + expect(lightness(palette.panel)).toBeGreaterThan(lightness(palette.bg)); + expect(lightness(palette.element)).toBeGreaterThan(lightness(palette.panel)); + expect(lightness(palette.element) - lightness(palette.bg)).toBeLessThan(30); + expect(palette.bad).toBe("#cc0000"); + expect(palette.good).toBe("#00aa00"); + expect(palette.warn).toBe("#aaaa00"); + expect(palette.accent).toBe("#5555ff"); + expect(palette.info).toBe("#00aaaa"); + for (const value of Object.values(palette)) expect(value).toMatch(/^#[0-9a-f]{6}$/); +}); + +test("on a light terminal the steps go darker, and missing ANSI colours come from the light palette", () => { + const palette = terminalPalette(terminal("#fafafa", "#202020"))!; + expect(palette.panel < palette.bg).toBe(true); + applyTheme("light"); + expect(palette.good).toBe(colors.good); + applyTheme(palette); + expect(colors.bg).toBe("#fafafa"); + expect(statusColor("good")).toBe(palette.good); +}); + +test("without the terminal's colours there is no terminal palette", () => { + expect(terminalPalette(terminal("#202020", null, ansi))).toBeNull(); + expect(terminalPalette(null)).toBeNull(); +});