fix(web): persist theme preference in settings

This commit is contained in:
Yichen Jiang
2026-08-06 20:27:31 +08:00
parent 6a32047e77
commit dd473870dd
30 changed files with 692 additions and 121 deletions

View File

@@ -10,7 +10,7 @@ import {
IconDarkOutline16, IconFollowsystemOutline16, IconLightOutline16,
} from '@deepseek-ai/dsh-client-ui-primitives'
import type { PropsLocale, PropsRuntime, PropsStore } from '@deepseek-ai/dsh-client-ui-slots'
import type { ThemePreference } from './index.ts'
import type { ThemePreference } from '../theme-settings.ts'
import type { ThemeKey } from './locales.ts'
import type {} from './settings-contract.ts'
import type { createAppearanceRowStore } from './settings-store.ts'

View File

@@ -1,12 +1,14 @@
/**
* Browser theme registry over the `--dsw-*` token stylesheets. The service
* owns the theme preference (light/dark/system), resolves `system` through
* owns the live theme preference (light/dark/system), resolves `system` through
* `prefers-color-scheme`, and publishes immutable snapshots; it never touches
* the DOM — ui-layout's presenter consumes the resolved snapshot. The plugin
* also registers the Appearance preference row into the settings General
* section — the theme feature owns its own settings surface.
* the DOM — ui-layout's presenter consumes the resolved snapshot. The Host
* settings controller loads and stores the preference in the user-settings
* document. The plugin also registers the Appearance preference row into the
* settings General section — the theme feature owns its own settings surface.
*/
import type { Context } from 'cordis'
import type { ConnectionHandle } from '@deepseek-ai/dsh-client-connection/client'
import type { BoundActions } from '@deepseek-ai/dsh-client-ui-slots'
import type { ClientContext } from '@deepseek-ai/dsh-client-runtime/client'
// Type-only: pulls the locale plugin's Context merge (ctx.locale).
@@ -14,11 +16,22 @@ import type {} from '@deepseek-ai/dsh-client-locale/client'
import type { AppearanceRowInjected } from './AppearanceRow.tsx'
import { AppearanceRow } from './AppearanceRow.tsx'
import { createAppearanceRowStore } from './settings-store.ts'
import { ThemeSettingsController } from './theme-settings.ts'
import { en, zh, type ThemeKey } from './locales.ts'
import {
DEFAULT_PREFERENCE, isThemePreference, THEME_SETTINGS_NAMESPACE,
type ThemePreference,
} from '../theme-settings.ts'
export type { AppearanceRowComponentProps, AppearanceRowInjected } from './AppearanceRow.tsx'
export type { AppearanceRowState } from './settings-store.ts'
export type { ThemePreferenceTarget } from './theme-settings.ts'
export { ThemeSettingsController } from './theme-settings.ts'
export type { ThemeKey } from './locales.ts'
export {
DEFAULT_PREFERENCE, THEME_PREFERENCE_FIELD, THEME_SETTINGS_NAMESPACE,
type ThemePreference,
} from '../theme-settings.ts'
/** Namespace owning this feature's settings-row copy. */
export const SETTINGS_NS = 'settings.theme'
@@ -33,9 +46,6 @@ declare module '@deepseek-ai/dsh-client-ui-slots' {
/** Theme token dictionary: --dsw-alias-* overrides keyed by variable name. */
export type ThemeTokens = Record<string, string>
/** Theme preference: a concrete theme id or follow-the-OS. */
export type ThemePreference = 'light' | 'dark' | 'system'
/** One selectable theme: id, dark/light semantics, and alias-token overrides. */
export interface ThemeDefinition {
/** Theme id (the setTheme argument for concrete themes). */
@@ -76,12 +86,6 @@ declare module 'cordis' {
}
}
/** localStorage key holding the persisted theme preference. */
export const STORAGE_KEY = 'dsh.theme'
/** Default preference when nothing (or garbage) is persisted. */
export const DEFAULT_PREFERENCE: ThemePreference = 'system'
const BUILTIN_THEMES: readonly ThemeDefinition[] = Object.freeze([
Object.freeze({ id: 'light', colorScheme: 'light' as const, tokens: Object.freeze({}) }),
Object.freeze({ id: 'dark', colorScheme: 'dark' as const, tokens: Object.freeze({}) }),
@@ -103,14 +107,17 @@ export class ThemeService {
private revision = 0
private snapshot: ThemeSnapshot
private readonly media: MediaQueryList | undefined
private persist: (preference: ThemePreference) => void
/**
* @param ctx - owning context (change events are emitted on it; the
* media-query listener is released through ctx.effect on dispose).
* @param persist - durable write callback for built-in preferences.
*/
constructor(ctx: Context) {
constructor(ctx: Context, persist: (preference: ThemePreference) => void = () => {}) {
this.ctx = ctx
this.preference = restorePreference()
this.persist = persist
this.preference = DEFAULT_PREFERENCE
// Non-browser runs (node e2e booting the client tree) have no matchMedia.
this.media = typeof matchMedia === 'undefined' ? undefined : matchMedia('(prefers-color-scheme: dark)')
this.snapshot = this.buildSnapshot()
@@ -136,8 +143,17 @@ export class ThemeService {
}
/**
* Switch the theme preference — the only preference write entry. Persists
* the preference and emits `theme/change`.
* Bind the owning plugin's durable writer before the service is provided.
* @param persist - callback accepting built-in preference changes.
*/
bindPersistence(persist: (preference: ThemePreference) => void): void {
this.persist = persist
}
/**
* Switch the theme preference — the only user preference write entry.
* Built-in preferences are persisted and every accepted value emits
* `theme/change`.
* @param id - a registered theme id or `system`; unknown ids throw.
*/
setTheme(id: string): void {
@@ -146,7 +162,17 @@ export class ThemeService {
}
if (this.preference === id) return
this.preference = id as ThemePreference
persistPreference(this.preference)
if (isThemePreference(id)) this.persist(id)
this.publish()
}
/**
* Apply a preference read from Host settings without writing it back.
* @param preference - validated durable preference.
*/
syncPreference(preference: ThemePreference): void {
if (this.preference === preference) return
this.preference = preference
this.publish()
}
@@ -170,7 +196,7 @@ export class ThemeService {
this.themes = this.themes.filter(t => t.id !== definition.id)
if (this.preference === definition.id) {
this.preference = DEFAULT_PREFERENCE
persistPreference(this.preference)
this.persist(this.preference)
}
this.publish()
}
@@ -200,32 +226,8 @@ export class ThemeService {
}
}
/** Read the persisted preference; unknown or unreadable values fall back to the default. */
function restorePreference(): ThemePreference {
// Non-browser runs (node e2e booting the client tree) have no localStorage.
if (typeof localStorage === 'undefined') return DEFAULT_PREFERENCE
try {
const stored = localStorage.getItem(STORAGE_KEY)
if (stored === 'light' || stored === 'dark' || stored === 'system') return stored
} catch {
// Storage access can throw (privacy mode); the default below covers it.
}
return DEFAULT_PREFERENCE
}
/** Persist the preference; storage failures are non-fatal (preference resets next boot). */
function persistPreference(preference: ThemePreference): void {
if (typeof localStorage === 'undefined') return
try {
localStorage.setItem(STORAGE_KEY, preference)
} catch {
// Storage access can throw (privacy mode / quota); the preference simply
// does not survive the session.
}
}
/** Required services: slots + locale (the feature registers its own settings row with localized copy). */
export const inject = ['slots', 'locale']
/** Required services: settings transport plus slots/locale for the Appearance row. */
export const inject = ['slots', 'locale', 'connection']
/**
* Client plugin body: provide the theme service and register the
@@ -233,10 +235,33 @@ export const inject = ['slots', 'locale']
* slot (a feature owns its settings surface).
* @param ctx - client cordis context.
*/
export function apply(ctx: ClientContext): void {
export async function apply(ctx: ClientContext): Promise<void> {
const connection = ctx.get('connection') as ConnectionHandle
const theme = new ThemeService(ctx)
const controller = new ThemeSettingsController(
connection.api,
theme,
connection.isLoopback ? 'host' : 'memory',
)
theme.bindPersistence((preference) => { void controller.persist(preference) })
await controller.load()
ctx.provide('theme', theme)
ctx.effect(() => {
const refresh = (ns?: string): void => {
if (ns !== undefined && ns !== THEME_SETTINGS_NAMESPACE) return
void controller.load()
}
const disposers = [
ctx.on('settings/changed', refresh),
ctx.on('connection/reset', () => { refresh() }),
]
return () => {
controller.dispose()
for (const dispose of disposers) dispose()
}
}, 'ui-theme: settings invalidations')
ctx.effect(() => ctx.locale.register(SETTINGS_NS, { zh, en }), 'ui-theme: settings row dictionaries')
const store = createAppearanceRowStore()

View File

@@ -4,7 +4,7 @@
* reads via props.useStore.
*/
import { defineStore, type EngineStoreHandle } from '@deepseek-ai/dsh-client-runtime/client'
import type { ThemePreference } from './index.ts'
import type { ThemePreference } from '../theme-settings.ts'
/** Store state mirrored from the theme snapshot. */
export interface AppearanceRowState {

View File

@@ -0,0 +1,100 @@
/** Host-backed persistence controller for the browser theme preference. */
import type {
IApiClient, SettingsNamespaceView,
} from '@deepseek-ai/dsh-client-connection/client'
import {
THEME_PREFERENCE_FIELD, THEME_SETTINGS_NAMESPACE, isThemePreference,
type ThemePreference,
} from '../theme-settings.ts'
/** Preference target implemented by {@link ThemeService}. */
export interface ThemePreferenceTarget {
/**
* Apply a Host value without writing it back.
* @param preference - validated durable preference.
*/
syncPreference(preference: ThemePreference): void
}
function preferenceOf(view: SettingsNamespaceView): ThemePreference | undefined {
if (typeof view.value !== 'object' || view.value === null) return undefined
const preference = (view.value as Record<string, unknown>)[THEME_PREFERENCE_FIELD]
return isThemePreference(preference) ? preference : undefined
}
/** Coordinates startup reads, ordered writes, and pushed invalidations. */
export class ThemeSettingsController {
private generation = 0
private writeTail: Promise<void> = Promise.resolve()
/**
* @param api - settings wire face.
* @param target - live theme service receiving durable values.
* @param persistence - remote browsers stay process-local because the settings API is loopback-only.
*/
constructor(
private readonly api: Pick<IApiClient, 'settings'>,
private readonly target: ThemePreferenceTarget,
private readonly persistence: 'host' | 'memory' = 'host',
) {}
/**
* Load the durable preference after earlier writes settle; the latest operation wins.
* @returns nothing; an unavailable or invalid descriptor leaves the last good value active.
*/
async load(): Promise<void> {
const generation = ++this.generation
if (this.persistence === 'memory') return
await this.writeTail
if (generation !== this.generation) return
let response: Awaited<ReturnType<Pick<IApiClient, 'settings'>['settings']['describe']>>
try {
response = await this.api.settings.describe({})
} catch (_settingsReadFailure) {
// A transport failure leaves the last good in-process theme active. A
// connection/reset or settings/changed notification retries the read.
return
}
if (!response.result.ok || generation !== this.generation) return
const view = response.result.value.namespaces.find(
candidate => candidate.ns === THEME_SETTINGS_NAMESPACE,
)
if (view === undefined) return
const preference = preferenceOf(view)
if (preference !== undefined) this.target.syncPreference(preference)
}
/**
* Persist one user selection. Writes are serialized so rapid picks land in
* gesture order; a rejected latest write reloads the durable value.
* @param preference - selected built-in preference.
* @returns nothing after the write or recovery read settles.
*/
async persist(preference: ThemePreference): Promise<void> {
const generation = ++this.generation
if (this.persistence === 'memory') return
const write = this.writeTail.then(async () => {
const response = await this.api.settings.mutate({
ns: THEME_SETTINGS_NAMESPACE,
ops: [{ op: 'set', path: [THEME_PREFERENCE_FIELD], value: preference }],
})
if (!response.result.ok) throw new Error(response.result.error.message)
if (generation === this.generation) {
const accepted = preferenceOf(response.result.value)
if (accepted !== undefined) this.target.syncPreference(accepted)
}
})
this.writeTail = write.catch(() => {})
try {
await write
} catch {
if (generation === this.generation) await this.load()
}
}
/** Prevent in-flight reads and writes from publishing after plugin disposal. */
dispose(): void {
this.generation += 1
}
}

View File

@@ -1,4 +1,35 @@
/** Host loader entry for the browser implementation exported from `./client`. */
/** Host registration for the browser theme preference. */
/** Host plugin body — no host-side behavior for the theme plugin. */
export function apply(): void {}
import type { Context } from 'cordis'
import z from 'schemastery'
import { settingsNamespace } from '@deepseek-ai/dsh-settings'
import {
DEFAULT_PREFERENCE, THEME_PREFERENCE_FIELD, THEME_SETTINGS_NAMESPACE,
type ThemePreference,
} from './theme-settings.ts'
export {
DEFAULT_PREFERENCE, THEME_PREFERENCE_FIELD, THEME_SETTINGS_NAMESPACE,
type ThemePreference,
} from './theme-settings.ts'
interface ThemeSettings {
preference: ThemePreference
}
const ThemeSettingsSchema: z<ThemeSettings> = z.object({
[THEME_PREFERENCE_FIELD]: z.union(['light', 'dark', 'system']).default(DEFAULT_PREFERENCE),
})
/**
* Register the durable theme section when a settings provider exists.
* @param ctx - Host context whose optional settings service owns the section.
*/
export function apply(ctx: Context): void {
ctx.inject(['settings'], (settingsCtx) => {
settingsCtx.settings.register(
settingsNamespace(THEME_SETTINGS_NAMESPACE),
ThemeSettingsSchema,
)
})
}

View File

@@ -15,10 +15,10 @@ export const name = 'client-ui-theme-invariant'
export const inject = ['invariants']
/**
* No runtime invariant: the theme registry publishes immutable snapshots on
* its own `theme/change` event synchronously with the setter/registry
* mutation in the same service — snapshot/event agreement is asserted
* directly by this package's behavior specs.
* No runtime invariant: the settings seam validates and publishes the durable
* theme section, while the registry emits `theme/change` synchronously with
* its own mutations. Store/registry agreement is covered directly by this
* package's Host, controller, and service behavior specs.
*/
const install: InvariantInstaller = () => {}

View File

@@ -0,0 +1,22 @@
/** Theme preferences stored in the Host user-settings document. */
/** Settings namespace owned by the theme plugin. */
export const THEME_SETTINGS_NAMESPACE = 'ui-theme'
/** Field carrying the selected built-in theme preference. */
export const THEME_PREFERENCE_FIELD = 'preference'
/** Theme preference persisted by the product Appearance row. */
export type ThemePreference = 'light' | 'dark' | 'system'
/** Default preference when the user-settings document has no override. */
export const DEFAULT_PREFERENCE: ThemePreference = 'system'
/**
* Narrow one wire or registry value to a persistable preference.
* @param value - value crossing the settings or registry boundary.
* @returns whether the value is a built-in preference.
*/
export function isThemePreference(value: unknown): value is ThemePreference {
return value === 'light' || value === 'dark' || value === 'system'
}