release: bump version to 0.84.0
ci / backend (push) Canceled after 0s
ci / frontend (push) Canceled after 0s
ci / delivery (push) Canceled after 0s

This commit is contained in:
linkong committed 2026-12-04 07:07:19 +08:00
1 parent 3b1b9ef68c
commit e1cc27f13d
241 files changed
+42779 -6027

No files matched your search

@@ -7,10 +7,64 @@ import {
type SortingState,
} from '@tanstack/react-table'
import { ArrowDown, ArrowUp, ChevronsUpDown } from 'lucide-react'
import { useMemo, useState } from 'react'
import {
useCallback,
useEffect,
useLayoutEffect,
useMemo,
useRef,
useState,
type KeyboardEvent as ReactKeyboardEvent,
type PointerEvent as ReactPointerEvent,
} from 'react'
import { useTranslation } from 'react-i18next'
import { translateLegacyAdminText } from '../../../i18n/LegacyI18nBridge'
import { normalizeLocale } from '../../../i18n/locale'
import TableScrollRegion from '../../../components/Scrollbar/TableScrollRegion'
import { Button } from '../ui/button'
import { SPLIT_RESIZE_END_EVENT } from '../layout/SplitPaneResizer'
import { TableCellMarquee } from './TableCellMarquee'
import {
DEFAULT_COLUMN_BASE_WIDTH,
DEFAULT_COLUMN_MAX_WIDTH,
DEFAULT_COLUMN_MIN_WIDTH,
SELECTION_COLUMN_WIDTH,
clampColumnWidth,
computeColumnWidths,
doesViewportChangeAffectColumns,
estimateHeaderMinWidth,
findLastDataColumnIndex,
readStoredColumnWidths,
shouldLoadMoreWaterfall,
writeStoredColumnWidths,
type ColumnWidthSpec,
} from './tableLayout'
const NO_MARQUEE_COLUMN_IDS = new Set([
'actions',
'action',
'schedule',
'gatekeeper_groups',
])
const DEFAULT_WATERFALL_PAGE_SIZE = 40
const DEFAULT_WATERFALL_THRESHOLD_PX = 160
function insertAtIndex<T>(items: T[], index: number, extra: T | null): T[] {
if (extra === null) return items
const safeIndex = Math.max(0, Math.min(items.length, index))
return [...items.slice(0, safeIndex), extra, ...items.slice(safeIndex)]
}
export interface DataTableWaterfallConfig {
enabled?: boolean
pageSize?: number
thresholdPx?: number
total?: number
hasMore?: boolean
loadingMore?: boolean
onLoadMore?: () => void
showFooter?: boolean
}
interface DataTableProps<TData> {
columns: Array<ColumnDef<TData>>
@@ -29,6 +83,11 @@ interface DataTableProps<TData> {
className?: string
footer?: React.ReactNode
onRowClick?: (row: TData) => void
resizableColumns?: boolean
columnWidthStorageKey?: string
enableSorting?: boolean
waterfall?: DataTableWaterfallConfig | false
scrollResetKey?: string | number
}
export function DataTable<TData>({
@@ -42,35 +101,491 @@ export function DataTable<TData>({
className = '',
footer,
onRowClick,
resizableColumns = true,
columnWidthStorageKey,
enableSorting,
waterfall,
scrollResetKey,
}: DataTableProps<TData>) {
const { t } = useTranslation()
const { t, i18n } = useTranslation()
const currentLocale = normalizeLocale(i18n.resolvedLanguage || i18n.language)
const [sorting, setSorting] = useState<SortingState>([])
const memoizedColumns = useMemo(() => columns, [columns])
const waterfallDisabled = waterfall === false || waterfall?.enabled === false
const waterfallConfig = waterfall && typeof waterfall === 'object' ? waterfall : undefined
const isServerWaterfall = !waterfallDisabled && Boolean(waterfallConfig?.onLoadMore)
const isClientWaterfall = !waterfallDisabled && !waterfallConfig?.onLoadMore
const waterfallPageSize = Math.max(10, waterfallConfig?.pageSize ?? DEFAULT_WATERFALL_PAGE_SIZE)
const thresholdPx = waterfallConfig?.thresholdPx ?? DEFAULT_WATERFALL_THRESHOLD_PX
const effectiveEnableSorting = enableSorting ?? !isServerWaterfall
const viewportRef = useRef<HTMLDivElement | null>(null)
const [viewportWidth, setViewportWidth] = useState(0)
const [measuredHeaderMinWidths, setMeasuredHeaderMinWidths] = useState<Record<string, number>>({})
const [manualWidths, setManualWidths] = useState<Record<string, number>>({})
const manualWidthsRef = useRef<Record<string, number>>({})
const storageKeyRef = useRef(columnWidthStorageKey)
storageKeyRef.current = columnWidthStorageKey
const [resizingColumnId, setResizingColumnId] = useState<string | null>(null)
const resizeCleanupRef = useRef<(() => void) | null>(null)
const table = useReactTable({
data,
columns: memoizedColumns,
enableSorting: effectiveEnableSorting,
state: { sorting },
onSortingChange: setSorting,
getRowId,
getCoreRowModel: getCoreRowModel(),
getSortedRowModel: getSortedRowModel(),
})
const headerGroups = table.getHeaderGroups()
const leafHeaders = headerGroups[headerGroups.length - 1]?.headers ?? []
const columnSignature = leafHeaders.map((header) => header.column.id).join('|')
const columnIds = useMemo(
() => (columnSignature ? columnSignature.split('|') : []),
[columnSignature],
)
useEffect(() => {
const stored = readStoredColumnWidths(columnWidthStorageKey, columnIds)
manualWidthsRef.current = stored
setManualWidths(stored)
setResizingColumnId(null)
}, [columnIds, columnWidthStorageKey])
useLayoutEffect(() => {
const element = viewportRef.current
if (!element) return
const nextMeasured: Record<string, number> = {}
const thNodes = element.querySelectorAll<HTMLTableCellElement>('thead th[data-column-id]')
thNodes.forEach((th) => {
const colId = th.getAttribute('data-column-id')
if (!colId || colId === 'actions' || colId === 'action') return
const labelEl = th.querySelector<HTMLElement>('.an-data-table__header-label')
if (!labelEl) return
const thStyle = window.getComputedStyle(th)
const padL = Number.parseFloat(thStyle.paddingLeft) || 10
const padR = Number.parseFloat(thStyle.paddingRight) || 10
const labelWidth = Math.ceil(labelEl.scrollWidth)
const sortSvg = th.querySelector<HTMLElement>('.an-data-table__sort svg')
const sortWidth = sortSvg ? Math.ceil(sortSvg.getBoundingClientRect().width) + 5 : 0
const computedMin = Math.ceil(padL + labelWidth + sortWidth + padR + 4)
if (computedMin > 0) {
nextMeasured[colId] = computedMin
}
})
setMeasuredHeaderMinWidths((prev) => {
const prevKeys = Object.keys(prev)
const nextKeys = Object.keys(nextMeasured)
if (
prevKeys.length === nextKeys.length &&
nextKeys.every((key) => prev[key] === nextMeasured[key])
) {
return prev
}
return nextMeasured
})
}, [columnSignature, currentLocale, effectiveEnableSorting, resizableColumns])
const lastDataColumnIndex = useMemo(
() => findLastDataColumnIndex(leafHeaders.map((header) => ({ id: header.column.id }))),
[leafHeaders],
)
const columnSpecs = useMemo<ColumnWidthSpec[]>(
() =>
leafHeaders.map((header, index) => {
const colDef = header.column.columnDef
const isUtilityAction = header.column.id === 'actions' || header.column.id === 'action'
const canResize = resizableColumns && header.column.getCanResize() && !isUtilityAction
const showResizer = canResize && index !== lastDataColumnIndex
const rawHeaderLabel =
typeof colDef.header === 'string'
? colDef.header
: header.column.id
const headerLabel = translateLegacyAdminText(rawHeaderLabel, currentLocale)
const colDefMin = typeof colDef.minSize === 'number' ? colDef.minSize : DEFAULT_COLUMN_MIN_WIDTH
const estimatedHeaderMin = isUtilityAction
? colDefMin
: estimateHeaderMinWidth(headerLabel, {
sortable: effectiveEnableSorting && header.column.getCanSort(),
resizable: showResizer,
})
const domHeaderMin = isUtilityAction ? 0 : (measuredHeaderMinWidths[header.column.id] ?? 0)
const minWidth = Math.max(colDefMin, estimatedHeaderMin, domHeaderMin)
const baseWidth = Math.max(
minWidth,
typeof colDef.size === 'number' ? colDef.size : DEFAULT_COLUMN_BASE_WIDTH,
)
const maxWidth =
typeof colDef.maxSize === 'number' && colDef.maxSize !== Number.MAX_SAFE_INTEGER
? Math.max(minWidth, colDef.maxSize)
: DEFAULT_COLUMN_MAX_WIDTH
return {
id: header.column.id,
baseWidth,
minWidth,
maxWidth,
resizable: canResize,
}
}),
[currentLocale, effectiveEnableSorting, lastDataColumnIndex, leafHeaders, measuredHeaderMinWidths, resizableColumns],
)
const selectionWidth = selection ? SELECTION_COLUMN_WIDTH : 0
const columnSpecsRef = useRef(columnSpecs)
columnSpecsRef.current = columnSpecs
const selectionWidthRef = useRef(selectionWidth)
selectionWidthRef.current = selectionWidth
const viewportWidthRef = useRef(viewportWidth)
viewportWidthRef.current = viewportWidth
useEffect(() => {
const element = viewportRef.current
if (!element) return
let rafId = 0
let deferredDuringDrag = false
const applySyncWidth = () => {
rafId = 0
if (document.body.classList.contains('an-is-resizing')) {
deferredDuringDrag = true
return
}
deferredDuringDrag = false
const nextWidth = element.clientWidth
if (
!doesViewportChangeAffectColumns({
columns: columnSpecsRef.current,
selectionWidth: selectionWidthRef.current,
manualWidths: manualWidthsRef.current,
prevViewportWidth: viewportWidthRef.current,
nextViewportWidth: nextWidth,
})
) {
viewportWidthRef.current = nextWidth
return
}
viewportWidthRef.current = nextWidth
setViewportWidth(nextWidth)
}
const scheduleSync = () => {
if (document.body.classList.contains('an-is-resizing')) {
deferredDuringDrag = true
return
}
if (!rafId) {
rafId = window.requestAnimationFrame(applySyncWidth)
}
}
const handleDragEnd = () => {
if (!deferredDuringDrag && element.clientWidth === viewportWidthRef.current) return
if (rafId) {
window.cancelAnimationFrame(rafId)
}
rafId = window.requestAnimationFrame(applySyncWidth)
}
const initialWidth = element.clientWidth
viewportWidthRef.current = initialWidth
setViewportWidth(initialWidth)
window.addEventListener(SPLIT_RESIZE_END_EVENT, handleDragEnd)
window.addEventListener('pointerup', handleDragEnd)
window.addEventListener('pointercancel', handleDragEnd)
if (typeof ResizeObserver === 'undefined') {
window.addEventListener('resize', scheduleSync)
return () => {
if (rafId) window.cancelAnimationFrame(rafId)
window.removeEventListener('resize', scheduleSync)
window.removeEventListener(SPLIT_RESIZE_END_EVENT, handleDragEnd)
window.removeEventListener('pointerup', handleDragEnd)
window.removeEventListener('pointercancel', handleDragEnd)
}
}
const observer = new ResizeObserver(scheduleSync)
observer.observe(element)
return () => {
if (rafId) window.cancelAnimationFrame(rafId)
observer.disconnect()
window.removeEventListener(SPLIT_RESIZE_END_EVENT, handleDragEnd)
window.removeEventListener('pointerup', handleDragEnd)
window.removeEventListener('pointercancel', handleDragEnd)
}
}, [])
useEffect(() => () => {
resizeCleanupRef.current?.()
}, [])
const { widths: resolvedWidths, spacerWidth, tableWidth } = useMemo(
() =>
computeColumnWidths({
columns: columnSpecs,
viewportWidth,
selectionWidth,
manualWidths,
}),
[columnSpecs, manualWidths, selectionWidth, viewportWidth],
)
const stickyEndIndex = columnSpecs.findIndex((spec) => spec.id === 'actions' || spec.id === 'action')
const hasSpacer = spacerWidth > 0
const spacerInsertIndex = stickyEndIndex !== -1 ? stickyEndIndex : columnSpecs.length
const widthsRef = useRef(resolvedWidths)
widthsRef.current = resolvedWidths
const startColumnResize = useCallback(
(spec: ColumnWidthSpec, event: ReactPointerEvent<HTMLElement>) => {
if (!spec.resizable) return
event.preventDefault()
event.stopPropagation()
resizeCleanupRef.current?.()
const startX = event.clientX
const snapshot = { ...widthsRef.current }
const startWidth = snapshot[spec.id] ?? spec.baseWidth
let pendingWidth = startWidth
let rafId = 0
manualWidthsRef.current = snapshot
setManualWidths(snapshot)
setResizingColumnId(spec.id)
document.body.classList.add('an-is-resizing')
const flushColumnWidth = () => {
rafId = 0
const base = Object.keys(manualWidthsRef.current).length > 0 ? manualWidthsRef.current : snapshot
if (base[spec.id] === pendingWidth) return
const nextWidths = { ...base, [spec.id]: pendingWidth }
manualWidthsRef.current = nextWidths
setManualWidths(nextWidths)
}
const handleMove = (moveEvent: PointerEvent) => {
pendingWidth = clampColumnWidth(
startWidth + (moveEvent.clientX - startX),
spec.minWidth,
spec.maxWidth,
)
if (!rafId) {
rafId = window.requestAnimationFrame(flushColumnWidth)
}
}
const cleanupListeners = () => {
if (rafId) {
window.cancelAnimationFrame(rafId)
rafId = 0
}
document.body.classList.remove('an-is-resizing')
window.removeEventListener('pointermove', handleMove)
window.removeEventListener('pointerup', stopResize)
window.removeEventListener('pointercancel', stopResize)
resizeCleanupRef.current = null
}
const stopResize = () => {
cleanupListeners()
flushColumnWidth()
setResizingColumnId(null)
writeStoredColumnWidths(storageKeyRef.current, manualWidthsRef.current)
}
resizeCleanupRef.current = cleanupListeners
window.addEventListener('pointermove', handleMove)
window.addEventListener('pointerup', stopResize, { once: true })
window.addEventListener('pointercancel', stopResize, { once: true })
},
[],
)
const handleResizerKeyDown = useCallback(
(spec: ColumnWidthSpec, event: ReactKeyboardEvent<HTMLElement>) => {
if (!spec.resizable) return
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault()
event.stopPropagation()
manualWidthsRef.current = {}
setManualWidths({})
writeStoredColumnWidths(storageKeyRef.current, {})
return
}
if (event.key !== 'ArrowLeft' && event.key !== 'ArrowRight') return
event.preventDefault()
event.stopPropagation()
const delta = event.key === 'ArrowRight' ? 16 : -16
const snapshot = { ...widthsRef.current }
const currentWidth = snapshot[spec.id] ?? spec.baseWidth
const nextWidth = clampColumnWidth(currentWidth + delta, spec.minWidth, spec.maxWidth)
const nextWidths = { ...snapshot, [spec.id]: nextWidth }
manualWidthsRef.current = nextWidths
setManualWidths(nextWidths)
writeStoredColumnWidths(storageKeyRef.current, nextWidths)
},
[],
)
const sortedRows = table.getRowModel().rows
const [clientVisibleCount, setClientVisibleCount] = useState(waterfallPageSize)
useEffect(() => {
setClientVisibleCount(waterfallPageSize)
}, [data, sorting, waterfallPageSize, waterfallDisabled])
const renderedRows = useMemo(() => {
if (!isClientWaterfall) return sortedRows
return sortedRows.slice(0, clientVisibleCount)
}, [clientVisibleCount, isClientWaterfall, sortedRows])
const totalCount = isServerWaterfall
? Math.max(renderedRows.length, waterfallConfig?.total ?? renderedRows.length)
: sortedRows.length
const hasMore = isServerWaterfall
? Boolean(waterfallConfig?.hasMore)
: isClientWaterfall && renderedRows.length < sortedRows.length
const loadingMore = isServerWaterfall ? Boolean(waterfallConfig?.loadingMore) : false
const triggerLoadMore = useCallback(() => {
if (!hasMore || loading || loadingMore) return
if (isServerWaterfall) {
waterfallConfig?.onLoadMore?.()
return
}
if (isClientWaterfall) {
setClientVisibleCount((prev) => Math.min(sortedRows.length, prev + waterfallPageSize))
}
}, [hasMore, isClientWaterfall, isServerWaterfall, loading, loadingMore, sortedRows.length, waterfallConfig, waterfallPageSize])
const triggerLoadMoreRef = useRef(triggerLoadMore)
triggerLoadMoreRef.current = triggerLoadMore
const scrollStateRef = useRef({ hasMore, loading, loadingMore, thresholdPx })
scrollStateRef.current = { hasMore, loading, loadingMore, thresholdPx }
useEffect(() => {
const viewport = viewportRef.current
if (!viewport || waterfallDisabled) return
const handleScroll = () => {
const state = scrollStateRef.current
if (
shouldLoadMoreWaterfall({
scrollTop: viewport.scrollTop,
clientHeight: viewport.clientHeight,
scrollHeight: viewport.scrollHeight,
thresholdPx: state.thresholdPx,
hasMore: state.hasMore,
loading: state.loading,
loadingMore: state.loadingMore,
})
) {
triggerLoadMoreRef.current()
}
}
viewport.addEventListener('scroll', handleScroll, { passive: true })
return () => viewport.removeEventListener('scroll', handleScroll)
}, [waterfallDisabled])
const lastAutoFillCountRef = useRef(-1)
useEffect(() => {
lastAutoFillCountRef.current = -1
const viewport = viewportRef.current
if (viewport) {
viewport.scrollTop = 0
}
}, [scrollResetKey])
useEffect(() => {
if (waterfallDisabled || !hasMore || loading || loadingMore || renderedRows.length === 0) return
const viewport = viewportRef.current
if (!viewport || viewport.clientHeight <= 0) return
if (lastAutoFillCountRef.current === renderedRows.length) return
if (viewport.scrollHeight <= viewport.clientHeight + thresholdPx) {
lastAutoFillCountRef.current = renderedRows.length
triggerLoadMoreRef.current()
}
}, [hasMore, loading, loadingMore, renderedRows.length, thresholdPx, waterfallDisabled])
const visibleSelectableRows = selection
? table.getRowModel().rows.filter((row) => selection.isRowSelectable?.(row.original) ?? true)
? renderedRows.filter((row) => selection.isRowSelectable?.(row.original) ?? true)
: []
const visibleSelectableIds = visibleSelectableRows.map((row) => row.id)
const allVisibleSelected = visibleSelectableIds.length > 0 && visibleSelectableIds.every((rowId) => selection?.selectedRowIds.has(rowId))
const allVisibleSelected =
visibleSelectableIds.length > 0 && visibleSelectableIds.every((rowId) => selection?.selectedRowIds.has(rowId))
const someVisibleSelected = visibleSelectableIds.some((rowId) => selection?.selectedRowIds.has(rowId))
const columnCount = columns.length + (selection ? 1 : 0)
const columnCount = columns.length + (selection ? 1 : 0) + (hasSpacer ? 1 : 0)
const showWaterfallFooter =
!footer &&
!waterfallDisabled &&
totalCount > 0 &&
(waterfallConfig?.showFooter ?? (isServerWaterfall || totalCount > waterfallPageSize))
const footerNode = footer ? (
footer
) : showWaterfallFooter ? (
<div className="an-data-table__waterfall-status">
<span className="an-data-table__waterfall-indicator">
{loadingMore ? <span className="an-spinner an-spinner--xs" aria-hidden="true" /> : null}
{loadingMore
? t('common.waterfallLoadingMore', {
loaded: renderedRows.length.toLocaleString(),
total: totalCount.toLocaleString(),
})
: hasMore
? t('common.waterfallLoadMoreHint', {
loaded: renderedRows.length.toLocaleString(),
total: totalCount.toLocaleString(),
})
: t('common.waterfallAllLoaded', {
total: totalCount.toLocaleString(),
})}
</span>
</div>
) : null
const isInitialLoading = loading && renderedRows.length === 0
const isRefreshing = loading && renderedRows.length > 0
return (
<div className={`an-data-table ${className}`}>
<div
className={`an-data-table ${className}`}
data-has-selection={selection ? 'true' : undefined}
>
{isRefreshing ? <div className="an-data-table__loading-bar" aria-hidden="true" /> : null}
<TableScrollRegion className="an-data-table__scroll" targetSelector=".an-data-table__viewport">
<div className="an-data-table__viewport">
<table className="an-data-table__table">
<div ref={viewportRef} className="an-data-table__viewport">
<table
className="an-data-table__table"
style={tableWidth > 0 ? { width: `${tableWidth}px` } : undefined}
>
<colgroup>
{selection ? <col className="an-data-table__col-selection" /> : null}
{insertAtIndex(
columnSpecs.map((spec) => (
<col
key={spec.id}
style={resolvedWidths[spec.id] ? { width: `${resolvedWidths[spec.id]}px` } : undefined}
/>
)),
spacerInsertIndex,
hasSpacer ? (
<col
key="__an_spacer"
className="an-data-table__col-spacer"
style={{ width: `${spacerWidth}px` }}
/>
) : null,
)}
</colgroup>
<thead>
{table.getHeaderGroups().map((headerGroup) => (
{headerGroups.map((headerGroup) => (
<tr key={headerGroup.id}>
{selection ? (
<th className="an-data-table__selection-cell">
@@ -86,32 +601,82 @@ export function DataTable<TData>({
/>
</th>
) : null}
{headerGroup.headers.map((header) => {
const sorted = header.column.getIsSorted()
const stickyEnd = header.column.id === 'actions' || header.column.id === 'action'
return (
<th key={header.id} style={{ width: header.getSize() }} data-column-id={header.column.id} data-sticky-end={stickyEnd || undefined}>
{header.isPlaceholder ? null : (
<button
type="button"
className="an-data-table__sort"
disabled={!header.column.getCanSort()}
onClick={header.column.getToggleSortingHandler()}
>
{flexRender(header.column.columnDef.header, header.getContext())}
{header.column.getCanSort() ? (
sorted === 'asc' ? <ArrowUp size={14} /> : sorted === 'desc' ? <ArrowDown size={14} /> : <ChevronsUpDown size={14} />
) : null}
</button>
)}
</th>
)
})}
{insertAtIndex(
headerGroup.headers.map((header, index) => {
const sorted = header.column.getIsSorted()
const stickyEnd = header.column.id === 'actions' || header.column.id === 'action'
const spec = columnSpecs[index]
const colWidth = resolvedWidths[header.column.id]
const isResizable = Boolean(spec?.resizable) && index !== lastDataColumnIndex
const isResizing = resizingColumnId === header.column.id
const rawHeaderLabel =
typeof header.column.columnDef.header === 'string'
? header.column.columnDef.header
: header.column.id
const headerLabel = translateLegacyAdminText(rawHeaderLabel, currentLocale)
return (
<th
key={header.id}
style={colWidth ? { width: `${colWidth}px` } : undefined}
data-column-id={header.column.id}
data-sticky-start={index === 0 ? 'true' : undefined}
data-sticky-end={stickyEnd || undefined}
data-resizable={isResizable || undefined}
data-resizing={isResizing || undefined}
>
{header.isPlaceholder ? null : (
<button
type="button"
className="an-data-table__sort"
disabled={!header.column.getCanSort()}
onClick={header.column.getToggleSortingHandler()}
>
<span className="an-data-table__header-label">
{flexRender(header.column.columnDef.header, header.getContext())}
</span>
{header.column.getCanSort() ? (
sorted === 'asc' ? <ArrowUp size={14} /> : sorted === 'desc' ? <ArrowDown size={14} /> : <ChevronsUpDown size={14} />
) : null}
</button>
)}
{isResizable && spec ? (
<span
role="separator"
aria-orientation="vertical"
aria-label={t('common.resizeColumn', { column: headerLabel })}
title={t('common.resizeColumnHint')}
tabIndex={0}
className={`an-data-table__resizer${isResizing ? ' is-resizing' : ''}`}
onPointerDown={(event) => startColumnResize(spec, event)}
onDoubleClick={(event) => {
event.preventDefault()
event.stopPropagation()
manualWidthsRef.current = {}
setManualWidths({})
writeStoredColumnWidths(storageKeyRef.current, {})
}}
onClick={(event) => event.stopPropagation()}
onKeyDown={(event) => handleResizerKeyDown(spec, event)}
/>
) : null}
</th>
)
}),
spacerInsertIndex,
hasSpacer ? (
<th
key="__an_spacer"
className="an-data-table__spacer-cell"
style={{ width: `${spacerWidth}px` }}
aria-hidden="true"
/>
) : null,
)}
</tr>
))}
</thead>
<tbody>
{loading ? (
<tbody data-refreshing={isRefreshing ? 'true' : undefined}>
{isInitialLoading ? (
<tr>
<td colSpan={columnCount}>
<div className="an-data-table__state">
@@ -120,8 +685,8 @@ export function DataTable<TData>({
</div>
</td>
</tr>
) : table.getRowModel().rows.length > 0 ? (
table.getRowModel().rows.map((row) => (
) : renderedRows.length > 0 ? (
renderedRows.map((row) => (
<tr
key={row.id}
className={getRowClassName?.(row.original)}
@@ -141,11 +706,25 @@ export function DataTable<TData>({
/>
</td>
) : null}
{row.getVisibleCells().map((cell) => (
<td key={cell.id} data-column-id={cell.column.id} data-sticky-end={cell.column.id === 'actions' || cell.column.id === 'action' || undefined}>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</td>
))}
{insertAtIndex(
row.getVisibleCells().map((cell, cellIndex) => {
const rendered = flexRender(cell.column.columnDef.cell, cell.getContext())
return (
<td
key={cell.id}
data-column-id={cell.column.id}
data-sticky-start={cellIndex === 0 ? 'true' : undefined}
data-sticky-end={cell.column.id === 'actions' || cell.column.id === 'action' || undefined}
>
{NO_MARQUEE_COLUMN_IDS.has(cell.column.id) ? rendered : (
<TableCellMarquee>{rendered}</TableCellMarquee>
)}
</td>
)
}),
spacerInsertIndex,
hasSpacer ? <td key="__an_spacer" className="an-data-table__spacer-cell" aria-hidden="true" /> : null,
)}
</tr>
))
) : (
@@ -159,37 +738,7 @@ export function DataTable<TData>({
</table>
</div>
</TableScrollRegion>
{footer ? <div className="an-data-table__footer">{footer}</div> : null}
</div>
)
}
export function DataTablePager({
page,
pageSize,
total,
onPageChange,
}: {
page: number
pageSize: number
total: number
onPageChange: (page: number) => void
}) {
const { t } = useTranslation()
const totalPages = Math.max(1, Math.ceil(total / pageSize))
return (
<div className="an-data-table__pager">
<span>
{t('common.page', { page, totalPages, total: total.toLocaleString() })}
</span>
<div className="an-data-table__pager-actions">
<Button size="sm" variant="subtle" disabled={page <= 1} onClick={() => onPageChange(page - 1)}>
{t('common.previousPage')}
</Button>
<Button size="sm" variant="subtle" disabled={page >= totalPages} onClick={() => onPageChange(page + 1)}>
{t('common.nextPage')}
</Button>
</div>
{footerNode ? <div className="an-data-table__footer">{footerNode}</div> : null}
</div>
)
}
@@ -0,0 +1,91 @@
import { useCallback, useRef, useState, type CSSProperties, type ReactNode } from 'react'
export interface MarqueeMetrics {
overflows: boolean
distancePx: number
durationSec: number
}
const MIN_DURATION_SEC = 2.6
const MAX_DURATION_SEC = 12
const BASE_PAUSE_SEC = 1.8
const SPEED_PX_PER_SEC = 42
const EXTRA_TAIL_PADDING_PX = 12
export function computeMarqueeMetrics(contentWidth: number, clipWidth: number): MarqueeMetrics {
if (!Number.isFinite(contentWidth) || !Number.isFinite(clipWidth) || clipWidth <= 0) {
return { overflows: false, distancePx: 0, durationSec: 0 }
}
const delta = contentWidth - clipWidth
if (delta <= 1) {
return { overflows: false, distancePx: 0, durationSec: 0 }
}
const distancePx = Math.ceil(delta) + EXTRA_TAIL_PADDING_PX
const durationSec = Math.min(
MAX_DURATION_SEC,
Math.max(MIN_DURATION_SEC, Number((Math.ceil(delta) / SPEED_PX_PER_SEC + BASE_PAUSE_SEC).toFixed(2))),
)
return { overflows: true, distancePx, durationSec }
}
function measureTrackContentWidth(track: HTMLElement): number {
let maxWidth = track.scrollWidth
let cursor: Element | null = track.firstElementChild
for (let depth = 0; depth < 2 && cursor instanceof HTMLElement; depth += 1) {
maxWidth = Math.max(maxWidth, cursor.scrollWidth)
cursor = cursor.firstElementChild
}
return maxWidth
}
export function TableCellMarquee({
children,
className = '',
}: {
children: ReactNode
className?: string
}) {
const clipRef = useRef<HTMLDivElement | null>(null)
const trackRef = useRef<HTMLSpanElement | null>(null)
const [marqueeStyle, setMarqueeStyle] = useState<CSSProperties | undefined>(undefined)
const [overflowing, setOverflowing] = useState(false)
const startMarquee = useCallback(() => {
const clip = clipRef.current
const track = trackRef.current
if (!clip || !track) return
const metrics = computeMarqueeMetrics(measureTrackContentWidth(track), clip.clientWidth)
if (!metrics.overflows) {
setOverflowing(false)
setMarqueeStyle(undefined)
return
}
setMarqueeStyle({
'--an-marquee-distance': `${metrics.distancePx}px`,
'--an-marquee-duration': `${metrics.durationSec}s`,
} as CSSProperties)
setOverflowing(true)
}, [])
const stopMarquee = useCallback(() => {
setOverflowing(false)
setMarqueeStyle(undefined)
}, [])
return (
<div
ref={clipRef}
className={`an-cell-marquee${overflowing ? ' is-marquee' : ''}${className ? ` ${className}` : ''}`}
data-overflow={overflowing ? 'true' : undefined}
style={marqueeStyle}
onMouseEnter={startMarquee}
onMouseLeave={stopMarquee}
onFocus={startMarquee}
onBlur={stopMarquee}
>
<span ref={trackRef} className="an-cell-marquee__track">
{children}
</span>
</div>
)
}
@@ -0,0 +1,257 @@
export const DEFAULT_COLUMN_MIN_WIDTH = 72
export const DEFAULT_COLUMN_MAX_WIDTH = 720
export const DEFAULT_COLUMN_BASE_WIDTH = 150
export const SELECTION_COLUMN_WIDTH = 40
export const FIXED_UTILITY_COLUMN_IDS = new Set([
'actions',
'action',
'schedule',
])
export function findLastDataColumnIndex(columns: ReadonlyArray<{ id: string }>): number {
for (let i = columns.length - 1; i >= 0; i -= 1) {
if (columns[i].id !== 'actions' && columns[i].id !== 'action') {
return i
}
}
return -1
}
export interface ColumnWidthSpec {
id: string
baseWidth: number
minWidth: number
maxWidth: number
resizable: boolean
}
export function clampColumnWidth(value: number, minWidth = DEFAULT_COLUMN_MIN_WIDTH, maxWidth = DEFAULT_COLUMN_MAX_WIDTH): number {
const safeMin = Math.max(40, Math.round(minWidth))
const safeMax = Math.max(safeMin, Math.round(maxWidth))
if (!Number.isFinite(value)) return safeMin
return Math.min(safeMax, Math.max(safeMin, Math.round(value)))
}
const CJK_OR_FULLWIDTH_RE = /[\u2e80-\u9fff\uf900-\ufaff\uff00-\uffef]/
export function estimateHeaderMinWidth(
label: string,
options?: { sortable?: boolean; resizable?: boolean },
): number {
const trimmed = label.trim()
let textWidth = 0
for (const ch of trimmed) {
textWidth += CJK_OR_FULLWIDTH_RE.test(ch) ? 13 : 7.5
}
const padLeft = 12
const padRight = options?.resizable ? 20 : 12
const sortSpace = options?.sortable ? 20 : 0
const clearance = 6
return Math.max(DEFAULT_COLUMN_MIN_WIDTH, Math.ceil(padLeft + textWidth + sortSpace + padRight + clearance))
}
export function computeColumnWidths({
columns,
viewportWidth,
selectionWidth = 0,
manualWidths = {},
}: {
columns: ColumnWidthSpec[]
viewportWidth: number
selectionWidth?: number
manualWidths?: Record<string, number>
}): { widths: Record<string, number>; spacerWidth: number; tableWidth: number } {
const widths: Record<string, number> = {}
if (columns.length === 0) {
return { widths, spacerWidth: 0, tableWidth: selectionWidth }
}
const targetViewportWidth = Math.max(0, Math.floor(viewportWidth))
const hasManualWidths = Object.keys(manualWidths).length > 0
if (hasManualWidths) {
let contentTotal = selectionWidth
for (const col of columns) {
const requested = manualWidths[col.id] ?? col.baseWidth
const clamped = clampColumnWidth(requested, col.minWidth, col.maxWidth)
widths[col.id] = clamped
contentTotal += clamped
}
const spacerWidth = targetViewportWidth > contentTotal ? targetViewportWidth - contentTotal : 0
return { widths, spacerWidth, tableWidth: contentTotal + spacerWidth }
}
let baseTotal = 0
for (const col of columns) {
const base = clampColumnWidth(col.baseWidth, col.minWidth, col.maxWidth)
widths[col.id] = base
baseTotal += base
}
const targetColumnsWidth = Math.max(0, targetViewportWidth - selectionWidth)
if (targetColumnsWidth <= 0 || baseTotal >= targetColumnsWidth) {
return { widths, spacerWidth: 0, tableWidth: selectionWidth + baseTotal }
}
let surplus = targetColumnsWidth - baseTotal
const primaryElastic = columns.filter(
(col) => col.resizable && !FIXED_UTILITY_COLUMN_IDS.has(col.id) && widths[col.id] < col.maxWidth,
)
let pool = primaryElastic.length > 0
? primaryElastic
: columns.filter((col) => widths[col.id] < col.maxWidth)
// Distribute extra viewport width proportionally so wide viewports never leave a single bloated column.
while (surplus > 0 && pool.length > 0) {
const weightSum = pool.reduce((acc, col) => acc + Math.max(1, widths[col.id]), 0)
if (weightSum <= 0) break
let distributed = 0
const nextPool: ColumnWidthSpec[] = []
for (const col of pool) {
const room = col.maxWidth - widths[col.id]
if (room <= 0) continue
const share = Math.floor((surplus * Math.max(1, widths[col.id])) / weightSum)
const gain = Math.min(room, share)
if (gain > 0) {
widths[col.id] += gain
distributed += gain
}
if (widths[col.id] < col.maxWidth) {
nextPool.push(col)
}
}
surplus -= distributed
if (surplus > 0 && nextPool.length > 0) {
// Absorb integer rounding remainder across widest elastic columns with remaining headroom.
const ordered = [...nextPool].sort((a, b) => widths[b.id] - widths[a.id])
let remainderAdded = 0
for (const col of ordered) {
if (surplus <= 0) break
if (widths[col.id] < col.maxWidth) {
widths[col.id] += 1
surplus -= 1
remainderAdded += 1
}
}
if (distributed === 0 && remainderAdded === 0) break
}
pool = nextPool.filter((col) => widths[col.id] < col.maxWidth)
}
const finalSum = columns.reduce((acc, col) => acc + widths[col.id], selectionWidth)
const spacerWidth = targetViewportWidth > finalSum ? targetViewportWidth - finalSum : 0
return { widths, spacerWidth, tableWidth: finalSum + spacerWidth }
}
export function doesViewportChangeAffectColumns({
columns,
selectionWidth = 0,
manualWidths = {},
prevViewportWidth,
nextViewportWidth,
}: {
columns: ColumnWidthSpec[]
selectionWidth?: number
manualWidths?: Record<string, number>
prevViewportWidth: number
nextViewportWidth: number
}): boolean {
const prev = Math.max(0, Math.floor(prevViewportWidth))
const next = Math.max(0, Math.floor(nextViewportWidth))
if (prev === next) return false
const hasManualWidths = Object.keys(manualWidths).length > 0
let minFullWidth = selectionWidth
for (const col of columns) {
const requested = hasManualWidths ? (manualWidths[col.id] ?? col.baseWidth) : col.baseWidth
minFullWidth += clampColumnWidth(requested, col.minWidth, col.maxWidth)
}
if (prev <= minFullWidth && next <= minFullWidth) {
return false
}
return true
}
export function shouldLoadMoreWaterfall({
scrollTop,
clientHeight,
scrollHeight,
thresholdPx = 160,
hasMore,
loading,
loadingMore,
}: {
scrollTop: number
clientHeight: number
scrollHeight: number
thresholdPx?: number
hasMore: boolean
loading: boolean
loadingMore: boolean
}): boolean {
if (!hasMore || loading || loadingMore) return false
if (clientHeight <= 0 || scrollHeight <= 0) return false
return scrollTop + clientHeight >= scrollHeight - thresholdPx
}
export function dedupeAppendRows<T>(existing: T[], incoming: T[], getKey: (row: T) => string): T[] {
if (incoming.length === 0) return existing
const seen = new Set(existing.map(getKey))
const next = [...existing]
for (const row of incoming) {
const key = getKey(row)
if (seen.has(key)) continue
seen.add(key)
next.push(row)
}
return next
}
export function readStoredColumnWidths(
storageKey: string | undefined,
validColumnIds: readonly string[],
): Record<string, number> {
if (!storageKey || typeof window === 'undefined' || !window.localStorage) {
return {}
}
const allowed = new Set(validColumnIds)
try {
const raw = window.localStorage.getItem(storageKey)
if (!raw) return {}
const parsed = JSON.parse(raw) as unknown
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return {}
const next: Record<string, number> = {}
for (const [key, val] of Object.entries(parsed as Record<string, unknown>)) {
if (allowed.size > 0 && !allowed.has(key)) continue
if (typeof val === 'number' && Number.isFinite(val) && val > 0) {
next[key] = Math.round(val)
}
}
return next
} catch {
return {}
}
}
export function writeStoredColumnWidths(
storageKey: string | undefined,
widths: Record<string, number>,
): void {
if (!storageKey || typeof window === 'undefined' || !window.localStorage) return
try {
const entries = Object.entries(widths).filter(
([, val]) => typeof val === 'number' && Number.isFinite(val) && val > 0,
)
if (entries.length === 0) {
window.localStorage.removeItem(storageKey)
return
}
window.localStorage.setItem(storageKey, JSON.stringify(Object.fromEntries(entries)))
} catch {
// Ignore storage quota or private browsing errors.
}
}
@@ -0,0 +1,127 @@
import { useCallback, useEffect, useRef, useState } from 'react'
import { dedupeAppendRows } from './tableLayout'
export interface WaterfallPageResult<TRow, TMeta> {
rows: TRow[]
total: number
meta: TMeta
}
export function useWaterfallQuery<TRow, TMeta>({
fetchPage,
getRowKey,
deps,
enabled = true,
pageSize = 30,
onError,
}: {
fetchPage: (page: number, pageSize: number) => Promise<WaterfallPageResult<TRow, TMeta>>
getRowKey: (row: TRow, index: number) => string
deps: readonly unknown[]
enabled?: boolean
pageSize?: number
onError?: (error: unknown) => void
}) {
const [items, setItems] = useState<TRow[]>([])
const [total, setTotal] = useState(0)
const [meta, setMeta] = useState<TMeta | null>(null)
const [hasMore, setHasMore] = useState(false)
const [loading, setLoading] = useState(false)
const [loadingMore, setLoadingMore] = useState(false)
const itemsRef = useRef<TRow[]>([])
const pageRef = useRef(1)
const hasMoreRef = useRef(false)
const loadingRef = useRef(false)
const loadingMoreRef = useRef(false)
const requestSeqRef = useRef(0)
const fetchPageRef = useRef(fetchPage)
const getRowKeyRef = useRef(getRowKey)
const onErrorRef = useRef(onError)
fetchPageRef.current = fetchPage
getRowKeyRef.current = getRowKey
onErrorRef.current = onError
const runInitialLoad = useCallback(async () => {
if (!enabled) return
const seq = ++requestSeqRef.current
loadingRef.current = true
loadingMoreRef.current = false
setLoading(true)
setLoadingMore(false)
try {
const result = await fetchPageRef.current(1, pageSize)
if (seq !== requestSeqRef.current) return
let idx = 0
const nextRows = dedupeAppendRows([], result.rows, (row) => getRowKeyRef.current(row, idx++))
const nextHasMore = nextRows.length > 0 && nextRows.length < result.total
itemsRef.current = nextRows
pageRef.current = 1
hasMoreRef.current = nextHasMore
setItems(nextRows)
setTotal(result.total)
setMeta(result.meta)
setHasMore(nextHasMore)
} catch (error) {
if (seq !== requestSeqRef.current) return
onErrorRef.current?.(error)
} finally {
if (seq === requestSeqRef.current) {
loadingRef.current = false
setLoading(false)
}
}
}, [enabled, pageSize])
const loadMore = useCallback(async () => {
if (!enabled || !hasMoreRef.current || loadingRef.current || loadingMoreRef.current) return
const seq = requestSeqRef.current
const nextPage = pageRef.current + 1
loadingMoreRef.current = true
setLoadingMore(true)
try {
const result = await fetchPageRef.current(nextPage, pageSize)
if (seq !== requestSeqRef.current) return
let idx = itemsRef.current.length
const merged = dedupeAppendRows(
itemsRef.current,
result.rows,
(row) => getRowKeyRef.current(row, idx++),
)
const nextHasMore = result.rows.length > 0 && merged.length < result.total
itemsRef.current = merged
pageRef.current = nextPage
hasMoreRef.current = nextHasMore
setItems(merged)
setTotal(result.total)
setMeta(result.meta)
setHasMore(nextHasMore)
} catch (error) {
if (seq !== requestSeqRef.current) return
onErrorRef.current?.(error)
} finally {
if (seq === requestSeqRef.current) {
loadingMoreRef.current = false
setLoadingMore(false)
}
}
}, [enabled, pageSize])
useEffect(() => {
void runInitialLoad()
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [enabled, pageSize, ...deps])
return {
items,
total,
meta,
loading,
loadingMore,
hasMore,
reload: runInitialLoad,
loadMore,
}
}
@@ -0,0 +1,206 @@
import {
useCallback,
useEffect,
useRef,
useState,
type KeyboardEvent as ReactKeyboardEvent,
type PointerEvent as ReactPointerEvent,
type RefObject,
} from 'react'
const RESIZE_KEYBOARD_STEP_PX = 20
export const SPLIT_RESIZE_END_EVENT = 'planet:split-resize-end'
export function clampSplitPaneWidth(
value: number,
minWidth: number,
maxWidth: number,
containerWidth?: number,
minOppositeWidth = 320,
): number {
const safeValue = Number.isFinite(value) ? value : minWidth
const dynamicMax =
Number.isFinite(containerWidth) && (containerWidth as number) > 0
? Math.min(maxWidth, Math.max(minWidth, (containerWidth as number) - minOppositeWidth))
: maxWidth
return Math.min(dynamicMax, Math.max(minWidth, Math.round(safeValue)))
}
export function readStoredSplitWidth(
storageKey: string,
fallback: number,
minWidth: number,
maxWidth: number,
): number {
try {
const raw = window.localStorage.getItem(storageKey)
const parsed = raw ? Number(raw) : NaN
if (Number.isFinite(parsed)) {
return clampSplitPaneWidth(parsed, minWidth, maxWidth)
}
} catch {
// ignore storage failures
}
return clampSplitPaneWidth(fallback, minWidth, maxWidth)
}
export function writeStoredSplitWidth(storageKey: string, width: number): void {
try {
window.localStorage.setItem(storageKey, String(Math.round(width)))
} catch {
// ignore storage failures
}
}
export function useSplitPaneResize({
storageKey,
defaultWidth,
minWidth,
maxWidth,
minOppositeWidth = 320,
side = 'left',
containerRef,
cssVarName,
}: {
storageKey: string
defaultWidth: number
minWidth: number
maxWidth: number
minOppositeWidth?: number
side?: 'left' | 'right'
containerRef?: RefObject<HTMLElement | null>
cssVarName?: string
}) {
const [width, setWidth] = useState<number>(() =>
readStoredSplitWidth(storageKey, defaultWidth, minWidth, maxWidth),
)
const [isDragging, setIsDragging] = useState(false)
const dragCleanupRef = useRef<(() => void) | null>(null)
useEffect(() => {
setWidth(readStoredSplitWidth(storageKey, defaultWidth, minWidth, maxWidth))
}, [defaultWidth, maxWidth, minWidth, storageKey])
useEffect(() => () => {
dragCleanupRef.current?.()
}, [])
const onPointerDown = useCallback(
(event: ReactPointerEvent<HTMLButtonElement>) => {
event.preventDefault()
dragCleanupRef.current?.()
const startX = event.clientX
const startWidth = width
let latestWidth = startWidth
let rafId = 0
const resolveContainerWidth = () =>
containerRef?.current?.clientWidth || window.innerWidth
const applyWidthFrame = () => {
rafId = 0
if (cssVarName && containerRef?.current) {
containerRef.current.style.setProperty(cssVarName, `${latestWidth}px`)
} else {
setWidth(latestWidth)
}
}
const handleMove = (moveEvent: PointerEvent) => {
const delta = moveEvent.clientX - startX
const rawWidth = side === 'left' ? startWidth + delta : startWidth - delta
latestWidth = clampSplitPaneWidth(
rawWidth,
minWidth,
maxWidth,
resolveContainerWidth(),
minOppositeWidth,
)
if (!rafId) {
rafId = window.requestAnimationFrame(applyWidthFrame)
}
}
const cleanupListeners = () => {
if (rafId) {
window.cancelAnimationFrame(rafId)
rafId = 0
}
document.body.classList.remove('an-is-resizing')
window.removeEventListener('pointermove', handleMove)
window.removeEventListener('pointerup', stopMove)
window.removeEventListener('pointercancel', stopMove)
dragCleanupRef.current = null
}
const stopMove = () => {
cleanupListeners()
if (cssVarName && containerRef?.current) {
containerRef.current.style.setProperty(cssVarName, `${latestWidth}px`)
}
setIsDragging(false)
setWidth(latestWidth)
writeStoredSplitWidth(storageKey, latestWidth)
window.dispatchEvent(new Event(SPLIT_RESIZE_END_EVENT))
}
dragCleanupRef.current = cleanupListeners
setIsDragging(true)
document.body.classList.add('an-is-resizing')
window.addEventListener('pointermove', handleMove)
window.addEventListener('pointerup', stopMove, { once: true })
window.addEventListener('pointercancel', stopMove, { once: true })
},
[containerRef, cssVarName, maxWidth, minOppositeWidth, minWidth, side, storageKey, width],
)
const onKeyDown = useCallback(
(event: ReactKeyboardEvent<HTMLButtonElement>) => {
let step = 0
if (event.key === 'ArrowLeft') step = side === 'left' ? -RESIZE_KEYBOARD_STEP_PX : RESIZE_KEYBOARD_STEP_PX
else if (event.key === 'ArrowRight') step = side === 'left' ? RESIZE_KEYBOARD_STEP_PX : -RESIZE_KEYBOARD_STEP_PX
else if (event.key === 'Home') step = Number.NEGATIVE_INFINITY
else if (event.key === 'End') step = Number.POSITIVE_INFINITY
else return
event.preventDefault()
const containerW = containerRef?.current?.clientWidth || window.innerWidth
const next =
step === Number.NEGATIVE_INFINITY || step === Number.POSITIVE_INFINITY
? clampSplitPaneWidth(defaultWidth, minWidth, maxWidth, containerW, minOppositeWidth)
: clampSplitPaneWidth(width + step, minWidth, maxWidth, containerW, minOppositeWidth)
setWidth(next)
writeStoredSplitWidth(storageKey, next)
},
[containerRef, defaultWidth, maxWidth, minOppositeWidth, minWidth, side, storageKey, width],
)
return { width, isDragging, onPointerDown, onKeyDown }
}
export function SplitPaneResizer({
label,
isDragging = false,
onPointerDown,
onKeyDown,
className = '',
}: {
label: string
isDragging?: boolean
onPointerDown: (event: ReactPointerEvent<HTMLButtonElement>) => void
onKeyDown?: (event: ReactKeyboardEvent<HTMLButtonElement>) => void
className?: string
}) {
return (
<button
type="button"
role="separator"
aria-orientation="vertical"
aria-label={label}
title={label}
className={`an-detail-resizer${isDragging ? ' is-dragging' : ''}${className ? ` ${className}` : ''}`}
onPointerDown={onPointerDown}
onKeyDown={onKeyDown}
/>
)
}
+2 -2
View File
@@ -33,8 +33,8 @@ export function Select({ value, onValueChange, options, placeholder, disabled, c
<span className="an-select__value">
<SelectPrimitive.Value placeholder={placeholder} />
</span>
<SelectPrimitive.Icon>
<ChevronDown size={16} />
<SelectPrimitive.Icon className="an-select__icon">
<ChevronDown size={16} aria-hidden="true" />
</SelectPrimitive.Icon>
</SelectPrimitive.Trigger>
<SelectPrimitive.Portal>
@@ -0,0 +1,44 @@
import { forwardRef, type ButtonHTMLAttributes } from 'react'
import type { TactileIconValue } from '../../../components/tactile-ui'
import { Button } from './button'
export type TableActionTone = 'default' | 'danger' | 'stop'
export interface TableActionButtonProps
extends Omit<ButtonHTMLAttributes<HTMLButtonElement>, 'size' | 'title'> {
'aria-label': string
icon?: TactileIconValue
loading?: boolean
title: string
tone?: TableActionTone
}
export const TableActionButton = forwardRef<HTMLElement, TableActionButtonProps>(
function TableActionButton(
{ 'aria-label': ariaLabel, className, icon, title, tone = 'default', ...props },
ref,
) {
const toneClass =
tone === 'danger'
? 'an-table-action--danger'
: tone === 'stop'
? 'an-table-action--stop'
: undefined
const composedClassName = ['an-table-action', toneClass, className].filter(Boolean).join(' ')
return (
<Button
ref={ref}
size="icon"
variant="ghost"
tactile={false}
icon={icon}
iconSize={14}
className={composedClassName}
aria-label={ariaLabel}
title={title}
{...props}
/>
)
},
)
@@ -0,0 +1,61 @@
import earthLogoUrl from '@earth-builtin-asset/brand/earth-logo.png'
import limLogoUrl from '@earth-builtin-asset/brand/lim-logo.png'
import titleEnUrl from '@earth-builtin-asset/brand/title-en.png'
import titleZhUrl from '@earth-builtin-asset/brand/title-zh.png'
import earthClouds2048Url from '@earth-builtin-asset/earth_clouds_2048.png'
export const DEFAULT_EARTH_BRAND_LOGO_PATH = '/earth/assets/brand/earth-logo.png'
export const DEFAULT_EARTH_BRAND_TITLE_ZH_PATH = '/earth/assets/brand/title-zh.png'
export const DEFAULT_EARTH_BRAND_TITLE_EN_PATH = '/earth/assets/brand/title-en.png'
export const DEFAULT_EARTH_ABOUT_LOGO_PATH = '/earth/assets/brand/lim-logo.png'
export const DEFAULT_EARTH_CLOUDS_PATH = '/earth/assets/earth_clouds_2048.png'
export const EARTH_BUILTIN_PREVIEW_ASSETS: Readonly<Record<string, string>> = {
[DEFAULT_EARTH_BRAND_LOGO_PATH]: earthLogoUrl,
[DEFAULT_EARTH_BRAND_TITLE_ZH_PATH]: titleZhUrl,
[DEFAULT_EARTH_BRAND_TITLE_EN_PATH]: titleEnUrl,
[DEFAULT_EARTH_ABOUT_LOGO_PATH]: limLogoUrl,
[DEFAULT_EARTH_CLOUDS_PATH]: earthClouds2048Url,
}
export function normalizeEarthBuiltinAssetKey(rawUrl: string): string | null {
const trimmed = rawUrl.trim()
if (!trimmed) return null
const withoutSuffix = trimmed.split(/[?#]/, 1)[0]
if (withoutSuffix.startsWith('/earth/assets/')) {
return withoutSuffix
}
if (withoutSuffix.startsWith('./assets/')) {
return `/earth/${withoutSuffix.slice(2)}`
}
if (withoutSuffix.startsWith('assets/')) {
return `/earth/${withoutSuffix}`
}
return null
}
/**
* Resolve built-in `/earth/assets/...` paths to Vite-bundled `/assets/...` URLs
* for Admin preview rendering while keeping persisted config values unchanged.
*/
export function resolveEarthPreviewAssetUrl(
rawUrl?: string | null,
fallbackPath?: string,
assetMap: Readonly<Record<string, string>> = EARTH_BUILTIN_PREVIEW_ASSETS,
): string {
const trimmed = String(rawUrl || '').trim()
if (!trimmed) {
return fallbackPath ? resolveEarthPreviewAssetUrl(fallbackPath, undefined, assetMap) : ''
}
const normalizedKey = normalizeEarthBuiltinAssetKey(trimmed)
if (normalizedKey && Object.prototype.hasOwnProperty.call(assetMap, normalizedKey)) {
return assetMap[normalizedKey]
}
if (fallbackPath && (trimmed.startsWith('./assets/') || trimmed.startsWith('assets/'))) {
return resolveEarthPreviewAssetUrl(fallbackPath, undefined, assetMap)
}
return trimmed
}
+78 -5
View File
@@ -602,6 +602,7 @@ export default function AdvisorWorkflows() {
const [inspectorWidth, setInspectorWidth] = useState<number>(() =>
readStoredWidth(WF_INSPECTOR_WIDTH_KEY, 396, 340, 560),
)
const [draggingResizer, setDraggingResizer] = useState<'rail' | 'inspector' | null>(null)
const [historyMeta, setHistoryMeta] = useState<{ canUndo: boolean; canRedo: boolean }>({
canUndo: false,
canRedo: false,
@@ -618,6 +619,8 @@ export default function AdvisorWorkflows() {
const [rollbackRev, setRollbackRev] = useState('')
const [guardrailsDraft, setGuardrailsDraft] = useState('{}')
const [guardrailsError, setGuardrailsError] = useState('')
const [paramsDraft, setParamsDraft] = useState('{}')
const [paramsError, setParamsError] = useState('')
const [evoPopoverOpen, setEvoPopoverOpen] = useState(false)
const [evoPolicy, setEvoPolicy] = useState<EvolutionPolicy | null>(null)
@@ -843,6 +846,8 @@ export default function AdvisorWorkflows() {
const targetNode = graphState.nodes.find((n) => n.id === selectedNodeId)
setGuardrailsDraft(JSON.stringify(targetNode?.guardrails || {}, null, 2))
setGuardrailsError('')
setParamsDraft(JSON.stringify(targetNode?.params || {}, null, 2))
setParamsError('')
// Intentionally sync only when node selection changes or a workflow snapshot reloads.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedNodeId, graphRevisionKey])
@@ -950,11 +955,13 @@ export default function AdvisorWorkflows() {
setRailWidth(latestWidth)
}
const stopMove = () => {
setDraggingResizer(null)
document.body.classList.remove('an-is-resizing')
window.removeEventListener('pointermove', handleMove)
window.removeEventListener('pointerup', stopMove)
writeStoredWidth(WF_RAIL_WIDTH_KEY, latestWidth)
}
setDraggingResizer('rail')
document.body.classList.add('an-is-resizing')
window.addEventListener('pointermove', handleMove)
window.addEventListener('pointerup', stopMove, { once: true })
@@ -972,11 +979,13 @@ export default function AdvisorWorkflows() {
setInspectorWidth(latestWidth)
}
const stopMove = () => {
setDraggingResizer(null)
document.body.classList.remove('an-is-resizing')
window.removeEventListener('pointermove', handleMove)
window.removeEventListener('pointerup', stopMove)
writeStoredWidth(WF_INSPECTOR_WIDTH_KEY, latestWidth)
}
setDraggingResizer('inspector')
document.body.classList.add('an-is-resizing')
window.addEventListener('pointermove', handleMove)
window.addEventListener('pointerup', stopMove, { once: true })
@@ -2516,7 +2525,7 @@ export default function AdvisorWorkflows() {
<button
type="button"
className="an-detail-resizer"
className={`an-detail-resizer${draggingResizer === 'rail' ? ' is-dragging' : ''}`}
onPointerDown={startRailResize}
aria-label={tx('拖拽调整左侧工作流目录宽度', 'Resize workflow catalog pane')}
title={tx('拖拽调整工作流目录宽度', 'Resize workflow catalog')}
@@ -2752,7 +2761,7 @@ export default function AdvisorWorkflows() {
<button
type="button"
className="an-detail-resizer"
className={`an-detail-resizer${draggingResizer === 'inspector' ? ' is-dragging' : ''}`}
onPointerDown={startInspectorResize}
aria-label={tx('拖拽调整右侧节点检查器宽度', 'Resize workflow inspector pane')}
title={tx('拖拽调整节点配置栏宽度', 'Resize inspector panel')}
@@ -2830,6 +2839,18 @@ export default function AdvisorWorkflows() {
onValueChange={(val) => handleUpdateSelectedEdge({ condition: val })}
options={[
{ value: 'always', label: tx('始终执行', 'Always run') },
{
value: 'on_field_equals',
label: tx('上游字段匹配 (field=a,b)', 'Upstream field equals'),
},
{
value: 'on_guardrail_passed',
label: tx('护栏校验通过时', 'Guardrail passed'),
},
{
value: 'on_guardrail_failed',
label: tx('护栏校验未通过时', 'Guardrail failed'),
},
{
value: 'on_empty_or_low_confidence',
label: tx(
@@ -2844,12 +2865,23 @@ export default function AdvisorWorkflows() {
'Match target entity type',
),
},
{ value: 'not_terminal', label: tx('非已知终态时', 'Not terminal') },
{ value: 'on_terminal', label: tx('命中终态缓存时', 'On cached terminal') },
{ value: 'high_confidence_hit', label: tx('知识库高置信度命中', 'Knowledge hit') },
{ value: 'fallback_to_agent', label: tx('未命中回退研判', 'Fallback to research') },
{ value: 'interactive', label: tx('仅前台交互触发', 'Interactive only') },
{ value: 'ingest', label: tx('仅后台采集触发', 'Background ingest only') },
]}
/>
</label>
{selectedEdge.condition === 'on_entity_type' ? (
{selectedEdge.condition === 'on_entity_type' ||
selectedEdge.condition === 'on_field_equals' ? (
<label className="an-field">
<span>{tx('目标类型列表(英文逗号分隔)', 'Entity Types (comma-separated)')}</span>
<span>
{selectedEdge.condition === 'on_field_equals'
? tx('字段匹配表达式(如 decision=need_followup)', 'Field expression (e.g. decision=need_followup)')
: tx('目标类型列表(英文逗号分隔)', 'Entity Types (comma-separated)')}
</span>
<input
type="text"
className="an-input"
@@ -2857,7 +2889,11 @@ export default function AdvisorWorkflows() {
onChange={(e) =>
handleUpdateSelectedEdge({ condition_value: e.target.value })
}
placeholder="cable,landing_point,vessel"
placeholder={
selectedEdge.condition === 'on_field_equals'
? 'decision=located'
: 'cable,landing_point,vessel'
}
/>
</label>
) : null}
@@ -3143,6 +3179,43 @@ export default function AdvisorWorkflows() {
</span>
) : null}
</label>
<label className="an-field">
<span>{tx('节点参数 / Output Schema(JSON)', 'Node Params / Output Schema (JSON)')}</span>
<textarea
className="an-advisor-textarea an-advisor-textarea--code"
value={paramsDraft}
onChange={(e) => {
const raw = e.target.value
setParamsDraft(raw)
try {
const parsed = JSON.parse(raw)
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
setParamsError('')
patchSelectedNode((n) => ({
...n,
params: parsed as Record<string, unknown>,
}))
} else {
setParamsError(
tx('节点参数必须为 JSON 对象', 'Node params must be a JSON object'),
)
}
} catch {
setParamsError(
tx(
'JSON 语法尚未完成,暂未同步到节点',
'Incomplete JSON syntax; node not updated yet',
),
)
}
}}
/>
{paramsError ? (
<span className="an-wf-pill an-wf-pill--warning">
{paramsError}
</span>
) : null}
</label>
<div className="an-context-card">
<span className="an-context-card__title">
{tx(
+121 -59
View File
@@ -1,11 +1,13 @@
import type { ColumnDef } from '@tanstack/react-table'
import { useCallback, useEffect, useMemo, useState } from 'react'
import axios from 'axios'
import { Ban, Check, Copy, Download, KeyRound, Plus, RefreshCw, Trash2 } from 'lucide-react'
import { describeApiError } from '../../i18n/api-errors'
import { useLocale } from '../../i18n/locale'
import Scrollbar from '../../components/Scrollbar/Scrollbar'
import { DataTable } from '../components/data-table/DataTable'
import { Badge } from '../components/ui/badge'
import { Button } from '../components/ui/button'
import { TableActionButton } from '../components/ui/table-action-button'
import { ConfirmDialog, Dialog } from '../components/ui/dialog'
import { Input } from '../components/ui/input'
import { Select } from '../components/ui/select'
@@ -93,13 +95,117 @@ export function ApiKeySettings({ active }: { active: boolean }) {
[availableScopes],
)
if (!active) return null
const formatDate = useCallback(
(iso: string | null) => {
if (!iso) return tr('永不过期', 'Never')
const parsed = new Date(iso)
return Number.isNaN(parsed.getTime()) ? iso : parsed.toLocaleString()
},
[tr],
)
const formatDate = (iso: string | null) => {
if (!iso) return tr('永不过期', 'Never')
const parsed = new Date(iso)
return Number.isNaN(parsed.getTime()) ? iso : parsed.toLocaleString()
}
const columns = useMemo<Array<ColumnDef<ApiKeyItem>>>(
() => [
{
accessorKey: 'name',
header: tr('名称', 'Name'),
size: 180,
minSize: 120,
cell: ({ row }) => <strong>{row.original.name}</strong>,
},
{
accessorKey: 'key_prefix',
header: tr('前缀', 'Prefix'),
size: 112,
minSize: 88,
cell: ({ row }) => <code>{row.original.key_prefix}</code>,
},
{
id: 'scopes',
header: tr('权限范围', 'Scopes'),
size: 210,
minSize: 120,
enableSorting: false,
cell: ({ row }) => (
<div className="an-inline-list">
{row.original.scopes.map((scope) => (
<Badge key={scope} tone={scope === 'earth:all_read' ? 'blue' : 'slate'}>{scope}</Badge>
))}
</div>
),
},
{
accessorKey: 'rate_limit_per_minute',
header: tr('限流', 'Rate Limit'),
size: 96,
minSize: 76,
cell: ({ row }) =>
row.original.rate_limit_per_minute ? `${row.original.rate_limit_per_minute}/min` : tr('不限流', 'Unlimited'),
},
{
accessorKey: 'expires_at',
header: tr('过期时间', 'Expires'),
size: 156,
minSize: 112,
cell: ({ row }) => formatDate(row.original.expires_at),
},
{
accessorKey: 'last_used_at',
header: tr('最近使用', 'Last Used'),
size: 156,
minSize: 112,
cell: ({ row }) => (row.original.last_used_at ? formatDate(row.original.last_used_at) : tr('未使用', 'Never')),
},
{
accessorKey: 'status',
header: tr('状态', 'Status'),
size: 92,
minSize: 76,
cell: ({ row }) => (
<Badge tone={row.original.status === 'active' ? 'green' : row.original.status === 'expired' ? 'amber' : 'red'}>
{row.original.status === 'active'
? tr('可用', 'Active')
: row.original.status === 'expired'
? tr('已过期', 'Expired')
: tr('已吊销', 'Revoked')}
</Badge>
),
},
{
id: 'actions',
header: tr('操作', 'Actions'),
size: 96,
minSize: 80,
enableSorting: false,
enableResizing: false,
cell: ({ row }) => (
<span className="an-table-actions">
{row.original.is_active ? (
<TableActionButton
tone="danger"
onClick={() => setConfirmTarget({ mode: 'revoke', item: row.original })}
title={tr('吊销', 'Revoke')}
aria-label={tr('吊销', 'Revoke')}
>
<Ban size={14} aria-hidden="true" />
</TableActionButton>
) : null}
<TableActionButton
tone="danger"
onClick={() => setConfirmTarget({ mode: 'delete', item: row.original })}
title={tr('删除', 'Delete')}
aria-label={tr('删除', 'Delete')}
>
<Trash2 size={14} aria-hidden="true" />
</TableActionButton>
</span>
),
},
],
[formatDate, tr],
)
if (!active) return null
const handleCreate = async () => {
const trimmed = name.trim()
@@ -205,58 +311,14 @@ export function ApiKeySettings({ active }: { active: boolean }) {
</div>
<div className="an-panel-body">
{items.length ? (
<Scrollbar className="an-table-wrap">
<table className="an-table">
<thead>
<tr>
<th>{tr('名称', 'Name')}</th>
<th>{tr('前缀', 'Prefix')}</th>
<th>{tr('权限范围', 'Scopes')}</th>
<th>{tr('限流', 'Rate Limit')}</th>
<th>{tr('过期时间', 'Expires')}</th>
<th>{tr('最近使用', 'Last Used')}</th>
<th>{tr('状态', 'Status')}</th>
<th>{tr('操作', 'Actions')}</th>
</tr>
</thead>
<tbody>
{items.map((item) => (
<tr key={item.id}>
<td><strong>{item.name}</strong></td>
<td><code>{item.key_prefix}</code></td>
<td>
<div className="an-inline-list">
{item.scopes.map((scope) => (
<Badge key={scope} tone={scope === 'earth:all_read' ? 'blue' : 'slate'}>{scope}</Badge>
))}
</div>
</td>
<td>{item.rate_limit_per_minute ? `${item.rate_limit_per_minute}/min` : tr('不限流', 'Unlimited')}</td>
<td>{formatDate(item.expires_at)}</td>
<td>{item.last_used_at ? formatDate(item.last_used_at) : tr('未使用', 'Never')}</td>
<td>
<Badge tone={item.status === 'active' ? 'green' : item.status === 'expired' ? 'amber' : 'red'}>
{item.status === 'active' ? tr('可用', 'Active') : item.status === 'expired' ? tr('已过期', 'Expired') : tr('已吊销', 'Revoked')}
</Badge>
</td>
<td>
<div className="an-row-actions">
{item.is_active ? (
<Button size="sm" variant="ghost" onClick={() => setConfirmTarget({ mode: 'revoke', item })}>
<Ban size={14} />{tr('吊销', 'Revoke')}
</Button>
) : null}
<Button size="sm" variant="ghost" className="is-danger" onClick={() => setConfirmTarget({ mode: 'delete', item })}>
<Trash2 size={14} />{tr('删除', 'Delete')}
</Button>
</div>
</td>
</tr>
))}
</tbody>
</table>
</Scrollbar>
{items.length || loading ? (
<DataTable
columns={columns}
data={items}
getRowId={(row) => String(row.id)}
loading={loading}
columnWidthStorageKey="planet.table.widths.api_keys"
/>
) : (
<EmptyState
title={tr('暂无 API 密钥', 'No API keys yet')}
+23 -1
View File
@@ -9,6 +9,7 @@ import { Input } from '../components/ui/input'
import { Select } from '../components/ui/select'
import { AdminSwitch } from '../components/ui/switch'
import { Panel } from '../patterns/patterns'
import { SplitPaneResizer, useSplitPaneResize } from '../components/layout/SplitPaneResizer'
import { CardImagePreview } from './CardImagePreview'
import { CARD_IMAGES_API, CARD_IMAGES_REVISION_KEY, imageRequestError, useImageTargets,
type EntityType, type MatchScope, type ImageAsset, type ImageRule,
@@ -36,6 +37,16 @@ export function CardImageSettings({active}:{active:boolean}) {
const [previewSearch,setPreviewSearch] = useState(''), [previewTarget,setPreviewTarget] = useState('')
const [resolution,setResolution] = useState<ImageResolution | null>(null)
const uploadRef = useRef<HTMLInputElement>(null), previewRevision = useRef(0)
const workspaceRef = useRef<HTMLFieldSetElement | null>(null)
const workspaceResize = useSplitPaneResize({
storageKey: 'planet.admin.cardImagesListWidth',
defaultWidth: 280,
minWidth: 200,
maxWidth: 480,
minOppositeWidth: 320,
side: 'left',
containerRef: workspaceRef,
})
const targets = useImageTargets(active && view === 'rules', entityType, scope, search)
const previewTargets = useImageTargets(active && view === 'rules', entityType, 'object', previewSearch)
const dirty = Boolean(saved && draft && JSON.stringify(saved.config) !== JSON.stringify(draft))
@@ -130,7 +141,12 @@ export function CardImageSettings({active}:{active:boolean}) {
</div>
{errorText?<p className="an-card-images-error" role="alert">{errorText}</p>:null}
{message?<p className="an-card-images-message" role="status">{message}</p>:null}
{!draft?<p className="an-card-images-message">{busy?t('加载中…','Loading…'):t('暂无可用配置','Configuration unavailable')}</p>:<fieldset disabled={busy} className="an-card-images-workspace">
{!draft?<p className="an-card-images-message">{busy?t('加载中…','Loading…'):t('暂无可用配置','Configuration unavailable')}</p>:<fieldset
ref={workspaceRef}
disabled={busy}
className="an-card-images-workspace"
style={{ '--an-card-images-list-width': `${workspaceResize.width}px` } as CSSProperties}
>
<Scrollbar className="an-card-images-list" axis="y">
{view==='assets'?<>
<div className="an-card-images-list-actions"><Button variant="subtle" disabled={busy} onClick={()=>uploadRef.current?.click()}><ImagePlus size={16}/>{t('上传','Upload')}</Button><Button size="icon" variant="subtle" title={t('添加图片地址','Add image URL')} aria-label={t('添加图片地址','Add image URL')} onClick={addUrl}><Plus size={16}/></Button></div>
@@ -143,6 +159,12 @@ export function CardImageSettings({active}:{active:boolean}) {
{draft.rules.map(rule=><div className="an-card-images-rule-row" key={rule.id}><button type="button" onClick={()=>selectRule(rule)}><span>{rule.label || rule.value}</span><small>{types.find(item=>item.value===rule.entity_type)?.label} · {scopes.find(item=>item.value===rule.scope)?.label}{!rule.enabled?` · ${t('停用','Disabled')}`:''}</small></button><Button size="icon" variant="subtle" title={t('解除关联','Remove assignment')} aria-label={t('解除关联','Remove assignment')} onClick={()=>{edit({...draft,rules:draft.rules.filter(item=>item.id!==rule.id)});if(editingRuleId===rule.id)setEditingRuleId(null)}}><Trash2 size={14}/></Button></div>)}
</>}
</Scrollbar>
<SplitPaneResizer
label={t('拖动调整列表宽度', 'Drag to resize list width')}
isDragging={workspaceResize.isDragging}
onPointerDown={workspaceResize.onPointerDown}
onKeyDown={workspaceResize.onKeyDown}
/>
<Scrollbar className="an-card-images-editor" axis="y">
{view==='assets' && asset?<>
<div className="an-card-images-fields">
@@ -1,5 +1,17 @@
import axios from 'axios'
import { Check, Download, Plus, RefreshCw, RotateCcw, Save, Sparkles, Trash2, X } from 'lucide-react'
import {
AlertTriangle,
Check,
Download,
History,
Plus,
RefreshCw,
RotateCcw,
Save,
Sparkles,
Trash2,
X,
} from 'lucide-react'
import { useCallback, useEffect, useRef, useState, type FormEvent, type ReactNode } from 'react'
import Scrollbar from '../../components/Scrollbar/Scrollbar'
import { useLocale } from '../../i18n/locale'
@@ -10,19 +22,27 @@ import { Select } from '../components/ui/select'
import { Panel } from '../patterns/patterns'
import {
applyApprovedCandidateToDraft,
APPROVE_REASON_OPTIONS,
COMPUTE_METRICS,
ensureCompleteConfiguration,
formatSourceOptionLabel,
hasMixedShareSourceRow,
normalizeDraftForPublish,
notifyComputeConfigurationChanged,
observationHasMixedSources,
reasonCodeLabel,
REJECT_REASON_OPTIONS,
reportIsUsed,
SHARE_METRICS,
sourceForObservation,
type CandidateReviewReasonCode,
type ComputeCandidateItem,
type ComputeConfiguration,
type ComputeConfigurationResponse,
type ComputeMetric,
type ComputeMilestoneEvent,
type ComputeObservation,
type ComputeRevisionSummary,
type ComputeStructureObservation,
type NationalComputeHub,
} from './compute-comparison-model'
@@ -30,9 +50,23 @@ import './compute-comparison.css'
const API_BASE = import.meta.env.VITE_API_URL || '/api/v1'
const ENDPOINT = `${API_BASE}/data-products/compute/configuration`
const REVISIONS_ENDPOINT = `${API_BASE}/data-products/compute/revisions`
const CANDIDATES_ENDPOINT = `${API_BASE}/situational-awareness/candidates`
type View = 'observations' | 'structures' | 'innovation' | 'milestones' | 'sources' | 'candidates'
type View = 'observations' | 'structures' | 'innovation' | 'milestones' | 'sources' | 'candidates' | 'revisions'
interface CandidateReviewDraft {
decision: 'approved' | 'rejected'
reasonCode: CandidateReviewReasonCode
reason: string
}
interface PeriodConflictState {
candidate: ComputeCandidateItem
existingPeriodLabel: string | null
candidatePeriodLabel: string | null
discardedCodes: string[]
}
function Field({ title, full = false, children }: { title: string; full?: boolean; children: ReactNode }) {
return <label className={`an-compute-field${full ? ' an-compute-field--full' : ''}`}><span>{title}</span>{children}</label>
@@ -49,6 +83,7 @@ function validationMessage(message: string, english: boolean) {
'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': '请使用国家观测,不能直接录入区域合计。',
'Per-country value_sources keys must be a subset of observation values': '逐国来源只能引用该行中存在的国家代码。',
'Use a report URL without credentials (maximum 2000 characters)': '报告链接不能包含账号密码,长度不能超过 2000 字符。',
'Structure scope must be GLOBAL or a canonical country code': '算力结构范围必须为全球或标准国家代码。',
'Internal compute structure shares must total 100 percent': '智能算力与通用/超算占比之和必须等于 100%。',
@@ -64,9 +99,13 @@ function validationMessage(message: string, english: boolean) {
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.'
: '配置已被其他人更新。当前草稿已保留,请核对后重新加载再保存。'
if (error.response?.status === 409) {
const detail = error.response?.data?.detail
if (typeof detail === 'string' && detail.includes('Candidate')) return detail
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', 'structures', 'milestones', 'national_hubs'].includes(String(value)))
@@ -81,12 +120,19 @@ function requestError(error: unknown, english: boolean) {
}
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(';')
return `${location}${row}${location ? (english ? ': ' : ':') : ''}${validationMessage(item.msg || '', english)}`
}).join(english ? '; ' : ';')
if (error.response?.status === 403) return english ? 'Administrator access required.' : '仅管理员可以维护算力对比数据。'
return typeof detail === 'string' ? detail : error.message
}
function formatDateTime(raw: string | null | undefined): string {
if (!raw) return '—'
const d = new Date(raw)
if (Number.isNaN(d.getTime())) return raw
return d.toLocaleString()
}
export function ComputeComparisonSettings({ active }: { active: boolean }) {
const { locale } = useLocale()
const english = locale === 'en-US'
@@ -98,23 +144,35 @@ export function ComputeComparisonSettings({ active }: { active: boolean }) {
const [error, setError] = useState('')
const [message, setMessage] = useState('')
const [confirmation, setConfirmation] = useState<'reset' | 'reload' | null>(null)
const [periodConflict, setPeriodConflict] = useState<PeriodConflictState | null>(null)
const [loadRevision, setLoadRevision] = useState(0)
const [publishNote, setPublishNote] = useState('')
const [pendingCandidateIds, setPendingCandidateIds] = useState<number[]>([])
const [candidates, setCandidates] = useState<ComputeCandidateItem[]>([])
const [candidateBusy, setCandidateBusy] = useState(false)
const [reviewDrafts, setReviewDrafts] = useState<Record<number, CandidateReviewDraft>>({})
const [extractYear, setExtractYear] = useState<number>(2025)
const [extractSourceId, setExtractSourceId] = useState('caict-extract-2025')
const [extractSourceTitle, setExtractSourceTitle] = useState('CAICT Compute Index Excerpt (2025)')
const [extractSourceUrl, setExtractSourceUrl] = useState('https://www.caict.ac.cn/')
const [extractPublisher, setExtractPublisher] = useState('CAICT')
const [extractLocator, setExtractLocator] = useState('Section 2, Figure 4')
const [extractReportYear, setExtractReportYear] = useState<number>(2026)
const [extractPeriodLabel, setExtractPeriodLabel] = useState('')
const [extractPublishedAt, setExtractPublishedAt] = useState('')
const [extractSourceId, setExtractSourceId] = useState('epoch-chip-imports-2026-11')
const [extractSourceTitle, setExtractSourceTitle] = useState('Epoch AI: Data on AI Chip Imports (2026-11-12 Revision)')
const [extractSourceUrl, setExtractSourceUrl] = useState('https://epoch.ai/data/ai-chip-imports-documentation/changelog')
const [extractPublisher, setExtractPublisher] = useState('Epoch AI')
const [extractLocator, setExtractLocator] = useState('Changelog (2026-11-12)')
const [extractExcerpt, setExtractExcerpt] = useState('')
const [revisions, setRevisions] = useState<ComputeRevisionSummary[]>([])
const [revisionsBusy, setRevisionsBusy] = useState(false)
const viewportRef = useRef<HTMLDivElement>(null)
const dirty = Boolean(
draft && saved
&& JSON.stringify(normalizeDraftForPublish(draft)) !== JSON.stringify(normalizeDraftForPublish(saved.config)),
)
const requiresMixedShareNote = Boolean(draft && hasMixedShareSourceRow(draft))
useEffect(() => {
viewportRef.current?.scrollTo({ top: 0 })
@@ -129,6 +187,7 @@ export function ComputeComparisonSettings({ active }: { active: boolean }) {
const normalized = ensureCompleteConfiguration(data.config)
setSaved({ ...data, config: normalized })
setDraft(normalized)
setPendingCandidateIds([])
setError('')
})
.catch(failure => { if (!controller.signal.aborted) setError(requestError(failure, english)) })
@@ -146,11 +205,23 @@ export function ComputeComparisonSettings({ active }: { active: boolean }) {
.finally(() => setCandidateBusy(false))
}, [english])
const loadRevisions = useCallback(() => {
setRevisionsBusy(true)
axios.get<{ items: ComputeRevisionSummary[] }>(`${REVISIONS_ENDPOINT}?limit=20`)
.then(({ data }) => {
setRevisions(Array.isArray(data.items) ? data.items : [])
})
.catch(failure => setError(requestError(failure, english)))
.finally(() => setRevisionsBusy(false))
}, [english])
useEffect(() => {
if (active && view === 'candidates') {
loadCandidates()
} else if (active && view === 'revisions') {
loadRevisions()
}
}, [active, view, loadCandidates])
}, [active, view, loadCandidates, loadRevisions])
useEffect(() => {
if (!dirty) return
@@ -162,7 +233,7 @@ export function ComputeComparisonSettings({ active }: { active: boolean }) {
if (!active) return null
const edit = (next: ComputeConfiguration) => { setDraft(next); setMessage(''); setError('') }
const reload = () => { setSaved(null); setLoadRevision(value => value + 1); setMessage('') }
const reload = () => { setSaved(null); setLoadRevision(value => value + 1); setPublishNote(''); setPendingCandidateIds([]); setMessage('') }
const metricLabel = (metric: ComputeMetric | string) => {
switch (metric) {
@@ -181,20 +252,64 @@ export function ComputeComparisonSettings({ active }: { active: boolean }) {
}
}
const getReviewDraft = (candidateId: number): CandidateReviewDraft => (
reviewDrafts[candidateId] || {
decision: 'approved',
reasonCode: 'newer_authoritative_report',
reason: '',
}
)
const updateReviewDraft = (candidateId: number, patch: Partial<CandidateReviewDraft>) => {
setReviewDrafts(prev => {
const current = prev[candidateId] || {
decision: 'approved' as const,
reasonCode: 'newer_authoritative_report' as CandidateReviewReasonCode,
reason: '',
}
const next = { ...current, ...patch }
if (patch.decision === 'approved' && !APPROVE_REASON_OPTIONS.some(o => o.value === next.reasonCode)) {
next.reasonCode = 'newer_authoritative_report'
} else if (patch.decision === 'rejected' && !REJECT_REASON_OPTIONS.some(o => o.value === next.reasonCode)) {
next.reasonCode = 'unverifiable_source'
}
return { ...prev, [candidateId]: next }
})
}
async function publish(reset = false) {
if (!saved || !draft) return
if (!reset && requiresMixedShareNote && !publishNote.trim()) {
setError(t('跨报告局部修订份额数据时,请在发布说明中写明同分母依据。', 'Cross-report partial share revision requires a publish note explaining denominator consistency.'))
return
}
setBusy(true); setError(''); setMessage('')
try {
const payloadConfig = normalizeDraftForPublish(draft)
const { data } = reset
? await axios.post<ComputeConfigurationResponse>(`${ENDPOINT}/reset`, { revision: saved.revision })
: await axios.put<ComputeConfigurationResponse>(ENDPOINT, { revision: saved.revision, config: payloadConfig })
? await axios.post<ComputeConfigurationResponse>(`${ENDPOINT}/reset`, {
revision: saved.revision,
publish_note: publishNote.trim(),
})
: await axios.put<ComputeConfigurationResponse>(ENDPOINT, {
revision: saved.revision,
config: payloadConfig,
publish_note: publishNote.trim(),
source_candidate_ids: pendingCandidateIds,
})
const normalized = ensureCompleteConfiguration(data.config)
setSaved({ ...data, config: normalized })
setDraft(normalized)
setConfirmation(null)
setMessage(t('已发布,地球多口径卡片与态势评估将自动刷新。', 'Published. Earth cards and posture assessments will refresh automatically.'))
setPublishNote('')
setPendingCandidateIds([])
setMessage(
data.no_changes
? t('配置内容未变化,未生成新版本。', 'No substantive configuration changes; no new revision created.')
: t('已发布新版本,地球多口径卡片与态势演播将自动同步。', 'Published new revision. Earth cards and stage narratives will refresh automatically.'),
)
notifyComputeConfigurationChanged()
if (view === 'revisions') loadRevisions()
} catch (failure) { setError(requestError(failure, english)); setConfirmation(null) }
finally { setBusy(false) }
}
@@ -205,6 +320,9 @@ export function ComputeComparisonSettings({ active }: { active: boolean }) {
try {
const { data } = await axios.post<{ items: ComputeCandidateItem[] }>(`${CANDIDATES_ENDPOINT}/extract`, {
year: extractYear,
report_year: extractReportYear || extractYear,
period_label: extractPeriodLabel.trim() || null,
published_at: extractPublishedAt.trim() || null,
excerpt: extractExcerpt.trim(),
source_id: extractSourceId.trim(),
source_title: extractSourceTitle.trim(),
@@ -212,10 +330,14 @@ export function ComputeComparisonSettings({ active }: { active: boolean }) {
publisher: extractPublisher.trim(),
locator: extractLocator.trim(),
})
const createdCount = Array.isArray(data.items) ? data.items.length : 0
const items = Array.isArray(data.items) ? data.items : []
const dupCount = items.filter(item => item.duplicate).length
const newCount = items.length - dupCount
setMessage(
createdCount > 0
? t(`已提取 ${createdCount} 条候选证据,请核验后导入草稿。`, `Extracted ${createdCount} candidate item(s). Review before importing into draft.`)
items.length > 0
? dupCount > 0 && newCount === 0
? t(`检测到 ${dupCount} 条重复候选,已定位到既有记录。`, `Detected ${dupCount} duplicate candidate(s); existing records retained.`)
: t(`已提取 ${newCount} 条新候选(${dupCount} 条重复),请填写复核理由后导入。`, `Extracted ${newCount} new candidate(s) (${dupCount} duplicate). Review with reason before importing.`)
: t('未在摘录中匹配到符合规则的国家算力份额数值。', 'No structured country compute share figures matched in the excerpt.'),
)
loadCandidates()
@@ -226,15 +348,24 @@ export function ComputeComparisonSettings({ active }: { active: boolean }) {
}
}
async function handleReviewCandidate(candidateId: number, decision: 'approved' | 'rejected') {
async function handleSubmitCandidateReview(candidateId: number) {
const rd = getReviewDraft(candidateId)
if (rd.reason.trim().length < 2) {
setError(t('请填写至少 2 个字的复核理由说明。', 'Please enter a review reason of at least 2 characters.'))
return
}
setCandidateBusy(true); setError('')
try {
const { data } = await axios.post<ComputeCandidateItem>(`${CANDIDATES_ENDPOINT}/${candidateId}/review`, { decision })
const { data } = await axios.post<ComputeCandidateItem>(`${CANDIDATES_ENDPOINT}/${candidateId}/review`, {
decision: rd.decision,
reason_code: rd.reasonCode,
reason: rd.reason.trim(),
})
setCandidates(prev => prev.map(item => item.id === candidateId ? data : item))
setMessage(
decision === 'approved'
? t('候选证据已通过审核,可一键导入配置草稿。', 'Candidate approved. Ready to import into draft.')
: t('候选证据已驳回。', 'Candidate rejected.'),
rd.decision === 'approved'
? t('候选证据已采纳并记录理由,可导入草稿发布。', 'Candidate approved with reason. Ready to import into draft.')
: t('候选证据已驳回并记录理由。', 'Candidate rejected with reason.'),
)
} catch (failure) {
setError(requestError(failure, english))
@@ -243,12 +374,33 @@ export function ComputeComparisonSettings({ active }: { active: boolean }) {
}
}
function handleImportCandidate(candidate: ComputeCandidateItem) {
function handleImportCandidate(candidate: ComputeCandidateItem, replaceOnPeriodConflict = false) {
if (!draft) return
const next = applyApprovedCandidateToDraft(draft, candidate)
edit(next)
const result = applyApprovedCandidateToDraft(draft, candidate, { replaceOnPeriodConflict })
if (result.status === 'period_conflict') {
setPeriodConflict({
candidate,
existingPeriodLabel: result.existingPeriodLabel,
candidatePeriodLabel: result.candidatePeriodLabel,
discardedCodes: result.discardedCodes,
})
return
}
setPeriodConflict(null)
edit(result.draft)
setPendingCandidateIds(prev => (prev.includes(candidate.id) ? prev : [...prev, candidate.id]))
setView('observations')
setMessage(t('已将审核通过的候选观测导入草稿,请核对后点击“保存并发布”。', 'Imported approved candidate into draft. Review and click "Save and publish".'))
setMessage(
result.mixedShareRowWarning
? t(
'已将审核通过的候选观测导入草稿(跨报告局部修订):请在顶部“发布说明”中写明同分母依据后再点击“保存并发布”。',
'Imported approved candidate into draft (partial cross-report revision): document denominator consistency in "Publish note" before saving.',
)
: t(
'已将审核通过的候选观测导入草稿,请核对后点击“保存并发布”。',
'Imported approved candidate into draft. Review and click "Save and publish".',
),
)
}
function save(event: FormEvent) { event.preventDefault(); void publish() }
@@ -287,6 +439,19 @@ export function ComputeComparisonSettings({ active }: { active: boolean }) {
if (draft) edit({ ...draft, national_hubs: draft.national_hubs.map((item, i) => i === index ? row : item) })
}
const actionLabel = (action: string) => {
if (action === 'baseline') return t('基线', 'Baseline')
if (action === 'reset') return t('恢复默认', 'Reset')
return t('发布', 'Publish')
}
const presentationStatusLabel = (status: string) => {
if (status === 'delivered') return t('已演播', 'Delivered')
if (status === 'failed') return t('演播失败', 'Failed')
if (status === 'pending') return t('待演播', 'Pending')
return t('已跳过', 'Skipped')
}
return (
<Panel className="an-compute-settings">
<form className="an-compute-form" onSubmit={save} onInvalidCapture={event => {
@@ -308,7 +473,7 @@ export function ComputeComparisonSettings({ active }: { active: boolean }) {
</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 authoritative report data') : saved ? t('当前使用后台已发布配置', 'Using published configuration') : t('正在读取配置…', 'Loading configuration…'))}
{message || (error && !saved ? t('配置读取失败', 'Configuration unavailable') : dirty ? t('有未发布修改', 'Unpublished changes') : saved?.is_default ? t('当前使用内置权威报告数据', 'Using bundled authoritative report data') : saved ? t(`当前已发布版本:${(saved.publish_id || saved.revision).slice(0, 12)}`, `Active revision: ${(saved.publish_id || saved.revision).slice(0, 12)}`) : t('正在读取配置…', 'Loading configuration…'))}
</div>
{error ? <p className="an-compute-error" role="alert">{error}</p> : null}
{draft && saved ? <>
@@ -321,6 +486,7 @@ export function ComputeComparisonSettings({ active }: { active: boolean }) {
['milestones', t('里程碑与八大枢纽', 'Milestones & 8 Hubs')],
['sources', t('报告来源', 'Sources')],
['candidates', t('Agent 待审队列', 'Candidate queue')],
['revisions', t('修订历史', 'Revisions')],
] as const).map(([key, label]) => (
<Button key={key} type="button" variant={view === key ? 'primary' : 'subtle'} aria-pressed={view === key} onClick={() => setView(key)}>{label}</Button>
))}
@@ -328,10 +494,24 @@ export function ComputeComparisonSettings({ active }: { active: boolean }) {
</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>
<div className="an-compute-fields">
<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>
<Field title={requiresMixedShareNote ? t('发布说明(混源份额修订必填同分母依据)', 'Publish note (required for mixed-source share row)') : t('发布说明(可选)', 'Publish note (optional)')}>
<Input
type="text"
maxLength={1000}
required={requiresMixedShareNote}
placeholder={requiresMixedShareNote
? t('请说明各报告同分母依据…', 'Explain shared denominator basis across sources...')
: t('记录本次修订原因或变更摘要…', 'Summarize reason for this revision...')}
value={publishNote}
onChange={event => setPublishNote(event.target.value)}
/>
</Field>
</div>
{view === 'observations' ? <>
<p className="an-compute-lead">
@@ -340,51 +520,81 @@ export function ComputeComparisonSettings({ active }: { active: boolean }) {
'Supports global share, AI compute share, absolute FP32 scale, frontier cluster power, and chip inflow share. Bilateral RPI is derived deterministically on the server.',
)}
</p>
{draft.observations.map((row, index) => <details className="an-compute-row" key={index} open={index === 0 ? true : undefined}>
<summary>
{row.period_label || row.year} · {metricLabel(row.metric)} · {Object.keys(row.values).length} {t('个国家', 'countries')}
</summary>
<div className="an-compute-fields an-compute-fields--three">
<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('统计周期标签(可选)', 'Period label (optional)')}>
<Input type="text" maxLength={40} placeholder="2025-H1" value={row.period_label || ''}
onChange={event => updateObservation(index, { ...row, period_label: event.target.value || null })} />
</Field>
<Field title={t('指标口径', 'Metric')}>
<Select value={row.metric} options={COMPUTE_METRICS.map(metric => ({ value: metric, label: metricLabel(metric) }))}
onValueChange={value => updateObservation(index, { ...row, metric: value as ComputeMetric })} />
</Field>
<Field title={t('全球分母总量(可选 EFlop/s)', 'Global denominator total (optional EFlop/s)')}>
<Input type="number" min={0} max={1e12} step="any" placeholder="2210"
value={typeof row.global_total === 'number' && Number.isFinite(row.global_total) ? row.global_total : ''}
onChange={event => updateObservation(index, {
...row,
global_total: Number.isFinite(event.target.valueAsNumber) ? event.target.valueAsNumber : null,
})} />
</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={SHARE_METRICS.has(row.metric) ? 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>)}
{draft.observations.map((row, index) => {
const isMixedShare = SHARE_METRICS.has(row.metric) && observationHasMixedSources(row)
return (
<details className={`an-compute-row${isMixedShare ? ' an-compute-row--mixed' : ''}`} key={index} open={index === 0 || isMixedShare ? true : undefined}>
<summary>
<span>{row.period_label || row.year} · {metricLabel(row.metric)} · {Object.keys(row.values).length} {t('个国家', 'countries')}</span>
{isMixedShare ? (
<span className="an-compute-badge an-compute-badge--revision">
{t('跨报告局部修订', 'Cross-report partial revision')}
</span>
) : null}
</summary>
{isMixedShare ? (
<div className="an-compute-warning-banner" role="note">
<AlertTriangle size={14} />
<span>{t('跨报告局部修订:请在发布说明中写明同分母依据。', 'Cross-report partial revision: please state denominator consistency in the publish note.')}</span>
</div>
) : null}
<div className="an-compute-fields an-compute-fields--three">
<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('统计周期标签(可选)', 'Period label (optional)')}>
<Input type="text" maxLength={40} placeholder="2025-H1" value={row.period_label || ''}
onChange={event => updateObservation(index, { ...row, period_label: event.target.value || null })} />
</Field>
<Field title={t('指标口径', 'Metric')}>
<Select value={row.metric} options={COMPUTE_METRICS.map(metric => ({ value: metric, label: metricLabel(metric) }))}
onValueChange={value => updateObservation(index, { ...row, metric: value as ComputeMetric })} />
</Field>
<Field title={t('全球分母总量(可选 EFlop/s)', 'Global denominator total (optional EFlop/s)')}>
<Input type="number" min={0} max={1e12} step="any" placeholder="2210"
value={typeof row.global_total === 'number' && Number.isFinite(row.global_total) ? row.global_total : ''}
onChange={event => updateObservation(index, {
...row,
global_total: Number.isFinite(event.target.valueAsNumber) ? event.target.valueAsNumber : null,
})} />
</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]) => {
const effectiveSource = sourceForObservation(row, code)
const hasPerCountryOverride = Boolean(row.value_sources && row.value_sources[code] && row.value_sources[code] !== row.source_id)
return (
<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={SHARE_METRICS.has(row.metric) ? 100 : 1e12} step="any" value={Number.isFinite(value) ? value : ''}
onChange={event => updateObservation(index, { ...row, values: { ...row.values, [code]: event.target.valueAsNumber } })} />
{hasPerCountryOverride ? (
<span className="an-compute-source-tag">
{t(`来源:${effectiveSource}`, `Source: ${effectiveSource}`)}
</span>
) : null}
</Field>
{removeButton(t(`移除 ${code} 观测`, `Remove ${code} observation`), () => {
const values = { ...row.values }; delete values[code]
const nextVs = row.value_sources ? { ...row.value_sources } : undefined
if (nextVs) delete nextVs[code]
updateObservation(index, { ...row, values, value_sources: nextVs })
})}
</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: [
@@ -612,11 +822,11 @@ export function ComputeComparisonSettings({ active }: { active: boolean }) {
<Button type="button" variant="subtle" onClick={() => edit({ ...draft, sources: [...draft.sources, { id: `report-${crypto.randomUUID().slice(0, 8)}`, title: '', publisher: '', url: '', locator: '', report_year: 2025, published_at: null }] })}>
<Plus size={15} />{t('添加报告来源', 'Add report source')}
</Button>
</> : <>
</> : view === 'candidates' ? <>
<p className="an-compute-lead">
{t(
'粘贴报告摘录后提取算力份额候选项,经人工审核后再导入草稿。',
'Extract candidate shares from report excerpts, review manually, and import approved items into draft.',
'粘贴报告摘录后提取算力候选,逐国核对旧值/新值与分母口径,填写复核理由后导入草稿。',
'Extract candidate figures from report excerpts, compare per-country deltas, record a review reason, and import into draft.',
)}
</p>
<div className="an-compute-candidate-box">
@@ -625,6 +835,14 @@ export function ComputeComparisonSettings({ active }: { active: boolean }) {
<Input type="number" min={2000} max={2100} value={extractYear}
onChange={event => setExtractYear(event.target.valueAsNumber || 2025)} />
</Field>
<Field title={t('报告年份', 'Report year')}>
<Input type="number" min={2000} max={2100} value={extractReportYear}
onChange={event => setExtractReportYear(event.target.valueAsNumber || extractYear)} />
</Field>
<Field title={t('统计周期标签(可选)', 'Period label (optional)')}>
<Input type="text" maxLength={40} placeholder="2025-H1" value={extractPeriodLabel}
onChange={event => setExtractPeriodLabel(event.target.value)} />
</Field>
<Field title={t('来源标识 ID', 'Source ID')}>
<Input type="text" maxLength={80} value={extractSourceId}
onChange={event => setExtractSourceId(event.target.value)} />
@@ -633,6 +851,10 @@ export function ComputeComparisonSettings({ active }: { active: boolean }) {
<Input type="text" maxLength={200} value={extractPublisher}
onChange={event => setExtractPublisher(event.target.value)} />
</Field>
<Field title={t('发表日期(可选)', 'Published date (optional)')}>
<Input type="date" value={extractPublishedAt}
onChange={event => setExtractPublishedAt(event.target.value)} />
</Field>
<Field title={t('报告标题', 'Report title')}>
<Input type="text" maxLength={300} value={extractSourceTitle}
onChange={event => setExtractSourceTitle(event.target.value)} />
@@ -641,7 +863,7 @@ export function ComputeComparisonSettings({ active }: { active: boolean }) {
<Input type="url" maxLength={2000} value={extractSourceUrl}
onChange={event => setExtractSourceUrl(event.target.value)} />
</Field>
<Field title={t('章节 / 图表定位', 'Section / figure locator')}>
<Field title={t('章节 / 页码定位', 'Page / figure locator')}>
<Input type="text" maxLength={300} value={extractLocator}
onChange={event => setExtractLocator(event.target.value)} />
</Field>
@@ -649,14 +871,14 @@ export function ComputeComparisonSettings({ active }: { active: boolean }) {
<textarea
className="an-compute-textarea"
rows={3}
placeholder={t('例如:美国全球算力份额 44%,中国全球算力份额 23%…', 'Paste report excerpt containing country compute share figures...')}
placeholder={t('粘贴含国家算力份额或芯片流向修订数据的报告原文…', 'Paste report excerpt containing country compute share or chip inflow figures...')}
value={extractExcerpt}
onChange={event => setExtractExcerpt(event.target.value)}
/>
</Field>
</div>
<div className="an-compute-actions">
<Button type="button" variant="primary" disabled={candidateBusy || !extractExcerpt.trim()} loading={candidateBusy} onClick={() => void handleExtractCandidates()}>
<Button type="button" variant="subtle" disabled={candidateBusy || !extractExcerpt.trim()} loading={candidateBusy} onClick={() => void handleExtractCandidates()}>
<Sparkles size={15} />{t('提取候选证据', 'Extract candidates')}
</Button>
<Button type="button" variant="subtle" disabled={candidateBusy} onClick={loadCandidates}>
@@ -667,40 +889,192 @@ export function ComputeComparisonSettings({ active }: { active: boolean }) {
{candidates.length === 0 ? (
<p className="an-compute-lead">{t('当前暂无待审或历史候选记录。', 'No candidate items in queue yet.')}</p>
) : candidates.map(candidate => (
<div className="an-compute-candidate-box" key={candidate.id}>
<div className="an-compute-candidate-head">
<strong>
#{candidate.id} · {candidate.candidate_type} · {t('置信度', 'Confidence')} {Math.round(candidate.confidence * 100)}%
</strong>
<span className={`an-compute-badge an-compute-badge--${candidate.status}`}>
{candidate.status === 'approved'
? t('已通过', 'Approved')
: candidate.status === 'rejected'
? t('已驳回', 'Rejected')
: t('待审核', 'Pending')}
</span>
</div>
<pre className="an-compute-code">{JSON.stringify(candidate.proposed_payload, null, 2)}</pre>
<div className="an-compute-actions">
{candidate.status !== 'approved' ? (
<Button type="button" variant="subtle" disabled={candidateBusy} onClick={() => void handleReviewCandidate(candidate.id, 'approved')}>
<Check size={15} />{t('审核通过', 'Approve')}
</Button>
) : candidates.map(candidate => {
const cmp = candidate.comparison
const codesEntries = Object.entries(cmp?.codes || {})
const metricKey = cmp?.metric || candidate.proposed_payload.metric || 'global_share'
const unit = metricKey === 'absolute' ? ' EFlops' : '%'
const deltaUnit = metricKey === 'absolute' ? ' EFlops' : ' pp'
const rd = getReviewDraft(candidate.id)
const reasonOptions = (rd.decision === 'approved' ? APPROVE_REASON_OPTIONS : REJECT_REASON_OPTIONS)
.map(opt => ({ value: opt.value, label: english ? opt.en : opt.zh }))
const isPublished = Boolean(candidate.published_publish_id)
return (
<div className="an-compute-candidate-box" key={candidate.id}>
<div className="an-compute-candidate-head">
<strong>
#{candidate.id} · {metricLabel(metricKey)} · {candidate.proposed_payload.period_label || candidate.proposed_payload.year}
</strong>
<div className="an-compute-badges">
{cmp?.has_historical_revision ? (
<span className="an-compute-badge an-compute-badge--revision">{t('历史修订', 'Historical revision')}</span>
) : codesEntries.some(([, c]) => c.change_kind === 'new_observation') ? (
<span className="an-compute-badge an-compute-badge--info">{t('新增观测', 'New observation')}</span>
) : null}
{cmp?.period_conflict ? (
<span className="an-compute-badge an-compute-badge--conflict">{t('统计期冲突', 'Period conflict')}</span>
) : null}
{candidate.duplicate ? (
<span className="an-compute-badge an-compute-badge--muted">{t('重复', 'Duplicate')}</span>
) : null}
{isPublished ? (
<span className="an-compute-badge an-compute-badge--info">{t('已发布', 'Published')}</span>
) : null}
<span className={`an-compute-badge an-compute-badge--${candidate.status}`}>
{candidate.status === 'approved'
? t('已采纳', 'Approved')
: candidate.status === 'rejected'
? t('已驳回', 'Rejected')
: t('待审核', 'Pending')}
</span>
</div>
</div>
<div className="an-compute-meta-strip">
<span>{t('分母口径', 'Denominator')}: {cmp?.denominator || '—'}</span>
<span>{t('报告来源', 'Source')}: {candidate.source_payload.title || candidate.source_payload.id || '—'}</span>
<span>{t('页码定位', 'Locator')}: {candidate.source_payload.locator || '—'}</span>
<span>{t('置信度', 'Confidence')}: {typeof candidate.confidence === 'number' && Number.isFinite(candidate.confidence) ? `${Math.round(candidate.confidence * 100)}%` : '—'}</span>
</div>
{codesEntries.length > 0 ? (
<div className="an-compute-table-wrap">
<table className="an-compute-table">
<thead>
<tr>
<th>{t('国家', 'Country')}</th>
<th>{t('旧值', 'Old')}</th>
<th>{t('新值', 'New')}</th>
<th>{t('差值', 'Delta')}</th>
<th>{t('旧来源', 'Prior source')}</th>
</tr>
</thead>
<tbody>
{codesEntries.map(([code, entry]) => (
<tr key={code}>
<td>{saved.countries.find(c => c.code === code)?.[english ? 'name_en' : 'name'] || code} ({code})</td>
<td>{entry.old_value !== null ? `${entry.old_value}${unit}` : '—'}</td>
<td>{`${entry.new_value}${unit}`}</td>
<td>{entry.old_value !== null ? `${entry.delta >= 0 ? '+' : ''}${entry.delta}${deltaUnit}` : t('新增', 'New')}</td>
<td>{entry.old_source_id || '—'}</td>
</tr>
))}
</tbody>
</table>
</div>
) : (
<pre className="an-compute-code">{JSON.stringify(candidate.proposed_payload, null, 2)}</pre>
)}
{candidate.review_reason_code ? (
<div className="an-compute-review-summary">
{t('复核记录', 'Review record')}: {reasonCodeLabel(candidate.review_reason_code, english)}
{candidate.review_reason ? ` — ${candidate.review_reason}` : ''}
{candidate.reviewed_by ? ` (${candidate.reviewed_by})` : ''}
{candidate.published_publish_id ? ` · publish_id: ${candidate.published_publish_id.slice(0, 12)}` : ''}
</div>
) : null}
{candidate.status !== 'rejected' ? (
<Button type="button" variant="subtle" disabled={candidateBusy} onClick={() => void handleReviewCandidate(candidate.id, 'rejected')}>
<X size={15} />{t('驳回', 'Reject')}
</Button>
) : null}
{candidate.status === 'approved' ? (
<Button type="button" variant="primary" disabled={candidateBusy} onClick={() => handleImportCandidate(candidate)}>
<Download size={15} />{t('导入配置草稿', 'Import to draft')}
</Button>
{!isPublished ? (
<div className="an-compute-review-box">
<Field title={t('复核结论与理由分类', 'Decision & reason code')}>
<div className="an-compute-actions">
<Button
type="button"
variant={rd.decision === 'approved' ? 'primary' : 'subtle'}
onClick={() => updateReviewDraft(candidate.id, { decision: 'approved' })}
>
<Check size={14} />{t('采纳', 'Approve')}
</Button>
<Button
type="button"
variant={rd.decision === 'rejected' ? 'danger' : 'subtle'}
onClick={() => updateReviewDraft(candidate.id, { decision: 'rejected' })}
>
<X size={14} />{t('驳回', 'Reject')}
</Button>
</div>
<Select
value={rd.reasonCode}
options={reasonOptions}
onValueChange={val => updateReviewDraft(candidate.id, { reasonCode: val as CandidateReviewReasonCode })}
/>
</Field>
<Field title={t('复核理由说明(必填)', 'Review reason (required)')}>
<Input
type="text"
maxLength={1000}
placeholder={t('填写核验依据或驳回说明(至少 2 字)…', 'Enter verification evidence or rejection note...')}
value={rd.reason}
onChange={event => updateReviewDraft(candidate.id, { reason: event.target.value })}
/>
</Field>
<div className="an-compute-actions">
<Button
type="button"
variant="subtle"
disabled={candidateBusy || rd.reason.trim().length < 2}
onClick={() => void handleSubmitCandidateReview(candidate.id)}
>
{t('提交复核', 'Submit review')}
</Button>
{candidate.status === 'approved' ? (
<Button
type="button"
variant="subtle"
disabled={candidateBusy}
onClick={() => handleImportCandidate(candidate)}
>
<Download size={15} />{t('导入配置草稿', 'Import to draft')}
</Button>
) : null}
</div>
</div>
) : null}
</div>
)
})}
</> : <>
<div className="an-compute-section-heading">
<span><History size={15} /> {t('系统发布版本历史', 'Published revision history')}</span>
<Button type="button" variant="subtle" disabled={revisionsBusy} onClick={loadRevisions}>
<RefreshCw size={15} />{t('刷新历史', 'Refresh history')}
</Button>
</div>
{revisions.length === 0 ? (
<p className="an-compute-lead">{t('暂无发布版本记录。', 'No revisions recorded yet.')}</p>
) : (
<div className="an-compute-table-wrap">
<table className="an-compute-table">
<thead>
<tr>
<th>{t('版本 ID', 'Revision')}</th>
<th>{t('动作', 'Action')}</th>
<th>{t('发布时间', 'Published at')}</th>
<th>{t('发布人', 'Publisher')}</th>
<th>{t('变化摘要', 'Change summary')}</th>
<th>{t('发布说明', 'Publish note')}</th>
<th>{t('演播状态', 'Presentation')}</th>
</tr>
</thead>
<tbody>
{revisions.map(rev => (
<tr key={rev.id}>
<td><code>{rev.publish_id.slice(0, 12)}</code></td>
<td><span className="an-compute-badge an-compute-badge--muted">{actionLabel(rev.action)}</span></td>
<td>{formatDateTime(rev.published_at)}</td>
<td>{rev.published_by_name || t('系统基线', 'System baseline')}</td>
<td>{rev.change_count > 0 ? `${rev.summary}(共 ${rev.change_count} 项)` : rev.summary}</td>
<td>{rev.publish_note || '—'}</td>
<td>
<span className={`an-compute-badge an-compute-badge--${rev.presentation_status === 'skipped' ? 'muted' : rev.presentation_status}`}>
{presentationStatusLabel(rev.presentation_status)}
</span>
</td>
</tr>
))}
</tbody>
</table>
</div>
))}
)}
</>}
</fieldset>
</Scrollbar>
@@ -708,8 +1082,24 @@ export function ComputeComparisonSettings({ active }: { active: boolean }) {
</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.')}
description={t('当前未发布修改将被替换。恢复默认会新增一条 reset 版本并记录在操作审计中。', 'Unpublished edits will be replaced. Restoring defaults creates a new audited reset revision.')}
onConfirm={() => { if (confirmation === 'reset') void publish(true); else { setConfirmation(null); reload() } }} />
<ConfirmDialog
open={periodConflict !== null}
onOpenChange={open => !open && setPeriodConflict(null)}
title={t('统计周期冲突:替换本年主观测?', 'Period label conflict: replace primary observation?')}
description={
periodConflict
? t(
`现有记录周期为「${periodConflict.existingPeriodLabel || '全年'}」,候选周期为「${periodConflict.candidatePeriodLabel || '全年'}」。确认将用候选整行替换本年主观测${periodConflict.discardedCodes.length > 0 ? `,并丢弃以下国家数据:${periodConflict.discardedCodes.join(', ')}` : ''}。`,
`Existing period is "${periodConflict.existingPeriodLabel || 'full year'}" vs candidate "${periodConflict.candidatePeriodLabel || 'full year'}". Replacing will overwrite the full row${periodConflict.discardedCodes.length > 0 ? ` and discard: ${periodConflict.discardedCodes.join(', ')}` : ''}.`,
)
: ''
}
onConfirm={() => {
if (periodConflict) handleImportCandidate(periodConflict.candidate, true)
}}
/>
</Panel>
)
}
File diff suppressed because it is too large. Load diff
+283 -256
View File
@@ -1,15 +1,14 @@
import type { ColumnDef } from '@tanstack/react-table'
import axios from 'axios'
import * as echarts from 'echarts/core'
import { BarChart } from 'echarts/charts'
import { GridComponent, TooltipComponent } from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import { Download, RefreshCw, Search, X } from 'lucide-react'
import { Download, RefreshCw, RotateCcw, Search, X } from 'lucide-react'
import { useCallback, useEffect, useMemo, useRef, useState, type CSSProperties, type PointerEvent as ReactPointerEvent } from 'react'
import { useSearchParams } from 'react-router-dom'
import Scrollbar from '../../components/Scrollbar/Scrollbar'
import { formatDateTimeZhCN, formatDateZhCN, parseBackendDate } from '../../utils/datetime'
import { DataTable, DataTablePager } from '../components/data-table/DataTable'
import { DataTable } from '../components/data-table/DataTable'
import { useWaterfallQuery } from '../components/data-table/useWaterfallQuery'
import { AdminLayout } from '../components/layout/AdminLayout'
import { SPLIT_RESIZE_END_EVENT } from '../components/layout/SplitPaneResizer'
import { Badge } from '../components/ui/badge'
import { Button } from '../components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '../components/ui/card'
@@ -17,8 +16,11 @@ import { Dialog } from '../components/ui/dialog'
import { Input } from '../components/ui/input'
import { Select } from '../components/ui/select'
import { useToast } from '../components/ui/toast'
echarts.use([BarChart, GridComponent, TooltipComponent, CanvasRenderer])
import { ComputeLedger } from './data-ledger/ComputeLedger'
import { LayerItemsLedger } from './data-ledger/LayerItemsLedger'
import { LayerNav } from './data-ledger/LayerNav'
import type { LedgerLayerSummary } from './data-ledger/ledger-model'
import { formatDataTypeLabel } from './dashboardHelpers'
interface CollectedData {
id: number
@@ -45,14 +47,6 @@ interface CollectedData {
is_valid: number
}
interface Summary {
total_records: number
overall_total_records: number
by_source: Record<string, Record<string, number>>
source_totals: Array<{ source: string; source_name: string; count: number }>
type_totals: Array<{ data_type: string; count: number }>
}
interface SourceOption {
source: string
source_name: string
@@ -75,7 +69,7 @@ function formatFieldLabel(key: string) {
function formatDetailValue(key: string, value: unknown) {
if (value === null || value === undefined || value === '') return '-'
if (key === 'data_type') return dataTypeLabel(String(value))
if (key === 'data_type') return formatDataTypeLabel(String(value), false)
if (key === 'collected_at' || key === 'reference_date') {
const date = parseBackendDate(String(value))
if (!date || Number.isNaN(date.getTime())) return String(value)
@@ -101,187 +95,180 @@ function typeTone(type: string) {
return 'slate'
}
function dataTypeLabel(type: string) {
const labels: Record<string, string> = {
as_stats: '自治系统统计',
bgp_update: 'BGP 更新',
bgp_rib: 'BGP 路由表',
bgp_route: 'BGP 路由',
bgp_event: 'BGP 事件',
cable: '海缆',
cable_landing_relation: '海缆登陆关系',
cable_system: '海缆系统',
compute_center: '算力中心',
device_stats: '设备统计',
landing_point: '登陆点',
gpu_cluster: 'GPU 集群',
generic: '通用数据',
generic_records: '通用记录',
ixp: '互联网交换点',
news_item: '新闻条目',
news_live_stream: 'Live 新闻源',
prefix_geography: '前缀地理位置',
satellite_tle: '卫星轨道根数',
space: '空间',
supercomputer: '超算',
submarine_cable: '海底光缆',
traffic_stats: '流量统计',
vessel: '船舶',
vessel_ais: 'AIS 船舶',
model: '模型',
dataset: '数据集',
network: '网络',
facility: '设施',
}
return labels[type] || type.split('_').filter(Boolean).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join(' ')
}
function DistributionChart({ summary, dimension }: { summary: Summary | null; dimension: 'source' | 'type' }) {
const chartRef = useRef<HTMLDivElement | null>(null)
useEffect(() => {
const element = chartRef.current
if (!element) return undefined
const chart = echarts.init(element)
const items = dimension === 'source'
? summary?.source_totals?.slice(0, 8).map((item) => ({ label: item.source_name, value: item.count })) || []
: summary?.type_totals?.slice(0, 8).map((item) => ({ label: dataTypeLabel(item.data_type), value: item.count })) || []
chart.setOption({
grid: { left: 8, right: 12, top: 8, bottom: 6, containLabel: true },
tooltip: { trigger: 'axis' },
xAxis: {
type: 'value',
axisLine: { show: false },
axisTick: { show: false },
axisLabel: { show: false },
splitLine: { lineStyle: { color: 'rgba(148, 163, 184, 0.18)' } },
},
yAxis: {
type: 'category',
data: items.map((item) => item.label),
axisLine: { show: false },
axisTick: { show: false },
axisLabel: { color: '#475569', width: 118, overflow: 'truncate' },
},
series: [{ type: 'bar', data: items.map((item) => item.value), itemStyle: { color: '#0f766e', borderRadius: [0, 5, 5, 0] } }],
})
const resize = () => chart.resize()
const resizeObserver = new ResizeObserver(resize)
resizeObserver.observe(element)
window.addEventListener('resize', resize)
return () => {
resizeObserver.disconnect()
window.removeEventListener('resize', resize)
chart.dispose()
}
}, [dimension, summary])
return <div ref={chartRef} className="an-distribution-chart" />
}
export default function DataList() {
const { toast } = useToast()
const [data, setData] = useState<CollectedData[]>([])
const [loading, setLoading] = useState(false)
const [summary, setSummary] = useState<Summary | null>(null)
const [total, setTotal] = useState(0)
const [page, setPage] = useState(1)
const [pageSize] = useState(20)
const [sourceFilter, setSourceFilter] = useState('')
const [typeFilter, setTypeFilter] = useState('')
const [searchParams, setSearchParams] = useSearchParams()
const activeLayer = searchParams.get('layer') || 'compute'
const [layers, setLayers] = useState<LedgerLayerSummary[]>([])
const [layersLoading, setLayersLoading] = useState(false)
const [summaryWidth, setSummaryWidth] = useState(260)
const summaryWidthRef = useRef(summaryWidth)
summaryWidthRef.current = summaryWidth
const dataLayoutRef = useRef<HTMLDivElement | null>(null)
const summaryResizeCleanupRef = useRef<(() => void) | null>(null)
useEffect(() => () => {
summaryResizeCleanupRef.current?.()
}, [])
const [sourceFilter, setSourceFilter] = useState(() => searchParams.get('source') || '')
const [typeFilter, setTypeFilter] = useState(() => searchParams.get('type') || '')
const [countryFilter, setCountryFilter] = useState('')
const [searchText, setSearchText] = useState('')
const [submittedSearchText, setSubmittedSearchText] = useState('')
const [debouncedSearchText, setDebouncedSearchText] = useState('')
const [sources, setSources] = useState<SourceOption[]>([])
const [types, setTypes] = useState<string[]>([])
const [countries, setCountries] = useState<string[]>([])
const [detailVisible, setDetailVisible] = useState(false)
const [detailData, setDetailData] = useState<CollectedData | null>(null)
const [detailLoading, setDetailLoading] = useState(false)
const [distributionDimension, setDistributionDimension] = useState<'source' | 'type'>('source')
const [summaryWidth, setSummaryWidth] = useState(320)
const startSummaryResize = (event: ReactPointerEvent<HTMLButtonElement>) => {
event.preventDefault()
const startX = event.clientX
const startWidth = summaryWidth
const handleMove = (moveEvent: PointerEvent) => {
setSummaryWidth(Math.min(520, Math.max(260, startWidth + (moveEvent.clientX - startX))))
const fetchLayers = useCallback(async () => {
setLayersLoading(true)
try {
const res = await axios.get<{ layers: LedgerLayerSummary[] }>('/api/v1/data-ledger/layers')
setLayers(res.data.layers || [])
} catch (error) {
console.error('Failed to fetch ledger layers:', error)
} finally {
setLayersLoading(false)
}
const stopMove = () => {
}, [])
useEffect(() => {
void fetchLayers()
}, [fetchLayers])
const handleSelectLayer = (layerId: string) => {
const next = new URLSearchParams(searchParams)
next.set('layer', layerId)
setSearchParams(next, { replace: false })
}
const startSummaryResize = useCallback((event: ReactPointerEvent<HTMLButtonElement>) => {
event.preventDefault()
summaryResizeCleanupRef.current?.()
const startX = event.clientX
const startWidth = summaryWidthRef.current
let latestWidth = startWidth
let rafId = 0
const applyFrame = () => {
rafId = 0
dataLayoutRef.current?.style.setProperty('--an-data-summary-width', `${latestWidth}px`)
}
const handleMove = (moveEvent: PointerEvent) => {
latestWidth = Math.min(420, Math.max(220, Math.round(startWidth + (moveEvent.clientX - startX))))
if (!rafId) {
rafId = window.requestAnimationFrame(applyFrame)
}
}
const cleanupListeners = () => {
if (rafId) {
window.cancelAnimationFrame(rafId)
rafId = 0
}
document.body.classList.remove('an-is-resizing')
window.removeEventListener('pointermove', handleMove)
window.removeEventListener('pointerup', stopMove)
window.removeEventListener('pointercancel', stopMove)
summaryResizeCleanupRef.current = null
}
const stopMove = () => {
cleanupListeners()
dataLayoutRef.current?.style.setProperty('--an-data-summary-width', `${latestWidth}px`)
setSummaryWidth(latestWidth)
window.dispatchEvent(new Event(SPLIT_RESIZE_END_EVENT))
}
summaryResizeCleanupRef.current = cleanupListeners
document.body.classList.add('an-is-resizing')
window.addEventListener('pointermove', handleMove)
window.addEventListener('pointerup', stopMove, { once: true })
}
const fetchData = useCallback(async () => {
setLoading(true)
try {
const params = new URLSearchParams({ page: String(page), page_size: String(pageSize), include_metadata: 'false' })
if (sourceFilter) params.append('source', sourceFilter)
if (typeFilter) params.append('data_type', typeFilter)
if (countryFilter) params.append('country', countryFilter)
if (submittedSearchText) params.append('search', submittedSearchText)
const res = await axios.get(`/api/v1/collected?${params}`)
setData(res.data.data)
setTotal(res.data.total)
} catch (error) {
console.error('Failed to fetch data:', error)
} finally {
setLoading(false)
}
}, [countryFilter, page, pageSize, sourceFilter, submittedSearchText, typeFilter])
const fetchSummary = useCallback(async () => {
try {
const params = new URLSearchParams()
if (sourceFilter) params.append('source', sourceFilter)
if (typeFilter) params.append('data_type', typeFilter)
if (countryFilter) params.append('country', countryFilter)
if (submittedSearchText) params.append('search', submittedSearchText)
const query = params.toString()
const res = await axios.get(query ? `/api/v1/collected/summary?${query}` : '/api/v1/collected/summary')
setSummary(res.data)
} catch (error) {
console.error('Failed to fetch summary:', error)
}
}, [countryFilter, sourceFilter, submittedSearchText, typeFilter])
window.addEventListener('pointercancel', stopMove, { once: true })
}, [])
useEffect(() => {
const trimmed = searchText.trim()
if (!trimmed) {
setDebouncedSearchText('')
return undefined
}
const timer = window.setTimeout(() => {
setDebouncedSearchText(trimmed)
}, 280)
return () => window.clearTimeout(timer)
}, [searchText])
const fetchRawPage = useCallback(
async (page: number, pageSize: number) => {
const params = new URLSearchParams({
page: String(page),
page_size: String(pageSize),
include_metadata: 'false',
})
if (sourceFilter) params.append('source', sourceFilter)
if (typeFilter) params.append('data_type', typeFilter)
if (countryFilter) params.append('country', countryFilter)
if (debouncedSearchText) params.append('search', debouncedSearchText)
const res = await axios.get<{ data: CollectedData[]; total: number }>(`/api/v1/collected?${params}`)
return {
rows: res.data.data || [],
total: res.data.total || 0,
meta: res.data,
}
},
[countryFilter, debouncedSearchText, sourceFilter, typeFilter],
)
const handleRawLoadError = useCallback(
(error: unknown) => {
toast({
tone: 'error',
title: '加载采集数据失败',
description: error instanceof Error ? error.message : '请稍后重试',
})
},
[toast],
)
const {
items: data,
total,
loading,
loadingMore,
hasMore,
reload: fetchRawData,
loadMore: loadMoreRawData,
} = useWaterfallQuery<CollectedData, { data: CollectedData[]; total: number }>({
fetchPage: fetchRawPage,
getRowKey: (row) => String(row.id),
deps: [activeLayer, countryFilter, debouncedSearchText, sourceFilter, typeFilter],
enabled: activeLayer === 'raw',
pageSize: 30,
onError: handleRawLoadError,
})
useEffect(() => {
if (activeLayer !== 'raw') return
void Promise.all([
axios.get('/api/v1/collected/sources').then((res) => setSources(res.data.sources || [])),
axios.get('/api/v1/collected/types').then((res) => setTypes(res.data.data_types || [])),
axios.get('/api/v1/collected/countries').then((res) => setCountries(res.data.countries || [])),
]).catch((error) => console.error('Failed to fetch filters:', error))
}, [])
useEffect(() => {
void fetchData()
}, [fetchData])
useEffect(() => {
const timer = window.setTimeout(() => void fetchSummary(), 250)
return () => window.clearTimeout(timer)
}, [fetchSummary])
const handleSearch = () => {
setSubmittedSearchText(searchText.trim())
setPage(1)
}
}, [activeLayer])
const handleReset = () => {
setSourceFilter('')
setTypeFilter('')
setCountryFilter('')
setSearchText('')
setSubmittedSearchText('')
setPage(1)
setDebouncedSearchText('')
setSearchParams({ layer: activeLayer }, { replace: true })
}
const handleViewDetail = async (id: number) => {
@@ -302,7 +289,7 @@ export default function DataList() {
if (sourceFilter) params.append('source', sourceFilter)
if (typeFilter) params.append('data_type', typeFilter)
if (countryFilter) params.append('country', countryFilter)
if (submittedSearchText) params.append('search', submittedSearchText)
if (debouncedSearchText) params.append('search', debouncedSearchText)
return params
}
@@ -331,9 +318,9 @@ export default function DataList() {
}
}
const activeFilterCount = [sourceFilter, typeFilter, countryFilter, submittedSearchText].filter(Boolean).length
const rawActiveFilterCount = [sourceFilter, typeFilter, countryFilter, searchText.trim()].filter(Boolean).length
const sourceOptions = [{ value: 'all', label: '全部数据源' }, ...sources.map((source) => ({ label: source.source_name, value: source.source }))]
const typeOptions = [{ value: 'all', label: '全部类型' }, ...types.map((type) => ({ label: dataTypeLabel(type), value: type }))]
const typeOptions = [{ value: 'all', label: '全部类型' }, ...types.map((type) => ({ label: formatDataTypeLabel(type, false), value: type }))]
const countryOptions = [{ value: 'all', label: '全部国家/地区' }, ...countries.map((country) => ({ label: country, value: country }))]
const columns = useMemo<Array<ColumnDef<CollectedData>>>(() => [
@@ -342,9 +329,16 @@ export default function DataList() {
header: '名称',
size: 320,
cell: ({ row }) => (
<Button variant="link" onClick={() => handleViewDetail(row.original.id)}>
<span className="an-table-name">{row.original.name}</span>
</Button>
<button
type="button"
className="an-table-link"
onClick={(event) => {
event.stopPropagation()
void handleViewDetail(row.original.id)
}}
>
{row.original.name}
</button>
),
},
{
@@ -359,7 +353,7 @@ export default function DataList() {
accessorKey: 'data_type',
header: '数据类型',
size: 160,
cell: ({ row }) => row.original.data_type ? <Badge tone={typeTone(row.original.data_type)} title={row.original.data_type}>{dataTypeLabel(row.original.data_type)}</Badge> : '-',
cell: ({ row }) => row.original.data_type ? <Badge tone={typeTone(row.original.data_type)} title={row.original.data_type}>{formatDataTypeLabel(row.original.data_type, false)}</Badge> : '-',
},
{
accessorKey: 'collected_at',
@@ -391,107 +385,140 @@ export default function DataList() {
.map(([key, value]) => ({ key, label: formatFieldLabel(key), value: formatDetailValue(key, value), isBlock: typeof value === 'object' && value !== null }))
}, [detailData])
const activeLayerMeta = useMemo(
() => layers.find((item) => item.id === activeLayer),
[activeLayer, layers],
)
return (
<AdminLayout>
<div className="an-page an-data-page">
<div className="an-page__header">
<div>
<h1>采集数据</h1>
<p>浏览采集结果、筛选数据源和查看原始元数据。</p>
</div>
<div className="an-toolbar">
<Badge tone="blue">{`结果 ${total.toLocaleString()} 条`}</Badge>
<Badge tone="slate">{`筛选 ${activeFilterCount} 项`}</Badge>
<p>按地球图层分类复核基础设施、台账与原始采集元数据。</p>
</div>
{activeLayer === 'raw' ? (
<div className="an-toolbar">
<Badge tone="blue">{`结果 ${total.toLocaleString()} 条`}</Badge>
<Badge tone="slate">{`筛选 ${rawActiveFilterCount} 项`}</Badge>
</div>
) : null}
</div>
<div className="an-data-layout" style={{ '--an-data-summary-width': `${summaryWidth}px` } as CSSProperties}>
<Card className="an-data-summary">
<CardHeader>
<CardTitle>数据概览</CardTitle>
<div className="an-segmented">
<button type="button" className={distributionDimension === 'source' ? 'is-active' : ''} onClick={() => setDistributionDimension('source')}>按数据源</button>
<button type="button" className={distributionDimension === 'type' ? 'is-active' : ''} onClick={() => setDistributionDimension('type')}>按类型</button>
</div>
</CardHeader>
<CardContent>
<div className="an-summary-kpis">
<div><span>总记录</span><strong>{(summary?.overall_total_records || 0).toLocaleString()}</strong></div>
<div><span>筛选结果</span><strong>{total.toLocaleString()}</strong></div>
<div><span>启用筛选</span><strong>{activeFilterCount}</strong></div>
<div><span>{distributionDimension === 'source' ? '覆盖数据源' : '覆盖类型'}</span><strong>{distributionDimension === 'source' ? summary?.source_totals?.length || 0 : summary?.type_totals?.length || 0}</strong></div>
</div>
<DistributionChart summary={summary} dimension={distributionDimension} />
</CardContent>
</Card>
<div ref={dataLayoutRef} className="an-data-layout" style={{ '--an-data-summary-width': `${summaryWidth}px` } as CSSProperties}>
<LayerNav
layers={layers}
activeLayer={activeLayer}
loading={layersLoading}
onSelectLayer={handleSelectLayer}
/>
<button
type="button"
className="an-detail-resizer an-data-resizer"
onPointerDown={startSummaryResize}
aria-label="拖动调整数据概览宽度"
title="拖动调整数据概览宽度"
aria-label="拖动调整图层导航宽度"
title="拖动调整图层导航宽度"
/>
<Card className="an-data-table-card">
<CardHeader className="an-data-table-card__header">
<div>
<CardTitle>数据列表</CardTitle>
<p>{`共 ${total.toLocaleString()} 条结果`}</p>
</div>
<div className="an-toolbar">
<Button size="sm" variant="subtle" onClick={handleReset}><X size={14} />清空</Button>
<Button size="sm" variant="subtle" onClick={() => void fetchData()}><RefreshCw size={14} />刷新</Button>
<Button size="sm" variant="subtle" onClick={() => void downloadExport('json')} title="导出 JSON"><Download size={14} />JSON</Button>
<Button size="sm" variant="subtle" onClick={() => void downloadExport('csv')} title="导出 CSV"><Download size={14} />CSV</Button>
<Button size="sm" variant="primary" onClick={handleSearch}><Search size={14} />搜索</Button>
</div>
</CardHeader>
<CardContent>
<div className="an-filter-grid">
<Select
value={sourceFilter || 'all'}
onValueChange={(value) => {
setSourceFilter(value === 'all' ? '' : value)
setPage(1)
}}
options={sourceOptions}
/>
<Select
value={typeFilter || 'all'}
onValueChange={(value) => {
setTypeFilter(value === 'all' ? '' : value)
setPage(1)
}}
options={typeOptions}
/>
<Select
value={countryFilter || 'all'}
onValueChange={(value) => {
setCountryFilter(value === 'all' ? '' : value)
setPage(1)
}}
options={countryOptions}
/>
<Input
placeholder="搜索名称、描述、元数据等"
value={searchText}
onChange={(event) => setSearchText(event.target.value)}
onKeyDown={(event) => {
if (event.key === 'Enter') handleSearch()
{activeLayer === 'compute' ? (
<ComputeLedger onMutated={() => void fetchLayers()} />
) : activeLayer === 'raw' ? (
<Card className="an-data-table-card">
<CardHeader className="an-data-table-card__header">
<div>
<CardTitle>数据列表</CardTitle>
<p>{`共 ${total.toLocaleString()} 条结果`}</p>
</div>
<div className="an-toolbar">
<Button size="sm" variant="subtle" onClick={() => void fetchRawData()}><RefreshCw size={14} />刷新</Button>
<Button size="sm" variant="subtle" onClick={() => void downloadExport('json')} title="导出 JSON"><Download size={14} />JSON</Button>
<Button size="sm" variant="subtle" onClick={() => void downloadExport('csv')} title="导出 CSV"><Download size={14} />CSV</Button>
</div>
</CardHeader>
<CardContent>
<div className="an-ledger-raw-controls">
<div className="an-filter-grid--datasources an-filter-grid--ledger">
<div className="an-field an-field--inline-filter">
<Select
value={sourceFilter || 'all'}
onValueChange={(value) => setSourceFilter(value === 'all' ? '' : value)}
options={sourceOptions}
/>
</div>
<div className="an-field an-field--inline-filter">
<Select
value={typeFilter || 'all'}
onValueChange={(value) => setTypeFilter(value === 'all' ? '' : value)}
options={typeOptions}
/>
</div>
<div className="an-field an-field--inline-filter">
<Select
value={countryFilter || 'all'}
onValueChange={(value) => setCountryFilter(value === 'all' ? '' : value)}
options={countryOptions}
/>
</div>
<div className="an-search-box an-search-box--inline">
<Search size={14} aria-hidden="true" />
<Input
placeholder="搜索名称、描述、元数据等"
aria-label="搜索名称、描述、元数据等"
value={searchText}
onChange={(event) => setSearchText(event.target.value)}
/>
{searchText ? (
<Button
size="icon"
variant="ghost"
onClick={() => setSearchText('')}
title="清空搜索"
aria-label="清空搜索"
>
<X size={14} />
</Button>
) : null}
</div>
<Button
size="icon"
variant="subtle"
onClick={handleReset}
disabled={rawActiveFilterCount === 0}
title="重置筛选"
aria-label="重置筛选"
>
<RotateCcw size={14} />
</Button>
</div>
</div>
<DataTable
columns={columns}
data={data}
getRowId={(row) => String(row.id)}
loading={loading}
columnWidthStorageKey="planet.table.widths.ledger.raw"
scrollResetKey={`${sourceFilter}|${typeFilter}|${countryFilter}|${debouncedSearchText}`}
onRowClick={(row) => void handleViewDetail(row.id)}
waterfall={{
total,
hasMore,
loadingMore,
onLoadMore: () => void loadMoreRawData(),
showFooter: true,
}}
/>
</div>
<DataTable
columns={columns}
data={data}
getRowId={(row) => String(row.id)}
loading={loading}
onRowClick={(row) => handleViewDetail(row.id)}
footer={<DataTablePager page={page} pageSize={pageSize} total={total} onPageChange={setPage} />}
/>
</CardContent>
</Card>
</CardContent>
</Card>
) : (
<LayerItemsLedger
key={activeLayer}
layerId={activeLayer}
layerName={activeLayerMeta?.name || activeLayer}
initialKinds={activeLayerMeta?.kinds || []}
/>
)}
</div>
</div>
@@ -0,0 +1,542 @@
import axios from 'axios'
import {
DatabaseZap,
Globe2,
Layers,
RefreshCw,
RotateCcw,
Save,
Settings2,
Trash2,
} 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 { useAuthStore } from '../../stores/auth'
import { SplitPaneResizer, useSplitPaneResize } from '../components/layout/SplitPaneResizer'
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 { Select } from '../components/ui/select'
import { AdminSwitch } from '../components/ui/switch'
import { Panel, StatusText } from '../patterns/patterns'
import './earth-cloud-map.css'
export const EARTH_BASEMAP_API = '/api/v1/earth/basemap'
export const EARTH_BASEMAP_CHANNEL = 'planet-earth-basemap'
export type BasemapActiveSource = 'static' | 'earth_imagery_sentinel2' | 'earth_imagery_viirs_daily'
export interface BasemapConfig {
active_source: BasemapActiveSource
hd_tiles_enabled: boolean
cloud_hd_tiles_enabled: boolean
lod_switch_altitude: number
max_zoom: number
warmup_max_zoom: number
max_cache_mb: number
request_timeout_seconds: number
}
export interface TileSourceStatusItem {
source: string
display_name: string
is_active: boolean
has_data: boolean
cached_tiles: number
cache_mb: number
zoom_levels: number[]
max_zoom: number
warmup_max_zoom: number
max_cache_mb: number
tile_url_template: string
upstream_template: string
}
export interface BasemapRuntimeMeta {
active_source: BasemapActiveSource
hd_tiles_enabled: boolean
cloud_hd_tiles_enabled: boolean
hd_tiles_ready: boolean
cloud_hd_tiles_ready: boolean
lod_switch_altitude: number
max_zoom: number
warmup_max_zoom: number
max_cache_mb: number
tile_url_template: string | null
cloud_tile_url_template: string | null
sources: TileSourceStatusItem[]
}
export interface BasemapConfigurationEnvelope {
config: BasemapConfig
revision: string
is_default: boolean
meta: BasemapRuntimeMeta
}
function notifyBasemapChanged(detail: Record<string, unknown> = {}) {
if (typeof BroadcastChannel === 'undefined') return
try {
const channel = new BroadcastChannel(EARTH_BASEMAP_CHANNEL)
channel.postMessage({ type: 'basemap_updated', ...detail })
channel.close()
} catch {
// Ignore unsupported BroadcastChannel environments.
}
}
function describeBasemapError(error: unknown, english: boolean): string {
if (!axios.isAxiosError(error)) return english ? 'Request failed.' : '请求失败。'
const status = error.response?.status
if (status === 409) {
return english
? 'Configuration changed by another editor. Reload and retry.'
: '配置已被其他编辑者更新,请刷新后重试。'
}
const detail = error.response?.data?.detail
if (typeof detail === 'string' && detail.trim()) return detail
return error.message || (english ? 'Request failed.' : '请求失败。')
}
function toNumberOr(raw: string, fallback: number, min: number, max: number): number {
const num = Number(raw)
if (!Number.isFinite(num)) return fallback
return Math.max(min, Math.min(max, num))
}
function BasemapField({
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>
)
}
export function EarthBasemapSettings({ active }: { active: boolean }) {
const { locale } = useLocale()
const english = locale === 'en-US'
const t = useCallback((zh: string, en: string) => (english ? en : zh), [english])
const user = useAuthStore((s) => s.user)
const role = String(user?.role || '').toLowerCase()
const canEdit = role === 'admin' || role === 'super_admin'
const [envelope, setEnvelope] = useState<BasemapConfigurationEnvelope | null>(null)
const [draft, setDraft] = useState<BasemapConfig | null>(null)
const [previewSource, setPreviewSource] = useState<string>('earth_imagery_sentinel2')
const [busy, setBusy] = useState(false)
const [error, setError] = useState('')
const [message, setMessage] = useState('')
const [confirmAction, setConfirmAction] = useState<null | 'reset' | 'reload'>(null)
const [clearTarget, setClearTarget] = useState<string | null>(null)
const workspaceRef = useRef<HTMLDivElement | null>(null)
const workspaceResize = useSplitPaneResize({
containerRef: workspaceRef,
storageKey: 'an_earth_basemap_config_width',
defaultWidth: 380,
minWidth: 320,
maxWidth: 540,
minOppositeWidth: 340,
})
const loadConfiguration = useCallback(async () => {
setBusy(true)
setError('')
try {
const response = await axios.get<BasemapConfigurationEnvelope>(`${EARTH_BASEMAP_API}/configuration`)
setEnvelope(response.data)
setDraft(response.data.config)
if (response.data.config.active_source !== 'static') {
setPreviewSource(response.data.config.active_source)
}
} catch (err) {
setError(describeBasemapError(err, english))
} finally {
setBusy(false)
}
}, [english])
useEffect(() => {
if (!active) return
void loadConfiguration()
}, [active, loadConfiguration])
const dirty = useMemo(() => {
if (!envelope || !draft) return false
return JSON.stringify(envelope.config) !== JSON.stringify(draft)
}, [draft, envelope])
const patchDraft = useCallback((patch: Partial<BasemapConfig>) => {
setDraft((prev) => (prev ? { ...prev, ...patch } : prev))
setMessage('')
setError('')
}, [])
const handleSave = useCallback(async () => {
if (!envelope || !draft) return
setBusy(true)
setError('')
setMessage('')
try {
const response = await axios.put<BasemapConfigurationEnvelope>(`${EARTH_BASEMAP_API}/configuration`, {
revision: envelope.revision,
config: draft,
})
setEnvelope(response.data)
setDraft(response.data.config)
setMessage(t('高清底图策略已保存并同步至智能星球。', 'Basemap settings saved and synced.'))
notifyBasemapChanged({ active_source: response.data.config.active_source })
} catch (err) {
setError(describeBasemapError(err, english))
} finally {
setBusy(false)
}
}, [draft, english, envelope, t])
const handleReset = useCallback(async () => {
if (!envelope) return
setConfirmAction(null)
setBusy(true)
setError('')
try {
const response = await axios.post<BasemapConfigurationEnvelope>(`${EARTH_BASEMAP_API}/configuration/reset`, {
revision: envelope.revision,
config: {},
})
setEnvelope(response.data)
setDraft(response.data.config)
setMessage(t('已恢复底图默认配置。', 'Basemap settings restored to defaults.'))
notifyBasemapChanged({ reset: true })
} catch (err) {
setError(describeBasemapError(err, english))
} finally {
setBusy(false)
}
}, [english, envelope, t])
const handleClearTileCache = useCallback(async (sourceKey: string) => {
setClearTarget(null)
setBusy(true)
setError('')
try {
await axios.delete(`/api/v1/earth/tiles/${encodeURIComponent(sourceKey)}/cache`)
setMessage(t(`已清理 ${sourceKey} 瓦片缓存。`, `Cleared tile cache for ${sourceKey}.`))
await loadConfiguration()
} catch (err) {
setError(describeBasemapError(err, english))
} finally {
setBusy(false)
}
}, [english, loadConfiguration, t])
const meta = envelope?.meta
const sources = meta?.sources || []
const activePreviewItem = sources.find((item) => item.source === previewSource) || sources[0]
return (
<Panel className="an-cloud-settings" hidden={!active}>
<div className="an-cloud-toolbar">
<div className="an-cloud-toolbar__title">
<Globe2 size={18} />
<h2>{t('地球高清底图与瓦片金字塔', 'High-Res Earth Basemap & Tile Pyramid')}</h2>
<StatusText tone={meta?.hd_tiles_ready ? 'success' : 'warning'}>
{meta?.hd_tiles_ready
? t('高清瓦片代理就绪', 'HD Tile Proxy Ready')
: t('当前使用静态 8K 底图', 'Static 8K Fallback')}
</StatusText>
</div>
<div className="an-cloud-toolbar__actions">
<Button asChild size="sm" variant="subtle">
<Link to="/datasources?product=geo">
<DatabaseZap size={14} />
{t('地理底图数据源', 'Geo 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="blue">{activePreviewItem?.display_name || previewSource}</Badge>
<Badge tone={activePreviewItem?.is_active ? 'green' : 'amber'}>
{activePreviewItem?.is_active ? t('代理开放', 'Proxy Active') : t('已停用', 'Disabled')}
</Badge>
<Badge tone="cyan">
{activePreviewItem ? `${activePreviewItem.cached_tiles} tiles · ${activePreviewItem.cache_mb} MB` : '0 tiles'}
</Badge>
</div>
</div>
{activePreviewItem?.is_active ? (
<div className="an-cloud-canvas">
<img
className="an-cloud-canvas__img"
src={`/api/v1/earth/tiles/${encodeURIComponent(activePreviewItem.source)}/0/0/0.webp`}
alt={activePreviewItem.display_name}
/>
</div>
) : (
<p className="an-cloud-banner">
{t('该瓦片数据源尚未启用,请前往数据源页面开启调度。', 'This tile source is currently inactive in Datasources.')}
</p>
)}
<div className="an-cloud-kpis">
{sources.map((src) => (
<div key={src.source} className="an-cloud-kpi">
<span>{english ? src.source : src.display_name}</span>
<strong>{src.cached_tiles} tiles</strong>
<small>{src.cache_mb} MB · Z0–Z{src.max_zoom}</small>
<div className="an-cloud-links">
<Button
type="button"
size="sm"
variant={previewSource === src.source ? 'primary' : 'subtle'}
onClick={() => setPreviewSource(src.source)}
>
<Layers size={13} />
{t('预览', 'Preview')}
</Button>
<Button
type="button"
size="sm"
variant="subtle"
disabled={!canEdit || busy || src.cached_tiles === 0}
onClick={() => setClearTarget(src.source)}
>
<Trash2 size={13} />
{t('清缓存', 'Clear')}
</Button>
</div>
</div>
))}
</div>
</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('拉近视口自动加载高清分块底图 (HD LOD Tiles)', 'Enable viewport-LOD HD basemap tiles')}</span>
<AdminSwitch
checked={draft.hd_tiles_enabled}
disabled={!canEdit || busy}
onCheckedChange={(checked) => patchDraft({ hd_tiles_enabled: checked })}
label={t('高清底图 LOD 瓦片', 'HD basemap LOD tiles')}
/>
</div>
<div className="an-cloud-switch-row">
<span>{t('拉近视口叠加高清局部红外云图瓦片', 'Overlay HD regional Band13 cloud tiles on zoom')}</span>
<AdminSwitch
checked={draft.cloud_hd_tiles_enabled}
disabled={!canEdit || busy}
onCheckedChange={(checked) => patchDraft({ cloud_hd_tiles_enabled: checked })}
label={t('高清云图瓦片叠加', 'HD cloud tile overlay')}
/>
</div>
<div className="an-cloud-fields">
<BasemapField label={t('默认高分卫星底图源', 'Active Satellite Basemap Source')} full>
<Select
value={draft.active_source}
disabled={!canEdit || busy}
onValueChange={(value) => {
const nextSrc = value as BasemapActiveSource
patchDraft({ active_source: nextSrc })
if (nextSrc !== 'static') setPreviewSource(nextSrc)
}}
options={[
{ value: 'earth_imagery_sentinel2', label: t('Sentinel-2 无云 2024 高分影像', 'Sentinel-2 Cloudless 2024') },
{ value: 'earth_imagery_viirs_daily', label: t('NASA GIBS VIIRS 每日真彩', 'NASA VIIRS SNPP Daily TrueColor') },
{ value: 'static', label: t('仅使用本地 8K 静态底图', 'Static 8K Fallback Only') },
]}
/>
</BasemapField>
<BasemapField label={t('LOD 切入相机高度比 (1.2–5.0)', 'LOD Switch Altitude Ratio (1.2–5.0)')}>
<Input
type="number"
step="0.1"
min={1.2}
max={5}
disabled={!canEdit || busy}
value={String(draft.lod_switch_altitude)}
onChange={(e) =>
patchDraft({ lod_switch_altitude: toNumberOr(e.target.value, 1.85, 1.2, 5.0) })
}
/>
</BasemapField>
<BasemapField label={t('代理最大允许缩放级别 (2–10)', 'Max Proxy Zoom Level (2–10)')}>
<Input
type="number"
min={2}
max={10}
disabled={!canEdit || busy}
value={String(draft.max_zoom)}
onChange={(e) => patchDraft({ max_zoom: Math.round(toNumberOr(e.target.value, 7, 2, 10)) })}
/>
</BasemapField>
<BasemapField label={t('定期预热最大层级 (1–4)', 'Warmup Pyramid Max Zoom (1–4)')}>
<Input
type="number"
min={1}
max={4}
disabled={!canEdit || busy}
value={String(draft.warmup_max_zoom)}
onChange={(e) => patchDraft({ warmup_max_zoom: Math.round(toNumberOr(e.target.value, 3, 1, 4)) })}
/>
</BasemapField>
<BasemapField label={t('单源缓存 LRU 上限 (MB)', 'Per-Source Disk LRU Cap (MB)')}>
<Input
type="number"
min={128}
max={8192}
disabled={!canEdit || busy}
value={String(draft.max_cache_mb)}
onChange={(e) => patchDraft({ max_cache_mb: Math.round(toNumberOr(e.target.value, 1024, 128, 8192)) })}
/>
</BasemapField>
</div>
<div className="an-cloud-probe-box">
<div className="an-cloud-probe-row">
<strong>{t('瓦片代理治理说明', 'Tile Governance')}</strong>
<Badge tone="green">/api/v1/earth/tiles/*</Badge>
</div>
<p className="an-cloud-banner">
{t(
'高清瓦片统一由后端代理并按 LRU 限制落盘,严格受数据源开关控制。',
'All HD tiles flow through the managed backend proxy with disk LRU pruning and DataSource active gating.',
)}
</p>
<div className="an-cloud-links">
<Button asChild size="sm" variant="subtle">
<Link to="/datasources?product=geo">
<DatabaseZap size={14} />
{t('地理底图数据源', 'Geo Datasources')}
</Link>
</Button>
<Button asChild size="sm" variant="subtle">
<Link to="/collection-management">
<Settings2 size={14} />
{t('采集器参数配置', 'Collector Parameters')}
</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 || clearTarget !== null}
onOpenChange={(open) => {
if (!open) {
setConfirmAction(null)
setClearTarget(null)
}
}}
title={
clearTarget
? t(`清理 ${clearTarget} 本地瓦片缓存?`, `Clear local tile cache for ${clearTarget}?`)
: confirmAction === 'reset'
? t('恢复默认底图配置?', 'Reset basemap configuration?')
: t('放弃未保存的改动并重新加载?', 'Discard unsaved edits and reload?')
}
description={
clearTarget
? t('清理后系统会在下次视口请求或定时预热时按需重新缓存。', 'Tiles will be re-cached on demand or during the next warmup job.')
: confirmAction === 'reset'
? t('将恢复 Sentinel-2 / VIIRS 与高清云图瓦片默认参数。', 'Default basemap & LOD parameters will be restored.')
: t('未保存的表单改动将会丢失。', 'Unsaved form changes will be lost.')
}
confirmLabel={t('确认', 'Confirm')}
cancelLabel={t('取消', 'Cancel')}
danger={clearTarget !== null}
onConfirm={() => {
if (clearTarget) void handleClearTileCache(clearTarget)
else if (confirmAction === 'reset') void handleReset()
else {
setConfirmAction(null)
void loadConfiguration()
}
}}
/>
</Panel>
)
}
@@ -0,0 +1,600 @@
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>
)
}
+25 -2
View File
@@ -1,12 +1,13 @@
import axios from 'axios'
import { Copy, Pause, Play, RefreshCw, Search, X } from 'lucide-react'
import { useEffect, useMemo, useRef, useState } from 'react'
import { useEffect, useMemo, useRef, useState, type CSSProperties } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
import Scrollbar from '../../components/Scrollbar/Scrollbar'
import { useWebSocket } from '../../hooks/useWebSocket'
import { describeApiError } from '../../i18n/api-errors'
import { useAuthStore } from '../../stores/auth'
import { AdminLayout } from '../components/layout/AdminLayout'
import { SplitPaneResizer, useSplitPaneResize } from '../components/layout/SplitPaneResizer'
import { Badge } from '../components/ui/badge'
import { Button } from '../components/ui/button'
import { Input } from '../components/ui/input'
@@ -484,6 +485,17 @@ export default function Logs() {
toast({ tone: 'success', title: '日志已复制' })
}
const logsLayoutRef = useRef<HTMLDivElement | null>(null)
const logsResize = useSplitPaneResize({
storageKey: 'planet.admin.logsSidebarWidth',
defaultWidth: 280,
minWidth: 210,
maxWidth: 480,
minOppositeWidth: 360,
side: 'left',
containerRef: logsLayoutRef,
})
if (!isSuperAdmin) {
return (
<AdminLayout>
@@ -549,7 +561,11 @@ export default function Logs() {
)
})}
</div>
<div className="an-logs-layout">
<div
ref={logsLayoutRef}
className="an-logs-layout"
style={{ '--an-logs-sidebar-width': `${logsResize.width}px` } as CSSProperties}
>
<Panel className="an-logs-sidebar">
<div className="an-panel-heading">
<div>
@@ -593,6 +609,13 @@ export default function Logs() {
)}
</Panel>
<SplitPaneResizer
label="拖动调整日志源列表宽度"
isDragging={logsResize.isDragging}
onPointerDown={logsResize.onPointerDown}
onKeyDown={logsResize.onKeyDown}
/>
<Panel className="an-logs-main">
<div className="an-panel-heading">
<div>
+334 -95
View File
@@ -33,18 +33,21 @@ import {
Trash2,
X,
} from 'lucide-react'
import { useCallback, useEffect, useMemo, useRef, useState, type ChangeEvent, type CSSProperties, type DragEvent as ReactDragEvent, type PointerEvent as ReactPointerEvent, type ReactNode } from 'react'
import { memo, useCallback, useEffect, useMemo, useRef, useState, type ChangeEvent, type CSSProperties, type DragEvent as ReactDragEvent, type PointerEvent as ReactPointerEvent, type ReactNode } from 'react'
import { Link, Navigate, useLocation, useNavigate } from 'react-router-dom'
import MarkdownRenderer from '../../components/MarkdownRenderer/MarkdownRenderer'
import Scrollbar from '../../components/Scrollbar/Scrollbar'
import { useWebSocket } from '../../hooks/useWebSocket'
import { formatDateTimeZhCN, parseBackendDate } from '../../utils/datetime'
import { describeApiError, localizeApiMessage } from '../../i18n/api-errors'
import { translateLegacyAdminText } from '../../i18n/LegacyI18nBridge'
import { useLocale, type SupportedLocale } from '../../i18n/locale'
import { AdminLayout } from '../components/layout/AdminLayout'
import { SPLIT_RESIZE_END_EVENT, SplitPaneResizer, useSplitPaneResize } from '../components/layout/SplitPaneResizer'
import { DataTable } from '../components/data-table/DataTable'
import { DatasourceBatchBar, type DatasourceBatchAction } from '../components/datasources/DatasourceBatchBar'
import { Button, type ButtonProps } from '../components/ui/button'
import { TableActionButton } from '../components/ui/table-action-button'
import { ConfirmDialog, Dialog } from '../components/ui/dialog'
import { Input, Textarea } from '../components/ui/input'
import { Select } from '../components/ui/select'
@@ -55,6 +58,9 @@ import type { AdminSearchTarget } from '../search/types'
import { DetailPanel, EmptyState, PageFrame, Panel, StatCell, StatusText, SummaryStrip } from '../patterns/patterns'
import { ComputeComparisonSettings } from './ComputeComparisonSettings'
import { CardImageSettings } from './CardImageSettings'
import { EarthBasemapSettings } from './EarthBasemapSettings'
import { EarthCloudMapSettings } from './EarthCloudMapSettings'
import { DEFAULT_EARTH_BRAND_LOGO_PATH, resolveEarthPreviewAssetUrl } from '../lib/earthBuiltinAssets'
import { ApiKeySettings } from './ApiKeySettings'
import {
DATASOURCE_SECRET_KEYS as datasourceSecretKeys,
@@ -64,6 +70,7 @@ import {
parsePositiveConfigId,
recordContainsSecrets,
redactRawJsonText,
resolveDatasourceProductLabel,
shouldHideDatasourceConfigObjectField,
} from './datasourceConfigHelpers'
import {
@@ -296,14 +303,24 @@ function pick(record: AnyRecord, keys: string[], fallback = '-') {
return fallback
}
function formatCountZh(value: number) {
function formatCount(value: number, locale: SupportedLocale = 'zh-CN') {
if (!Number.isFinite(value)) return '-'
const count = Math.max(0, Math.round(value))
if (locale === 'en-US') {
if (count >= 1000000000) return `${(count / 1000000000).toFixed(count >= 10000000000 ? 1 : 2).replace(/\.0+$/, '')}B items`
if (count >= 1000000) return `${(count / 1000000).toFixed(count >= 10000000 ? 1 : 2).replace(/\.0+$/, '')}M items`
if (count >= 10000) return `${(count / 1000).toFixed(count >= 100000 ? 1 : 2).replace(/\.0+$/, '')}K items`
return `${count.toLocaleString('en-US')} items`
}
if (count >= 100000000) return `${(count / 100000000).toFixed(count >= 1000000000 ? 1 : 2).replace(/\.0+$/, '')} 亿条`
if (count >= 10000) return `${(count / 10000).toFixed(count >= 100000 ? 1 : 2).replace(/\.0+$/, '')} 万条`
return `${count.toLocaleString('zh-CN')} 条`
}
function formatCountZh(value: number) {
return formatCount(value, 'zh-CN')
}
function datasourceRecordCount(record: AnyRecord) {
const candidates = [record.__metric_count, record.collected_records, record.record_count, record.records, record.count, record.total]
for (const value of candidates) {
@@ -718,7 +735,7 @@ function DetailFields({ record }: { record: AnyRecord }) {
{entries.map(([key, value]) => (
<div key={key}>
<dt>{fieldLabel(key, locale)}</dt>
<dd>{localizeDisplayValue(semanticLabel(value), locale)}</dd>
<dd>{localizeDisplayValue(semanticLabel(value, locale), locale)}</dd>
</div>
))}
</dl>
@@ -745,10 +762,37 @@ function DetailMarkdownDocument({ record }: { record: AnyRecord }) {
)
}
function formatResourceTableTime(raw: string, locale: SupportedLocale): string {
const trimmed = raw.trim()
if (!trimmed || trimmed === '-') return '-'
if (/^\d{4}-\d{2}-\d{2}/.test(trimmed)) {
const parsed = parseBackendDate(trimmed)
if (parsed && !Number.isNaN(parsed.getTime())) {
return formatDateTimeZhCN(trimmed) || String(localizeDisplayValue(raw, locale) ?? '-')
}
}
return String(localizeDisplayValue(raw, locale) ?? '-')
}
function sortableTimeValue(raw: string): number {
const parsed = raw && raw !== '-' ? parseBackendDate(raw) : null
return parsed && !Number.isNaN(parsed.getTime()) ? parsed.getTime() : 0
}
function sortableMetricValue(record: TableRecord): number {
for (const key of ['collected_records', 'record_count', 'records_processed', 'count', 'total', 'value', 'records', 'events', 'score', 'latency_ms']) {
const val = record[key]
if (typeof val === 'number' && Number.isFinite(val)) return val
}
const parsed = Number.parseFloat(String(recordMetric(record) || '').replace(/[^\d.-]/g, ''))
return Number.isFinite(parsed) ? parsed : -1
}
function defaultColumns(onSelect: (record: TableRecord) => void, locale: SupportedLocale): Array<ColumnDef<TableRecord>> {
return [
{
id: 'name',
accessorFn: (row) => recordTitle(row),
header: localizeAdminText('名称', locale),
size: 260,
cell: ({ row }) => (
@@ -757,9 +801,16 @@ function defaultColumns(onSelect: (record: TableRecord) => void, locale: Support
</button>
),
},
{ id: 'module', header: localizeAdminText('模块', locale), size: 150, cell: ({ row }) => localizeDisplayValue(row.original.__module, locale) },
{
id: 'module',
accessorFn: (row) => String(row.__module || ''),
header: localizeAdminText('模块', locale),
size: 150,
cell: ({ row }) => localizeDisplayValue(row.original.__module, locale),
},
{
id: 'status',
accessorFn: (row) => recordDisplayStatus(row),
header: localizeAdminText('状态', locale),
size: 130,
cell: ({ row }) => {
@@ -767,22 +818,37 @@ function defaultColumns(onSelect: (record: TableRecord) => void, locale: Support
return <StatusText tone={statusTone(status)}>{localizeDisplayValue(status, locale)}</StatusText>
},
},
{ id: 'metric', header: localizeAdminText('指标', locale), size: 220, cell: ({ row }) => <span className="an-muted-text">{localizeDisplayValue(semanticLabel(recordMetric(row.original)), locale)}</span> },
{ id: 'updated', header: localizeAdminText('更新时间', locale), size: 180, cell: ({ row }) => localizeDisplayValue(row.original.__time, locale) },
{
id: 'metric',
accessorFn: (row) => sortableMetricValue(row),
header: localizeAdminText('指标', locale),
size: 220,
cell: ({ row }) => <span className="an-muted-text">{localizeDisplayValue(semanticLabel(recordMetric(row.original), locale), locale)}</span>,
},
{
id: 'updated',
accessorFn: (row) => sortableTimeValue(row.__time),
header: localizeAdminText('更新时间', locale),
size: 180,
cell: ({ row }) => formatResourceTableTime(row.original.__time, locale),
},
]
}
function ModuleTable({
const EMPTY_TABLE_ROWS: TableRecord[] = []
const ModuleTable = memo(function ModuleTable({
rows,
selected,
selectedRowId,
onSelect,
columns,
selection,
loading,
columnWidthStorageKey,
className = '',
}: {
rows: TableRecord[]
selected: TableRecord | null
selectedRowId?: string | null
onSelect: (record: TableRecord) => void
columns?: Array<ColumnDef<TableRecord>>
selection?: {
@@ -793,27 +859,34 @@ function ModuleTable({
isRowSelectable?: (row: TableRecord) => boolean
}
loading?: boolean
columnWidthStorageKey?: string
className?: string
}) {
const { locale } = useLocale()
const tableColumns = useMemo(() => columns || defaultColumns(onSelect, locale), [columns, locale, onSelect])
const getRowClassName = useCallback(
(row: TableRecord) => [
row.__rowId === selectedRowId ? 'is-selected' : '',
row.__filterStale ? 'is-filter-stale' : '',
].filter(Boolean).join(' ') || undefined,
[selectedRowId],
)
const getRowId = useCallback((row: TableRecord) => row.__rowId, [])
return (
<DataTable
className={`an-resource-table${className ? ` ${className}` : ''}`}
columns={tableColumns}
data={rows}
emptyText={localizeAdminText('当前模块暂无数据', locale)}
getRowClassName={(row) => [
row.__rowId === selected?.__rowId ? 'is-selected' : '',
row.__filterStale ? 'is-filter-stale' : '',
].filter(Boolean).join(' ') || undefined}
getRowId={(row) => row.__rowId}
getRowClassName={getRowClassName}
getRowId={getRowId}
loading={loading}
onRowClick={onSelect}
selection={selection}
columnWidthStorageKey={columnWidthStorageKey}
/>
)
}
})
function SectionTabs({
sections,
@@ -1022,6 +1095,9 @@ const fieldLabels: Record<string, string> = {
auth_type: '认证方式',
auth_config: '认证配置',
auth_configured: '认证状态',
config_id: '配置 ID',
api_key_name: 'API Key 名称',
api_key_location: 'API Key 位置',
datasource_config_id: '采集器配置',
target_schema: '目标 Schema',
sample_payload: '采样 Payload',
@@ -1092,6 +1168,7 @@ const fieldHelp: Record<string, string> = {
}
function fieldLabel(key: string, locale?: SupportedLocale) {
if (locale === 'en-US' && key === 'key') return 'Key'
const label = fieldLabels[key] || key.replace(/_/g, ' ')
return locale ? localizeAdminText(label, locale) : label
}
@@ -1107,9 +1184,14 @@ function fieldLabelElement(key: string, locale?: SupportedLocale) {
)
}
function semanticLabel(value: unknown) {
function semanticLabel(value: unknown, locale?: SupportedLocale) {
const raw = text(value, '')
const lower = raw.toLowerCase()
if (locale === 'en-US') {
if (lower === 'true') return 'Yes'
if (lower === 'false') return 'No'
if (lower === 'empty') return 'Empty'
}
const labels: Record<string, string> = {
success: '成功',
completed: '完成',
@@ -1410,12 +1492,16 @@ function snapshotModeDescription(mode: unknown) {
return '仅保留最新 1 份数据,按实体差异原地增量更新,未变化记录零写入,极省硬盘容量。'
}
function snapshotOptionLabel(record: AnyRecord) {
const current = record.is_current === true ? '当前 · ' : ''
const status = semanticLabel(snapshotStatus(record))
const count = typeof record.record_count === 'number' ? formatCountZh(record.record_count) : pick(record, ['record_count'], '0 条')
function snapshotOptionLabel(record: AnyRecord, locale: SupportedLocale = 'zh-CN') {
const current = record.is_current === true ? (locale === 'en-US' ? 'Current · ' : '当前 · ') : ''
const status = localizeAdminText(semanticLabel(snapshotStatus(record), locale), locale)
const count = typeof record.record_count === 'number'
? formatCount(record.record_count, locale)
: pick(record, ['record_count'], locale === 'en-US' ? '0 items' : '0 条')
const milestoneYear = isObjectRecord(record.summary) ? record.summary.milestone_year : null
const milestoneSuffix = milestoneYear ? ` · 年末里程碑 (${String(milestoneYear)})` : ''
const milestoneSuffix = milestoneYear
? (locale === 'en-US' ? ` · Year-end milestone (${String(milestoneYear)})` : ` · 年末里程碑 (${String(milestoneYear)})`)
: ''
return `${current}${formatSnapshotTime(record)} · ${status} · ${count}${milestoneSuffix}`
}
@@ -1905,7 +1991,7 @@ function makeNewDatasourceConfigGroup(index: number): HierarchyGroup {
return {
key: 'collection:new-config',
label: '新增采集器',
description: '采集器配置',
description: '自定义源',
status: '新建',
count: 12,
record: {
@@ -1924,7 +2010,7 @@ function makeNewDatasourceConfigGroup(index: number): HierarchyGroup {
__sourceEndpoint: 'configsAll',
__sourceLabel: '采集器配置',
__isDraft: true,
__module: '采集器配置',
__module: '自定义源',
__status: '新建',
},
}
@@ -1956,8 +2042,12 @@ function makeNewMappingGroup(index: number, datasourceConfigId = ''): HierarchyG
function EarthBrandPreview({ record }: { record: AnyRecord }) {
const { locale } = useLocale()
const logoSrc = text(record.logo_src, '/earth/assets/brand/earth-logo.png')
const titleSrc = text(localizeEditableValue('title_src', text(record.title_src, ''), locale), '')
const logoSrc = resolveEarthPreviewAssetUrl(
text(record.logo_src, DEFAULT_EARTH_BRAND_LOGO_PATH),
DEFAULT_EARTH_BRAND_LOGO_PATH,
)
const rawTitleSrc = text(localizeEditableValue('title_src', text(record.title_src, ''), locale), '')
const titleSrc = rawTitleSrc ? resolveEarthPreviewAssetUrl(rawTitleSrc) : ''
const titleText = text(localizeEditableValue('title_text', text(record.title_text, '智能星球计划'), locale), '智能星球计划')
const titleAlt = text(record.title_alt, titleText)
const localizedTitleAlt = text(localizeEditableValue('title_alt', titleAlt, locale), titleText)
@@ -2724,6 +2814,24 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
const [mobileResourceDetailOpen, setMobileResourceDetailOpen] = useState(false)
const [mobileHierarchyDetailOpen, setMobileHierarchyDetailOpen] = useState(false)
const [detailWidth, setDetailWidth] = useState(360)
const detailWidthRef = useRef(detailWidth)
detailWidthRef.current = detailWidth
const resourceLayoutRef = useRef<HTMLDivElement | null>(null)
const detailResizeCleanupRef = useRef<(() => void) | null>(null)
useEffect(() => () => {
detailResizeCleanupRef.current?.()
}, [])
const hierarchyLayoutRef = useRef<HTMLDivElement | null>(null)
const hierarchyResize = useSplitPaneResize({
storageKey: 'planet.admin.hierarchyWidth',
defaultWidth: 290,
minWidth: 220,
maxWidth: 520,
minOppositeWidth: 360,
side: 'left',
containerRef: hierarchyLayoutRef,
})
const [advancedJson, setAdvancedJson] = useState('')
const [revealedSecrets, setRevealedSecrets] = useState<Record<string, AnyRecord>>({})
const [visibleSecretFields, setVisibleSecretFields] = useState<Record<string, boolean>>({})
@@ -2743,22 +2851,51 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
run: () => Promise<void>
}>(null)
const startDetailResize = (event: ReactPointerEvent<HTMLButtonElement>) => {
const startDetailResize = useCallback((event: ReactPointerEvent<HTMLButtonElement>) => {
event.preventDefault()
detailResizeCleanupRef.current?.()
const startX = event.clientX
const startWidth = detailWidth
const handleMove = (moveEvent: PointerEvent) => {
setDetailWidth(Math.min(640, Math.max(300, startWidth - (moveEvent.clientX - startX))))
const startWidth = detailWidthRef.current
let latestWidth = startWidth
let rafId = 0
const applyFrame = () => {
rafId = 0
resourceLayoutRef.current?.style.setProperty('--an-detail-width', `${latestWidth}px`)
}
const stopMove = () => {
const handleMove = (moveEvent: PointerEvent) => {
latestWidth = Math.min(640, Math.max(300, Math.round(startWidth - (moveEvent.clientX - startX))))
if (!rafId) {
rafId = window.requestAnimationFrame(applyFrame)
}
}
const cleanupListeners = () => {
if (rafId) {
window.cancelAnimationFrame(rafId)
rafId = 0
}
document.body.classList.remove('an-is-resizing')
window.removeEventListener('pointermove', handleMove)
window.removeEventListener('pointerup', stopMove)
window.removeEventListener('pointercancel', stopMove)
detailResizeCleanupRef.current = null
}
const stopMove = () => {
cleanupListeners()
resourceLayoutRef.current?.style.setProperty('--an-detail-width', `${latestWidth}px`)
setDetailWidth(latestWidth)
window.dispatchEvent(new Event(SPLIT_RESIZE_END_EVENT))
}
detailResizeCleanupRef.current = cleanupListeners
document.body.classList.add('an-is-resizing')
window.addEventListener('pointermove', handleMove)
window.addEventListener('pointerup', stopMove, { once: true })
}
window.addEventListener('pointercancel', stopMove, { once: true })
}, [])
const startCredentialGuideDrag = (event: ReactPointerEvent<HTMLDivElement>) => {
event.preventDefault()
@@ -3193,9 +3330,11 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
const activeState = useMemo(() => states.find((state) => state.section.key === activeSection?.key), [activeSection?.key, states])
const isComputeConfigSection = config === configs.earthContent && activeSection?.key === 'compute_comparison'
const isCardImagesSection = config === configs.earthContent && activeSection?.key === 'layer_resources'
const isCloudMapSection = config === configs.earthContent && activeSection?.key === 'cloud_map'
const isBasemapSection = config === configs.earthContent && activeSection?.key === 'basemap'
const isApiKeysSection = config === configs.settings && activeSection?.key === 'api_keys'
const isSpecialContentSection = isComputeConfigSection || isCardImagesSection || isApiKeysSection
const rows = activeState?.rows ?? []
const isSpecialContentSection = isComputeConfigSection || isCardImagesSection || isCloudMapSection || isBasemapSection || isApiKeysSection
const rows = activeState?.rows ?? EMPTY_TABLE_ROWS
const isDatasourceBuiltinSection = config === configs.datasources && activeSection?.key === 'builtin'
const selectedDatasourceRows = useMemo(
() => isDatasourceBuiltinSection ? rows.filter((row) => datasourceSelectedRowIds.has(row.__rowId)) : [],
@@ -3226,6 +3365,25 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
return next
})
}, [])
const getDatasourceCheckboxLabel = useCallback(
(row: TableRecord) => localizeAdminText(`选择${recordTitle(row)}`, locale),
[locale],
)
const datasourceSelection = useMemo(
() => isDatasourceBuiltinSection ? {
selectedRowIds: datasourceSelectedRowIds,
onToggleAllVisible: toggleAllVisibleDatasourceSelection,
onToggleRow: toggleDatasourceSelection,
getCheckboxLabel: getDatasourceCheckboxLabel,
} : undefined,
[
datasourceSelectedRowIds,
getDatasourceCheckboxLabel,
isDatasourceBuiltinSection,
toggleAllVisibleDatasourceSelection,
toggleDatasourceSelection,
],
)
const summary = sectionSummary(states)
const collectionQueueSummary = useMemo(() => {
const running = collectionQueue.filter((item) => isActiveQueueStatus(item.status)).length
@@ -3280,11 +3438,11 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
}
}
const openResourceDetail = (record: TableRecord | null) => {
const openResourceDetail = useCallback((record: TableRecord | null) => {
setSelected(record)
setSelectedHistory([])
setMobileResourceDetailOpen(Boolean(record))
}
}, [])
const goBackResourceDetail = () => {
setSelectedHistory((history) => {
@@ -4095,7 +4253,8 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
return
}
if (config === configs.earthContent && endpointKey === 'boundaries') {
await requestAction('保存边界配置', 'put', '/earth/boundaries/config', { config: payload })
const boundaryConfig = isObjectRecord(payload) && isObjectRecord(payload.config) ? payload.config : payload
await requestAction('保存边界配置', 'put', '/earth/boundaries/config', { config: boundaryConfig })
return
}
if (config === configs.ai && endpointKey === 'prompts' && id) {
@@ -5099,8 +5258,18 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
}
return (
<div className={`an-hierarchy-layout${mobileHierarchyDetailOpen ? ' is-mobile-detail-open' : ''}`}>
<div
ref={hierarchyLayoutRef}
className={`an-hierarchy-layout${mobileHierarchyDetailOpen ? ' is-mobile-detail-open' : ''}`}
style={{ '--an-hierarchy-width': `${hierarchyResize.width}px` } as CSSProperties}
>
<GroupList groups={groups} activeKey={activeGroup?.key || ''} onSelect={selectHierarchyGroup} renderGroupControl={activeSection.key === 'tools' ? renderToolSwitch : undefined} />
<SplitPaneResizer
label={localizeAdminText('拖动调整列表宽度', locale)}
isDragging={hierarchyResize.isDragging}
onPointerDown={hierarchyResize.onPointerDown}
onKeyDown={hierarchyResize.onKeyDown}
/>
<Panel className="an-hierarchy-detail">
<div className="an-mobile-detail-bar">
<Button size="icon" variant="subtle" title={localizeAdminText('返回列表', locale)} aria-label={localizeAdminText('返回列表', locale)} onClick={() => setMobileHierarchyDetailOpen(false)}><ArrowLeft size={15} /></Button>
@@ -5276,7 +5445,7 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
.map((row) => ({
key: row.__rowId,
label: recordTitle(row),
description: row.__module,
description: endpoint.key === 'configsAll' ? resolveDatasourceProductLabel(row) : row.__module,
status: normalizeStatusLabel(recordStatus(row)),
count: Object.keys(cleanRecord(row)).length,
record: { ...cleanRecord(row), __sourceEndpoint: row.__endpointKey, __sourceLabel: row.__endpointLabel },
@@ -5423,17 +5592,25 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
const hiddenCollectorStorageField = (key: string) => (
activeSection.key === 'collectors' && COLLECTOR_STORAGE_POLICY_KEYS.has(key)
)
const collectorFieldLabel = (key: string) => (
activeSection.key === 'collectors' && key === 'source_type'
? localizeAdminText('源类型', locale)
: fieldLabel(key, locale)
)
const isEarthAssets = config === configs.earthContent && activeSection.key === 'earth_assets'
const scalarFields = Object.entries(activeGroup?.record || {})
.filter(([key, value]) => !key.startsWith('__') && !hiddenCollectorStorageField(key) && ['string', 'number', 'boolean'].includes(typeof value))
.map(([key, value]): FieldConfig => ({
key,
label: fieldLabel(key),
label: collectorFieldLabel(key),
type: datasourceSecretKeys.has(key) ? 'secret' : key === 'api_key_location' ? 'select' : typeof value === 'boolean' ? 'boolean' : typeof value === 'number' ? 'number' : 'text',
options: key === 'api_key_location' ? [{ value: 'header', label: 'Header' }, { value: 'query', label: 'Query' }] : undefined,
disabled: config === configs.earthContent && activeSection.key === 'about' && key === 'version',
disabled: (config === configs.earthContent && activeSection.key === 'about' && key === 'version') || isEarthAssets,
help: config === configs.earthContent && activeSection.key === 'about' && key === 'version'
? '版本号来自当前系统版本,只读展示,不会随关于信息提交。'
: undefined,
: isEarthAssets
? '只读运行态字段,不会随边界源配置提交。'
: undefined,
wide: datasourceSecretKeys.has(key),
secretVisible: Boolean(visibleSecretFields[hierarchySecretFieldKey(key)]),
onToggleSecret: datasourceSecretKeys.has(key)
@@ -5445,7 +5622,18 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
}))
const objectFields = Object.entries(activeGroup?.record || {})
.filter(([key, value]) => !key.startsWith('__') && !hiddenCollectorStorageField(key) && !shouldHideDatasourceConfigObjectField(activeGroup?.record || {}, activeSourceEndpoint, key) && value !== null && typeof value === 'object')
.map(([key]): FieldConfig => ({ key, label: fieldLabel(key), type: 'textarea', wide: true }))
.map(([key]): FieldConfig => ({
key,
label: collectorFieldLabel(key),
type: 'textarea',
wide: true,
disabled: isEarthAssets && (activeSourceEndpoint !== 'boundaries' || key !== 'config'),
help: isEarthAssets && activeSourceEndpoint === 'boundaries' && key === 'config'
? '编辑边界源配置 JSON 后点击右上角「保存」写入本地源配置;其余状态字段为只读展示。'
: isEarthAssets
? '只读运行态字段,不可直接编辑。'
: undefined,
}))
const newsSourceFields: FieldConfig[] = config === configs.earthContent && activeSection.key === 'news_sources' ? [
{ key: 'id', label: '源 ID' },
{ key: 'name', label: '源名称' },
@@ -5805,8 +5993,9 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
await saveHierarchySettings('/earth/about', aboutPayload, '保存关于配置')
return
}
if (activeGroup.key.includes('boundaries')) {
await saveHierarchySettings('/earth/boundaries/config', { config: payload }, '保存边界配置')
if (activeSection.key === 'earth_assets' && activeSourceEndpoint === 'boundaries') {
const boundaryConfig = isObjectRecord(payload.config) ? payload.config : payload
await saveHierarchySettings('/earth/boundaries/config', { config: boundaryConfig }, '保存边界配置')
return
}
if (activeSection.key === 'news_sources') {
@@ -6209,8 +6398,18 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
return (
<div className="an-hierarchy-workspace">
{hierarchyHeader}
<div className={`an-hierarchy-layout${mobileHierarchyDetailOpen ? ' is-mobile-detail-open' : ''}`}>
<div
ref={hierarchyLayoutRef}
className={`an-hierarchy-layout${mobileHierarchyDetailOpen ? ' is-mobile-detail-open' : ''}`}
style={{ '--an-hierarchy-width': `${hierarchyResize.width}px` } as CSSProperties}
>
<GroupList groups={groups} activeKey={activeGroup?.key || ''} onSelect={selectHierarchyGroup} footer={hierarchyFooter} />
<SplitPaneResizer
label={localizeAdminText('拖动调整列表宽度', locale)}
isDragging={hierarchyResize.isDragging}
onPointerDown={hierarchyResize.onPointerDown}
onKeyDown={hierarchyResize.onKeyDown}
/>
<Panel className="an-hierarchy-detail">
<div className="an-mobile-detail-bar">
<Button size="icon" variant="subtle" title={localizeAdminText('返回列表', locale)} aria-label={localizeAdminText('返回列表', locale)} onClick={() => setMobileHierarchyDetailOpen(false)}><ArrowLeft size={15} /></Button>
@@ -6261,7 +6460,7 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
})} loading={actionLoading}><RefreshCw size={15} /></Button>
) : null}
{config === configs.earthContent && activeSection.key === 'earth_assets' ? (
<Button variant="primary" icon="trigger" onClick={() => void requestAction('启动边界构建', 'post', '/earth/boundaries/build', undefined, { refresh: false, successDescription: '边界构建任务已提交,当前表单未保存。' })} loading={actionLoading}>构建</Button>
<Button variant="primary" icon="trigger" onClick={() => void requestAction('启动边界构建', 'post', '/earth/boundaries/build', undefined, { refresh: true, successDescription: '边界构建任务已提交,已刷新当前状态;可在「边界构建任务」中查看进度。' })} loading={actionLoading}>构建</Button>
) : null}
{config === configs.earthContent && activeSection.key === 'news_sources' && activeGroup ? (
<>
@@ -6396,7 +6595,7 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
<Button size="icon" variant="subtle" icon="start" title="启用映射" aria-label="启用映射" onClick={() => void activateActiveMapping()} loading={actionLoading} />
</>
) : null}
{config === configs.collection && activeSection.key === 'collection_history' ? null : (
{(config === configs.collection && activeSection.key === 'collection_history') || (config === configs.earthContent && activeSection.key === 'earth_assets' && activeSourceEndpoint !== 'boundaries') ? null : (
<>
{config === configs.earthContent && activeSection.key === 'tv' && activeGroup?.key === 'tv:new-source' ? (
<Button variant="subtle" onClick={() => {
@@ -6456,13 +6655,13 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
}))}
options={snapshotTimeline.map((snapshot) => ({
value: snapshotId(snapshot),
label: snapshotOptionLabel(snapshot),
label: snapshotOptionLabel(snapshot, locale),
}))}
/>
</label>
{activeSnapshot ? (
<StatusText tone={statusTone(snapshotStatus(activeSnapshot))}>
{semanticLabel(snapshotStatus(activeSnapshot))}
{localizeAdminText(semanticLabel(snapshotStatus(activeSnapshot), locale), locale)}
</StatusText>
) : null}
</div>
@@ -6650,7 +6849,7 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
) : (
<FieldGrid record={activeGroup.record} draft={hierarchyDraft} onDraftChange={setHierarchyDraft} fields={editableFields} searchGroupKey={activeGroup.key} />
)}
{config === configs.collection && activeSection.key === 'collection_history' ? null : (() => {
{(config === configs.collection && activeSection.key === 'collection_history') || (config === configs.earthContent && activeSection.key === 'earth_assets' && activeSourceEndpoint !== 'boundaries') ? null : (() => {
const rawSensitive = isObjectRecord(activeGroup.record) && recordContainsSecrets(activeGroup.record)
const rawValue = hierarchyDraft || formatRaw(activeGroup.record)
return (
@@ -6809,7 +7008,7 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
}
if (config === configs.earthContent && endpointKey === 'boundaries') {
actions.push(<Button key="build-boundaries" variant="primary" icon="trigger" onClick={() => void requestAction('启动边界构建', 'post', '/earth/boundaries/build', undefined, { refresh: false, successDescription: '边界构建任务已提交,当前配置未保存。' })} loading={actionLoading}>构建</Button>)
actions.push(<Button key="build-boundaries" variant="primary" icon="trigger" onClick={() => void requestAction('启动边界构建', 'post', '/earth/boundaries/build', undefined, { refresh: true, successDescription: '边界构建任务已提交,已刷新当前状态;可在「边界构建任务」中查看进度。' })} loading={actionLoading}>构建</Button>)
}
if (config === configs.earthContent && endpointKey === 'newsSources') {
actions.push(
@@ -6981,6 +7180,8 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
onValueChange={(value) => setDatasourceFilter('product', value)}
options={[
{ value: '', label: localizeAdminText('全部产品域', locale) },
{ value: 'geo', label: localizeAdminText('地理/底图', locale) },
{ value: 'weather', label: localizeAdminText('气象', locale) },
{ value: 'vessels', label: localizeAdminText('船舶', locale) },
{ value: 'cables', label: localizeAdminText('海缆', locale) },
{ value: 'satellites', label: localizeAdminText('卫星', locale) },
@@ -7170,11 +7371,31 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
}))
}
const datasourceColumns: Array<ColumnDef<TableRecord>> = [
const datasourceColumnActionsRef = useRef({
setDatasourceActive,
activeCollectQueueItemFor,
stopDatasourceCollection,
triggerDatasourceWithPrecheck,
clearDatasourceCache,
cancelQueueItem,
clearDatasourceData,
})
datasourceColumnActionsRef.current = {
setDatasourceActive,
activeCollectQueueItemFor,
stopDatasourceCollection,
triggerDatasourceWithPrecheck,
clearDatasourceCache,
cancelQueueItem,
clearDatasourceData,
}
const datasourceColumns = useMemo<Array<ColumnDef<TableRecord>>>(() => [
{
id: 'name',
accessorFn: (row) => recordTitle(row),
header: localizeAdminText('名称', locale),
size: 148,
size: 220,
cell: ({ row }) => (
<button type="button" className="an-table-link" onClick={() => openResourceDetail(row.original)}>
{localizeDisplayValue(recordTitle(row.original), locale)}
@@ -7184,7 +7405,7 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
{
id: 'schedule',
header: localizeAdminText('定时调度', locale),
size: 64,
size: 96,
enableSorting: false,
cell: ({ row }) => {
const record = row.original
@@ -7196,107 +7417,125 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
checked={active}
disabled={Boolean(rowActionLoading[id])}
label={localizeAdminText(active ? '停用调度' : '启用调度', locale)}
onCheckedChange={(next) => void setDatasourceActive(record, next)}
onCheckedChange={(next) => void datasourceColumnActionsRef.current.setDatasourceActive(record, next)}
/>
</span>
)
},
},
{ id: 'module', header: localizeAdminText('模块', locale), size: 54, cell: ({ row }) => localizeDisplayValue(row.original.__module, locale) },
{
id: 'module',
accessorFn: (row) => String(row.__module || ''),
header: localizeAdminText('模块', locale),
size: 84,
cell: ({ row }) => localizeDisplayValue(row.original.__module, locale),
},
{
id: 'status',
accessorFn: (row) => recordDisplayStatus(row),
header: localizeAdminText('状态', locale),
size: 96,
size: 100,
cell: ({ row }) => {
const status = recordDisplayStatus(row.original)
return <StatusText tone={statusTone(status)}>{localizeDisplayValue(status, locale)}</StatusText>
},
},
{ id: 'metric', header: localizeAdminText('指标', locale), size: 72, cell: ({ row }) => <span className="an-muted-text">{localizeDisplayValue(semanticLabel(recordMetric(row.original)), locale)}</span> },
{ id: 'updated', header: localizeAdminText('更新时间', locale), size: 152, cell: ({ row }) => localizeDisplayValue(row.original.__time, locale) },
{
id: 'metric',
accessorFn: (row) => sortableMetricValue(row),
header: localizeAdminText('指标', locale),
size: 84,
cell: ({ row }) => <span className="an-muted-text">{localizeDisplayValue(semanticLabel(recordMetric(row.original), locale), locale)}</span>,
},
{
id: 'updated',
accessorFn: (row) => sortableTimeValue(row.__time),
header: localizeAdminText('更新时间', locale),
size: 164,
cell: ({ row }) => formatResourceTableTime(row.original.__time, locale),
},
{
id: 'actions',
header: localizeAdminText('操作', locale),
size: 104,
size: 112,
enableSorting: false,
cell: ({ row }) => {
const record = row.original
const id = pick(record, ['id', 'source_id', 'key', 'name'], '')
const active = record.is_active !== false
const loadingRow = Boolean(rowActionLoading[id])
const collecting = isCollectTaskActive(record) || Boolean(activeCollectQueueItemFor(record))
const collecting = isCollectTaskActive(record) || Boolean(datasourceColumnActionsRef.current.activeCollectQueueItemFor(record))
const activeDeleteItem = collectionQueue.find(
(item) => isSameDatasourceRow(record, item.sourceId || '', item.source || '') && item.taskType === 'clear_data' && isActiveQueueStatus(item.status),
)
return (
<span className="an-table-actions" onClick={(event) => event.stopPropagation()}>
{collecting ? (
<Button size="icon" variant="danger" onClick={() => stopDatasourceCollection(record)} loading={loadingRow} title={localizeAdminText('停止采集', locale)} aria-label={localizeAdminText('停止采集', locale)}>
<Square size={14} />
</Button>
<TableActionButton
tone="stop"
onClick={() => datasourceColumnActionsRef.current.stopDatasourceCollection(record)}
loading={loadingRow}
title={localizeAdminText('停止采集', locale)}
aria-label={localizeAdminText('停止采集', locale)}
>
<Square size={12} fill="currentColor" strokeWidth={1.75} aria-hidden="true" />
</TableActionButton>
) : (
<Button
size="icon"
variant="ghost"
<TableActionButton
icon="trigger"
onClick={() => void triggerDatasourceWithPrecheck(record)}
onClick={() => void datasourceColumnActionsRef.current.triggerDatasourceWithPrecheck(record)}
loading={loadingRow}
disabled={!active}
title={localizeAdminText(active ? '立即采集' : '调度已停用', locale)}
aria-label={localizeAdminText('立即采集', locale)}
/>
)}
<Button
size="icon"
variant="ghost"
<TableActionButton
onClick={() => setConfirmAction({
title: '清理数据源缓存',
description: `确认清理 ${recordTitle(record)} 的智能星球展示缓存?这不会删除数据库里的采集数据。`,
danger: false,
confirmLabel: '清理缓存',
run: () => clearDatasourceCache(record),
run: () => datasourceColumnActionsRef.current.clearDatasourceCache(record),
})}
disabled={actionLoading}
title={localizeAdminText('清理缓存', locale)}
aria-label={localizeAdminText('清理缓存', locale)}
>
<BrushCleaning size={14} />
</Button>
<BrushCleaning size={14} aria-hidden="true" />
</TableActionButton>
{activeDeleteItem ? (
<Button
size="icon"
variant="ghost"
onClick={() => void cancelQueueItem(activeDeleteItem)}
<TableActionButton
tone="stop"
onClick={() => void datasourceColumnActionsRef.current.cancelQueueItem(activeDeleteItem)}
disabled={actionLoading}
title={localizeAdminText('停止删除', locale)}
aria-label={localizeAdminText('停止删除', locale)}
>
<X size={14} />
</Button>
<X size={14} aria-hidden="true" />
</TableActionButton>
) : (
<Button
size="icon"
variant="ghost"
className="an-table-action--danger"
<TableActionButton
tone="danger"
onClick={() => setConfirmAction({
title: '清理数据库数据',
description: `确认删除 ${recordTitle(record)} 的已采集数据库记录?这不会清理智能星球展示缓存,此操作不可恢复。`,
danger: true,
confirmLabel: '删除数据',
run: () => clearDatasourceData(record),
run: () => datasourceColumnActionsRef.current.clearDatasourceData(record),
})}
disabled={actionLoading}
title={localizeAdminText('清理数据库数据', locale)}
aria-label={localizeAdminText('清理数据库数据', locale)}
>
<Trash2 size={14} />
</Button>
<Trash2 size={14} aria-hidden="true" />
</TableActionButton>
)}
</span>
)
},
},
]
], [actionLoading, collectionQueue, locale, openResourceDetail, rowActionLoading])
const selectedInactiveCount = selectedDatasourceRows.filter((row) => row.is_active === false).length
const selectedActiveCount = selectedDatasourceRows.length - selectedInactiveCount
@@ -7484,11 +7723,14 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
{config === configs.earthContent ? <ComputeComparisonSettings active={isComputeConfigSection} /> : null}
{config === configs.earthContent ? <CardImageSettings active={isCardImagesSection} /> : null}
{config === configs.earthContent ? <EarthCloudMapSettings active={isCloudMapSection} /> : null}
{config === configs.earthContent ? <EarthBasemapSettings active={isBasemapSection} /> : null}
{config === configs.settings ? <ApiKeySettings active={isApiKeysSection} /> : null}
{isSpecialContentSection ? null : isHierarchySection ? (
config === configs.ai ? renderAIHierarchy() : renderConfigHierarchy()
) : (
<div
ref={resourceLayoutRef}
className={`an-resource-layout${isDatasourceBuiltinSection ? ' an-resource-layout--datasources' : ''}${mobileResourceDetailOpen ? ' is-mobile-detail-open' : ''}`}
style={{ '--an-detail-width': `${detailWidth}px` } as CSSProperties}
>
@@ -7507,16 +7749,12 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
<ModuleTable
className={isDatasourceBuiltinSection ? 'an-data-table--datasources' : undefined}
rows={rows}
selected={selected}
selectedRowId={selected?.__rowId ?? null}
onSelect={openResourceDetail}
columns={isDatasourceBuiltinSection ? datasourceColumns : config.columns}
loading={loading && rows.length === 0}
selection={isDatasourceBuiltinSection ? {
selectedRowIds: datasourceSelectedRowIds,
onToggleAllVisible: toggleAllVisibleDatasourceSelection,
onToggleRow: toggleDatasourceSelection,
getCheckboxLabel: (row) => localizeAdminText(`选择${recordTitle(row)}`, locale),
} : undefined}
columnWidthStorageKey={`planet.table.widths.resource.${activeSection?.key || config.listTitle}`}
selection={datasourceSelection}
/>
) : (
<EmptyState title={localizeAdminText(loading ? '正在加载数据' : '当前分区暂无记录', locale)} description={localizeAdminText('切换上方分区可精准查看不同配置和接口。', locale)} />
@@ -7770,6 +8008,7 @@ const configs = {
{ key: 'boundaryBuild', label: '边界构建', url: '/earth/boundaries/build/status', map: (payload) => [isObjectRecord(payload) ? { ...payload, __title: '边界构建任务', __module: '边界', __status: pick(payload, ['status'], '已读取') } : { __title: '边界构建任务', __module: '边界', __status: '空' }] },
],
},
{ key: 'cloud_map', label: '大气云图', map: emptyRows },
{
key: 'tv',
label: '电视直播',
+26 -6
View File
@@ -12,6 +12,7 @@ import { DataTable } from '../components/data-table/DataTable'
import { AdminLayout } from '../components/layout/AdminLayout'
import { Badge } from '../components/ui/badge'
import { Button } from '../components/ui/button'
import { TableActionButton } from '../components/ui/table-action-button'
import { ConfirmDialog, Dialog } from '../components/ui/dialog'
import { Input } from '../components/ui/input'
import { Select } from '../components/ui/select'
@@ -191,13 +192,26 @@ export default function Users() {
{
id: 'actions',
header: t('users.actions'),
size: 148,
size: 96,
enableSorting: false,
cell: ({ row }) => (
<div className="an-row-actions">
<Button size="sm" variant="ghost" onClick={() => handleEdit(row.original)}><Edit size={14} />{t('users.edit')}</Button>
<Button size="sm" variant="ghost" className="is-danger" onClick={() => setDeleteTarget(row.original)}><Trash2 size={14} />{t('common.delete')}</Button>
</div>
<span className="an-table-actions">
<TableActionButton
onClick={() => handleEdit(row.original)}
title={t('users.edit')}
aria-label={t('users.edit')}
>
<Edit size={14} aria-hidden="true" />
</TableActionButton>
<TableActionButton
tone="danger"
onClick={() => setDeleteTarget(row.original)}
title={t('common.delete')}
aria-label={t('common.delete')}
>
<Trash2 size={14} aria-hidden="true" />
</TableActionButton>
</span>
),
},
], [gatekeeperOptions, roleOptions, t])
@@ -241,7 +255,13 @@ export default function Users() {
</div>
</div>
<div className="an-page__body">
<DataTable columns={columns} data={filteredUsers} getRowId={(row) => String(row.id)} loading={loading} />
<DataTable
columns={columns}
data={filteredUsers}
getRowId={(row) => String(row.id)}
loading={loading}
columnWidthStorageKey="planet.table.widths.users"
/>
</div>
</div>
+2 -1
View File
@@ -3,7 +3,7 @@
.an-card-images-toolbar { display:flex; align-items:center; flex-wrap:wrap; gap:8px; padding:12px 16px; border-bottom:1px solid var(--an-border); }
.an-card-images-toolbar h2 { font-size:15px; margin:0 auto 0 0; }
.an-card-images-toolbar [role=tablist] { display:flex; gap:4px; }
.an-card-images-workspace { margin:0; padding:0; border:0; min-width:0; flex:1; min-height:0; display:grid; grid-template-columns:minmax(190px,28%) minmax(0,1fr); overflow:hidden; }
.an-card-images-workspace { margin:0; padding:0; border:0; min-width:0; flex:1; min-height:0; display:grid; grid-template-columns:var(--an-card-images-list-width,280px) 14px minmax(0,1fr); overflow:hidden; }
.an-card-images-list { min-height:0; min-width:0; overflow:hidden; display:flex; flex-direction:column; border-right:1px solid var(--an-border); }
.an-card-images-list > .tui-scrollbar__viewport { padding:12px 14px 12px 12px; box-sizing:border-box; }
.an-card-images-list-actions { display:flex; gap:8px; margin-bottom:12px; }
@@ -35,6 +35,7 @@
.an-card-image-preview__rows strong { text-align:right; overflow-wrap:anywhere; }
@media(max-width:680px) {
.an-card-images-workspace { grid-template-columns:1fr; grid-template-rows:minmax(90px,25%) minmax(0,1fr); }
.an-card-images-workspace > .an-detail-resizer { display:none; }
.an-card-images-list { border-right:0; border-bottom:1px solid var(--an-border); }
.an-card-images-fields { grid-template-columns:1fr; }
}
@@ -20,6 +20,51 @@ export const SHARE_METRICS: ReadonlySet<ComputeMetric> = new Set<ComputeMetric>(
'chip_inflow_share',
])
export type ApproveReasonCode =
| 'newer_authoritative_report'
| 'corrects_prior_error'
| 'adds_missing_observation'
| 'methodology_update'
export type RejectReasonCode =
| 'unverifiable_source'
| 'denominator_mismatch'
| 'extraction_error'
| 'superseded'
| 'duplicate'
export type CandidateReviewReasonCode = ApproveReasonCode | RejectReasonCode
export const APPROVE_REASON_OPTIONS: ReadonlyArray<{
value: ApproveReasonCode
zh: string
en: string
}> = [
{ value: 'newer_authoritative_report', zh: '更权威新版报告更新', en: 'Newer authoritative report' },
{ value: 'corrects_prior_error', zh: '更正历史录入误差', en: 'Corrects prior error' },
{ value: 'adds_missing_observation', zh: '补充缺失年份观测', en: 'Adds missing observation' },
{ value: 'methodology_update', zh: '同分母方法学修订', en: 'Methodology update (same denominator)' },
]
export const REJECT_REASON_OPTIONS: ReadonlyArray<{
value: RejectReasonCode
zh: string
en: string
}> = [
{ value: 'unverifiable_source', zh: '来源无法核验', en: 'Unverifiable source' },
{ value: 'denominator_mismatch', zh: '统计口径或分母不一致', en: 'Denominator mismatch' },
{ value: 'extraction_error', zh: '自动提取数值错误', en: 'Extraction error' },
{ value: 'superseded', zh: '已被更新报告取代', en: 'Superseded by newer report' },
{ value: 'duplicate', zh: '重复候选', en: 'Duplicate candidate' },
]
export function reasonCodeLabel(code: string | null | undefined, english: boolean): string {
if (!code) return ''
const found = [...APPROVE_REASON_OPTIONS, ...REJECT_REASON_OPTIONS].find(item => item.value === code)
if (!found) return code
return english ? found.en : found.zh
}
export interface ComputeSource {
id: string
title: string
@@ -35,6 +80,7 @@ export interface ComputeObservation {
metric: ComputeMetric
source_id: string
values: Record<string, number>
value_sources?: Record<string, string> | null
period_label?: string | null
global_total?: number | null
}
@@ -97,10 +143,35 @@ export interface ComputeConfiguration {
export interface ComputeConfigurationResponse {
config: ComputeConfiguration
revision: string
publish_id?: string
published_at?: string | null
action?: string
is_default: boolean
no_changes?: boolean
presentation_status?: string
countries: Array<{ code: string; name: string; name_en: string }>
}
export interface ComputeCandidateCodeComparison {
old_value: number | null
new_value: number
delta: number
change_kind: 'historical_revision' | 'new_observation' | 'unchanged'
old_source_id: string | null
}
export interface ComputeCandidateComparison {
publish_id?: string
metric?: ComputeMetric | string
year?: number
period_label?: string | null
existing_period_label?: string | null
period_conflict?: boolean
denominator?: string | null
codes?: Record<string, ComputeCandidateCodeComparison>
has_historical_revision?: boolean
}
export interface ComputeCandidateItem {
id: number
status: 'pending' | 'approved' | 'rejected'
@@ -121,15 +192,70 @@ export interface ComputeCandidateItem {
published_at?: string | null
locator?: string
}
comparison?: ComputeCandidateComparison
dedupe_fingerprint?: string | null
confidence: number
extractor_note: string
review_reason_code?: string | null
review_reason?: string
published_publish_id?: string | null
reviewed_by: string | null
reviewed_at: string | null
created_at: string | null
duplicate?: boolean
}
export interface ComputeRevisionSummary {
id: number
publish_id: string
parent_publish_id: string | null
action: 'baseline' | 'publish' | 'reset' | string
published_at: string | null
is_default_content: boolean
change_count: number
summary: string
publish_note: string
published_by_name: string | null
published_by_role: string | null
source_candidate_ids: number[]
presentation_status: 'pending' | 'delivered' | 'failed' | 'skipped' | string
presentation_attempts: number
presentation_error: string
presentation_delivered_at: string | null
}
export interface CandidateImportResult {
status: 'applied' | 'period_conflict'
draft: ComputeConfiguration
mixedShareRowWarning: boolean
discardedCodes: string[]
existingPeriodLabel: string | null
candidatePeriodLabel: string | null
affectedObservationIndex: number
}
const CJK_PATTERN = /[\u3400-\u9fff]/
export function sourceForObservation(row: ComputeObservation, code: string): string {
if (row.value_sources && row.value_sources[code]) {
return row.value_sources[code]
}
return row.source_id
}
export function observationHasMixedSources(row: ComputeObservation): boolean {
const codes = Object.keys(row.values || {})
if (codes.length <= 1) return false
const unique = new Set(codes.map(code => sourceForObservation(row, code)))
return unique.size > 1
}
export function hasMixedShareSourceRow(config: ComputeConfiguration): boolean {
return (config.observations || []).some(
row => SHARE_METRICS.has(row.metric) && observationHasMixedSources(row),
)
}
export function ensureCompleteConfiguration(raw: Partial<ComputeConfiguration>): ComputeConfiguration {
return {
reviewed_at: raw.reviewed_at || new Date().toISOString().slice(0, 10),
@@ -157,12 +283,37 @@ export function normalizeDraftForPublish(draft: ComputeConfiguration): ComputeCo
published_at: cleanOptText(source.published_at),
})),
observations: draft.observations.map(row => {
const valueKeys = Object.keys(row.values || {})
let effectiveSourceId = row.source_id
let cleanedValueSources: Record<string, string> | undefined
if (row.value_sources && valueKeys.length > 0) {
const perCode: Record<string, string> = {}
for (const code of valueKeys) {
perCode[code] = row.value_sources[code] || row.source_id
}
const uniqueSources = Array.from(new Set(Object.values(perCode)))
if (uniqueSources.length === 1) {
effectiveSourceId = uniqueSources[0]
cleanedValueSources = undefined
} else {
const overrides: Record<string, string> = {}
for (const [code, srcId] of Object.entries(perCode)) {
if (srcId !== effectiveSourceId) {
overrides[code] = srcId
}
}
if (Object.keys(overrides).length > 0) {
cleanedValueSources = overrides
}
}
}
const next: ComputeObservation = {
year: Math.trunc(row.year),
metric: row.metric,
source_id: row.source_id,
source_id: effectiveSourceId,
values: row.values,
}
if (cleanedValueSources) next.value_sources = cleanedValueSources
const periodLabel = cleanOptText(row.period_label)
const globalTotal = cleanOptNumber(row.global_total)
if (periodLabel !== null) next.period_label = periodLabel
@@ -224,13 +375,17 @@ export function normalizeDraftForPublish(draft: ComputeConfiguration): ComputeCo
}
export function reportIsUsed(config: ComputeConfiguration, id: string) {
return [
...config.observations,
...config.innovation,
...(config.structures || []),
...(config.milestones || []),
...(config.national_hubs || []),
].some(row => row.source_id === id)
return (
config.observations.some(
row => row.source_id === id || Object.values(row.value_sources || {}).includes(id),
)
|| [
...config.innovation,
...(config.structures || []),
...(config.milestones || []),
...(config.national_hubs || []),
].some(row => row.source_id === id)
)
}
export function formatSourceOptionLabel(source: ComputeSource, english: boolean): string {
@@ -249,7 +404,8 @@ export function formatSourceOptionLabel(source: ComputeSource, english: boolean)
export function applyApprovedCandidateToDraft(
draft: ComputeConfiguration,
candidate: ComputeCandidateItem,
): ComputeConfiguration {
options?: { replaceOnPeriodConflict?: boolean },
): CandidateImportResult {
const proposed = candidate.proposed_payload || {}
const src = candidate.source_payload || {}
const year = typeof proposed.year === 'number' && Number.isFinite(proposed.year)
@@ -259,6 +415,37 @@ export function applyApprovedCandidateToDraft(
? (proposed.metric as ComputeMetric)
: 'global_share'
const sourceId = (proposed.source_id || src.id || `candidate-src-${year}`).replace(/[^a-zA-Z0-9_-]/g, '-')
const candidatePeriod = (proposed.period_label || '').trim() || null
const values: Record<string, number> = {}
for (const [code, val] of Object.entries(proposed.values || {})) {
if (typeof val === 'number' && Number.isFinite(val)) {
values[code] = val
}
}
const existingIndex = draft.observations.findIndex(
item => item.metric === metric && item.year === year,
)
if (existingIndex >= 0) {
const existing = draft.observations[existingIndex]
const existingPeriod = (existing.period_label || '').trim() || null
if (existingPeriod !== candidatePeriod) {
const discardedCodes = Object.keys(existing.values).filter(code => !(code in values))
if (!options?.replaceOnPeriodConflict) {
return {
status: 'period_conflict',
draft,
mixedShareRowWarning: false,
discardedCodes,
existingPeriodLabel: existingPeriod,
candidatePeriodLabel: candidatePeriod,
affectedObservationIndex: existingIndex,
}
}
}
}
const hasSource = draft.sources.some(item => item.id === sourceId)
const nextSources = hasSource
@@ -280,41 +467,100 @@ export function applyApprovedCandidateToDraft(
},
]
const values: Record<string, number> = {}
for (const [code, val] of Object.entries(proposed.values || {})) {
if (typeof val === 'number' && Number.isFinite(val)) {
values[code] = val
if (existingIndex < 0) {
const appended: ComputeObservation = {
year,
metric,
source_id: sourceId,
values,
...(candidatePeriod ? { period_label: candidatePeriod } : {}),
}
return {
status: 'applied',
draft: {
...draft,
sources: nextSources,
observations: [...draft.observations, appended],
},
mixedShareRowWarning: false,
discardedCodes: [],
existingPeriodLabel: null,
candidatePeriodLabel: candidatePeriod,
affectedObservationIndex: draft.observations.length,
}
}
const existingIndex = draft.observations.findIndex(
item => item.metric === metric && item.year === year,
)
const nextObservations = existingIndex >= 0
? draft.observations.map((item, index) => (
index === existingIndex
? {
...item,
source_id: sourceId,
values: { ...item.values, ...values },
}
: item
))
: [
...draft.observations,
{
year,
metric,
source_id: sourceId,
values,
...(proposed.period_label ? { period_label: proposed.period_label } : {}),
const existing = draft.observations[existingIndex]
const existingPeriod = (existing.period_label || '').trim() || null
if (existingPeriod !== candidatePeriod && options?.replaceOnPeriodConflict) {
const discardedCodes = Object.keys(existing.values).filter(code => !(code in values))
const replaced: ComputeObservation = {
year,
metric,
source_id: sourceId,
values,
...(candidatePeriod ? { period_label: candidatePeriod } : {}),
}
return {
status: 'applied',
draft: {
...draft,
sources: nextSources,
observations: draft.observations.map((item, idx) => (idx === existingIndex ? replaced : item)),
},
]
mixedShareRowWarning: false,
discardedCodes,
existingPeriodLabel: existingPeriod,
candidatePeriodLabel: candidatePeriod,
affectedObservationIndex: existingIndex,
}
}
// Partial / same-period merge: preserve row-level source_id and attribute only revised countries via value_sources.
const nextValues: Record<string, number> = { ...existing.values, ...values }
const perCodeSources: Record<string, string> = {}
for (const code of Object.keys(nextValues)) {
const prevSource = sourceForObservation(existing, code)
perCodeSources[code] = code in values ? sourceId : prevSource
}
const uniqueSources = Array.from(new Set(Object.values(perCodeSources)))
let mergedRow: ComputeObservation
if (uniqueSources.length === 1) {
const rest = { ...existing }
delete rest.value_sources
mergedRow = {
...rest,
source_id: uniqueSources[0],
values: nextValues,
}
} else {
const overrides: Record<string, string> = {}
for (const [code, srcId] of Object.entries(perCodeSources)) {
if (srcId !== existing.source_id) {
overrides[code] = srcId
}
}
mergedRow = {
...existing,
source_id: existing.source_id,
values: nextValues,
value_sources: overrides,
}
}
const mixedShareRowWarning = SHARE_METRICS.has(metric) && uniqueSources.length > 1
return {
...draft,
sources: nextSources,
observations: nextObservations,
status: 'applied',
draft: {
...draft,
sources: nextSources,
observations: draft.observations.map((item, idx) => (idx === existingIndex ? mergedRow : item)),
},
mixedShareRowWarning,
discardedCodes: [],
existingPeriodLabel: existingPeriod,
candidatePeriodLabel: candidatePeriod,
affectedObservationIndex: existingIndex,
}
}
+82 -10
View File
@@ -35,7 +35,8 @@
font-weight: 600;
}
.an-compute-row { border-bottom: 1px solid var(--an-border); padding: 12px 0; }
.an-compute-row summary { cursor: pointer; padding: 6px 0; font-weight: 500; overflow-wrap: anywhere; }
.an-compute-row--mixed { border-left: 3px solid #f59e0b; padding-left: 10px; }
.an-compute-row summary { cursor: pointer; padding: 6px 0; font-weight: 500; overflow-wrap: anywhere; display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
.an-compute-fields { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; margin: 12px 0; }
.an-compute-fields--three { grid-template-columns: repeat(3, minmax(0, 1fr)); }
.an-compute-field { display: flex; flex-direction: column; gap: 6px; min-width: 0; font-size: 13px; }
@@ -44,21 +45,42 @@
.an-compute-textarea {
min-height: 76px;
padding: 8px 10px;
border-radius: 8px;
border-radius: var(--an-control-radius, 6px);
border: 1px solid var(--an-border);
background: var(--an-surface-subtle, rgba(15, 23, 42, 0.35));
color: inherit;
background: var(--an-surface);
color: var(--an-text);
font: inherit;
resize: vertical;
box-sizing: border-box;
}
.an-compute-textarea:hover:not(:disabled) { border-color: var(--an-border-strong); }
.an-compute-textarea:focus { outline: none; border-color: var(--an-accent); }
.an-compute-values { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 12px; }
.an-compute-value { display: flex; align-items: end; gap: 4px; min-width: 0; }
.an-compute-value .an-compute-field { flex: 1; }
.an-compute-source-tag {
font-size: 11px;
color: var(--an-muted, #94a3b8);
font-weight: 400;
overflow-wrap: anywhere;
}
.an-compute-row-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; margin: 10px 0 4px; }
.an-compute-row-actions .an-select { flex: 1; min-width: 180px; }
.an-compute-warning-banner {
display: flex;
align-items: center;
gap: 8px;
padding: 8px 12px;
margin: 8px 0;
border-radius: 6px;
border: 1px solid rgba(245, 158, 11, 0.45);
background: rgba(245, 158, 11, 0.1);
color: #f59e0b;
font-size: 12px;
}
.an-compute-candidate-box {
border: 1px solid var(--an-border);
border-radius: 10px;
border-radius: 8px;
padding: 12px;
margin: 10px 0;
display: flex;
@@ -72,6 +94,7 @@
justify-content: space-between;
gap: 8px;
}
.an-compute-badges { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; }
.an-compute-badge {
display: inline-flex;
align-items: center;
@@ -79,16 +102,64 @@
border-radius: 999px;
font-size: 12px;
border: 1px solid var(--an-border);
white-space: nowrap;
}
.an-compute-badge--approved, .an-compute-badge--delivered { color: #10b981; border-color: rgba(16, 185, 129, 0.4); }
.an-compute-badge--rejected, .an-compute-badge--failed { color: #ef4444; border-color: rgba(239, 68, 68, 0.4); }
.an-compute-badge--pending, .an-compute-badge--revision { color: #f59e0b; border-color: rgba(245, 158, 11, 0.45); }
.an-compute-badge--conflict { color: #f97316; border-color: rgba(249, 115, 22, 0.45); }
.an-compute-badge--info { color: #38bdf8; border-color: rgba(56, 189, 248, 0.4); }
.an-compute-badge--muted { color: var(--an-muted, #94a3b8); border-color: var(--an-border); }
.an-compute-meta-strip {
display: flex;
flex-wrap: wrap;
gap: 8px 16px;
font-size: 12px;
color: var(--an-muted, #94a3b8);
}
.an-compute-table-wrap {
width: 100%;
overflow-x: auto;
}
.an-compute-table {
width: 100%;
border-collapse: collapse;
font-size: 12px;
font-variant-numeric: tabular-nums;
}
.an-compute-table th,
.an-compute-table td {
padding: 6px 8px;
text-align: left;
border-bottom: 1px solid var(--an-border);
vertical-align: top;
}
.an-compute-table th {
font-weight: 600;
color: var(--an-muted, #94a3b8);
white-space: nowrap;
}
.an-compute-review-box {
display: grid;
grid-template-columns: minmax(180px, 240px) minmax(0, 1fr) auto;
gap: 8px;
align-items: end;
padding-top: 6px;
border-top: 1px dashed var(--an-border);
}
.an-compute-review-summary {
font-size: 12px;
color: var(--an-muted, #94a3b8);
padding-top: 4px;
border-top: 1px dashed var(--an-border);
}
.an-compute-badge--approved { color: #10b981; border-color: rgba(16, 185, 129, 0.4); }
.an-compute-badge--rejected { color: #ef4444; border-color: rgba(239, 68, 68, 0.4); }
.an-compute-badge--pending { color: #f59e0b; border-color: rgba(245, 158, 11, 0.4); }
.an-compute-code {
margin: 0;
padding: 8px 10px;
border-radius: 8px;
border-radius: 6px;
border: 1px solid var(--an-border);
background: rgba(15, 23, 42, 0.32);
background: var(--an-bg-subtle, var(--an-surface));
color: var(--an-text);
font-size: 12px;
overflow-x: auto;
scrollbar-width: thin;
@@ -104,6 +175,7 @@
.an-compute-code::-webkit-scrollbar-thumb { border-radius: 999px; background: var(--an-border-strong); }
@media (max-width: 860px) {
.an-compute-fields--three { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.an-compute-review-box { grid-template-columns: minmax(0, 1fr); }
}
@media (max-width: 680px) {
.an-compute-fields, .an-compute-fields--three, .an-compute-values { grid-template-columns: minmax(0, 1fr); }
@@ -0,0 +1,492 @@
import { useState, type CSSProperties, type MouseEvent } from 'react'
import { formatNumber } from '../utils'
import type {
AssetDistributionItem,
LayerShareItem,
TaskTrendBucket,
} from './dashboardHelpers'
interface ChartTooltipState {
title: string
body: string
x: number
y: number
}
function DashboardChartTooltip({ tip }: { tip: ChartTooltipState | null }) {
if (!tip) return null
const clampedX =
typeof window !== 'undefined' ? Math.min(window.innerWidth - 220, tip.x + 12) : tip.x + 12
const clampedY = Math.max(10, tip.y - 54)
return (
<div
className="an-dash-tooltip is-visible"
role="status"
aria-live="polite"
style={
{
'--an-tip-x': `${clampedX}px`,
'--an-tip-y': `${clampedY}px`,
} as CSSProperties
}
>
<div className="an-dash-tooltip__title">{tip.title}</div>
<div className="an-dash-tooltip__body">{tip.body}</div>
</div>
)
}
function makeTipMoveHandler(
setTip: (next: ChartTooltipState | null) => void,
title: string,
body: string,
) {
return {
onMouseEnter: (event: MouseEvent<SVGElement | HTMLElement>) => {
setTip({ title, body, x: event.clientX, y: event.clientY })
},
onMouseMove: (event: MouseEvent<SVGElement | HTMLElement>) => {
setTip({ title, body, x: event.clientX, y: event.clientY })
},
onMouseLeave: () => setTip(null),
}
}
export interface DashboardHorizontalBarChartProps {
items: AssetDistributionItem[]
compact?: boolean
emptyText: string
unitLabel: string
shareLabel: string
onItemClick?: (item: AssetDistributionItem) => void
}
export function DashboardHorizontalBarChart({
items,
compact = true,
emptyText,
unitLabel,
shareLabel,
onItemClick,
}: DashboardHorizontalBarChartProps) {
const [tip, setTip] = useState<ChartTooltipState | null>(null)
const visibleItems = compact ? items.slice(0, 8) : items.slice(0, 12)
if (!visibleItems.length) {
return <div className="an-dash-chart-empty">{emptyText}</div>
}
const max = Math.max(...visibleItems.map((item) => item.count), 1)
const total = items.reduce((sum, item) => sum + item.count, 0) || 1
const w = 640
const rowH = compact ? 27 : 30
const topPad = 6
const labelW = 152
const rightPad = 74
const barAreaW = w - labelW - rightPad
const h = topPad * 2 + visibleItems.length * rowH
const gridTicks = [0.25, 0.5, 0.75, 1]
return (
<div className="an-dash-chart-stage">
<svg
className="an-dash-chart-svg"
viewBox={`0 0 ${w} ${h}`}
preserveAspectRatio="xMidYMin meet"
role="img"
>
{gridTicks.map((ratio) => {
const gx = labelW + barAreaW * ratio
return (
<line
key={ratio}
x1={gx}
y1={2}
x2={gx}
y2={h - 4}
stroke="var(--an-dash-grid)"
strokeWidth={1}
/>
)
})}
{visibleItems.map((item, idx) => {
const y = topPad + idx * rowH
const barW = Math.max(4, (item.count / max) * barAreaW)
const pct = ((item.count / total) * 100).toFixed(1)
const isTop = idx === 0
const opacity = isTop ? 0.92 : Math.max(0.42, 0.85 - idx * 0.06)
const label = item.name.length > 20 ? `${item.name.slice(0, 19)}…` : item.name
const tipBody = `${formatNumber(item.count)} ${unitLabel} · ${shareLabel} ${pct}%${
item.meta ? ` · ${item.meta}` : ''
}`
const clickable = !compact && Boolean(onItemClick)
return (
<g
key={item.key}
className={clickable ? 'an-dash-chart-hit is-clickable' : 'an-dash-chart-hit'}
{...makeTipMoveHandler(setTip, item.name, tipBody)}
onClick={
clickable && onItemClick
? (event) => {
event.stopPropagation()
onItemClick(item)
}
: undefined
}
>
<rect x={0} y={y} width={w} height={rowH - 2} fill="transparent" />
<text
x={labelW - 10}
y={y + rowH * 0.56}
textAnchor="end"
fill="var(--an-muted)"
fontSize={11.5}
fontWeight={isTop ? 600 : 500}
>
{label}
</text>
<rect
x={labelW}
y={y + 5}
width={barAreaW}
height={rowH - 13}
rx={3}
fill="var(--tui-surface-soft)"
/>
<rect
x={labelW}
y={y + 5}
width={Number(barW.toFixed(1))}
height={rowH - 13}
rx={3}
fill="var(--an-accent)"
fillOpacity={Number(opacity.toFixed(2))}
/>
<text
x={w - 4}
y={y + rowH * 0.56}
textAnchor="end"
fill="var(--an-text)"
fontSize={11.5}
fontWeight={600}
className="an-dash-chart-num"
>
{formatNumber(item.count)}
</text>
</g>
)
})}
</svg>
<DashboardChartTooltip tip={tip} />
</div>
)
}
export interface DashboardTaskTrendChartProps {
buckets: TaskTrendBucket[]
compact?: boolean
okLabel: string
failLabel: string
rateLabel: string
}
export function DashboardTaskTrendChart({
buckets,
compact = true,
okLabel,
failLabel,
rateLabel,
}: DashboardTaskTrendChartProps) {
const [tip, setTip] = useState<ChartTooltipState | null>(null)
const safeBuckets = buckets.length ? buckets : [{ label: '-', ok: 0, fail: 0 }]
const w = 460
const h = compact ? 196 : 230
const pad = { top: 14, right: 16, bottom: 26, left: 32 }
const plotW = w - pad.left - pad.right
const plotH = h - pad.top - pad.bottom
const maxTotal = Math.max(...safeBuckets.map((b) => b.ok + b.fail), 1) * 1.15
const stepW = plotW / safeBuckets.length
const barW = Math.min(28, stepW * 0.44)
const linePts: Array<{ x: number; y: number }> = []
const columns = safeBuckets.map((bucket, idx) => {
const cx = pad.left + stepW * (idx + 0.5)
const okH = (bucket.ok / maxTotal) * plotH
const failH = (bucket.fail / maxTotal) * plotH
const yOk = pad.top + plotH - okH
const yFail = yOk - failH
const total = bucket.ok + bucket.fail
const rate = total > 0 ? Math.round((bucket.ok / total) * 100) : 0
const lineY = pad.top + plotH * (1 - rate / 100)
linePts.push({ x: Number(cx.toFixed(1)), y: Number(lineY.toFixed(1)) })
const tipBody = `${okLabel} ${bucket.ok} · ${failLabel} ${bucket.fail} · ${rateLabel} ${rate}%`
return {
bucket,
cx,
okH,
failH,
yOk,
yFail,
tipBody,
}
})
const polyPoints = linePts.map((pt) => `${pt.x},${pt.y}`).join(' ')
return (
<div className="an-dash-chart-stage">
<svg
className="an-dash-chart-svg"
viewBox={`0 0 ${w} ${h}`}
preserveAspectRatio="xMidYMin meet"
role="img"
>
{[0, 0.5, 1].map((ratio) => {
const y = pad.top + plotH * (1 - ratio)
const tickVal = Math.round(maxTotal * ratio)
return (
<g key={ratio}>
<line
x1={pad.left}
y1={Number(y.toFixed(1))}
x2={w - pad.right}
y2={Number(y.toFixed(1))}
stroke="var(--an-dash-grid)"
strokeWidth={1}
/>
<text
x={pad.left - 6}
y={y + 3}
textAnchor="end"
fill="var(--an-muted)"
fontSize={10.5}
className="an-dash-chart-num"
>
{tickVal}
</text>
</g>
)
})}
{columns.map((col) => (
<g
key={col.bucket.label}
className="an-dash-chart-hit"
{...makeTipMoveHandler(setTip, col.bucket.label, col.tipBody)}
>
<rect
x={Number((col.cx - stepW * 0.45).toFixed(1))}
y={pad.top}
width={Number((stepW * 0.9).toFixed(1))}
height={plotH}
fill="transparent"
/>
<rect
x={Number((col.cx - barW / 2).toFixed(1))}
y={Number(col.yOk.toFixed(1))}
width={Number(barW.toFixed(1))}
height={Number(Math.max(0, col.okH).toFixed(1))}
rx={3}
fill="var(--an-accent)"
fillOpacity={0.82}
/>
{col.failH > 0 ? (
<rect
x={Number((col.cx - barW / 2).toFixed(1))}
y={Number(col.yFail.toFixed(1))}
width={Number(barW.toFixed(1))}
height={Number(col.failH.toFixed(1))}
rx={2}
fill="var(--an-danger)"
fillOpacity={0.78}
/>
) : null}
<text
x={Number(col.cx.toFixed(1))}
y={h - 6}
textAnchor="middle"
fill="var(--an-muted)"
fontSize={10.5}
className="an-dash-chart-num"
>
{col.bucket.label}
</text>
</g>
))}
<polyline
fill="none"
stroke="var(--an-success)"
strokeWidth={1.8}
strokeLinecap="round"
strokeLinejoin="round"
points={polyPoints}
/>
{linePts.map((pt, idx) => (
<circle
key={`pt-${idx}`}
cx={pt.x}
cy={pt.y}
r={2.7}
fill="var(--an-surface)"
stroke="var(--an-success)"
strokeWidth={1.6}
/>
))}
</svg>
<DashboardChartTooltip tip={tip} />
</div>
)
}
export interface DashboardLayerDonutChartProps {
items: LayerShareItem[]
centerLabel: string
unitLabel: string
shareLabel: string
emptyText: string
computeLocated: number
computeTotal: number
computeNeedsConfirm: number
geocodeTitle: string
}
export function DashboardLayerDonutChart({
items,
centerLabel,
unitLabel,
shareLabel,
emptyText,
computeLocated,
computeTotal,
computeNeedsConfirm,
geocodeTitle,
}: DashboardLayerDonutChartProps) {
const [tip, setTip] = useState<ChartTooltipState | null>(null)
const total = items.reduce((sum, item) => sum + item.count, 0)
const radius = 56
const cx = 74
const cy = 74
const circumference = 2 * Math.PI * radius
let offset = 0
const arcs = items.map((item) => {
const len = total > 0 ? (item.count / total) * circumference : 0
const gap = items.length > 1 ? 2.5 : 0
const seg = Math.max(0, len - gap)
const dashArray = `${seg.toFixed(2)} ${(circumference - seg).toFixed(2)}`
const dashOffset = Number((-offset).toFixed(2))
offset += len
const pct = total > 0 ? ((item.count / total) * 100).toFixed(1) : '0.0'
return {
item,
dashArray,
dashOffset,
pct,
tipBody: `${formatNumber(item.count)} ${unitLabel} · ${shareLabel} ${pct}%`,
}
})
const safeComputeTotal = Math.max(0, computeTotal)
const safeLocated = Math.min(safeComputeTotal, Math.max(0, computeLocated))
const safeConfirm = Math.min(Math.max(0, safeComputeTotal - safeLocated), Math.max(0, computeNeedsConfirm))
const safeRemaining = Math.max(0, safeComputeTotal - safeLocated - safeConfirm)
const locatedPct = safeComputeTotal > 0 ? ((safeLocated / safeComputeTotal) * 100).toFixed(1) : '0.0'
return (
<div className="an-dash-donut-shell">
{items.length > 0 ? (
<div className="an-dash-donut-layout">
<div className="an-dash-donut-wrap">
<svg width={148} height={148} viewBox="0 0 148 148" role="img">
<circle
cx={cx}
cy={cy}
r={radius}
fill="none"
stroke="var(--tui-surface-soft)"
strokeWidth={14}
/>
{arcs.map((arc) => (
<circle
key={arc.item.id}
cx={cx}
cy={cy}
r={radius}
fill="none"
stroke={arc.item.color}
strokeWidth={14}
strokeDasharray={arc.dashArray}
strokeDashoffset={arc.dashOffset}
transform={`rotate(-90 ${cx} ${cy})`}
className="an-dash-chart-hit"
{...makeTipMoveHandler(setTip, arc.item.name, arc.tipBody)}
/>
))}
</svg>
<div className="an-dash-donut-center">
<strong>{formatNumber(total)}</strong>
<span>{centerLabel}</span>
</div>
</div>
<div className="an-dash-legend">
{arcs.map((arc) => (
<div
key={arc.item.id}
className="an-dash-legend-row"
{...makeTipMoveHandler(setTip, arc.item.name, arc.tipBody)}
>
<svg className="an-dash-legend-dot" width={8} height={8} viewBox="0 0 8 8" aria-hidden="true">
<circle cx={4} cy={4} r={4} fill={arc.item.color} />
</svg>
<span className="an-dash-legend-row__name">{arc.item.name}</span>
<span className="an-dash-legend-row__val">{formatNumber(arc.item.count)}</span>
<span className="an-dash-legend-row__pct">{arc.pct}%</span>
</div>
))}
</div>
</div>
) : (
<div className="an-dash-chart-empty">{emptyText}</div>
)}
<div className="an-dash-geocode">
<div className="an-dash-geocode__head">
<span>{geocodeTitle}</span>
<strong>
{`${formatNumber(safeLocated)} / ${formatNumber(safeComputeTotal)} · ${locatedPct}%`}
</strong>
</div>
<div className="an-dash-bar">
{safeLocated > 0 ? (
<span
className="an-dash-bar__seg an-dash-bar__seg--green"
style={{ '--an-bar-weight': safeLocated } as CSSProperties}
/>
) : null}
{safeConfirm > 0 ? (
<span
className="an-dash-bar__seg an-dash-bar__seg--amber"
style={{ '--an-bar-weight': safeConfirm } as CSSProperties}
/>
) : null}
{safeRemaining > 0 || safeComputeTotal === 0 ? (
<span
className="an-dash-bar__seg an-dash-bar__seg--slate"
style={{ '--an-bar-weight': safeComputeTotal === 0 ? 1 : safeRemaining } as CSSProperties}
/>
) : null}
</div>
</div>
<DashboardChartTooltip tip={tip} />
</div>
)
}
@@ -0,0 +1,476 @@
export type DatasourceHealth = 'healthy' | 'running' | 'stale' | 'error' | 'disabled'
export type CollectorHealth = 'connected' | 'unverified' | 'missing_credentials' | 'disabled'
export interface DashboardDatasourceRow {
id: number
source: string
name: string
module: string
product?: string
frequency?: string
frequency_minutes?: number
is_active: boolean
is_running?: boolean
last_status?: string | null
last_run_at?: string | null
collected_records?: number
records_processed?: number | null
error_message?: string | null
health: DatasourceHealth
}
export interface DashboardCollectorRow {
key: string
name: string
displayName: string
kind: 'builtin' | 'custom'
product: string
sourceType: string
endpoint: string
isActive: boolean
requiresCredentials: boolean
hasCredentials: boolean
authType: string
credentialPreview: string
health: CollectorHealth
checkedAt?: string | null
configId?: number | null
headers?: Record<string, string>
config?: Record<string, unknown>
}
export interface DashboardTaskRow {
id: number
datasource_id: number
datasource_name: string
source?: string
status: string
started_at?: string | null
completed_at?: string | null
records_processed?: number | null
total_records?: number | null
error_message?: string | null
}
export interface DashboardAlertRow {
id: number
title: string
message?: string
severity: 'critical' | 'warning' | 'info' | string
status: string
source?: string
created_at?: string | null
}
/**
* Normalize `{ data: T[] }`, `{ items: T[] }`, or raw `T[]` API responses cleanly.
*/
export function extractArrayPayload<T>(payload: unknown): T[] {
if (Array.isArray(payload)) return payload as T[]
if (payload && typeof payload === 'object') {
const obj = payload as Record<string, unknown>
if (Array.isArray(obj.data)) return obj.data as T[]
if (Array.isArray(obj.items)) return obj.items as T[]
}
return []
}
/**
* Derive a unified datasource health tier from scheduler state, status, and freshness window.
*/
export function computeDatasourceHealth(
row: {
is_active?: boolean
is_running?: boolean
last_status?: string | null
last_run_at?: string | null
frequency_minutes?: number | null
},
nowMs = Date.now(),
): DatasourceHealth {
if (row.is_active === false) return 'disabled'
if (row.is_running) return 'running'
const status = String(row.last_status || '').toLowerCase()
if (status === 'failed' || status === 'error') return 'error'
if (row.last_run_at) {
const ts = Date.parse(row.last_run_at)
if (Number.isFinite(ts)) {
const freq = Number(row.frequency_minutes) || 60
const staleThresholdMs = Math.max(freq * 2, 120) * 60_000
if (nowMs - ts > staleThresholdMs) return 'stale'
}
}
return 'healthy'
}
/**
* Merge built-in (`/configs/all`) and custom (`/configs`) collectors without duplicating overrides.
*/
export function normalizeCollectorRows(
builtinRaw: unknown,
customRaw: unknown,
): DashboardCollectorRow[] {
const builtins = extractArrayPayload<Record<string, unknown>>(builtinRaw)
const customs = extractArrayPayload<Record<string, unknown>>(customRaw)
const builtinNames = new Set(builtins.map((item) => String(item.name || '').trim()).filter(Boolean))
const rows: DashboardCollectorRow[] = builtins.map((item) => {
const name = String(item.name || '')
const isActive = item.is_active !== false
const requiresCredentials = Boolean(item.requires_credentials)
const authConfigured = (item.auth_configured as Record<string, unknown> | undefined) || {}
const hasConfiguredAny = Object.values(authConfigured).some(Boolean)
const hasCredentials =
typeof item.has_credentials === 'boolean'
? item.has_credentials
: !requiresCredentials || hasConfiguredAny || String(item.credential_status || '') === 'configured'
const rawConn = String(item.connectivity_status || '')
const health: CollectorHealth = !isActive
? 'disabled'
: requiresCredentials && !hasCredentials
? 'missing_credentials'
: rawConn === 'connected'
? 'connected'
: 'unverified'
return {
key: `builtin:${name}`,
name,
displayName: String(item.display_name || item.name || '-'),
kind: 'builtin',
product: String(item.product || '-'),
sourceType: String(item.source_type || 'http'),
endpoint: String(item.endpoint || item.default_url || ''),
isActive,
requiresCredentials,
hasCredentials,
authType: String(item.auth_type || (requiresCredentials ? 'configured' : 'none')),
credentialPreview: String(item.credential_preview || ''),
health,
checkedAt: typeof item.connectivity_checked_at === 'string' ? item.connectivity_checked_at : null,
configId: typeof item.config_id === 'number' ? item.config_id : null,
headers: (item.headers as Record<string, string> | undefined) || {},
config: (item.config as Record<string, unknown> | undefined) || {},
}
})
for (const item of customs) {
const name = String(item.name || '').trim()
if (!name || builtinNames.has(name)) continue
const isActive = item.is_active !== false
const authType = String(item.auth_type || 'none')
const requiresCredentials =
typeof item.requires_credentials === 'boolean' ? item.requires_credentials : authType !== 'none'
const hasCredentials =
typeof item.has_credentials === 'boolean' ? item.has_credentials : !requiresCredentials || Boolean(item.credential_preview)
const health: CollectorHealth = !isActive
? 'disabled'
: requiresCredentials && !hasCredentials
? 'missing_credentials'
: 'unverified'
rows.push({
key: `custom:${String(item.id || name)}`,
name,
displayName: name,
kind: 'custom',
product: String(item.product || '-'),
sourceType: String(item.source_type || 'rest'),
endpoint: String(item.endpoint || ''),
isActive,
requiresCredentials,
hasCredentials,
authType,
credentialPreview: String(item.credential_preview || ''),
health,
checkedAt: null,
configId: typeof item.id === 'number' ? item.id : null,
headers: (item.headers as Record<string, string> | undefined) || {},
config: (item.config as Record<string, unknown> | undefined) || {},
})
}
return rows
}
/**
* Format compact relative age string for table cells.
*/
export function formatRelativeAge(iso: string | null | undefined, isEnglish = false, nowMs = Date.now()): string {
if (!iso) return '-'
const ts = Date.parse(iso)
if (!Number.isFinite(ts)) return '-'
const diffMin = Math.max(0, Math.round((nowMs - ts) / 60_000))
if (diffMin < 1) return isEnglish ? 'just now' : '刚刚'
if (diffMin < 60) return isEnglish ? `${diffMin}m ago` : `${diffMin} 分钟前`
const diffHours = Math.round(diffMin / 60)
if (diffHours < 48) return isEnglish ? `${diffHours}h ago` : `${diffHours} 小时前`
const diffDays = Math.round(diffHours / 24)
return isEnglish ? `${diffDays}d ago` : `${diffDays} 天前`
}
/**
* Format execution duration between two ISO timestamps.
*/
export function formatDurationShort(startedAt?: string | null, completedAt?: string | null): string {
if (!startedAt || !completedAt) return '-'
const start = Date.parse(startedAt)
const end = Date.parse(completedAt)
if (!Number.isFinite(start) || !Number.isFinite(end) || end < start) return '-'
const sec = (end - start) / 1000
if (sec < 60) return `${sec.toFixed(sec < 10 ? 1 : 0)}s`
const min = Math.floor(sec / 60)
const rem = Math.round(sec % 60)
return `${min}m${rem}s`
}
/**
* Compute how many fixed-height preview rows fit inside a Bento card preview container,
* reserving a final "Show more" footer row whenever items overflow.
*/
export function computeBentoPreviewLimit(
containerHeight: number,
totalItems: number,
rowHeight = 32,
rowGap = 6,
moreHeight = 28,
): { visibleCount: number; hiddenCount: number } {
if (totalItems <= 0) return { visibleCount: 0, hiddenCount: 0 }
if (!Number.isFinite(containerHeight) || containerHeight <= 0) {
const fallbackVisible = Math.min(4, totalItems)
return {
visibleCount: fallbackVisible,
hiddenCount: Math.max(0, totalItems - fallbackVisible),
}
}
const maxWithoutMore = Math.max(1, Math.floor((containerHeight + rowGap) / (rowHeight + rowGap)))
if (totalItems <= maxWithoutMore) {
return { visibleCount: totalItems, hiddenCount: 0 }
}
const visibleCount = Math.min(
totalItems,
Math.max(1, Math.floor((containerHeight - moreHeight) / (rowHeight + rowGap))),
)
return {
visibleCount,
hiddenCount: Math.max(0, totalItems - visibleCount),
}
}
export interface CollectedSummaryResponse {
total_records: number
overall_total_records: number
source_totals: Array<{ source: string; source_name: string; count: number }>
type_totals: Array<{ data_type: string; count: number }>
}
export interface LayerSummaryItem {
id: string
name: string
count: number
kinds?: unknown[]
}
export interface ComputeCountsSummary {
total: number
byStatus: Record<string, number>
}
export interface AssetDistributionItem {
key: string
name: string
count: number
meta?: string
filterQuery?: string
}
export interface TaskTrendBucket {
label: string
ok: number
fail: number
}
export interface LayerShareItem {
id: string
name: string
count: number
color: string
}
const DATA_TYPE_LABELS: Record<string, { zh: string; en: string }> = {
as_stats: { zh: '自治系统统计', en: 'AS Stats' },
bgp_update: { zh: 'BGP 更新', en: 'BGP Updates' },
bgp_rib: { zh: 'BGP 路由表', en: 'BGP RIB' },
bgp_route: { zh: 'BGP 路由', en: 'BGP Routes' },
bgp_event: { zh: 'BGP 事件', en: 'BGP Events' },
cable: { zh: '海缆', en: 'Cables' },
cable_landing_relation: { zh: '海缆登陆关系', en: 'Cable Landings' },
cable_system: { zh: '海缆系统', en: 'Cable Systems' },
submarine_cable: { zh: '海底光缆', en: 'Subsea Cables' },
landing_point: { zh: '登陆点', en: 'Landing Stations' },
compute_center: { zh: '算力中心', en: 'Compute Centers' },
supercomputer: { zh: '超算', en: 'Supercomputers' },
gpu_cluster: { zh: 'GPU 集群', en: 'GPU Clusters' },
datacenter: { zh: '数据中心', en: 'Data Centers' },
cloud_region: { zh: '云区区域', en: 'Cloud Regions' },
device_stats: { zh: '设备统计', en: 'Device Stats' },
generic: { zh: '通用数据', en: 'Generic Data' },
generic_records: { zh: '通用记录', en: 'Generic Records' },
ixp: { zh: '互联网交换点', en: 'IXPs' },
news_item: { zh: '新闻条目', en: 'News Items' },
news_live_stream: { zh: 'Live 新闻源', en: 'Live News Feeds' },
media_news: { zh: '媒体新闻', en: 'Media News' },
news: { zh: '新闻事件', en: 'News Events' },
prefix_geography: { zh: '前缀地理位置', en: 'Prefix Geography' },
geofeed_prefix: { zh: 'IP 地理前缀', en: 'Geofeed Prefixes' },
peeringdb_facility: { zh: '互联设施', en: 'IX Facilities' },
peeringdb_network: { zh: '自治网络', en: 'AS Networks' },
satellite_tle: { zh: '卫星轨道根数', en: 'Satellite TLE' },
satellite: { zh: '卫星实体', en: 'Satellites' },
space: { zh: '空间', en: 'Space' },
traffic_stats: { zh: '流量统计', en: 'Traffic Stats' },
vessel: { zh: '船舶', en: 'Vessels' },
vessel_position: { zh: '船舶 AIS', en: 'Vessel AIS' },
vessel_ais: { zh: 'AIS 船舶', en: 'Vessel AIS' },
flight: { zh: '航班轨迹', en: 'Flights' },
aircraft: { zh: '航空器', en: 'Aircraft' },
model: { zh: '模型', en: 'Models' },
dataset: { zh: '数据集', en: 'Datasets' },
network: { zh: '网络', en: 'Networks' },
facility: { zh: '设施', en: 'Facilities' },
weather: { zh: '气象图层', en: 'Weather' },
earthquake: { zh: '地震事件', en: 'Earthquakes' },
disaster: { zh: '灾害事件', en: 'Disasters' },
}
const LAYER_PALETTE = [
'var(--an-accent)',
'#0ea5e9',
'var(--an-success)',
'var(--an-warning)',
'#8b5cf6',
'var(--an-muted)',
]
function parseTimestampMs(raw: string | null | undefined): number {
if (!raw) return Number.NaN
const normalized =
raw.includes('T') && !raw.endsWith('Z') && !/[+-]\d{2}:\d{2}$/.test(raw)
? `${raw}Z`
: raw
return Date.parse(normalized)
}
/**
* Format raw data_type codes to human-readable bilingual labels.
*/
export function formatDataTypeLabel(dataType: string, isEnglish = false): string {
const key = String(dataType || '').trim()
if (!key) return '-'
const found = DATA_TYPE_LABELS[key]
if (found) return isEnglish ? found.en : found.zh
return key
.split('_')
.filter(Boolean)
.map((part) => part.charAt(0).toUpperCase() + part.slice(1))
.join(' ')
}
/**
* Aggregate raw collection task logs into 24h (6 × 4h) or 7d (7 × 1d) trend buckets.
*/
export function buildTaskTrendBuckets(
tasks: DashboardTaskRow[],
windowMode: '24h' | '7d',
nowMs = Date.now(),
): TaskTrendBucket[] {
if (windowMode === '24h') {
const bucketMs = 4 * 3_600_000
const endHourAligned = new Date(nowMs)
endHourAligned.setUTCMinutes(0, 0, 0)
const endBucketEndMs = endHourAligned.getTime() + 3_600_000
const startMs = endBucketEndMs - 6 * bucketMs
const buckets: TaskTrendBucket[] = Array.from({ length: 6 }, (_, index) => {
const slotStart = new Date(startMs + index * bucketMs)
const hh = String(slotStart.getHours()).padStart(2, '0')
return { label: `${hh}:00`, ok: 0, fail: 0 }
})
for (const task of tasks) {
const ts = parseTimestampMs(task.started_at || task.completed_at)
if (!Number.isFinite(ts) || ts < startMs || ts >= endBucketEndMs) continue
const idx = Math.min(5, Math.max(0, Math.floor((ts - startMs) / bucketMs)))
const status = String(task.status || '').toLowerCase()
if (status === 'success' || status === 'completed') {
buckets[idx].ok += 1
} else if (status === 'failed' || status === 'error') {
buckets[idx].fail += 1
}
}
return buckets
}
const dayMs = 86_400_000
const todayStart = new Date(nowMs)
todayStart.setHours(0, 0, 0, 0)
const startDayMs = todayStart.getTime() - 6 * dayMs
const endDayMs = todayStart.getTime() + dayMs
const buckets: TaskTrendBucket[] = Array.from({ length: 7 }, (_, index) => {
const slotDate = new Date(startDayMs + index * dayMs)
const mm = String(slotDate.getMonth() + 1).padStart(2, '0')
const dd = String(slotDate.getDate()).padStart(2, '0')
return { label: `${mm}/${dd}`, ok: 0, fail: 0 }
})
for (const task of tasks) {
const ts = parseTimestampMs(task.started_at || task.completed_at)
if (!Number.isFinite(ts) || ts < startDayMs || ts >= endDayMs) continue
const idx = Math.min(6, Math.max(0, Math.floor((ts - startDayMs) / dayMs)))
const status = String(task.status || '').toLowerCase()
if (status === 'success' || status === 'completed') {
buckets[idx].ok += 1
} else if (status === 'failed' || status === 'error') {
buckets[idx].fail += 1
}
}
return buckets
}
/**
* Shape globe core layers into bounded top slices plus an optional aggregate tail.
*/
export function buildLayerShareItems(
layers: LayerSummaryItem[],
maxSlices = 6,
otherLabel = '其他图层',
): LayerShareItem[] {
const sorted = [...layers]
.filter((item) => Number(item.count) > 0)
.sort((a, b) => b.count - a.count)
if (!sorted.length) return []
const cap = Math.max(2, maxSlices)
const top = sorted.length > cap ? sorted.slice(0, cap - 1) : sorted
const rest = sorted.length > cap ? sorted.slice(cap - 1) : []
const items: LayerShareItem[] = top.map((item, idx) => ({
id: item.id,
name: item.name,
count: item.count,
color: LAYER_PALETTE[idx % (LAYER_PALETTE.length - 1)],
}))
if (rest.length > 0) {
items.push({
id: '__other__',
name: otherLabel,
count: rest.reduce((sum, item) => sum + item.count, 0),
color: LAYER_PALETTE[LAYER_PALETTE.length - 1],
})
}
return items
}
@@ -0,0 +1,845 @@
import type { ColumnDef } from '@tanstack/react-table'
import axios from 'axios'
import { ArrowRight, Compass, MapPin, RefreshCw, RotateCcw, Search, Square, X } from 'lucide-react'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import Scrollbar from '../../../components/Scrollbar/Scrollbar'
import { formatDateTimeZhCN } from '../../../utils/datetime'
import { DataTable } from '../../components/data-table/DataTable'
import { useWaterfallQuery } from '../../components/data-table/useWaterfallQuery'
import { Badge } from '../../components/ui/badge'
import { Button } from '../../components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '../../components/ui/card'
import { Dialog } from '../../components/ui/dialog'
import { Input } from '../../components/ui/input'
import { Select } from '../../components/ui/select'
import { TableActionButton } from '../../components/ui/table-action-button'
import { useToast } from '../../components/ui/toast'
import { StatusText } from '../../patterns/patterns'
import {
COMPUTE_SITE_TYPE_LABELS,
COMPUTE_SITE_TYPE_ORDER,
COMPUTE_STATUS_BUCKET_META,
EDITABLE_PRECISION_OPTIONS,
PRECISION_LABELS,
TERMINAL_STATUS_LABELS,
type ComputeCandidate,
type ComputeLedgerResponse,
type ComputeLedgerRow,
type ComputeSiteType,
type ComputeStatusBucket,
} from './ledger-model'
export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
const { toast } = useToast()
const navigate = useNavigate()
const [siteTypeFilter, setSiteTypeFilter] = useState('')
const [statusFilter, setStatusFilter] = useState('')
const [countryFilter, setCountryFilter] = useState('')
const [searchInput, setSearchInput] = useState('')
const [debouncedSearch, setDebouncedSearch] = useState('')
const [selectedRowIds, setSelectedRowIds] = useState<Set<string>>(() => new Set())
const [relocatingIds, setRelocatingIds] = useState<Set<string>>(() => new Set())
const [batchProgress, setBatchProgress] = useState<{ running: boolean; done: number; total: number } | null>(null)
const batchStopRef = useRef(false)
const [detailRow, setDetailRow] = useState<ComputeLedgerRow | null>(null)
const [detailOpen, setDetailOpen] = useState(false)
const [candidatesBySourceId, setCandidatesBySourceId] = useState<
Record<string, { items: ComputeCandidate[]; workflowRunId: string | null }>
>({})
const [adoptingKey, setAdoptingKey] = useState<string | null>(null)
const [editTarget, setEditTarget] = useState<ComputeLedgerRow | null>(null)
const [editLat, setEditLat] = useState('')
const [editLon, setEditLon] = useState('')
const [editCity, setEditCity] = useState('')
const [editCountry, setEditCountry] = useState('')
const [editPrecision, setEditPrecision] = useState('site')
const [savingEdit, setSavingEdit] = useState(false)
useEffect(() => {
const trimmed = searchInput.trim()
if (!trimmed) {
setDebouncedSearch('')
return undefined
}
const timer = window.setTimeout(() => {
setDebouncedSearch(trimmed)
}, 280)
return () => window.clearTimeout(timer)
}, [searchInput])
useEffect(() => {
setSelectedRowIds(new Set())
}, [countryFilter, debouncedSearch, siteTypeFilter, statusFilter])
const fetchComputePage = useCallback(
async (page: number, pageSize: number) => {
const params = new URLSearchParams({
page: String(page),
page_size: String(pageSize),
})
if (siteTypeFilter) params.set('site_type', siteTypeFilter)
if (statusFilter) params.set('status', statusFilter)
if (countryFilter) params.set('country', countryFilter)
if (debouncedSearch) params.set('search', debouncedSearch)
const res = await axios.get<ComputeLedgerResponse>(`/api/v1/data-ledger/compute-centers?${params}`)
return {
rows: res.data.items || [],
total: res.data.total || 0,
meta: res.data,
}
},
[countryFilter, debouncedSearch, siteTypeFilter, statusFilter],
)
const handleLoadError = useCallback(
(error: unknown) => {
toast({
tone: 'error',
title: '加载算力中心台账失败',
description: error instanceof Error ? error.message : '请稍后重试',
})
},
[toast],
)
const {
items,
total,
meta: payload,
loading,
loadingMore,
hasMore,
reload: fetchComputeLedger,
loadMore,
} = useWaterfallQuery<ComputeLedgerRow, ComputeLedgerResponse>({
fetchPage: fetchComputePage,
getRowKey: (row) => `${row.source}:${row.source_id}`,
deps: [countryFilter, debouncedSearch, siteTypeFilter, statusFilter],
pageSize: 30,
onError: handleLoadError,
})
const handleReset = () => {
setSiteTypeFilter('')
setStatusFilter('')
setCountryFilter('')
setSearchInput('')
setDebouncedSearch('')
}
const handleForceRelocate = useCallback(async (row: ComputeLedgerRow) => {
setRelocatingIds((prev) => {
const next = new Set(prev)
next.add(row.source_id)
return next
})
try {
const res = await axios.post(`/api/v1/visualization/compute-centers/${encodeURIComponent(row.source_id)}/collect-location`, {
force: true,
source: row.source,
name: row.name,
operator: row.operator || undefined,
city: row.city || undefined,
country: row.country || undefined,
})
const data = res.data || {}
const candidates = Array.isArray(data.candidates) ? (data.candidates as ComputeCandidate[]) : []
const runId = typeof data.workflow_run_id === 'string' ? data.workflow_run_id : row.workflow_run_id
setCandidatesBySourceId((prev) => ({
...prev,
[row.source_id]: { items: candidates, workflowRunId: runId || null },
}))
if (data.success && candidates.length > 0) {
toast({ tone: 'success', title: `已获取 ${candidates.length} 个候选坐标`, description: '点击行可查看并采纳候选位置' })
} else if (data.terminal_status) {
const label = TERMINAL_STATUS_LABELS[data.terminal_status] || data.terminal_status
toast({ tone: 'default', title: `已确认:${label}`, description: data.failure_reason || undefined })
} else {
toast({ tone: 'default', title: '未找到可用候选坐标', description: data.failure_reason || data.llm_failure_reason || undefined })
}
setDetailRow({
...row,
workflow_run_id: runId || row.workflow_run_id,
terminal_status: data.terminal_status || row.terminal_status,
source_note: data.failure_reason || row.source_note,
})
setDetailOpen(true)
await fetchComputeLedger()
onMutated?.()
} catch (error) {
toast({
tone: 'error',
title: '重新定位失败',
description: error instanceof Error ? error.message : '请稍后重试',
})
} finally {
setRelocatingIds((prev) => {
const next = new Set(prev)
next.delete(row.source_id)
return next
})
}
}, [fetchComputeLedger, onMutated, toast])
const selectedRows = useMemo(
() => items.filter((row) => !row.is_anonymous_placeholder && selectedRowIds.has(`${row.source}:${row.source_id}`)),
[items, selectedRowIds],
)
const toggleAllVisibleSelection = useCallback((visibleIds: string[]) => {
setSelectedRowIds((prev) => {
const next = new Set(prev)
const allSelected = visibleIds.length > 0 && visibleIds.every((id) => next.has(id))
if (allSelected) {
visibleIds.forEach((id) => next.delete(id))
} else {
visibleIds.forEach((id) => next.add(id))
}
return next
})
}, [])
const toggleSingleSelection = useCallback((rowId: string) => {
setSelectedRowIds((prev) => {
const next = new Set(prev)
if (next.has(rowId)) {
next.delete(rowId)
} else {
next.add(rowId)
}
return next
})
}, [])
const handleBatchRelocate = useCallback(async () => {
const queue = selectedRows.slice()
if (queue.length === 0 || batchProgress?.running) return
batchStopRef.current = false
setBatchProgress({ running: true, done: 0, total: queue.length })
let cursor = 0
let done = 0
let found = 0
let terminal = 0
let missed = 0
let failed = 0
const processedRowKeys = new Set<string>()
const runWorker = async () => {
while (!batchStopRef.current) {
const index = cursor++
if (index >= queue.length) return
const row = queue[index]
const rowKey = `${row.source}:${row.source_id}`
setRelocatingIds((prev) => {
const next = new Set(prev)
next.add(row.source_id)
return next
})
try {
const res = await axios.post(`/api/v1/visualization/compute-centers/${encodeURIComponent(row.source_id)}/collect-location`, {
force: true,
source: row.source,
name: row.name,
operator: row.operator || undefined,
city: row.city || undefined,
country: row.country || undefined,
})
const data = res.data || {}
const candidates = Array.isArray(data.candidates) ? (data.candidates as ComputeCandidate[]) : []
const runId = typeof data.workflow_run_id === 'string' ? data.workflow_run_id : row.workflow_run_id
if (candidates.length > 0) {
setCandidatesBySourceId((prev) => ({
...prev,
[row.source_id]: { items: candidates, workflowRunId: runId || null },
}))
}
if (data.success && candidates.length > 0) {
found += 1
} else if (data.terminal_status) {
terminal += 1
} else {
missed += 1
}
processedRowKeys.add(rowKey)
} catch {
failed += 1
} finally {
done += 1
setBatchProgress({ running: true, done, total: queue.length })
setRelocatingIds((prev) => {
const next = new Set(prev)
next.delete(row.source_id)
return next
})
}
}
}
const concurrency = Math.min(2, queue.length)
await Promise.all(Array.from({ length: concurrency }, () => runWorker()))
setBatchProgress(null)
if (processedRowKeys.size > 0) {
setSelectedRowIds((prev) => {
const next = new Set(prev)
processedRowKeys.forEach((id) => next.delete(id))
return next
})
}
toast({
tone: failed > 0 && found === 0 ? 'error' : found > 0 ? 'success' : 'default',
title: batchStopRef.current
? `已停止批量定位(已完成 ${done} / ${queue.length} 条)`
: `批量定位完成:候选 ${found} 条,暂不可定位 ${terminal} 条,未命中 ${missed} 条${failed ? `,失败 ${failed} 条` : ''}`,
})
await fetchComputeLedger()
onMutated?.()
}, [batchProgress?.running, fetchComputeLedger, onMutated, selectedRows, toast])
const openEditDialog = useCallback((row: ComputeLedgerRow) => {
setEditTarget(row)
setEditLat(row.latitude !== null ? String(row.latitude) : '')
setEditLon(row.longitude !== null ? String(row.longitude) : '')
setEditCity(row.city || '')
setEditCountry(row.country || '')
setEditPrecision(row.precision && row.precision !== 'unknown' ? row.precision : 'site')
}, [])
const handleSaveManualLocation = async () => {
if (!editTarget) return
const lat = Number(editLat)
const lon = Number(editLon)
if (!Number.isFinite(lat) || !Number.isFinite(lon) || lat < -90 || lat > 90 || lon < -180 || lon > 180 || lat === 0 || lon === 0) {
toast({ tone: 'error', title: '请输入有效的非零经纬度坐标' })
return
}
setSavingEdit(true)
try {
await axios.post(`/api/v1/visualization/compute-centers/${encodeURIComponent(editTarget.source_id)}/location`, {
source: editTarget.source,
name: editTarget.name,
operator: editTarget.operator || undefined,
city: editCity.trim() || undefined,
country: editCountry.trim() || undefined,
latitude: lat,
longitude: lon,
precision: editPrecision,
location_source: 'manual_selection',
verification_status: 'verified',
needs_confirmation: false,
})
toast({ tone: 'success', title: '坐标已保存' })
setEditTarget(null)
await fetchComputeLedger()
onMutated?.()
} catch (error) {
toast({
tone: 'error',
title: '保存坐标失败',
description: error instanceof Error ? error.message : '请稍后重试',
})
} finally {
setSavingEdit(false)
}
}
const handleAdoptCandidate = async (row: ComputeLedgerRow, candidate: ComputeCandidate, index: number, wfRunId: string | null) => {
const key = `${row.source_id}:${index}`
setAdoptingKey(key)
try {
await axios.post(`/api/v1/visualization/compute-centers/${encodeURIComponent(row.source_id)}/location`, {
source: row.source,
name: candidate.display_name || row.name,
operator: row.operator || undefined,
city: candidate.city || undefined,
country: candidate.country || undefined,
latitude: candidate.latitude,
longitude: candidate.longitude,
precision: candidate.precision || 'city',
confidence: candidate.confidence,
location_source: candidate.source || 'llm_location_factcheck',
source_url: candidate.source_url || undefined,
source_note: candidate.source_note || undefined,
raw_payload: {
...(candidate.raw_payload || {}),
...(wfRunId ? { workflow_run_id: wfRunId } : {}),
},
verification_status: 'verified',
needs_confirmation: false,
workflow_run_id: wfRunId || undefined,
})
toast({ tone: 'success', title: '已采纳候选坐标' })
setDetailOpen(false)
await fetchComputeLedger()
onMutated?.()
} catch (error) {
toast({
tone: 'error',
title: '采纳候选失败',
description: error instanceof Error ? error.message : '请稍后重试',
})
} finally {
setAdoptingKey(null)
}
}
const bySiteType = payload?.counts?.by_site_type || {}
const byStatus = payload?.counts?.by_status || {}
const allSiteTypeCount = COMPUTE_SITE_TYPE_ORDER.reduce((sum, key) => sum + (bySiteType[key] || 0), 0)
const statusOptions = [
{ value: 'all', label: '全部定位状态' },
{ value: 'located', label: `已定位 (${byStatus.located || 0})` },
{ value: 'needs_confirmation', label: `待确认 (${byStatus.needs_confirmation || 0})` },
{ value: 'terminal', label: `暂不可定位 (${byStatus.terminal || 0})` },
{ value: 'pending', label: `待定位 (${byStatus.pending || 0})` },
]
const countryOptions = useMemo(() => [
{ value: 'all', label: '全部国家/地区' },
...(payload?.countries || []).map((c) => ({ value: c, label: c })),
], [payload?.countries])
const columns = useMemo<Array<ColumnDef<ComputeLedgerRow>>>(() => [
{
accessorKey: 'name',
header: '名称',
size: 220,
minSize: 160,
cell: ({ row }) => (
<button
type="button"
className="an-table-link"
onClick={(event) => {
event.stopPropagation()
setDetailRow(row.original)
setDetailOpen(true)
}}
>
{row.original.name}
</button>
),
},
{
accessorKey: 'site_type',
header: '设施类型',
size: 112,
minSize: 96,
cell: ({ row }) => (
<Badge tone="slate">
{COMPUTE_SITE_TYPE_LABELS[row.original.site_type as ComputeSiteType] || row.original.site_type}
</Badge>
),
},
{
accessorKey: 'operator',
header: '运营方',
size: 140,
minSize: 100,
cell: ({ row }) => row.original.operator || '-',
},
{
accessorKey: 'country',
header: '国家',
size: 96,
minSize: 80,
cell: ({ row }) => row.original.country || '-',
},
{
accessorKey: 'city',
header: '城市',
size: 112,
minSize: 84,
cell: ({ row }) => row.original.city || '-',
},
{
id: 'coordinates',
header: '坐标',
size: 156,
minSize: 136,
cell: ({ row }) => (
row.original.latitude !== null && row.original.longitude !== null
? <span className="an-tabular-num">{`${row.original.latitude.toFixed(4)}, ${row.original.longitude.toFixed(4)}`}</span>
: '-'
),
},
{
accessorKey: 'precision',
header: '精度',
size: 76,
minSize: 68,
cell: ({ row }) => PRECISION_LABELS[row.original.precision] || row.original.precision || '-',
},
{
accessorKey: 'status_bucket',
header: '定位状态',
size: 156,
minSize: 128,
cell: ({ row }) => {
const meta = COMPUTE_STATUS_BUCKET_META[row.original.status_bucket as ComputeStatusBucket]
|| { label: row.original.status_bucket, tone: 'neutral' as const }
const terminalText = row.original.terminal_status
? TERMINAL_STATUS_LABELS[row.original.terminal_status] || row.original.terminal_status
: null
return (
<StatusText tone={meta.tone}>
{terminalText ? `${meta.label} · ${terminalText}` : meta.label}
</StatusText>
)
},
},
{
accessorKey: 'updated_at',
header: '更新时间',
size: 168,
minSize: 152,
cell: ({ row }) => (row.original.updated_at ? formatDateTimeZhCN(row.original.updated_at) : '-'),
},
{
id: 'actions',
header: '操作',
size: 80,
minSize: 80,
enableResizing: false,
cell: ({ row }) => {
const isAnonymousPlaceholder = Boolean(row.original.is_anonymous_placeholder)
const relocateTitle = isAnonymousPlaceholder
? '源数据为匿名占位条目,无可检索线索'
: '重新定位'
return (
<div
className="an-table-actions"
onClick={(event) => event.stopPropagation()}
>
<TableActionButton
aria-label={isAnonymousPlaceholder ? `源数据为匿名占位条目,无可检索线索 ${row.original.name}` : `重新定位 ${row.original.name}`}
title={relocateTitle}
disabled={isAnonymousPlaceholder}
loading={relocatingIds.has(row.original.source_id)}
onClick={() => void handleForceRelocate(row.original)}
>
<Compass size={14} aria-hidden="true" />
</TableActionButton>
<TableActionButton
aria-label={`编辑坐标 ${row.original.name}`}
title="编辑坐标"
onClick={() => openEditDialog(row.original)}
>
<MapPin size={14} aria-hidden="true" />
</TableActionButton>
</div>
)
},
},
], [handleForceRelocate, openEditDialog, relocatingIds])
const activeCandidates = detailRow ? candidatesBySourceId[detailRow.source_id] : undefined
const hasActiveFilters = Boolean(siteTypeFilter || statusFilter || countryFilter || searchInput.trim())
const showBatchBar = selectedRows.length > 0 || Boolean(batchProgress?.running)
return (
<Card className="an-data-table-card">
<CardHeader className="an-data-table-card__header">
<div>
<CardTitle>算力中心台账</CardTitle>
<p>{`共 ${total.toLocaleString()} 条结果`}</p>
</div>
{showBatchBar ? (
<div className="an-batch-bar" role="toolbar" aria-label="批量操作">
<span className="an-batch-bar__count">
<strong>
{batchProgress?.running
? `${batchProgress.done}/${batchProgress.total}`
: selectedRows.length}
</strong>
{batchProgress?.running ? '定位中' : '已选择'}
</span>
{batchProgress?.running ? (
<Button
size="sm"
variant="danger"
onClick={() => {
batchStopRef.current = true
}}
title="停止批量定位"
>
<Square size={13} aria-hidden="true" />
停止
</Button>
) : (
<Button
size="sm"
variant="primary"
onClick={() => void handleBatchRelocate()}
disabled={!selectedRows.length}
title="批量定位选中条目"
>
<Compass size={14} aria-hidden="true" />
批量定位
<span className="an-batch-bar__num">{selectedRows.length}</span>
</Button>
)}
<Button
size="icon"
variant="subtle"
onClick={() => setSelectedRowIds(new Set())}
disabled={Boolean(batchProgress?.running)}
title="清除选择"
aria-label="清除选择"
>
<X size={14} />
</Button>
</div>
) : (
<div className="an-toolbar">
<Button size="sm" variant="subtle" onClick={() => void fetchComputeLedger()}><RefreshCw size={14} />刷新</Button>
</div>
)}
</CardHeader>
<CardContent>
<div className="an-filter-grid--datasources an-filter-grid--ledger">
<div className="an-segmented an-segmented--counted" role="tablist" aria-label="设施类型">
<button
type="button"
className={!siteTypeFilter ? 'is-active' : ''}
onClick={() => { setSiteTypeFilter('') }}
>
<span>全部</span>
<span className="an-segmented__count">{allSiteTypeCount}</span>
</button>
{COMPUTE_SITE_TYPE_ORDER.map((typeKey) => (
<button
key={typeKey}
type="button"
className={siteTypeFilter === typeKey ? 'is-active' : ''}
onClick={() => { setSiteTypeFilter(typeKey) }}
>
<span>{COMPUTE_SITE_TYPE_LABELS[typeKey]}</span>
<span className="an-segmented__count">{bySiteType[typeKey] || 0}</span>
</button>
))}
</div>
<div className="an-field an-field--inline-filter">
<Select
value={statusFilter || 'all'}
onValueChange={(value) => {
setStatusFilter(value === 'all' ? '' : value)
}}
options={statusOptions}
/>
</div>
<div className="an-field an-field--inline-filter">
<Select
value={countryFilter || 'all'}
onValueChange={(value) => {
setCountryFilter(value === 'all' ? '' : value)
}}
options={countryOptions}
/>
</div>
<div className="an-search-box an-search-box--inline">
<Search size={14} aria-hidden="true" />
<Input
placeholder="搜索名称、运营方、城市、说明"
aria-label="搜索名称、运营方、城市、说明"
value={searchInput}
onChange={(event) => setSearchInput(event.target.value)}
/>
{searchInput ? (
<Button
size="icon"
variant="ghost"
onClick={() => setSearchInput('')}
title="清空搜索"
aria-label="清空搜索"
>
<X size={14} />
</Button>
) : null}
</div>
<Button
size="icon"
variant="subtle"
onClick={handleReset}
disabled={!hasActiveFilters}
title="重置筛选"
aria-label="重置筛选"
>
<RotateCcw size={14} />
</Button>
</div>
<DataTable
className="an-ledger-table an-ledger-table--compute"
columns={columns}
data={items}
getRowId={(row) => `${row.source}:${row.source_id}`}
loading={loading}
columnWidthStorageKey="planet.table.widths.ledger.compute"
scrollResetKey={`${siteTypeFilter}|${statusFilter}|${countryFilter}|${debouncedSearch}`}
selection={{
selectedRowIds,
onToggleAllVisible: toggleAllVisibleSelection,
onToggleRow: (rowId) => toggleSingleSelection(rowId),
getCheckboxLabel: (row) => `选择 ${row.name}`,
isRowSelectable: (row) => !row.is_anonymous_placeholder,
}}
onRowClick={(row) => {
setDetailRow(row)
setDetailOpen(true)
}}
waterfall={{
total,
hasMore,
loadingMore,
onLoadMore: () => void loadMore(),
showFooter: true,
}}
/>
</CardContent>
<Dialog title={detailRow ? `${detailRow.name} 定位详情` : '算力中心详情'} open={detailOpen} onOpenChange={setDetailOpen} width={760}>
{detailRow ? (
<div className="an-detail">
<div className="an-detail-links">
{detailRow.workflow_run_id ? (
<button
type="button"
className="an-detail-link"
onClick={() => {
setDetailOpen(false)
navigate('/advisor/runs')
}}
>
<span>{`查看工作流运行记录 (${detailRow.workflow_run_id})`}</span>
<ArrowRight size={14} />
</button>
) : null}
<button
type="button"
className="an-detail-link"
onClick={() => void handleForceRelocate(detailRow)}
disabled={relocatingIds.has(detailRow.source_id) || Boolean(detailRow.is_anonymous_placeholder)}
title={detailRow.is_anonymous_placeholder ? '源数据为匿名占位条目,无可检索线索' : '重新定位'}
>
<span>{relocatingIds.has(detailRow.source_id) ? '正在重新定位...' : '重新定位'}</span>
<Compass size={14} />
</button>
<button
type="button"
className="an-detail-link"
onClick={() => {
setDetailOpen(false)
openEditDialog(detailRow)
}}
>
<span>编辑坐标</span>
<MapPin size={14} />
</button>
</div>
<section className="an-detail__section">
<h3>核验依据与定位属性</h3>
<div className="an-detail__grid">
<div><span>来源标识</span><strong>{`${detailRow.source} / ${detailRow.source_id}`}</strong></div>
<div><span>设施类型</span><strong>{COMPUTE_SITE_TYPE_LABELS[detailRow.site_type] || detailRow.site_type}</strong></div>
<div><span>运营方</span><strong>{detailRow.operator || '-'}</strong></div>
<div><span>国家 / 城市</span><strong>{[detailRow.country, detailRow.city].filter(Boolean).join(' · ') || '-'}</strong></div>
<div><span>定位来源</span><strong>{detailRow.location_source || '-'}</strong></div>
<div>
<span>核验状态</span>
<strong>
{detailRow.terminal_status
? `${COMPUTE_STATUS_BUCKET_META[detailRow.status_bucket].label}(${TERMINAL_STATUS_LABELS[detailRow.terminal_status] || detailRow.terminal_status})`
: COMPUTE_STATUS_BUCKET_META[detailRow.status_bucket].label}
</strong>
</div>
</div>
<div className="an-ledger-note-box">
<span>依据说明</span>
<p>{detailRow.source_note || '暂无补充说明'}</p>
</div>
</section>
{activeCandidates && activeCandidates.items.length > 0 ? (
<section className="an-detail__section">
<h3>{`新采集候选位置 (${activeCandidates.items.length})`}</h3>
<Scrollbar className="an-ledger-candidate-scroll">
<div className="an-ledger-candidates">
{activeCandidates.items.map((cand, index) => {
const key = `${detailRow.source_id}:${index}`
return (
<div key={key} className="an-ledger-candidate-item">
<div>
<strong>{cand.display_name || detailRow.name}</strong>
<p>{`${cand.latitude.toFixed(5)}, ${cand.longitude.toFixed(5)} · ${PRECISION_LABELS[cand.precision] || cand.precision} · ${[cand.country, cand.city].filter(Boolean).join(' / ') || '-'}`}</p>
{cand.source_note ? <small>{cand.source_note}</small> : null}
</div>
<Button
size="sm"
variant="primary"
loading={adoptingKey === key}
onClick={() => void handleAdoptCandidate(detailRow, cand, index, activeCandidates.workflowRunId)}
>
采纳
</Button>
</div>
)
})}
</div>
</Scrollbar>
</section>
) : null}
</div>
) : null}
</Dialog>
<Dialog
title={editTarget ? `编辑坐标:${editTarget.name}` : '编辑坐标'}
open={Boolean(editTarget)}
onOpenChange={(open) => {
if (!open) setEditTarget(null)
}}
width={480}
footer={(
<>
<Button variant="subtle" onClick={() => setEditTarget(null)} disabled={savingEdit}>取消</Button>
<Button variant="primary" onClick={() => void handleSaveManualLocation()} loading={savingEdit}>保存坐标</Button>
</>
)}
>
<div className="an-form-grid">
<div className="an-field">
<label htmlFor="ledger-edit-lat">纬度</label>
<Input id="ledger-edit-lat" value={editLat} onChange={(e) => setEditLat(e.target.value)} placeholder="如 35.7804" />
</div>
<div className="an-field">
<label htmlFor="ledger-edit-lon">经度</label>
<Input id="ledger-edit-lon" value={editLon} onChange={(e) => setEditLon(e.target.value)} placeholder="如 -78.6391" />
</div>
<div className="an-field">
<label htmlFor="ledger-edit-city">城市</label>
<Input id="ledger-edit-city" value={editCity} onChange={(e) => setEditCity(e.target.value)} placeholder="城市名称" />
</div>
<div className="an-field">
<label htmlFor="ledger-edit-country">国家</label>
<Input id="ledger-edit-country" value={editCountry} onChange={(e) => setEditCountry(e.target.value)} placeholder="国家或地区" />
</div>
<div className="an-field">
<label>精度</label>
<Select value={editPrecision} onValueChange={setEditPrecision} options={EDITABLE_PRECISION_OPTIONS} />
</div>
</div>
</Dialog>
</Card>
)
}
@@ -0,0 +1,227 @@
import type { ColumnDef } from '@tanstack/react-table'
import axios from 'axios'
import { RefreshCw, RotateCcw, Search, X } from 'lucide-react'
import { useCallback, useEffect, useMemo, useState } from 'react'
import { formatDateTimeZhCN } from '../../../utils/datetime'
import { DataTable } from '../../components/data-table/DataTable'
import { useWaterfallQuery } from '../../components/data-table/useWaterfallQuery'
import { Button } from '../../components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '../../components/ui/card'
import { Input } from '../../components/ui/input'
import { useToast } from '../../components/ui/toast'
import type { GenericLayerItemsResponse, LedgerKind } from './ledger-model'
const TIMESTAMP_COLUMN_KEYS = new Set([
'collected_at',
'reference_date',
'observed_at',
'updated_at',
'started_at',
'published_at',
])
const WIDE_COLUMN_KEYS = new Set(['name', 'title', 'collector_id', 'location_label'])
const SOURCE_COLUMN_KEYS = new Set(['source'])
const IDENTIFIER_COLUMN_KEYS = new Set(['source_id', 'mmsi', 'international_designator'])
function columnWidthSpec(key: string): { size: number; minSize: number } {
if (WIDE_COLUMN_KEYS.has(key)) return { size: 240, minSize: 140 }
if (TIMESTAMP_COLUMN_KEYS.has(key)) return { size: 172, minSize: 150 }
if (SOURCE_COLUMN_KEYS.has(key)) return { size: 168, minSize: 110 }
if (key === 'coordinates') return { size: 156, minSize: 130 }
if (IDENTIFIER_COLUMN_KEYS.has(key)) return { size: 132, minSize: 96 }
return { size: 120, minSize: 88 }
}
export function LayerItemsLedger({
layerId,
layerName,
initialKinds,
}: {
layerId: string
layerName: string
initialKinds: LedgerKind[]
}) {
const { toast } = useToast()
const [kind, setKind] = useState<string>(initialKinds[0]?.id || 'all')
const [searchInput, setSearchInput] = useState('')
const [debouncedSearch, setDebouncedSearch] = useState('')
useEffect(() => {
const firstKind = initialKinds[0]?.id || 'all'
setKind((prev) => {
if (initialKinds.length > 0 && (prev === 'all' || !initialKinds.some((k) => k.id === prev))) {
return firstKind
}
return prev
})
}, [initialKinds])
useEffect(() => {
const trimmed = searchInput.trim()
if (!trimmed) {
setDebouncedSearch('')
return undefined
}
const timer = window.setTimeout(() => {
setDebouncedSearch(trimmed)
}, 280)
return () => window.clearTimeout(timer)
}, [searchInput])
const fetchItemsPage = useCallback(
async (page: number, pageSize: number) => {
const params = new URLSearchParams({
page: String(page),
page_size: String(pageSize),
})
if (kind && kind !== 'all') params.set('kind', kind)
if (debouncedSearch) params.set('search', debouncedSearch)
const res = await axios.get<GenericLayerItemsResponse>(
`/api/v1/data-ledger/${encodeURIComponent(layerId)}/items?${params}`,
)
return {
rows: res.data.rows || [],
total: res.data.total || 0,
meta: res.data,
}
},
[debouncedSearch, kind, layerId],
)
const handleLoadError = useCallback(
(error: unknown) => {
toast({
tone: 'error',
title: `加载${layerName}台账失败`,
description: error instanceof Error ? error.message : '请稍后重试',
})
},
[layerName, toast],
)
const {
items: rows,
total,
meta: payload,
loading,
loadingMore,
hasMore,
reload: fetchItems,
loadMore,
} = useWaterfallQuery<Record<string, unknown>, GenericLayerItemsResponse>({
fetchPage: fetchItemsPage,
getRowKey: (row, index) => String(row.id ?? row.source_id ?? index),
deps: [layerId, kind, debouncedSearch],
pageSize: 30,
onError: handleLoadError,
})
const kinds = payload?.kinds?.length ? payload.kinds : initialKinds
const columns = useMemo<Array<ColumnDef<Record<string, unknown>>>>(() => {
const defs = payload?.columns || []
return defs.map((col) => {
const sizing = columnWidthSpec(col.key)
return {
accessorKey: col.key,
header: col.label,
size: sizing.size,
minSize: sizing.minSize,
cell: ({ row }) => {
const val = row.original[col.key]
if (val === null || val === undefined || val === '') return '-'
if (TIMESTAMP_COLUMN_KEYS.has(col.key) && typeof val === 'string') {
return formatDateTimeZhCN(val)
}
return String(val)
},
}
})
}, [payload?.columns])
const hasActiveFilters = Boolean(searchInput.trim() || (kinds.length > 0 && kind !== kinds[0].id))
return (
<Card className="an-data-table-card">
<CardHeader className="an-data-table-card__header">
<div>
<CardTitle>{`${layerName}台账`}</CardTitle>
<p>{`共 ${total.toLocaleString()} 条结果`}</p>
</div>
<div className="an-toolbar">
<Button size="sm" variant="subtle" onClick={() => void fetchItems()}><RefreshCw size={14} />刷新</Button>
</div>
</CardHeader>
<CardContent>
<div className="an-filter-grid--datasources an-filter-grid--ledger">
{kinds.length > 0 ? (
<div className="an-segmented an-segmented--counted" role="tablist" aria-label={`${layerName}子分类`}>
{kinds.map((item) => (
<button
key={item.id}
type="button"
className={kind === item.id ? 'is-active' : ''}
onClick={() => setKind(item.id)}
>
<span>{item.label}</span>
</button>
))}
</div>
) : null}
<div className="an-search-box an-search-box--inline">
<Search size={14} aria-hidden="true" />
<Input
placeholder="搜索名称、标识或来源"
aria-label="搜索名称、标识或来源"
value={searchInput}
onChange={(event) => setSearchInput(event.target.value)}
/>
{searchInput ? (
<Button
size="icon"
variant="ghost"
onClick={() => setSearchInput('')}
title="清空搜索"
aria-label="清空搜索"
>
<X size={14} />
</Button>
) : null}
</div>
<Button
size="icon"
variant="subtle"
onClick={() => {
setSearchInput('')
setDebouncedSearch('')
if (kinds.length > 0) setKind(kinds[0].id)
}}
disabled={!hasActiveFilters}
title="重置筛选"
aria-label="重置筛选"
>
<RotateCcw size={14} />
</Button>
</div>
<DataTable
className="an-ledger-table"
columns={columns}
data={rows}
getRowId={(row, index) => String(row.id ?? row.source_id ?? index)}
loading={loading}
columnWidthStorageKey={`planet.table.widths.ledger.${layerId}.${kind}`}
scrollResetKey={`${layerId}|${kind}|${debouncedSearch}`}
waterfall={{
total,
hasMore,
loadingMore,
onLoadMore: () => void loadMore(),
showFooter: true,
}}
/>
</CardContent>
</Card>
)
}
@@ -0,0 +1,53 @@
import Scrollbar from '../../../components/Scrollbar/Scrollbar'
import { Card, CardContent, CardHeader, CardTitle } from '../../components/ui/card'
import { Badge } from '../../components/ui/badge'
import { cn } from '../../utils'
import type { LedgerLayerSummary } from './ledger-model'
export function LayerNav({
layers,
activeLayer,
loading,
onSelectLayer,
}: {
layers: LedgerLayerSummary[]
activeLayer: string
loading: boolean
onSelectLayer: (layerId: string) => void
}) {
return (
<Card className="an-data-summary an-ledger-nav-card">
<CardHeader>
<CardTitle>图层分类</CardTitle>
<Badge tone="slate">{layers.length}</Badge>
</CardHeader>
<CardContent className="an-ledger-nav-card__content">
<Scrollbar className="an-ledger-nav-scroll">
<div className="an-ledger-nav-list" role="tablist" aria-label="图层分类">
{loading && layers.length === 0 ? (
<div className="an-loading"><span className="an-spinner" />加载中</div>
) : (
layers.map((layer) => {
const isActive = layer.id === activeLayer
return (
<button
key={layer.id}
type="button"
role="tab"
aria-selected={isActive}
data-layer-id={layer.id}
className={cn('an-ledger-nav-item', isActive && 'is-active')}
onClick={() => onSelectLayer(layer.id)}
>
<span className="an-ledger-nav-item__name">{layer.name}</span>
<span className="an-ledger-nav-item__count">{layer.count.toLocaleString()}</span>
</button>
)
})
)}
</div>
</Scrollbar>
</CardContent>
</Card>
)
}
@@ -0,0 +1,139 @@
export interface LedgerKind {
id: string
label: string
}
export interface LedgerLayerSummary {
id: string
name: string
count: number
kinds: LedgerKind[]
}
export type ComputeSiteType =
| 'supercomputer'
| 'gpu_cluster'
| 'data_center'
| 'cloud_center'
| 'edge_node'
export type ComputeStatusBucket =
| 'located'
| 'needs_confirmation'
| 'terminal'
| 'pending'
export interface ComputeLedgerRow {
id: number
source: string
source_id: string
name: string
site_type: ComputeSiteType
operator: string | null
country: string | null
city: string | null
latitude: number | null
longitude: number | null
precision: string
confidence: number | null
verification_status: string
status_bucket: ComputeStatusBucket
terminal_status: string | null
is_anonymous_placeholder?: boolean
location_source: string | null
source_url: string | null
source_note: string | null
workflow_run_id: string | null
updated_at: string | null
}
export interface ComputeCandidate {
latitude: number
longitude: number
display_name: string
precision: string
confidence: number
source: string
source_note?: string | null
source_url?: string | null
city?: string | null
region?: string | null
country?: string | null
raw_payload?: Record<string, unknown>
}
export interface ComputeLedgerResponse {
items: ComputeLedgerRow[]
total: number
page: number
page_size: number
counts: {
total: number
by_site_type: Record<string, number>
by_status: Record<string, number>
}
countries: string[]
}
export interface GenericLayerColumn {
key: string
label: string
}
export interface GenericLayerItemsResponse {
layer: string
kind: string
kinds: LedgerKind[]
columns: GenericLayerColumn[]
rows: Array<Record<string, unknown>>
total: number
page: number
page_size: number
}
export const COMPUTE_SITE_TYPE_ORDER: ComputeSiteType[] = [
'supercomputer',
'gpu_cluster',
'data_center',
'cloud_center',
'edge_node',
]
export const COMPUTE_SITE_TYPE_LABELS: Record<ComputeSiteType, string> = {
supercomputer: '超算',
gpu_cluster: 'GPU 集群',
data_center: '数据中心',
cloud_center: '云计算中心',
edge_node: '边缘节点',
}
export const COMPUTE_STATUS_BUCKET_META: Record<
ComputeStatusBucket,
{ label: string; tone: 'success' | 'warning' | 'neutral' | 'info' }
> = {
located: { label: '已定位', tone: 'success' },
needs_confirmation: { label: '待确认', tone: 'warning' },
terminal: { label: '暂不可定位', tone: 'neutral' },
pending: { label: '待定位', tone: 'info' },
}
export const TERMINAL_STATUS_LABELS: Record<string, string> = {
undisclosed: '位置未公开',
multi_site: '多地分布式部署',
planned: '规划中尚未建成',
cloud_only: '纯云服务无独立站点',
anonymous: '匿名设施',
}
export const PRECISION_LABELS: Record<string, string> = {
precise: '精确',
site: '园区',
city: '城市',
unknown: '未知',
}
export const EDITABLE_PRECISION_OPTIONS = [
{ value: 'precise', label: '精确' },
{ value: 'site', label: '园区' },
{ value: 'city', label: '城市' },
]
@@ -16,6 +16,48 @@ const RAW_REDACT_SECRET_KEYS = new Set([
const DATASOURCE_CREDENTIAL_OBJECT_KEYS = new Set(['auth_config', 'auth_configured'])
export const PRODUCT_DOMAIN_LABELS: Record<string, string> = {
geo: '地理/底图',
weather: '气象',
vessels: '船舶',
cables: '海缆',
satellites: '卫星',
bgp: 'BGP',
compute: '算力',
ai: 'AI',
media: '媒体',
other: '其他',
}
const PRODUCT_DOMAIN_KEYWORDS: Array<[string, string[]]> = [
['geo', ['earth_imagery', 'sentinel2', 'viirs', 'basemap', 'imagery']],
['weather', ['cloud', 'weather', 'meteorolog', 'atmosphere', 'ir108', 'wind', 'gfs']],
['vessels', ['vessel', 'ais']],
['cables', ['cable', 'landing', 'telegeography', 'arcgis', 'fao']],
['satellites', ['tle', 'satellite', 'spacetrack', 'celestrak']],
['bgp', ['bgp', 'asn', 'prefix_geo', 'opengeofeed', 'nro']],
['compute', ['top500', 'gpu', 'supercomputer', 'compute']],
['ai', ['huggingface', 'epoch_ai']],
['media', ['news', 'tv', 'live_stream']],
]
export function resolveDatasourceProductKey(record: AnyRecord): string {
const explicit = asText(record.product, '').trim().toLowerCase()
if (explicit && PRODUCT_DOMAIN_LABELS[explicit]) return explicit
const haystack = `${asText(record.source, '')} ${asText(record.name, '')} ${asText(record.description, '')}`.toLowerCase()
for (const [product, keywords] of PRODUCT_DOMAIN_KEYWORDS) {
if (keywords.some((keyword) => haystack.includes(keyword))) {
return product
}
}
return 'other'
}
export function resolveDatasourceProductLabel(record: AnyRecord): string {
const key = resolveDatasourceProductKey(record)
return PRODUCT_DOMAIN_LABELS[key] || PRODUCT_DOMAIN_LABELS.other
}
function asRecord(value: unknown): AnyRecord {
return value && typeof value === 'object' && !Array.isArray(value) ? (value as AnyRecord) : {}
}
@@ -122,11 +164,16 @@ export function mapConfigsAllRow(row: AnyRecord): AnyRecord {
|| (kind === 'api_key' && !authConfigured.api_key)
)
const productKey = resolveDatasourceProductKey(row)
const productLabel = PRODUCT_DOMAIN_LABELS[productKey] || PRODUCT_DOMAIN_LABELS.other
return {
...row,
...credentialFields,
product: productKey,
__productLabel: productLabel,
auth_type: authType,
__module: '采集器配置',
__module: productLabel,
__status: missingCreds ? '未配置' : row.is_active ? '已配置' : '未启用',
}
}
@@ -0,0 +1,178 @@
import axios from 'axios'
export const EARTH_CLOUDS_API = '/api/v1/earth/clouds'
export const CLOUD_ANALYSIS_API = '/api/v1/data-products/clouds'
export const EARTH_CLOUD_MAP_CHANNEL = 'planet-earth-cloud-map'
export type CloudPrimarySource = 'multi_sat_ir' | 'matteason_live'
export type CloudFallbackSource = 'matteason_live' | 'static'
export type CloudResolution = '2048x1024' | '4096x2048'
export interface CloudMapConfig {
enabled: boolean
primary_source: CloudPrimarySource
fallback_source: CloudFallbackSource
resolution: CloudResolution
ir_threshold: number
contrast_gamma: number
convective_threshold: number
min_cluster_area_km2: number
polar_feather_enabled: boolean
max_history_frames: number
timelapse_enabled: boolean
show_convective_markers: boolean
default_opacity: number
request_timeout_seconds: number
geocolor_enabled: boolean
relief_shading_strength: number
optical_flow_enabled: boolean
}
export interface CloudGlobalSummary {
global_cloud_cover_pct?: number | null
global_overcast_pct?: number | null
global_convective_pct?: number | null
northern_hemisphere_pct?: number | null
southern_hemisphere_pct?: number | null
tropics_pct?: number | null
delta_pct?: number | null
convective_cluster_count?: number
min_brightness_temp_c?: number | null
}
export interface CloudRegionSummary {
key: string
name: string
name_en: string
center_lat: number
center_lon: number
cloud_cover_pct: number
overcast_coverage_pct: number
convective_coverage_pct: number
min_brightness_temp_c: number | null
delta_pct: number | null
}
export interface CloudConvectiveCluster {
cluster_id: string
latitude: number
longitude: number
area_km2: number
peak_intensity: number
min_brightness_temp_c: number | null
region: string
region_en: string
bbox: {
lon_min: number
lon_max: number
lat_max: number
lat_min: number
}
}
export interface CloudFrameMeta {
version: string
captured_at: string
source: string
satellites: string[]
degraded: boolean
resolution: string
file_size_bytes: number
image_url: string
global_summary: CloudGlobalSummary
}
export interface CloudRuntimeMeta {
enabled: boolean
mode: 'realtime' | 'fallback_static' | 'static'
degraded: boolean
source: string
satellites: string[]
captured_at: string | null
version: string | null
image_url: string
default_opacity: number
timelapse_enabled: boolean
show_convective_markers: boolean
convective_threshold: number
frames: CloudFrameMeta[]
summary: CloudGlobalSummary
regions: CloudRegionSummary[]
convective_clusters: CloudConvectiveCluster[]
storage_stats: {
file_count: number
total_bytes: number
total_mb: number
}
}
export interface CloudDatasourceSummary {
id: number
source: string
name: string
is_active: boolean
frequency_minutes: number
last_run_at: string | null
next_run_at: string | null
last_status: string | null
}
export interface CloudConfigurationEnvelope {
config: CloudMapConfig
revision: string
is_default: boolean
meta: CloudRuntimeMeta
datasource: CloudDatasourceSummary | null
}
export interface CloudSourceTestResult {
source_id: string
ok: boolean
latency_ms: number
reachable_count?: number
total_count?: number
satellites: Array<{
id: string
label?: string
ok: boolean
latency_ms?: number
error?: string
}>
}
export function notifyCloudMapChanged(detail: Record<string, unknown> = {}) {
if (typeof BroadcastChannel === 'undefined') return
try {
const channel = new BroadcastChannel(EARTH_CLOUD_MAP_CHANNEL)
channel.postMessage({ type: 'cloud_map_updated', ...detail })
channel.close()
} catch {
// Ignore environments without BroadcastChannel support.
}
}
export function describeCloudMapError(error: unknown, english: boolean): string {
if (!axios.isAxiosError(error)) {
return english ? 'Request failed.' : '请求失败。'
}
const status = error.response?.status
if (status === 409) {
return english
? 'Configuration changed by another editor. Reload before saving.'
: '配置已被其他编辑者更新。当前草稿已保留,请重新加载后再保存。'
}
if (status === 403) {
return english
? 'Administrator permissions are required for this action.'
: '仅管理员可执行该修改或清理操作。'
}
const detail = error.response?.data?.detail
if (typeof detail === 'string' && detail.trim()) return detail
if (Array.isArray(detail) && detail.length > 0) {
return detail
.map((entry: { msg?: string }) => entry.msg || '')
.filter(Boolean)
.join('; ')
}
return error.message || (english ? 'Request failed.' : '请求失败。')
}
@@ -0,0 +1,296 @@
.an-cloud-settings {
flex: 1;
min-height: 0;
min-width: 0;
width: 100%;
box-sizing: border-box;
display: flex;
flex-direction: column;
overflow: hidden;
}
.an-cloud-settings[hidden] {
display: none;
}
.an-cloud-toolbar {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 10px;
padding: 12px 16px;
border-bottom: 1px solid var(--an-border);
min-width: 0;
flex: 0 0 auto;
}
.an-cloud-toolbar__title {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 10px;
min-width: 0;
}
.an-cloud-toolbar__title h2 {
margin: 0;
font-size: 15px;
font-weight: 600;
}
.an-cloud-toolbar__actions {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
}
.an-cloud-banner {
margin: 0;
padding: 8px 16px;
font-size: 12.5px;
border-bottom: 1px solid var(--an-border);
overflow-wrap: anywhere;
flex: 0 0 auto;
}
.an-cloud-banner--error {
color: var(--an-danger);
}
.an-cloud-banner--ok {
color: var(--an-success);
}
.an-cloud-workspace {
flex: 1;
min-height: 0;
min-width: 0;
width: 100%;
display: grid;
grid-template-columns: minmax(320px, 1fr) 14px var(--an-cloud-config-width, 380px);
overflow: hidden;
}
.an-cloud-pane {
min-height: 0;
min-width: 0;
display: flex;
flex-direction: column;
overflow: hidden;
}
.an-cloud-pane--preview {
border-right: 1px solid var(--an-border);
}
.an-cloud-pane > .tui-scrollbar__viewport {
padding: 14px 16px 20px;
box-sizing: border-box;
}
.an-cloud-stage-head {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 8px;
margin-bottom: 10px;
}
.an-cloud-stage-head__meta {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 6px;
}
.an-cloud-canvas {
position: relative;
width: 100%;
aspect-ratio: 2 / 1;
border-radius: 10px;
overflow: hidden;
border: 1px solid var(--an-border);
background: radial-gradient(circle at 50% 45%, #11223a 0%, #070d18 75%, #04070e 100%);
}
.an-cloud-canvas__img {
position: relative;
z-index: 1;
width: 100%;
height: 100%;
object-fit: cover;
display: block;
}
.an-cloud-canvas__overlay {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
z-index: 2;
pointer-events: none;
}
.an-cloud-canvas__grid-line {
stroke: rgba(148, 197, 255, 0.24);
stroke-width: 0.25;
stroke-dasharray: 1 1.2;
}
.an-cloud-canvas__cluster-box {
fill: rgba(251, 146, 60, 0.14);
stroke: rgba(251, 146, 60, 0.9);
stroke-width: 0.45;
}
.an-cloud-canvas__cluster-dot {
fill: #fb923c;
}
.an-cloud-kpis {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 8px;
margin-top: 12px;
}
.an-cloud-kpi {
border: 1px solid var(--an-border);
border-radius: 8px;
padding: 8px 10px;
background: var(--an-surface-alt);
min-width: 0;
}
.an-cloud-kpi span {
display: block;
font-size: 11.5px;
color: var(--an-muted);
}
.an-cloud-kpi strong {
display: block;
margin-top: 4px;
font-size: 14px;
overflow-wrap: anywhere;
}
.an-cloud-section-title {
margin: 16px 0 8px;
font-size: 13px;
font-weight: 600;
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
}
.an-cloud-frames {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.an-cloud-frame-chip {
height: var(--an-control-xs);
padding: 0 10px;
border-radius: var(--an-control-radius);
border: 1px solid var(--an-border);
background: var(--an-surface-alt);
color: inherit;
font-size: 12px;
cursor: pointer;
}
.an-cloud-frame-chip.is-active {
border-color: var(--an-accent);
color: var(--an-accent);
font-weight: 600;
}
.an-cloud-regions {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 8px;
}
.an-cloud-region-item {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
padding: 8px 10px;
border: 1px solid var(--an-border);
border-radius: 8px;
font-size: 12px;
min-width: 0;
}
.an-cloud-region-item span {
color: var(--an-muted);
overflow-wrap: anywhere;
}
.an-cloud-links {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-top: 12px;
}
.an-cloud-form {
display: flex;
flex-direction: column;
gap: 12px;
}
.an-cloud-fields {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 10px 12px;
}
.an-cloud-field {
display: flex;
flex-direction: column;
gap: 6px;
min-width: 0;
font-size: 12.5px;
}
.an-cloud-field--full {
grid-column: 1 / -1;
}
.an-cloud-field .an-input,
.an-cloud-field .an-select {
width: 100%;
min-width: 0;
}
.an-cloud-switch-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 8px 10px;
border: 1px solid var(--an-border);
border-radius: 8px;
font-size: 12.5px;
min-width: 0;
box-sizing: border-box;
}
.an-cloud-switch-row > span {
min-width: 0;
overflow-wrap: anywhere;
}
.an-cloud-probe-box {
border: 1px solid var(--an-border);
border-radius: 8px;
padding: 10px 12px;
background: var(--an-surface-alt);
font-size: 12px;
display: flex;
flex-direction: column;
gap: 6px;
}
.an-cloud-probe-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
min-width: 0;
}
.an-cloud-danger-actions {
display: flex;
flex-wrap: wrap;
gap: 8px;
padding-top: 8px;
border-top: 1px solid var(--an-border);
}
@media (max-width: 1080px) {
.an-cloud-workspace {
grid-template-columns: minmax(0, 1fr);
grid-template-rows: auto minmax(0, 1fr);
}
.an-cloud-workspace > .an-detail-resizer {
display: none;
}
.an-cloud-pane--preview {
border-right: 0;
border-bottom: 1px solid var(--an-border);
max-height: 46%;
}
}
@media (max-width: 680px) {
.an-cloud-kpis,
.an-cloud-regions,
.an-cloud-fields {
grid-template-columns: minmax(0, 1fr);
}
}
+1 -1
View File
@@ -48,7 +48,7 @@ export const adminRoutes: AdminRouteItem[] = [
{ path: '/advisor/workflows', label: '工作流与节点', labelKey: 'admin.routes.advisorWorkflows', group: 'advisor', icon: Workflow, keywords: ['workflow', 'nodes', 'react flow', 'prompt', 'tools', '工作流', '节点', '提示词'] },
{ path: '/advisor/runs', label: '运行记录', labelKey: 'admin.routes.advisorRuns', group: 'advisor', icon: History, keywords: ['runs', 'trace', 'audit', '运行记录', '轨迹'] },
{ path: '/ai', label: 'AI', labelKey: 'admin.routes.ai', group: 'ops', icon: Bot, keywords: ['ai', 'provider', 'llm', 'web search', 'ocr', '模型', '供应商'] },
{ path: '/earth-content', label: '智能星球内容', labelKey: 'admin.routes.earthContent', group: 'ops', icon: Globe2, keywords: ['earth', '地球', '智能星球', 'tv', 'boundary', 'brand', 'news', 'rss', '新闻源'] },
{ path: '/earth-content', label: '智能星球内容', labelKey: 'admin.routes.earthContent', group: 'ops', icon: Globe2, keywords: ['earth', '地球', '智能星球', 'tv', 'boundary', 'brand', 'news', 'rss', '新闻源', 'cloud', '云图', '气象', '卫星云图', 'NASA GIBS'] },
{ path: '/collection-management', label: '采集管理', labelKey: 'admin.routes.collectionManagement', group: 'ops', icon: Database, keywords: ['collector', 'mapping', 'custom source'] },
{ path: '/logs', label: '系统日志', labelKey: 'admin.routes.logs', group: 'ops', icon: FileText, keywords: ['log', '日志', 'tail'], superAdminOnly: true },
{ path: '/users', label: '用户管理', labelKey: 'admin.routes.users', group: 'ops', icon: Users, keywords: ['users', 'role', 'gatekeeper'] },
+4
View File
@@ -74,6 +74,7 @@ const labelKeys: Record<string, string> = {
'用户': 'admin.routes.users',
'用户管理': 'admin.routes.users',
'国界精度': 'admin.sections.earthAssets',
'大气云图': 'admin.sections.earthCloudMap',
'品牌标识': 'admin.sections.earthBrand',
'通知策略': 'admin.sections.notifications',
'安全策略': 'admin.sections.security',
@@ -137,6 +138,8 @@ const sectionTargets = [
{ routePath: '/earth-content', routeLabel: '智能星球内容', icon: Globe2, sections: [
{ key: 'brand', label: '品牌标识', terms: ['logo', '标题', 'subtitle'] },
{ key: 'earth_assets', label: '国界精度', terms: ['boundary', 'PMTiles', '边界'] },
{ key: 'cloud_map', label: '大气云图', terms: ['cloud', '云图', '气象', 'GeoColor', '光流', '卫星云图', 'NASA GIBS', 'EUMETSAT', '强对流', 'GFS', '风场'] },
{ key: 'basemap', label: '底图资源', terms: ['basemap', '底图', 'Sentinel-2', 'VIIRS', 'LOD', '瓦片', '地理'] },
{ key: 'tv', label: '电视直播', terms: ['TV', '直播源', '频道'] },
{ key: 'news_sources', label: '新闻源', terms: ['news', 'rss', '商业新闻', '电商', '财经', '新闻类型'] },
] },
@@ -161,6 +164,7 @@ const fieldTargets = [
{ routePath: '/ai', routeLabel: 'AI', sectionKey: 'tools', sectionLabel: '工具调用', labels: ['搜索供应商', 'API 基础地址', 'Web Search API Key', '最大结果数', '搜索深度', 'SerpAPI 引擎', 'SearXNG 分类', 'OCR 供应商', 'OCR API Key', '测试 Web Search 连通性'] },
{ routePath: '/collection-management', routeLabel: '采集管理', sectionKey: 'collector_credentials', sectionLabel: '采集器', labels: ['凭证教程', '生成凭证教程', '采集器配置', '映射模板', '目标 Schema'] },
{ routePath: '/earth-content', routeLabel: '智能星球内容', sectionKey: 'tv', sectionLabel: '电视直播', labels: ['默认频道', '自动回退', '直播源', '频道', '主页地址'] },
{ routePath: '/earth-content', routeLabel: '智能星球内容', sectionKey: 'cloud_map', sectionLabel: '大气云图', labels: ['主数据源', '降级备用源', '输出纹理分辨率', '红外晴空截断阈值', '强对流识别阈值', '保留历史帧数', '极地视角平滑羽化', '立即采集', '测试源连通性'] },
{ routePath: '/settings', routeLabel: '系统设置', sectionKey: 'smtp', sectionLabel: 'SMTP 邮件', labels: ['主机', '端口', '用户名', '密码', '使用 TLS', '发件邮箱'] },
]
File diff suppressed because it is too large. Load diff
@@ -101,7 +101,19 @@ export function ScrollbarOverlay({
return { visible: true, dragging: dragStateRef.current?.axis === 'y', thumbSize, thumbOffset: (scrollTop / scrollRange) * maxThumbOffset }
})()
: { ...INITIAL_AXIS_STATE }
setScrollbar({ x: nextX, y: nextY })
setScrollbar((prev) => {
const sameX =
prev.x.visible === nextX.visible &&
prev.x.dragging === nextX.dragging &&
Math.abs(prev.x.thumbSize - nextX.thumbSize) < 0.5 &&
Math.abs(prev.x.thumbOffset - nextX.thumbOffset) < 0.5
const sameY =
prev.y.visible === nextY.visible &&
prev.y.dragging === nextY.dragging &&
Math.abs(prev.y.thumbSize - nextY.thumbSize) < 0.5 &&
Math.abs(prev.y.thumbOffset - nextY.thumbOffset) < 0.5
return sameX && sameY ? prev : { x: nextX, y: nextY }
})
}, [bindTarget, minThumbSize, xEnabled, yEnabled])
useEffect(() => {
@@ -148,8 +160,13 @@ export function ScrollbarOverlay({
}
attachTarget()
mutationObserver = new MutationObserver(() => {
attachTarget()
scheduleUpdate()
const currentTarget = targetRef.current
const latestTarget = targetSelector ? container.querySelector<HTMLElement>(targetSelector) : container
if (!currentTarget || !currentTarget.isConnected || currentTarget !== latestTarget) {
attachTarget()
} else {
scheduleUpdate()
}
})
mutationObserver.observe(container, { childList: true, subtree: true })
window.addEventListener('resize', scheduleUpdate)
+82 -4
View File
@@ -23,6 +23,7 @@ type LegacyTextPattern = {
}
const legacyTextPatternsEnUS: LegacyTextPattern[] = [
{ match: /^内置采集器默认配置[::]\s*(.+)$/, replace: (match) => `Built-in collector default config: ${translateLegacyAdminText(match[1], 'en-US')}` },
{ match: /^结果\s+(.+)\s+条$/, replace: (match) => `Results ${match[1]}` },
{ match: /^筛选\s+(.+)\s+项$/, replace: (match) => `${match[1]} filters` },
{ match: /^共\s+(.+)\s+条结果$/, replace: (match) => `${match[1]} results` },
@@ -30,6 +31,11 @@ const legacyTextPatternsEnUS: LegacyTextPattern[] = [
{ match: /^共\s+(.+)\s+条$/, replace: (match) => `${match[1]} items` },
{ match: /^(.+)\s+条新闻。?$/, replace: (match) => `${match[1]} news items.` },
{ match: /^(.+)\s+个历史快照,选择后查看该版本详情。?$/, replace: (match) => `${match[1]} snapshots. Select one to inspect details.` },
{ match: /^(.+)\s+个历史快照,选择后查看详情。?$/, replace: (match) => `${match[1]} snapshots. Select one to inspect details.` },
{ match: /^(.+)\s+个快照$/, replace: (match) => `${match[1]} snapshots` },
{ match: /^(.+)\s+亿条$/, replace: (match) => `${match[1]}00M items` },
{ match: /^(.+)\s+万条$/, replace: (match) => `${match[1]}0k items` },
{ match: /^已处理\s+(.+)$/, replace: (match) => `Processed ${translateLegacyAdminText(match[1], 'en-US')}` },
{ match: /^(.+)\s+字段$/, replace: (match) => `${match[1]} fields` },
{ match: /^(.+)\s+个源 \/ (.+)\s+个类型$/, replace: (match) => `${match[1]} sources / ${match[2]} categories` },
{ match: /^(.+)\s+个来源$/, replace: (match) => `${match[1]} sources` },
@@ -37,6 +43,7 @@ const legacyTextPatternsEnUS: LegacyTextPattern[] = [
{ match: /^(.+)\s+条$/, replace: (match) => `${match[1]} items` },
{ match: /^(.+)\s+行$/, replace: (match) => `${match[1]} lines` },
{ match: /^(.+)\s+次$/, replace: (match) => `${match[1]} times` },
{ match: /^来源\s+(\d+)$/, replace: (match) => `Source ${match[1]}` },
{ match: /^最后更新:\s*(.+)$/, replace: (match) => `Last updated: ${match[1]}` },
{ match: /^任务已创建:\s*(.+)$/, replace: (match) => `Task created: ${match[1]}` },
{ match: /^执行命令\s+(.+)$/, replace: (match) => `Command ${match[1]}` },
@@ -45,13 +52,83 @@ const legacyTextPatternsEnUS: LegacyTextPattern[] = [
{ match: /^Live 新闻源\s+(.+)$/, replace: (match) => `Live News source ${match[1]}` },
{ match: /^新闻直播源\s+(.+)$/, replace: (match) => `Live News source ${match[1]}` },
{ match: /^新增新闻源\s+(.+)$/, replace: (match) => `New news source ${match[1]}` },
{ match: /^最终指标:(.+)$/, replace: (match) => `Final metric: ${match[1]}` },
{ match: /^最终结果:(.+)$/, replace: (match) => `Final metric: ${match[1]}` },
{ match: /^最终指标:(.+)$/, replace: (match) => `Final metric: ${translateLegacyAdminText(match[1], 'en-US')}` },
{ match: /^最终结果:(.+)$/, replace: (match) => `Final metric: ${translateLegacyAdminText(match[1], 'en-US')}` },
{ match: /^指纹\s+(.+)$/, replace: (match) => `Fingerprint ${match[1]}` },
{ match: /^首次\s+(.+)\s+·\s+最近\s+(.+)$/, replace: (match) => `First ${match[1]} · Latest ${match[2]}` },
{ match: /^已导出\s+(.+)$/, replace: (match) => `Exported ${match[1]}` },
{ match: /^(已定位|待确认|暂不可定位|待定位)\s*\((.+)\)$/, replace: (match) => `${translateLegacyAdminText(match[1], 'en-US')} (${match[2]})` },
{ match: /^暂不可定位\s*·\s*(.+)$/, replace: (match) => `Unlocatable · ${translateLegacyAdminText(match[1], 'en-US')}` },
{ match: /^(.+?)台账$/, replace: (match) => `${translateLegacyAdminText(match[1].trim(), 'en-US')} Ledger` },
{ match: /^加载(.+)台账失败$/, replace: (match) => `Failed to load ${translateLegacyAdminText(match[1], 'en-US')} ledger` },
{ match: /^(.+)子分类$/, replace: (match) => `${translateLegacyAdminText(match[1], 'en-US')} sub-categories` },
{ match: /^查看工作流运行记录\s*\((.+)\)$/, replace: (match) => `View workflow run (${match[1]})` },
{ match: /^新采集候选位置\s*\((.+)\)$/, replace: (match) => `Collected candidates (${match[1]})` },
{ match: /^编辑坐标:(.+)$/, replace: (match) => `Edit coordinates: ${match[1]}` },
{ match: /^(.+)\s+定位详情$/, replace: (match) => `${match[1]} Location Details` },
{ match: /^重新定位\s+(.+)$/, replace: (match) => `Relocate ${match[1]}` },
{ match: /^源数据为匿名占位条目,无可检索线索\s+(.+)$/, replace: (match) => `Anonymous placeholder record with no searchable clues (${match[1]})` },
{ match: /^已采纳候选坐标$/, replace: () => 'Candidate location adopted' },
{ match: /^已停止批量定位(已完成\s+(\d+)\s*\/\s*(\d+)\s*条)$/, replace: (match) => `Batch locate stopped (${match[1]} / ${match[2]} completed)` },
{ match: /^批量定位完成:候选\s+(\d+)\s*条,暂不可定位\s+(\d+)\s*条,未命中\s+(\d+)\s*条(?:,失败\s+(\d+)\s*条)?$/, replace: (match) => `Batch locate finished: ${match[1]} candidate(s), ${match[2]} terminal, ${match[3]} missed${match[4] ? `, ${match[4]} failed` : ''}` },
{ match: /^编辑坐标\s+(.+)$/, replace: (match) => `Edit coordinates ${match[1]}` },
{ match: /^当前\s*·\s*(.+)$/, replace: (match) => `Current · ${translateLegacyAdminText(match[1], 'en-US')}` },
{ match: /^(.+)\s*·\s*默认$/, replace: (match) => `${translateLegacyAdminText(match[1], 'en-US')} · Default` },
{ match: /^(.+)\s*·\s*年末里程碑\s*\((.+)\)$/, replace: (match) => `${translateLegacyAdminText(match[1], 'en-US')} · Year-end milestone (${match[2]})` },
{ match: /^部分开启\s*\((.+)\)$/, replace: (match) => `Partial (${match[1]})` },
{ match: /^全部单份\s*\((.+)\)$/, replace: (match) => `All single-copy (${match[1]})` },
{ match: /^全部历史\s*\((.+)\)$/, replace: (match) => `All history (${match[1]})` },
{ match: /^默认([^(·]+?)(?:(全局单份已锁定))?\s*·\s*保留\s+(\d+)\s+天\s*·\s*(自动清理已开|自动清理已关(保留存量))$/, replace: (match) => {
const mode = translateLegacyAdminText(match[1].trim(), 'en-US')
const locked = match[0].includes('(全局单份已锁定)') ? ' (global single-copy locked)' : ''
const prune = match[3] === '自动清理已开' ? 'Auto prune on' : 'Auto prune off (keep existing)'
return `Default ${mode}${locked} · Retain ${match[2]} days · ${prune}`
} },
{ match: /^(采集|删除|清缓存|刷新|任务)排队中$/, replace: (match) => `${translateLegacyAdminText(match[1], 'en-US')} queued` },
{ match: /^(采集|删除|清缓存|刷新|任务)中$/, replace: (match) => `${translateLegacyAdminText(match[1], 'en-US')} in progress` },
{ match: /^(采集|删除|清缓存|刷新|任务)成功$/, replace: (match) => `${translateLegacyAdminText(match[1], 'en-US')} succeeded` },
{ match: /^(采集|删除|清缓存|刷新|任务)失败$/, replace: (match) => `${translateLegacyAdminText(match[1], 'en-US')} failed` },
{ match: /^(采集|删除|清缓存|刷新|任务)已取消$/, replace: (match) => `${translateLegacyAdminText(match[1], 'en-US')} cancelled` },
{ match: /^(采集|删除|清缓存|刷新|任务)已停止$/, replace: (match) => `${translateLegacyAdminText(match[1], 'en-US')} stopped` },
{ match: /^停止(采集|删除|清缓存|刷新|任务)中$/, replace: (match) => `Stopping ${translateLegacyAdminText(match[1], 'en-US').toLowerCase()}` },
{ match: /^正在停止(采集|删除|清缓存|刷新|任务)$/, replace: (match) => `Stopping ${translateLegacyAdminText(match[1], 'en-US').toLowerCase()}` },
{ match: /^停止(采集|删除|清缓存|刷新|任务)$/, replace: (match) => `Stop ${translateLegacyAdminText(match[1], 'en-US').toLowerCase()}` },
{ match: /^暂无\s*(.+?)\s*任务$/, replace: (match) => `No ${translateLegacyAdminText(match[1], 'en-US').toLowerCase()} tasks` },
{ match: /^(.+)\s+凭证教程$/, replace: (match) => `${match[1]} Credential Guide` },
{ match: /^(.+)\s+预览$/, replace: (match) => `${translateLegacyAdminText(match[1], 'en-US')} preview` },
{ match: /^(.+)\s+快照$/, replace: (match) => `${match[1]} snapshot` },
{ match: /^Source ID "(.+)" 已存在。$/, replace: (match) => `Source ID "${match[1]}" already exists.` },
{ match: /^新闻源 ID "(.+)" 已存在。$/, replace: (match) => `News source ID "${match[1]}" already exists.` },
{ match: /^停用\s+(.+)\s+个数据源的定时调度,运行中的任务不受影响。$/, replace: (match) => `Disable scheduled sync for ${match[1]} datasources. Running tasks are unaffected.` },
{ match: /^跳过\s+(.+)(未到采集间隔或任务运行中)$/, replace: (match) => `Skipped ${match[1]} (within interval or already running)` },
{ match: /^(进行|完成|失败|跳过)\s+(\d+)$/, replace: (match) => {
const labelMap: Record<string, string> = { 进行: 'Running', 完成: 'Completed', 失败: 'Failed', 跳过: 'Skipped' }
return `${labelMap[match[1]] || match[1]} ${match[2]}`
} },
{ match: /^(.+)\s+个已提交,(.+)\s+个提交失败。$/, replace: (match) => `${match[1]} submitted, ${match[2]} failed.` },
{ match: /^(.+)\s+个任务正在停止。$/, replace: (match) => `${match[1]} tasks stopping.` },
{ match: /^任务\s+(.+)\s+会异步删除采集记录并刷新智能星球。$/, replace: (match) => `Task ${match[1]} will asynchronously delete collected records and refresh Intelligent Planet.` },
{ match: /^任务\s+(.+)\s+会异步清理缓存并刷新智能星球。$/, replace: (match) => `Task ${match[1]} will asynchronously clear cache and refresh Intelligent Planet.` },
{ match: /^当前阶段:(.+)。确认后会强制取消当前采集,并重新开始采集。$/, replace: (match) => `Current phase: ${translateLegacyAdminText(match[1], 'en-US')}. Confirming will force-cancel the active collection and restart it.` },
{ match: /^(.+)\s+当前阶段:(.+)。$/, replace: (match) => `${translateLegacyAdminText(match[1], 'en-US')} Current phase: ${translateLegacyAdminText(match[2], 'en-US')}.` },
{ match: /^仅支持\s+(.+)。$/, replace: (match) => `Only ${match[1]} files are supported.` },
{ match: /^新增\s+(.+)\s+条,更新\s+(.+)\s+条,失败\s+(.+)\s+条。$/, replace: (match) => `Created ${match[1]}, updated ${match[2]}, failed ${match[3]}.` },
{ match: /^(.+)\s+返回\s+(.+)\s+条内容。$/, replace: (match) => `${translateLegacyAdminText(match[1], 'en-US')} returned ${match[2]} items.` },
{ match: /^确认将\s+(.+)\s+重置为默认内容?$/, replace: (match) => `Reset ${translateLegacyAdminText(match[1], 'en-US')} to default content?` },
{ match: /^确认将\s+(.+)\s+凭证教程恢复默认?$/, replace: (match) => `Reset credential guide for ${match[1]} to default?` },
{ match: /^确认清理\s+(.+)\s+的智能星球展示缓存?这不会删除数据库里的采集数据。$/, replace: (match) => `Clear Intelligent Planet display cache for ${translateLegacyAdminText(match[1], 'en-US')}? Collected database records will not be deleted.` },
{ match: /^确认删除\s+(.+)\s+的已采集数据库记录?这不会清理智能星球展示缓存,此操作不可恢复。$/, replace: (match) => `Delete collected database records for ${translateLegacyAdminText(match[1], 'en-US')}? Display cache will not be cleared. This cannot be undone.` },
{ match: /^数据源任务\s+(.+)%,进行\s+(.+),完成\s+(.+),失败\s+(.+),跳过\s+(.+)$/, replace: (match) => `Datasource jobs ${match[1]}%: ${match[2]} running, ${match[3]} done, ${match[4]} failed, ${match[5]} skipped` },
{ match: /^开启后将按保留周期(历史快照与日志\s+(.+)\s+天、BGP 原始观测 7 天)自动清理过期历史记录,同时永久保留最新数据与年度算力里程碑。$/, replace: (match) => `When enabled, expired history is pruned automatically by retention window (snapshots & logs ${match[1]} days, raw BGP observations 7 days) while keeping latest data and annual compute milestones.` },
{ match: /^高体积提醒(预计增量\s+(.+?)):(.+)$/, replace: (match) => `High volume warning (est. ${match[1]}): ${match[2]}` },
{ match: /^(.+)\s+采集失败$/, replace: (match) => `${match[1]} collection failed` },
{ match: /^(.+)\s+采集已取消$/, replace: (match) => `${match[1]} collection cancelled` },
{ match: /^隐藏(.+)$/, replace: (match) => `Hide ${translateLegacyAdminText(match[1], 'en-US')}` },
{ match: /^显示(.+)$/, replace: (match) => `Show ${translateLegacyAdminText(match[1], 'en-US')}` },
{ match: /^保存(.+)$/, replace: (match) => `Save ${translateLegacyAdminText(match[1], 'en-US')}` },
{ match: /^(.+)已完成$/, replace: (match) => `${translateLegacyAdminText(match[1], 'en-US')} completed` },
{ match: /^(.+)请求已提交$/, replace: (match) => `${translateLegacyAdminText(match[1], 'en-US')} request submitted` },
{ match: /^(.+)失败$/, replace: (match) => `${translateLegacyAdminText(match[1], 'en-US')} failed` },
{ match: /^选择(.+)$/, replace: (match) => `Select ${translateLegacyAdminText(match[1], 'en-US')}` },
]
@@ -63,7 +140,7 @@ function preserveOuterWhitespace(source: string, replacement: string) {
function translatePatternText(value: string) {
const text = value.trim()
if (!text || text.length > 160) return value
if (!text || text.length > 180) return value
for (const pattern of legacyTextPatternsEnUS) {
const matched = text.match(pattern.match)
if (matched) return preserveOuterWhitespace(value, pattern.replace(matched))
@@ -84,7 +161,8 @@ export function translateLegacyAdminText(value: string, locale: SupportedLocale)
.filter(([source]) => source.length >= 3 && cjkPattern.test(source) && text.includes(source))
.sort(([left], [right]) => right.length - left.length)
if (!entries.length) return value
return entries.reduce((next, [source, target]) => next.split(source).join(target), value)
const rewritten = entries.reduce((next, [source, target]) => next.split(source).join(target), value)
return cjkPattern.test(rewritten) ? value : rewritten
}
function resolveAttrSource(element: Element, attributeName: string, currentValue: string) {
+423
View File
@@ -145,9 +145,17 @@ export const legacyUiTextEnUS: Record<string, string> = {
'告警统计': 'Alert stats',
'名称': 'Name',
'认证方式': 'Auth method',
'认证配置': 'Auth config',
'认证状态': 'Auth status',
'后台账号': 'Console account',
'回到首页': 'Back to overview',
'国界精度': 'Boundary accuracy',
'大气云图': 'Atmosphere cloud map',
'全球卫星红外云图': 'Global Satellite IR Cloud Map',
'高清云图瓦片金字塔': 'HD Satellite Cloud Tiles',
'Sentinel-2 无云高分底图': 'Sentinel-2 Cloudless 2024 Imagery',
'NASA 每日真彩色卫星底图': 'NASA GIBS Daily TrueColor Imagery',
'全球 10m 风场 (NOAA GFS)': 'NOAA GFS Global 10m Wind Field',
'国家': 'Country',
'地址': 'Address',
'基础字段': 'Basic fields',
@@ -336,6 +344,8 @@ export const legacyUiTextEnUS: Record<string, string> = {
'活跃数据源': 'Active datasources',
'海底光缆': 'Submarine cable',
'海缆': 'Cable',
'气象': 'Weather',
'地理/底图': 'Geo / Basemap',
'海缆登陆关系': 'Cable landing relation',
'海缆系统': 'Cable system',
'后端已停止响应,正在等待服务恢复。': 'Backend stopped responding. Waiting for service recovery.',
@@ -596,6 +606,9 @@ export const legacyUiTextEnUS: Record<string, string> = {
'最大输出 Tokens': 'Max output tokens',
'超时(秒)': 'Timeout (seconds)',
'拖动调整详情宽度': 'Drag to resize details',
'拖动调整列表宽度': 'Drag to resize list width',
'拖动调整日志源列表宽度': 'Drag to resize log source list width',
'拖动调整配置区宽度': 'Drag to resize settings width',
'异常': 'Anomaly',
'播放类型': 'Playback type',
'上次状态': 'Last status',
@@ -972,4 +985,414 @@ export const legacyUiTextEnUS: Record<string, string> = {
'AI 参谋': 'AI Advisor',
'AI 参谋 Playground': 'AI Advisor Playground',
'管理模型供应商、Web Search、OCR 等 AI 配置;Playground 与工作流节点在 AI 参谋中管理。': 'Manage model providers, Web Search, OCR, and AI settings; Playground and workflows live in AI Advisor.',
// Collector, schema & integration field labels / help
'眉标': 'Eyebrow',
'默认提供方': 'Default provider',
'创建时间': 'Created at',
'发布时间': 'Published at',
'摘要': 'Summary',
'正文': 'Content',
'位置标签': 'Location label',
'处理状态': 'Enrichment status',
'已翻译': 'Translated',
'产品': 'Product',
'频率': 'Frequency',
'下次执行': 'Next run',
'上次错误': 'Last error',
'凭证状态': 'Credential status',
'默认地址': 'Default URL',
'请求头': 'Headers',
'配置参数': 'Configuration',
'采样 Payload': 'Sample payload',
'映射 JSON': 'Mapping JSON',
'采样 Hash': 'Sample hash',
'校验状态': 'Validation status',
'覆盖内置配置': 'Override built-in config',
'配置 ID': 'Config ID',
'API Key 名称': 'API Key name',
'API Key 位置': 'API Key location',
'服务地址': 'Service URL',
'服务令牌': 'Service token',
'接口协议': 'Provider API',
'基础地址': 'Base URL',
'模型列表': 'Models',
'搜索引擎': 'Search engine',
'搜索引擎列表': 'Search engines',
'搜索路径': 'Search path',
'抓取路径': 'Scrape path',
'抓取格式': 'Scrape formats',
'输出格式': 'Output format',
'使用 SSL': 'Use SSL',
'信息条目': 'Meta items',
'出品信息': 'Credits',
'链接': 'Links',
'模型 / Engine': 'Model / Engine',
'识别语言': 'Recognition languages',
// Built-in datasource display names
'TOP500 超算榜单': 'TOP500 Supercomputers',
'Epoch AI GPU 集群': 'Epoch AI GPU Clusters',
'Hugging Face 模型': 'Hugging Face Models',
'Hugging Face 数据集': 'Hugging Face Datasets',
'PeeringDB 交换中心': 'PeeringDB IXPs',
'PeeringDB 网络': 'PeeringDB Networks',
'PeeringDB 设施': 'PeeringDB Facilities',
'光缆登陆点': 'Landing Points',
'光缆系统': 'Cable Systems',
'ArcGIS 海底光缆': 'ArcGIS Subsea Cables',
'ArcGIS 登陆点': 'ArcGIS Landing Points',
'ArcGIS 光缆登陆关系': 'ArcGIS Cable-Landing Links',
'FAO 登陆点': 'FAO Landing Points',
'Space-Track 轨道根数': 'Space-Track TLEs',
'CelesTrak 轨道根数': 'CelesTrak TLEs',
'RIPE RIS 实时 BGP': 'RIPE RIS Live BGP',
'CAIDA BGPStream 回填': 'CAIDA BGPStream Backfill',
'IPtoASN 前缀地理': 'IPtoASN Prefix Geo',
'OpenGeoFeed 前缀地理': 'OpenGeoFeed Prefix Geo',
'NRO 分配前缀地理': 'NRO Delegated Prefix Geo',
'BarentsWatch AIS 船舶': 'BarentsWatch AIS Vessels',
'AISStream 实时船舶': 'AISStream Live Vessels',
'媒体新闻归档': 'Media News Archive',
// Dashboard restart & status copy
'重启后端服务,页面会短暂断开后自动恢复。': 'Restart the backend service. The page will reconnect automatically.',
'重启前端服务,恢复后将自动刷新页面。': 'Restart the frontend service. The page will reload automatically once ready.',
'重启 AI 适配服务。': 'Restart the AI Provider adapter service.',
'重启 PostgreSQL 和 Redis 容器。': 'Restart the PostgreSQL and Redis containers.',
'重启前后端及相关服务,恢复后将自动刷新页面。': 'Restart frontend, backend, and related services. The page will reload automatically once ready.',
'恢复超时,请手动检查服务状态': 'Recovery timed out. Check service status manually.',
// Collection, queue, snapshot, settings & credential guide copy
'记录': 'Record',
'采集': 'Collection',
'清缓存': 'Clear cache',
'清缓存中': 'Clearing cache',
'刷新中': 'Refreshing',
'正在删除数据': 'Deleting data',
'正在清理缓存': 'Clearing cache',
'正在刷新图层': 'Refreshing layers',
'正在采集': 'Collecting',
'正在取消删除': 'Cancelling deletion',
'正在停止采集': 'Stopping collection',
'正在取消任务': 'Cancelling task',
'清缓存完成': 'Cache cleared',
'刷新完成': 'Refresh completed',
'清缓存失败': 'Failed to clear cache',
'刷新失败': 'Refresh failed',
'当前': 'Current',
'未到采集间隔': 'Within collection interval',
'触发失败': 'Trigger failed',
'系统事件': 'System events',
'进行中': 'Running',
'同自然年内原地增量更新;跨年首次采集自动固化上一年末里程碑快照,支撑算力跨年对比。': 'Updates in place within the same calendar year; the first collection in a new year freezes a prior year-end milestone snapshot for cross-year compute comparison.',
'每次采集均保留历史版本与时间胶囊对比,超期非当前快照受自动清理与保留天数约束。': 'Keeps historical snapshots for time-capsule comparison. Expired non-current snapshots follow auto-prune and retention days.',
'仅保留最新 1 份数据,按实体差异原地增量更新,未变化记录零写入,极省硬盘容量。': 'Keeps only the latest copy and updates changed entities in place with zero writes for unchanged rows.',
'手动添加': 'Manual',
'新增采集器': 'New collector',
'当前频道仅支持外部打开': 'Current channel only supports external link',
'暂无可播放直播源': 'No playable stream sources',
'暂无可用频道': 'No available channels',
'刷新直播源': 'Refresh stream sources',
'支持后台配置默认源与采集器补充源。': 'Supports backend default sources and collector-supplemented sources.',
'当前频道仅支持跳转官网或外部播放器打开。': 'This channel can only be opened on its website or in an external player.',
'暂无可播放直播源,请先在系统配置中添加频道。': 'No playable stream sources. Add channels in System Settings first.',
'新闻直播': 'Live News',
'等待任务创建': 'Waiting for task creation',
'请查看任务状态详情。': 'Check the task status details.',
'后端已接受本次变更。': 'Backend accepted the change.',
'没有可测试的新闻源': 'No testable news sources',
'当前新闻源配置里没有 sources。': 'No sources found in the current news source configuration.',
'新闻源测试通过': 'News source test passed',
'该来源暂不可按 RSS/Atom 抓取。': 'This source cannot be fetched via RSS/Atom.',
'当前来源只作为官网、报告页或未来采集器线索保留,不会执行 RSS/Atom 测试。': 'Kept as an official homepage, report page, or future collector lead; RSS/Atom testing is skipped.',
'没有可停止的任务': 'No stoppable tasks',
'当前活跃任务缺少后端任务编号或已经结束。': 'The active task has no backend task ID or has already finished.',
'数据源任务': 'Datasource jobs',
'查看数据源': 'View datasource',
'后端任务仍在运行': 'Backend task still running',
'正在删除数据库数据': 'Deleting database records',
'删除可能需要一点时间,当前页面仍可继续操作。': 'Deletion may take a moment; you can keep using this page.',
'删除任务已提交': 'Delete task submitted',
'数据库清理已入队': 'Database cleanup queued',
'清理数据库数据失败': 'Failed to clear database records',
'正在清理展示缓存': 'Clearing display cache',
'缓存清理已在后台执行。': 'Cache cleanup is running in the background.',
'缓存清理任务已提交': 'Cache cleanup task submitted',
'展示缓存清理已入队': 'Display cache cleanup queued',
'清理展示缓存失败': 'Failed to clear display cache',
'当前任务未完成': 'Current task not finished',
'强制重新采集': 'Force re-collect',
'当前采集任务仍在运行。': 'Collection task is still running.',
'任务已提交': 'Task submitted',
'文件类型不支持': 'Unsupported file type',
'上传接口未返回资产 URL': 'Upload API did not return an asset URL',
'品牌资产上传': 'Brand asset upload',
'品牌资产上传结果': 'Brand asset upload result',
'标题图片': 'Title image',
'已上传': 'Uploaded',
'品牌资产上传失败': 'Failed to upload brand asset',
'新建新闻组': 'New news group',
'新闻组已创建': 'News group created',
'创建新闻组失败': 'Failed to create news group',
'请选择 JSON 文件': 'Select a JSON file',
'请选择新闻组': 'Select a news group',
'JSON 导入需要在手动新闻组详情页中执行。': 'JSON import must be run inside a manual news group detail page.',
'新闻导入完成': 'News import completed',
'导入新闻失败': 'Failed to import news',
'保存 TV 配置': 'Save TV configuration',
'保存新闻源配置': 'Save news source configuration',
'保存采集器配置': 'Save collector configuration',
'保存品牌配置': 'Save brand configuration',
'保存边界配置': 'Save boundary configuration',
'保存 Prompt': 'Save prompt',
'保存 AI 集成配置': 'Save AI integration configuration',
'只读记录': 'Read-only record',
'该实体只提供只读详情。': 'This entity provides read-only details.',
'已复制详情': 'Details copied',
'当前记录 JSON 已写入剪贴板。': 'Current record JSON copied to clipboard.',
'日志快照': 'Log snapshot',
'日志快照已读取': 'Log snapshot loaded',
'已拉取最近 200 行日志。': 'Fetched the latest 200 log lines.',
'读取日志失败': 'Failed to load logs',
'详情已刷新': 'Details refreshed',
'详情加载失败': 'Failed to load details',
'任务状态已刷新': 'Task status refreshed',
'任务状态加载失败': 'Failed to load task status',
'运行状态已刷新': 'Runtime status refreshed',
'运行状态加载失败': 'Failed to load runtime status',
'请先保存自定义数据源配置': 'Save custom datasource config first',
'内置采集器或未保存草稿不支持自定义映射采样。': 'Built-in collectors or unsaved drafts do not support custom mapping sampling.',
'采样数据已读取': 'Sample payload loaded',
'采样失败': 'Sampling failed',
'保存映射': 'Save mapping',
'缺少预览参数': 'Missing preview parameters',
'需要采样 Payload、映射 JSON 和目标 Schema。': 'Sample payload, mapping JSON, and target schema are required.',
'映射预览已生成': 'Mapping preview generated',
'映射预览失败': 'Mapping preview failed',
'当前采集器': 'Current collector',
'暂无凭证教程': 'No credential guide',
'未生成新教程': 'No new guide generated',
'教程已生成': 'Guide generated',
'教程已重置': 'Guide reset',
'智能星球图层缓存': 'Intelligent Planet layer cache',
'缓存': 'Cache',
'缓存状态已读取': 'Cache status loaded',
'缓存状态读取失败': 'Failed to load cache status',
'未配置密钥': 'Key not configured',
'当前项没有落库密钥,也没有匹配当前 provider 的 fallback。': 'No stored key or matching provider fallback for this entry.',
'读取密钥失败': 'Failed to load key',
'保存模型供应商': 'Save model provider',
'保存 Web Search': 'Save Web Search',
'保存 OCR': 'Save OCR',
'已恢复默认配置': 'Defaults restored',
'当前表单已回到默认值,保存后生效。': 'Form restored to defaults. Save to apply.',
'设为默认模型供应商': 'Set as default model provider',
'设为默认 Web Search': 'Set as default Web Search',
'停用 OCR': 'Disable OCR',
'新闻内容不完整': 'Incomplete news item',
'新增新闻内容': 'Add news item',
'保存新闻内容': 'Save news item',
'新闻已重新进入清洗、翻译和定位队列。': 'News item re-queued for cleaning, translation, and geolocation.',
'该 RSS 来源暂无入库新闻。': 'No ingested news items for this RSS source yet.',
'保存采集器设置': 'Save collector settings',
'保存关于配置': 'Save About settings',
'保存新闻源': 'Save news source',
'RSS 来源只读': 'RSS source is read-only',
'RSS 来源组不能在这里重命名或编辑。': 'RSS source groups cannot be renamed or edited here.',
'保存新闻组': 'Save news group',
'创建采集器配置': 'Create collector config',
'请补齐 Schema 映射参数': 'Complete schema mapping fields',
'需要采集器配置 ID、目标 Schema 和映射 JSON。': 'Collector config ID, target schema, and mapping JSON are required.',
'创建 Schema 映射': 'Create schema mapping',
'保存映射模板': 'Save mapping template',
'保存采集调度': 'Save collection schedule',
'启用映射模板': 'Enable mapping template',
'开启全部历史快照后,IP 前缀库(iptoasn / nro)与实时船舶 AIS 数据源将继续写入完整历史快照(估算约 66 GB/月),仅建议在需要全量审计时使用。': 'Enabling full historical snapshots keeps writing complete history for IP prefix tables (iptoasn / nro) and live vessel AIS (~66 GB/month). Use only when full audit history is required.',
'确认恢复默认智能星球品牌配置?当前自定义配置会被清空。': 'Reset Intelligent Planet brand settings to defaults? Current custom values will be cleared.',
'确认删除智能星球品牌配置?': 'Delete Intelligent Planet brand settings?',
'确认恢复智能星球关于卡片的默认内容?': 'Reset Intelligent Planet About card to default content?',
'恢复': 'Restore',
'边界构建任务已提交,当前表单未保存。': 'Boundary build job submitted; current form changes were not saved.',
'设为默认频道': 'Set as default channel',
'设置默认 TV 频道': 'Set default TV channel',
'请输入测试收件人': 'Enter a test recipient',
'暂无可用快照': 'No snapshots available',
'已开启全局全部单份锁定,需切换为默认推荐后方可单独开启历史': 'Global single-copy lock is active. Switch to Recommended Default before enabling per-source history.',
'已开启全局全部单份锁定,请先切换为默认推荐或全部历史': 'Global single-copy lock is active. Switch to Recommended Default or All History first.',
'停止实时源': 'Stop live source',
'实时源操作已提交,不会保存当前表单。': 'Live source action submitted; current form changes were not saved.',
'重启请求已提交,不会保存当前表单。': 'Restart request submitted; current form changes were not saved.',
'采集任务已提交,当前配置未保存。': 'Collection job submitted; current unsaved config was not saved.',
'停止请求已提交,当前配置未保存。': 'Stop request submitted; current unsaved config was not saved.',
'删除采集配置': 'Delete collector config',
'重置 Prompt': 'Reset prompt',
'边界构建任务已提交,当前配置未保存。': 'Boundary build job submitted; current unsaved config was not saved.',
'确认恢复内置默认来源、Feed 子项、源属性标签和策略?当前自定义配置会被清空。': 'Restore built-in default sources, feeds, source tags, and policies? Current custom configuration will be cleared.',
'确认恢复内置默认来源、Feed 子项、源属性标签和策略?': 'Restore built-in default sources, feeds, source tags, and policies?',
'确认清理智能星球图层缓存?清理后下次访问会重新生成。': 'Clear Intelligent Planet layer cache? It will be regenerated on next visit.',
'清理': 'Clear',
'缓存清理请求已提交,不会保存当前页面配置。': 'Cache cleanup request submitted; current unsaved page changes were not saved.',
'关闭日志快照': 'Close log snapshot',
'复制原始数据': 'Copy raw data',
'重置凭证教程': 'Reset credential guide',
'搜索证据': 'Search evidence',
'正在生成凭证教程': 'Generating credential guide',
'正在重置凭证教程': 'Resetting credential guide',
'正在读取凭证教程': 'Loading credential guide',
'正在搜索证据并调用 AI,请稍等。': 'Searching evidence and invoking AI, please wait.',
'正在同步后端状态。': 'Syncing backend status.',
'供应商运行状态': 'Provider runtime status',
'工具配置': 'Tool settings',
'默认配置': 'Default configuration',
'查看日志源、读取快照并复制原始日志。': 'Inspect log sources, fetch snapshots, and copy raw logs.',
'先选择日志源,再读取对应日志快照。': 'Select a log source to load its log snapshot.',
'系统通道': 'System',
'批量测连': 'Test all connections',
'返回总览': 'Back to overview',
'前往凭证配置': 'Manage credentials',
'重试采集': 'Retry collection',
'测连': 'Test connection',
'缺凭证': 'Missing credentials',
'已连通': 'Connected',
'未验证': 'Unverified',
'免凭证': 'No credentials',
'偏旧': 'Stale',
'健康': 'Healthy',
'认证': 'Auth',
'凭证': 'Credentials',
'耗时': 'Duration',
'级别': 'Severity',
'全部': 'All',
'无活跃告警': 'No active alerts',
'模型通道': 'Model channel',
'实时总线': 'Realtime bus',
'数据与接口': 'Storage & API',
'连通测试完成': 'Connection test complete',
'已提交采集任务': 'Collection task queued',
'确认解决告警': 'Resolve alert',
'已确认': 'Acknowledged',
'已解决': 'Resolved',
'搜索名称或模块': 'Search name or module',
'搜索采集器或端点': 'Search collector or endpoint',
'数据接口': 'API service',
'活跃': 'Active',
'类型': 'Type',
'时间': 'Time',
'解决': 'Resolve',
'测试连接': 'Test connection',
'显示更多': 'Show more',
'按地球图层分类复核基础设施、台账与原始采集元数据。': 'Review infrastructure, layer ledgers, and raw collected metadata by Earth layer.',
'拖动调整图层导航宽度': 'Drag to resize layer navigation width',
'图层分类': 'Layer Categories',
'原始采集记录': 'Raw Collected Records',
'新闻与直播': 'News & Live Streams',
'船只': 'Vessels',
'算力中心台账': 'Compute Center Ledger',
'设施类型': 'Facility type',
'数据中心': 'Data center',
'云计算中心': 'Cloud center',
'边缘节点': 'Edge node',
'运营方': 'Operator',
'坐标': 'Coordinates',
'精度': 'Precision',
'定位状态': 'Location status',
'核验状态': 'Verification status',
'全部定位状态': 'All location statuses',
'待确认': 'Needs confirmation',
'暂不可定位': 'Unlocatable',
'位置未公开': 'Location undisclosed',
'多地分布式部署': 'Multi-site distributed deployment',
'规划中尚未建成': 'Planned / not yet built',
'纯云服务无独立站点': 'Cloud-only / no dedicated site',
'匿名设施': 'Anonymous facility',
'精确': 'Precise',
'园区': 'Site',
'重新定位': 'Relocate',
'源数据为匿名占位条目,无可检索线索': 'Anonymous placeholder record with no searchable clues',
'正在重新定位...': 'Relocating...',
'编辑坐标': 'Edit coordinates',
'采纳': 'Adopt',
'保存坐标': 'Save coordinates',
'算力中心详情': 'Compute Center Details',
'核验依据与定位属性': 'Verification Evidence & Attributes',
'来源标识': 'Source Identifier',
'国家 / 城市': 'Country / City',
'定位来源': 'Location source',
'依据说明': 'Reasoning Note',
'暂无补充说明': 'No additional notes.',
'搜索名称、运营方、城市、说明': 'Search name, operator, city, or note',
'搜索名称、标识或来源': 'Search name, identifier, or source',
'加载算力中心台账失败': 'Failed to load compute center ledger',
'重新定位失败': 'Relocation failed',
'请输入有效的非零经纬度坐标': 'Please enter valid non-zero latitude and longitude coordinates',
'坐标已保存': 'Coordinates saved',
'保存坐标失败': 'Failed to save coordinates',
'已采纳候选坐标': 'Candidate location adopted',
'采纳候选失败': 'Failed to adopt candidate',
'未找到可用候选坐标': 'No usable candidate coordinates found',
'点击行可查看并采纳候选位置': 'Click a row to inspect and adopt candidates',
'如 35.7804': 'e.g. 35.7804',
'如 -78.6391': 'e.g. -78.6391',
'城市名称': 'City name',
'国家或地区': 'Country or region',
'NORAD / 原始 ID': 'NORAD / Source ID',
'清空搜索': 'Clear search',
'批量定位': 'Batch locate',
'定位中': 'Locating',
'国际编号': 'COSPAR ID',
'星座分组': 'Constellation',
'轨道倾角': 'Inclination',
'历元时间': 'Epoch',
'归属国家/组织': 'Country / Organization',
'国家/地区': 'Country / Region',
'频道名称': 'Channel name',
'观测时间': 'Observed at',
'瓦片数据集': 'Tile dataset',
'Live 直播源': 'Live streams',
'气象图层': 'Weather layer',
'云图记录': 'Cloud map records',
'风场记录': 'Wind field records',
'观测站': 'Collectors',
'观测站 ID': 'Collector ID',
'运营机构': 'Operator organization',
'事件标题': 'Incident title',
'事件类型': 'Incident type',
'开始时间': 'Started at',
'船名': 'Vessel name',
'船型': 'Vessel type',
'船旗': 'Flag',
'航速': 'Speed',
'新闻标题': 'Headline',
'地理落点': 'Resolved location',
'数据资产': 'Data Assets',
'运行态势': 'Runtime Insights',
'数据源与采集器': 'Sources & Collectors',
'告警与系统通道': 'Alerts & System Channels',
'按图层': 'Layer',
'任务态势': 'Task Trends',
'图层占比': 'Layer Share',
'算力中心地理定位进度': 'Compute Center Geocoding Progress',
'核心图层记录': 'Core Layer Records',
'采集任务执行趋势': 'Collection Task Execution Trend',
'地球图层资产占比与算力定位': 'Globe Layer Asset Share & Compute Geocoding',
'总采集记录': 'Total Collected Records',
'地球核心图层': 'Core Globe Layers',
'算力已定位': 'Compute Geocoded',
'按数据源记录分布': 'Records by Datasource',
'按实体类型记录分布': 'Records by Entity Type',
'按地球图层记录分布': 'Records by Globe Layer',
'悬停查看占比': 'Hover for share',
'系统与实时通道': 'System & Realtime Channels',
'需关注': 'Needs Attention',
'占比': 'Share',
'台账': 'Ledger',
'最近任务': 'Recent Tasks',
'查看采集数据': 'Inspect Collected Data',
'暂无数据源': 'No datasources',
'暂无采集器': 'No collectors',
'全部健康': 'All Healthy',
'凭证齐全': 'Credentials Ready',
'7天': '7d',
'其他图层': 'Other Layers',
}
+12
View File
@@ -15,6 +15,11 @@ export const zhCN = {
page: '第 {{page}} / {{totalPages}} 页,共 {{total}} 条',
previousPage: '上一页',
nextPage: '下一页',
resizeColumn: '调整「{{column}}」列宽',
resizeColumnHint: '拖动调整列宽,双击恢复弹性宽度',
waterfallLoadingMore: '正在加载更多…(已加载 {{loaded}} / {{total}} 条)',
waterfallLoadMoreHint: '已加载 {{loaded}} / {{total}} 条 · 向下滚动加载更多',
waterfallAllLoaded: '已加载全部 {{total}} 条',
selectRow: '选择行',
selectVisibleRows: '选择当前可见数据',
theme: '主题',
@@ -91,6 +96,7 @@ export const zhCN = {
collectors: '采集调度',
earthAssets: '国界精度',
earthBrand: '品牌标识',
earthCloudMap: '大气云图',
logsSources: '日志源',
newsSources: '新闻源',
notifications: '通知策略',
@@ -255,6 +261,11 @@ export const enUS = {
page: 'Page {{page}} / {{totalPages}}, {{total}} total',
previousPage: 'Previous',
nextPage: 'Next',
resizeColumn: 'Resize {{column}} column',
resizeColumnHint: 'Drag to resize column, double-click to reset',
waterfallLoadingMore: 'Loading more… ({{loaded}} / {{total}} loaded)',
waterfallLoadMoreHint: 'Loaded {{loaded}} / {{total}} · Scroll down for more',
waterfallAllLoaded: 'All {{total}} items loaded',
selectRow: 'Select row',
selectVisibleRows: 'Select visible rows',
theme: 'Theme',
@@ -331,6 +342,7 @@ export const enUS = {
collectors: 'Collection Schedule',
earthAssets: 'Boundary Accuracy',
earthBrand: 'Branding',
earthCloudMap: 'Atmosphere Cloud Map',
logsSources: 'Log Sources',
newsSources: 'News Sources',
notifications: 'Notification Policy',