- Build single-source-of-truth 7-domain locale catalog (`locales/{zh-CN,en-US}/*.json`, 1,100+ keys) and `cmd/i18ngen` generator emitting Go catalogs and eager/lazy-split TypeScript domain modules (`core`/`vm` eager; `wizard`/`settings`/`plugins` lazy)
- Add zero-dependency ICU MessageFormat subset (`{var}`, `{n, number}`, CLDR `plural`, `select`), 8-hop cycle-free regional fallback (`zh-HK/zh-MO -> zh-Hant -> zh-TW -> zh-CN`), `auto` OS display-language preference, and `en-XA` pseudo-localization across Go and TypeScript
- Introduce `CodedError` supportability with `[E_CODE]` badges, collapsible `[detail]` diagnostics, and automatic SMC OSK / SMBIOS serial / MAC / token redaction
- Add Host × Guest macOS dual-terminology annotation (`FormatGuestTerm`) across 6 official Apple guest UI locales and localize Win32 system tray, file pickers, and DPI-adaptive `installguide` overlays with CJK font fallback probing
- Upgrade L1–L4 plugin localization to dual-track v2: Track A full language packs (`files`, WOFF2 `fonts`, cross-plugin `pluginOverrides`), Track B plugin-scoped `l10n` bundles (`HasUIMessages` isolation), live `plugin/localeChanged` notifications, `< 2ms` static CLI pack loading, and `reims-go plugin locale init|check` translator toolchain with `zh-TW` and `ja-JP` reference packs
- Harden security, WCAG 2.1 AA token contrast, `< 768px` responsive drawer & form layouts, and RTL logical properties; add backend security/locale regression tests and frontend `node --test` static/runtime guard suite in CI
# Conflicts:
# frontend/src/i18n.ts
# internal/cli/cli.go
# internal/i18n/i18n.go
335 lines
13 KiB
TypeScript
335 lines
13 KiB
TypeScript
import { I18nKey, t } from '../i18n'
|
||
import { formatLocaleNumber } from '../i18n/icu'
|
||
import { DisplayPreset, GPUInfo, HostReport, Locale, VMDetail } from '../types'
|
||
|
||
function currentDocLocale(): string {
|
||
if (typeof document === 'undefined') return 'en-US'
|
||
return document.documentElement.dataset.locale || document.documentElement.lang || 'en-US'
|
||
}
|
||
|
||
// Human-readable values for the main view (docs/design-guidelines.md §7.1).
|
||
// Raw values stay available under "Technical details".
|
||
|
||
const MEMORY_CHOICES = [4, 6, 8, 12, 16, 24, 32, 48, 64]
|
||
|
||
/**
|
||
* Largest offered memory size that fits in 60% of physical RAM and in the
|
||
* commit memory free now, minus 1 GB for QEMU and 2 GB for the host. Mirrors
|
||
* host.RecommendedMemoryGB (internal/host/memory.go).
|
||
*/
|
||
export function recommendedMemoryGB(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 MEMORY_CHOICES.reduce((best, m) => (m <= limit ? m : best), MEMORY_CHOICES[0])
|
||
}
|
||
|
||
/** 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 null
|
||
const n = Number(m[1])
|
||
const unit = (m[2] ?? 'M').toUpperCase()
|
||
return unit === 'T' ? n * 1024 : unit === 'G' ? n : unit === 'M' ? n / 1024 : n / 1024 / 1024
|
||
}
|
||
|
||
/** "16G" / "16384M" / "16GiB" → "16 GB" (or "16,5 GB" in comma-decimal locales). */
|
||
export function formatMemory(raw: string, locale?: Locale): string {
|
||
const gb = parseMemoryGB(raw)
|
||
if (gb === null) return raw
|
||
const rounded = gb >= 10 ? Math.round(gb) : Math.round(gb * 10) / 10
|
||
const loc = locale ?? currentDocLocale()
|
||
const precision = Number.isInteger(rounded) ? 0 : 1
|
||
return `${formatLocaleNumber(loc, rounded, precision)} GB`
|
||
}
|
||
|
||
export function controllerLabel(raw: string): string {
|
||
switch ((raw ?? '').toLowerCase()) {
|
||
case 'ahci': case 'sata': return 'SATA'
|
||
case 'nvme': return 'NVMe'
|
||
case 'virtio': return 'VirtIO'
|
||
default: return raw ? raw.toUpperCase() : '—'
|
||
}
|
||
}
|
||
|
||
const normPath = (s: string) => s.replace(/\//g, '\\').toLowerCase()
|
||
|
||
export function gpuKey(g: GPUInfo, idx = 0): string {
|
||
const pci = g.vendor_id && g.device_id ? `${g.vendor_id}:${g.device_id}` : ''
|
||
return `${pci}|${normPath(g.vulkan_icd || '')}|${g.name}|${idx}`
|
||
}
|
||
|
||
export function sameGPU(a?: GPUInfo, b?: GPUInfo): boolean {
|
||
if (!a || !b) return false
|
||
if (a.vendor_id && a.device_id && b.vendor_id && b.device_id) {
|
||
return a.vendor_id === b.vendor_id && a.device_id === b.device_id
|
||
}
|
||
return !!a.vulkan_icd && normPath(a.vulkan_icd) === normPath(b.vulkan_icd) && a.name === b.name
|
||
}
|
||
|
||
/** Stable `--gpu` value for a GPU: its ICD path when unique, else its name (for shared AMD ICDs). */
|
||
export function gpuOptionValue(g: GPUInfo, all: GPUInfo[]): string {
|
||
if (g.vulkan_icd) {
|
||
const target = normPath(g.vulkan_icd)
|
||
const shared = all.filter((o) => o.vulkan_icd && normPath(o.vulkan_icd) === target).length > 1
|
||
if (!shared) return g.vulkan_icd
|
||
}
|
||
return g.name
|
||
}
|
||
|
||
export function findGPU(host: HostReport, value: string | undefined): GPUInfo | undefined {
|
||
if (!value || value === 'auto') return host.recommended_gpu
|
||
const norm = normPath(value)
|
||
return (host.gpus ?? []).find(
|
||
(g) => (g.vulkan_icd && normPath(g.vulkan_icd) === norm) || g.name.toLowerCase() === value.toLowerCase(),
|
||
)
|
||
}
|
||
|
||
export function gpuMetaLine(g: GPUInfo): string {
|
||
const parts: string[] = []
|
||
if (g.vendor_id && g.device_id) parts.push(`${g.vendor_id}:${g.device_id}`)
|
||
if (g.vulkan_version) parts.push(`Vulkan ${g.vulkan_version}`)
|
||
if (g.driver_version) parts.push(g.driver_version)
|
||
return parts.join(' · ')
|
||
}
|
||
|
||
export function gpuCompatHint(locale: Locale, g?: GPUInfo): string {
|
||
if (!g) return ''
|
||
switch (g.compat_code) {
|
||
case 'amd_legacy_win_driver':
|
||
return t(locale, 'gpuWarnAmdLegacy', { ref: g.compat_detail || 'steelbrain/reims-vgpu#181' })
|
||
case 'amd_rdna2_device_lost':
|
||
return t(locale, 'gpuWarnAmdRdna2', { ref: g.compat_detail || 'steelbrain/reims-vgpu#173' })
|
||
case 'vulkan_too_old':
|
||
return t(locale, 'gpuErrVulkanTooOld', { ver: g.compat_detail || g.vulkan_version || '?' })
|
||
case 'vulkan_missing_extensions':
|
||
return t(locale, 'gpuErrMissingExt', { ext: g.compat_detail || '' })
|
||
case 'vulkan_cpu':
|
||
return t(locale, 'gpuErrVulkanCpu')
|
||
default:
|
||
return ''
|
||
}
|
||
}
|
||
|
||
/** Drop vendor boilerplate: "NVIDIA GeForce RTX 4070 Ti" → "RTX 4070 Ti". */
|
||
export function shortGPUName(name: string): string {
|
||
return name
|
||
.replace(/^NVIDIA\s+(GeForce\s+)?/i, '')
|
||
.replace(/^AMD\s+(Radeon\s+)?(?=RX|Pro)/i, 'Radeon ')
|
||
.replace(/^Intel\(R\)\s+/i, 'Intel ')
|
||
.trim()
|
||
}
|
||
|
||
/** "1920x1080" → "1080p"; non-16:9 sizes keep "W×H". */
|
||
export function resolutionLabel(raw: string): string {
|
||
const m = /^(\d+)\s*[x×]\s*(\d+)$/i.exec(raw ?? '')
|
||
if (!m) return raw
|
||
const w = Number(m[1]), h = Number(m[2])
|
||
return Math.abs(w / h - 16 / 9) < 0.01 ? `${h}p` : `${w}×${h}`
|
||
}
|
||
|
||
/** A `gpu` value ("auto" or a Vulkan ICD path) as the card's short name, e.g. "RTX 4070 Ti". */
|
||
export function gpuLabel(locale: Locale, icd: string | undefined, host: HostReport): string {
|
||
if (!icd || icd === 'auto') {
|
||
return host.recommended_gpu ? shortGPUName(host.recommended_gpu.name) : t(locale, 'gpuAuto')
|
||
}
|
||
const found = findGPU(host, icd)
|
||
return found ? shortGPUName(found.name) : t(locale, 'gpuAuto')
|
||
}
|
||
|
||
export function graphicsLabel(locale: Locale, d: VMDetail, host: HostReport): string {
|
||
if (d.graphics && d.graphics !== 'reims-vgpu') return t(locale, 'softwareGraphics')
|
||
const gpu = gpuLabel(locale, d.gpu, host)
|
||
const res = resolutionLabel(d.resolution)
|
||
const screens = d.displays > 1 ? `${d.displays} × ${res}` : res
|
||
return res ? `${gpu} · ${screens}` : gpu
|
||
}
|
||
|
||
export function sshCommand(port: number): string {
|
||
return `ssh -p ${port} 127.0.0.1`
|
||
}
|
||
|
||
export function formatBytes(bytes: number, locale?: Locale): string {
|
||
if (!bytes || bytes <= 0) return '0 B'
|
||
const units = ['B', 'KB', 'MB', 'GB', 'TB']
|
||
let v = bytes
|
||
let i = 0
|
||
while (v >= 1024 && i < units.length - 1) {
|
||
v /= 1024
|
||
i++
|
||
}
|
||
const digits = v >= 100 || i === 0 ? 0 : v >= 10 ? 1 : 2
|
||
const loc = locale ?? currentDocLocale()
|
||
return `${formatLocaleNumber(loc, v, digits)} ${units[i]}`
|
||
}
|
||
|
||
/** Compact "54 / 128 GB" when both are gigabytes, falling back to full units. */
|
||
export function formatDiskUsage(actual: number, virtual: number, locale?: Locale): string {
|
||
const GiB = 1024 ** 3
|
||
const loc = locale ?? currentDocLocale()
|
||
if (actual >= GiB && virtual >= GiB && virtual < 1024 * GiB) {
|
||
const a = actual / GiB
|
||
const v = virtual / GiB
|
||
const aStr = a >= 10 ? formatLocaleNumber(loc, Math.round(a), 0) : formatLocaleNumber(loc, a, 1)
|
||
const vStr = formatLocaleNumber(loc, Math.round(v), 0)
|
||
return `${aStr} / ${vStr} GB`
|
||
}
|
||
return `${formatBytes(actual, loc)} / ${formatBytes(virtual, loc)}`
|
||
}
|
||
|
||
export function formatUptime(sec: number, locale: Locale): string {
|
||
if (!sec || sec <= 0) return '—'
|
||
const h = Math.floor(sec / 3600)
|
||
const m = Math.floor((sec % 3600) / 60)
|
||
const s = sec % 60
|
||
if (h > 0) return t(locale, 'uptimeHoursMinutes', { h, m })
|
||
if (m > 0) return t(locale, 'uptimeMinutesSeconds', { m, s })
|
||
return t(locale, 'uptimeSeconds', { s })
|
||
}
|
||
|
||
// Used only when the host report has no presets: with nothing known about the
|
||
// screen, no size can be called HiDPI (internal/host/display.go).
|
||
const DEFAULT_DISPLAY_PRESETS: DisplayPreset[] = [
|
||
{ resolution: '1920x1080', label: '1920 × 1080', hidpi: false, recommended: true },
|
||
{ resolution: '2560x1440', label: '2560 × 1440', hidpi: false },
|
||
{ resolution: '2880x1800', label: '2880 × 1800', hidpi: false },
|
||
]
|
||
|
||
type Tr = (k: I18nKey, v?: Record<string, string | number>) => string
|
||
|
||
// The resolution row's description: the main display and its scaling.
|
||
export function hostDisplayDesc(host: HostReport, tr: Tr): string | undefined {
|
||
const d = host.primary_display
|
||
if (!d) return undefined
|
||
return tr('hostDisplayHint', { w: d.width, h: d.height, scale: d.scale_pct || 100 })
|
||
}
|
||
|
||
// How to get a HiDPI (sharp-text) macOS desktop when no window size gives
|
||
// one on this screen; undefined when one does.
|
||
export function hostDisplayAdvice(host: HostReport, tr: Tr): string | undefined {
|
||
const tip: Record<string, I18nKey> = {
|
||
fullscreen: 'hidpiTipFullscreen',
|
||
scale: 'hidpiTipScale',
|
||
unavailable: 'hidpiTipUnavailable',
|
||
}
|
||
const key = host.hidpi_advice ? tip[host.hidpi_advice] : undefined
|
||
return key ? tr(key) : undefined
|
||
}
|
||
|
||
// "Looks like" size of a HiDPI preset: macOS draws it at half each way.
|
||
export function hidpiLooksLike(resolution: string, tr: Tr): string | undefined {
|
||
const m = /^(\d+)\s*[x×]\s*(\d+)$/i.exec(resolution)
|
||
return m ? tr('resLooksLike', { w: Math.round(Number(m[1]) / 2), h: Math.round(Number(m[2]) / 2) }) : undefined
|
||
}
|
||
|
||
export function recommendedDisplayPresets(host: HostReport): DisplayPreset[] {
|
||
if (host.display_presets && host.display_presets.length > 0) {
|
||
return host.display_presets
|
||
}
|
||
return DEFAULT_DISPLAY_PRESETS
|
||
}
|
||
|
||
export function recommendedResolution(host: HostReport): string {
|
||
if (host.recommended_resolution) return host.recommended_resolution
|
||
const rec = recommendedDisplayPresets(host).find((p) => p.recommended)
|
||
return rec?.resolution ?? '1920x1080'
|
||
}
|
||
|
||
export interface GuestLangPreset {
|
||
value: string
|
||
labelKey: I18nKey
|
||
detailKey?: I18nKey
|
||
}
|
||
|
||
export const GUEST_LANG_PRESETS: GuestLangPreset[] = [
|
||
{ value: 'zh-Hans:0', labelKey: 'guestLangZhHansUS', detailKey: 'guestKbdUSRecommended' },
|
||
{ value: 'zh-Hans:252', labelKey: 'guestLangZhHansUS', detailKey: 'guestKbdPinyin' },
|
||
{ value: 'zh-Hant:0', labelKey: 'guestLangZhHantUS', detailKey: 'guestKbdUS' },
|
||
{ value: 'en-US:0', labelKey: 'guestLangEnUS' },
|
||
{ value: 'ja-JP:0', labelKey: 'guestLangJaJP', detailKey: 'guestKbdUS' },
|
||
{ value: 'ko-KR:0', labelKey: 'guestLangKoKR', detailKey: 'guestKbdUS' },
|
||
]
|
||
|
||
export function guestLangOptions(locale: Locale): Array<{ value: string; label: string; detail?: string }> {
|
||
return GUEST_LANG_PRESETS.map((p) => ({
|
||
value: p.value,
|
||
label: t(locale, p.labelKey),
|
||
detail: p.detailKey ? t(locale, p.detailKey) : undefined,
|
||
}))
|
||
}
|
||
|
||
export function defaultGuestLang(locale: Locale): string {
|
||
const l = locale.toLowerCase()
|
||
if (l === 'zh-tw' || l === 'zh-hk' || l === 'zh-mo' || l.startsWith('zh-hant')) return 'zh-Hant:0'
|
||
if (l.startsWith('zh')) return 'zh-Hans:0'
|
||
if (l.startsWith('ja')) return 'ja-JP:0'
|
||
if (l.startsWith('ko')) return 'ko-KR:0'
|
||
return 'en-US:0'
|
||
}
|
||
|
||
export function resolveGuestLang(locale: Locale, code: string | undefined): { label: string; detail?: string } {
|
||
const target = code || defaultGuestLang(locale)
|
||
const hit = GUEST_LANG_PRESETS.find((p) => p.value === target)
|
||
if (!hit) return { label: target }
|
||
const label = t(locale, hit.labelKey)
|
||
const detail = hit.detailKey ? t(locale, hit.detailKey) : undefined
|
||
return { label, detail }
|
||
}
|
||
|
||
export function guestLangLabel(locale: Locale, code: string | undefined): string {
|
||
const { label, detail } = resolveGuestLang(locale, code)
|
||
return detail ? `${label} (${detail})` : label
|
||
}
|
||
|
||
/**
|
||
* Split "简体中文(美式键盘,推荐)" / "Simplified Chinese (US Keyboard)" into a
|
||
* pop-up label and its grey detail, so the menu reads like macOS.
|
||
*/
|
||
export function splitLangLabel(value: string, text: string): { value: string; label: string; detail?: string } {
|
||
const m = /^(.*?)\s*[((](.*)[))]\s*$/.exec(text)
|
||
return m ? { value, label: m[1], detail: m[2] } : { value, label: text }
|
||
}
|
||
|
||
/**
|
||
* A change saved while the VM runs, as the user would say it:
|
||
* `memory 8G→16G` becomes "内存 8 GB → 16 GB". Field names come from
|
||
* PendingChange in internal/app/app.go.
|
||
*/
|
||
export function pendingChangeText(locale: Locale, p: { field: string; from: string; to: string }, host: HostReport): string {
|
||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||
const bool = (v: string) => tr(v === 'true' ? 'on' : 'off')
|
||
const lang = (v: string) => resolveGuestLang(locale, v).label
|
||
const fields: Record<string, { label: I18nKey; fmt: (v: string) => string }> = {
|
||
cpus: { label: 'factCPU', fmt: (v) => tr('cores', { n: v }) },
|
||
memory: { label: 'factMemory', fmt: (v) => formatMemory(v, locale) },
|
||
resolution: { label: 'resolution', fmt: resolutionLabel },
|
||
gpu: { label: 'factGraphics', fmt: (v) => gpuLabel(locale, v, host) },
|
||
displays: { label: 'displays', fmt: (v) => v },
|
||
borderless: { label: 'borderless', fmt: bool },
|
||
audio: { label: 'fieldAudio', fmt: bool },
|
||
audio_backend: { label: 'fieldAudio', fmt: (v) => v },
|
||
guest_lang: { label: 'specLang', fmt: lang },
|
||
}
|
||
const f = fields[p.field]
|
||
if (!f) return `${p.field} ${p.from} → ${p.to}`
|
||
return `${tr(f.label)} ${f.fmt(p.from)} → ${f.fmt(p.to)}`
|
||
}
|