Files
Reims-Go/frontend/src/components/Setup.tsx
T

335 lines
13 KiB
TypeScript

import { FolderOpen, HardDrive } from 'lucide-react'
import React, { useEffect, useState } from 'react'
import '../i18n/domains/wizard.gen'
import '../i18n/domains/settings.gen'
import { getLocaleOptions, I18nKey, joinNotices, locText, t } from '../i18n'
import { AppState, DataRootCheck, DataRootChoice, Locale, MarketCatalogItem, ResolvedLocalePack, Task } from '../types'
import { Button } from '../ui/controls'
import { PopupSelect } from '../ui/settings'
import { gpuCompatHint, recommendedMemoryGB, shortGPUName } from '../lib/format'
import { describeHostWHPX } from '../lib/hypervisor'
import { hasStambhaRuntime } from '../lib/endpoints'
import { api } from '../wails'
import { PluginAppIcon } from './PluginAppIcon'
import { RuntimeOnline } from './RuntimeOnline'
interface Props {
locale: Locale
locales?: ResolvedLocalePack[]
state: AppState
stage: 'folder' | 'runtime'
runtimeTask: Task | null
onLocale: (l: Locale) => void
/** A plugin was installed or enabled; the app reloads plugin contributions. */
onPluginsChanged: () => void
onFolderDone: () => void
onFinish: () => void
onError: (title: string, e: unknown) => void
onChannel: (alpha: boolean) => void
onInstallRuntime: (commit: string) => void
onCancelTask: (id: string) => void
onImportRuntime: () => void
}
const LOW_SPACE_GB = 60
/** First launch: choose the data folder, then (optionally) install the runtime. */
export const Setup: React.FC<Props> = (p) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(p.locale, k, v)
return (
<div className="setup">
<div className="setup-card">
{p.stage === 'folder' ? <FolderStep {...p} tr={tr} /> : <RuntimeStep {...p} tr={tr} />}
</div>
</div>
)
}
type StepProps = Props & { tr: (k: I18nKey, v?: Record<string, string | number>) => string }
const FolderStep: React.FC<StepProps> = ({ locale, locales, state, tr, onLocale, onPluginsChanged, onFolderDone, onError }) => {
const [choices, setChoices] = useState<DataRootChoice[]>([])
const [custom, setCustom] = useState('')
const [customMode, setCustomMode] = useState(false)
const [selected, setSelected] = useState('')
const [check, setCheck] = useState<DataRootCheck | null>(null)
const [busy, setBusy] = useState(false)
// A market language pack for the OS language, looked up once on first launch.
const [langPack, setLangPack] = useState<MarketCatalogItem | null>(null)
const [langPackOn, setLangPackOn] = useState(true)
useEffect(() => {
api.SuggestDataRoots().then((list) => {
const l = list ?? []
setChoices(l)
const rec = l.find((c) => c.recommended) ?? l[0]
if (rec) setSelected(rec.path)
}).catch((e) => onError(tr('failGeneric'), e))
api.SuggestLanguagePack().then((p) => { if (p?.entry) setLangPack(p) }).catch((e) => console.warn('[setup] SuggestLanguagePack failed:', e))
}, [])
useEffect(() => {
if (!selected) { setCheck(null); return }
let live = true
api.CheckDataRoot(selected)
.then((c) => { if (live) setCheck(c) })
.catch((e) => {
if (live) setCheck(null)
console.warn('[setup] CheckDataRoot failed:', e)
})
return () => { live = false }
}, [selected])
const browse = async () => {
try {
const dir = await api.PickDirectory(tr('setupTitle'))
if (dir) { setCustom(dir); setCustomMode(true); setSelected(dir) }
} catch (e) {
console.warn('[setup] PickDirectory failed:', e)
onError(tr('failGeneric'), e)
}
}
const next = async () => {
setBusy(true)
try {
await api.CompleteSetup(selected)
} catch (e) {
onError(tr('failGeneric'), e)
setBusy(false)
return
}
// Plugins live in the data folder, so the pack installs once it exists.
// With the language left on "auto", enabling the pack is enough for the
// UI to switch to the OS language.
if (langPack && langPackOn) {
try {
const info = await api.InstallMarketPlugin(langPack.entry.id, false)
if (info && !info.enabled && !info.needs_approval) await api.EnablePlugin(info.id, false)
onPluginsChanged()
} catch (e) {
onError(tr('setupLangPackFailed'), e)
}
}
setBusy(false)
onFolderDone()
}
const osTag = state.detected_locale || locale
const option = (path: string, meta: React.ReactNode) => (
<label key={path} className="choice-card" data-selected={selected === path}>
<input type="radio" name="data-root" checked={selected === path} onChange={() => setSelected(path)} />
<HardDrive size={18} aria-hidden="true" />
<span className="choice-card-main">
<span className="mono choice-card-path">{path}</span>
<span className="choice-card-meta">{meta}</span>
</span>
</label>
)
const notices: string[] = []
if (check?.error) notices.push(check.error)
else if (check) {
if (check.system) notices.push(tr('setupWarnSystem'))
if (check.external) notices.push(tr('setupWarnExternal'))
if (check.free_gb > 0 && check.free_gb < LOW_SPACE_GB) notices.push(tr('setupWarnSpace'))
}
return (
<>
<div className="setup-head">
<h1>{tr('setupTitle')}</h1>
<p>{tr('setupDesc')}</p>
</div>
<div className="choices-list" role="radiogroup" aria-label={tr('setupTitle')}>
{choices.map((c) => option(c.path, (
<>
{tr('setupFree', { n: c.free_gb.toFixed(0) })}
{c.recommended && <span className="badge rg-p-badge badge-accent">{tr('setupRecommended')}</span>}
{c.system && <span className="badge rg-p-badge">{tr('setupSystem')}</span>}
{c.external && <span className="badge rg-p-badge badge-warn">{tr('setupExternal')}</span>}
</>
)))}
{customMode ? (
<div className="input-group">
<input
className="input rg-p-input mono"
aria-label={tr('setupOther')}
value={custom}
placeholder="D:\VMs\reims-go"
spellCheck={false}
autoComplete="off"
autoFocus
onFocus={() => custom && setSelected(custom)}
onChange={(e) => { setCustom(e.target.value); setSelected(e.target.value.trim()) }}
/>
<Button icon={<FolderOpen size={14} />} onClick={browse}>{tr('choose')}</Button>
</div>
) : (
<Button variant="ghost" icon={<FolderOpen size={14} />} onClick={() => setCustomMode(true)} className="choice-other">{tr('setupOther')}</Button>
)}
</div>
{notices.length > 0 && (
<div className={check?.error ? 'notice notice-error' : 'hint warn'}>{joinNotices(locale, notices)}</div>
)}
{!check?.error && check?.has_config && <div className="hint">{tr('setupReuse')}</div>}
{customMode && check && check.path === custom && !check.error && (
<div className="hint">{tr('setupFree', { n: check.free_gb.toFixed(0) })}</div>
)}
{langPack && (
<label className="setup-langpack">
<input type="checkbox" checked={langPackOn} disabled={busy} onChange={(e) => setLangPackOn(e.target.checked)} />
<PluginAppIcon kind="locale" size="sm" />
<span className="setup-langpack-main">
{/* The pack's name and blurb in the OS language: that is who it is for. */}
<span className="setup-langpack-title">
{tr('setupLangPackOffer', { name: locText(langPack.entry.name, osTag, langPack.entry.id) })}
</span>
{locText(langPack.entry.description, osTag) && (
<span className="setup-langpack-sub">{locText(langPack.entry.description, osTag)}</span>
)}
</span>
</label>
)}
<div className="setup-foot">
<PopupSelect
label={tr('language')}
value={state.config.locale || 'auto'}
onChange={onLocale}
options={getLocaleOptions(locales, locale, state.detected_locale)}
/>
<Button variant="primary" busy={busy} disabled={!selected || !!check?.error} onClick={next}>{tr('setupContinue')}</Button>
</div>
</>
)
}
const RuntimeStep: React.FC<StepProps> = ({ locale, tr, state, runtimeTask, onChannel, onInstallRuntime, onCancelTask, onImportRuntime, onFolderDone, onFinish, onError }) => {
const ready = !!state.active_runtime || hasStambhaRuntime(state.runtimes)
const { host } = state
const [enabling, setEnabling] = useState(false)
const [activating, setActivating] = useState('')
const activate = async (commit: string) => {
setActivating(commit)
try {
await api.UseRuntime(commit)
onFolderDone()
} catch (e) {
onError(tr('runtimeActivationFailed'), e)
} finally {
setActivating('')
}
}
const enableWHPX = async () => {
setEnabling(true)
try {
const changed = await api.SetHypervisorBoot(true)
if (changed) onFolderDone()
} catch (e) {
onError(tr('failGeneric'), e)
} finally {
setEnabling(false)
}
}
const whpx = describeHostWHPX(locale, host)
const whpxOK = whpx.tone === 'ok'
const gpu = host.recommended_gpu ?? (host.gpus ?? []).find((g) => g.kind !== 'virtual')
const gpuHint = gpuCompatHint(locale, gpu)
const gpuOK = !host.vulkan_probe_error && !!gpu && gpu.compat !== 'warn' && gpu.compat !== 'unsupported'
const recMem = recommendedMemoryGB(host)
return (
<>
<div className="setup-head">
<h1>{tr('setupRuntimeTitle')}</h1>
<p>{tr('setupRuntimeDesc')}</p>
</div>
<section className="section">
<div className="section-title">{tr('setupCheck')}</div>
<div className="list">
<div className="row">
<div className="row-main">
<div className="row-title">{tr('hostWHPX')}</div>
{whpx.hint && (
<div className="row-sub">{whpx.hint}</div>
)}
</div>
<div className="row-right">
{whpx.canEnable ? (
<Button variant="primary" busy={enabling} onClick={enableWHPX}>{tr('enableWHPX')}</Button>
) : (
<span className={`badge rg-p-badge ${whpxOK ? 'badge-ok' : 'badge-warn'}`}>
{whpx.short}
</span>
)}
</div>
</div>
<div className="row">
<div className="row-main">
<div className="row-title">{tr('setupGPU')}</div>
{gpu && <div className="row-sub">{shortGPUName(gpu.name)}</div>}
{host.vulkan_probe_error ? (
<div className="row-sub warn-text">{tr('vulkanProbeFailed', { detail: host.vulkan_probe_error })}</div>
) : !gpu && <div className="row-sub">{tr('setupNoGPU')}</div>}
{gpuHint && <div className="row-sub warn-text">{gpuHint}</div>}
</div>
<div className="row-right">
<span className={`badge rg-p-badge ${gpuOK ? 'badge-ok' : 'badge-warn'}`}>
{tr(
gpuOK
? 'whpxReady'
: gpu?.compat === 'unsupported'
? 'gpuCompatUnsupported'
: gpu?.compat === 'warn'
? 'gpuCompatWarn'
: 'hostNeedsAction',
)}
</span>
</div>
</div>
<div className="row">
<div className="row-main">
<div className="row-title">{tr('hostRAM')}</div>
<div className="row-sub">
{host.commit_avail_gb > 0
? tr('memCommitHint', { avail: host.commit_avail_gb.toFixed(1), rec: recMem })
: tr('hostRAMTotal', { n: host.total_ram_gb.toFixed(1) })}
</div>
</div>
<div className="row-right">
<span className={`badge rg-p-badge ${recMem >= 8 ? 'badge-ok' : 'badge-warn'}`}>{tr('setupRecMem', { n: recMem })}</span>
</div>
</div>
</div>
</section>
<div className="list">
<RuntimeOnline
locale={locale}
channel={state.config.runtime_channel === 'alpha' ? 'alpha' : 'stable'}
installed={state.runtimes ?? []}
task={runtimeTask}
onChannel={onChannel}
onInstall={onInstallRuntime}
onCancel={onCancelTask}
/>
{(state.runtimes ?? []).filter((rt) => !rt.active).map((rt) => (
<div className="row" key={rt.commit}>
<div className="row-main"><div className="row-title mono">{rt.commit}</div></div>
<div className="row-right">
<Button busy={activating === rt.commit} disabled={!!activating} onClick={() => activate(rt.commit)}>
{tr('activate')}
</Button>
</div>
</div>
))}
</div>
<div className="setup-foot">
<Button variant="ghost" onClick={onImportRuntime}>{tr('setupImport')}</Button>
<Button variant={ready ? 'primary' : 'secondary'} disabled={runtimeTask?.status === 'running'} onClick={onFinish}>
{tr(ready ? 'setupDone' : 'setupLater')}
</Button>
</div>
</>
)
}