241 lines
18 KiB
TypeScript
241 lines
18 KiB
TypeScript
import axios from 'axios'
|
||
import { Plus, RefreshCw, RotateCcw, Save, Trash2 } from 'lucide-react'
|
||
import { useEffect, useRef, useState, type FormEvent, type ReactNode } from 'react'
|
||
import Scrollbar from '../../components/Scrollbar/Scrollbar'
|
||
import { useLocale } from '../../i18n/locale'
|
||
import { Button } from '../components/ui/button'
|
||
import { ConfirmDialog } from '../components/ui/dialog'
|
||
import { Input } from '../components/ui/input'
|
||
import { Select } from '../components/ui/select'
|
||
import { Panel } from '../patterns/patterns'
|
||
import {
|
||
notifyComputeConfigurationChanged, reportIsUsed,
|
||
type ComputeConfiguration, type ComputeConfigurationResponse, type ComputeObservation,
|
||
} from './compute-comparison-model'
|
||
import './compute-comparison.css'
|
||
|
||
const ENDPOINT = `${import.meta.env.VITE_API_URL || '/api/v1'}/data-products/compute/configuration`
|
||
type View = 'observations' | 'sources' | 'innovation'
|
||
|
||
function Field({ title, children }: { title: string; children: ReactNode }) {
|
||
return <label className="an-compute-field"><span>{title}</span>{children}</label>
|
||
}
|
||
|
||
function validationMessage(message: string, english: boolean) {
|
||
const normalized = message.replace(/^Value error, /, '')
|
||
if (english) return normalized
|
||
const translations: Record<string, string> = {
|
||
'Global shares for one year must total at most 100 percent': '同年各国全球算力占比之和不能超过 100%。',
|
||
'Each metric/year may have only one observation': '同一指标、同一年只能保留一条年度观测。',
|
||
'Report source IDs must be unique': '报告来源不能重复。',
|
||
'Innovation observation years must be unique': '创新指数分差的年份不能重复。',
|
||
'Observation year must not be after its report year': '观测年份不能晚于所选报告的年份。',
|
||
'Review date must not be in the future': '核验日期不能晚于今天。',
|
||
'Use countries from the canonical compute catalog, not regional totals': '请使用国家观测,不能直接录入区域合计。',
|
||
'Use a report URL without credentials (maximum 2000 characters)': '报告链接不能包含账号密码,长度不能超过 2000 字符。',
|
||
}
|
||
if (normalized.startsWith('Missing report source:')) return '请为观测选择有效的报告来源。'
|
||
return translations[normalized] || '字段内容无效,请检查必填项、数值范围和报告链接。'
|
||
}
|
||
|
||
function requestError(error: unknown, english: boolean) {
|
||
if (!axios.isAxiosError(error)) return english ? 'Request failed.' : '请求失败。'
|
||
if (error.response?.status === 409) return english
|
||
? 'Someone updated this configuration. Your draft is preserved. Reload and reconcile before saving.'
|
||
: '配置已被其他人更新。当前草稿已保留,请核对后重新加载再保存。'
|
||
const detail: unknown = error.response?.data?.detail
|
||
if (Array.isArray(detail)) return detail.map((item: { loc?: Array<string | number>; msg?: string }) => {
|
||
const section = item.loc?.find(value => ['sources', 'observations', 'innovation'].includes(String(value)))
|
||
const index = item.loc?.find(value => typeof value === 'number')
|
||
const labels: Record<string, string> = { sources: '报告来源', observations: '年度观测', innovation: '创新指数分差' }
|
||
const location = section ? english ? String(section) : labels[String(section)] : ''
|
||
const row = typeof index === 'number' ? english ? ` #${index + 1}` : ` 第 ${index + 1} 条` : ''
|
||
return `${location}${row}${location ? ':' : ''}${validationMessage(item.msg || '', english)}`
|
||
}).join(';')
|
||
if (error.response?.status === 403) return english ? 'Administrator access required.' : '仅管理员可以维护算力对比数据。'
|
||
return typeof detail === 'string' ? detail : error.message
|
||
}
|
||
|
||
export function ComputeComparisonSettings({ active }: { active: boolean }) {
|
||
const { locale } = useLocale()
|
||
const english = locale === 'en-US'
|
||
const t = (zh: string, en: string) => english ? en : zh
|
||
const [saved, setSaved] = useState<ComputeConfigurationResponse | null>(null)
|
||
const [draft, setDraft] = useState<ComputeConfiguration | null>(null)
|
||
const [view, setView] = useState<View>('observations')
|
||
const [busy, setBusy] = useState(false)
|
||
const [error, setError] = useState('')
|
||
const [message, setMessage] = useState('')
|
||
const [confirmation, setConfirmation] = useState<'reset' | 'reload' | null>(null)
|
||
const [loadRevision, setLoadRevision] = useState(0)
|
||
const viewportRef = useRef<HTMLDivElement>(null)
|
||
const dirty = Boolean(draft && saved && JSON.stringify(draft) !== JSON.stringify(saved.config))
|
||
|
||
useEffect(() => {
|
||
viewportRef.current?.scrollTo({ top: 0 })
|
||
}, [view])
|
||
|
||
useEffect(() => {
|
||
if (!active || saved) return
|
||
const controller = new AbortController()
|
||
setBusy(true)
|
||
axios.get<ComputeConfigurationResponse>(ENDPOINT, { signal: controller.signal })
|
||
.then(({ data }) => { setSaved(data); setDraft(data.config); setError('') })
|
||
.catch(failure => { if (!controller.signal.aborted) setError(requestError(failure, english)) })
|
||
.finally(() => { if (!controller.signal.aborted) setBusy(false) })
|
||
return () => controller.abort()
|
||
}, [active, saved, loadRevision, english])
|
||
|
||
useEffect(() => {
|
||
if (!dirty) return
|
||
const preventLoss = (event: BeforeUnloadEvent) => { event.preventDefault(); event.returnValue = '' }
|
||
window.addEventListener('beforeunload', preventLoss)
|
||
return () => window.removeEventListener('beforeunload', preventLoss)
|
||
}, [dirty])
|
||
|
||
const edit = (next: ComputeConfiguration) => { setDraft(next); setMessage(''); setError('') }
|
||
const reload = () => { setSaved(null); setLoadRevision(value => value + 1); setMessage('') }
|
||
const metricLabel = (metric: string) => metric === 'global_share'
|
||
? t('全球算力占比 (%)', 'Global compute share (%)')
|
||
: t('计算设备总规模 · FP32 (EFlop/s)', 'Total compute · FP32 (EFlop/s)')
|
||
|
||
async function publish(reset = false) {
|
||
if (!saved || !draft) return
|
||
setBusy(true); setError(''); setMessage('')
|
||
try {
|
||
const { data } = reset
|
||
? await axios.post<ComputeConfigurationResponse>(`${ENDPOINT}/reset`, { revision: saved.revision })
|
||
: await axios.put<ComputeConfigurationResponse>(ENDPOINT, { revision: saved.revision, config: draft })
|
||
setSaved(data); setDraft(data.config); setConfirmation(null)
|
||
setMessage(t('已发布,地球卡片将自动更新。', 'Published. Earth cards will refresh automatically.'))
|
||
notifyComputeConfigurationChanged()
|
||
} catch (failure) { setError(requestError(failure, english)); setConfirmation(null) }
|
||
finally { setBusy(false) }
|
||
}
|
||
|
||
function save(event: FormEvent) { event.preventDefault(); void publish() }
|
||
if (!active && !saved) return null
|
||
const sources = draft?.sources.map(source => ({ value: source.id, label: source.title || source.id })) || []
|
||
const sourceSelect = (value: string, onChange: (value: string) => void) => (
|
||
<Field title={t('报告来源', 'Report source')}><Select value={value} onValueChange={onChange}
|
||
options={sources} placeholder={t('选择报告', 'Select a report')} /></Field>
|
||
)
|
||
const removeButton = (label: string, onClick: () => void, disabled = false) => (
|
||
<Button type="button" size="icon" variant="subtle" title={label} aria-label={label}
|
||
disabled={disabled || busy} onClick={onClick}><Trash2 size={15} /></Button>
|
||
)
|
||
const updateObservation = (index: number, row: ComputeObservation) => {
|
||
if (draft) edit({ ...draft, observations: draft.observations.map((item, i) => i === index ? row : item) })
|
||
}
|
||
|
||
return (
|
||
<Panel className="an-compute-settings" hidden={!active}>
|
||
<form className="an-compute-form" onSubmit={save} onInvalidCapture={event => {
|
||
const details = (event.target as HTMLElement).closest('details')
|
||
if (details) details.open = true
|
||
}}>
|
||
<div className="an-panel-heading an-compute-heading">
|
||
<div><h2>{t('算力对比数据', 'Compute comparison data')}</h2>
|
||
<p>{t('同年、同口径的国家观测;未录入的数值保持缺失。', 'Comparable country observations by year. Omitted values stay unavailable.')}</p></div>
|
||
<div className="an-compute-actions">
|
||
<Button type="button" size="icon" variant="subtle" title={t('重新加载', 'Reload')} aria-label={t('重新加载', 'Reload')} disabled={busy} onClick={() => dirty ? setConfirmation('reload') : reload()}>
|
||
<RefreshCw size={15} /></Button>
|
||
<Button type="button" size="icon" variant="subtle" title={t('恢复默认', 'Restore defaults')} aria-label={t('恢复默认', 'Restore defaults')} disabled={busy || !saved} onClick={() => setConfirmation('reset')}>
|
||
<RotateCcw size={15} /></Button>
|
||
<Button type="submit" disabled={busy || !dirty} loading={busy}>
|
||
<Save size={15} />{t('保存并发布', 'Save and publish')}</Button>
|
||
</div>
|
||
</div>
|
||
<div className="an-compute-status" role="status">
|
||
{message || (error && !saved ? t('配置读取失败', 'Configuration unavailable') : dirty ? t('有未发布修改', 'Unpublished changes') : saved?.is_default ? t('当前使用内置报告数据', 'Using bundled report data') : saved ? t('当前使用后台配置', 'Using published configuration') : t('正在读取配置…', 'Loading configuration…'))}
|
||
</div>
|
||
{error ? <p className="an-compute-error" role="alert">{error}</p> : null}
|
||
{draft && saved ? <>
|
||
<div className="an-compute-toolbar">
|
||
<div className="an-compute-actions" role="group" aria-label={t('数据分类', 'Data categories')}>
|
||
{([['observations', t('年度观测', 'Observations')], ['sources', t('报告来源', 'Sources')], ['innovation', t('创新指数分差', 'Innovation gap')]] as const).map(([key, label]) => (
|
||
<Button key={key} type="button" variant={view === key ? 'primary' : 'subtle'} aria-pressed={view === key} onClick={() => setView(key)}>{label}</Button>
|
||
))}
|
||
</div>
|
||
</div>
|
||
<Scrollbar className="an-compute-scroll" viewportRef={viewportRef}>
|
||
<fieldset className="an-compute-content" disabled={busy}>
|
||
<Field title={t('核验日期', 'Review date')}><Input type="date" required disabled={busy} value={draft.reviewed_at}
|
||
onChange={event => edit({ ...draft, reviewed_at: event.target.value })} /></Field>
|
||
{view === 'observations' ? <>
|
||
<p>{t('占比以全球为分母;绝对量统一为 FP32 EFlop/s。区域只在全部成员都有同年数据时汇总。', 'Shares use the global denominator. Absolute values use FP32 EFlop/s. Regions require every member in the same year.')}</p>
|
||
{draft.observations.map((row, index) => <details className="an-compute-row" key={index} open={index === 0 ? true : undefined}>
|
||
<summary>{row.year} · {metricLabel(row.metric)} · {Object.keys(row.values).length} {t('个国家', 'countries')}</summary>
|
||
<div className="an-compute-fields">
|
||
<Field title={t('观测年份', 'Observation year')}><Input type="number" required min={2000} max={2100} value={Number.isFinite(row.year) ? row.year : ''}
|
||
onChange={event => updateObservation(index, { ...row, year: event.target.valueAsNumber })} /></Field>
|
||
<Field title={t('指标', 'Metric')}><Select value={row.metric} options={(['global_share', 'absolute'] as const).map(metric => ({ value: metric, label: metricLabel(metric) }))}
|
||
onValueChange={value => updateObservation(index, { ...row, metric: value as ComputeObservation['metric'] })} /></Field>
|
||
{sourceSelect(row.source_id, value => updateObservation(index, { ...row, source_id: value }))}
|
||
</div>
|
||
<div className="an-compute-values">
|
||
{Object.entries(row.values).map(([code, value]) => <div className="an-compute-value" key={code}>
|
||
<Field title={saved.countries.find(country => country.code === code)?.[english ? 'name_en' : 'name'] || code}>
|
||
<Input type="number" required min={0} max={row.metric === 'global_share' ? 100 : 1e12} step="any" value={Number.isFinite(value) ? value : ''}
|
||
onChange={event => updateObservation(index, { ...row, values: { ...row.values, [code]: event.target.valueAsNumber } })} />
|
||
</Field>
|
||
{removeButton(t(`移除 ${code} 观测`, `Remove ${code} observation`), () => {
|
||
const values = { ...row.values }; delete values[code]; updateObservation(index, { ...row, values })
|
||
})}
|
||
</div>)}
|
||
</div>
|
||
<div className="an-compute-row-actions">
|
||
<Select value="" placeholder={t('添加国家观测', 'Add country observation')}
|
||
options={saved.countries.filter(country => !(country.code in row.values)).map(country => ({ value: country.code, label: english ? country.name_en : country.name }))}
|
||
onValueChange={code => updateObservation(index, { ...row, values: { ...row.values, [code]: Number.NaN } })} />
|
||
{removeButton(t('移除年度观测', 'Remove annual observation'), () => edit({ ...draft, observations: draft.observations.filter((_, i) => i !== index) }))}
|
||
</div>
|
||
</details>)}
|
||
<Button type="button" variant="subtle" onClick={() => edit({ ...draft, observations: [...draft.observations, { year: new Date().getFullYear(), metric: 'global_share', source_id: sources[0]?.value || '', values: {} }] })}>
|
||
<Plus size={15} />{t('添加年度观测', 'Add annual observation')}</Button>
|
||
</> : view === 'sources' ? <>
|
||
{draft.sources.map((source, index) => <details className="an-compute-row" key={index} open={index === 0 ? true : undefined}>
|
||
<summary>{source.title || t('新报告', 'New report')} · {source.report_year}</summary>
|
||
<div className="an-compute-fields">
|
||
{(['title', 'publisher', 'url', 'locator'] as const).map((key, fieldIndex) => <Field key={key} title={[
|
||
t('报告标题', 'Report title'), t('发布机构', 'Publisher'), t('报告链接', 'Report URL'), t('页码 / 图表位置', 'Page / figure locator'),
|
||
][fieldIndex]}><Input required type={key === 'url' ? 'url' : 'text'} maxLength={key === 'url' ? 2000 : 500}
|
||
value={source[key]}
|
||
onChange={event => edit({ ...draft, sources: draft.sources.map((item, i) => i === index ? { ...item, [key]: event.target.value } : item) })} /></Field>)}
|
||
<Field title={t('报告年份', 'Report year')}><Input type="number" required min={2000} max={2100} value={Number.isFinite(source.report_year) ? source.report_year : ''}
|
||
onChange={event => edit({ ...draft, sources: draft.sources.map((item, i) => i === index ? { ...item, report_year: event.target.valueAsNumber } : item) })} /></Field>
|
||
<Field title={t('发布日期(可选)', 'Publication date (optional)')}><Input type="date" value={source.published_at || ''}
|
||
onChange={event => edit({ ...draft, sources: draft.sources.map((item, i) => i === index ? { ...item, published_at: event.target.value || null } : item) })} /></Field>
|
||
</div>
|
||
{removeButton(reportIsUsed(draft, source.id) ? t('该来源仍被观测引用', 'Source is referenced by observations') : t('移除报告', 'Remove report'),
|
||
() => edit({ ...draft, sources: draft.sources.filter((_, i) => i !== index) }), reportIsUsed(draft, source.id))}
|
||
</details>)}
|
||
<Button type="button" variant="subtle" onClick={() => edit({ ...draft, sources: [...draft.sources, { id: `report-${crypto.randomUUID()}`, title: '', publisher: '', url: '', locator: '', report_year: new Date().getFullYear(), published_at: null }] })}>
|
||
<Plus size={15} />{t('添加报告来源', 'Add report source')}</Button>
|
||
</> : <>
|
||
<p>{t('美国减中国的创新指数分差,与算力占比独立,不反推单国得分。', 'US minus China innovation index gap. Independent of compute shares; individual scores are not inferred.')}</p>
|
||
{draft.innovation.map((row, index) => <div className="an-compute-row" key={index}>
|
||
<div className="an-compute-fields">
|
||
<Field title={t('观测年份', 'Observation year')}><Input type="number" required min={2000} max={2100} value={Number.isFinite(row.year) ? row.year : ''}
|
||
onChange={event => edit({ ...draft, innovation: draft.innovation.map((item, i) => i === index ? { ...item, year: event.target.valueAsNumber } : item) })} /></Field>
|
||
<Field title={t('指数分差', 'Index gap')}><Input type="number" required min={-100} max={100} step="any" value={Number.isFinite(row.value) ? row.value : ''}
|
||
onChange={event => edit({ ...draft, innovation: draft.innovation.map((item, i) => i === index ? { ...item, value: event.target.valueAsNumber } : item) })} /></Field>
|
||
{sourceSelect(row.source_id, value => edit({ ...draft, innovation: draft.innovation.map((item, i) => i === index ? { ...item, source_id: value } : item) }))}
|
||
</div>
|
||
{removeButton(t('移除创新观测', 'Remove innovation observation'), () => edit({ ...draft, innovation: draft.innovation.filter((_, i) => i !== index) }))}
|
||
</div>)}
|
||
<Button type="button" variant="subtle" onClick={() => edit({ ...draft, innovation: [...draft.innovation, { year: new Date().getFullYear(), value: Number.NaN, source_id: sources[0]?.value || '' }] })}>
|
||
<Plus size={15} />{t('添加创新观测', 'Add innovation observation')}</Button>
|
||
</>}
|
||
</fieldset>
|
||
</Scrollbar>
|
||
</> : null}
|
||
</form>
|
||
<ConfirmDialog open={confirmation !== null} onOpenChange={open => !open && setConfirmation(null)} loading={busy}
|
||
title={confirmation === 'reset' ? t('恢复内置报告数据?', 'Restore bundled report data?') : t('放弃草稿并重新加载?', 'Discard draft and reload?')}
|
||
description={t('当前未发布修改将被替换。恢复默认会记录在操作审计中。', 'Unpublished edits will be replaced. Restoring defaults is audited.')}
|
||
onConfirm={() => { if (confirmation === 'reset') void publish(true); else { setConfirmation(null); reload() } }} />
|
||
</Panel>
|
||
)
|
||
}
|