From 9e4bc98c7d84fbb9a0d9f9b97b362353dd41983c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=83=E5=B7=9D=E7=99=BD=E6=B5=AA?= <1679659@qq.com> Date: Sat, 28 Nov 2026 09:53:05 -0700 Subject: [PATCH] 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 --- frontend/src/components/CreateWizard.tsx | 4 +- frontend/src/components/SettingsModal.tsx | 829 ++++++++++++++-------- frontend/src/i18n.ts | 82 +++ frontend/src/lib/format.ts | 34 +- frontend/src/styles/app.css | 145 +++- frontend/src/ui/dialog.tsx | 6 +- frontend/src/ui/settings.tsx | 350 +++++++++ 7 files changed, 1156 insertions(+), 294 deletions(-) create mode 100644 frontend/src/ui/settings.tsx diff --git a/frontend/src/components/CreateWizard.tsx b/frontend/src/components/CreateWizard.tsx index e1b6485..9029835 100644 --- a/frontend/src/components/CreateWizard.tsx +++ b/frontend/src/components/CreateWizard.tsx @@ -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 = ({ 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: '', diff --git a/frontend/src/components/SettingsModal.tsx b/frontend/src/components/SettingsModal.tsx index 1ae77e5..70b7363 100644 --- a/frontend/src/components/SettingsModal.tsx +++ b/frontend/src/components/SettingsModal.tsx @@ -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 + +const FIELD_CAT: Record = { + 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 = ({ locale, detail, host, optimizations, running, onClose, onSaved }) => { const tr = (k: I18nKey, v?: Record) => t(locale, k, v) const irqOpt = findOptimization(optimizations, 'kernel_irqchip') - const [cat, setCat] = useState('cpu') + const base = useMemo(() => baseline(detail, host), [detail, host]) + + const [cat, setCat] = useState('compute') const [busy, setBusy] = useState(false) const [issues, setIssues] = useState([]) const [err, setErr] = useState('') + const [form, setForm] = useState(base) + const pane = useRef(null) - const [form, setForm] = useState({ - 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) => 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) => { + 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) + 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('[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)[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 = ({ 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) => ( - + // ── Pages ──────────────────────────────────────────────── + + const general = ( + <> + + + + + + + + ) - const presets = (values: T[], current: T | undefined, label: (v: T) => string, pick: (v: T) => void) => ( -
- {values.map((v) => ( - - ))} -
+ const cpuOver = (form.cpus ?? 0) > threads - 2 && threads > 2 + const memOver = memGB > memSafe + const compute = ( + <> + + {tr('cpuOverHint')} : tr('cpuRecHint', { rec: cpuRec, n: threads })} + block={ + 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) }))} + /> + } + /> + + + {tr('memOverHint')} + : 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={ + 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) }))} + /> + } + /> + + ) + 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 ? : + } + const display = ( + <> + + set({ graphics })} + options={[ + { value: 'reims-vgpu', label: tr('graphicsReimsShort') }, + { value: 'vmware-svga', label: tr('graphicsSvgaShort') }, + ]} + /> + } + /> + {tr('gpuUnavailableHint')} : undefined} + disabled={!vgpu} + reason={tr('gpuSvgaReason')} + block={ normPath(o.value) === normPath(form.gpu))?.value} onChange={(gpu) => set({ gpu })} options={gpuOptions} />} + /> + + + + { + 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: + + ) + + const storage = ( + <> + + + set({ disk_controller })} + options={[ + { value: 'ahci', label: 'SATA' }, + { value: 'nvme', label: 'NVMe' }, + { value: 'virtio', label: 'VirtIO' }, + ]} + /> + } + /> + + + set({ network })} />} + /> + {sshCommand(form.ssh_port ?? 0)} : tr('sshOffDesc')} + disabled={!form.network} + reason={tr('sshNeedsNetwork')} + control={ +
+ {sshOn && ( + set({ ssh_port })} /> + )} + set({ ssh_port: on ? (base.ssh_port || 2222) : 0 })} + /> +
+ } + /> +
+ + ) + + const input = ( + <> + + set({ capture })} />} + /> + + + set({ audio })} />} + /> + + + ) + + const irqMode = parseKernelIrqchip(form.extra_args) + const advanced = ( + <> + + set({ logs })} />} + /> + + { + 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 && ( + set({ log_level: e.target.value })} + /> + )} + + } + /> + + + set({ extra_args: applyKernelIrqchip(form.extra_args, parseKernelIrqchip(base.extra_args)) })} + error={undefined} + field={undefined} + title={tr('kernelIrqchipLabel')} + desc={ + <> + {optStatusLabel(locale, irqOpt?.status)} + {' '} + {kernelIrqchipHint(locale, irqOpt)} + + } + control={ + 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') }, + ]} + /> + } + /> + + + set({ stop_timeout })} />} + /> + set({ extra_args: e.target.value })} />} + /> + + + ) + + const pages: Record = { general, compute, display, storage, input, advanced } + return ( -
+
-
+
+

{tr(CATS.find((c) => c.id === cat)!.label)}

{err &&
{err}
} - {issues.length > 0 && ( + {strayIssues.length > 0 && (
-
    {issues.map((i) =>
  • {i.message}
  • )}
+
    {strayIssues.map((i) =>
  • {i.message}
  • )}
)} - - {cat === 'platform' && ( - <> - {tr('platformReadonly')} -
-
{tr('fieldKind')}
{detail.kind || '—'}
-
{tr('fieldCPUModel')}
{detail.cpu_model || '—'}
-
{tr('opencore')}
{detail.has_opencore ? tr('configured') : '—'}
-
{tr('fieldDir')}
{detail.directory}
-
- - )} - - {cat === 'cpu' && ( -
- - {presets([4, 6, 8, 12].filter((n) => n <= Math.max(host.logical_cpus, 4)), form.cpus, (n) => tr('cores', { n }), (cpus) => set({ cpus }))} - set({ cpus: Number(e.target.value) })} /> - {tr('cpuHint')} -
- )} - - {cat === 'memory' && ( -
- - {presets(['4G', '8G', '12G', '16G', '24G'], form.memory, (m) => m, (memory) => set({ memory }))} - set({ memory: e.target.value })} /> - - {host.commit_avail_gb > 0 - ? tr('memCommitHint', { avail: host.commit_avail_gb.toFixed(1), rec: recommendedMemoryGB(host) }) - : tr('memHint')} - -
- )} - - {cat === 'storage' && ( - <> -
- - -
-
- - - {detail.has_installer - ? {tr('diskControllerWarn')} · {tr('diskControllerInstallHint')} - : form.disk_controller === 'ahci' && {tr('diskControllerNvmeHint')}} -
- - )} - - {cat === 'network' && ( - <> - {check('network', 'enableNetwork')} -
- - set({ ssh_port: Number(e.target.value) })} /> - {tr('sshPortHint')} -
- - )} - - {cat === 'graphics' && ( - <> -
- - -
-
- - - {realGPUs.length === 0 && {tr('gpuUnavailableHint')}} -
-
- -
- {recommendedDisplayPresets(host).map((p) => ( - - ))} -
- {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', - })} - - )} -
-
-
- - set({ resolution: e.target.value })} /> -
-
- - set({ displays: Number(e.target.value) })} /> -
-
- {(host.displays?.length ?? 0) > 1 && ( - {tr('multiDisplayHint', { n: host.displays?.length ?? 1 })} - )} - {check('borderless', 'fullscreenLaunch')} - {tr('fullscreenLaunchHint')} - - )} - - {cat === 'audio' && check('audio', 'enableAudio')} - {cat === 'input' && ( - <> - {check('capture', 'captureInput')} - {tr('captureInputHint')} - {tr('macKeymapHint')} - - )} - - {cat === 'logs' && ( - <> - {check('logs', 'enableLogs')} -
- - set({ log_level: e.target.value })} placeholder="info" /> -
- - )} - - {cat === 'advanced' && ( - <> -
- -
- - - -
- - {kernelIrqchipHint(locale, irqOpt)} - -
-
- - set({ stop_timeout: Number(e.target.value) })} /> - {tr('stopTimeoutHint')} -
-
- - set({ extra_args: e.target.value })} /> -
- - )} + {pages[cat]}
- - - + + {changed.length > 0 + ? <> + + + +
) diff --git a/frontend/src/i18n.ts b/frontend/src/i18n.ts index bb31726..83bbb8e 100644 --- a/frontend/src/i18n.ts +++ b/frontend/src/i18n.ts @@ -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', diff --git a/frontend/src/lib/format.ts b/frontend/src/lib/format.ts index fbf45e0..eea2294 100644 --- a/frontend/src/lib/format.ts +++ b/frontend/src/lib/format.ts @@ -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' } + diff --git a/frontend/src/styles/app.css b/frontend/src/styles/app.css index 65efa1c..91cf268 100644 --- a/frontend/src/styles/app.css +++ b/frontend/src/styles/app.css @@ -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; } diff --git a/frontend/src/ui/dialog.tsx b/frontend/src/ui/dialog.tsx index f3aec4a..a2f40a8 100644 --- a/frontend/src/ui/dialog.tsx +++ b/frontend/src/ui/dialog.tsx @@ -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 = ({ title, subtitle, closeLabel, dismissable = true, onClose, children }) => ( +export const Modal: React.FC = ({ title, subtitle, closeLabel, dismissable = true, onClose, className, children }) => ( { if (!open && dismissable) onClose() }}> e.preventDefault()} // Focus the first form field rather than ✕, so the close tooltip doesn't pop on open. onOpenAutoFocus={(e) => { diff --git a/frontend/src/ui/settings.tsx b/frontend/src/ui/settings.tsx new file mode 100644 index 0000000..649b97f --- /dev/null +++ b/frontend/src/ui/settings.tsx @@ -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 }) => ( +
+ {title &&

{title}

} +
{children}
+ {note &&

{note}

} +
+) + +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 = ({ title, desc, control, block, dirty, onReset, resetLabel, disabled, reason, error, field }) => { + const titleId = useId() + return ( +
+
+
+
+ {title} + {dirty &&
+ {desc &&
{desc}
} + {disabled && reason && ( +
+ )} +
+ {(control || (dirty && onReset)) && ( +
+ {dirty && onReset && !disabled && ( + } onClick={onReset} className="srow-reset" tipSide="top" /> + )} + {control &&
{control}
} +
+ )} +
+ {block &&
{block}
} + {error &&
} +
+ ) +} + +/** Read-only row: a label and its value. */ +export const SetValue: React.FC<{ title: string; value: React.ReactNode; mono?: boolean }> = ({ title, value, mono }) => ( +
+
+
{title}
+
{value}
+
+
+) + +export const Switch: React.FC<{ checked: boolean; onChange: (v: boolean) => void; label: string; disabled?: boolean }> = ({ checked, onChange, label, disabled }) => ( + +) + +export interface SegOption { + 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({ options, value, onChange, label, wide }: { + options: SegOption[] + value: V | undefined + onChange: (v: V) => void + label: string + /** Stretch to the row's width with equal segments. */ + wide?: boolean +}) { + const box = useRef(null) + const [thumb, setThumb] = useState<{ x: number; w: number } | null>(null) + + const measure = () => { + const el = box.current?.querySelector('[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('[aria-checked="true"]')?.focus()) + } + } + + const hasActive = options.some((o) => o.value === value) + return ( +
+ {thumb &&
+ ) +} + +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 = ({ 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 ( +
+ 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 && {unit}} +
+ ) +} + +/** 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 = ({ 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 ( +
+
+
+