From f26f5be4c35412e8dea1004c108576ad56306e63 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=83=E5=B7=9D=E7=99=BD=E6=B5=AA?= <1679659@qq.com> Date: Tue, 1 Dec 2026 05:53:19 -0700 Subject: [PATCH 1/8] feat(theme): implement host theme slots, layout, and visuals --- docs/plugin-architecture.md | 3 +- frontend/scripts/check-ui-contract.mjs | 46 +++- frontend/src/App.tsx | 50 ++++- frontend/src/components/AboutPage.tsx | 9 +- frontend/src/components/AppSettingsPage.tsx | 2 +- frontend/src/components/CloneDialog.tsx | 8 +- frontend/src/components/CreateWizard.tsx | 7 +- frontend/src/components/ErrorBoundary.tsx | 2 +- frontend/src/components/HostView.tsx | 14 +- frontend/src/components/LogPanel.tsx | 16 +- frontend/src/components/PluginMarket.tsx | 6 +- frontend/src/components/PluginPanelFrame.tsx | 2 +- frontend/src/components/PluginsPage.tsx | 22 +- frontend/src/components/RuntimeOnline.tsx | 4 +- frontend/src/components/SchemaForm.tsx | 6 +- frontend/src/components/SendTextDialog.tsx | 8 +- frontend/src/components/SettingsModal.tsx | 22 +- frontend/src/components/Setup.tsx | 14 +- frontend/src/components/Sidebar.tsx | 86 ++++---- frontend/src/components/TitleMenus.tsx | 8 +- frontend/src/components/VMPage.tsx | 99 ++++----- frontend/src/lib/themeEngine.ts | 46 +++- frontend/src/lib/uiSdk.ts | 77 ++++++- frontend/src/macos/InstallersPage.tsx | 22 +- frontend/src/macos/OnlineRecoveryDialog.tsx | 6 +- frontend/src/styles/app.css | 61 ++++++ frontend/src/styles/ui-contract.ts | 99 ++++++--- frontend/src/ui/controls.tsx | 26 ++- frontend/src/ui/dialog.tsx | 10 +- frontend/src/ui/settings.tsx | 8 +- frontend/src/ui/themeVisuals.tsx | 175 +++++++++++++++ frontend/src/ui/toast.tsx | 12 +- frontend/ui-contract.json | 211 ++++++++++--------- frontend/wailsjs/go/models.ts | 28 ++- internal/plugin/contract.go | 31 +-- internal/plugin/contract_test.go | 18 +- 36 files changed, 899 insertions(+), 365 deletions(-) create mode 100644 frontend/src/ui/themeVisuals.tsx diff --git a/docs/plugin-architecture.md b/docs/plugin-architecture.md index 1aa385b..2f3f7eb 100644 --- a/docs/plugin-architecture.md +++ b/docs/plugin-architecture.md @@ -211,7 +211,8 @@ UI 槽位采用「声明即占有」:插件只能向宿主槽位目录(§5.1 - 只读状态订阅:非敏感的 VM 摘要、任务进度、当前视图、外观;不提供原始路径与敏感字段。 - 事件流:VM 状态变化(含过渡态)、任务开始/进度/结束、提示条出现、视图切换,供主题做转场动画,不必轮询状态。 - 宿主提供的页面观察总线、帧读写管线与按部件查询:主题不自建节点观察者,也不整页查询文档。 -- 槽位挂载:框架无关的 DOM 挂载,不共享宿主的 React 实例,避免随宿主依赖升级断裂。 +- 槽位挂载:框架无关的 DOM 挂载,不共享宿主的 React 实例,避免随宿主依赖升级断裂。按 VM 重复的槽位(`nav.item.trailing`)以 VM 引用为键挂载;全窗口图层另有专用挂载;按部件查询可取回重复部件的全部实例。 +- 声明式装饰与 SDK 挂载共用同一批槽位与图层;重复槽位里的装饰按所在 VM 自身的状态匹配。 - 受限动作:仅开放非破坏性界面动作(折叠侧栏、打开设置、前置 VM 窗口等);启停、删除、配置写入不在 SDK 中。 - 主题设置:由 `settings` Schema 定义,宿主渲染设置页。 diff --git a/frontend/scripts/check-ui-contract.mjs b/frontend/scripts/check-ui-contract.mjs index 4b36972..ceec94a 100644 --- a/frontend/scripts/check-ui-contract.mjs +++ b/frontend/scripts/check-ui-contract.mjs @@ -15,6 +15,7 @@ const srcDir = path.join(rootDir, 'src') const contractSrc = fs.readFileSync(path.join(srcDir, 'styles', 'ui-contract.ts'), 'utf8') const bridgeSrc = fs.readFileSync(path.join(srcDir, 'lib', 'bridgeContract.ts'), 'utf8') const tokensCss = fs.readFileSync(path.join(srcDir, 'styles', 'tokens.css'), 'utf8') +const appCss = fs.readFileSync(path.join(srcDir, 'styles', 'app.css'), 'utf8') function extractArray(src, name) { const re = new RegExp(`export const ${name} = \\[([\\s\\S]*?)\\] as const`) @@ -33,8 +34,13 @@ const uiApi = extractVersion(contractSrc, 'UI_API_VERSION') const stable = { parts: extractArray(contractSrc, 'UI_CONTRACT_PARTS'), stateAttrs: extractArray(contractSrc, 'UI_CONTRACT_STATE_ATTRS'), + itemStates: extractArray(contractSrc, 'UI_CONTRACT_ITEM_STATES'), slots: extractArray(contractSrc, 'UI_CONTRACT_SLOTS'), layers: extractArray(contractSrc, 'UI_CONTRACT_LAYERS'), + layoutOptions: extractArray(contractSrc, 'UI_CONTRACT_LAYOUT_OPTIONS'), + icons: extractArray(contractSrc, 'UI_CONTRACT_ICONS'), + viewLocations: extractArray(contractSrc, 'UI_CONTRACT_VIEW_LOCATIONS'), + sdkEvents: extractArray(contractSrc, 'UI_CONTRACT_SDK_EVENTS'), tokens: extractArray(contractSrc, 'UI_CONTRACT_TOKENS'), } const experimental = { @@ -70,6 +76,16 @@ function readSources(dir, exts) { } const allTsx = readSources(srcDir, ['.tsx']) const allCode = readSources(srcDir, ['.ts', '.tsx']) +// Per-file sources, for checks that need two things in the same component. +function sourceFiles(dir, out = []) { + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + const full = path.join(dir, entry.name) + if (entry.isDirectory()) sourceFiles(full, out) + else if (entry.name.endsWith('.tsx')) out.push(fs.readFileSync(full, 'utf8')) + } + return out +} +const tsxFiles = sourceFiles(srcDir) const hasClass = (p) => new RegExp(`(? attr.replace(/^data-/, '').replace(/-([a-z])/g, (_, c) => c.toUpperCase()) @@ -85,6 +101,26 @@ fail('stable state attributes never set', stable.stateAttrs.filter((a) => !hasAt fail('stable slots without a data-rg-slot anchor', stable.slots.filter((s) => !hasSlot(s))) fail('stable layers without a data-rg-layer element', stable.layers.filter((l) => !hasLayer(l))) fail('stable tokens missing in tokens.css', stable.tokens.filter((tk) => !tokensCss.includes(`${tk}:`))) +// An item state counts as emitted when one component carries both the part and the attribute. +fail('stable item states not emitted together with their part', stable.itemStates.filter((s) => { + const [part, attr] = s.split(':') + return !tsxFiles.some((src) => new RegExp(`(? { + if (LAYOUT_DEFAULTS.includes(o)) return false + const [opt, val] = o.split('=') + return !LAYOUT_ATTR[opt] || !appCss.includes(`[${LAYOUT_ATTR[opt]}="${val}"]`) +})) +fail('layout options with an unknown option name', [...stable.layoutOptions, ...experimental.layoutOptions].filter((o) => !LAYOUT_ATTR[o.split('=')[0]])) +// Every stable icon name is rendered through (or the status-shape map). +const controlsSrc = fs.readFileSync(path.join(srcDir, 'ui', 'controls.tsx'), 'utf8') +fail('stable icon names never rendered through HostIcon', stable.icons.filter((n) => + !allTsx.includes(`HostIcon name="${n}"`) && !(n.startsWith('vm.state.') && controlsSrc.includes(`'${n}'`)))) +// Every stable SDK event has an emitter. +fail('stable SDK events never emitted', stable.sdkEvents.filter((e) => !allCode.includes(`emitThemeEvent('${e}'`))) fail('experimental parts already emitted (promote them to UI_CONTRACT_PARTS)', experimental.parts.filter(hasClass)) fail('experimental slots already anchored (promote them to UI_CONTRACT_SLOTS)', experimental.slots.filter(hasSlot)) @@ -95,11 +131,16 @@ fail('entries listed as both stable and experimental (parts)', overlap(stable.pa fail('entries listed as both stable and experimental (state attributes)', overlap(stable.stateAttrs, experimental.stateAttrs)) fail('entries listed as both stable and experimental (slots)', overlap(stable.slots, experimental.slots)) fail('entries listed as both stable and experimental (layers)', overlap(stable.layers, experimental.layers)) +fail('entries listed as both stable and experimental (item states)', overlap(stable.itemStates, experimental.itemStates)) +fail('entries listed as both stable and experimental (layout options)', overlap(stable.layoutOptions, experimental.layoutOptions)) +fail('entries listed as both stable and experimental (icons)', overlap(stable.icons, experimental.icons)) +fail('entries listed as both stable and experimental (view locations)', overlap(stable.viewLocations, experimental.viewLocations)) +fail('entries listed as both stable and experimental (SDK events)', overlap(stable.sdkEvents, experimental.sdkEvents)) fail('bridge methods listed as both stable and experimental', overlap(bridge.methods, bridge.experimentalMethods)) fail('bridge events listed as both stable and experimental', overlap(bridge.events, bridge.experimentalEvents)) const knownParts = [...stable.parts, ...experimental.parts] -fail('item states on unknown parts', experimental.itemStates.filter((s) => !knownParts.includes(s.split(':')[0]))) +fail('item states on unknown parts', [...stable.itemStates, ...experimental.itemStates].filter((s) => !knownParts.includes(s.split(':')[0]))) for (const [name, list] of Object.entries({ ...stable, ...experimental, ...bridge })) { const dupes = list.filter((x, i) => list.indexOf(x) !== i) fail(`duplicate entries in ${name}`, dupes) @@ -125,6 +166,7 @@ write('bridge-contract.json', { }) console.log( `[ui-contract] OK (uiApi=${uiApi}, parts=${stable.parts.length}+${experimental.parts.length}x, ` + - `tokens=${stable.tokens.length}, slots=${stable.slots.length}+${experimental.slots.length}x, ` + + `tokens=${stable.tokens.length}, slots=${stable.slots.length}+${experimental.slots.length}x, layers=${stable.layers.length}, ` + + `icons=${stable.icons.length}, sdkEvents=${stable.sdkEvents.length}, ` + `bridgeApi=${bridgeApi}, methods=${bridge.methods.length}+${bridge.experimentalMethods.length}x)`, ) diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 2709c1e..9aeaac3 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -17,13 +17,14 @@ import { defaultGuestLang, recommendedMemoryGB, recommendedResolution } from './ import { LogLine, appendLog } from './lib/logs' import { macOSMajor } from './macos/macosRelease' import { currentTask, finishedTaskTTL, isActiveInstallerTask, pruneFinishedTasks, upsertTask } from './lib/tasks' -import { applyActiveLocaleFonts, applyActiveTheme, disposeActiveThemeAndLocaleFonts, notifyInteractiveThemeState, type UIStateSnapshot } from './lib/themeEngine' +import { applyActiveLocaleFonts, applyActiveTheme, disposeActiveThemeAndLocaleFonts, emitThemeEvent, notifyInteractiveThemeState, type UIStateSnapshot } from './lib/themeEngine' import { latestVMStatsWithDriver, refreshSubscribedVMStats, refreshVMStatsWithDriver } from './lib/vmStats' import { vmRefKey } from './lib/vmRef' import { ActiveThemePayload, AppState, AppUpdateInfo, CachedInstaller, CreateOpts, Locale, PluginUIContributions, Task, VMDetail } from './types' import { Button, Tip, TooltipProvider } from './ui/controls' import { ConfirmDialog, Modal } from './ui/dialog' import { Toaster, useToasts } from './ui/toast' +import { BrandMark, ThemeDecorations, ThemeVisualsProvider } from './ui/themeVisuals' import { api, events, OnFileDrop, OnFileDropOff, WindowMinimise, WindowToggleMaximise } from './wails' // Opened on demand, so each is its own chunk and stays out of the startup @@ -500,6 +501,42 @@ export const App: React.FC = () => { notifyInteractiveThemeState(uiStateRef.current) }, [currentView, effectiveState, isBusyAny, hasAnyError, sidebarOpen, state?.safe_mode, locale, dir, theme]) + // UI SDK event stream (ui-contract UI_CONTRACT_SDK_EVENTS). emitThemeEvent is + // a no-op unless an interactive theme is loaded; payloads carry no paths. + const selectedRef = selectedVM ? vmRefKey(selectedVM) : '' + useEffect(() => { + emitThemeEvent('view.changed', { view: currentView, vm: selectedRef }) + }, [currentView, selectedRef]) + const vmStatesRef = useRef | null>(null) + useEffect(() => { + const next: Record = {} + for (const v of vms) next[vmRefKey(v)] = state?.transitions[vmRefKey(v)] ?? v.state + const prev = vmStatesRef.current + vmStatesRef.current = next + if (!prev) return + for (const v of vms) { + const key = vmRefKey(v) + if (prev[key] !== undefined && prev[key] !== next[key]) { + emitThemeEvent('vm.stateChanged', { vm: key, name: v.name, driver: v.driver_id ?? '', from: prev[key], to: next[key] }) + } + } + }, [vms, state?.transitions]) + const taskStatesRef = useRef | null>(null) + useEffect(() => { + const prev = taskStatesRef.current + const next: Record = {} + for (const t of Object.values(taskMap)) next[t.id] = { status: t.status, percent: t.percent } + taskStatesRef.current = next + if (!prev) return + for (const t of Object.values(taskMap)) { + const was = prev[t.id] + const info = { id: t.id, kind: t.kind, vm: t.vm ?? '', percent: t.percent } + if (!was && t.status === 'running') emitThemeEvent('task.started', info) + else if (was?.status === 'running' && t.status === 'running' && was.percent !== t.percent) emitThemeEvent('task.progress', info) + if ((!was || was.status === 'running') && t.status !== 'running') emitThemeEvent('task.finished', { ...info, status: t.status }) + } + }, [taskMap]) + // Apply active theme pack (zero extra CSS for builtin default theme, §5.1 & §8.1). useEffect(() => { api.GetActiveTheme().then(setActiveThemePayload).catch(() => {}) @@ -965,12 +1002,14 @@ export const App: React.FC = () => { }, []) return ( +
+