refactor(client): replace the per-field settings preference controller with a namespace settings scope

bindSettingsScope mirrors the Host-side settings owner seam in the browser:
one scope per namespace publishes a snapshot store (status, section value,
revision, writability, host/memory mode), validates sections against the
namespace's serialized wire schema via dsh-client-schema-form, and keeps the
controller's listener-before-read, revisioned serialized writes, latest-wins
publication, conflict recovery, and disposal quiescence. Theme, locale, and
busy-Enter services now take the scope as a constructor collaborator, which
removes the bindPersistence/syncPreference two-phase callback pair and the
defaulted no-op persist writers; hand-written wire guards fall away in favor
of the registered schema. test-runtime gains a stubSettingsScope double.
This commit is contained in:
Yichen Jiang
2026-08-07 23:25:42 +08:00
parent 6922a942a6
commit 638c9e4bd7
37 changed files with 926 additions and 617 deletions

View File

@@ -3,13 +3,15 @@
* 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 Host
* settings controller loads and stores the preference in the user-settings
* settings scope 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 { BoundActions } from '@deepseek-ai/dsh-client-ui-slots'
import { bindSettingsPreference, type ClientContext } from '@deepseek-ai/dsh-client-runtime/client'
import {
bindSettingsScope, type ClientContext, type SettingsScope,
} from '@deepseek-ai/dsh-client-runtime/client'
// Type-only: pulls the locale plugin's Context merge (ctx.locale).
import type {} from '@deepseek-ai/dsh-client-locale/client'
import type { AppearanceRowInjected } from './AppearanceRow.tsx'
@@ -18,7 +20,7 @@ import { createAppearanceRowStore } from './settings-store.ts'
import { en, zh, type ThemeKey } from './locales.ts'
import {
DEFAULT_PREFERENCE, isThemePreference, THEME_PREFERENCE_FIELD, THEME_SETTINGS_NAMESPACE,
type ThemePreference,
type ThemePreference, type ThemeSettings,
} from '../theme-settings.ts'
export type { AppearanceRowComponentProps, AppearanceRowInjected } from './AppearanceRow.tsx'
@@ -26,7 +28,7 @@ export type { AppearanceRowState } from './settings-store.ts'
export type { ThemeKey } from './locales.ts'
export {
DEFAULT_PREFERENCE, THEME_PREFERENCE_FIELD, THEME_PREFERENCES, THEME_SETTINGS_NAMESPACE,
type ThemePreference,
type ThemePreference, type ThemeSettings,
} from '../theme-settings.ts'
/** Namespace owning this feature's settings-row copy. */
@@ -98,21 +100,21 @@ const BUILTIN_THEMES: readonly ThemeDefinition[] = Object.freeze([
*/
export class ThemeService {
private readonly ctx: Context
private readonly host: SettingsScope<ThemeSettings>
private themes: ThemeDefinition[] = [...BUILTIN_THEMES]
private preference: ThemePreference
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.
* media-query and scope listeners are released through ctx.effect on dispose).
* @param host - durable preference scope owned by the same plugin.
*/
constructor(ctx: Context, persist: (preference: ThemePreference) => void = () => {}) {
constructor(ctx: Context, host: SettingsScope<ThemeSettings>) {
this.ctx = ctx
this.persist = persist
this.host = host
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)')
@@ -128,6 +130,8 @@ export class ThemeService {
return () => { media.removeEventListener('change', onChange) }
}, 'ui-theme: prefers-color-scheme listener')
}
ctx.effect(() => host.subscribe(() => { this.adopt() }), 'ui-theme: settings scope adoption')
this.adopt()
}
/**
@@ -138,18 +142,10 @@ export class ThemeService {
return this.snapshot
}
/**
* 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`.
* Built-in preferences are written through the settings scope and every
* accepted value emits `theme/change`.
* @param id - a registered theme id or `system`; unknown ids throw.
*/
setTheme(id: string): void {
@@ -158,17 +154,15 @@ export class ThemeService {
}
if (this.preference === id) return
this.preference = id as ThemePreference
if (isThemePreference(id)) this.persist(id)
if (isThemePreference(id)) void this.host.set(THEME_PREFERENCE_FIELD, 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
/** Adopt the scope's accepted durable preference without writing it back. */
private adopt(): void {
const section = this.host.getSnapshot().value
if (section === undefined || this.preference === section.preference) return
this.preference = section.preference
this.publish()
}
@@ -231,14 +225,8 @@ export const inject = ['slots', 'locale', 'connection']
* @param ctx - client cordis context.
*/
export function apply(ctx: ClientContext): void {
const theme = new ThemeService(ctx)
const controller = bindSettingsPreference(ctx, {
namespace: THEME_SETTINGS_NAMESPACE,
field: THEME_PREFERENCE_FIELD,
decode: value => isThemePreference(value) ? value : undefined,
sync: (preference) => { theme.syncPreference(preference) },
})
theme.bindPersistence((preference) => { void controller.persist(preference) })
const host = bindSettingsScope<ThemeSettings>(ctx, { namespace: THEME_SETTINGS_NAMESPACE })
const theme = new ThemeService(ctx, host)
ctx.provide('theme', theme)
ctx.effect(() => ctx.locale.register(SETTINGS_NS, { zh, en }), 'ui-theme: settings row dictionaries')

View File

@@ -5,19 +5,16 @@ import z from 'schemastery'
import { settingsNamespace } from '@deepseek-ai/dsh-settings'
import {
DEFAULT_PREFERENCE, THEME_PREFERENCE_FIELD, THEME_PREFERENCES, THEME_SETTINGS_NAMESPACE,
type ThemePreference,
type ThemeSettings,
} from './theme-settings.ts'
export {
DEFAULT_PREFERENCE, THEME_PREFERENCE_FIELD, THEME_PREFERENCES, THEME_SETTINGS_NAMESPACE,
type ThemePreference,
type ThemePreference, type ThemeSettings,
} from './theme-settings.ts'
interface ThemeSettings {
preference: ThemePreference
}
const ThemeSettingsSchema: z<ThemeSettings> = z.object({
/** Durable theme schema; also the wire envelope the browser scope validates against. */
export const ThemeSettingsSchema: z<ThemeSettings> = z.object({
[THEME_PREFERENCE_FIELD]: z.union([...THEME_PREFERENCES]).default(DEFAULT_PREFERENCE),
})

View File

@@ -15,10 +15,10 @@ export const name = 'client-ui-theme-invariant'
export const inject = ['invariants']
/**
* No runtime invariant: the settings seam validates and publishes the durable
* No runtime invariant: the settings scope 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.
* package's Host, scope, and service behavior specs.
*/
const install: InvariantInstaller = () => {}

View File

@@ -15,6 +15,12 @@ export type ThemePreference = typeof THEME_PREFERENCES[number]
/** Default preference when the user-settings document has no override. */
export const DEFAULT_PREFERENCE: ThemePreference = 'system'
/** Durable theme section shared by the Host schema and the browser scope. */
export interface ThemeSettings {
/** Selected built-in preference. */
preference: ThemePreference
}
/**
* Narrow one wire or registry value to a persistable preference.
* @param value - value crossing the settings or registry boundary.

View File

@@ -10,6 +10,7 @@ import {
apply, inject, SETTINGS_NS, THEME_SETTINGS_NAMESPACE,
} from '@deepseek-ai/dsh-client-ui-theme/client'
import type { AppearanceRowInjected, ThemeService } from '@deepseek-ai/dsh-client-ui-theme/client'
import { ThemeSettingsSchema } from '@deepseek-ai/dsh-client-ui-theme'
import { AppearanceRow } from '../src/client/AppearanceRow.tsx'
import type { createAppearanceRowStore } from '../src/client/settings-store.ts'
@@ -33,7 +34,7 @@ async function bench(isLoopback = true) {
let preference = 'system'
const namespace = () => ({
ns: THEME_SETTINGS_NAMESPACE,
schema: {},
schema: ThemeSettingsSchema.toJSON(),
value: { preference },
applies: 'live' as const,
secrets: [],

View File

@@ -1,19 +1,20 @@
// @vitest-environment jsdom
import { afterEach, describe, expect, it, vi } from 'vitest'
import { Context } from 'cordis'
import type { ThemeSnapshot } from '@deepseek-ai/dsh-client-ui-theme/client'
import { stubSettingsScope, type StubSettingsScope } from '@deepseek-ai/dsh-client-test-runtime'
import type { ThemeSettings, ThemeSnapshot } from '@deepseek-ai/dsh-client-ui-theme/client'
import { ThemeService } from '@deepseek-ai/dsh-client-ui-theme/client'
const make = (persist = vi.fn()): {
const make = (host = stubSettingsScope<ThemeSettings>()): {
ctx: Context
theme: ThemeService
events: ThemeSnapshot[]
persist: typeof persist
host: StubSettingsScope<ThemeSettings>
} => {
const ctx = new Context()
const events: ThemeSnapshot[] = []
ctx.on('theme/change', (snapshot) => { events.push(snapshot) })
return { ctx, theme: new ThemeService(ctx, persist), events, persist }
return { ctx, theme: new ThemeService(ctx, host.scope), events, host }
}
describe('ThemeService', () => {
@@ -27,12 +28,12 @@ describe('ThemeService', () => {
expect(snapshot.themes.map(t => t.id)).toEqual(['light', 'dark'])
})
it('setTheme switches, requests persistence, republishes, and keeps DOM untouched', () => {
const { theme, events, persist } = make()
it('setTheme switches, writes through the scope, republishes, and keeps DOM untouched', () => {
const { theme, events, host } = make()
theme.setTheme('dark')
expect(theme.getTheme().preference).toBe('dark')
expect(theme.getTheme().active.colorScheme).toBe('dark')
expect(persist).toHaveBeenCalledWith('dark')
expect(host.set).toHaveBeenCalledWith('preference', 'dark')
expect(events).toHaveLength(1)
expect(events[0]).toBe(theme.getTheme())
// The service never touches presentation state.
@@ -40,19 +41,26 @@ describe('ThemeService', () => {
// Same-value set is a no-op (no extra event).
theme.setTheme('dark')
expect(events).toHaveLength(1)
expect(persist).toHaveBeenCalledOnce()
expect(host.set).toHaveBeenCalledOnce()
})
it('syncs a Host preference without writing it back', () => {
const { theme, events, persist } = make()
theme.syncPreference('dark')
it('adopts a published Host section without writing it back', () => {
const { theme, events, host } = make()
host.publish({ status: 'ready', value: { preference: 'dark' }, revision: 1, writable: true })
expect(theme.getTheme().preference).toBe('dark')
expect(events).toHaveLength(1)
expect(persist).not.toHaveBeenCalled()
theme.syncPreference('dark')
expect(host.set).not.toHaveBeenCalled()
host.publish({ value: { preference: 'dark' }, revision: 2 })
expect(events).toHaveLength(1)
})
it('adopts a section already standing at construction', () => {
const host = stubSettingsScope<ThemeSettings>()
host.publish({ status: 'ready', value: { preference: 'dark' }, revision: 1, writable: true })
const { theme } = make(host)
expect(theme.getTheme().preference).toBe('dark')
})
it('throws on unknown setTheme ids, duplicate registration, and the system id', () => {
const { theme } = make()
expect(() => { theme.setTheme('sepia') }).toThrow('not registered')
@@ -61,7 +69,7 @@ describe('ThemeService', () => {
})
it('registered themes join the snapshot; disposing the active one resets to default', () => {
const { theme, events, persist } = make()
const { theme, events, host } = make()
const dispose = theme.register({ id: 'sepia', colorScheme: 'light', tokens: { '--dsw-alias-bg-base': 'red' } })
expect(theme.getTheme().themes.map(t => t.id)).toEqual(['light', 'dark', 'sepia'])
theme.setTheme('sepia')
@@ -71,7 +79,7 @@ describe('ThemeService', () => {
expect(theme.getTheme().themes.map(t => t.id)).toEqual(['light', 'dark'])
// Custom ids are in-process extension themes; only the built-in product
// preferences cross the Host settings schema.
expect(persist).not.toHaveBeenCalled()
expect(host.set).not.toHaveBeenCalled()
// register + set + dispose = three publishes; disposer is idempotent.
expect(events.length).toBe(3)
dispose()
@@ -95,11 +103,11 @@ describe('ThemeService', () => {
expect(events.map(e => e.revision)).toEqual([1, 2, 3, 4])
})
it('uses a no-op persistence callback when constructed directly', () => {
const ctx = new Context()
const theme = new ThemeService(ctx)
theme.setTheme('dark')
expect(theme.getTheme().preference).toBe('dark')
it('context dispose releases the scope subscription', async () => {
const { ctx, host } = make()
expect(host.listenerCount()).toBe(1)
await ctx.fiber.dispose()
expect(host.listenerCount()).toBe(0)
})
describe('prefers-color-scheme resolution (stubbed matchMedia)', () => {