feat(settings): rebuild VM settings as an interactive System Settings-style panel

- Merge 10 categories into 6 (General, CPU & Memory, Graphics & Displays,
  Storage & Network, Input & Audio, Advanced) with coloured nav icons
- New ui/settings.tsx primitives: row shell, switch, segmented control with
  sliding highlight, slider + number field with recommended/risky zones,
  option cards with screen-shape previews
- Host-aware CPU/memory recommendations (recommendedCPUs, memorySafeLimitGB)
- Rows explain why they are disabled (graphics while running, SSH without
  network, controller with installer attached, GPU under VMware SVGA)
- Per-row change marks and revert, per-category change counts, footer
  summary, Revert all, Ctrl+S; Save disabled with no changes
- Validation issues attach to their row and jump to its page; inline check
  for custom resolutions
- Fix duplicate resolution label/input

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
NwflowerandClaude Opus 5.5 committed 2026-11-28 09:53:05 -07:00
1 parent 8b6073b6b1
commit 9e4bc98c7d
7 files changed
+1156 -294

No files matched your search

+2 -2
View File
@@ -1,7 +1,7 @@
import { ChevronRight, CircleAlert, CircleCheck, Check, Copy } from 'lucide-react'
import React, { useEffect, useState } from 'react'
import { I18nKey, t } from '../i18n'
import { formatMemory, gpuLabel, recommendedDisplayPresets, recommendedMemoryGB, recommendedResolution, shortGPUName } from '../lib/format'
import { formatMemory, gpuLabel, recommendedCPUs, recommendedDisplayPresets, recommendedMemoryGB, recommendedResolution, shortGPUName } from '../lib/format'
import { CachedInstaller, CreateOpts, HostReport, Locale, Release, ValidationIssue } from '../types'
import { Button, IconButton } from '../ui/controls'
import { Modal } from '../ui/dialog'
@@ -52,7 +52,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, draft, onClose, on
macos: '',
offline: true,
installer: '',
cpus: host.logical_cpus >= 12 ? 8 : 4,
cpus: recommendedCPUs(host),
memory: `${recommendedMemoryGB(host)}G`,
disk_size: '128G',
disk: '',
+546 -283
View File
@@ -1,6 +1,16 @@
import React, { useState } from 'react'
import { CircleAlert, Cpu, HardDrive, Info, Keyboard, LucideIcon, Monitor, Wrench } from 'lucide-react'
import React, { useEffect, useMemo, useRef, useState } from 'react'
import { I18nKey, t } from '../i18n'
import { recommendedDisplayPresets, recommendedMemoryGB, shortGPUName } from '../lib/format'
import {
MEMORY_MARKS,
memorySafeLimitGB,
parseMemoryGB,
recommendedCPUs,
recommendedDisplayPresets,
recommendedMemoryGB,
shortGPUName,
sshCommand,
} from '../lib/format'
import {
applyKernelIrqchip,
findOptimization,
@@ -12,23 +22,90 @@ import {
import { HostReport, Locale, Optimization, SetOpts, ValidationIssue, VMDetail } from '../types'
import { Button } from '../ui/controls'
import { Modal } from '../ui/dialog'
import { NumberField, OptionCards, RangeField, ScreenArt, Segmented, SetGroup, SetRow, SetValue, Switch } from '../ui/settings'
import { backend } from '../wails'
type Cat = 'platform' | 'cpu' | 'memory' | 'storage' | 'network' | 'graphics' | 'audio' | 'input' | 'logs' | 'advanced'
// VM settings (docs/shell-design.md §4): edits are staged here and written in
// one `reims-ctl set` on Save, because upstream applies every change on the
// next start. Each row marks itself when it differs from the VM's current
// value and can be put back on its own.
const CATS: { id: Cat; label: I18nKey }[] = [
{ id: 'platform', label: 'catPlatform' },
{ id: 'cpu', label: 'catCPU' },
{ id: 'memory', label: 'catMemory' },
{ id: 'storage', label: 'catStorage' },
{ id: 'network', label: 'catNetwork' },
{ id: 'graphics', label: 'catGraphics' },
{ id: 'audio', label: 'catAudio' },
{ id: 'input', label: 'catInput' },
{ id: 'logs', label: 'catLogs' },
{ id: 'advanced', label: 'catAdvanced' },
type Cat = 'general' | 'compute' | 'display' | 'storage' | 'input' | 'advanced'
const CATS: { id: Cat; label: I18nKey; icon: LucideIcon }[] = [
{ id: 'general', label: 'catGeneral', icon: Info },
{ id: 'compute', label: 'catCompute', icon: Cpu },
{ id: 'display', label: 'catGraphics', icon: Monitor },
{ id: 'storage', label: 'catStorageNet', icon: HardDrive },
{ id: 'input', label: 'catInputAudio', icon: Keyboard },
{ id: 'advanced', label: 'catAdvanced', icon: Wrench },
]
type Field = Exclude<keyof SetOpts, 'name' | 'audio_backend'>
const FIELD_CAT: Record<Field, Cat> = {
cpus: 'compute',
memory: 'compute',
graphics: 'display',
gpu: 'display',
resolution: 'display',
displays: 'display',
borderless: 'display',
disk_controller: 'storage',
network: 'storage',
ssh_port: 'storage',
capture: 'input',
audio: 'input',
logs: 'advanced',
log_level: 'advanced',
stop_timeout: 'advanced',
extra_args: 'advanced',
}
const FIELDS = Object.keys(FIELD_CAT) as Field[]
const LOG_LEVELS = ['error', 'warn', 'info', 'debug', 'trace'] as const
const CUSTOM = '__custom'
const RES_RE = /^\s*\d{3,5}\s*[x×]\s*\d{3,5}\s*$/i
const normPath = (s: string | undefined) => (s ?? '').replace(/\//g, '\\').toLowerCase()
const normRes = (s: string | undefined) => (s ?? '').replace(/\s/g, '').replace(/×/g, 'x').toLowerCase()
/** Whether two values of a field mean the same thing to reims-ctl. */
function same(field: Field, a: SetOpts[Field], b: SetOpts[Field]): boolean {
switch (field) {
case 'memory': return parseMemoryGB(a as string) === parseMemoryGB(b as string)
case 'gpu': return normPath(a as string) === normPath(b as string)
case 'resolution': return normRes(a as string) === normRes(b as string)
case 'log_level':
case 'extra_args':
default: return a === b
}
}
function baseline(detail: VMDetail, host: HostReport): SetOpts {
// Match the stored ICD path to the host's spelling so the GPU card lights up.
const icd = (host.gpus ?? []).find((g) => normPath(g.vulkan_icd) === normPath(detail.gpu))?.vulkan_icd
return {
name: detail.name,
cpus: detail.cpus,
memory: detail.memory,
graphics: detail.graphics,
displays: detail.displays || 1,
disk_controller: detail.disk_controller,
resolution: detail.resolution,
borderless: detail.borderless,
capture: detail.capture,
gpu: icd ?? (detail.gpu || 'auto'),
logs: detail.logs,
log_level: detail.log_level,
audio: detail.audio,
network: detail.network,
ssh_port: detail.ssh_port,
stop_timeout: detail.stop_timeout,
extra_args: detail.extra_args,
}
}
interface Props {
locale: Locale
detail: VMDetail
@@ -42,62 +119,70 @@ interface Props {
export const SettingsModal: React.FC<Props> = ({ locale, detail, host, optimizations, running, onClose, onSaved }) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const irqOpt = findOptimization(optimizations, 'kernel_irqchip')
const [cat, setCat] = useState<Cat>('cpu')
const base = useMemo(() => baseline(detail, host), [detail, host])
const [cat, setCat] = useState<Cat>('compute')
const [busy, setBusy] = useState(false)
const [issues, setIssues] = useState<ValidationIssue[]>([])
const [err, setErr] = useState('')
const [form, setForm] = useState<SetOpts>(base)
const pane = useRef<HTMLDivElement>(null)
const [form, setForm] = useState<SetOpts>({
name: detail.name,
cpus: detail.cpus,
memory: detail.memory,
graphics: detail.graphics,
displays: detail.displays,
disk_controller: detail.disk_controller,
resolution: detail.resolution,
borderless: detail.borderless,
capture: detail.capture,
gpu: detail.gpu,
logs: detail.logs,
log_level: detail.log_level,
audio: detail.audio,
network: detail.network,
ssh_port: detail.ssh_port,
stop_timeout: detail.stop_timeout,
extra_args: detail.extra_args,
})
const set = (patch: Partial<SetOpts>) => setForm((f) => ({ ...f, ...patch }))
const presets = recommendedDisplayPresets(host)
const presetHit = presets.some((p) => same('resolution', p.resolution, form.resolution))
const [customRes, setCustomRes] = useState(!presetHit)
const [customLog, setCustomLog] = useState(!!form.log_level && !(LOG_LEVELS as readonly string[]).includes(form.log_level))
const buildDiff = (): SetOpts => {
const out: SetOpts = { name: detail.name }
if (form.cpus && form.cpus !== detail.cpus) out.cpus = form.cpus
if (form.memory && form.memory !== detail.memory) out.memory = form.memory
if (form.graphics && form.graphics !== detail.graphics) out.graphics = form.graphics
if (form.displays && form.displays !== detail.displays) out.displays = form.displays
if (form.disk_controller && form.disk_controller !== detail.disk_controller) out.disk_controller = form.disk_controller
if (form.resolution && form.resolution !== detail.resolution) out.resolution = form.resolution
if (form.borderless !== detail.borderless) out.borderless = form.borderless
if (form.capture !== detail.capture) out.capture = form.capture
if (form.gpu && form.gpu !== detail.gpu) out.gpu = form.gpu
if (form.logs !== detail.logs) out.logs = form.logs
if (form.log_level && form.log_level !== detail.log_level) out.log_level = form.log_level
if (form.audio !== detail.audio) out.audio = form.audio
if (form.network !== detail.network) out.network = form.network
if (form.ssh_port !== detail.ssh_port) out.ssh_port = form.ssh_port
if (form.stop_timeout !== detail.stop_timeout) out.stop_timeout = form.stop_timeout
if (form.extra_args !== detail.extra_args) out.extra_args = form.extra_args
return out
const set = (patch: Partial<SetOpts>) => {
setForm((f) => ({ ...f, ...patch }))
const touched = Object.keys(patch)
setIssues((list) => list.filter((i) => !touched.includes(i.field)))
}
const dirty = (f: Field) => !same(f, form[f], base[f])
const reset = (f: Field) => () => {
set({ [f]: base[f] } as Partial<SetOpts>)
if (f === 'resolution') setCustomRes(!presets.some((p) => same('resolution', p.resolution, base.resolution)))
if (f === 'log_level') setCustomLog(!!base.log_level && !(LOG_LEVELS as readonly string[]).includes(base.log_level))
}
const changed = FIELDS.filter(dirty)
const changedIn = (c: Cat) => changed.filter((f) => FIELD_CAT[f] === c).length
const issueOf = (f: Field) => issues.find((i) => i.field === f)?.message
const issueIn = (c: Cat) => issues.some((i) => FIELD_CAT[i.field as Field] === c) || (c === 'display' && resBad)
const strayIssues = issues.filter((i) => !(i.field in FIELD_CAT))
// Inline checks the backend would also reject, so the row says it first.
const resBad = customRes && !RES_RE.test(form.resolution ?? '')
const sshOn = (form.ssh_port ?? 0) > 0
const localBlock = resBad
const rowProps = (f: Field) => ({
field: f,
dirty: dirty(f),
onReset: reset(f),
resetLabel: tr('resetField'),
error: issueOf(f),
})
// Scroll the first row with an error into view after switching to its page.
useEffect(() => {
if (issues.length === 0) return
const el = pane.current?.querySelector<HTMLElement>('[data-error]')
el?.scrollIntoView({ block: 'nearest', behavior: 'smooth' })
}, [issues, cat])
const handleSave = async () => {
if (busy || changed.length === 0 || localBlock) return
setErr('')
setIssues([])
setBusy(true)
try {
const diff = buildDiff()
const diff: SetOpts = { name: detail.name }
for (const f of changed) (diff as unknown as Record<string, unknown>)[f] = form[f]
const iss = await backend.validateSet(diff)
if (iss && iss.length > 0) {
setIssues(iss)
const first = iss.map((i) => FIELD_CAT[i.field as Field]).find(Boolean)
if (first) setCat(first)
return
}
await backend.applyVMSettings(diff)
@@ -109,258 +194,436 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, host, optimizat
}
}
const resetAll = () => {
setForm(base)
setIssues([])
setCustomRes(!presets.some((p) => same('resolution', p.resolution, base.resolution)))
setCustomLog(!!base.log_level && !(LOG_LEVELS as readonly string[]).includes(base.log_level))
}
const onKeyDown = (e: React.KeyboardEvent) => {
if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 's') {
e.preventDefault()
void handleSave()
}
}
const realGPUs = (host.gpus ?? []).filter((g) => g.kind !== 'virtual')
const threads = Math.max(host.logical_cpus || 0, 1)
const cpuRec = recommendedCPUs(host)
const memRec = recommendedMemoryGB(host)
const memSafe = memorySafeLimitGB(host)
const memMax = Math.max(Math.floor((host.total_ram_gb || 16) * 0.85), memRec, 4)
const memGB = Math.round(parseMemoryGB(form.memory) ?? memRec)
const check = (key: 'network' | 'borderless' | 'audio' | 'capture' | 'logs', label: I18nKey) => (
<label className="choice">
<input type="checkbox" checked={!!form[key]} onChange={(e) => set({ [key]: e.target.checked })} />
{tr(label)}
</label>
// ── Pages ────────────────────────────────────────────────
const general = (
<>
<SetGroup note={tr('platformReadonly')}>
<SetValue title={tr('vmName')} value={detail.name} />
<SetValue title={tr('fieldKind')} value={detail.kind || '—'} />
<SetValue title={tr('fieldCPUModel')} value={detail.cpu_model || '—'} mono />
<SetValue title={tr('opencore')} value={detail.has_opencore ? tr('configured') : '—'} />
<SetValue title={tr('fieldDir')} value={detail.directory} mono />
</SetGroup>
</>
)
const presets = <T extends string | number>(values: T[], current: T | undefined, label: (v: T) => string, pick: (v: T) => void) => (
<div className="presets">
{values.map((v) => (
<button key={v} type="button" className="preset" aria-pressed={current === v} onClick={() => pick(v)}>
{label(v)}
</button>
))}
</div>
const cpuOver = (form.cpus ?? 0) > threads - 2 && threads > 2
const memOver = memGB > memSafe
const compute = (
<>
<SetGroup title={tr('factCPU')}>
<SetRow
{...rowProps('cpus')}
title={tr('vcpus')}
desc={cpuOver ? <span className="warn-text">{tr('cpuOverHint')}</span> : tr('cpuRecHint', { rec: cpuRec, n: threads })}
block={
<RangeField
label={tr('vcpus')}
value={form.cpus ?? cpuRec}
min={1}
max={threads}
unit={tr('coresUnit')}
onChange={(cpus) => set({ cpus })}
recommend={[Math.min(4, cpuRec), cpuRec]}
warnFrom={threads > 2 ? threads - 1 : undefined}
marks={[1, 2, 4, 6, 8, 12, 16, 24, 32, 48, 64].concat(threads).map((n) => ({ value: n, label: String(n) }))}
/>
}
/>
</SetGroup>
<SetGroup title={tr('factMemory')}>
<SetRow
{...rowProps('memory')}
title={tr('guestMemory')}
desc={memOver
? <span className="warn-text">{tr('memOverHint')}</span>
: host.commit_avail_gb > 0
? tr('memCommitHint', { avail: host.commit_avail_gb.toFixed(1), rec: memRec })
: tr('memRecHint', { rec: memRec, n: host.total_ram_gb.toFixed(0) })}
block={
<RangeField
label={tr('guestMemory')}
value={memGB}
min={2}
max={memMax}
unit="GB"
onChange={(gb) => set({ memory: `${gb}G` })}
recommend={[Math.min(4, memRec), memRec]}
warnFrom={memSafe + 1}
marks={MEMORY_MARKS.concat(memMax).map((n) => ({ value: n, label: String(n) }))}
/>
}
/>
</SetGroup>
</>
)
const gpuOptions = [
{
value: 'auto',
title: tr('gpuAutoTitle'),
sub: host.recommended_gpu ? tr('gpuAutoSub', { name: shortGPUName(host.recommended_gpu.name) }) : tr('gpuAutoOption'),
},
...realGPUs.map((g) => ({
value: g.vulkan_icd,
title: shortGPUName(g.name),
sub: g.kind === 'discrete' ? tr('gpuKindDiscrete') : g.kind === 'integrated' ? tr('gpuKindIntegrated') : undefined,
})),
]
if (form.gpu && form.gpu !== 'auto' && !gpuOptions.some((o) => normPath(o.value) === normPath(form.gpu))) {
gpuOptions.push({ value: form.gpu, title: form.gpu.split(/[\\/]/).pop() || form.gpu, sub: tr('gpuCustomIcd') })
}
const vgpu = form.graphics !== 'vmware-svga'
const resValue = customRes ? CUSTOM : presets.find((p) => same('resolution', p.resolution, form.resolution))?.resolution
const resArt = (r: string) => {
const m = /^(\d+)\s*[x×]\s*(\d+)$/i.exec(r)
return m ? <ScreenArt w={Number(m[1])} h={Number(m[2])} /> : <ScreenArt w={16} h={10} />
}
const display = (
<>
<SetGroup title={tr('groupGraphics')}>
<SetRow
{...rowProps('graphics')}
title={tr('graphicsBackend')}
desc={vgpu ? tr('graphicsReimsDesc') : tr('graphicsSvgaDesc')}
disabled={running}
reason={tr('graphicsRunningReason')}
control={
<Segmented
label={tr('graphicsBackend')}
value={form.graphics}
onChange={(graphics) => set({ graphics })}
options={[
{ value: 'reims-vgpu', label: tr('graphicsReimsShort') },
{ value: 'vmware-svga', label: tr('graphicsSvgaShort') },
]}
/>
}
/>
<SetRow
{...rowProps('gpu')}
title={tr('gpuSelect')}
desc={realGPUs.length === 0 ? <span className="warn-text">{tr('gpuUnavailableHint')}</span> : undefined}
disabled={!vgpu}
reason={tr('gpuSvgaReason')}
block={<OptionCards label={tr('gpuSelect')} value={gpuOptions.find((o) => normPath(o.value) === normPath(form.gpu))?.value} onChange={(gpu) => set({ gpu })} options={gpuOptions} />}
/>
</SetGroup>
<SetGroup title={tr('displayGroup')}>
<SetRow
{...rowProps('resolution')}
error={issueOf('resolution') ?? (resBad ? tr('resInvalid') : undefined)}
title={tr('resolution')}
desc={host.primary_display
? tr('hostDisplayHint', {
w: host.primary_display.width,
h: host.primary_display.height,
scale: host.primary_display.scale_pct || 100,
rec: host.recommended_resolution || '1920x1080',
})
: undefined}
block={
<>
<OptionCards
label={tr('resolution')}
value={resValue}
onChange={(v) => {
if (v === CUSTOM) { setCustomRes(true); return }
setCustomRes(false)
set({ resolution: v })
}}
options={[
...presets.map((p) => ({
value: p.resolution,
title: p.label,
art: resArt(p.resolution),
badges: [p.hidpi ? tr('hidpiPresetBadge') : '', p.recommended ? tr('recommendedBadge') : ''].filter(Boolean),
})),
{ value: CUSTOM, title: tr('resCustom'), sub: tr('resCustomSub'), art: <span className="screen-art custom" aria-hidden="true" /> },
]}
/>
{customRes && (
<input
className="input mono res-input"
aria-label={tr('resolution')}
placeholder="2560x1600"
autoFocus
value={form.resolution ?? ''}
onChange={(e) => set({ resolution: e.target.value })}
/>
)}
</>
}
/>
<SetRow
{...rowProps('displays')}
title={tr('displays')}
desc={(host.displays?.length ?? 0) > 1 ? tr('multiDisplayHint', { n: host.displays?.length ?? 1 }) : undefined}
control={
<Segmented
label={tr('displays')}
value={form.displays ?? 1}
onChange={(displays) => set({ displays })}
options={[1, 2, 3, 4].map((n) => ({ value: n, label: String(n) }))}
/>
}
/>
<SetRow
{...rowProps('borderless')}
title={tr('fullscreenLaunch')}
desc={tr('fullscreenLaunchHint')}
control={<Switch label={tr('fullscreenLaunch')} checked={!!form.borderless} onChange={(borderless) => set({ borderless })} />}
/>
</SetGroup>
</>
)
const storage = (
<>
<SetGroup title={tr('catStorage')}>
<SetValue title={tr('fieldDisk')} value={detail.disk} mono />
<SetRow
{...rowProps('disk_controller')}
title={tr('diskController')}
desc={detail.has_installer
? tr('diskControllerInstallHint')
: form.disk_controller === 'ahci' ? tr('diskControllerNvmeHint') : undefined}
disabled={detail.has_installer}
reason={tr('diskControllerWarn')}
control={
<Segmented
label={tr('diskController')}
value={form.disk_controller}
onChange={(disk_controller) => set({ disk_controller })}
options={[
{ value: 'ahci', label: 'SATA' },
{ value: 'nvme', label: 'NVMe' },
{ value: 'virtio', label: 'VirtIO' },
]}
/>
}
/>
</SetGroup>
<SetGroup title={tr('catNetwork')}>
<SetRow
{...rowProps('network')}
title={tr('enableNetwork')}
desc={tr('networkDesc')}
control={<Switch label={tr('enableNetwork')} checked={!!form.network} onChange={(network) => set({ network })} />}
/>
<SetRow
{...rowProps('ssh_port')}
title={tr('sshForward')}
desc={sshOn ? <code className="inline-code">{sshCommand(form.ssh_port ?? 0)}</code> : tr('sshOffDesc')}
disabled={!form.network}
reason={tr('sshNeedsNetwork')}
control={
<div className="hstack">
{sshOn && (
<NumberField label={tr('sshPort')} value={form.ssh_port ?? 0} min={1} max={65535} onChange={(ssh_port) => set({ ssh_port })} />
)}
<Switch
label={tr('sshForward')}
checked={sshOn}
onChange={(on) => set({ ssh_port: on ? (base.ssh_port || 2222) : 0 })}
/>
</div>
}
/>
</SetGroup>
</>
)
const input = (
<>
<SetGroup title={tr('catInput')} note={tr('macKeymapHint')}>
<SetRow
{...rowProps('capture')}
title={tr('captureInput')}
desc={tr('captureInputHint')}
control={<Switch label={tr('captureInput')} checked={!!form.capture} onChange={(capture) => set({ capture })} />}
/>
</SetGroup>
<SetGroup title={tr('catAudio')}>
<SetRow
{...rowProps('audio')}
title={tr('enableAudio')}
desc={tr('audioDesc')}
control={<Switch label={tr('enableAudio')} checked={!!form.audio} onChange={(audio) => set({ audio })} />}
/>
</SetGroup>
</>
)
const irqMode = parseKernelIrqchip(form.extra_args)
const advanced = (
<>
<SetGroup title={tr('catLogs')}>
<SetRow
{...rowProps('logs')}
title={tr('enableLogs')}
control={<Switch label={tr('enableLogs')} checked={!!form.logs} onChange={(logs) => set({ logs })} />}
/>
<SetRow
{...rowProps('log_level')}
title={tr('logLevel')}
block={
<div className="stack-2">
<Segmented
label={tr('logLevel')}
value={customLog ? CUSTOM : (form.log_level || 'info')}
onChange={(v) => {
if (v === CUSTOM) { setCustomLog(true); return }
setCustomLog(false)
set({ log_level: v })
}}
options={[...LOG_LEVELS.map((l) => ({ value: l as string, label: l })), { value: CUSTOM, label: tr('logLevelCustom') }]}
/>
{customLog && (
<input
className="input mono"
aria-label={tr('logLevel')}
placeholder="info,reims=debug"
value={form.log_level ?? ''}
onChange={(e) => set({ log_level: e.target.value })}
/>
)}
</div>
}
/>
</SetGroup>
<SetGroup title={tr('groupPerformance')}>
<SetRow
{...rowProps('extra_args')}
dirty={parseKernelIrqchip(form.extra_args) !== parseKernelIrqchip(base.extra_args)}
onReset={() => set({ extra_args: applyKernelIrqchip(form.extra_args, parseKernelIrqchip(base.extra_args)) })}
error={undefined}
field={undefined}
title={tr('kernelIrqchipLabel')}
desc={
<>
<span className={`badge ${optBadgeClass(irqOpt?.status)}`}>{optStatusLabel(locale, irqOpt?.status)}</span>
{' '}
<span className={irqOpt?.status === 'unavailable' && irqOpt.detail?.startsWith('0x') ? 'warn-text' : ''}>{kernelIrqchipHint(locale, irqOpt)}</span>
</>
}
control={
<Segmented
label={tr('kernelIrqchipLabel')}
value={irqMode}
onChange={(mode) => set({ extra_args: applyKernelIrqchip(form.extra_args, mode) })}
options={[
{ value: 'auto', label: tr('kernelIrqchipAuto') },
{ value: 'on', label: tr('kernelIrqchipOn'), disabled: !irqOpt?.supported },
{ value: 'off', label: tr('kernelIrqchipOff') },
]}
/>
}
/>
</SetGroup>
<SetGroup title={tr('groupQemu')}>
<SetRow
{...rowProps('stop_timeout')}
title={tr('stopTimeout')}
desc={tr('stopTimeoutHint')}
control={<NumberField label={tr('stopTimeout')} value={form.stop_timeout ?? 90} min={0} max={3600} onChange={(stop_timeout) => set({ stop_timeout })} />}
/>
<SetRow
{...rowProps('extra_args')}
title={tr('extraArgs')}
desc={tr('extraArgsDesc')}
block={<input className="input mono" aria-label={tr('extraArgs')} value={form.extra_args ?? ''} onChange={(e) => set({ extra_args: e.target.value })} />}
/>
</SetGroup>
</>
)
const pages: Record<Cat, React.ReactNode> = { general, compute, display, storage, input, advanced }
return (
<Modal
className="settings-dialog"
title={tr('settingsTitle', { name: detail.name })}
subtitle={tr(running ? 'appliesNextStart' : 'requiresStop')}
subtitle={`${tr(running ? 'state_running' : 'state_stopped')} · ${tr('appliesNextStart')}`}
closeLabel={tr('close')}
dismissable={!busy}
onClose={onClose}
>
<div className="settings-split">
<div className="settings-split" onKeyDown={onKeyDown}>
<nav className="settings-nav" aria-label={tr('settings')}>
{CATS.map((c) => (
<button
key={c.id}
type="button"
className="nav-item"
aria-selected={cat === c.id}
aria-current={cat === c.id ? 'page' : undefined}
onClick={() => setCat(c.id)}
>
<span className="nav-label">{tr(c.label)}</span>
</button>
))}
{CATS.map((c) => {
const n = changedIn(c.id)
const bad = issueIn(c.id)
const Icon = c.icon
return (
<button
key={c.id}
type="button"
className="nav-item"
aria-selected={cat === c.id}
aria-current={cat === c.id ? 'page' : undefined}
onClick={() => setCat(c.id)}
>
<span className={`nav-icon-badge nav-icon-cat-${c.id}`} aria-hidden="true"><Icon size={14} /></span>
<span className="nav-label">{tr(c.label)}</span>
{bad
? <CircleAlert size={14} className="nav-issue" aria-label={tr('navHasIssue')} />
: n > 0 && <span className="nav-count" aria-label={tr('pendingChanges', { n })}>{n}</span>}
</button>
)
})}
</nav>
<div className="settings-pane">
<div className="settings-pane" ref={pane}>
<h2 className="settings-pane-title">{tr(CATS.find((c) => c.id === cat)!.label)}</h2>
{err && <div className="notice notice-error">{err}</div>}
{issues.length > 0 && (
{strayIssues.length > 0 && (
<div className="notice notice-error">
<ul>{issues.map((i) => <li key={i.field + i.code}>{i.message}</li>)}</ul>
<ul>{strayIssues.map((i) => <li key={i.field + i.code}>{i.message}</li>)}</ul>
</div>
)}
{cat === 'platform' && (
<>
<span className="hint">{tr('platformReadonly')}</span>
<dl className="kv-list">
<dt>{tr('fieldKind')}</dt><dd>{detail.kind || '—'}</dd>
<dt>{tr('fieldCPUModel')}</dt><dd className="mono">{detail.cpu_model || '—'}</dd>
<dt>{tr('opencore')}</dt><dd>{detail.has_opencore ? tr('configured') : '—'}</dd>
<dt>{tr('fieldDir')}</dt><dd className="mono">{detail.directory}</dd>
</dl>
</>
)}
{cat === 'cpu' && (
<div className="field">
<label className="field-label" htmlFor="set-cpus">{tr('factCPU')} · {tr('hostThreads', { n: host.logical_cpus })}</label>
{presets([4, 6, 8, 12].filter((n) => n <= Math.max(host.logical_cpus, 4)), form.cpus, (n) => tr('cores', { n }), (cpus) => set({ cpus }))}
<input id="set-cpus" className="input" type="number" min={1} max={host.logical_cpus || 64} value={form.cpus ?? 8} onChange={(e) => set({ cpus: Number(e.target.value) })} />
<span className="hint">{tr('cpuHint')}</span>
</div>
)}
{cat === 'memory' && (
<div className="field">
<label className="field-label" htmlFor="set-mem">{tr('factMemory')} · {tr('hostMemory', { n: host.total_ram_gb.toFixed(0) })}</label>
{presets(['4G', '8G', '12G', '16G', '24G'], form.memory, (m) => m, (memory) => set({ memory }))}
<input id="set-mem" className="input" value={form.memory ?? ''} onChange={(e) => set({ memory: e.target.value })} />
<span className="hint">
{host.commit_avail_gb > 0
? tr('memCommitHint', { avail: host.commit_avail_gb.toFixed(1), rec: recommendedMemoryGB(host) })
: tr('memHint')}
</span>
</div>
)}
{cat === 'storage' && (
<>
<div className="field">
<label className="field-label" htmlFor="set-disk">{tr('fieldDisk')}</label>
<input id="set-disk" className="input mono" value={detail.disk} readOnly />
</div>
<div className="field">
<label className="field-label" htmlFor="set-ctl">{tr('diskController')}</label>
<select id="set-ctl" className="select" value={form.disk_controller} onChange={(e) => set({ disk_controller: e.target.value })}>
<option value="ahci">SATA</option>
<option value="nvme">NVMe</option>
<option value="virtio">VirtIO</option>
</select>
{detail.has_installer
? <span className="hint warn">{tr('diskControllerWarn')} · {tr('diskControllerInstallHint')}</span>
: form.disk_controller === 'ahci' && <span className="hint">{tr('diskControllerNvmeHint')}</span>}
</div>
</>
)}
{cat === 'network' && (
<>
{check('network', 'enableNetwork')}
<div className="field">
<label className="field-label" htmlFor="set-ssh">{tr('sshPort')}</label>
<input id="set-ssh" className="input" type="number" min={0} max={65535} value={form.ssh_port ?? 0} onChange={(e) => set({ ssh_port: Number(e.target.value) })} />
<span className="hint">{tr('sshPortHint')}</span>
</div>
</>
)}
{cat === 'graphics' && (
<>
<div className="field">
<label className="field-label" htmlFor="set-gfx">{tr('graphicsBackend')}</label>
<select id="set-gfx" className="select" value={form.graphics} onChange={(e) => set({ graphics: e.target.value })}>
<option value="reims-vgpu">{tr('graphicsReims')}</option>
<option value="vmware-svga">{tr('graphicsSvga')}</option>
</select>
</div>
<div className="field">
<label className="field-label" htmlFor="set-gpu">{tr('gpuSelect')}</label>
<select id="set-gpu" className="select" value={form.gpu} onChange={(e) => set({ gpu: e.target.value })}>
<option value="auto">{tr('gpuAutoOption')}</option>
{realGPUs.map((g) => <option key={g.vulkan_icd} value={g.vulkan_icd}>{shortGPUName(g.name)}</option>)}
</select>
{realGPUs.length === 0 && <span className="hint warn">{tr('gpuUnavailableHint')}</span>}
</div>
<div className="field">
<label className="field-label" htmlFor="set-res">{tr('resolution')}</label>
<div className="presets">
{recommendedDisplayPresets(host).map((p) => (
<button
key={p.resolution}
type="button"
className="preset"
aria-pressed={form.resolution === p.resolution}
onClick={() => set({ resolution: p.resolution })}
>
{p.label}
{p.hidpi && <span className="preset-tag">{tr('hidpiPresetBadge')}</span>}
{p.recommended && <span className="preset-tag">· {tr('recommendedBadge')}</span>}
</button>
))}
</div>
{host.primary_display && (
<span className="hint">
{tr('hostDisplayHint', {
w: host.primary_display.width,
h: host.primary_display.height,
scale: host.primary_display.scale_pct || 100,
rec: host.recommended_resolution || '1920x1080',
})}
</span>
)}
</div>
<div className="field-row">
<div className="field">
<label className="field-label" htmlFor="set-res">{tr('resolution')}</label>
<input id="set-res" className="input" value={form.resolution ?? ''} onChange={(e) => set({ resolution: e.target.value })} />
</div>
<div className="field">
<label className="field-label" htmlFor="set-displays">{tr('displays')}</label>
<input id="set-displays" className="input" type="number" min={1} max={4} value={form.displays ?? 1} onChange={(e) => set({ displays: Number(e.target.value) })} />
</div>
</div>
{(host.displays?.length ?? 0) > 1 && (
<span className="hint">{tr('multiDisplayHint', { n: host.displays?.length ?? 1 })}</span>
)}
{check('borderless', 'fullscreenLaunch')}
<span className="hint">{tr('fullscreenLaunchHint')}</span>
</>
)}
{cat === 'audio' && check('audio', 'enableAudio')}
{cat === 'input' && (
<>
{check('capture', 'captureInput')}
<span className="hint">{tr('captureInputHint')}</span>
<span className="hint">{tr('macKeymapHint')}</span>
</>
)}
{cat === 'logs' && (
<>
{check('logs', 'enableLogs')}
<div className="field">
<label className="field-label" htmlFor="set-loglevel">{tr('logLevel')}</label>
<input id="set-loglevel" className="input mono" value={form.log_level ?? ''} onChange={(e) => set({ log_level: e.target.value })} placeholder="info" />
</div>
</>
)}
{cat === 'advanced' && (
<>
<div className="field">
<label className="field-label">
{tr('kernelIrqchipLabel')}
{' '}
<span className={`badge ${optBadgeClass(irqOpt?.status)}`}>{optStatusLabel(locale, irqOpt?.status)}</span>
</label>
<div className="segmented" role="group" aria-label={tr('kernelIrqchipLabel')}>
<button
type="button"
aria-pressed={parseKernelIrqchip(form.extra_args) === 'auto'}
onClick={() => set({ extra_args: applyKernelIrqchip(form.extra_args, 'auto') })}
>
{tr('kernelIrqchipAuto')}
</button>
<button
type="button"
disabled={!irqOpt?.supported}
aria-pressed={parseKernelIrqchip(form.extra_args) === 'on'}
onClick={() => set({ extra_args: applyKernelIrqchip(form.extra_args, 'on') })}
>
{tr('kernelIrqchipOn')}
</button>
<button
type="button"
aria-pressed={parseKernelIrqchip(form.extra_args) === 'off'}
onClick={() => set({ extra_args: applyKernelIrqchip(form.extra_args, 'off') })}
>
{tr('kernelIrqchipOff')}
</button>
</div>
<span className={`hint ${irqOpt?.status === 'unavailable' && irqOpt.detail?.startsWith('0x') ? 'warn' : ''}`}>
{kernelIrqchipHint(locale, irqOpt)}
</span>
</div>
<div className="field">
<label className="field-label" htmlFor="set-timeout">{tr('stopTimeout')}</label>
<input id="set-timeout" className="input" type="number" min={0} value={form.stop_timeout ?? 90} onChange={(e) => set({ stop_timeout: Number(e.target.value) })} />
<span className="hint">{tr('stopTimeoutHint')}</span>
</div>
<div className="field">
<label className="field-label" htmlFor="set-extra">{tr('extraArgs')}</label>
<input id="set-extra" className="input mono" value={form.extra_args ?? ''} onChange={(e) => set({ extra_args: e.target.value })} />
</div>
</>
)}
{pages[cat]}
</div>
</div>
<div className="dialog-foot">
<span className="spacer" />
<Button variant="ghost" disabled={busy} onClick={onClose}>{tr('cancel')}</Button>
<Button variant="primary" busy={busy} onClick={handleSave}>{tr('save')}</Button>
<span className="foot-status" aria-live="polite">
{changed.length > 0
? <><span className="dirty-dot" aria-hidden="true" />{tr('pendingChanges', { n: changed.length })}</>
: <span className="muted">{tr('noChanges')}</span>}
{changed.length > 0 && (
<button type="button" className="link-btn" disabled={busy} onClick={resetAll}>{tr('resetAll')}</button>
)}
</span>
<span className="hstack">
<Button variant="ghost" disabled={busy} onClick={onClose}>{tr('cancel')}</Button>
<Button variant="primary" busy={busy} disabled={changed.length === 0 || localBlock} onClick={handleSave} title="Ctrl+S">
{tr('save')}
</Button>
</span>
</div>
</Modal>
)
+82
View File
@@ -358,6 +358,47 @@ const dict = {
catLogs: '串口与日志',
catAdvanced: '高级',
platformReadonly: '机型、序列号等平台身份信息不在界面显示',
catGeneral: '通用',
catCompute: '处理器与内存',
catStorageNet: '存储与网络',
catInputAudio: '输入与音频',
vcpus: '虚拟处理器',
coresUnit: '核',
cpuRecHint: '推荐 {rec} 核 · 宿主共 {n} 线程',
cpuOverHint: '只给宿主留下不到 2 个线程,宿主可能会卡顿',
guestMemory: '分配内存',
memRecHint: '推荐 {rec} GB · 宿主共 {n} GB',
memOverHint: '超过推荐值,Windows 可能分配不出这么多内存,启动会失败',
graphicsReimsShort: 'Reims vGPU',
graphicsSvgaShort: 'VMware SVGA',
graphicsReimsDesc: '硬件加速:macOS 的 Metal 经 Vulkan 在宿主显卡上执行,推荐',
graphicsSvgaDesc: '没有硬件加速,只用于排障',
graphicsRunningReason: '先关机才能切换(需要重建 OpenCore)',
gpuAutoTitle: '自动',
gpuAutoSub: '将使用 {name}',
gpuKindDiscrete: '独立显卡',
gpuKindIntegrated: '集成显卡',
gpuCustomIcd: '自定义 Vulkan ICD',
gpuSvgaReason: 'VMware SVGA 不使用宿主显卡',
groupGraphics: '图形',
displayGroup: '显示器',
resCustom: '自定义',
resCustomSub: '宽 × 高',
resInvalid: '格式为 宽x高,例如 2560x1600',
networkDesc: '通过 NAT 共享宿主的网络连接',
sshForward: 'SSH 端口转发',
sshOffDesc: '把宿主的一个端口转发到 macOS 的 22 端口',
sshNeedsNetwork: '需要先开启网络',
audioDesc: '把 macOS 的声音输出到宿主',
logLevelCustom: '自定义',
groupPerformance: '性能',
groupQemu: 'QEMU',
extraArgsDesc: '原样追加到 QEMU 命令行;上面的内核中断模式也写在这里',
navHasIssue: '这一页有需要修改的项',
pendingChanges: '{n} 项更改,下次启动生效',
noChanges: '没有更改',
resetAll: '全部还原',
resetField: '还原为当前值',
opencore: 'OpenCore',
configured: '已配置',
diskController: '磁盘控制器',
@@ -775,6 +816,47 @@ const dict = {
catLogs: 'Serial & logs',
catAdvanced: 'Advanced',
platformReadonly: 'Model, serial number and other platform identity are never shown',
catGeneral: 'General',
catCompute: 'CPU & Memory',
catStorageNet: 'Storage & Network',
catInputAudio: 'Input & Audio',
vcpus: 'Virtual CPUs',
coresUnit: 'cores',
cpuRecHint: '{rec} cores recommended · host has {n} threads',
cpuOverHint: 'Leaves the host fewer than 2 threads; Windows may stutter',
guestMemory: 'Memory',
memRecHint: '{rec} GB recommended · host has {n} GB',
memOverHint: 'Above the recommendation; Windows may not be able to allocate this much and the VM will fail to start',
graphicsReimsShort: 'Reims vGPU',
graphicsSvgaShort: 'VMware SVGA',
graphicsReimsDesc: 'Accelerated: macOS Metal runs on the host GPU through Vulkan. Recommended',
graphicsSvgaDesc: 'No acceleration; for troubleshooting only',
graphicsRunningReason: 'Shut down to switch (OpenCore must be rebuilt)',
gpuAutoTitle: 'Automatic',
gpuAutoSub: 'Will use {name}',
gpuKindDiscrete: 'Discrete',
gpuKindIntegrated: 'Integrated',
gpuCustomIcd: 'Custom Vulkan ICD',
gpuSvgaReason: 'VMware SVGA does not use the host GPU',
groupGraphics: 'Graphics',
displayGroup: 'Displays',
resCustom: 'Custom',
resCustomSub: 'Width × height',
resInvalid: 'Use WIDTHxHEIGHT, e.g. 2560x1600',
networkDesc: 'Shares the host connection through NAT',
sshForward: 'SSH port forwarding',
sshOffDesc: 'Forwards a host port to port 22 in macOS',
sshNeedsNetwork: 'Turn on the network first',
audioDesc: 'Plays macOS sound on the host',
logLevelCustom: 'Custom',
groupPerformance: 'Performance',
groupQemu: 'QEMU',
extraArgsDesc: 'Appended to the QEMU command line as is; the kernel irqchip mode above is stored here too',
navHasIssue: 'This page has settings to fix',
pendingChanges: '{n} changes, applied on next start',
noChanges: 'No changes',
resetAll: 'Revert all',
resetField: 'Revert to current value',
opencore: 'OpenCore',
configured: 'Configured',
diskController: 'Disk controller',
+30 -4
View File
@@ -17,13 +17,38 @@ export function recommendedMemoryGB(host: HostReport): number {
return MEMORY_CHOICES.reduce((best, m) => (m <= limit ? m : best), MEMORY_CHOICES[0])
}
/** "16G" / "16384M" / "16GiB" → "16 GB". Unknown shapes pass through. */
export function formatMemory(raw: string): string {
/** Memory sizes offered as quick picks, in GB. */
export const MEMORY_MARKS = MEMORY_CHOICES
/**
* Largest memory size in GB that still fits the same limits
* recommendedMemoryGB applies; above it the settings slider turns amber.
*/
export function memorySafeLimitGB(host: HostReport): number {
let limit = host.total_ram_gb * 0.6
if (host.commit_avail_gb > 0) limit = Math.min(limit, host.commit_avail_gb - 3)
return Math.max(Math.floor(limit), recommendedMemoryGB(host))
}
/** vCPU count suggested for a new VM; same rule as the create wizard. */
export function recommendedCPUs(host: HostReport): number {
const rec = host.logical_cpus >= 12 ? 8 : 4
return host.logical_cpus > 0 ? Math.min(rec, host.logical_cpus) : rec
}
/** "16G" / "16384M" / "16GiB" → 16. Null when the shape is unknown. */
export function parseMemoryGB(raw: string | undefined): number | null {
const m = /^\s*(\d+(?:\.\d+)?)\s*([KMGT])?(?:i?B)?\s*$/i.exec(raw ?? '')
if (!m) return raw
if (!m) return null
const n = Number(m[1])
const unit = (m[2] ?? 'M').toUpperCase()
const gb = unit === 'T' ? n * 1024 : unit === 'G' ? n : unit === 'M' ? n / 1024 : n / 1024 / 1024
return unit === 'T' ? n * 1024 : unit === 'G' ? n : unit === 'M' ? n / 1024 : n / 1024 / 1024
}
/** "16G" / "16384M" / "16GiB" → "16 GB". Unknown shapes pass through. */
export function formatMemory(raw: string): string {
const gb = parseMemoryGB(raw)
if (gb === null) return raw
const rounded = gb >= 10 ? Math.round(gb) : Math.round(gb * 10) / 10
return `${rounded} GB`
}
@@ -127,3 +152,4 @@ export function recommendedResolution(host: HostReport): string {
const rec = recommendedDisplayPresets(host).find((p) => p.recommended)
return rec?.resolution ?? '1920x1080'
}
+142 -3
View File
@@ -467,9 +467,148 @@ h1, h2, h3, p { margin: 0; }
.review-cmd-box { display: flex; align-items: flex-start; gap: var(--sp-2); }
.review-cmd-box .code { flex: 1; min-width: 0; }
.settings-split { display: flex; height: 460px; min-height: 0; }
.settings-nav { width: 186px; flex-shrink: 0; padding: 10px 8px; border-right: 1px solid var(--border); background: var(--surface-1); display: flex; flex-direction: column; gap: 3px; overflow-y: auto; }
.settings-pane { flex: 1; padding: 20px 24px; overflow-y: auto; display: flex; flex-direction: column; gap: var(--sp-4); }
/* ── VM settings (ui/settings.tsx) ─────────────────────── */
.dialog.settings-dialog { width: 900px; }
.settings-split { display: flex; height: min(600px, calc(100vh - 210px)); min-height: 0; }
.settings-nav { width: 204px; flex-shrink: 0; padding: 10px 8px; border-right: 1px solid var(--border); background: var(--surface-1); display: flex; flex-direction: column; gap: 3px; overflow-y: auto; }
.settings-pane { flex: 1; min-width: 0; padding: 18px 24px 28px; overflow-y: auto; display: flex; flex-direction: column; gap: 20px; }
.settings-pane-title { margin: 0; font-size: 18px; font-weight: var(--fw-strong); letter-spacing: -0.01em; color: var(--text); }
.nav-icon-cat-general { background: linear-gradient(145deg, #8e8e93 0%, #636366 100%); }
.nav-icon-cat-compute { background: linear-gradient(145deg, #7a78ff 0%, #5856d6 100%); }
.nav-icon-cat-display { background: linear-gradient(145deg, #32a0ff 0%, #007aff 100%); }
.nav-icon-cat-storage { background: linear-gradient(145deg, #34c759 0%, #248a3d 100%); }
.nav-icon-cat-input { background: linear-gradient(145deg, #ff6482 0%, #ff2d55 100%); }
.nav-icon-cat-advanced { background: linear-gradient(145deg, #aeaeb2 0%, #48484a 100%); }
.nav-count {
min-width: 18px; height: 18px; padding: 0 5px; flex-shrink: 0;
display: grid; place-items: center; border-radius: 999px;
background: var(--accent-soft); color: var(--accent-soft-text);
font-size: 11px; font-weight: var(--fw-strong); font-variant-numeric: tabular-nums;
}
.nav-item[aria-selected="true"] .nav-count { background: rgba(255, 255, 255, 0.25); color: var(--accent-text); }
.nav-issue { color: var(--status-error); flex-shrink: 0; }
.nav-item[aria-selected="true"] .nav-issue { color: var(--accent-text); }
.sgroup { display: flex; flex-direction: column; gap: var(--sp-2); }
.sgroup-title { margin: 0 0 0 4px; font-size: var(--fs-12); font-weight: var(--fw-strong); color: var(--text-3); }
.sgroup-list { background: var(--surface-1); border: 1px solid var(--border); border-radius: var(--r-lg); overflow: hidden; }
.sgroup-note { margin: 0 4px; font-size: var(--fs-12); color: var(--text-3); line-height: 1.5; }
.srow { position: relative; padding: 12px 16px; display: flex; flex-direction: column; gap: 10px; transition: background var(--dur-fast); }
.srow + .srow::before { content: ""; position: absolute; top: 0; left: 16px; right: 16px; height: 1px; background: var(--border); }
.srow[data-error] { background: var(--danger-soft); }
.srow-head { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-4); min-height: 28px; }
.srow-text { min-width: 0; display: flex; flex-direction: column; gap: 3px; }
.srow-title { display: flex; align-items: center; gap: 6px; font-size: 13.5px; color: var(--text); }
.srow-desc { font-size: var(--fs-12); color: var(--text-3); line-height: 1.5; }
.srow-reason { display: inline-flex; align-items: center; gap: 5px; font-size: var(--fs-12); color: var(--text-2); }
.srow-ctrl { display: flex; align-items: center; gap: var(--sp-2); flex-shrink: 0; }
.srow-fieldset { border: 0; padding: 0; margin: 0; min-width: 0; transition: opacity var(--dur-fast); }
.srow-fieldset:disabled { opacity: 0.42; }
.srow[data-disabled] .srow-title { color: var(--text-2); }
.srow-error { display: flex; align-items: flex-start; gap: 6px; font-size: var(--fs-12); color: var(--danger-text); }
.srow-error svg { flex-shrink: 0; margin-top: 2px; }
.srow-kv .srow-value { min-width: 0; text-align: right; font-size: var(--fs-13); color: var(--text-2); overflow-wrap: anywhere; user-select: text; }
.dirty-dot { width: 6px; height: 6px; border-radius: 50%; background: var(--accent); flex-shrink: 0; }
.warn-text { color: #b86e00; }
:root[data-theme="dark"] .warn-text { color: var(--status-busy); }
.inline-code { font-family: var(--font-mono); font-size: var(--fs-12); color: var(--text-code); background: var(--surface-active); padding: 1px 6px; border-radius: 4px; user-select: text; }
.stack-2 { display: flex; flex-direction: column; align-items: flex-start; gap: var(--sp-2); }
.stack-2 > .input { max-width: 320px; }
.res-input { margin-top: var(--sp-2); max-width: 220px; }
.foot-status { display: flex; align-items: center; gap: var(--sp-2); font-size: var(--fs-13); color: var(--text-2); }
.foot-status .link-btn { font-size: var(--fs-13); margin-left: var(--sp-1); }
.foot-status .link-btn:disabled { opacity: 0.5; cursor: default; text-decoration: none; }
/* Segmented control with a sliding highlight */
:root { --seg-thumb: #ffffff; }
:root[data-theme="dark"] { --seg-thumb: #5b5c63; }
.seg { position: relative; display: inline-flex; padding: 2px; gap: 2px; border-radius: var(--r-md); background: var(--surface-active); isolation: isolate; }
.seg-wide { display: flex; }
.seg-wide button { flex: 1; }
.seg-thumb {
position: absolute; top: 2px; bottom: 2px; left: 0; z-index: 0;
border-radius: var(--r-sm); background: var(--seg-thumb);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.12), 0 0 0 0.5px rgba(0, 0, 0, 0.06);
transition: transform var(--dur) cubic-bezier(0.3, 0.7, 0.2, 1), width var(--dur) cubic-bezier(0.3, 0.7, 0.2, 1);
}
.seg button {
position: relative; z-index: 1; height: 26px; padding: 0 12px;
border: none; border-radius: var(--r-sm); background: transparent;
color: var(--text-2); font: inherit; font-size: var(--fs-13); white-space: nowrap;
cursor: pointer; transition: color var(--dur-fast);
}
.seg button:hover:not(:disabled) { color: var(--text); }
.seg button[aria-checked="true"] { color: var(--text); font-weight: var(--fw-medium); }
.seg button:disabled { opacity: 0.4; cursor: not-allowed; }
/* Range field: slider + number */
.range-field { display: flex; flex-direction: column; }
.range-main { display: flex; align-items: flex-start; gap: var(--sp-4); }
.range-rail-wrap { position: relative; flex: 1; min-width: 0; height: 42px; }
.range-rail { position: absolute; left: 9px; right: 9px; top: 13px; height: 4px; pointer-events: none; }
.range-track { position: absolute; inset: 0; border-radius: 999px; background: var(--surface-active); }
/* Zones sit as a thin ruler under the track so the fill never hides them. */
.range-band { position: absolute; top: 8px; height: 3px; border-radius: 999px; }
.range-band.rec { background: rgba(40, 205, 65, 0.55); }
.range-band.warn { background: rgba(255, 159, 10, 0.55); }
.range-fill { position: absolute; left: 0; top: 0; bottom: 0; border-radius: 999px; background: var(--accent); transition: background var(--dur-fast); }
.range-field[data-warn] .range-fill { background: var(--status-busy); }
.range {
position: absolute; left: 0; top: 5px; width: 100%; height: 20px; margin: 0;
background: transparent; -webkit-appearance: none; appearance: none; cursor: pointer;
}
.range:focus-visible { box-shadow: none; }
.range::-webkit-slider-runnable-track { height: 20px; background: transparent; }
.range::-webkit-slider-thumb {
-webkit-appearance: none; width: 18px; height: 18px; margin-top: 1px; border-radius: 50%;
background: #ffffff; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3), 0 0 0 0.5px rgba(0, 0, 0, 0.14);
transition: transform var(--dur-fast), box-shadow var(--dur-fast);
}
.range:active::-webkit-slider-thumb { transform: scale(1.12); }
.range:focus-visible::-webkit-slider-thumb { box-shadow: var(--focus-ring), 0 1px 3px rgba(0, 0, 0, 0.3); }
.range-marks { position: absolute; left: 9px; right: 9px; top: 25px; height: 17px; }
.range-mark {
position: absolute; top: 0; transform: translateX(-50%); padding: 0 4px;
border: none; border-radius: 4px; background: transparent;
font: inherit; font-size: 11px; line-height: 17px; color: var(--text-3);
font-variant-numeric: tabular-nums; cursor: pointer;
}
.range-mark:hover { color: var(--text); background: var(--surface-hover); }
.range-mark[aria-pressed="true"] { color: var(--accent-soft-text); font-weight: var(--fw-strong); }
.num-field {
display: inline-flex; align-items: center; gap: 6px; height: 30px; padding: 0 10px; flex-shrink: 0;
border-radius: var(--r-md); border: 1px solid var(--border-strong); background: var(--surface-input);
transition: border-color var(--dur-fast), box-shadow var(--dur-fast);
}
.num-field:focus-within { border-color: var(--accent); box-shadow: var(--focus-ring); }
.num-input { min-width: 0; padding: 0; border: none; outline: none; background: transparent; color: var(--text); font: inherit; font-size: var(--fs-13); text-align: right; font-variant-numeric: tabular-nums; }
.num-input:focus-visible { box-shadow: none; }
.num-unit { font-size: var(--fs-12); color: var(--text-3); white-space: nowrap; }
/* Option cards */
.opt-cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(128px, 1fr)); gap: var(--sp-2); }
.opt-card {
position: relative; display: flex; flex-direction: column; align-items: flex-start; gap: 3px; min-width: 0;
padding: 10px 12px; border-radius: var(--r-md); border: 1px solid var(--border-strong);
background: var(--surface-card-elevated); cursor: pointer;
transition: border-color var(--dur-fast), background var(--dur-fast), box-shadow var(--dur-fast);
}
.opt-card:hover { background: var(--surface-hover); }
.opt-card[data-selected] { border-color: var(--accent); background: var(--accent-soft); box-shadow: inset 0 0 0 1px var(--accent); }
.opt-card[data-disabled] { opacity: 0.45; cursor: not-allowed; }
.opt-card input { position: absolute; opacity: 0; pointer-events: none; }
.opt-card:focus-within { box-shadow: var(--focus-ring); }
.opt-card[data-selected]:focus-within { box-shadow: inset 0 0 0 1px var(--accent), var(--focus-ring); }
.opt-card-title { max-width: 100%; font-size: var(--fs-13); font-weight: var(--fw-medium); color: var(--text); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.opt-card-sub { max-width: 100%; font-size: var(--fs-12); color: var(--text-3); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.opt-card-badges { display: flex; flex-wrap: wrap; gap: 4px; margin-top: 2px; }
.opt-card .badge { height: 18px; padding: 0 6px; font-size: 11px; }
.screen-art { display: block; margin-bottom: 6px; border-radius: 3px; border: 1.5px solid var(--text-3); background: linear-gradient(160deg, var(--accent-soft), transparent 70%); transition: border-color var(--dur-fast); }
.opt-card[data-selected] .screen-art { border-color: var(--accent); }
.screen-art.custom { width: 44px; height: 26px; border-style: dashed; background: none; }
.code { padding: 10px 12px; border-radius: var(--r-md); background: var(--surface-1); border: 1px solid var(--border); font-family: var(--font-mono); font-size: var(--fs-12); color: var(--text-code); word-break: break-all; user-select: text; }
.fieldset { border: 0; padding: 0; margin: 0; min-width: 0; }
+4 -2
View File
@@ -10,16 +10,18 @@ interface Props {
/** While false, Esc / outside click / ✕ are ignored (e.g. during a create). */
dismissable?: boolean
onClose: () => void
/** Extra class on the dialog box, e.g. a wider variant. */
className?: string
children: React.ReactNode
}
/** Modal frame: head with title and ✕; children supply body/steps/foot sections. */
export const Modal: React.FC<Props> = ({ title, subtitle, closeLabel, dismissable = true, onClose, children }) => (
export const Modal: React.FC<Props> = ({ title, subtitle, closeLabel, dismissable = true, onClose, className, children }) => (
<RDialog.Root open onOpenChange={(open) => { if (!open && dismissable) onClose() }}>
<RDialog.Portal>
<RDialog.Overlay className="overlay" />
<RDialog.Content
className="dialog"
className={className ? `dialog ${className}` : 'dialog'}
onInteractOutside={(e) => e.preventDefault()}
// Focus the first form field rather than ✕, so the close tooltip doesn't pop on open.
onOpenAutoFocus={(e) => {
+350
View File
@@ -0,0 +1,350 @@
import { CircleAlert, Lock, RotateCcw } from 'lucide-react'
import React, { useEffect, useId, useLayoutEffect, useRef, useState } from 'react'
import { IconButton } from './controls'
// Settings page primitives (docs/ui-redesign.md, docs/shell-design.md §4):
// one row shell — title and description on the left, the control on the
// right — plus the switch, segmented control, range field and option cards
// every category builds its rows from, so the whole panel reads as one set.
/** A labelled block of rows, like a grouped list in macOS System Settings. */
export const SetGroup: React.FC<{ title?: string; note?: React.ReactNode; children: React.ReactNode }> = ({ title, note, children }) => (
<section className="sgroup">
{title && <h3 className="sgroup-title">{title}</h3>}
<div className="sgroup-list">{children}</div>
{note && <p className="sgroup-note">{note}</p>}
</section>
)
interface RowProps {
title: string
desc?: React.ReactNode
/** Control drawn on the right of the title. */
control?: React.ReactNode
/** Control drawn under the title at full width (sliders, cards). */
block?: React.ReactNode
/** The value differs from what the VM has now. */
dirty?: boolean
onReset?: () => void
resetLabel?: string
/** The row can't act right now; `reason` says why. */
disabled?: boolean
reason?: string
error?: string
/** Anchor so a validation error can scroll its row into view. */
field?: string
}
/** One setting: title, one line of description, a control, and its state marks. */
export const SetRow: React.FC<RowProps> = ({ title, desc, control, block, dirty, onReset, resetLabel, disabled, reason, error, field }) => {
const titleId = useId()
return (
<div
className="srow"
data-field={field}
data-dirty={dirty || undefined}
data-disabled={disabled || undefined}
data-error={error ? true : undefined}
role="group"
aria-labelledby={titleId}
>
<div className="srow-head">
<div className="srow-text">
<div className="srow-title" id={titleId}>
{title}
{dirty && <span className="dirty-dot" aria-hidden="true" />}
</div>
{desc && <div className="srow-desc">{desc}</div>}
{disabled && reason && (
<div className="srow-reason"><Lock size={12} aria-hidden="true" />{reason}</div>
)}
</div>
{(control || (dirty && onReset)) && (
<div className="srow-ctrl">
{dirty && onReset && !disabled && (
<IconButton small label={resetLabel ?? 'Reset'} icon={<RotateCcw size={13} />} onClick={onReset} className="srow-reset" tipSide="top" />
)}
{control && <fieldset className="srow-fieldset" disabled={disabled}>{control}</fieldset>}
</div>
)}
</div>
{block && <fieldset className="srow-fieldset srow-block" disabled={disabled}>{block}</fieldset>}
{error && <div className="srow-error" role="alert"><CircleAlert size={13} aria-hidden="true" />{error}</div>}
</div>
)
}
/** Read-only row: a label and its value. */
export const SetValue: React.FC<{ title: string; value: React.ReactNode; mono?: boolean }> = ({ title, value, mono }) => (
<div className="srow srow-kv">
<div className="srow-head">
<div className="srow-title">{title}</div>
<div className={`srow-value${mono ? ' mono' : ''}`}>{value}</div>
</div>
</div>
)
export const Switch: React.FC<{ checked: boolean; onChange: (v: boolean) => void; label: string; disabled?: boolean }> = ({ checked, onChange, label, disabled }) => (
<label className="switch">
<input type="checkbox" role="switch" aria-label={label} checked={checked} disabled={disabled} onChange={(e) => onChange(e.target.checked)} />
<span className="slider" />
</label>
)
export interface SegOption<V> {
value: V
label: string
disabled?: boolean
}
/**
* Segmented control with a sliding highlight. A radio group under the hood:
* arrow keys move the choice, Tab leaves the group.
*/
export function Segmented<V extends string | number>({ options, value, onChange, label, wide }: {
options: SegOption<V>[]
value: V | undefined
onChange: (v: V) => void
label: string
/** Stretch to the row's width with equal segments. */
wide?: boolean
}) {
const box = useRef<HTMLDivElement>(null)
const [thumb, setThumb] = useState<{ x: number; w: number } | null>(null)
const measure = () => {
const el = box.current?.querySelector<HTMLElement>('[aria-checked="true"]')
setThumb(el ? { x: el.offsetLeft, w: el.offsetWidth } : null)
}
useLayoutEffect(measure, [value, options])
useEffect(() => {
if (!box.current || typeof ResizeObserver === 'undefined') return
const ro = new ResizeObserver(measure)
ro.observe(box.current)
return () => ro.disconnect()
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
const onKey = (e: React.KeyboardEvent) => {
if (e.key !== 'ArrowRight' && e.key !== 'ArrowLeft') return
e.preventDefault()
const enabled = options.filter((o) => !o.disabled)
const i = enabled.findIndex((o) => o.value === value)
const next = enabled[(i + (e.key === 'ArrowRight' ? 1 : -1) + enabled.length) % enabled.length]
if (next) {
onChange(next.value)
requestAnimationFrame(() => box.current?.querySelector<HTMLElement>('[aria-checked="true"]')?.focus())
}
}
const hasActive = options.some((o) => o.value === value)
return (
<div ref={box} className={`seg${wide ? ' seg-wide' : ''}`} role="radiogroup" aria-label={label} onKeyDown={onKey}>
{thumb && <span className="seg-thumb" style={{ transform: `translateX(${thumb.x}px)`, width: thumb.w }} aria-hidden="true" />}
{options.map((o, i) => {
const on = o.value === value
return (
<button
key={String(o.value)}
type="button"
role="radio"
aria-checked={on}
tabIndex={on || (!hasActive && i === 0) ? 0 : -1}
disabled={o.disabled}
onClick={() => onChange(o.value)}
>
{o.label}
</button>
)
})}
</div>
)
}
interface NumberProps {
value: number
min: number
max: number
step?: number
unit?: string
label: string
onChange: (v: number) => void
/** Width in characters; the default fits five digits. */
size?: number
}
/**
* Number field with a unit suffix and no spinner. It keeps what is typed so
* far and commits a whole, clamped number on Enter or blur; ↑/↓ step it.
*/
export const NumberField: React.FC<NumberProps> = ({ value, min, max, step = 1, unit, label, onChange, size = 5 }) => {
const [text, setText] = useState(String(value))
useEffect(() => { setText(String(value)) }, [value])
const clamp = (v: number) => Math.min(max, Math.max(min, Math.round(v / step) * step))
const commit = () => {
const n = Number.parseFloat(text)
if (!Number.isFinite(n)) { setText(String(value)); return }
const c = clamp(n)
setText(String(c))
if (c !== value) onChange(c)
}
return (
<div className="num-field">
<input
className="num-input"
type="text"
inputMode="numeric"
aria-label={label}
style={{ width: `${size + 1.5}ch` }}
value={text}
onChange={(e) => setText(e.target.value.replace(/[^\d.]/g, ''))}
onBlur={commit}
onKeyDown={(e) => {
if (e.key === 'Enter') { e.preventDefault(); commit() }
if (e.key === 'ArrowUp' || e.key === 'ArrowDown') {
e.preventDefault()
onChange(clamp(value + (e.key === 'ArrowUp' ? step : -step)))
}
}}
/>
{unit && <span className="num-unit">{unit}</span>}
</div>
)
}
/** Drop marks that would sit closer than `gap` percent to the one before. */
function thinMarks(marks: RangeMark[], min: number, max: number, gap = 9): RangeMark[] {
const span = Math.max(max - min, 1)
const out: RangeMark[] = []
let last = -Infinity
for (const m of marks) {
if (m.value < min || m.value > max) continue
const p = ((m.value - min) / span) * 100
if (p - last < gap) continue
out.push(m)
last = p
}
return out
}
export interface RangeMark {
value: number
label: string
}
interface RangeProps {
value: number
min: number
max: number
step?: number
unit: string
label: string
onChange: (v: number) => void
/** Clickable labels under the track. */
marks?: RangeMark[]
/** Highlighted "recommended" span of the track. */
recommend?: [number, number]
/** From here to the end the track turns amber. */
warnFrom?: number
}
/**
* Slider and number field bound to one value. The slider and the marks write
* straight away; the field commits on Enter or blur (NumberField).
*/
export const RangeField: React.FC<RangeProps> = ({ value, min, max, step = 1, unit, label, onChange, marks, recommend, warnFrom }) => {
const span = Math.max(max - min, 1)
const pct = (v: number) => `${((Math.min(max, Math.max(min, v)) - min) / span) * 100}%`
const shown = marks ? thinMarks(marks, min, max) : []
const over = warnFrom !== undefined && value >= warnFrom
return (
<div className="range-field" data-warn={over || undefined}>
<div className="range-main">
<div className="range-rail-wrap">
<div className="range-rail" aria-hidden="true">
<div className="range-track" />
{recommend && (
<div className="range-band rec" style={{ left: pct(recommend[0]), width: `calc(${pct(recommend[1])} - ${pct(recommend[0])})` }} />
)}
{warnFrom !== undefined && warnFrom <= max && (
<div className="range-band warn" style={{ left: pct(warnFrom), right: 0 }} />
)}
<div className="range-fill" style={{ width: pct(value) }} />
</div>
<input
className="range"
type="range"
aria-label={label}
min={min}
max={max}
step={step}
value={value}
onChange={(e) => onChange(Number(e.target.value))}
/>
{shown.length > 0 && (
<div className="range-marks">
{shown.map((m) => (
<button
key={m.value}
type="button"
tabIndex={-1}
className="range-mark"
aria-pressed={m.value === value}
style={{ left: pct(m.value) }}
onClick={() => onChange(m.value)}
>
{m.label}
</button>
))}
</div>
)}
</div>
<NumberField value={value} min={min} max={max} step={step} unit={unit} label={label} onChange={onChange} size={3} />
</div>
</div>
)
}
export interface CardOption<V> {
value: V
title: string
sub?: string
badges?: string[]
/** Small picture drawn above the title (e.g. a screen shape). */
art?: React.ReactNode
disabled?: boolean
}
/** A row of option cards, one picked: a radio group with larger targets. */
export function OptionCards<V extends string>({ options, value, onChange, label, columns }: {
options: CardOption<V>[]
value: V | undefined
onChange: (v: V) => void
label: string
columns?: number
}) {
const name = useId()
return (
<div className="opt-cards" role="radiogroup" aria-label={label} style={columns ? { gridTemplateColumns: `repeat(${columns}, minmax(0, 1fr))` } : undefined}>
{options.map((o) => (
<label key={o.value} className="opt-card" data-selected={o.value === value || undefined} data-disabled={o.disabled || undefined}>
<input type="radio" name={name} checked={o.value === value} disabled={o.disabled} onChange={() => onChange(o.value)} />
{o.art}
<span className="opt-card-title" title={o.title}>{o.title}</span>
{o.sub && <span className="opt-card-sub">{o.sub}</span>}
{o.badges && o.badges.length > 0 && (
<span className="opt-card-badges">{o.badges.map((b) => <span key={b} className="badge badge-accent">{b}</span>)}</span>
)}
</label>
))}
</div>
)
}
/** A screen outline with the resolution's aspect ratio. */
export const ScreenArt: React.FC<{ w: number; h: number }> = ({ w, h }) => {
const W = 44
const H = Math.max(18, Math.min(34, Math.round((W * h) / Math.max(w, 1))))
return <span className="screen-art" style={{ width: W, height: H }} aria-hidden="true" />
}