Files
planet/frontend/src/admin/pages/EarthCloudMapSettings.tsx
T
linkong e1cc27f13d
ci / backend (push) Canceled after 0s
ci / frontend (push) Canceled after 0s
ci / delivery (push) Canceled after 0s
release: bump version to 0.84.0
2026-12-04 07:07:19 +08:00

601 lines
23 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import axios from 'axios'
import {
Cloud,
DatabaseZap,
ExternalLink,
FileText,
RefreshCw,
RotateCcw,
Save,
Settings2,
} from 'lucide-react'
import { useCallback, useEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from 'react'
import { Link } from 'react-router-dom'
import Scrollbar from '../../components/Scrollbar/Scrollbar'
import { useLocale } from '../../i18n/locale'
import { SplitPaneResizer, useSplitPaneResize } from '../components/layout/SplitPaneResizer'
import { useAuthStore } from '../../stores/auth'
import { formatDateTimeZhCN } from '../../utils/datetime'
import { Badge } from '../components/ui/badge'
import { Button } from '../components/ui/button'
import { ConfirmDialog } from '../components/ui/dialog'
import { Input } from '../components/ui/input'
import { AdminSwitch } from '../components/ui/switch'
import { Panel, StatusText } from '../patterns/patterns'
import {
describeCloudMapError,
EARTH_CLOUDS_API,
notifyCloudMapChanged,
type CloudConfigurationEnvelope,
type CloudMapConfig,
} from './earth-cloud-map-model'
import { DEFAULT_EARTH_CLOUDS_PATH, resolveEarthPreviewAssetUrl } from '../lib/earthBuiltinAssets'
import './earth-cloud-map.css'
function Field({
label,
full = false,
children,
}: {
label: string
full?: boolean
children: ReactNode
}) {
return (
<label className={`an-cloud-field${full ? ' an-cloud-field--full' : ''}`}>
<span>{label}</span>
{children}
</label>
)
}
function toNumberOr(value: string, fallback: number, min: number, max: number): number {
const parsed = Number(value)
if (!Number.isFinite(parsed)) return fallback
return Math.max(min, Math.min(max, parsed))
}
function normalizePreviewSrc(rawUrl?: string | null): string {
return resolveEarthPreviewAssetUrl(rawUrl, DEFAULT_EARTH_CLOUDS_PATH)
}
export function EarthCloudMapSettings({ active }: { active: boolean }) {
const { locale } = useLocale()
const english = locale === 'en-US'
const t = (zh: string, en: string) => (english ? en : zh)
const { user } = useAuthStore()
const role = String(user?.role || '').toLowerCase()
const canEdit = role === 'admin' || role === 'super_admin'
const [envelope, setEnvelope] = useState<CloudConfigurationEnvelope | null>(null)
const [draft, setDraft] = useState<CloudMapConfig | null>(null)
const [selectedVersion, setSelectedVersion] = useState<string>('')
const [showOverlay, setShowOverlay] = useState(true)
const [busy, setBusy] = useState(false)
const [error, setError] = useState('')
const [message, setMessage] = useState('')
const [confirmAction, setConfirmAction] = useState<'reset' | 'reload' | null>(null)
const workspaceRef = useRef<HTMLDivElement | null>(null)
const workspaceResize = useSplitPaneResize({
storageKey: 'planet.admin.cloudConfigWidth',
defaultWidth: 380,
minWidth: 280,
maxWidth: 560,
minOppositeWidth: 320,
side: 'right',
containerRef: workspaceRef,
})
const loadConfiguration = useCallback(async (signal?: AbortSignal) => {
setBusy(true)
try {
const { data } = await axios.get<CloudConfigurationEnvelope>(`${EARTH_CLOUDS_API}/configuration`, {
signal,
})
setEnvelope(data)
setDraft(data.config)
setSelectedVersion(data.meta.version || '')
setError('')
} catch (failure) {
if (!signal?.aborted) {
setError(describeCloudMapError(failure, english))
}
} finally {
if (!signal?.aborted) {
setBusy(false)
}
}
}, [english])
useEffect(() => {
if (!active || envelope) return
const controller = new AbortController()
void loadConfiguration(controller.signal)
return () => controller.abort()
}, [active, envelope, loadConfiguration])
const dirty = useMemo(
() => Boolean(envelope && draft && JSON.stringify(envelope.config) !== JSON.stringify(draft)),
[envelope, draft],
)
useEffect(() => {
if (!dirty) return
const onBeforeUnload = (event: BeforeUnloadEvent) => {
event.preventDefault()
event.returnValue = ''
}
window.addEventListener('beforeunload', onBeforeUnload)
return () => window.removeEventListener('beforeunload', onBeforeUnload)
}, [dirty])
if (!active && !envelope) return null
const meta = envelope?.meta
const datasource = envelope?.datasource
const frames = meta?.frames || []
const activeFrame = frames.find((item) => item.version === selectedVersion) || frames[0] || null
const previewSrc = normalizePreviewSrc(activeFrame?.image_url || meta?.image_url)
const summary = activeFrame?.global_summary || meta?.summary || {}
const clusters = meta?.convective_clusters || []
const regions = meta?.regions || []
const statusTone = !meta?.enabled
? 'neutral'
: meta?.mode === 'realtime' && !meta?.degraded
? 'success'
: meta?.mode === 'realtime' && meta?.degraded
? 'warning'
: 'warning'
const statusLabel = !meta?.enabled
? t('已停用', 'Disabled')
: meta?.mode === 'realtime' && !meta?.degraded
? t('实时运行', 'Live')
: meta?.mode === 'realtime' && meta?.degraded
? t('降级运行', 'Degraded')
: t('暂无快照', 'Fallback')
const patchDraft = (patch: Partial<CloudMapConfig>) => {
if (!draft) return
setDraft({ ...draft, ...patch })
setError('')
setMessage('')
}
const handleSave = async () => {
if (!envelope || !draft || !canEdit) return
setBusy(true)
setError('')
setMessage('')
try {
const mergedConfig: CloudMapConfig = {
...envelope.config,
enabled: draft.enabled,
default_opacity: draft.default_opacity,
timelapse_enabled: draft.timelapse_enabled,
show_convective_markers: draft.show_convective_markers,
}
const { data } = await axios.put<CloudConfigurationEnvelope>(`${EARTH_CLOUDS_API}/configuration`, {
revision: envelope.revision,
config: mergedConfig,
})
setEnvelope(data)
setDraft(data.config)
setMessage(t('云图展示配置已保存并同步至星球端。', 'Cloud map display settings saved and synced.'))
notifyCloudMapChanged({ reason: 'config_updated' })
} catch (failure) {
setError(describeCloudMapError(failure, english))
} finally {
setBusy(false)
}
}
const handleReset = async () => {
if (!envelope || !canEdit) return
setConfirmAction(null)
setBusy(true)
setError('')
setMessage('')
try {
const { data } = await axios.post<CloudConfigurationEnvelope>(
`${EARTH_CLOUDS_API}/configuration/reset`,
{ revision: envelope.revision, config: {} },
)
setEnvelope(data)
setDraft(data.config)
setMessage(t('已恢复云图默认展示配置。', 'Cloud map display settings reset to defaults.'))
notifyCloudMapChanged({ reason: 'config_reset' })
} catch (failure) {
setError(describeCloudMapError(failure, english))
} finally {
setBusy(false)
}
}
return (
<Panel className="an-cloud-settings" hidden={!active}>
<div className="an-cloud-toolbar">
<div className="an-cloud-toolbar__title">
<Cloud size={17} />
<h2>{t('全球实时红外云图', 'Live Satellite Cloud Map')}</h2>
<StatusText tone={statusTone}>{statusLabel}</StatusText>
</div>
<div className="an-cloud-toolbar__actions">
<Button asChild size="sm" variant="subtle">
<Link to="/datasources?product=weather">
<DatabaseZap size={14} />
{t('数据源采集', 'Datasources')}
</Link>
</Button>
<Button
size="icon"
variant="subtle"
title={t('重新加载', 'Reload')}
aria-label={t('重新加载', 'Reload')}
disabled={busy}
onClick={() => (dirty ? setConfirmAction('reload') : void loadConfiguration())}
>
<RefreshCw size={15} />
</Button>
<Button
size="sm"
disabled={!dirty || busy || !canEdit}
loading={busy}
onClick={() => void handleSave()}
>
<Save size={14} />
{t('保存配置', 'Save')}
</Button>
</div>
</div>
{error ? (
<p className="an-cloud-banner an-cloud-banner--error" role="alert">
{error}
</p>
) : null}
{message ? (
<p className="an-cloud-banner an-cloud-banner--ok" role="status">
{message}
</p>
) : null}
<div
ref={workspaceRef}
className="an-cloud-workspace"
style={{ '--an-cloud-config-width': `${workspaceResize.width}px` } as CSSProperties}
>
<Scrollbar className="an-cloud-pane an-cloud-pane--preview" axis="y">
<div className="an-cloud-stage-head">
<div className="an-cloud-stage-head__meta">
<Badge tone={meta?.mode === 'realtime' ? 'green' : 'amber'}>
{activeFrame?.source || meta?.source || 'static'}
</Badge>
{activeFrame?.captured_at || meta?.captured_at ? (
<Badge tone="slate">
{formatDateTimeZhCN(activeFrame?.captured_at || meta?.captured_at || '')}
</Badge>
) : null}
<Badge tone="cyan">{activeFrame?.resolution || draft?.resolution || '4096x2048'}</Badge>
{meta?.satellites?.length ? (
<Badge tone="blue">
{t(`${meta.satellites.length} 颗卫星合成`, `${meta.satellites.length} satellites`)}
</Badge>
) : null}
</div>
<AdminSwitch
checked={showOverlay}
onCheckedChange={setShowOverlay}
label={t('叠加经纬网与强对流核', 'Overlay grid & clusters')}
/>
</div>
<div className="an-cloud-canvas">
<img
className="an-cloud-canvas__img"
src={previewSrc}
alt={t('全球实时红外云图预览', 'Global live infrared cloud preview')}
/>
{showOverlay ? (
<svg
className="an-cloud-canvas__overlay"
viewBox="0 0 360 180"
preserveAspectRatio="none"
aria-hidden="true"
>
{[-60, -30, 0, 30, 60].map((lat) => (
<line
key={`lat-${lat}`}
className="an-cloud-canvas__grid-line"
x1={0}
y1={90 - lat}
x2={360}
y2={90 - lat}
/>
))}
{[-120, -60, 0, 60, 120].map((lon) => (
<line
key={`lon-${lon}`}
className="an-cloud-canvas__grid-line"
x1={180 + lon}
y1={0}
x2={180 + lon}
y2={180}
/>
))}
{clusters.map((cluster) => {
const x = 180 + cluster.bbox.lon_min
const y = 90 - cluster.bbox.lat_max
const w = Math.max(2, cluster.bbox.lon_max - cluster.bbox.lon_min)
const h = Math.max(2, cluster.bbox.lat_max - cluster.bbox.lat_min)
return (
<g key={cluster.cluster_id}>
<rect
className="an-cloud-canvas__cluster-box"
x={x}
y={y}
width={w}
height={h}
/>
<circle
className="an-cloud-canvas__cluster-dot"
cx={180 + cluster.longitude}
cy={90 - cluster.latitude}
r={1.3}
/>
</g>
)
})}
</svg>
) : null}
</div>
<div className="an-cloud-kpis">
<div className="an-cloud-kpi">
<span>{t('全球平均云量', 'Global Cloud Cover')}</span>
<strong>
{summary.global_cloud_cover_pct != null ? `${summary.global_cloud_cover_pct}%` : '--'}
</strong>
</div>
<div className="an-cloud-kpi">
<span>{t('厚云覆盖率', 'Overcast Share')}</span>
<strong>{summary.global_overcast_pct != null ? `${summary.global_overcast_pct}%` : '--'}</strong>
</div>
<div className="an-cloud-kpi">
<span>{t('强对流云团', 'Convective Clusters')}</span>
<strong>{summary.convective_cluster_count ?? clusters.length}</strong>
</div>
<div className="an-cloud-kpi">
<span>{t('最低云顶亮温', 'Min Cloud Top Temp')}</span>
<strong>
{summary.min_brightness_temp_c != null ? `${summary.min_brightness_temp_c}°C` : '--'}
</strong>
</div>
</div>
{frames.length > 0 ? (
<>
<div className="an-cloud-section-title">
<span>{t('历史采集帧切换', 'Captured Frames')}</span>
<small>{t(`共 ${frames.length} 帧 · ${meta?.storage_stats?.total_mb ?? 0} MB`, `${frames.length} frames · ${meta?.storage_stats?.total_mb ?? 0} MB`)}</small>
</div>
<div className="an-cloud-frames">
{frames.slice(0, 10).map((frame) => (
<button
key={frame.version}
type="button"
className={`an-cloud-frame-chip${(activeFrame?.version || '') === frame.version ? ' is-active' : ''}`}
onClick={() => setSelectedVersion(frame.version)}
>
{frame.captured_at.slice(11, 16)} UTC
</button>
))}
</div>
</>
) : null}
{regions.length > 0 ? (
<>
<div className="an-cloud-section-title">
<span>{t('重点区域实时云量', 'Focus Region Cloud Cover')}</span>
</div>
<div className="an-cloud-regions">
{regions.map((region) => (
<div key={region.key} className="an-cloud-region-item">
<span>{english ? region.name_en : region.name}</span>
<strong>{region.cloud_cover_pct}%</strong>
</div>
))}
</div>
</>
) : null}
</Scrollbar>
<SplitPaneResizer
label={t('拖动调整配置区宽度', 'Drag to resize settings width')}
isDragging={workspaceResize.isDragging}
onPointerDown={workspaceResize.onPointerDown}
onKeyDown={workspaceResize.onKeyDown}
/>
<Scrollbar className="an-cloud-pane" axis="y">
{!draft ? (
<p className="an-cloud-banner">{busy ? t('加载中…', 'Loading…') : t('暂无配置', 'No config')}</p>
) : (
<div className="an-cloud-form">
<div className="an-cloud-switch-row">
<span>{t('启用实时卫星云图(关闭后回退静态默认贴图)', 'Enable live cloud imagery')}</span>
<AdminSwitch
checked={draft.enabled}
disabled={!canEdit || busy}
onCheckedChange={(checked) => patchDraft({ enabled: checked })}
label={t('启用实时云图', 'Enable live cloud map')}
/>
</div>
<div className="an-cloud-switch-row">
<span>{t('允许星球端播放历史云图演变', 'Allow Earth timelapse playback')}</span>
<AdminSwitch
checked={draft.timelapse_enabled}
disabled={!canEdit || busy}
onCheckedChange={(checked) => patchDraft({ timelapse_enabled: checked })}
label={t('历史帧演变播放', 'Timelapse playback')}
/>
</div>
<div className="an-cloud-switch-row">
<span>{t('默认开启强对流云团标识', 'Highlight convective storm cores by default')}</span>
<AdminSwitch
checked={draft.show_convective_markers}
disabled={!canEdit || busy}
onCheckedChange={(checked) => patchDraft({ show_convective_markers: checked })}
label={t('强对流云团标识', 'Convective markers')}
/>
</div>
<div className="an-cloud-switch-row">
<span>{t('启用日间真彩色 GeoColor 合成', 'Enable daytime GeoColor RGB composite')}</span>
<AdminSwitch
checked={draft.geocolor_enabled}
disabled={!canEdit || busy}
onCheckedChange={(checked) => patchDraft({ geocolor_enabled: checked })}
label={t('日间真彩色 GeoColor', 'GeoColor compositing')}
/>
</div>
<div className="an-cloud-switch-row">
<span>{t('启用连续云团光流形变插值 (DIS)', 'Enable DIS optical-flow cloud advection')}</span>
<AdminSwitch
checked={draft.optical_flow_enabled}
disabled={!canEdit || busy}
onCheckedChange={(checked) => patchDraft({ optical_flow_enabled: checked })}
label={t('DIS 光流平滑插值', 'DIS optical flow advection')}
/>
</div>
<div className="an-cloud-fields">
<Field label={t('默认云层透明度 (0.1–0.8)', 'Default Cloud Opacity (0.1–0.8)')}>
<Input
type="number"
step="0.02"
min={0.1}
max={0.8}
disabled={!canEdit || busy}
value={String(draft.default_opacity)}
onChange={(e) =>
patchDraft({ default_opacity: toNumberOr(e.target.value, 0.38, 0.1, 0.8) })
}
/>
</Field>
<Field label={t('云顶 3D 浮雕法线强度 (0.0–1.0)', 'Cloud-Top Relief Shading (0.0–1.0)')}>
<Input
type="number"
step="0.05"
min={0}
max={1}
disabled={!canEdit || busy}
value={String(draft.relief_shading_strength ?? 0.45)}
onChange={(e) =>
patchDraft({ relief_shading_strength: toNumberOr(e.target.value, 0.45, 0, 1) })
}
/>
</Field>
</div>
<div className="an-cloud-probe-box">
<div className="an-cloud-probe-row">
<strong>{t('采集器分工与当前状态', 'Collector Status & Entry')}</strong>
<Badge tone={datasource?.is_active ? 'green' : 'amber'}>
{datasource?.is_active ? t('采集器已启用', 'Collector Active') : t('采集器未启用', 'Collector Inactive')}
</Badge>
</div>
<div className="an-cloud-probe-row">
<span>{t('气象采集器', 'Weather Collector')}</span>
<span>global_cloud_map · {datasource?.frequency_minutes ?? 30} min</span>
</div>
<div className="an-cloud-probe-row">
<span>{t('当前上游策略', 'Upstream Strategy')}</span>
<span>{draft.primary_source} · {draft.resolution}</span>
</div>
<div className="an-cloud-probe-row">
<span>{t('最近执行状态', 'Last Collection')}</span>
<span>
{datasource?.last_run_at
? `${formatDateTimeZhCN(datasource.last_run_at)} (${datasource.last_status || '-'})`
: t('尚未执行', 'Not run yet')}
</span>
</div>
<div className="an-cloud-links">
<Button asChild size="sm" variant="subtle">
<Link to="/datasources?product=weather">
<DatabaseZap size={14} />
{t('前往数据源管理采集', 'Manage Collection in Datasources')}
</Link>
</Button>
<Button asChild size="sm" variant="subtle">
<Link to="/collection-management">
<Settings2 size={14} />
{t('前往采集器配置参数', 'Configure Collector Parameters')}
</Link>
</Button>
<Button asChild size="sm" variant="subtle">
<Link to="/data">
<ExternalLink size={14} />
{t('查看采集记录', 'Collected Records')}
</Link>
</Button>
<Button asChild size="sm" variant="subtle">
<Link to="/logs?source=system-db&search=global_cloud_map">
<FileText size={14} />
{t('查看云图日志', 'Cloud Logs')}
</Link>
</Button>
</div>
</div>
<div className="an-cloud-danger-actions">
<Button
size="sm"
variant="subtle"
disabled={!canEdit || busy}
onClick={() => setConfirmAction('reset')}
>
<RotateCcw size={14} />
{t('恢复默认配置', 'Reset Defaults')}
</Button>
</div>
</div>
)}
</Scrollbar>
</div>
<ConfirmDialog
open={confirmAction !== null}
onOpenChange={(open) => {
if (!open) setConfirmAction(null)
}}
title={
confirmAction === 'reset'
? t('恢复默认云图展示配置?', 'Reset cloud map display settings?')
: t('放弃未保存的修改并重新加载?', 'Discard unsaved edits and reload?')
}
description={
confirmAction === 'reset'
? t('当前展示配置将被重置为系统默认参数。', 'Current display settings will be restored to defaults.')
: t('未保存的表单改动将会丢失。', 'Unsaved form edits will be discarded.')
}
confirmLabel={t('确认', 'Confirm')}
cancelLabel={t('取消', 'Cancel')}
onConfirm={() => {
if (confirmAction === 'reset') void handleReset()
else {
setConfirmAction(null)
void loadConfiguration()
}
}}
/>
</Panel>
)
}