Files
Reims-Go/frontend/src/components/LogPanel.tsx
T
Dnyo666 ceeec602be feat(i18n,plugin): implement end-to-end i18n & L10n v2 architecture and language pack protocol
- 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
2026-11-30 14:56:19 +08:00

359 lines
15 KiB
TypeScript

import { AlertTriangle, ArrowDown, ChevronDown, ChevronUp, Copy, Eraser, LoaderCircle, Pause, RefreshCw } from 'lucide-react'
import React, { useLayoutEffect, useMemo, useRef, useState } from 'react'
import { t } from '../i18n'
import { LogLine } from '../lib/logs'
import { taskDetail, taskTitle } from '../lib/tasks'
import { HostReport, Locale, Task } from '../types'
import { Button, IconButton, Tip } from '../ui/controls'
export type LogTab = 'app' | 'serial' | 'qemu'
interface Props {
locale: Locale
open: boolean
onToggle: () => void
tab: LogTab
onTab: (tab: LogTab) => void
lines: LogLine[]
unseenErrors: number
onClear: () => void
serialText: string
qemuText: string
showSerial: boolean
onRefreshSerial: () => void
onRefreshQemu: () => void
task: Task | null
runningTasks: number
onCancelTask: (id: string) => void
host?: HostReport
runningVMs?: number
onCopy?: (text: string) => void
/** False when WHPX or the runtime needs attention; the bar then leads with a link to the host page. */
hostReady?: boolean
onOpenHost?: () => void
}
/** Sticks to the bottom until the user scrolls up; offers "jump to latest" then. */
function useStickToBottom(dep: unknown, active: boolean) {
const ref = useRef<HTMLDivElement>(null)
const [stuck, setStuck] = useState(true)
useLayoutEffect(() => {
const el = ref.current
if (el && active && stuck) el.scrollTop = el.scrollHeight
}, [dep, active, stuck])
const onScroll = () => {
const el = ref.current
if (!el) return
setStuck(el.scrollHeight - el.scrollTop - el.clientHeight < 24)
}
const jump = () => {
const el = ref.current
if (el) el.scrollTop = el.scrollHeight
setStuck(true)
}
return { ref, stuck, onScroll, jump }
}
const LogRow = React.memo(({ line }: { line: LogLine }) => (
<div className={`log-line ${line.level}`}>
<span className="log-ts">{line.ts}</span>
<span className="log-src">{line.source}</span>
<span className="log-msg">{line.line}</span>
</div>
))
LogRow.displayName = 'LogRow'
const LOG_HEIGHT_KEY = 'reims-go-log-height'
const DEFAULT_LOG_HEIGHT = 240
const MIN_LOG_HEIGHT = 120
const MAX_LOG_HEIGHT = 520
export const LogPanel: React.FC<Props> = ({
locale, open, onToggle, tab, onTab, lines, unseenErrors, onClear, serialText, qemuText, showSerial, onRefreshSerial, onRefreshQemu,
task, runningTasks, onCancelTask, host, runningVMs = 0, onCopy, hostReady = true, onOpenHost,
}) => {
const tr = (k: Parameters<typeof t>[1], v?: Record<string, string | number>) => t(locale, k, v)
const [query, setQuery] = useState('')
const [errorsOnly, setErrorsOnly] = useState(false)
const q = query.trim().toLowerCase()
const filteredLines = useMemo(() => {
return lines.filter((l) => {
if (errorsOnly && l.level !== 'error' && l.level !== 'warn') return false
if (q && !l.line.toLowerCase().includes(q) && !l.source.toLowerCase().includes(q)) return false
return true
})
}, [lines, errorsOnly, q])
// Same element list while the lines are unchanged, so an App re-render for
// something else doesn't rebuild up to MAX_LOG_LINES rows; a new line renders
// just its own row (LogRow is memoised on the line object).
const rows = useMemo(() => filteredLines.map((l) => <LogRow key={l.id} line={l} />), [filteredLines])
const filteredText = useMemo(() => {
const raw = tab === 'serial' ? serialText : qemuText
if (!q || !raw) return raw
return raw.split('\n').filter((line) => line.toLowerCase().includes(q)).join('\n')
}, [tab, serialText, qemuText, q])
const copyVisible = () => {
if (!onCopy) return
if (tab === 'app') {
const txt = filteredLines.map((l) => `${l.ts} [${l.source}] ${l.line}`).join('\n')
if (txt) onCopy(txt)
} else if (filteredText) {
onCopy(filteredText)
}
}
const content = tab === 'app' ? filteredLines : filteredText
const { ref, stuck, onScroll, jump } = useStickToBottom(content, open)
const memPct = host
? Math.max(0, Math.min(100, host.memory_load_pct > 0
? host.memory_load_pct
: host.total_ram_gb > 0
? Math.round(((host.total_ram_gb - host.avail_ram_gb) / host.total_ram_gb) * 100)
: 0))
: 0
const usedMemGB = host && host.total_ram_gb > 0 ? Math.max(0, host.total_ram_gb - host.avail_ram_gb) : 0
const memTone = memPct >= 90 ? ' high' : memPct >= 80 ? ' warn' : ''
const lowDisk = !!host && host.free_disk_gb > 0 && host.free_disk_gb < 30
// "D:\Data\reims-go" → "D:": the drive VM disks and snapshots grow on.
const dataDrive = /^([A-Za-z]:)/.exec(host?.data_root ?? '')?.[1]?.toUpperCase() ?? ''
const [height, setHeight] = useState<number>(() => {
try {
const saved = Number(localStorage.getItem(LOG_HEIGHT_KEY))
if (Number.isFinite(saved) && saved >= MIN_LOG_HEIGHT && saved <= MAX_LOG_HEIGHT) return saved
} catch {}
return DEFAULT_LOG_HEIGHT
})
const [dragging, setDragging] = useState(false)
const dragRef = useRef<{ startY: number; startH: number } | null>(null)
const onResizeDown = (e: React.PointerEvent<HTMLDivElement>) => {
e.preventDefault()
e.currentTarget.setPointerCapture(e.pointerId)
dragRef.current = { startY: e.clientY, startH: height }
setDragging(true)
}
const onResizeMove = (e: React.PointerEvent<HTMLDivElement>) => {
if (!dragRef.current) return
const next = Math.min(MAX_LOG_HEIGHT, Math.max(MIN_LOG_HEIGHT, Math.round(dragRef.current.startH + (dragRef.current.startY - e.clientY))))
setHeight(next)
}
const onResizeUp = (e: React.PointerEvent<HTMLDivElement>) => {
if (!dragRef.current) return
dragRef.current = null
setDragging(false)
if (e.currentTarget.hasPointerCapture(e.pointerId)) e.currentTarget.releasePointerCapture(e.pointerId)
try { localStorage.setItem(LOG_HEIGHT_KEY, String(height)) } catch {}
}
return (
<div className="logs rg-p-logpanel">
{open && (
<div
className="log-resize-handle"
role="separator"
tabIndex={0}
aria-orientation="horizontal"
aria-label={tr('resizeLogPanel')}
aria-valuemin={MIN_LOG_HEIGHT}
aria-valuemax={MAX_LOG_HEIGHT}
aria-valuenow={height}
data-dragging={dragging}
onPointerDown={onResizeDown}
onPointerMove={onResizeMove}
onPointerUp={onResizeUp}
onPointerCancel={onResizeUp}
onKeyDown={(e) => {
if (e.key !== 'ArrowUp' && e.key !== 'ArrowDown') return
e.preventDefault()
const delta = e.key === 'ArrowUp' ? 24 : -24
const next = Math.min(MAX_LOG_HEIGHT, Math.max(MIN_LOG_HEIGHT, height + delta))
setHeight(next)
try { localStorage.setItem(LOG_HEIGHT_KEY, String(next)) } catch {}
}}
onDoubleClick={() => {
setHeight(DEFAULT_LOG_HEIGHT)
try { localStorage.setItem(LOG_HEIGHT_KEY, String(DEFAULT_LOG_HEIGHT)) } catch {}
}}
>
<span className="log-resize-pill" aria-hidden="true" />
</div>
)}
<div className="logbar rg-p-statusbar">
{task ? (
<>
<Tip label={[task.step, taskDetail(task)].filter(Boolean).join(' · ') || taskTitle(locale, task)} side="top">
<span className="task" tabIndex={0}>
<LoaderCircle size={14} className="spin" aria-hidden="true" />
<span className="task-label">
{runningTasks > 1 ? t(locale, 'tasksRunning', { n: runningTasks }) : taskTitle(locale, task)}
</span>
{task.percent >= 0 && (
<>
<span className="progress" aria-hidden="true">
<span className="progress-fill" style={{ transform: `scaleX(${Math.max(0, Math.min(1, task.percent / 100))})` }} />
</span>
<span className="task-pct">{Math.floor(task.percent)}%</span>
</>
)}
</span>
</Tip>
{task.cancelable && (
<IconButton small tipSide="top" label={tr('pauseDownload')} icon={<Pause size={14} />} onClick={() => onCancelTask(task.id)} />
)}
</>
) : host ? (
// Host at a glance: a problem first (only when there is one), then
// memory, the data drive and running VMs. "Label value" pairs with
// thin rules between them; exact figures live in the tooltips.
<div className="status-telemetry">
{!hostReady && onOpenHost && (
<Tip side="top" label={tr('footerHostIssueTip')}>
<button type="button" className="status-metric status-issue" onClick={onOpenHost}>
<AlertTriangle size={12} aria-hidden="true" />
<span>{tr('footerHostIssue')}</span>
</button>
</Tip>
)}
{host.total_ram_gb > 0 && (
<Tip
side="top"
label={tr('footerMemTip', {
used: usedMemGB.toFixed(1),
total: host.total_ram_gb.toFixed(1),
avail: host.avail_ram_gb.toFixed(1),
})}
>
<span className={`status-metric${memTone}`} tabIndex={0}>
<span className="status-label">{tr('footerMemLabel')}</span>
<span className="status-value">{tr('footerMemValue', { used: usedMemGB.toFixed(1), total: host.total_ram_gb.toFixed(0) })}</span>
<span className="status-mini-bar" aria-hidden="true">
<span className={`status-mini-fill${memTone}`} style={{ transform: `scaleX(${memPct / 100})` }} />
</span>
</span>
</Tip>
)}
{host.free_disk_gb > 0 && (
<Tip side="top" label={tr('footerDiskTip', { dir: host.data_root })}>
<span className={`status-metric${lowDisk ? ' warn' : ''}`} tabIndex={0}>
<span className="status-label">{dataDrive || tr('footerDiskLabel')}</span>
<span className="status-value">{tr('footerDiskValue', { gb: host.free_disk_gb.toFixed(0) })}</span>
</span>
</Tip>
)}
{runningVMs > 0 && (
<span className="status-metric ok">
<span className="status status-running" aria-hidden="true" />
<span className="status-value">{tr('footerRunningVMs', { n: runningVMs })}</span>
</span>
)}
</div>
) : null}
<span className="spacer" />
{open && (
<>
<input
type="search"
className="log-filter-input"
value={query}
placeholder={tr('logSearchPlaceholder')}
aria-label={tr('logSearchPlaceholder')}
spellCheck={false}
onChange={(e) => setQuery(e.target.value)}
/>
{tab === 'app' && (
<button
type="button"
className="log-filter-pill"
aria-pressed={errorsOnly}
onClick={() => setErrorsOnly((v) => !v)}
>
{tr('logErrorsOnly')}
</button>
)}
<div
className="tabs"
role="tablist"
onKeyDown={(e) => {
if (e.key !== 'ArrowRight' && e.key !== 'ArrowLeft') return
e.preventDefault()
const order: LogTab[] = showSerial ? ['app', 'serial', 'qemu'] : ['app']
const cur = Math.max(0, order.indexOf(tab))
const isRTL = getComputedStyle(e.currentTarget).direction === 'rtl'
const delta = (e.key === 'ArrowRight') !== isRTL ? 1 : -1
const next = order[(cur + delta + order.length) % order.length]
onTab(next)
const btns = e.currentTarget.querySelectorAll<HTMLButtonElement>('[role="tab"]')
btns[order.indexOf(next)]?.focus()
}}
>
<button type="button" role="tab" className="tab" tabIndex={tab === 'app' ? 0 : -1} aria-selected={tab === 'app'} onClick={() => onTab('app')}>
{tr('logActivity')}
</button>
{showSerial && (
<>
<button type="button" role="tab" className="tab" tabIndex={tab === 'serial' ? 0 : -1} aria-selected={tab === 'serial'} onClick={() => onTab('serial')}>
{tr('logSerial')}
</button>
<button type="button" role="tab" className="tab" tabIndex={tab === 'qemu' ? 0 : -1} aria-selected={tab === 'qemu'} onClick={() => onTab('qemu')}>
{tr('logQemu')}
</button>
</>
)}
</div>
</>
)}
{open && onCopy && (
<IconButton small tipSide="top" label={tr('logCopy')} icon={<Copy size={14} />} onClick={copyVisible} />
)}
{open && tab === 'app' && lines.length > 0 && (
<IconButton small tipSide="top" label={tr('clear')} icon={<Eraser size={14} />} onClick={onClear} />
)}
{open && tab === 'serial' && (
<IconButton small tipSide="top" label={tr('refresh')} icon={<RefreshCw size={14} />} onClick={onRefreshSerial} />
)}
{open && tab === 'qemu' && (
<IconButton small tipSide="top" label={tr('refresh')} icon={<RefreshCw size={14} />} onClick={onRefreshQemu} />
)}
<span className="rg-slot-inline" data-rg-slot="statusbar.right" />
{!open && unseenErrors > 0 && <span className="badge badge-error" aria-hidden="true">{unseenErrors}</span>}
<Tip label={open ? tr('collapseLogs') : tr('expandLogs')} shortcut="Ctrl+L" side="top">
<button
type="button"
className="log-toggle-btn"
onClick={onToggle}
aria-expanded={open}
aria-label={open ? tr('collapseLogs') : tr('expandLogs')}
>
<span>{tr('logButton')}</span>
{open ? <ChevronDown size={14} aria-hidden="true" /> : <ChevronUp size={14} aria-hidden="true" />}
</button>
</Tip>
</div>
{open && (
<div className="logs-body-wrap">
<div className="logs-body" style={{ height }} ref={ref} onScroll={onScroll} role="log" aria-live="off">
{tab === 'app'
? (filteredLines.length === 0
? <span className="muted">{tr('logsEmpty')}</span>
: rows)
: (filteredText || <span className="muted">{tr('logsEmpty')}</span>)}
</div>
{!stuck && (
<Button className="jump-latest" icon={<ArrowDown size={14} />} onClick={jump}>
{tr('jumpLatest')}
</Button>
)}
</div>
)}
</div>
)
}