mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-20 10:18:46 +03:00
feat(app): let GUI plugins add color themes (#61485)
This commit is contained in:
committed by
GitHub
Unverified
parent
15a863346f
commit
4dd7b2662c
@@ -41,7 +41,8 @@ import { createInstalled } from "../src/runtime/plugin/installed"
|
||||
import { pluginEnabled, type Entry } from "@opencode/plugin/gui/host"
|
||||
import { createRegion, RegionContent } from "../src/runtime/plugin/panels"
|
||||
import { createClosedTabs } from "../src/runtime/plugin/closed-tabs"
|
||||
import { PluginSlot } from "../src/runtime/plugin/render"
|
||||
import { PluginSlot, PluginThemes } from "../src/runtime/plugin/render"
|
||||
import { ThemeProvider, useTheme } from "@opencode/ui/theme/context"
|
||||
import { persistedHandle } from "../src/runtime/plugin/stores"
|
||||
import { LanguageProvider } from "../src/runtime/i18n/language"
|
||||
import { ExtensionPlugins } from "../src/runtime/plugin/extension-plugins"
|
||||
@@ -58,6 +59,7 @@ export {
|
||||
Panel,
|
||||
Slot,
|
||||
Store,
|
||||
Theme,
|
||||
} from "@opencode/plugin/gui"
|
||||
|
||||
export { Schema }
|
||||
@@ -557,6 +559,65 @@ export function mountSessionRegion(input: {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Mounts the real host's theme contributions into the app's theme provider, as the window does. `options` reads the
|
||||
* theme picker's choices as Settings › Appearance lists them; `disable` and `enable` toggle a plugin as
|
||||
* Extensions › Plugins does. With `pending`, the plugin list has not arrived until `load()`. `applied` counts the
|
||||
* provider's `onThemeApplied` calls, which show a desktop window.
|
||||
*/
|
||||
export function mountThemes(input: { definitions: readonly Entry[]; pending?: true }) {
|
||||
const container = document.createElement("div")
|
||||
document.body.appendChild(container)
|
||||
const [disabled, setDisabled] = createSignal<ReadonlySet<string>>(new Set())
|
||||
const [loaded, setLoaded] = createSignal(!input.pending)
|
||||
const hosts: PluginHost[] = []
|
||||
const themes: ReturnType<typeof useTheme>[] = []
|
||||
const applied = { count: 0 }
|
||||
|
||||
function Capture() {
|
||||
hosts.push(usePluginHost())
|
||||
themes.push(useTheme())
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
const dispose = render(
|
||||
() => (
|
||||
<ThemeProvider onThemeApplied={() => void applied.count++}>
|
||||
<LanguageProvider locale="en">
|
||||
<DialogProvider>
|
||||
<PluginHostProvider
|
||||
definitions={() => input.definitions}
|
||||
disabled={disabled}
|
||||
apis={fakeApis(unused)}
|
||||
whenMounted={mounted}
|
||||
>
|
||||
<PluginThemes loaded={loaded} />
|
||||
<Capture />
|
||||
</PluginHostProvider>
|
||||
</DialogProvider>
|
||||
</LanguageProvider>
|
||||
</ThemeProvider>
|
||||
),
|
||||
container,
|
||||
)
|
||||
|
||||
return {
|
||||
status: (id: string) => hosts[0]?.state.status[id],
|
||||
options: () => themes[0]?.ids().map((id) => ({ id, name: themes[0]?.name(id) })) ?? [],
|
||||
select: (id: string) => themes[0]?.setTheme(id),
|
||||
selected: () => themes[0]?.themeId(),
|
||||
applied: () => applied.count,
|
||||
load: () => setLoaded(true),
|
||||
disable: (id: string) => setDisabled(new Set([id])),
|
||||
enable: () => setDisabled(new Set<string>()),
|
||||
unmount: () => {
|
||||
dispose()
|
||||
container.remove()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Mounts the real host and the composer lane's plugin pills for one session, as the composer region renders them
|
||||
* (right-aligned). The session's directory is `/repo`.
|
||||
|
||||
@@ -1424,6 +1424,111 @@ story("startup enable state does not wait for the manager, and live updates beat
|
||||
})
|
||||
})
|
||||
|
||||
story(
|
||||
"a plugin theme joins the theme picker and leaves it with its plugin, keeping the user's choice",
|
||||
async ({ page }) => {
|
||||
const result = await page.evaluate(async (fixture) => {
|
||||
const { mountThemes, until, Theme } = await import(fixture)
|
||||
const root = document.documentElement
|
||||
|
||||
const variant = {
|
||||
palette: {
|
||||
neutral: "#101418",
|
||||
ink: "#e6edf3",
|
||||
primary: "#009fff",
|
||||
success: "#3fb950",
|
||||
warning: "#d29922",
|
||||
error: "#f85149",
|
||||
info: "#a371f7",
|
||||
},
|
||||
}
|
||||
|
||||
const host = mountThemes({
|
||||
definitions: [
|
||||
{
|
||||
id: "acme",
|
||||
windowEntry: async () => ({
|
||||
default: (ctx: Context) =>
|
||||
void ctx.add(Theme, {
|
||||
$schema: "https://opencode.ai/desktop-theme.json",
|
||||
name: "Midnight",
|
||||
id: "midnight",
|
||||
light: variant,
|
||||
dark: variant,
|
||||
}),
|
||||
}),
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
await until(() => host.status("acme") === "active")
|
||||
const names = host.options().map((option: { name: string }) => option.name)
|
||||
const index = names.indexOf("Midnight")
|
||||
host.select("acme:midnight")
|
||||
await until(() => root.dataset.theme === "acme:midnight")
|
||||
|
||||
host.disable("acme")
|
||||
await until(() => root.dataset.theme === "oc-2")
|
||||
|
||||
const withdrawn = {
|
||||
listed: host.options().some((option: { id: string }) => option.id === "acme:midnight"),
|
||||
selected: host.selected(),
|
||||
stored: localStorage.getItem("opencode-theme-id"),
|
||||
}
|
||||
|
||||
host.enable()
|
||||
await until(() => root.dataset.theme === "acme:midnight")
|
||||
const restored = host.selected()
|
||||
host.unmount()
|
||||
|
||||
return { neighbors: names.slice(index - 1, index + 2), withdrawn, restored }
|
||||
}, fixture)
|
||||
|
||||
expect(result).toEqual({
|
||||
// Alphabetical among the app's themes, not appended after them.
|
||||
neighbors: ["Mercury", "Midnight", "Monokai"],
|
||||
withdrawn: { listed: false, selected: "oc-2", stored: "acme:midnight" },
|
||||
restored: "acme:midnight",
|
||||
})
|
||||
},
|
||||
)
|
||||
|
||||
story("a selected plugin theme that never returns shows the default theme once plugins settle", async ({ page }) => {
|
||||
const result = await page.evaluate(async (fixture) => {
|
||||
const { mountThemes, until } = await import(fixture)
|
||||
const root = document.documentElement
|
||||
// The last run picked a theme whose plugin is now uninstalled, and cached its colors.
|
||||
localStorage.setItem("opencode-theme-id", "gone:midnight")
|
||||
localStorage.setItem("opencode-theme-css-dark", "--background-base:#010203;")
|
||||
localStorage.setItem("opencode-theme-css-light", "--background-base:#010203;")
|
||||
|
||||
const host = mountThemes({ definitions: [], pending: true })
|
||||
// The window is ready to show on the cached colors while the plugin list is still on its way.
|
||||
await until(() => host.applied() > 0)
|
||||
const waiting = host.selected()
|
||||
// The frame's own provider already shows the default theme; mark the root to see this provider apply it.
|
||||
root.dataset.theme = "frame"
|
||||
|
||||
host.load()
|
||||
await until(() => root.dataset.theme === "oc-2")
|
||||
|
||||
const settled = {
|
||||
selected: host.selected(),
|
||||
stored: localStorage.getItem("opencode-theme-id"),
|
||||
cached: localStorage.getItem("opencode-theme-css-dark") ?? localStorage.getItem("opencode-theme-css-light"),
|
||||
}
|
||||
|
||||
host.unmount()
|
||||
|
||||
return { waiting, settled }
|
||||
}, fixture)
|
||||
|
||||
expect(result).toEqual({
|
||||
waiting: "gone:midnight",
|
||||
settled: { selected: "oc-2", stored: "gone:midnight", cached: null },
|
||||
})
|
||||
})
|
||||
|
||||
story("composer pills show per session, open their rows, and fail only their own plugin", async ({ page }) => {
|
||||
const statuses = await page.evaluate(async (fixture) => {
|
||||
const { mountComposerPills, until, ComposerPill } = await import(fixture)
|
||||
|
||||
@@ -59,11 +59,7 @@ export function AppBaseProviders(
|
||||
<MetaProvider>
|
||||
<Title>OpenCode</Title>
|
||||
<Font />
|
||||
<ThemeProvider
|
||||
onThemeApplied={(_, mode, scheme) => {
|
||||
props.onThemeApplied?.(mode, scheme)
|
||||
}}
|
||||
>
|
||||
<ThemeProvider onThemeApplied={(mode, scheme) => props.onThemeApplied?.(mode, scheme)}>
|
||||
<LanguageProvider locale={props.locale} onNativeTranslations={props.onNativeTranslations}>
|
||||
<UiI18nBridge>
|
||||
<ErrorBoundary
|
||||
|
||||
@@ -1,9 +1,22 @@
|
||||
import { createMemo, ErrorBoundary, For, onMount, Show, untrack, type JSX, type ParentProps } from "solid-js"
|
||||
import {
|
||||
createEffect,
|
||||
createMemo,
|
||||
ErrorBoundary,
|
||||
For,
|
||||
onCleanup,
|
||||
onMount,
|
||||
Show,
|
||||
untrack,
|
||||
type JSX,
|
||||
type ParentProps,
|
||||
} from "solid-js"
|
||||
import { Portal } from "solid-js/web"
|
||||
import { MarkdownProvider, useMarkdown } from "@opencode/session-ui/context/markdown"
|
||||
import { SourcesProvider } from "@opencode/session-ui/context/sources"
|
||||
import { sourcesExperiment } from "@opencode/session-ui/sources/experiment"
|
||||
import { Style, type MountedSession } from "@opencode/plugin/gui"
|
||||
import { useTheme } from "@opencode/ui/theme/context"
|
||||
import type { DesktopTheme } from "@opencode/ui/theme/types"
|
||||
import { Style, Theme, type MountedSession } from "@opencode/plugin/gui"
|
||||
import { BuiltinSlot, type BuiltinSlotMap } from "@opencode/plugin/gui/builtin"
|
||||
import { PluginContext } from "@opencode/plugin/gui/host"
|
||||
import { usePluginHost } from "./host"
|
||||
@@ -73,6 +86,46 @@ export function PluginStyles() {
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists each contributed theme in the theme picker, keyed by plugin, while it is contributed. Once every plugin the
|
||||
* window runs has settled (`loaded`: the plugin list has arrived), a selected theme no plugin contributed is not
|
||||
* coming, and the theme provider shows the default theme.
|
||||
*/
|
||||
export function PluginThemes(props: { loaded: () => boolean }) {
|
||||
const host = usePluginHost()
|
||||
const theme = useTheme()
|
||||
|
||||
const settled = createMemo(
|
||||
() =>
|
||||
props.loaded() &&
|
||||
host.ready() &&
|
||||
host.definitions().every((definition) => {
|
||||
if (!definition.windowEntry) return true
|
||||
|
||||
const status = host.state.status[definition.id]
|
||||
|
||||
return status === "active" || status === "failed" || status === "disabled"
|
||||
}),
|
||||
)
|
||||
|
||||
// Hands the settled plugin set to the theme provider, outside the plugin host.
|
||||
createEffect(() => {
|
||||
if (settled()) theme.settle()
|
||||
})
|
||||
|
||||
return (
|
||||
<For each={host.items(Theme)}>
|
||||
{(item) => {
|
||||
// SAFETY: an SDK theme has the bundled themes' shape with colors typed as plain strings; the resolver parses
|
||||
// any string without throwing (a malformed color resolves to black), so the narrower color types add nothing.
|
||||
onCleanup(theme.registerTheme({ ...item.value, id: `${item.plugin}:${item.value.id}` } as DesktopTheme))
|
||||
|
||||
return null
|
||||
}}
|
||||
</For>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Routes local markdown links in the session to plugin LinkHandler contributions, keeping image loading. A turn's
|
||||
* sources chip opens its turn through the Sources plugin's handler.
|
||||
|
||||
@@ -9,7 +9,7 @@ import { PluginHostProvider, usePluginHost } from "./host"
|
||||
import { createIpcClients } from "./ipc"
|
||||
import { createPluginAttachment, createHostApis, PluginAttachmentProvider, type HostApis } from "./host-apis"
|
||||
import { PluginCommands } from "./commands"
|
||||
import { PluginStyles } from "./render"
|
||||
import { PluginStyles, PluginThemes } from "./render"
|
||||
import { PluginServersProvider } from "./servers"
|
||||
import { PluginServerEndpoints } from "./server-shell"
|
||||
import { createContext, useContext } from "solid-js"
|
||||
@@ -54,15 +54,16 @@ export function PluginRoot(props: ParentProps) {
|
||||
|
||||
const localBuiltins = builtins.filter((definition) => runsOn(definition, os))
|
||||
|
||||
// The GUIs of the plugins on the app's own server, as main sends them.
|
||||
const [plugins, setPlugins] = createSignal<readonly PluginGui[]>([])
|
||||
// The GUIs of the plugins on the app's own server, as main sends them; undefined until main first sends them. The web
|
||||
// runs built-ins only.
|
||||
const [plugins, setPlugins] = createSignal<readonly PluginGui[] | undefined>(bridge ? undefined : [])
|
||||
// Plugins whose GUI cannot load because a built-in claims the id, as main reports them; Extensions › Plugins shows
|
||||
// them.
|
||||
const [reserved, setReserved] = createSignal<readonly string[]>([])
|
||||
|
||||
// The same definitions in the same order are no change, so a refetch that found nothing new restarts nothing.
|
||||
const definitions = createMemo<readonly Entry[]>(
|
||||
() => [...localBuiltins, ...plugins().map((plugin) => plugin.definition)],
|
||||
() => [...localBuiltins, ...(plugins() ?? []).map((plugin) => plugin.definition)],
|
||||
[],
|
||||
{
|
||||
equals: (a, b) => a.length === b.length && a.every((definition, index) => definition === b[index]),
|
||||
@@ -107,11 +108,12 @@ export function PluginRoot(props: ParentProps) {
|
||||
apis={apis.apis}
|
||||
whenMounted={apis.whenMounted}
|
||||
ipc={bridge ? (token) => ipcs.client(token) : undefined}
|
||||
plugin={(id) => plugins().find((plugin) => plugin.definition.id === id)}
|
||||
plugin={(id) => plugins()?.find((plugin) => plugin.definition.id === id)}
|
||||
generation={ipcs.generation}
|
||||
failed={failed}
|
||||
>
|
||||
<PluginStyles />
|
||||
<PluginThemes loaded={() => plugins() !== undefined} />
|
||||
{PluginHotReload && (
|
||||
<Suspense>
|
||||
<PluginHotReload />
|
||||
|
||||
@@ -252,6 +252,7 @@ SDK icon fields take an `IconName` from `@opencode/plugin/gui`: the names of the
|
||||
| [`ComposerPill`](../plugin/src/gui/registries.ts) | window | A pill in the row above a session's composer, optionally opening a menu of rows or a popover of your own content |
|
||||
| [`Slot`](../plugin/src/gui/registries.ts) | window | Content for `window.bottom`, `session.header`, `session.location.menu`, `session.panel.end`; built-ins also fill `session.location.workspace`, `session.location.branch.menu` and `session.location.path.menu` through `BuiltinSlot` |
|
||||
| [`Style`](../plugin/src/gui/registries.ts) | window | CSS imported with `?inline` |
|
||||
| [`Theme`](../plugin/src/gui/registries.ts) | window | A color theme in the app's theme file format, listed in Settings › Appearance › Theme |
|
||||
| [`MenubarItem`](../plugin/src/gui/main.ts) | main | An item of the native app menu |
|
||||
|
||||
`session.location.menu` contributes items after the project menu's location details. It receives the owning `screen`,
|
||||
|
||||
@@ -673,6 +673,103 @@ export interface ComposerPill {
|
||||
menu?(input: ComposerPillMenuProps): JSX.Element
|
||||
}
|
||||
|
||||
/**
|
||||
* The seed colors a theme variant generates its scales from. Each is a hex color: `#rgb`, `#rgba`, `#rrggbb` or
|
||||
* `#rrggbbaa`.
|
||||
*/
|
||||
export interface ThemeSeedColors {
|
||||
/** Base of the gray scale. */
|
||||
readonly neutral: string
|
||||
/** The brand and accent color. */
|
||||
readonly primary: string
|
||||
/** Success states, usually green. */
|
||||
readonly success: string
|
||||
/** Warning states, usually yellow or orange. */
|
||||
readonly warning: string
|
||||
/** Error and critical states, usually red. */
|
||||
readonly error: string
|
||||
/** Informational states, usually blue or purple. */
|
||||
readonly info: string
|
||||
/** Links and interactive elements. */
|
||||
readonly interactive: string
|
||||
/** Added lines in diffs. */
|
||||
readonly diffAdd: string
|
||||
/** Deleted lines in diffs. */
|
||||
readonly diffDelete: string
|
||||
}
|
||||
|
||||
/**
|
||||
* The palette a theme variant derives its colors from, the form most of the app's own themes use. Each is a hex color:
|
||||
* `#rgb`, `#rgba`, `#rrggbb` or `#rrggbbaa`.
|
||||
*/
|
||||
export interface ThemePaletteColors {
|
||||
/** The background the neutral scale starts from. */
|
||||
readonly neutral: string
|
||||
/** The text color the neutral scale ends at. */
|
||||
readonly ink: string
|
||||
/** The brand color. */
|
||||
readonly primary: string
|
||||
/** Success states, usually green. */
|
||||
readonly success: string
|
||||
/** Warning states, usually yellow or orange. */
|
||||
readonly warning: string
|
||||
/** Error and critical states, usually red. */
|
||||
readonly error: string
|
||||
/** Informational states, usually blue or purple. */
|
||||
readonly info: string
|
||||
/** A secondary accent. Defaults to `info`. */
|
||||
readonly accent?: string
|
||||
/** Links and interactive elements. Defaults to `primary`. */
|
||||
readonly interactive?: string
|
||||
/** Added lines in diffs. Defaults to one derived from `success`. */
|
||||
readonly diffAdd?: string
|
||||
/** Deleted lines in diffs. Defaults to one derived from `error`. */
|
||||
readonly diffDelete?: string
|
||||
}
|
||||
|
||||
/** The fields every theme variant can have, whichever colors it starts from. */
|
||||
interface ThemeVariantBase {
|
||||
/** Exact values for single tokens, such as `syntax-keyword`: a hex color or a `var(--token)` reference. */
|
||||
readonly overrides?: Readonly<Record<string, string>>
|
||||
/** Exact values for single tokens of the app's newer token set: a hex color, a `var(--token)` reference, or CSS. */
|
||||
readonly v2Overrides?: Readonly<Record<string, string>>
|
||||
}
|
||||
|
||||
/** The colors of one color scheme of a `Theme`: generated from `seeds` or from a `palette`, never both. */
|
||||
export type ThemeVariant =
|
||||
| (ThemeVariantBase & {
|
||||
/** The seed colors to generate from. */
|
||||
readonly seeds: ThemeSeedColors
|
||||
/** Not allowed beside `seeds`. */
|
||||
readonly palette?: never
|
||||
})
|
||||
| (ThemeVariantBase & {
|
||||
/** The palette to derive from. */
|
||||
readonly palette: ThemePaletteColors
|
||||
/** Not allowed beside `palette`. */
|
||||
readonly seeds?: never
|
||||
})
|
||||
|
||||
/**
|
||||
* A color theme, in the format of the app's own themes (`https://opencode.ai/desktop-theme.json`), so a theme file
|
||||
* imports as it is. The host lists it in Settings › Appearance › Theme among the app's themes, alphabetically by
|
||||
* `name`, under the key `${plugin}:${id}`; withdrawing the theme takes it out of the list. A user who picked it keeps the choice: the window
|
||||
* shows the theme's colors from the last run until the plugin contributes it again, and the default theme while it is
|
||||
* withdrawn.
|
||||
*/
|
||||
export interface Theme {
|
||||
/** The JSON Schema reference of a theme file. Ignored. */
|
||||
readonly $schema?: string
|
||||
/** The name the theme list shows. */
|
||||
readonly name: string
|
||||
/** The theme's id, unique within the plugin, in lowercase letters, digits and hyphens. */
|
||||
readonly id: string
|
||||
/** The light color scheme. */
|
||||
readonly light: ThemeVariant
|
||||
/** The dark color scheme. */
|
||||
readonly dark: ThemeVariant
|
||||
}
|
||||
|
||||
/** The places a `Slot` renders, with the input each passes to `render`. */
|
||||
export interface SlotMap {
|
||||
/** Full-width strip under the window content, above toasts. */
|
||||
@@ -847,3 +944,14 @@ export const Slot = Registry.define<Slot>("slot")
|
||||
* ```
|
||||
*/
|
||||
export const Style = Registry.define<string>("style")
|
||||
|
||||
/**
|
||||
* The registry of color themes the user can pick in Settings › Appearance, in the format of the app's own theme files.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import theme from "./midnight.json"
|
||||
* ctx.add(Theme, theme)
|
||||
* ```
|
||||
*/
|
||||
export const Theme = Registry.define<Theme>("theme")
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Type-level contract of the registries, checked by `bun typecheck`. Nothing imports this file. Each `@ts-expect-error`
|
||||
// fails the typecheck if its line stops being an error.
|
||||
import { Plugin } from "./index.js"
|
||||
import { MenuItem, TitlebarItem } from "./index.js"
|
||||
import { MenuItem, Theme, TitlebarItem } from "./index.js"
|
||||
|
||||
const Fixture = Plugin.define({})
|
||||
|
||||
@@ -33,3 +33,31 @@ export const menus: Plugin.Setup<typeof Fixture> = (ctx) => {
|
||||
// A pill without `run` only shows its label.
|
||||
ctx.add(TitlebarItem, { id: "status", label: "Ready" })
|
||||
}
|
||||
|
||||
const palette = {
|
||||
neutral: "#2e3440",
|
||||
ink: "#e5e9f0",
|
||||
primary: "#88c0d0",
|
||||
success: "#a3be8c",
|
||||
warning: "#d08770",
|
||||
error: "#bf616a",
|
||||
info: "#81a1c1",
|
||||
}
|
||||
|
||||
const seeds = { ...palette, interactive: "#88c0d0", diffAdd: "#a3be8c", diffDelete: "#bf616a" }
|
||||
|
||||
// Typed like an imported theme file: JSON modules widen every color to `string`.
|
||||
const file = {
|
||||
$schema: "https://opencode.ai/desktop-theme.json",
|
||||
name: "Nord",
|
||||
id: "nord",
|
||||
light: { palette, overrides: { "syntax-keyword": "var(--text-strong)" } },
|
||||
dark: { seeds },
|
||||
}
|
||||
|
||||
export const themes: Plugin.Setup<typeof Fixture> = (ctx) => {
|
||||
ctx.add(Theme, file)
|
||||
|
||||
// @ts-expect-error a variant starts from seeds or a palette, not both
|
||||
ctx.add(Theme, { ...file, light: { palette, seeds } })
|
||||
}
|
||||
|
||||
+139
-110
@@ -1,7 +1,7 @@
|
||||
// @refresh reload
|
||||
|
||||
import { createEffect, onMount } from "solid-js"
|
||||
import { createStore } from "solid-js/store"
|
||||
import { createEffect, createMemo, onMount } from "solid-js"
|
||||
import { createStore, produce, unwrap } from "solid-js/store"
|
||||
import { makeEventListener } from "@solid-primitives/event-listener"
|
||||
import { createSimpleContext } from "../context/helper"
|
||||
import oc2ThemeJson from "./themes/oc-2.json"
|
||||
@@ -11,6 +11,18 @@ import type { DesktopTheme } from "./types"
|
||||
|
||||
export type ColorScheme = "light" | "dark" | "system"
|
||||
|
||||
type ThemeState = {
|
||||
/** Loaded bundled themes and registered themes, by id. */
|
||||
themes: Record<string, DesktopTheme>
|
||||
themeId: string
|
||||
colorScheme: ColorScheme
|
||||
mode: "light" | "dark"
|
||||
previewThemeId: string | null
|
||||
previewScheme: ColorScheme | null
|
||||
/** Registered themes that have not arrived are not coming. */
|
||||
settled: boolean
|
||||
}
|
||||
|
||||
const STORAGE_KEYS = {
|
||||
THEME_ID: "opencode-theme-id",
|
||||
COLOR_SCHEME: "opencode-color-scheme",
|
||||
@@ -49,56 +61,53 @@ function knownThemes() {
|
||||
return known
|
||||
}
|
||||
|
||||
const names: Record<string, string> = {
|
||||
"oc-2": "OpenCode",
|
||||
amoled: "AMOLED",
|
||||
aura: "Aura",
|
||||
ayu: "Ayu",
|
||||
carbonfox: "Carbonfox",
|
||||
catppuccin: "Catppuccin",
|
||||
"catppuccin-frappe": "Catppuccin Frappe",
|
||||
"catppuccin-macchiato": "Catppuccin Macchiato",
|
||||
cobalt2: "Cobalt2",
|
||||
cursor: "Cursor",
|
||||
dracula: "Dracula",
|
||||
everforest: "Everforest",
|
||||
flexoki: "Flexoki",
|
||||
github: "GitHub",
|
||||
gruvbox: "Gruvbox",
|
||||
kanagawa: "Kanagawa",
|
||||
"lucent-orng": "Lucent Orng",
|
||||
material: "Material",
|
||||
matrix: "Matrix",
|
||||
mercury: "Mercury",
|
||||
monokai: "Monokai",
|
||||
nightowl: "Night Owl",
|
||||
nord: "Nord",
|
||||
"one-dark": "One Dark",
|
||||
onedarkpro: "One Dark Pro",
|
||||
orng: "Orng",
|
||||
"osaka-jade": "Osaka Jade",
|
||||
palenight: "Palenight",
|
||||
rosepine: "Rose Pine",
|
||||
shadesofpurple: "Shades of Purple",
|
||||
solarized: "Solarized",
|
||||
synthwave84: "Synthwave '84",
|
||||
tokyonight: "Tokyonight",
|
||||
vercel: "Vercel",
|
||||
vesper: "Vesper",
|
||||
zenburn: "Zenburn",
|
||||
}
|
||||
const names = new Map(
|
||||
Object.entries({
|
||||
"oc-2": "OpenCode",
|
||||
amoled: "AMOLED",
|
||||
aura: "Aura",
|
||||
ayu: "Ayu",
|
||||
carbonfox: "Carbonfox",
|
||||
catppuccin: "Catppuccin",
|
||||
"catppuccin-frappe": "Catppuccin Frappe",
|
||||
"catppuccin-macchiato": "Catppuccin Macchiato",
|
||||
cobalt2: "Cobalt2",
|
||||
cursor: "Cursor",
|
||||
dracula: "Dracula",
|
||||
everforest: "Everforest",
|
||||
flexoki: "Flexoki",
|
||||
github: "GitHub",
|
||||
gruvbox: "Gruvbox",
|
||||
kanagawa: "Kanagawa",
|
||||
"lucent-orng": "Lucent Orng",
|
||||
material: "Material",
|
||||
matrix: "Matrix",
|
||||
mercury: "Mercury",
|
||||
monokai: "Monokai",
|
||||
nightowl: "Night Owl",
|
||||
nord: "Nord",
|
||||
"one-dark": "One Dark",
|
||||
onedarkpro: "One Dark Pro",
|
||||
orng: "Orng",
|
||||
"osaka-jade": "Osaka Jade",
|
||||
palenight: "Palenight",
|
||||
rosepine: "Rose Pine",
|
||||
shadesofpurple: "Shades of Purple",
|
||||
solarized: "Solarized",
|
||||
synthwave84: "Synthwave '84",
|
||||
tokyonight: "Tokyonight",
|
||||
vercel: "Vercel",
|
||||
vesper: "Vesper",
|
||||
zenburn: "Zenburn",
|
||||
}),
|
||||
)
|
||||
|
||||
// SAFETY: oc-2.json follows desktop-theme.schema.json; JSON modules only widen its colors to `string`, and
|
||||
// v2/resolve.test.ts resolves the same file as a DesktopTheme.
|
||||
const oc2Theme = oc2ThemeJson as DesktopTheme
|
||||
|
||||
function resolveStoredTheme(id: string | null | undefined, registered?: Record<string, DesktopTheme>) {
|
||||
if (id === "oc-2" || (id && (knownThemes().has(id) || registered?.[id]))) return id
|
||||
|
||||
return "oc-2"
|
||||
}
|
||||
|
||||
// Storage access throws where localStorage is missing or blocked; every caller treats that as no stored value.
|
||||
function read(key: string) {
|
||||
if (typeof localStorage !== "object") return null
|
||||
|
||||
try {
|
||||
return localStorage.getItem(key)
|
||||
} catch {
|
||||
@@ -107,30 +116,32 @@ function read(key: string) {
|
||||
}
|
||||
|
||||
function write(key: string, value: string) {
|
||||
if (typeof localStorage !== "object") return
|
||||
|
||||
try {
|
||||
localStorage.setItem(key, value)
|
||||
} catch {}
|
||||
}
|
||||
|
||||
function drop(key: string) {
|
||||
if (typeof localStorage !== "object") return
|
||||
|
||||
try {
|
||||
localStorage.removeItem(key)
|
||||
} catch {}
|
||||
}
|
||||
|
||||
function readScheme(): ColorScheme {
|
||||
const value = read(STORAGE_KEYS.COLOR_SCHEME)
|
||||
|
||||
return value === "light" || value === "dark" ? value : "system"
|
||||
}
|
||||
|
||||
function clear() {
|
||||
drop(STORAGE_KEYS.THEME_CSS_LIGHT)
|
||||
drop(STORAGE_KEYS.THEME_CSS_DARK)
|
||||
}
|
||||
|
||||
function ensureThemeStyleElement(): HTMLStyleElement {
|
||||
const existing = document.getElementById(THEME_STYLE_ID) as HTMLStyleElement | null
|
||||
const existing = document.getElementById(THEME_STYLE_ID)
|
||||
|
||||
if (existing) return existing
|
||||
if (existing instanceof HTMLStyleElement) return existing
|
||||
const element = document.createElement("style")
|
||||
element.id = THEME_STYLE_ID
|
||||
document.head.appendChild(element)
|
||||
@@ -139,9 +150,7 @@ function ensureThemeStyleElement(): HTMLStyleElement {
|
||||
}
|
||||
|
||||
function getSystemMode(): "light" | "dark" {
|
||||
if (typeof window !== "object") return "light"
|
||||
|
||||
return window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light"
|
||||
return globalThis.matchMedia?.("(prefers-color-scheme: dark)").matches ? "dark" : "light"
|
||||
}
|
||||
|
||||
function applyThemeCss(theme: DesktopTheme, themeId: string, mode: "light" | "dark") {
|
||||
@@ -191,28 +200,31 @@ export const { use: useTheme, provider: ThemeProvider } = createSimpleContext({
|
||||
name: "Theme",
|
||||
init: (props: {
|
||||
defaultTheme?: string
|
||||
onThemeApplied?: (theme: DesktopTheme, mode: "light" | "dark", scheme: ColorScheme) => void
|
||||
/** The window shows the theme: its colors, or until a registered theme arrives, those cached from the last run. */
|
||||
onThemeApplied?: (mode: "light" | "dark", scheme: ColorScheme) => void
|
||||
}) => {
|
||||
const rawTheme = read(STORAGE_KEYS.THEME_ID) ?? props.defaultTheme
|
||||
const themeId = resolveStoredTheme(rawTheme)
|
||||
|
||||
if (rawTheme && rawTheme !== themeId) {
|
||||
write(STORAGE_KEYS.THEME_ID, themeId)
|
||||
clear()
|
||||
}
|
||||
|
||||
const colorScheme = (read(STORAGE_KEYS.COLOR_SCHEME) as ColorScheme | null) ?? "system"
|
||||
// An id no theme has yet stays selected until `settle`: a registered theme can arrive after startup.
|
||||
const themeId = read(STORAGE_KEYS.THEME_ID) || props.defaultTheme || "oc-2"
|
||||
const colorScheme = readScheme()
|
||||
const mode = colorScheme === "system" ? getSystemMode() : colorScheme
|
||||
|
||||
const [store, setStore] = createStore({
|
||||
const [store, setStore] = createStore<ThemeState>({
|
||||
themes: {
|
||||
"oc-2": oc2Theme,
|
||||
} as Record<string, DesktopTheme>,
|
||||
},
|
||||
themeId,
|
||||
colorScheme,
|
||||
mode,
|
||||
previewThemeId: null as string | null,
|
||||
previewScheme: null as ColorScheme | null,
|
||||
previewThemeId: null,
|
||||
previewScheme: null,
|
||||
settled: false,
|
||||
})
|
||||
|
||||
// The selected theme, or the default while it is not loaded, registered or coming.
|
||||
const active = createMemo(() => {
|
||||
const id = store.themeId
|
||||
|
||||
return knownThemes().has(id) || store.themes[id] || !store.settled ? id : "oc-2"
|
||||
})
|
||||
|
||||
const loads = new Map<string, Promise<DesktopTheme | undefined>>()
|
||||
@@ -249,32 +261,22 @@ export const { use: useTheme, provider: ThemeProvider } = createSimpleContext({
|
||||
|
||||
const applyTheme = (theme: DesktopTheme, themeId: string, mode: "light" | "dark", scheme: ColorScheme) => {
|
||||
applyThemeCss(theme, themeId, mode)
|
||||
props.onThemeApplied?.(theme, mode, scheme)
|
||||
props.onThemeApplied?.(mode, scheme)
|
||||
}
|
||||
|
||||
const ids = () => {
|
||||
const extra = Object.keys(store.themes)
|
||||
.filter((id) => !knownThemes().has(id))
|
||||
.sort()
|
||||
const name = (id: string) => store.themes[id]?.name ?? names.get(id) ?? id
|
||||
|
||||
const all = themeIDs()
|
||||
|
||||
if (extra.length === 0) return all
|
||||
|
||||
return [...all, ...extra]
|
||||
}
|
||||
// Bundled and registered themes in one list, alphabetical by name.
|
||||
const ids = () =>
|
||||
[...themeIDs(), ...Object.keys(store.themes).filter((id) => !knownThemes().has(id))].toSorted((a, b) =>
|
||||
name(a).localeCompare(name(b), undefined, { sensitivity: "base" }),
|
||||
)
|
||||
|
||||
const loadThemes = () => Promise.all(themeIDs().map(load)).then(() => store.themes)
|
||||
|
||||
const onStorage = (e: StorageEvent) => {
|
||||
if (e.key === STORAGE_KEYS.THEME_ID && e.newValue) {
|
||||
const next = resolveStoredTheme(e.newValue, store.themes)
|
||||
|
||||
if (next !== e.newValue) {
|
||||
write(STORAGE_KEYS.THEME_ID, next)
|
||||
clear()
|
||||
}
|
||||
|
||||
const next = e.newValue
|
||||
setStore("themeId", next)
|
||||
|
||||
if (next === "oc-2") {
|
||||
@@ -290,8 +292,9 @@ export const { use: useTheme, provider: ThemeProvider } = createSimpleContext({
|
||||
}
|
||||
|
||||
if (e.key === STORAGE_KEYS.COLOR_SCHEME && e.newValue) {
|
||||
setStore("colorScheme", e.newValue as ColorScheme)
|
||||
setStore("mode", e.newValue === "system" ? getSystemMode() : (e.newValue as "light" | "dark"))
|
||||
const scheme = readScheme()
|
||||
setStore("colorScheme", scheme)
|
||||
setStore("mode", scheme === "system" ? getSystemMode() : scheme)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -307,14 +310,8 @@ export const { use: useTheme, provider: ThemeProvider } = createSimpleContext({
|
||||
|
||||
makeEventListener(mediaQuery, "change", onMedia)
|
||||
|
||||
const rawTheme = read(STORAGE_KEYS.THEME_ID) ?? props.defaultTheme
|
||||
const savedTheme = resolveStoredTheme(rawTheme, store.themes)
|
||||
const savedScheme = (read(STORAGE_KEYS.COLOR_SCHEME) as ColorScheme | null) ?? "system"
|
||||
|
||||
if (rawTheme && rawTheme !== savedTheme) {
|
||||
write(STORAGE_KEYS.THEME_ID, savedTheme)
|
||||
clear()
|
||||
}
|
||||
const savedTheme = read(STORAGE_KEYS.THEME_ID) || props.defaultTheme || "oc-2"
|
||||
const savedScheme = readScheme()
|
||||
|
||||
if (savedTheme !== store.themeId) setStore("themeId", savedTheme)
|
||||
|
||||
@@ -327,10 +324,22 @@ export const { use: useTheme, provider: ThemeProvider } = createSimpleContext({
|
||||
})
|
||||
|
||||
createEffect(() => {
|
||||
const theme = store.themes[store.themeId]
|
||||
const id = active()
|
||||
const theme = store.themes[id]
|
||||
|
||||
if (!theme) return
|
||||
applyTheme(theme, store.themeId, store.mode, store.colorScheme)
|
||||
if (theme) {
|
||||
// The selected theme is gone, so the next start paints the default theme instead of its cached colors. The
|
||||
// choice stays stored and returns with the theme.
|
||||
if (id !== store.themeId) clear()
|
||||
applyTheme(theme, id, store.mode, store.colorScheme)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// A bundled theme is loading: keep what is on screen until it arrives.
|
||||
if (knownThemes().has(id)) return
|
||||
// A registered theme may still arrive: the colors cached from the last run stay on screen meanwhile.
|
||||
props.onThemeApplied?.(store.mode, store.colorScheme)
|
||||
})
|
||||
|
||||
const setTheme = (id: string) => {
|
||||
@@ -371,16 +380,35 @@ export const { use: useTheme, provider: ThemeProvider } = createSimpleContext({
|
||||
}
|
||||
|
||||
return {
|
||||
themeId: () => store.themeId,
|
||||
themeId: active,
|
||||
colorScheme: () => store.colorScheme,
|
||||
mode: () => store.mode,
|
||||
ids,
|
||||
name: (id: string) => store.themes[id]?.name ?? names[id] ?? id,
|
||||
name,
|
||||
loadThemes,
|
||||
themes: () => store.themes,
|
||||
setTheme,
|
||||
setColorScheme,
|
||||
registerTheme: (theme: DesktopTheme) => setStore("themes", theme.id, theme),
|
||||
/** Lists a theme beside the bundled ones until the returned function withdraws it. */
|
||||
registerTheme: (theme: DesktopTheme) => {
|
||||
setStore("themes", theme.id, theme)
|
||||
|
||||
return () => {
|
||||
// A theme registered again under the same id replaces this one; leave it.
|
||||
if (unwrap(store.themes)[theme.id] !== theme) return
|
||||
setStore(
|
||||
"themes",
|
||||
produce((themes) => {
|
||||
delete themes[theme.id]
|
||||
}),
|
||||
)
|
||||
}
|
||||
},
|
||||
/**
|
||||
* Every theme source has registered what it will: a selected theme that is still missing is not coming, so the
|
||||
* window shows the default theme and keeps the choice for when it returns.
|
||||
*/
|
||||
settle: () => setStore("settled", true),
|
||||
previewTheme: (id: string) => {
|
||||
const next = id
|
||||
|
||||
@@ -403,11 +431,11 @@ export const { use: useTheme, provider: ThemeProvider } = createSimpleContext({
|
||||
previewColorScheme: (scheme: ColorScheme) => {
|
||||
setStore("previewScheme", scheme)
|
||||
const mode = scheme === "system" ? getSystemMode() : scheme
|
||||
const id = store.previewThemeId ?? store.themeId
|
||||
const id = store.previewThemeId ?? active()
|
||||
void load(id).then((theme) => {
|
||||
if (!theme) return
|
||||
|
||||
if ((store.previewThemeId ?? store.themeId) !== id) return
|
||||
if ((store.previewThemeId ?? active()) !== id) return
|
||||
|
||||
if (store.previewScheme !== scheme) return
|
||||
applyTheme(theme, id, mode, scheme)
|
||||
@@ -428,9 +456,10 @@ export const { use: useTheme, provider: ThemeProvider } = createSimpleContext({
|
||||
cancelPreview: () => {
|
||||
setStore("previewThemeId", null)
|
||||
setStore("previewScheme", null)
|
||||
void load(store.themeId).then((theme) => {
|
||||
if (!theme) return
|
||||
applyTheme(theme, store.themeId, store.mode, store.colorScheme)
|
||||
const id = active()
|
||||
void load(id).then((theme) => {
|
||||
if (!theme || active() !== id) return
|
||||
applyTheme(theme, id, store.mode, store.colorScheme)
|
||||
})
|
||||
},
|
||||
}
|
||||
|
||||
@@ -1327,6 +1327,58 @@ import css from "./panel.css?inline"
|
||||
ctx.add(Style, css)
|
||||
```
|
||||
|
||||
### Themes
|
||||
|
||||
`Theme` adds a color theme to Settings › Appearance › Theme. It takes the same format as the app's own theme files, so
|
||||
a theme file imports as it is.
|
||||
|
||||
```ts
|
||||
import { Theme } from "@opencode/plugin/gui"
|
||||
import midnight from "./midnight.json"
|
||||
|
||||
ctx.add(Theme, midnight)
|
||||
```
|
||||
|
||||
A theme file names itself and gives a light and a dark variant. Each variant starts from a `palette` or from `seeds`,
|
||||
never both, and can pin single tokens with `overrides`.
|
||||
|
||||
```json
|
||||
{
|
||||
"$schema": "https://opencode.ai/desktop-theme.json",
|
||||
"name": "Midnight",
|
||||
"id": "midnight",
|
||||
"light": {
|
||||
"palette": {
|
||||
"neutral": "#eceff4",
|
||||
"ink": "#2e3440",
|
||||
"primary": "#5e81ac",
|
||||
"success": "#8fbcbb",
|
||||
"warning": "#d08770",
|
||||
"error": "#bf616a",
|
||||
"info": "#81a1c1"
|
||||
}
|
||||
},
|
||||
"dark": {
|
||||
"palette": {
|
||||
"neutral": "#1b1f27",
|
||||
"ink": "#e5e9f0",
|
||||
"primary": "#88c0d0",
|
||||
"success": "#a3be8c",
|
||||
"warning": "#d08770",
|
||||
"error": "#bf616a",
|
||||
"info": "#81a1c1"
|
||||
},
|
||||
"overrides": { "syntax-keyword": "#88c0d0" }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- The picker lists plugin themes among the app's themes, alphabetically by `name`.
|
||||
- The host keys each theme as `<plugin id>:<theme id>`, so it never replaces an app theme or another plugin's.
|
||||
- Withdrawing the theme, or disabling the plugin, takes it out of the picker. A user who picked it keeps the choice: the
|
||||
window shows the default theme until the theme returns.
|
||||
- At startup, the window shows the colors cached from the last run until the plugin contributes the theme again.
|
||||
|
||||
## Host APIs
|
||||
|
||||
Host APIs are properties of `ctx`. None of them throw before the app interface mounts: reads return their documented
|
||||
|
||||
Reference in New Issue
Block a user