feat(ui): add dedicated Plugins page, hot-reload theme capability, and harden UI error handling

This commit is contained in:
Nwflower committed 2026-11-29 09:21:33 -07:00
1 parent 86d2da4a04
commit 007f2ac93c
15 files changed
+1157 -573

No files matched your search

+8 -8
View File
@@ -23,22 +23,22 @@ const stateAttrs = extractArray('UI_CONTRACT_STATE_ATTRS')
const slots = extractArray('UI_CONTRACT_SLOTS')
const tokens = extractArray('UI_CONTRACT_TOKENS')
// Collect all TSX source text to verify every declared part class is actually emitted (§5.1).
function readAllTsx(dir) {
// Collect all React component TSX source text (excluding contract/SDK/theme helpers)
// and verify every declared part class is emitted as a distinct class token (§5.1, M17).
function readComponentTsx(dir) {
let buf = ''
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
const full = path.join(dir, entry.name)
if (entry.isDirectory()) buf += readAllTsx(full)
else if (entry.name.endsWith('.tsx') || entry.name.endsWith('.ts')) buf += '\n' + fs.readFileSync(full, 'utf8')
if (entry.isDirectory()) buf += readComponentTsx(full)
else if (entry.name.endsWith('.tsx')) buf += '\n' + fs.readFileSync(full, 'utf8')
}
return buf
}
const allSrc = readAllTsx(srcDir)
const allTsx = readComponentTsx(srcDir)
const missingParts = parts.filter((p) => {
// Exclude the definition file itself by checking for usage outside ui-contract.ts.
const withoutContract = allSrc.replace(contractSrc, '')
return !withoutContract.includes(p)
const re = new RegExp(`(?<![a-zA-Z0-9_-])${p.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?![a-zA-Z0-9_-])`)
return !re.test(allTsx)
})
const missingTokens = tokens.filter((tk) => !tokensCss.includes(`${tk}:`))
+79 -34
View File
@@ -8,7 +8,7 @@ import { SendTextDialog } from './components/SendTextDialog'
import type { ThemeMode } from './components/AppSettingsPage'
import { LogPanel, LogTab } from './components/LogPanel'
import { TitleMenus } from './components/TitleMenus'
import { HOST_ID, INSTALLERS_ID, SETTINGS_ID, Sidebar } from './components/Sidebar'
import { HOST_ID, INSTALLERS_ID, PLUGINS_ID, SETTINGS_ID, Sidebar } from './components/Sidebar'
import { VMAction, VMPage } from './components/VMPage'
import { I18nKey, t } from './i18n'
import { defaultGuestLang, recommendedMemoryGB, recommendedResolution } from './lib/format'
@@ -31,6 +31,7 @@ const AffinityDialog = lazy(() => import('./components/AffinityDialog').then((m)
const Setup = lazy(() => import('./components/Setup').then((m) => ({ default: m.Setup })))
const HostView = lazy(() => import('./components/HostView').then((m) => ({ default: m.HostView })))
const InstallersPage = lazy(() => import('./components/InstallersPage').then((m) => ({ default: m.InstallersPage })))
const PluginsPage = lazy(() => import('./components/PluginsPage').then((m) => ({ default: m.PluginsPage })))
const AppSettingsPage = lazy(() => import('./components/AppSettingsPage').then((m) => ({ default: m.AppSettingsPage })))
const errText = (e: unknown) => String(e).replace(/^Error:\s*/, '')
@@ -88,11 +89,24 @@ export const App: React.FC = () => {
const [reducedMotion, setReducedMotion] = useState<boolean>(() =>
typeof window !== 'undefined' && !!window.matchMedia?.('(prefers-reduced-motion: reduce)').matches,
)
const theme: 'light' | 'dark' = themeMode === 'system' ? (sysDark ? 'dark' : 'light') : themeMode
const [pluginUI, setPluginUI] = useState<PluginUIContributions | null>(null)
const [activeThemePayload, setActiveThemePayload] = useState<ActiveThemePayload | null>(null)
const [themeRevision, setThemeRevision] = useState(0)
const activeThemeContrib = activeThemePayload?.theme
?? (pluginUI?.themes ?? []).find((th) => th.id === (activeThemePayload?.theme_id || 'builtin.theme.default'))
?? null
const themeAppearanceCap: 'light' | 'dark' | 'both' =
pluginUI === null
? 'both'
: activeThemeContrib
? (activeThemeContrib.appearance === 'light' || activeThemeContrib.appearance === 'dark' ? activeThemeContrib.appearance : 'both')
: 'light'
const canLight = themeAppearanceCap === 'both' || themeAppearanceCap === 'light'
const canDark = themeAppearanceCap === 'both' || themeAppearanceCap === 'dark'
const theme: 'light' | 'dark' = !canDark ? 'light' : !canLight ? 'dark' : (themeMode === 'system' ? (sysDark ? 'dark' : 'light') : themeMode)
const effectiveThemeMode: ThemeMode = !canDark ? 'light' : !canLight ? 'dark' : themeMode
useEffect(() => {
document.documentElement.dataset.theme = theme
document.documentElement.dataset.motion = reducedMotion ? 'reduced' : 'full'
@@ -122,7 +136,10 @@ export const App: React.FC = () => {
} catch {}
}
const toggleTheme = () => setThemeMode(theme === 'light' ? 'dark' : 'light')
const toggleTheme = () => {
if (!canLight || !canDark) return
setThemeMode(theme === 'light' ? 'dark' : 'light')
}
// Sidebar can be hidden (Ctrl+B or the title-bar toggle); remembered per user.
const [sidebarOpen, setSidebarOpen] = useState<boolean>(() => {
@@ -154,7 +171,7 @@ export const App: React.FC = () => {
setState(s)
setLoadError('')
setSelected((cur) => {
if (cur === HOST_ID || cur === INSTALLERS_ID || cur === SETTINGS_ID) return cur
if (cur === HOST_ID || cur === INSTALLERS_ID || cur === PLUGINS_ID || cur === SETTINGS_ID) return cur
if ((s.vms ?? []).some((v) => v.name === cur)) return cur
return s.vms && s.vms.length > 0 ? s.vms[0].name : HOST_ID
})
@@ -166,21 +183,21 @@ export const App: React.FC = () => {
useEffect(() => {
refresh()
const offState = events.onStateChanged(() => { refresh(true) })
events.emitUIPong()
const offPing = events.onUIPing(() => { events.emitUIPong() })
const offState = events.onStateChanged(() => {
refresh(true)
setThemeRevision((r) => r + 1)
})
// Logs never pop the panel open (docs/design-guidelines.md §7.3); errors only bump a badge.
const offLog = events.onLog((entry) => {
setLogLines((prev) => {
const next = appendLog(prev, entry)
const last = next[next.length - 1]
if (!logsOpenRef.current && last.level === 'error' && last !== prev[prev.length - 1]) {
setUnseenErrors((n) => n + 1)
}
return next
})
if (!entry || typeof entry !== 'object') return
const lineText = typeof entry.line === 'string' ? entry.line : String(entry.line ?? '')
if (!logsOpenRef.current && /\b(error|failed|fatal|panic)\b/i.test(lineText)) {
setUnseenErrors((n) => n + 1)
}
setLogLines((prev) => appendLog(prev, entry))
})
api.GetState().then(async (s) => {
setState(s)
}).catch(() => {})
api.GetPluginUIContributions().then(setPluginUI).catch(() => {})
api.GetActiveTheme().then(setActiveThemePayload).catch(() => {})
// Tasks: seed from the backend, then follow events.
@@ -188,6 +205,13 @@ export const App: React.FC = () => {
setTaskMap((prev) => (list ?? []).reduce(upsertTask, prev))
}).catch(() => {})
const offTask = events.onTask((task) => onTaskRef.current(task))
const onVisibility = () => {
if (!document.hidden) {
events.emitUIPong()
void refresh()
}
}
document.addEventListener('visibilitychange', onVisibility)
// Keep host telemetry (memory load, free disk) fresh while the window is visible.
const hostTimer = window.setInterval(() => {
if (!document.hidden) void refresh()
@@ -197,12 +221,19 @@ export const App: React.FC = () => {
if (updatedAt < cutoff) notifiedTasks.current.delete(id)
}
}, 10000)
return () => { offState(); offLog(); offTask(); window.clearInterval(hostTimer) }
return () => {
offPing()
offState()
offLog()
offTask()
document.removeEventListener('visibilitychange', onVisibility)
window.clearInterval(hostTimer)
}
}, [refresh])
const vms = state?.vms ?? []
const runningVMCount = vms.filter((v) => (state?.transitions[v.name] ?? v.state) === 'running').length
const selectedVM = selected !== HOST_ID && selected !== INSTALLERS_ID && selected !== SETTINGS_ID
const selectedVM = selected !== HOST_ID && selected !== INSTALLERS_ID && selected !== PLUGINS_ID && selected !== SETTINGS_ID
? vms.find((v) => v.name === selected)
: undefined
@@ -306,7 +337,7 @@ export const App: React.FC = () => {
const showSetup = !!state && (state.needs_setup || setupStage === 'runtime')
// UI Contract v1 read-only document state attributes (§5.1).
const currentView = showSetup ? 'setup' : selected === HOST_ID ? 'host' : selected === INSTALLERS_ID ? 'installers' : selected === SETTINGS_ID ? 'settings' : 'vm'
const currentView = showSetup ? 'setup' : selected === HOST_ID ? 'host' : selected === INSTALLERS_ID ? 'installers' : selected === PLUGINS_ID ? 'plugins' : selected === SETTINGS_ID ? 'settings' : 'vm'
const isBusyAny = Object.keys(busy).length > 0 || runningTasks > 0
const hasAnyError = unseenErrors > 0 || !!loadError
const uiStateRef = useRef<UIStateSnapshot>({
@@ -718,7 +749,9 @@ export const App: React.FC = () => {
onToggleSidebar={toggleSidebar}
logsOpen={logsOpen}
onToggleLogs={toggleLogs}
themeMode={themeMode}
themeMode={effectiveThemeMode}
canLight={canLight}
canDark={canDark}
onThemeMode={setThemeMode}
vm={selectedVM ? { name: selectedVM.name, state: effectiveState, busy: !!busy[selectedVM.name] } : null}
onNewVM={openWizard}
@@ -731,16 +764,18 @@ export const App: React.FC = () => {
/>
)}
<div className="titlebar-right" onDoubleClick={(e) => e.stopPropagation()}>
<Tip label={tr(theme === 'light' ? 'themeSwitchDark' : 'themeSwitchLight')}>
<button
type="button"
className="theme-toggle"
aria-label={tr(theme === 'light' ? 'themeSwitchDark' : 'themeSwitchLight')}
onClick={toggleTheme}
>
{theme === 'light' ? <Moon size={14} aria-hidden="true" /> : <Sun size={14} aria-hidden="true" />}
</button>
</Tip>
{canLight && canDark && (
<Tip label={tr(theme === 'light' ? 'themeSwitchDark' : 'themeSwitchLight')}>
<button
type="button"
className="theme-toggle"
aria-label={tr(theme === 'light' ? 'themeSwitchDark' : 'themeSwitchLight')}
onClick={toggleTheme}
>
{theme === 'light' ? <Moon size={14} aria-hidden="true" /> : <Sun size={14} aria-hidden="true" />}
</button>
</Tip>
)}
<div className="win-controls">
<button type="button" className="win-btn" aria-label={tr('minimize')} onClick={() => WindowMinimise()}><Minus size={14} aria-hidden="true" /></button>
<button type="button" className="win-btn" aria-label={tr('maximize')} onClick={() => WindowToggleMaximise()}><Square size={12} aria-hidden="true" /></button>
@@ -752,7 +787,7 @@ export const App: React.FC = () => {
{state?.safe_mode && (
<div className="safe-mode-banner" role="status">
<span>{tr('safeModeBanner')}</span>
<button type="button" className="link-btn" onClick={() => setSelected(SETTINGS_ID)}>
<button type="button" className="link-btn" onClick={() => setSelected(PLUGINS_ID)}>
{tr('safeModeManagePlugins')}
</button>
</div>
@@ -791,6 +826,7 @@ export const App: React.FC = () => {
onNew={openWizard}
onVMContextAction={onSidebarContextAction}
downloading={Object.values(taskMap).some((x) => x.kind === 'installer-download' && x.status === 'running')}
safeMode={state?.safe_mode}
/>
<main className="main rg-p-main">
@@ -809,6 +845,15 @@ export const App: React.FC = () => {
onError={fail}
onToast={(title) => toasts.push({ kind: 'ok', title })}
/>
) : selected === PLUGINS_ID ? (
<PluginsPage
locale={locale}
appearance={theme}
safeMode={state.safe_mode}
onRefresh={refresh}
onError={fail}
onThemeChanged={() => setThemeRevision((r) => r + 1)}
/>
) : selectedVM ? (
<VMPage
locale={locale}
@@ -860,10 +905,10 @@ export const App: React.FC = () => {
<AppSettingsPage
state={state}
locale={locale}
themeMode={themeMode}
appearance={theme}
themeMode={effectiveThemeMode}
canLight={canLight}
canDark={canDark}
onThemeMode={setThemeMode}
onThemeChanged={() => setThemeRevision((r) => r + 1)}
onSetLocale={setLang}
onRefresh={refresh}
onError={fail}
+13 -21
View File
@@ -1,5 +1,5 @@
import { Download } from 'lucide-react'
import React, { Suspense, lazy, useEffect, useState } from 'react'
import React, { useEffect, useState } from 'react'
import { I18nKey, t } from '../i18n'
import { findOptimization, optBadgeClass, optStatusLabel } from '../lib/optimizations'
import { AppState, AppUpdateInfo, Locale } from '../types'
@@ -7,24 +7,22 @@ import { Button } from '../ui/controls'
import { Segmented, Switch } from '../ui/settings'
import { api } from '../wails'
const PluginsSection = lazy(() => import('./PluginsSection').then((m) => ({ default: m.PluginsSection })))
export type ThemeMode = 'light' | 'dark' | 'system'
interface Props {
state: AppState
locale: Locale
themeMode: ThemeMode
appearance?: 'light' | 'dark'
canLight?: boolean
canDark?: boolean
onThemeMode: (mode: ThemeMode) => void
onThemeChanged?: () => void
onSetLocale: (l: Locale) => void
onRefresh: () => void
onError: (title: string, e: unknown) => void
}
export const AppSettingsPage: React.FC<Props> = ({
state, locale, themeMode, appearance = 'light', onThemeMode, onThemeChanged, onSetLocale, onRefresh, onError,
state, locale, themeMode, canLight = true, canDark = true, onThemeMode, onSetLocale, onRefresh, onError,
}) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const { host, config, optimizations } = state
@@ -124,16 +122,21 @@ export const AppSettingsPage: React.FC<Props> = ({
<div className="section-title">{tr('settingsAppearance')}</div>
<div className="list">
<div className="row">
<div className="row-main"><div className="row-title">{tr('themeLabel')}</div></div>
<div className="row-main">
<div className="row-title">{tr('themeLabel')}</div>
{(!canDark || !canLight) && (
<div className="row-sub">{tr(!canDark ? 'themePluginDarkDisabled' : 'themePluginLightDisabled')}</div>
)}
</div>
<div className="row-right">
<Segmented
label={tr('themeLabel')}
value={themeMode}
onChange={onThemeMode}
options={[
{ value: 'light', label: tr('themeLight') },
{ value: 'dark', label: tr('themeDark') },
{ value: 'system', label: tr('themeSystem') },
{ value: 'light', label: tr('themeLight'), disabled: !canLight },
{ value: 'dark', label: tr('themeDark'), disabled: !canDark },
{ value: 'system', label: tr('themeSystem'), disabled: !canLight || !canDark },
]}
/>
</div>
@@ -155,17 +158,6 @@ export const AppSettingsPage: React.FC<Props> = ({
</div>
</section>
<Suspense fallback={null}>
<PluginsSection
locale={locale}
appearance={appearance}
safeMode={state.safe_mode}
onRefresh={onRefresh}
onError={onError}
onThemeChanged={onThemeChanged}
/>
</Suspense>
<section className="section">
<div className="section-title">{tr('settingsAbout')}</div>
<div className="list">
+96
View File
@@ -0,0 +1,96 @@
import React from 'react'
import { events } from '../wails'
interface State {
error: Error | null
stack: string
}
/**
* Top-level React error boundary: prevents any uncaught render/lifecycle error
* from unmounting the entire tree into an unrecoverable blank white screen,
* reports the stack trace to the Go backend log, and offers a one-click reload.
*/
export class ErrorBoundary extends React.Component<{ children: React.ReactNode }, State> {
state: State = { error: null, stack: '' }
static getDerivedStateFromError(error: Error): Partial<State> {
return { error }
}
componentDidCatch(error: Error, info: React.ErrorInfo): void {
const stack = [error.stack, info.componentStack].filter(Boolean).join('\n').trim()
this.setState({ stack })
events.emitUIError(`ReactErrorBoundary: ${error.message}\n${stack.slice(0, 1500)}`)
}
render(): React.ReactNode {
const { error, stack } = this.state
if (!error) return this.props.children
const isZh = (document.documentElement.lang || '').toLowerCase().startsWith('zh')
return (
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
height: '100%',
padding: 24,
background: 'var(--surface-canvas, #1c1c1e)',
color: 'var(--text, #f5f5f7)',
fontFamily: 'var(--font-sans, system-ui, sans-serif)',
}}
>
<div
style={{
maxWidth: 560,
width: '100%',
padding: 20,
borderRadius: 12,
border: '1px solid var(--border, rgba(128,128,128,0.25))',
background: 'var(--surface-1, rgba(128,128,128,0.08))',
display: 'flex',
flexDirection: 'column',
gap: 12,
}}
>
<h2 style={{ margin: 0, fontSize: 16 }}>
{isZh ? '界面发生异常' : 'Interface encountered an error'}
</h2>
<p style={{ margin: 0, fontSize: 13, opacity: 0.85 }}>
{isZh
? '渲染过程出现未捕获异常,虚拟机和后台服务不受影响。你可以重新加载界面。'
: 'An unexpected UI error occurred. Running VMs and background services are unaffected.'}
</p>
<pre
style={{
margin: 0,
padding: 10,
borderRadius: 8,
fontSize: 12,
maxHeight: 180,
overflow: 'auto',
background: 'var(--surface-0, rgba(0,0,0,0.2))',
border: '1px solid var(--border, rgba(128,128,128,0.2))',
whiteSpace: 'pre-wrap',
wordBreak: 'break-word',
}}
>
{error.message || String(error)}
{stack ? `\n\n${stack}` : ''}
</pre>
<div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
<button
type="button"
className="btn btn-primary"
onClick={() => window.location.reload()}
>
{isZh ? '重新加载界面' : 'Reload UI'}
</button>
</div>
</div>
</div>
)
}
}
+713
View File
@@ -0,0 +1,713 @@
import {
AlertTriangle, BadgeCheck, Clipboard, Code2, Cpu, Disc3, FolderOpen, Keyboard,
Layers, Monitor, PackagePlus, Palette, Puzzle, RefreshCw, RotateCcw, Search,
Settings2, Shield, ShieldAlert, ShieldCheck, Sparkles, Terminal, Trash2,
} from 'lucide-react'
import React, { useEffect, useMemo, useState } from 'react'
import { I18nKey, t } from '../i18n'
import {
ActiveThemePayload, CustomThemeScheme, Locale, PluginInfo, PluginUIContributions,
} from '../types'
import { Button, IconButton, Tip } from '../ui/controls'
import { Modal } from '../ui/dialog'
import { PopupSelect, Switch } from '../ui/settings'
import { api } from '../wails'
import { PluginPanelFrame } from './PluginPanelFrame'
import { SchemaForm, locText } from './SchemaForm'
// Search only earns its space once the list is long enough to scan.
const SEARCH_THRESHOLD = 12
interface Props {
locale: Locale
appearance: 'light' | 'dark'
safeMode?: boolean
onRefresh: () => void
onError: (title: string, e: unknown) => void
onThemeChanged?: () => void
}
interface PluginVisual {
tone: string
icon: React.ReactNode
}
function resolvePluginVisual(p: PluginInfo): PluginVisual {
const id = p.id.toLowerCase()
const perms = new Set((p.permissions ?? []).map((x) => x.name))
if (id.includes('theme') || perms.has('ui:script')) {
return { tone: 'purple', icon: <Palette size={19} aria-hidden="true" /> }
}
if (id.includes('driver') || perms.has('driver:vm') || perms.has('runtime:provider')) {
return { tone: 'indigo', icon: <Monitor size={19} aria-hidden="true" /> }
}
if (id.includes('clipboard') || perms.has('host:clipboard')) {
return { tone: 'sky', icon: <Clipboard size={19} aria-hidden="true" /> }
}
if (id.includes('ime') || id.includes('input') || id.includes('wheel') || perms.has('input:filter')) {
return { tone: 'rose', icon: <Keyboard size={19} aria-hidden="true" /> }
}
if (id.includes('reboot')) {
return { tone: 'amber', icon: <RotateCcw size={19} aria-hidden="true" /> }
}
if (id.includes('whpx') || id.includes('irq')) {
return { tone: 'emerald', icon: <Cpu size={19} aria-hidden="true" /> }
}
if (id.includes('offline') || id.includes('installer') || id.includes('helper')) {
return { tone: 'teal', icon: <Disc3 size={19} aria-hidden="true" /> }
}
if (p.tier === 'L3') {
return { tone: 'slate', icon: <Layers size={19} aria-hidden="true" /> }
}
return { tone: 'purple', icon: <Puzzle size={19} aria-hidden="true" /> }
}
/**
* Dedicated top-level Plugins & Themes management page (§5.1, §8.1, §10).
* Grouped inset list, same pattern as the installers page.
*/
export const PluginsPage: React.FC<Props> = ({
locale, appearance, safeMode, onRefresh, onError, onThemeChanged,
}) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const [query, setQuery] = useState('')
const [plugins, setPlugins] = useState<PluginInfo[]>([])
const [contribs, setContribs] = useState<PluginUIContributions | null>(null)
const [activeTheme, setActiveTheme] = useState<ActiveThemePayload | null>(null)
const [loading, setLoading] = useState(true)
const [busyID, setBusyID] = useState('')
const [approveTarget, setApproveTarget] = useState<PluginInfo | null>(null)
const [approveChecked, setApproveChecked] = useState(false)
const [settingsTarget, setSettingsTarget] = useState<PluginInfo | null>(null)
const [settingsValues, setSettingsValues] = useState<Record<string, unknown>>({})
const [logTarget, setLogTarget] = useState<{ id: string; text: string } | null>(null)
const [removeTarget, setRemoveTarget] = useState<PluginInfo | null>(null)
const [deleteSchemeTarget, setDeleteSchemeTarget] = useState<CustomThemeScheme | null>(null)
// Theme scheme editor state (§5.1)
const [schemeEditorOpen, setSchemeEditorOpen] = useState(false)
const [schemeName, setSchemeName] = useState('')
const [seedAccent, setSeedAccent] = useState('#007aff')
const [seedSurface, setSeedSurface] = useState('')
const reload = async () => {
try {
const [list, ui, th] = await Promise.all([
api.ListPlugins(),
api.GetPluginUIContributions(),
api.GetActiveTheme(),
])
setPlugins(list ?? [])
setContribs(ui)
setActiveTheme(th)
} catch (e) {
onError(tr('pluginFailLoad'), e)
} finally {
setLoading(false)
}
}
useEffect(() => { void reload() }, [safeMode])
const togglePlugin = async (p: PluginInfo, enable: boolean) => {
if (enable && p.needs_approval) {
setApproveChecked(false)
setApproveTarget(p)
return
}
setBusyID(p.id)
try {
if (enable) await api.EnablePlugin(p.id, false)
else await api.DisablePlugin(p.id)
await reload()
onRefresh()
onThemeChanged?.()
} catch (e) {
onError(tr('pluginFailToggle'), e)
} finally {
setBusyID('')
}
}
const confirmApprove = async () => {
if (!approveTarget || !approveChecked) return
const target = approveTarget
setApproveTarget(null)
setBusyID(target.id)
try {
await api.EnablePlugin(target.id, true)
await reload()
onRefresh()
onThemeChanged?.()
} catch (e) {
onError(tr('pluginFailEnable'), e)
} finally {
setBusyID('')
}
}
const importLocalZip = async () => {
try {
const path = await api.PickFile(tr('pluginImportTitle'), '*.zip')
if (!path) return
await api.InstallPluginArchive(path)
await reload()
onRefresh()
} catch (e) {
onError(tr('pluginFailImport'), e)
}
}
const linkDevDir = async () => {
try {
const dir = await api.PickDirectory(tr('pluginLinkDevTitle'))
if (!dir) return
await api.LinkPluginDev(dir)
await reload()
onRefresh()
} catch (e) {
onError(tr('pluginFailLinkDev'), e)
}
}
const removePlugin = async (p: PluginInfo) => {
setBusyID(p.id)
try {
await api.RemovePlugin(p.id, false)
await reload()
onRefresh()
onThemeChanged?.()
} catch (e) {
onError(tr('pluginFailRemove'), e)
} finally {
setBusyID('')
}
}
const openPluginSettings = async (p: PluginInfo) => {
try {
const vals = await api.GetPluginSettings(p.id, '')
setSettingsValues((vals ?? {}) as Record<string, unknown>)
setSettingsTarget(p)
} catch (e) {
onError(tr('pluginFailLoadSettings'), e)
}
}
const savePluginSettings = async (next: Record<string, unknown>) => {
setSettingsValues(next)
if (!settingsTarget) return
try {
await api.SetPluginSettings(settingsTarget.id, '', next)
onRefresh()
} catch (e) {
onError(tr('pluginFailSaveSettings'), e)
}
}
const openPluginLog = async (p: PluginInfo) => {
try {
const txt = await api.ReadPluginLog(p.id)
setLogTarget({ id: p.id, text: txt || tr('pluginLogEmpty') })
} catch (e) {
onError(tr('pluginFailReadLog'), e)
}
}
const selectTheme = async (themeID: string, schemeID = '') => {
try {
await api.SetActiveTheme(themeID, schemeID)
await reload()
onThemeChanged?.()
} catch (e) {
onError(tr('pluginFailSwitchTheme'), e)
}
}
const saveScheme = async () => {
if (!activeTheme || !schemeName.trim()) return
const id = `custom-${Date.now()}`
const scheme: CustomThemeScheme = {
id,
theme_id: activeTheme.theme_id,
name: schemeName.trim(),
appearance,
seeds: {
accent: seedAccent,
...(seedSurface.trim() ? { surface: seedSurface.trim() } : {}),
},
}
try {
await api.SaveCustomThemeScheme(scheme)
await api.SetActiveTheme(activeTheme.theme_id, id)
setSchemeEditorOpen(false)
setSchemeName('')
setSeedSurface('')
await reload()
onThemeChanged?.()
} catch (e) {
onError(tr('pluginFailSaveScheme'), e)
}
}
const deleteScheme = async (schemeID: string) => {
try {
await api.DeleteCustomThemeScheme(schemeID)
await reload()
onThemeChanged?.()
} catch (e) {
onError(tr('pluginFailDeleteScheme'), e)
}
}
const q = query.trim().toLowerCase()
const matchesFilter = (p: PluginInfo) => {
if (!q) return true
const name = locText(p.name, locale, p.id).toLowerCase()
const desc = locText(p.description, locale, '').toLowerCase()
return name.includes(q) || desc.includes(q) || p.id.toLowerCase().includes(q)
}
const builtins = useMemo(() => plugins.filter((p) => p.source === 'builtin'), [plugins])
const external = useMemo(() => plugins.filter((p) => p.source !== 'builtin'), [plugins])
const filteredBuiltins = useMemo(() => builtins.filter(matchesFilter), [builtins, q, locale])
const filteredExternal = useMemo(() => external.filter(matchesFilter), [external, q, locale])
const themes = contribs?.themes ?? []
const settingsPanels = (contribs?.panels ?? []).filter((p) => p.slot === 'settings.plugin')
const presetSchemes = activeTheme?.theme?.schemes ?? []
const customSchemes = (activeTheme?.custom_schemes ?? []).filter((s) => s.theme_id === activeTheme?.theme_id)
const activeCount = useMemo(() => plugins.filter((p) => p.state === 'active').length, [plugins])
const activeThemeObj = themes.find((th) => th.id === (activeTheme?.theme_id || 'builtin.theme.default')) ?? themes[0]
const activeSchemeSeeds = useMemo(() => {
const base = { ...(activeTheme?.theme?.seeds ?? {}) }
if (activeTheme?.active_scheme) {
const custom = customSchemes.find((s) => s.id === activeTheme.active_scheme)
const preset = presetSchemes.find((s) => s.id === activeTheme.active_scheme)
if (custom?.seeds) return { ...base, ...custom.seeds }
if (preset?.seeds) return { ...base, ...preset.seeds }
}
return base
}, [activeTheme, customSchemes, presetSchemes])
const trustMeta = (trLevel: string) => {
if (trLevel === 'official') return { label: tr('pluginTrustOfficial'), cls: 'is-official', icon: <BadgeCheck size={12} aria-hidden="true" /> }
if (trLevel === 'verified') return { label: tr('pluginTrustVerified'), cls: 'is-verified', icon: <ShieldCheck size={12} aria-hidden="true" /> }
if (trLevel === 'dev') return { label: tr('pluginTrustDev'), cls: 'is-dev', icon: <Code2 size={12} aria-hidden="true" /> }
return { label: tr('pluginTrustCommunity'), cls: 'is-community', icon: <Shield size={12} aria-hidden="true" /> }
}
// The switch already says on/off, so only surface states that need attention.
const stateBadge = (p: PluginInfo) => {
if (p.state === 'degraded') return <span className="badge badge-warn">{tr('pluginStateDegraded')}</span>
if (p.state === 'failed') return <span className="badge badge-warn">{tr('pluginStateFailed')}</span>
if (p.state === 'pending' && p.enabled) return <span className="badge">{tr('pluginStatePending')}</span>
return null
}
const renderRow = (p: PluginInfo) => {
const visual = resolvePluginVisual(p)
const isBuiltin = p.source === 'builtin'
const trust = trustMeta(p.trust)
const perms = p.permissions ?? []
const highPerms = perms.filter((x) => x.level === 'high')
const desc = locText(p.description, locale, '')
const fault = p.error || p.degraded_reason
const alert = fault || (p.needs_approval && highPerms.length > 0 ? tr('pluginHighRiskNotice') : '')
return (
<div className={`row plugin-row${p.enabled ? ' is-enabled' : ''}`} key={p.id}>
<div className={`plugin-app-icon tone-${visual.tone}`}>{visual.icon}</div>
<div className="row-main">
<div className="row-title">
<span className="plugin-row-name">{locText(p.name, locale, p.id)}</span>
{stateBadge(p)}
</div>
{desc && <div className="row-sub plugin-row-desc" title={desc}>{desc}</div>}
{!isBuiltin && (
<div className="row-sub plugin-row-meta">
<span className={`plugin-trust ${trust.cls}`}>{trust.icon}{p.publisher || trust.label}</span>
<span className="mono">v{p.version}</span>
{perms.length > 0 && (
<Tip label={tr('pluginPermissionsLabel', { list: perms.map((x) => x.name).join(', ') })}>
<span>{tr('pluginPermCount', { count: perms.length })}</span>
</Tip>
)}
</div>
)}
{alert && (
<div className="row-sub plugin-row-alert">
{fault ? <AlertTriangle size={12} aria-hidden="true" /> : <ShieldAlert size={12} aria-hidden="true" />}
<span>{alert}</span>
</div>
)}
</div>
<div className="row-right">
{p.settings && (
<IconButton label={tr('pluginSettings')} icon={<Settings2 size={15} />} onClick={() => void openPluginSettings(p)} />
)}
{p.log_path && (
<IconButton label={tr('pluginViewLog')} icon={<Terminal size={15} />} onClick={() => void openPluginLog(p)} />
)}
{p.removable && (
<IconButton
disabled={p.in_use || busyID === p.id}
label={p.in_use ? tr('pluginInUse') : tr('pluginRemove')}
icon={<Trash2 size={15} />}
onClick={() => setRemoveTarget(p)}
/>
)}
<Switch
label={locText(p.name, locale, p.id)}
disabled={busyID === p.id || (p.enabled && p.in_use) || (!!safeMode && !isBuiltin)}
checked={p.enabled}
onChange={(checked) => void togglePlugin(p, checked)}
/>
</div>
</div>
)
}
const showThemeHero = themes.length > 1 && !q
const showSearch = plugins.length > SEARCH_THRESHOLD
const noMatches = !loading && !!q && filteredBuiltins.length === 0 && filteredExternal.length === 0
const previewAccent = activeSchemeSeeds.accent || 'var(--accent)'
const previewSurface = activeSchemeSeeds.surface || 'var(--surface-canvas)'
return (
<div className="page plugins-page">
<header className="page-head">
<div className="page-title plugins-page-title">
<h1>{tr('sidebarPlugins')}</h1>
{!loading && <span>{tr('pluginActiveCount', { active: activeCount, total: plugins.length })}</span>}
</div>
<div className="actions">
{showSearch && (
<div className="plugins-search-wrap">
<Search size={13} className="plugins-search-icon" aria-hidden="true" />
<input
type="search"
className="input plugins-search"
aria-label={tr('pluginSearchPlaceholder')}
placeholder={tr('pluginSearchPlaceholder')}
value={query}
onChange={(e) => setQuery(e.target.value)}
/>
</div>
)}
<IconButton label={tr('refresh')} icon={<RefreshCw size={16} />} onClick={() => void reload()} />
<IconButton label={tr('pluginLinkDevBtn')} icon={<FolderOpen size={16} />} onClick={linkDevDir} />
<Button variant="primary" icon={<PackagePlus size={14} aria-hidden="true" />} onClick={importLocalZip}>
{tr('pluginImportBtn')}
</Button>
</div>
</header>
{showThemeHero && (
<section className="section">
<div className="section-title">{tr('pluginThemeSection')}</div>
<div className="theme-hero-card">
<div className="theme-mini-preview" style={{ background: previewSurface }} aria-hidden="true">
<div className="theme-mini-chrome">
<span className="theme-mini-dot" />
<span className="theme-mini-dot" />
<span className="theme-mini-dot" />
</div>
<div className="theme-mini-body">
<div className="theme-mini-sidebar">
<span className="theme-mini-pill" style={{ background: previewAccent }} />
<span className="theme-mini-line" />
<span className="theme-mini-line short" />
</div>
<div className="theme-mini-main">
<div className="theme-mini-bar" />
<div className="theme-mini-cta" style={{ background: previewAccent }} />
</div>
</div>
</div>
<div className="theme-hero-info">
<div className="theme-hero-top">
<div>
<div className="theme-hero-kicker">
<Sparkles size={12} aria-hidden="true" />
{tr('pluginActiveTheme')}
</div>
<div className="theme-hero-title">
{activeThemeObj ? locText(activeThemeObj.name, locale, activeThemeObj.id) : tr('pluginSchemeDefault')}
</div>
<div className="row-sub">
{safeMode ? tr('pluginThemeSafeModeHint') : tr('pluginThemeHint')}
</div>
</div>
<div className="hstack">
<PopupSelect
label={tr('pluginThemePackLabel')}
value={activeTheme?.theme_id || 'builtin.theme.default'}
options={themes.map((th) => ({
value: th.id,
label: locText(th.name, locale, th.id),
disabled: !!safeMode && th.id !== 'builtin.theme.default',
}))}
onChange={(id) => { if (!safeMode) void selectTheme(id) }}
/>
{activeTheme && activeTheme.theme_id !== 'builtin.theme.default' && (
<Button icon={<Palette size={14} aria-hidden="true" />} onClick={() => setSchemeEditorOpen(true)}>
{tr('pluginNewScheme')}
</Button>
)}
</div>
</div>
{activeTheme && activeTheme.theme_id !== 'builtin.theme.default' ? (
<div className="theme-scheme-strip">
<span className="muted" style={{ fontSize: 'var(--fs-12)' }}>{tr('pluginColorSchemes')}</span>
<div className="theme-scheme-chips">
<button
type="button"
className={`plugin-cat-pill${!activeTheme.active_scheme ? ' is-active' : ''}`}
onClick={() => void selectTheme(activeTheme.theme_id, '')}
>
{tr('pluginSchemeDefault')}
</button>
{presetSchemes.map((s) => (
<button
key={s.id}
type="button"
className={`plugin-cat-pill${activeTheme.active_scheme === s.id ? ' is-active' : ''}`}
onClick={() => void selectTheme(activeTheme.theme_id, s.id)}
>
{s.seeds?.accent && <span className="plugins-scheme-dot" style={{ background: s.seeds.accent }} aria-hidden="true" />}
{locText(s.name, locale, s.id)}
</button>
))}
{customSchemes.map((s) => (
<span className="hstack" style={{ gap: 2 }} key={s.id}>
<button
type="button"
className={`plugin-cat-pill${activeTheme.active_scheme === s.id ? ' is-active' : ''}`}
onClick={() => void selectTheme(activeTheme.theme_id, s.id)}
>
{s.seeds?.accent && <span className="plugins-scheme-dot" style={{ background: s.seeds.accent }} aria-hidden="true" />}
{s.name}
</button>
<IconButton small label={tr('pluginDeleteScheme')} icon={<Trash2 size={12} />} onClick={() => setDeleteSchemeTarget(s)} />
</span>
))}
</div>
</div>
) : (
<div className="row-sub">{tr('pluginThemeEmptyHint')}</div>
)}
</div>
</div>
</section>
)}
{noMatches && <div className="plugins-empty">{tr('pluginSearchEmpty')}</div>}
{filteredExternal.length > 0 && (
<section className="section">
<div className="section-title">
<span>{tr('pluginExternalSection')}</span>
<span className="section-count">{filteredExternal.length}</span>
</div>
<div className="list">{filteredExternal.map(renderRow)}</div>
</section>
)}
{(loading || filteredBuiltins.length > 0) && (
<section className="section">
<div className="section-title">
<span>{tr('pluginBuiltinSection')}</span>
{!loading && <span className="section-count">{filteredBuiltins.length}</span>}
</div>
{loading ? (
<div className="list"><div className="row plugin-row"><span className="muted">…</span></div></div>
) : (
<div className="list">{filteredBuiltins.map(renderRow)}</div>
)}
</section>
)}
{settingsPanels.length > 0 && contribs?.asset_token ? (
<section className="section" data-rg-slot="settings.plugin">
<div className="section-title">{tr('pluginPanelsSection')}</div>
{settingsPanels.map((panel) => (
<PluginPanelFrame
key={`${panel.pluginId}:${panel.id}`}
locale={locale}
panel={panel}
assetToken={contribs.asset_token!}
appearance={appearance}
/>
))}
</section>
) : (
<div className="rg-slot-anchor" data-rg-slot="settings.plugin" />
)}
{approveTarget && (
<Modal
title={tr('pluginApproveTitle')}
subtitle={locText(approveTarget.name, locale, approveTarget.id)}
closeLabel={tr('close')}
onClose={() => setApproveTarget(null)}
>
<div className="stack-3" style={{ padding: 'var(--sp-4)' }}>
{(approveTarget.tier === 'L3' || (approveTarget.permissions ?? []).some((p) => p.name === 'ui:script')) && (
<div className="notice notice-warn">
<ShieldAlert size={15} aria-hidden="true" style={{ marginRight: 6, verticalAlign: '-2px' }} />
{tr('pluginApproveL3Warn')}
</div>
)}
<div className="list">
<div className="row"><div className="row-main"><div className="row-title">{tr('pluginPublisherLicense')}</div><div className="row-sub">{approveTarget.publisher || '—'} · {approveTarget.license || '—'}</div></div></div>
{approveTarget.entry_path && (
<div className="row"><div className="row-main"><div className="row-title">{tr('pluginEntryPath')}</div><div className="row-sub mono selectable">{approveTarget.entry_path}</div></div></div>
)}
{approveTarget.entry_hash && (
<div className="row"><div className="row-main"><div className="row-title">SHA-256</div><div className="row-sub mono selectable">{approveTarget.entry_hash}</div></div></div>
)}
<div className="row"><div className="row-main"><div className="row-title">{tr('pluginRequestedPerms')}</div><div className="row-sub mono">{(approveTarget.permissions ?? []).length > 0 ? (approveTarget.permissions ?? []).map((p) => `${p.name} (${p.level})`).join(', ') : '—'}</div></div></div>
</div>
<label className="hstack" style={{ cursor: 'pointer' }}>
<input type="checkbox" checked={approveChecked} onChange={(e) => setApproveChecked(e.target.checked)} />
<span>{tr('pluginApproveCheckbox')}</span>
</label>
</div>
<div className="dialog-foot">
<span />
<span className="hstack">
<Button variant="ghost" onClick={() => setApproveTarget(null)}>{tr('cancel')}</Button>
<Button variant="primary" disabled={!approveChecked} onClick={() => void confirmApprove()}>
{tr('pluginApproveConfirm')}
</Button>
</span>
</div>
</Modal>
)}
{settingsTarget && settingsTarget.settings && (
<Modal
title={locText(settingsTarget.name, locale, settingsTarget.id)}
subtitle={tr('pluginGlobalSettings')}
closeLabel={tr('close')}
onClose={() => setSettingsTarget(null)}
>
<div style={{ padding: 'var(--sp-4)' }}>
<SchemaForm
locale={locale}
schema={settingsTarget.settings}
values={settingsValues}
scopeFilter="app"
onChange={(next) => void savePluginSettings(next)}
/>
</div>
<div className="dialog-foot">
<span />
<Button variant="primary" onClick={() => setSettingsTarget(null)}>{tr('pluginDone')}</Button>
</div>
</Modal>
)}
{removeTarget && (
<Modal
title={tr('pluginRemove')}
subtitle={locText(removeTarget.name, locale, removeTarget.id)}
closeLabel={tr('close')}
onClose={() => setRemoveTarget(null)}
>
<div style={{ padding: 'var(--sp-4)', fontSize: 'var(--fs-13)', color: 'var(--text-2)' }}>
<span className="mono">{removeTarget.id}@{removeTarget.version}</span>
</div>
<div className="dialog-foot">
<span />
<span className="hstack">
<Button variant="ghost" onClick={() => setRemoveTarget(null)}>{tr('cancel')}</Button>
<Button
variant="danger"
onClick={() => {
const target = removeTarget
setRemoveTarget(null)
void removePlugin(target)
}}
>
{tr('pluginRemove')}
</Button>
</span>
</div>
</Modal>
)}
{deleteSchemeTarget && (
<Modal
title={tr('pluginDeleteScheme')}
subtitle={deleteSchemeTarget.name}
closeLabel={tr('close')}
onClose={() => setDeleteSchemeTarget(null)}
>
<div className="dialog-foot">
<span />
<span className="hstack">
<Button variant="ghost" onClick={() => setDeleteSchemeTarget(null)}>{tr('cancel')}</Button>
<Button
variant="danger"
onClick={() => {
const target = deleteSchemeTarget
setDeleteSchemeTarget(null)
void deleteScheme(target.id)
}}
>
{tr('pluginDeleteScheme')}
</Button>
</span>
</div>
</Modal>
)}
{logTarget && (
<Modal
title={tr('pluginLogTitle', { id: logTarget.id })}
closeLabel={tr('close')}
onClose={() => setLogTarget(null)}
>
<pre className="mono selectable" style={{ padding: 'var(--sp-4)', maxHeight: 360, overflow: 'auto', margin: 0 }}>
{logTarget.text}
</pre>
</Modal>
)}
{schemeEditorOpen && (
<Modal
title={tr('pluginSchemeModalTitle')}
closeLabel={tr('close')}
onClose={() => setSchemeEditorOpen(false)}
>
<div className="stack-3" style={{ padding: 'var(--sp-4)' }}>
<label className="stack-1">
<span>{tr('pluginSchemeName')}</span>
<input className="input" value={schemeName} onChange={(e) => setSchemeName(e.target.value)} placeholder={tr('pluginSchemePlaceholder')} />
</label>
<label className="hstack">
<span>{tr('pluginAccentSeed')}</span>
<input type="color" value={seedAccent} onChange={(e) => setSeedAccent(e.target.value)} />
<span className="mono">{seedAccent}</span>
</label>
<label className="stack-1">
<span>{tr('pluginSurfaceSeed')}</span>
<input className="input mono" value={seedSurface} onChange={(e) => setSeedSurface(e.target.value)} placeholder="#1d1e23" />
</label>
</div>
<div className="dialog-foot">
<span />
<span className="hstack">
<Button variant="ghost" onClick={() => setSchemeEditorOpen(false)}>{tr('cancel')}</Button>
<Button variant="primary" disabled={!schemeName.trim()} onClick={() => void saveScheme()}>{tr('save')}</Button>
</span>
</div>
</Modal>
)}
</div>
)
}
-496
View File
@@ -1,496 +0,0 @@
import { AlertTriangle, FolderOpen, PackagePlus, Palette, Settings2, ShieldAlert, Terminal, Trash2 } from 'lucide-react'
import React, { useEffect, useState } from 'react'
import { I18nKey, t } from '../i18n'
import {
ActiveThemePayload, CustomThemeScheme, Locale, PluginInfo, PluginUIContributions,
} from '../types'
import { Button, IconButton } from '../ui/controls'
import { Modal } from '../ui/dialog'
import { PopupSelect, Switch } from '../ui/settings'
import { api } from '../wails'
import { PluginPanelFrame } from './PluginPanelFrame'
import { SchemaForm, locText } from './SchemaForm'
interface Props {
locale: Locale
appearance: 'light' | 'dark'
safeMode?: boolean
onRefresh: () => void
onError: (title: string, e: unknown) => void
onThemeChanged?: () => void
}
/**
* Lazy-loaded Plugin & Theme Management section inside App Settings (§5.1, §8.1, §10).
* Keeps plugin management + SchemaForm out of the startup bundle.
*/
export const PluginsSection: React.FC<Props> = ({
locale, appearance, safeMode, onRefresh, onError, onThemeChanged,
}) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const [plugins, setPlugins] = useState<PluginInfo[]>([])
const [contribs, setContribs] = useState<PluginUIContributions | null>(null)
const [activeTheme, setActiveTheme] = useState<ActiveThemePayload | null>(null)
const [busyID, setBusyID] = useState('')
const [approveTarget, setApproveTarget] = useState<PluginInfo | null>(null)
const [approveChecked, setApproveChecked] = useState(false)
const [settingsTarget, setSettingsTarget] = useState<PluginInfo | null>(null)
const [settingsValues, setSettingsValues] = useState<Record<string, unknown>>({})
const [logTarget, setLogTarget] = useState<{ id: string; text: string } | null>(null)
// Theme scheme editor state (§5.1)
const [schemeEditorOpen, setSchemeEditorOpen] = useState(false)
const [schemeName, setSchemeName] = useState('')
const [seedAccent, setSeedAccent] = useState('#007aff')
const [seedSurface, setSeedSurface] = useState('')
const reload = async () => {
try {
const [list, ui, th] = await Promise.all([
api.ListPlugins(),
api.GetPluginUIContributions(),
api.GetActiveTheme(),
])
setPlugins(list ?? [])
setContribs(ui)
setActiveTheme(th)
} catch (e) {
onError(tr('pluginFailLoad'), e)
}
}
useEffect(() => { void reload() }, [])
const togglePlugin = async (p: PluginInfo, enable: boolean) => {
if (enable && p.needs_approval) {
setApproveChecked(false)
setApproveTarget(p)
return
}
setBusyID(p.id)
try {
if (enable) await api.EnablePlugin(p.id, false)
else await api.DisablePlugin(p.id)
await reload()
onRefresh()
onThemeChanged?.()
} catch (e) {
onError(tr('pluginFailToggle'), e)
} finally {
setBusyID('')
}
}
const confirmApprove = async () => {
if (!approveTarget || !approveChecked) return
const target = approveTarget
setApproveTarget(null)
setBusyID(target.id)
try {
await api.EnablePlugin(target.id, true)
await reload()
onRefresh()
onThemeChanged?.()
} catch (e) {
onError(tr('pluginFailEnable'), e)
} finally {
setBusyID('')
}
}
const importLocalZip = async () => {
try {
const path = await api.PickFile(tr('pluginImportTitle'), '*.zip')
if (!path) return
await api.InstallPluginArchive(path)
await reload()
onRefresh()
} catch (e) {
onError(tr('pluginFailImport'), e)
}
}
const linkDevDir = async () => {
try {
const dir = await api.PickDirectory(tr('pluginLinkDevTitle'))
if (!dir) return
await api.LinkPluginDev(dir)
await reload()
onRefresh()
} catch (e) {
onError(tr('pluginFailLinkDev'), e)
}
}
const removePlugin = async (p: PluginInfo) => {
setBusyID(p.id)
try {
await api.RemovePlugin(p.id, false)
await reload()
onRefresh()
onThemeChanged?.()
} catch (e) {
onError(tr('pluginFailRemove'), e)
} finally {
setBusyID('')
}
}
const openPluginSettings = async (p: PluginInfo) => {
try {
const vals = await api.GetPluginSettings(p.id, '')
setSettingsValues((vals ?? {}) as Record<string, unknown>)
setSettingsTarget(p)
} catch (e) {
onError(tr('pluginFailLoadSettings'), e)
}
}
const savePluginSettings = async (next: Record<string, unknown>) => {
setSettingsValues(next)
if (!settingsTarget) return
try {
await api.SetPluginSettings(settingsTarget.id, '', next)
onRefresh()
} catch (e) {
onError(tr('pluginFailSaveSettings'), e)
}
}
const openPluginLog = async (p: PluginInfo) => {
try {
const txt = await api.ReadPluginLog(p.id)
setLogTarget({ id: p.id, text: txt || tr('pluginLogEmpty') })
} catch (e) {
onError(tr('pluginFailReadLog'), e)
}
}
const selectTheme = async (themeID: string, schemeID = '') => {
try {
await api.SetActiveTheme(themeID, schemeID)
await reload()
onThemeChanged?.()
} catch (e) {
onError(tr('pluginFailSwitchTheme'), e)
}
}
const saveScheme = async () => {
if (!activeTheme || !schemeName.trim()) return
const id = `custom-${Date.now()}`
const scheme: CustomThemeScheme = {
id,
theme_id: activeTheme.theme_id,
name: schemeName.trim(),
appearance,
seeds: {
accent: seedAccent,
...(seedSurface ? { surface: seedSurface } : {}),
},
}
try {
await api.SaveCustomThemeScheme(scheme)
await api.SetActiveTheme(activeTheme.theme_id, id)
setSchemeEditorOpen(false)
setSchemeName('')
await reload()
onThemeChanged?.()
} catch (e) {
onError(tr('pluginFailSaveScheme'), e)
}
}
const deleteScheme = async (schemeID: string) => {
try {
await api.DeleteCustomThemeScheme(schemeID)
await reload()
onThemeChanged?.()
} catch (e) {
onError(tr('pluginFailDeleteScheme'), e)
}
}
const builtins = plugins.filter((p) => p.source === 'builtin')
const external = plugins.filter((p) => p.source !== 'builtin')
const themes = contribs?.themes ?? []
const settingsPanels = (contribs?.panels ?? []).filter((p) => p.slot === 'settings.plugin')
const trustLabel = (trLevel: string) => {
if (trLevel === 'official') return tr('pluginTrustOfficial')
if (trLevel === 'verified') return tr('pluginTrustVerified')
if (trLevel === 'dev') return tr('pluginTrustDev')
return tr('pluginTrustCommunity')
}
const stateBadge = (p: PluginInfo) => {
if (p.state === 'active') return <span className="badge badge-ok">{tr('pluginStateActive')}</span>
if (p.state === 'degraded') return <span className="badge badge-warn">{tr('pluginStateDegraded')}</span>
if (p.state === 'failed') return <span className="badge badge-error">{tr('pluginStateFailed')}</span>
if (p.state === 'pending') return <span className="badge">{tr('pluginStatePending')}</span>
return <span className="badge">{tr('pluginStateOff')}</span>
}
const renderRow = (p: PluginInfo) => {
const highPerms = (p.permissions ?? []).filter((x) => x.level === 'high')
return (
<div className="row" key={p.id}>
<div className="row-main">
<div className="row-title">
{locText(p.name, locale, p.id)}
<span className="mono muted">v{p.version}</span>
<span className="badge">{trustLabel(p.trust)}</span>
{p.tier !== 'builtin' && <span className="badge">{p.tier}</span>}
{stateBadge(p)}
</div>
<div className="row-sub">
{locText(p.description, locale, p.id)}
{p.license ? ` · ${p.license}` : ''}
{p.permissions && p.permissions.length > 0
? ` · ${tr('pluginPermissionsLabel', { list: p.permissions.map((x) => x.name).join(', ') })}`
: ''}
</div>
{(p.error || p.degraded_reason) && (
<div className="row-sub warn-text">
<AlertTriangle size={12} style={{ verticalAlign: '-2px', marginRight: 4 }} />
{p.error || p.degraded_reason}
</div>
)}
{p.needs_approval && highPerms.length > 0 && (
<div className="row-sub warn-text">
{tr('pluginHighRiskNotice')}
</div>
)}
</div>
<div className="row-right hstack">
{p.settings && (
<IconButton small label={tr('pluginSettings')} icon={<Settings2 size={14} />} onClick={() => void openPluginSettings(p)} />
)}
{p.log_path && (
<IconButton small label={tr('pluginViewLog')} icon={<Terminal size={14} />} onClick={() => void openPluginLog(p)} />
)}
{p.removable && (
<IconButton
small
disabled={p.in_use || busyID === p.id}
label={p.in_use ? tr('pluginInUse') : tr('pluginRemove')}
icon={<Trash2 size={14} />}
onClick={() => void removePlugin(p)}
/>
)}
<Switch
label={locText(p.name, locale, p.id)}
disabled={busyID === p.id || (p.enabled && p.in_use) || (!!safeMode && p.source !== 'builtin')}
checked={p.enabled}
onChange={(checked) => void togglePlugin(p, checked)}
/>
</div>
</div>
)
}
return (
<>
{themes.length > 1 && (
<section className="section">
<div className="section-title">{tr('pluginThemeSection')}</div>
<div className="list">
<div className="row">
<div className="row-main">
<div className="row-title">{tr('pluginActiveTheme')}</div>
<div className="row-sub">
{safeMode ? tr('pluginThemeSafeModeHint') : tr('pluginThemeHint')}
</div>
</div>
<div className="row-right hstack">
<PopupSelect
label={tr('pluginThemePackLabel')}
value={activeTheme?.theme_id || 'builtin.theme.default'}
options={themes.map((th) => ({
value: th.id,
label: locText(th.name, locale, th.id),
disabled: !!safeMode && th.id !== 'builtin.theme.default',
}))}
onChange={(id) => { if (!safeMode) void selectTheme(id) }}
/>
{activeTheme && activeTheme.theme_id !== 'builtin.theme.default' && (
<Button icon={<Palette size={14} />} onClick={() => setSchemeEditorOpen(true)}>
{tr('pluginNewScheme')}
</Button>
)}
</div>
</div>
{activeTheme && activeTheme.theme_id !== 'builtin.theme.default' && (
<div className="row">
<div className="row-main">
<div className="row-title">{tr('pluginColorSchemes')}</div>
<div className="row-sub">{tr('pluginColorSchemesHint')}</div>
</div>
<div className="row-right hstack">
{(activeTheme.custom_schemes ?? []).filter((s) => s.theme_id === activeTheme.theme_id).map((s) => (
<span className="hstack" key={s.id}>
<Button
variant={activeTheme.active_scheme === s.id ? 'primary' : undefined}
onClick={() => void selectTheme(activeTheme.theme_id, s.id)}
>
{s.name}
</Button>
<IconButton small label={tr('pluginDeleteScheme')} icon={<Trash2 size={13} />} onClick={() => void deleteScheme(s.id)} />
</span>
))}
</div>
</div>
)}
</div>
</section>
)}
<section className="section">
<div className="section-title hstack" style={{ justifyContent: 'space-between' }}>
<span>{tr('pluginExternalSection')}</span>
<span className="hstack">
<Button icon={<FolderOpen size={14} />} onClick={linkDevDir}>
{tr('pluginLinkDevBtn')}
</Button>
<Button icon={<PackagePlus size={14} />} onClick={importLocalZip}>
{tr('pluginImportBtn')}
</Button>
</span>
</div>
<div className="list">
{external.length === 0 ? (
<div className="row"><div className="row-sub">{tr('pluginExternalEmpty')}</div></div>
) : external.map(renderRow)}
</div>
</section>
<section className="section">
<div className="section-title">{tr('pluginBuiltinSection')}</div>
<div className="list">{builtins.map(renderRow)}</div>
</section>
{settingsPanels.length > 0 && contribs?.asset_token ? (
<section className="section" data-rg-slot="settings.plugin">
<div className="section-title">{tr('pluginPanelsSection')}</div>
{settingsPanels.map((panel) => (
<PluginPanelFrame
key={`${panel.pluginId}:${panel.id}`}
locale={locale}
panel={panel}
assetToken={contribs.asset_token!}
appearance={appearance}
/>
))}
</section>
) : (
<div className="rg-slot-anchor" data-rg-slot="settings.plugin" />
)}
{approveTarget && (
<Modal
title={tr('pluginApproveTitle')}
subtitle={locText(approveTarget.name, locale, approveTarget.id)}
closeLabel={tr('close')}
onClose={() => setApproveTarget(null)}
>
<div className="stack-3" style={{ padding: 'var(--sp-4)' }}>
{(approveTarget.tier === 'L3' || (approveTarget.permissions ?? []).some((p) => p.name === 'ui:script')) && (
<div className="notice notice-warn">
<ShieldAlert size={15} aria-hidden="true" style={{ marginRight: 6, verticalAlign: '-2px' }} />
{tr('pluginApproveL3Warn')}
</div>
)}
<div className="list">
<div className="row"><div className="row-main"><div className="row-title">{tr('pluginPublisherLicense')}</div><div className="row-sub">{approveTarget.publisher || '—'} · {approveTarget.license || '—'}</div></div></div>
{approveTarget.entry_path && (
<div className="row"><div className="row-main"><div className="row-title">{tr('pluginEntryPath')}</div><div className="row-sub mono selectable">{approveTarget.entry_path}</div></div></div>
)}
{approveTarget.entry_hash && (
<div className="row"><div className="row-main"><div className="row-title">SHA-256</div><div className="row-sub mono selectable">{approveTarget.entry_hash}</div></div></div>
)}
<div className="row"><div className="row-main"><div className="row-title">{tr('pluginRequestedPerms')}</div><div className="row-sub mono">{(approveTarget.permissions ?? []).length > 0 ? (approveTarget.permissions ?? []).map((p) => `${p.name} (${p.level})`).join(', ') : '—'}</div></div></div>
</div>
<label className="hstack" style={{ cursor: 'pointer' }}>
<input type="checkbox" checked={approveChecked} onChange={(e) => setApproveChecked(e.target.checked)} />
<span>{tr('pluginApproveCheckbox')}</span>
</label>
</div>
<div className="dialog-foot">
<span />
<span className="hstack">
<Button variant="ghost" onClick={() => setApproveTarget(null)}>{tr('cancel')}</Button>
<Button variant="primary" disabled={!approveChecked} onClick={() => void confirmApprove()}>
{tr('pluginApproveConfirm')}
</Button>
</span>
</div>
</Modal>
)}
{settingsTarget && settingsTarget.settings && (
<Modal
title={locText(settingsTarget.name, locale, settingsTarget.id)}
subtitle={tr('pluginGlobalSettings')}
closeLabel={tr('close')}
onClose={() => setSettingsTarget(null)}
>
<div style={{ padding: 'var(--sp-4)' }}>
<SchemaForm
locale={locale}
schema={settingsTarget.settings}
values={settingsValues}
onChange={(next) => void savePluginSettings(next)}
/>
</div>
<div className="dialog-foot">
<span />
<Button variant="primary" onClick={() => setSettingsTarget(null)}>{tr('pluginDone')}</Button>
</div>
</Modal>
)}
{logTarget && (
<Modal
title={tr('pluginLogTitle', { id: logTarget.id })}
closeLabel={tr('close')}
onClose={() => setLogTarget(null)}
>
<pre className="mono selectable" style={{ padding: 'var(--sp-4)', maxHeight: 360, overflow: 'auto', margin: 0 }}>
{logTarget.text}
</pre>
</Modal>
)}
{schemeEditorOpen && (
<Modal
title={tr('pluginSchemeModalTitle')}
closeLabel={tr('close')}
onClose={() => setSchemeEditorOpen(false)}
>
<div className="stack-3" style={{ padding: 'var(--sp-4)' }}>
<label className="stack-1">
<span>{tr('pluginSchemeName')}</span>
<input className="input" value={schemeName} onChange={(e) => setSchemeName(e.target.value)} placeholder={tr('pluginSchemePlaceholder')} />
</label>
<label className="hstack">
<span>{tr('pluginAccentSeed')}</span>
<input type="color" value={seedAccent} onChange={(e) => setSeedAccent(e.target.value)} />
<span className="mono">{seedAccent}</span>
</label>
<label className="stack-1">
<span>{tr('pluginSurfaceSeed')}</span>
<input className="input mono" value={seedSurface} onChange={(e) => setSeedSurface(e.target.value)} placeholder="#1d1e23" />
</label>
</div>
<div className="dialog-foot">
<span />
<span className="hstack">
<Button variant="ghost" onClick={() => setSchemeEditorOpen(false)}>{tr('cancel')}</Button>
<Button variant="primary" disabled={!schemeName.trim()} onClick={() => void saveScheme()}>{tr('save')}</Button>
</span>
</div>
</Modal>
)}
</>
)
}
+14 -3
View File
@@ -1,5 +1,5 @@
import * as Ctx from '@radix-ui/react-context-menu'
import { AppWindow, Camera, CopyPlus, Cpu, Download, FolderOpen, Play, Plus, Power, RotateCw, Settings, Square, Trash } from 'lucide-react'
import { AppWindow, Camera, CopyPlus, Cpu, Download, FolderOpen, Play, Plus, Power, Puzzle, RotateCw, Settings, Square, Trash } from 'lucide-react'
import React, { useRef } from 'react'
import { I18nKey, t } from '../i18n'
import { Locale, VMListItem } from '../types'
@@ -9,6 +9,7 @@ import { VMAction } from './VMPage'
export const HOST_ID = '__host__'
export const INSTALLERS_ID = '__installers__'
export const PLUGINS_ID = '__plugins__'
export const SETTINGS_ID = '__settings__'
interface Props {
@@ -28,14 +29,16 @@ interface Props {
onVMContextAction?: (name: string, action: VMAction | 'settings') => void
/** An installer download is running (busy dot on the Installers entry). */
downloading?: boolean
/** Safe mode is active (third-party plugins skipped). */
safeMode?: boolean
}
export const Sidebar: React.FC<Props> = ({
locale, vms, transitions, selected, hostReady, onSelect, displayNames = {}, macosMajors = {}, onActivate, onNew, onVMContextAction, downloading,
locale, vms, transitions, selected, hostReady, onSelect, displayNames = {}, macosMajors = {}, onActivate, onNew, onVMContextAction, downloading, safeMode,
}) => {
const tr = (k: I18nKey) => t(locale, k)
const listRef = useRef<HTMLDivElement>(null)
const ids = [...vms.map((v) => v.name), INSTALLERS_ID, HOST_ID, SETTINGS_ID]
const ids = [...vms.map((v) => v.name), INSTALLERS_ID, PLUGINS_ID, HOST_ID, SETTINGS_ID]
// Listbox keyboard model: ↑/↓/Home/End move selection and focus together.
const onKeyDown = (e: React.KeyboardEvent) => {
@@ -172,6 +175,14 @@ export const Sidebar: React.FC<Props> = ({
downloading ? tr('state_starting') : '',
downloading ? 'busy' : null,
)}
{navBtn(
PLUGINS_ID,
tr('sidebarPlugins'),
<Puzzle size={13} />,
'nav-icon-plugins',
safeMode ? tr('pluginSafeModeShort') : '',
safeMode ? 'warn' : null,
)}
{navBtn(
HOST_ID,
tr('sidebarHost'),
+11 -3
View File
@@ -5,7 +5,7 @@ import { I18nKey, t } from '../i18n'
import { Locale } from '../types'
import { Tip } from '../ui/controls'
import type { ThemeMode } from './AppSettingsPage'
import { HOST_ID, INSTALLERS_ID, SETTINGS_ID } from './Sidebar'
import { HOST_ID, INSTALLERS_ID, PLUGINS_ID, SETTINGS_ID } from './Sidebar'
import { VMAction } from './VMPage'
const REPO_URL = 'https://github.com/Nwflower/Reims-Go'
@@ -17,6 +17,8 @@ interface Props {
logsOpen: boolean
onToggleLogs: () => void
themeMode: ThemeMode
canLight?: boolean
canDark?: boolean
onThemeMode: (mode: ThemeMode) => void
/** The selected VM and its current state, or null on the system pages. */
vm: { name: string; state: string; busy: boolean } | null
@@ -36,7 +38,7 @@ interface Props {
* open, hovering the next title switches to it, as in a native menu bar.
*/
export const TitleMenus: React.FC<Props> = ({
locale, sidebarOpen, onToggleSidebar, logsOpen, onToggleLogs, themeMode, onThemeMode,
locale, sidebarOpen, onToggleSidebar, logsOpen, onToggleLogs, themeMode, canLight = true, canDark = true, onThemeMode,
vm, onNewVM, onVMAction, onVMSettings, onVMDelete, onNavigate, onOpenURL, appVersion,
}) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
@@ -121,7 +123,12 @@ export const TitleMenus: React.FC<Props> = ({
<Menu.Label className="menu-group-label">{tr('appearance')}</Menu.Label>
<Menu.RadioGroup value={themeMode} onValueChange={(v) => onThemeMode(v as ThemeMode)}>
{(['light', 'dark', 'system'] as const).map((m) => (
<Menu.RadioItem key={m} className="menu-item menu-item-check" value={m}>
<Menu.RadioItem
key={m}
className="menu-item menu-item-check"
value={m}
disabled={(m === 'light' && !canLight) || (m === 'dark' && !canDark) || (m === 'system' && (!canLight || !canDark))}
>
<Menu.ItemIndicator className="menu-check"><Check size={13} /></Menu.ItemIndicator>
<span className="menu-label">{tr(m === 'light' ? 'themeLight' : m === 'dark' ? 'themeDark' : 'themeSystem')}</span>
</Menu.RadioItem>
@@ -129,6 +136,7 @@ export const TitleMenus: React.FC<Props> = ({
</Menu.RadioGroup>
<Menu.Separator className="menu-sep" />
{item(tr('sidebarInstallers'), () => onNavigate(INSTALLERS_ID))}
{item(tr('sidebarPlugins'), () => onNavigate(PLUGINS_ID))}
{item(tr('sidebarHost'), () => onNavigate(HOST_ID))}
{item(tr('sidebarSettings'), () => onNavigate(SETTINGS_ID))}
</>
+2 -2
View File
@@ -143,7 +143,7 @@ export const VMPage: React.FC<Props> = ({
let live = true
const pull = () => {
if (document.hidden) return
api.GetVMThumbnail(name).then((t) => { if (live && t.data_url) setThumb(t) }).catch(() => {})
api.GetVMThumbnail(name).then((t) => { if (live && t?.data_url) setThumb(t) }).catch(() => {})
}
pull()
const timer = running ? window.setInterval(pull, 15000) : undefined
@@ -404,7 +404,7 @@ export const VMPage: React.FC<Props> = ({
<Archive size={14} /> {tr('exportDiagnostics')}
</Menu.Item>
{(pluginUI?.menus ?? [])
.filter((m) => m.slot === 'vm.toolbar' && (!m.when || (m.when === 'vm.running' ? running : m.when === 'vm.stopped' ? state === 'stopped' : true)))
.filter((m) => m.slot === 'vm.toolbar' && (!m.when || (m.when === 'vm.running' ? running : m.when === 'vm.stopped' ? state === 'stopped' : false)))
.map((m) => (
<Menu.Item
key={`${m.pluginId}:${m.id}`}
+48
View File
@@ -8,6 +8,7 @@ const dict = {
sidebarVMs: '虚拟机',
sidebarSystem: '系统',
sidebarHost: '内核',
sidebarPlugins: '插件',
sidebarSettings: '设置',
sidebarInstallers: '安装包',
installersTitle: '安装包',
@@ -748,6 +749,29 @@ const dict = {
pluginSchemePlaceholder: '如:柔蓝',
pluginAccentSeed: '强调种子色',
pluginSurfaceSeed: '画布种子色(可选)',
pluginSafeModeShort: '安全模式',
pluginTabAll: '全部 ({count})',
pluginTabInstalled: '已安装 ({count})',
pluginTabThemes: '主题 ({count})',
pluginTabBuiltin: '内置 ({count})',
pluginSearchPlaceholder: '筛选插件',
pluginSearchEmpty: '没有匹配的插件',
pluginSchemeDefault: '默认',
pluginThemeEmptyHint: '导入本地主题包(.zip)后可在此切换外观与配色方案',
pluginActiveCount: '已启用 {active} / {total}',
pluginCategoryFilter: '按类别筛选',
pluginCatAll: '全部类别',
pluginCatDriver: '驱动与运行时',
pluginCatTheme: '主题外观',
pluginCatBridge: '输入与协作',
pluginCatCompat: '兼容与工具',
pluginCatOther: '扩展',
pluginPermCount: '{count} 项权限',
pluginExternalEmptyHint: '支持导入签名或本地 .zip 插件包,或链接开发目录实时调试',
pluginInstallBarTitle: '安装本地插件',
pluginInstallBarDesc: '导入 .zip 插件包或链接本地插件开发目录',
themePluginDarkDisabled: '默认主题插件已停用,深色与跟随系统外观不可用',
themePluginLightDisabled: '当前主题仅支持深色外观',
// Locale-aware composite labels
offlineListFailedDetail: '无法读取 Apple 的版本列表:{err}',
@@ -761,6 +785,7 @@ const dict = {
sidebarVMs: 'Virtual machines',
sidebarSystem: 'System',
sidebarHost: 'Engine',
sidebarPlugins: 'Plugins',
sidebarSettings: 'Settings',
sidebarInstallers: 'Installers',
installersTitle: 'Installers',
@@ -1488,6 +1513,29 @@ const dict = {
pluginSchemePlaceholder: 'e.g. Soft Blue',
pluginAccentSeed: 'Accent seed',
pluginSurfaceSeed: 'Surface seed (optional)',
pluginSafeModeShort: 'Safe mode',
pluginTabAll: 'All ({count})',
pluginTabInstalled: 'Installed ({count})',
pluginTabThemes: 'Themes ({count})',
pluginTabBuiltin: 'Built-in ({count})',
pluginSearchPlaceholder: 'Filter plugins',
pluginSearchEmpty: 'No matching plugins',
pluginSchemeDefault: 'Default',
pluginThemeEmptyHint: 'Import a local theme package (.zip) to switch visual themes and color schemes',
pluginActiveCount: '{active} / {total} active',
pluginCategoryFilter: 'Filter by category',
pluginCatAll: 'All types',
pluginCatDriver: 'Drivers & runtimes',
pluginCatTheme: 'Themes',
pluginCatBridge: 'Input & bridge',
pluginCatCompat: 'Compatibility',
pluginCatOther: 'Extensions',
pluginPermCount: '{count} permissions',
pluginExternalEmptyHint: 'Import a signed or local .zip package, or link a local dev folder',
pluginInstallBarTitle: 'Install local plugin',
pluginInstallBarDesc: 'Import a .zip plugin archive or link a local development directory',
themePluginDarkDisabled: 'Default theme plugin is disabled; dark and system appearances are unavailable',
themePluginLightDisabled: 'The active theme supports dark appearance only',
// Locale-aware composite labels
offlineListFailedDetail: 'Couldn’t read Apple’s release list: {err}',
+5 -2
View File
@@ -18,8 +18,11 @@ const WARN_RE = /\bwarn(ing)?\b/i
let nextId = 1
export function classify(entry: LogEntry): LogLine {
const level: LogLevel = ERROR_RE.test(entry.line) ? 'error' : WARN_RE.test(entry.line) ? 'warn' : 'info'
return { ...entry, id: nextId++, level }
const ts = typeof entry?.ts === 'string' ? entry.ts : ''
const source = typeof entry?.source === 'string' ? entry.source : ''
const line = typeof entry?.line === 'string' ? entry.line : String(entry?.line ?? '')
const level: LogLevel = ERROR_RE.test(line) ? 'error' : WARN_RE.test(line) ? 'warn' : 'info'
return { ts, source, line, id: nextId++, level }
}
export function appendLog(prev: LogLine[], entry: LogEntry): LogLine[] {
+32 -1
View File
@@ -1,14 +1,45 @@
import React from 'react'
import ReactDOM from 'react-dom/client'
import { App } from './App'
import { ErrorBoundary } from './components/ErrorBoundary'
import { applyCachedThemeTokensSync } from './lib/themeEngine'
import './styles/app.css'
import { events } from './wails'
// Inline cached theme tokens before first paint to prevent FOUC (§5.1).
applyCachedThemeTokensSync()
let lastReportedErr = ''
let lastReportedAt = 0
function reportUIError(msg: string) {
const trimmed = msg.trim()
if (!trimmed) return
// Benign Chromium ResizeObserver delivery notice fired during rapid layout/resize.
if (trimmed.includes('ResizeObserver loop completed with undelivered notifications') || trimmed.includes('ResizeObserver loop limit exceeded')) {
return
}
const now = Date.now()
if (trimmed === lastReportedErr && now - lastReportedAt < 5000) return
lastReportedErr = trimmed
lastReportedAt = now
events.emitUIError(trimmed.slice(0, 1500))
}
window.addEventListener('error', (e) => {
const msg = e.error instanceof Error ? `${e.error.message}\n${e.error.stack ?? ''}` : (e.message || 'Unknown window error')
reportUIError(`window.error: ${msg}`)
})
window.addEventListener('unhandledrejection', (e) => {
const r = e.reason
const msg = r instanceof Error ? `${r.message}\n${r.stack ?? ''}` : String(r ?? 'Unknown rejection')
reportUIError(`unhandledrejection: ${msg}`)
})
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<App />
<ErrorBoundary>
<App />
</ErrorBoundary>
</React.StrictMode>,
)
+101
View File
@@ -208,6 +208,7 @@ h1, h2, h3, p { margin: 0; }
.nav-icon-art { overflow: hidden; background: #8d95a9; }
.nav-icon-art svg { width: 100%; height: 100%; display: block; }
.nav-icon-host { background: linear-gradient(145deg, #6e7cf0 0%, #4d5be0 100%); }
.nav-icon-plugins { background: linear-gradient(145deg, #af52de 0%, #8944ab 100%); }
.nav-icon-settings { background: linear-gradient(145deg, #8e8e93 0%, #636366 100%); }
.nav-icon-installers { background: linear-gradient(145deg, #34c759 0%, #248a3d 100%); }
.nav-label { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: var(--fs-13); }
@@ -1495,6 +1496,106 @@ button.status-issue + .status-metric { margin-left: 6px; }
padding: 12px 14px; border: 1px solid var(--danger-border); border-radius: var(--r-md);
background: var(--danger-soft); color: var(--danger-text); font-size: var(--fs-12);
}
.plugins-search-wrap { position: relative; display: flex; align-items: center; }
.plugins-search-icon {
position: absolute; left: 10px; color: var(--text-3); pointer-events: none;
}
.plugins-search { width: 210px; padding-left: 30px; }
.plugins-scheme-dot {
width: 9px; height: 9px; border-radius: 50%; flex-shrink: 0;
border: 1px solid var(--border-strong); display: inline-block;
}
.plugin-cat-pill {
display: inline-flex; align-items: center; gap: 6px;
height: 26px; padding: 0 11px; border-radius: 999px;
border: 1px solid var(--border); background: var(--surface-1);
color: var(--text-2); font-size: var(--fs-12); font-weight: var(--fw-medium);
cursor: pointer; transition: background 0.12s ease, border-color 0.12s ease, color 0.12s ease;
}
.plugin-cat-pill:hover { background: var(--surface-hover); color: var(--text); }
.plugin-cat-pill.is-active {
background: var(--accent-soft); border-color: var(--accent); color: var(--accent-soft-text);
}
/* iOS/macOS App Store–inspired squircle icon tiles */
.plugin-app-icon {
width: 40px; height: 40px; border-radius: 11px; flex-shrink: 0;
display: inline-flex; align-items: center; justify-content: center;
color: #fff; box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.28), 0 1px 2px rgba(0, 0, 0, 0.14);
}
.plugin-app-icon.tone-indigo { background: linear-gradient(145deg, #6e7cf0 0%, #4d5be0 100%); }
.plugin-app-icon.tone-purple { background: linear-gradient(145deg, #bf5af2 0%, #8944ab 100%); }
.plugin-app-icon.tone-sky { background: linear-gradient(145deg, #32a0ff 0%, #007aff 100%); }
.plugin-app-icon.tone-rose { background: linear-gradient(145deg, #ff6482 0%, #ff2d55 100%); }
.plugin-app-icon.tone-emerald { background: linear-gradient(145deg, #34c759 0%, #248a3d 100%); }
.plugin-app-icon.tone-amber { background: linear-gradient(145deg, #ffb340 0%, #ff9500 100%); }
.plugin-app-icon.tone-teal { background: linear-gradient(145deg, #40c8e0 0%, #00a3c4 100%); }
.plugin-app-icon.tone-slate { background: linear-gradient(145deg, #8e8e93 0%, #636366 100%); }
/* Plugin rows: grouped inset list, matching the installers page */
.plugins-page { max-width: 780px; }
.plugins-page-title { flex-direction: column; align-items: flex-start; gap: 1px; }
.plugins-page-title > span { color: var(--text-3); font-size: var(--fs-12); line-height: 1.45; }
.plugin-row { gap: 12px; min-height: 60px; }
.plugin-row .plugin-app-icon { width: 34px; height: 34px; border-radius: 9px; }
.plugin-row .plugin-app-icon svg { width: 18px; height: 18px; }
.plugin-row-name { font-weight: var(--fw-medium); }
.plugin-row-desc {
color: var(--text-2); line-height: 1.45;
display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden;
}
.plugin-row-meta { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
.plugin-row-alert { display: flex; align-items: center; gap: 5px; color: var(--warn-text); }
.plugin-trust { display: inline-flex; align-items: center; gap: 3px; font-weight: var(--fw-medium); }
.plugin-trust.is-official, .plugin-trust.is-verified { color: var(--ok-text); }
.plugin-trust.is-dev { color: var(--accent-soft-text); }
.plugin-trust.is-community { color: var(--text-2); }
.plugins-empty { padding: 24px 4px; text-align: center; color: var(--text-3); font-size: var(--fs-13); }
/* Visual theme hero card with live miniature window preview */
.theme-hero-card {
display: flex; align-items: stretch; gap: 16px; padding: 14px 16px;
border-radius: var(--r-lg); background: var(--surface-1);
border: 1px solid var(--border); box-shadow: var(--shadow-card);
}
@media (max-width: 720px) {
.theme-hero-card { flex-direction: column; }
}
.theme-mini-preview {
width: 152px; min-height: 92px; flex-shrink: 0; border-radius: var(--r-md);
border: 1px solid var(--border-strong); overflow: hidden;
display: flex; flex-direction: column;
}
.theme-mini-chrome {
height: 18px; padding: 0 7px; display: flex; align-items: center; gap: 4px;
background: var(--surface-chrome); border-bottom: 1px solid var(--border);
}
.theme-mini-dot { width: 5px; height: 5px; border-radius: 50%; background: var(--border-strong); }
.theme-mini-body { flex: 1; display: flex; }
.theme-mini-sidebar {
width: 44px; padding: 7px 6px; display: flex; flex-direction: column; gap: 5px;
background: var(--surface-sidebar); border-right: 1px solid var(--border);
}
.theme-mini-pill { height: 7px; border-radius: 3px; opacity: 0.9; }
.theme-mini-line { height: 5px; border-radius: 3px; background: var(--border-strong); opacity: 0.65; }
.theme-mini-line.short { width: 70%; }
.theme-mini-main {
flex: 1; padding: 9px 10px; display: flex; flex-direction: column; justify-content: space-between; gap: 8px;
}
.theme-mini-bar { height: 10px; width: 68%; border-radius: 4px; background: var(--border-strong); opacity: 0.5; }
.theme-mini-cta { height: 14px; width: 42px; border-radius: 5px; align-self: flex-end; }
.theme-hero-info { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 10px; justify-content: space-between; }
.theme-hero-top { display: flex; align-items: flex-start; justify-content: space-between; gap: var(--sp-3); flex-wrap: wrap; }
.theme-hero-kicker {
display: inline-flex; align-items: center; gap: 4px;
font-size: var(--fs-11); font-weight: var(--fw-medium); color: var(--accent-soft-text);
margin-bottom: 2px;
}
.theme-hero-title { font-size: var(--fs-16); font-weight: var(--fw-strong); color: var(--text); }
.theme-scheme-strip { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
.theme-scheme-chips { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
}
/* Host usability invariants locked with !important in earliest layer so themes
+18 -3
View File
@@ -115,14 +115,29 @@ export function Segmented<V extends string | number>({ options, value, onChange,
const measure = () => {
const el = box.current?.querySelector<HTMLElement>('[aria-checked="true"]')
setThumb(el ? { x: el.offsetLeft, w: el.offsetWidth } : null)
const next = el ? { x: el.offsetLeft, w: el.offsetWidth } : null
setThumb((prev) => {
if (!prev && !next) return prev
if (prev && next && prev.x === next.x && prev.w === next.w) return prev
return next
})
}
useLayoutEffect(measure, [value, options])
useEffect(() => {
if (!box.current || typeof ResizeObserver === 'undefined') return
const ro = new ResizeObserver(measure)
let raf = 0
const ro = new ResizeObserver(() => {
if (raf) cancelAnimationFrame(raf)
raf = requestAnimationFrame(() => {
raf = 0
measure()
})
})
ro.observe(box.current)
return () => ro.disconnect()
return () => {
if (raf) cancelAnimationFrame(raf)
ro.disconnect()
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
+17
View File
@@ -7,6 +7,7 @@
// Tier-3 interactive theme script without breaking the app's own calls (§5.1, B6).
import * as Go from '../wailsjs/go/app/App'
import {
EventsEmit as RawEventsEmit,
EventsOn as RawEventsOn,
OnFileDrop as RawOnFileDrop,
OnFileDropOff as RawOnFileDropOff,
@@ -121,6 +122,18 @@ function eventsOn<T>(eventName: string, cb: (data: T) => void): () => void {
return RawEventsOn(eventName, cb)
}
function eventsEmit(eventName: string, ...args: unknown[]): void {
try {
if (typeof capturedRuntime.EventsEmit === 'function') {
;(capturedRuntime.EventsEmit as (name: string, ...data: unknown[]) => void)(eventName, ...args)
return
}
;(RawEventsEmit as (name: string, ...data: unknown[]) => void)(eventName, ...args)
} catch {
// ignore if Wails runtime is unavailable (e.g. standalone preview)
}
}
export const api = {
...boundGo,
GetState: boundGo.GetState as () => Promise<AppState>,
@@ -144,4 +157,8 @@ export const events = {
// Tray menu (internal/app/app.go trayVMAction): "Show in Reims-Go" and "New VM…".
onTraySelectVM: (cb: (name: string) => void) => eventsOn('reims:tray-select-vm', cb),
onTrayNewVM: (cb: () => void) => eventsOn('reims:tray-new-vm', cb),
// Renderer health watchdog & crash reporting (internal/app/ui_health.go).
onUIPing: (cb: () => void) => eventsOn('reims:ui-ping', cb),
emitUIPong: () => eventsEmit('reims:ui-pong'),
emitUIError: (detail: string) => eventsEmit('reims:ui-error', detail),
}