release: bump version to 0.84.2
ci / backend (push) Waiting to run
ci / frontend (push) Waiting to run

This commit is contained in:
rayd1o committed 2026-12-05 01:56:03 +08:00
1 parent 5e6352f524
commit 30b44ec00d
77 files changed
+3312 -1039

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "planet-frontend",
"version": "0.84.1",
"version": "0.84.2",
"private": true,
"packageManager": "bun@1",
"dependencies": {
+39 -1
View File
@@ -1304,6 +1304,23 @@ body:not(.layout-mode-mobile) .compute-card.is-spotlight:hover:not(.is-dragging)
color: var(--hud-accent-strong);
}
.compute-source-link.earth-mobile-action-btn {
gap: var(--hud-gap-xs);
}
.compute-source-link > .material-symbols-rounded {
display: inline-flex;
align-items: center;
justify-content: center;
flex: 0 0 auto;
width: 1em;
height: 1em;
overflow: hidden;
font-size: calc(13px * var(--hud-scale));
line-height: 1;
font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 20;
}
/* Stage Narrative Player HUD Bar (F-12, F-14, F-15, F-17 — Pinned Always-On-Top) */
.stage-narrative-bar {
position: absolute;
@@ -2621,9 +2638,26 @@ body:has(.earth-toolbar-cluster.is-expanded):has(.earth-bottom-dock > :not([hidd
}
.copilot-source-card__link {
display: inline-flex;
align-items: center;
gap: calc(3px * var(--hud-scale));
color: var(--hud-accent-strong);
text-decoration: none;
font-weight: 600;
line-height: 1.2;
}
.copilot-source-card__link > .material-symbols-rounded {
display: inline-flex;
align-items: center;
justify-content: center;
flex: 0 0 auto;
width: 1em;
height: 1em;
overflow: hidden;
font-size: calc(12.5px * var(--hud-scale));
line-height: 1;
font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 20;
}
.copilot-source-card__link:hover {
@@ -2786,11 +2820,12 @@ body:has(.earth-toolbar-cluster.is-expanded):has(.earth-bottom-dock > :not([hidd
font: inherit;
font-size: calc(11.5px * var(--hud-scale));
font-weight: 600;
white-space: nowrap;
cursor: pointer;
transition: background 0.18s ease, border-color 0.18s ease, color 0.18s ease, transform 0.18s ease;
}
.situational-copilot__send .material-symbols-rounded {
.situational-copilot__send > .material-symbols-rounded {
display: inline-flex;
align-items: center;
justify-content: center;
@@ -2801,6 +2836,8 @@ body:has(.earth-toolbar-cluster.is-expanded):has(.earth-bottom-dock > :not([hidd
font-size: calc(14px * var(--hud-scale));
line-height: 1;
font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 20;
/* The send and stop glyphs sit above the label's visible center in their font boxes. */
translate: 0 calc(1px * var(--hud-scale));
user-select: none;
pointer-events: none;
}
@@ -4274,6 +4311,7 @@ body:not(.layout-mode-mobile) .stage-narrative-bar.is-compact-coexist {
display: inline-flex;
align-items: center;
justify-content: center;
flex: 0 0 auto;
width: 1em;
height: 1em;
overflow: hidden;
+24 -5
View File
@@ -405,8 +405,23 @@
white-space: nowrap;
}
.hud-select-trigger > .material-symbols-rounded {
.hud-select-trigger > .material-symbols-rounded,
.hud-select-menu__option > .material-symbols-rounded,
.earth-mobile-layer-card-icon.material-symbols-rounded,
.earth-mobile-search-chip > .material-symbols-rounded,
.earth-mobile-details-media-credit > .material-symbols-rounded,
.earth-mobile-details-actions .earth-mobile-action-btn > .material-symbols-rounded {
display: inline-flex;
align-items: center;
justify-content: center;
flex: 0 0 auto;
width: 1em;
height: 1em;
overflow: hidden;
font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 20;
}
.hud-select-trigger > .material-symbols-rounded {
color: var(--hud-text-soft);
font-size: calc(16px * var(--hud-scale));
}
@@ -510,7 +525,6 @@
}
.hud-select-menu__option > .material-symbols-rounded {
flex: 0 0 auto;
font-size: calc(14px * var(--hud-scale));
}
@@ -1241,7 +1255,7 @@
opacity: 0.46;
}
.earth-mobile-layer-card-icon {
.earth-mobile-layer-card-icon.material-symbols-rounded {
font-size: 22px;
color: var(--hud-accent-strong);
}
@@ -1347,6 +1361,7 @@
display: inline-flex;
align-items: center;
justify-content: center;
gap: 4px;
padding: 5px 12px;
border-radius: 18px;
border: 1px solid rgba(255, 255, 255, 0.1);
@@ -1360,6 +1375,10 @@
white-space: nowrap;
}
.earth-mobile-search-chip > .material-symbols-rounded {
font-size: 13px;
}
.earth-mobile-search-chip:active {
transform: scale(0.96);
}
@@ -3021,7 +3040,7 @@ label.is-disabled.earth-mobile-settings-card {
pointer-events: auto;
}
.earth-mobile-details-media-credit .material-symbols-rounded {
.earth-mobile-details-media-credit > .material-symbols-rounded {
font-size: 13px;
}
@@ -3181,7 +3200,7 @@ label.is-disabled.earth-mobile-settings-card {
transform: scale(0.97);
}
.earth-mobile-details-actions .earth-mobile-action-btn .material-symbols-rounded {
.earth-mobile-details-actions .earth-mobile-action-btn > .material-symbols-rounded {
font-size: 17px;
}
+52 -18
View File
@@ -510,13 +510,19 @@ body[data-callout-line-style="bold"] .callout-connector circle {
-webkit-user-select: none;
}
.info-card-source-link {
display: inline-block;
margin-top: calc(8px * var(--hud-scale));
.info-card-source-link,
.info-card-auth-link {
display: inline-flex;
align-items: center;
gap: calc(4px * var(--hud-scale));
color: var(--hud-accent);
text-decoration: none;
}
.info-card-source-link {
margin-top: calc(8px * var(--hud-scale));
font-size: var(--hud-font-size-sm);
line-height: 1.45;
text-decoration: none;
}
.info-card-source-link:hover,
@@ -755,10 +761,12 @@ body[data-callout-line-style="bold"] .callout-connector circle {
}
.info-card-compute-collect-button {
--info-card-collect-icon-size: calc(13px * var(--hud-scale));
position: relative;
display: inline-flex;
align-items: center;
gap: 4px;
justify-content: center;
gap: calc(4px * var(--hud-scale));
padding: calc(3px * var(--hud-scale)) calc(8px * var(--hud-scale));
background: transparent;
color: var(--hud-text-soft);
@@ -800,15 +808,27 @@ body[data-callout-line-style="bold"] .callout-connector circle {
flex-shrink: 0;
width: calc(10px * var(--hud-scale));
height: calc(10px * var(--hud-scale));
vertical-align: middle;
border: 1.5px solid rgba(201, 220, 255, 0.35);
border-top-color: #c9dcff;
border-radius: 999px;
animation: info-card-location-spin 0.8s linear infinite;
}
.info-card-compute-candidate-preview.is-loading::before {
margin-inline-end: 4px;
.info-card-compute-collect-button.is-loading::before {
box-sizing: border-box;
width: var(--info-card-collect-icon-size);
height: var(--info-card-collect-icon-size);
}
.info-card-compute-collect-button.is-loading > .material-symbols-rounded {
display: none;
}
.info-card-compute-candidate-preview.is-loading {
display: inline-flex;
align-items: center;
justify-content: center;
gap: calc(4px * var(--hud-scale));
}
.info-card-unresolved-item.is-locating .info-card-unresolved-index {
@@ -819,8 +839,29 @@ body[data-callout-line-style="bold"] .callout-connector circle {
position: absolute;
}
.info-card-compute-collect-button .material-symbols-rounded {
font-size: calc(13px * var(--hud-scale));
.info-card-compute-collect-button > .material-symbols-rounded,
.info-card-source-link > .material-symbols-rounded,
.info-card-auth-link > .material-symbols-rounded,
.earth-workflow-menu__icon.material-symbols-rounded,
.earth-target-tray__icon.material-symbols-rounded {
display: inline-flex;
align-items: center;
justify-content: center;
flex: 0 0 auto;
width: 1em;
height: 1em;
overflow: hidden;
line-height: 1;
font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 20;
}
.info-card-compute-collect-button > .material-symbols-rounded {
font-size: var(--info-card-collect-icon-size);
}
.info-card-source-link > .material-symbols-rounded,
.info-card-auth-link > .material-symbols-rounded {
font-size: calc(12.5px * var(--hud-scale));
}
.info-card-compute-collect-status {
@@ -830,11 +871,8 @@ body[data-callout-line-style="bold"] .callout-connector circle {
}
.info-card-auth-link {
display: inline-block;
margin-left: calc(6px * var(--hud-scale));
color: var(--hud-accent);
font-weight: 500;
text-decoration: none;
}
.info-card-auth-link:hover,
@@ -1045,11 +1083,6 @@ body[data-callout-line-style="bold"] .callout-connector circle {
.earth-workflow-menu__icon.material-symbols-rounded,
.earth-target-tray__icon.material-symbols-rounded {
font-size: 16px;
width: 16px;
height: 16px;
line-height: 1;
font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 20;
flex: 0 0 auto;
}
.earth-workflow-menu__label {
@@ -1160,6 +1193,7 @@ body[data-callout-line-style="bold"] .callout-connector circle {
font-weight: 600;
display: inline-flex;
align-items: center;
justify-content: center;
gap: 5px;
cursor: pointer;
letter-spacing: 0;
+12 -7
View File
@@ -24,12 +24,22 @@
cursor: grabbing;
}
.layer-panel-icon {
flex-shrink: 0;
.layer-panel-icon.material-symbols-rounded,
.layer-row-icon.material-symbols-rounded {
display: inline-flex;
align-items: center;
justify-content: center;
flex: 0 0 auto;
width: 1em;
height: 1em;
overflow: hidden;
font-size: calc(15px * var(--hud-scale));
color: var(--hud-text-soft);
line-height: 1;
font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 20;
}
.layer-panel-icon {
pointer-events: none;
}
@@ -197,11 +207,6 @@
}
.layer-row-icon {
flex-shrink: 0;
font-size: calc(15px * var(--hud-scale));
color: var(--hud-text-soft);
line-height: 1;
font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 20;
transition: color 0.18s ease;
}
@@ -184,7 +184,28 @@ body:not(.layout-mode-mobile) .news-region-card.is-spotlight:hover:not(.is-dragg
}
.news-region-card__content::-webkit-scrollbar { display:none; width:0; height:0; }
.news-region-card__footer { display:flex; align-items:center; gap:calc(4px * var(--hud-scale)); padding:calc(5px * var(--hud-scale)) calc(8px * var(--hud-scale)); flex-shrink:0; border-top:1px solid var(--hud-border); }
.news-region-card__footer a { margin-left:auto; color:var(--hud-accent,#91baff); font-size:var(--hud-font-size-sm); text-decoration:none; white-space:nowrap; }
.news-region-card__source {
display: inline-flex;
align-items: center;
gap: var(--hud-gap-xs);
margin-inline-start: auto;
color: var(--hud-accent, #91baff);
font-size: var(--hud-font-size-sm);
text-decoration: none;
white-space: nowrap;
}
.news-region-card__source > .material-symbols-rounded {
display: inline-flex;
align-items: center;
justify-content: center;
flex: 0 0 auto;
width: 1em;
height: 1em;
overflow: hidden;
font-size: calc(13px * var(--hud-scale));
line-height: 1;
font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 20;
}
.news-region-card__count { min-width:calc(36px * var(--hud-scale)); text-align:center; font-size:var(--hud-font-size-sm); }
.news-region-card button { cursor:pointer; }
.news-region-card button:disabled { opacity:.35; cursor:default; }
+5 -5
View File
@@ -719,11 +719,11 @@
</div>
<div class="earth-mobile-search-chips" role="group" aria-label="快捷分类筛选">
<button type="button" class="earth-mobile-search-chip is-active" data-search-filter="all">全部</button>
<button type="button" class="earth-mobile-search-chip" data-search-filter="satellite" data-search-keyword="卫星"><span aria-hidden="true">🛰️ </span><span>卫星</span></button>
<button type="button" class="earth-mobile-search-chip" data-search-filter="cable" data-search-keyword="海缆"><span aria-hidden="true">🌊 </span><span>海缆</span></button>
<button type="button" class="earth-mobile-search-chip" data-search-filter="landing_point" data-search-keyword="登陆点"><span aria-hidden="true">📍 </span><span>登陆点</span></button>
<button type="button" class="earth-mobile-search-chip" data-search-filter="compute_center" data-search-keyword="算力"><span aria-hidden="true">🖥️ </span><span>算力</span></button>
<button type="button" class="earth-mobile-search-chip" data-search-filter="bgp" data-search-keyword="BGP"><span aria-hidden="true">⚡ </span><span>BGP</span></button>
<button type="button" class="earth-mobile-search-chip" data-search-filter="satellite" data-search-keyword="卫星"><span class="material-symbols-rounded" aria-hidden="true">satellite_alt</span><span>卫星</span></button>
<button type="button" class="earth-mobile-search-chip" data-search-filter="cable" data-search-keyword="海缆"><span class="material-symbols-rounded" aria-hidden="true">cable</span><span>海缆</span></button>
<button type="button" class="earth-mobile-search-chip" data-search-filter="landing_point" data-search-keyword="登陆点"><span class="material-symbols-rounded" aria-hidden="true">location_on</span><span>登陆点</span></button>
<button type="button" class="earth-mobile-search-chip" data-search-filter="compute_center" data-search-keyword="算力"><span class="material-symbols-rounded" aria-hidden="true">memory</span><span>算力</span></button>
<button type="button" class="earth-mobile-search-chip" data-search-filter="bgp" data-search-keyword="BGP"><span class="material-symbols-rounded" aria-hidden="true">hub</span><span>BGP</span></button>
</div>
<div id="mobile-earth-search-meta" class="earth-mobile-search-meta">输入关键词或轻点上方分类快速探索地球对象</div>
<div id="mobile-earth-search-results" class="earth-mobile-search-results" role="listbox" aria-label="移动端搜索结果"></div>
+9 -8
View File
@@ -74,6 +74,11 @@ function safeMediaUrl(value) {
}
}
function computeSourceLink(url, label, buttonClass) {
if (!/^https:\/\//i.test(url || "")) return "";
return `<a class="${buttonClass} compute-source-link" href="${escape(url)}" target="_blank" rel="noopener noreferrer"><span class="earth-settings-chip__label">${escape(label)}</span><span class="material-symbols-rounded" aria-hidden="true">open_in_new</span></a>`;
}
export function initComputeTopic({
setMapQuery,
focusFacility,
@@ -906,9 +911,6 @@ export function initComputeTopic({
}
function mobileRegionDetailHtml(entry, view = participantView(entry)) {
const sourceUrl = /^https:\/\//i.test(view.evidence?.url || "")
? view.evidence.url
: "";
const isBilateral = ["CN", "US"].includes(entry.code) && countries.includes("CN") && countries.includes("US");
const facilityStatus = facilityError
? `<div class="compute-mobile__inline-error" role="alert">${escape(facilityError)} <button type="button" class="earth-mobile-action-btn earth-mobile-action-btn--ghost" data-action="retry">${text("重试", "Retry")}</button></div>`
@@ -929,7 +931,7 @@ export function initComputeTopic({
${view.members.length ? `<section class="compute-mobile__detail-section"><h3>${text("区域成员", "Region members")} <span>${view.members.length}</span></h3><div class="compute-card__members">${view.members.map((member) => `<span class="earth-mobile-settings-chip is-active earth-settings-chip--with-icon">${participantIdentity(member)}<span>${escape(nameOf(member))}</span></span>`).join("")}</div></section>` : ""}
<section class="compute-mobile__detail-section"><h3>${text("已核验设施样本", "Verified Facility Samples")} <span>${escape(view.sampleStatus)}</span></h3><p class="earth-mobile-detail-empty">${text("设施条数仅反映已收录公开样本。", "Facility counts reflect publicly indexed samples only.")}</p>${view.sourceBreakdown ? `<p class="earth-mobile-detail-type">${escape(view.sourceBreakdown)}</p>` : ""}${facilityStatus}</section>
${mediaHtml(view.locations)}
${view.evidence ? `<section class="compute-mobile__detail-section"><h3>${text("来源与证据", "Source and evidence")}</h3><p class="earth-mobile-detail-title">${escape(view.evidence.title || "")}</p><p class="earth-mobile-detail-type">${escape(view.evidence.publisher || "")} · ${escape(view.evidence.report_year || view.evidence.published_at || "")}</p>${view.evidence.locator ? `<p class="earth-mobile-detail-type">${escape(view.evidence.locator)}</p>` : ""}${sourceUrl ? `<a class="earth-mobile-action-btn" href="${escape(sourceUrl)}" target="_blank" rel="noopener noreferrer">${text("打开来源", "Open source")} ↗</a>` : ""}</section>` : ""}`;
${view.evidence ? `<section class="compute-mobile__detail-section"><h3>${text("来源与证据", "Source and evidence")}</h3><p class="earth-mobile-detail-title">${escape(view.evidence.title || "")}</p><p class="earth-mobile-detail-type">${escape(view.evidence.publisher || "")} · ${escape(view.evidence.report_year || view.evidence.published_at || "")}</p>${view.evidence.locator ? `<p class="earth-mobile-detail-type">${escape(view.evidence.locator)}</p>` : ""}${computeSourceLink(view.evidence.url, text("打开来源", "Open source"), "earth-mobile-action-btn")}</section>` : ""}`;
}
function destroyMobileCardPanels() {
@@ -1042,12 +1044,12 @@ export function initComputeTopic({
const lineageMarkup = renderLineageDrawerHtml(evidence);
if (body.innerHTML !== lineageMarkup) body.innerHTML = lineageMarkup;
} else if (evidence) {
const sourceUrl = /^https:\/\//i.test(evidence.url || "") ? evidence.url : "";
evidencePanel.querySelector(".hud-panel__title").textContent = evidence.title;
const pubDateNote = evidence.published_at
? `${text("发布日", "Published")} ${evidence.published_at}`
: `${text("报告年", "Report year")} ${evidence.report_year || ""}`;
const sourceMarkup = `<p class="compute-evidence__meta"><strong>${escape(evidence.publisher)}</strong> · ${escape(pubDateNote)}</p>${evidence.locator ? `<p class="compute-evidence__locator"><span class="material-symbols-rounded" aria-hidden="true">find_in_page</span><span>${escape(evidence.locator)}</span></p>` : ""}${sourceUrl ? `<a class="earth-settings-chip compute-evidence__link" href="${escape(sourceUrl)}" target="_blank" rel="noopener noreferrer">${text("打开权威原文", "Open verified source")} ↗</a>` : ""}`;
const sourceLink = computeSourceLink(evidence.url, text("打开权威原文", "Open verified source"), "earth-settings-chip compute-evidence__link");
const sourceMarkup = `<p class="compute-evidence__meta"><strong>${escape(evidence.publisher)}</strong> · ${escape(pubDateNote)}</p>${evidence.locator ? `<p class="compute-evidence__locator"><span class="material-symbols-rounded" aria-hidden="true">find_in_page</span><span>${escape(evidence.locator)}</span></p>` : ""}${sourceLink}`;
if (body.innerHTML !== sourceMarkup) body.innerHTML = sourceMarkup;
}
}
@@ -1063,7 +1065,6 @@ export function initComputeTopic({
}
const current = lineageData?.current || null;
const src = current?.source || fallbackEvidence || null;
const sourceUrl = /^https:\/\//i.test(src?.url || "") ? src.url : "";
const timestamps = lineageData?.timestamps || null;
const timeline = Array.isArray(lineageData?.timeline) ? lineageData.timeline : [];
const unit = current?.unit || (lineageTarget?.metric === "absolute" ? "EFlops" : "%");
@@ -1086,7 +1087,7 @@ export function initComputeTopic({
${src.locator ? `<p class="compute-evidence__locator"><span class="material-symbols-rounded" aria-hidden="true">find_in_page</span><span>${escape(src.locator)}</span></p>` : ""}
${src.excerpt ? `<blockquote class="compute-evidence__excerpt">${escape(src.excerpt)}</blockquote>` : ""}
${src.content_sha256 ? `<p class="compute-evidence__hash" title="${escape(src.content_sha256)}"><span>SHA-256</span><code>${escape(src.content_sha256.slice(0, 20))}…</code></p>` : ""}
${sourceUrl ? `<a class="earth-settings-chip compute-evidence__link" href="${escape(sourceUrl)}" target="_blank" rel="noopener noreferrer">${text("打开权威原文", "Open verified source")} ↗</a>` : ""}
${computeSourceLink(src.url, text("打开权威原文", "Open verified source"), "earth-settings-chip compute-evidence__link")}
</section>`
: "";
+9 -2
View File
@@ -168,7 +168,11 @@ function applyLocationStatusElement(statusEl, statusText, authRequired = false)
link.href = getAdminLoginUrl();
link.target = '_blank';
link.rel = 'noopener noreferrer';
link.textContent = `${infoText('前往管理员登录')} ↗`;
const icon = document.createElement('span');
icon.className = 'material-symbols-rounded';
icon.setAttribute('aria-hidden', 'true');
icon.textContent = 'open_in_new';
link.append(infoText('前往管理员登录'), icon);
link.addEventListener('click', (event) => {
event.stopPropagation();
});
@@ -840,7 +844,10 @@ function renderDefaultCardContent(content, config, data) {
const fields = [['精度 / 测量', `${metadata.precision || '—'} / ${metadata.measurement || '—'}`]];
html += fields.map(([label, value]) => `<div class="info-card-property"><span class="info-card-label">${escapeInfoCardHtml(infoText(label))}</span><span class="info-card-value">${escapeInfoCardHtml(value)}</span></div>`).join('');
if (/^https?:\/\//i.test(metadata.source_url || '')) {
html += `<a class="info-card-source-link" href="${escapeInfoCardHtml(metadata.source_url)}" target="_blank" rel="noopener noreferrer">${escapeInfoCardHtml(infoText('查看原始来源'))} ↗</a>`;
html += `<a class="info-card-source-link" href="${escapeInfoCardHtml(metadata.source_url)}" target="_blank" rel="noopener noreferrer">
<span>${escapeInfoCardHtml(infoText('查看原始来源'))}</span>
<span class="material-symbols-rounded" aria-hidden="true">open_in_new</span>
</a>`;
}
}
@@ -5,7 +5,6 @@ import {
toggleCables,
} from "./cables.js";
import {
clearSatelliteData,
getSatelliteLegendItems,
loadSatellites,
toggleSatellites,
@@ -173,7 +172,6 @@ function registerSatelliteStartupTask() {
);
await context.yieldFrame(12);
try {
clearSatelliteData();
const canApplyUpdate = () => !context.isCancelled() && context.isSatellitesEnabled();
const loadResult = await loadSatellites({
limit: context.getInitialSatelliteLoadLimit(),
-1
View File
@@ -4337,7 +4337,6 @@ async function ensureSatellitesEnabled(options = {}) {
createSatellites(scene, earth);
}
clearSatelliteData();
let loadResult;
try {
loadResult = await loadSatellites({
+17 -3
View File
@@ -74,7 +74,7 @@ export function initNewsRegionCards({ rootParent, spatial }) {
} : null;
card.source.hidden = !/^https?:\/\//i.test(url);
if (!card.source.hidden) card.source.href = url; else card.source.removeAttribute("href");
card.source.textContent = text("阅读原文 ↗","Read source ↗");
card.sourceLabel.textContent = text("阅读原文", "Read source");
if (card.analyze) card.analyze.disabled = !card.currentStory;
card.scrollbar?.update();
}
@@ -91,10 +91,24 @@ export function initNewsRegionCards({ rootParent, spatial }) {
const element=document.createElement("article");
element.className="hud-panel info-card news news-region-card";
element.dataset.region=region.key;
element.innerHTML=`<header class="info-card-header hud-panel-drag-handle"><span class="info-card-icon" aria-hidden="true">${NEWS_CARD_ICON}</span><h3 class="news-region-card__headline"></h3><span class="news-region-card__region"></span><div class="hud-panel__actions">${iconButton("news-analyze","forum",text("在 AI 参谋中分析","Analyze in AI Copilot"))}${iconButton("card-collapse","expand_less",text("折叠","Collapse"))}</div></header><div class="news-region-card__body hud-panel__body hud-panel__body--collapsible"><div class="info-card-content news-region-card__content hud-scroll-region"></div><footer class="news-region-card__footer">${iconButton("news-prev","chevron_left",text("上一条新闻","Previous story"))}<span class="news-region-card__count"></span>${iconButton("news-next","chevron_right",text("下一条新闻","Next story"))}${iconButton("news-play","pause",text("暂停轮播","Pause rotation"))}<a target="_blank" rel="noopener noreferrer" hidden></a></footer></div>`;
element.innerHTML = `<header class="info-card-header hud-panel-drag-handle"><span class="info-card-icon" aria-hidden="true">${NEWS_CARD_ICON}</span><h3 class="news-region-card__headline"></h3><span class="news-region-card__region"></span><div class="hud-panel__actions">${iconButton("news-analyze","forum",text("在 AI 参谋中分析","Analyze in AI Copilot"))}${iconButton("card-collapse","expand_less",text("折叠","Collapse"))}</div></header>
<div class="news-region-card__body hud-panel__body hud-panel__body--collapsible">
<div class="info-card-content news-region-card__content hud-scroll-region"></div>
<footer class="news-region-card__footer">
${iconButton("news-prev", "chevron_left", text("上一条新闻", "Previous story"))}
<span class="news-region-card__count"></span>
${iconButton("news-next", "chevron_right", text("下一条新闻", "Next story"))}
${iconButton("news-play", "pause", text("暂停轮播", "Pause rotation"))}
<a class="news-region-card__source" target="_blank" rel="noopener noreferrer" hidden>
<span class="news-region-card__source-label"></span>
<span class="material-symbols-rounded" aria-hidden="true">open_in_new</span>
</a>
</footer>
</div>`;
const card={ element, hovered:false, signature:null, typing:false, writer:createTypewriter(), currentStory:null,
title:element.querySelector("h3"), region:element.querySelector(".news-region-card__region"), content:element.querySelector(".news-region-card__content"),
count:element.querySelector(".news-region-card__count"),source:element.querySelector("a"),
count:element.querySelector(".news-region-card__count"),source:element.querySelector(".news-region-card__source"),
sourceLabel:element.querySelector(".news-region-card__source-label"),
previous:element.querySelector('[data-action="news-prev"]'),next:element.querySelector('[data-action="news-next"]'),play:element.querySelector('[data-action="news-play"]'),analyze:element.querySelector('[data-action="news-analyze"]'),
};
card.panel=createHUDPanel({panel:element,header:element.querySelector("header"),body:element.querySelector(".news-region-card__body"),collapseBtn:element.querySelector('[data-action="card-collapse"]'),expandLabel:text("展开新闻","Expand news"),collapseLabel:text("折叠新闻","Collapse news")});
+27 -9
View File
@@ -1074,6 +1074,8 @@ function scheduleBackgroundSatelliteValidation({
})();
}
const lastSatelliteEtags = new Map();
export async function loadSatellites(options = {}) {
abortActiveSatelliteRevalidation();
const limit = getRequestedSatelliteLimit(options.limit);
@@ -1117,7 +1119,7 @@ export async function loadSatellites(options = {}) {
const networkResult = await fetchSatellitesWithRetry({
url: url.toString(),
etag: options.forceNetwork ? null : cachedSnapshot?.etag || null,
etag: options.cacheBust ? null : cachedSnapshot?.etag || lastSatelliteEtags.get(cacheKey) || null,
timeoutMs: options.timeoutMs || SATELLITE_FETCH_TIMEOUT_MS,
maxAttempts: options.maxAttempts || SATELLITE_FETCH_MAX_ATTEMPTS,
signal: options.signal,
@@ -1127,17 +1129,33 @@ export async function loadSatellites(options = {}) {
throw createAbortError("Satellite load aborted");
}
if (networkResult.notModified && cachedFeatures.length > 0) {
applyDecodedSatelliteFeatures(cachedFeatures);
return {
count: cachedFeatures.length,
requestedLimit: limit,
fromCache: true,
notModified: true,
};
if (networkResult.notModified) {
if (networkResult.etag) {
lastSatelliteEtags.set(cacheKey, networkResult.etag);
}
if (satelliteData.length > 0) {
return {
count: satelliteData.length,
requestedLimit: limit,
fromCache: true,
notModified: true,
};
}
if (cachedFeatures.length > 0) {
applyDecodedSatelliteFeatures(cachedFeatures);
return {
count: cachedFeatures.length,
requestedLimit: limit,
fromCache: true,
notModified: true,
};
}
}
const decodedFeatures = decodeSatellitePayload(networkResult.payload);
if (networkResult.etag) {
lastSatelliteEtags.set(cacheKey, networkResult.etag);
}
void writeSatelliteSnapshot(cacheKey, {
etag: networkResult.etag,
payload: networkResult.payload,
@@ -1274,7 +1274,10 @@ export function initSituationalCopilot({
<div class="copilot-source-card__title">${escape(selectedEv.title || turn.activeEvidenceId)}</div>
<div class="copilot-source-card__meta">
<span>${escape([selectedEv.publisher, selectedEv.locator].filter(Boolean).join(" · "))}</span>
${sourceUrl ? `<a class="copilot-source-card__link" href="${escape(sourceUrl)}" target="_blank" rel="noopener noreferrer">${escape(text("原文", "Source"))} ↗</a>` : ""}
${sourceUrl ? `<a class="copilot-source-card__link" href="${escape(sourceUrl)}" target="_blank" rel="noopener noreferrer">
<span>${escape(text("原文", "Source"))}</span>
<span class="material-symbols-rounded" aria-hidden="true">open_in_new</span>
</a>` : ""}
</div>
</div>
</div>` : ""}
+4 -1
View File
@@ -534,7 +534,10 @@ function renderEvidenceDrawerBlock(block, { collapsedOverride } = {}) {
</div>
<div class="wb-evidence-item__meta">
<span>${escapeWorkbenchHtml(metaParts)}</span>
${safeUrl ? `<a class="copilot-source-card__link" href="${escapeWorkbenchHtml(safeUrl)}" target="_blank" rel="noopener noreferrer">${escapeWorkbenchHtml(t("原文", "Source"))} ↗</a>` : ""}
${safeUrl ? `<a class="copilot-source-card__link" href="${escapeWorkbenchHtml(safeUrl)}" target="_blank" rel="noopener noreferrer">
<span>${escapeWorkbenchHtml(t("原文", "Source"))}</span>
<span class="material-symbols-rounded" aria-hidden="true">open_in_new</span>
</a>` : ""}
</div>
</li>`;
})
@@ -5,6 +5,7 @@ import {
useReactTable,
type ColumnDef,
type SortingState,
type VisibilityState,
} from '@tanstack/react-table'
import { ArrowDown, ArrowUp, ChevronsUpDown } from 'lucide-react'
import {
@@ -86,6 +87,7 @@ interface DataTableProps<TData> {
resizableColumns?: boolean
columnWidthStorageKey?: string
enableSorting?: boolean
hiddenColumnIds?: readonly string[]
waterfall?: DataTableWaterfallConfig | false
scrollResetKey?: string | number
}
@@ -104,6 +106,7 @@ export function DataTable<TData>({
resizableColumns = true,
columnWidthStorageKey,
enableSorting,
hiddenColumnIds,
waterfall,
scrollResetKey,
}: DataTableProps<TData>) {
@@ -130,11 +133,20 @@ export function DataTable<TData>({
const [resizingColumnId, setResizingColumnId] = useState<string | null>(null)
const resizeCleanupRef = useRef<(() => void) | null>(null)
const columnVisibility = useMemo<VisibilityState>(() => {
if (!hiddenColumnIds?.length) return {}
const next: VisibilityState = {}
for (const id of hiddenColumnIds) {
next[id] = false
}
return next
}, [hiddenColumnIds])
const table = useReactTable({
data,
columns: memoizedColumns,
enableSorting: effectiveEnableSorting,
state: { sorting },
state: { sorting, columnVisibility },
onSortingChange: setSorting,
getRowId,
getCoreRowModel: getCoreRowModel(),
@@ -519,7 +531,7 @@ export function DataTable<TData>({
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) + (hasSpacer ? 1 : 0)
const columnCount = leafHeaders.length + (selection ? 1 : 0) + (hasSpacer ? 1 : 0)
const showWaterfallFooter =
!footer &&
@@ -23,6 +23,7 @@ import { adminRouteGroups, getVisibleAdminRoutes } from '../../routes/manifest'
import { useAdminSearch } from '../../search/AdminSearchContext'
import { AdminSearchSpotlight } from '../../search/AdminSearchSpotlight'
import { Button } from '../ui/button'
import { fetchRuntimeVersion, getCachedRuntimeVersion } from './runtimeVersion'
import {
ensureGroupOpen,
getInitialOpenKeys,
@@ -35,14 +36,22 @@ import {
writeStoredOpenKeys,
} from './sidebarState'
const COMPACT_DESKTOP_MEDIA_QUERY = '(min-width: 761px) and (max-width: 1360px)'
let cachedOpenKeys: string[] | null = null
let cachedCollapsed: boolean | null = null
let cachedCompactCollapsedOverride: boolean | null = null
let cachedMenuScrollTop = 0
function sameStringArray(a: readonly string[], b: readonly string[]) {
return a.length === b.length && a.every((item, index) => item === b[index])
}
function matchesCompactDesktop(): boolean {
if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return false
return window.matchMedia(COMPACT_DESKTOP_MEDIA_QUERY).matches
}
export function AdminLayout({ children }: { children: ReactNode }) {
const location = useLocation()
const navigate = useNavigate()
@@ -56,6 +65,9 @@ export function AdminLayout({ children }: { children: ReactNode }) {
const [searchOpen, setSearchOpen] = useState(false)
const [preferencesOpen, setPreferencesOpen] = useState(false)
const [highlightedSearchIndex, setHighlightedSearchIndex] = useState(0)
const [runtimeVersion, setRuntimeVersion] = useState<string>(
() => getCachedRuntimeVersion() ?? packageJson.version,
)
const menuViewportRef = useRef<HTMLDivElement>(null)
const mobileMenuViewportRef = useRef<HTMLDivElement>(null)
const searchInputRef = useRef<HTMLInputElement>(null)
@@ -80,12 +92,34 @@ export function AdminLayout({ children }: { children: ReactNode }) {
const activeGroupKey = activeRoute?.group
const activeRouteLabel = activeRoute ? t(activeRoute.labelKey) : ''
const [collapsed, setCollapsed] = useState<boolean>(() => {
const [desktopCollapsed, setDesktopCollapsed] = useState<boolean>(() => {
if (cachedCollapsed !== null) return cachedCollapsed
const stored = readStoredCollapsed()
cachedCollapsed = stored ?? false
return cachedCollapsed
})
const [isCompactDesktop, setIsCompactDesktop] = useState<boolean>(matchesCompactDesktop)
const [compactCollapsedOverride, setCompactCollapsedOverride] = useState<boolean | null>(
() => cachedCompactCollapsedOverride,
)
useEffect(() => {
if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return
const mediaQuery = window.matchMedia(COMPACT_DESKTOP_MEDIA_QUERY)
const handleChange = () => {
const matches = mediaQuery.matches
setIsCompactDesktop(matches)
if (!matches) {
cachedCompactCollapsedOverride = null
setCompactCollapsedOverride(null)
}
}
handleChange()
mediaQuery.addEventListener('change', handleChange)
return () => mediaQuery.removeEventListener('change', handleChange)
}, [])
const collapsed = isCompactDesktop ? (compactCollapsedOverride ?? true) : desktopCollapsed
const [openKeys, setOpenKeys] = useState<string[]>(() => {
const initial = getInitialOpenKeys({
@@ -114,9 +148,14 @@ export function AdminLayout({ children }: { children: ReactNode }) {
})), [t])
const updateCollapsed = (nextCollapsed: boolean) => {
if (isCompactDesktop) {
cachedCompactCollapsedOverride = nextCollapsed
setCompactCollapsedOverride(nextCollapsed)
return
}
cachedCollapsed = nextCollapsed
writeStoredCollapsed(nextCollapsed)
setCollapsed(nextCollapsed)
setDesktopCollapsed(nextCollapsed)
}
const updateOpenKeys = (nextKeys: string[]) => {
@@ -184,6 +223,18 @@ export function AdminLayout({ children }: { children: ReactNode }) {
void adminSearch.ensureDynamicIndex(searchQuery)
}, [adminSearch, searchQuery])
useEffect(() => {
let active = true
void fetchRuntimeVersion(packageJson.version).then((resolved) => {
if (active) {
setRuntimeVersion(resolved)
}
})
return () => {
active = false
}
}, [])
const renderNav = ({ mobile }: { mobile: boolean }) => {
const isCollapsed = !mobile && collapsed
return (
@@ -284,7 +335,18 @@ export function AdminLayout({ children }: { children: ReactNode }) {
<span className="admin__account-avatar" aria-hidden="true">{userInitial}</span>
<div>
<strong>{t('admin.greeting', { name: username })}</strong>
<span>{t('admin.version')} v{packageJson.version}</span>
<span
title={
runtimeVersion !== packageJson.version
? t('admin.versionDetail', {
backend: runtimeVersion,
ui: packageJson.version,
})
: undefined
}
>
{t('admin.version')} v{runtimeVersion}
</span>
</div>
</div>
<div className="admin__account-actions">
@@ -74,12 +74,72 @@ export function useSplitPaneResize({
const [width, setWidth] = useState<number>(() =>
readStoredSplitWidth(storageKey, defaultWidth, minWidth, maxWidth),
)
const preferredWidthRef = useRef<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])
const stored = readStoredSplitWidth(storageKey, defaultWidth, minWidth, maxWidth)
preferredWidthRef.current = stored
const containerW = containerRef?.current?.clientWidth
const next = clampSplitPaneWidth(stored, minWidth, maxWidth, containerW, minOppositeWidth)
if (cssVarName && containerRef?.current) {
containerRef.current.style.setProperty(cssVarName, `${next}px`)
}
setWidth(next)
}, [containerRef, cssVarName, defaultWidth, maxWidth, minOppositeWidth, minWidth, storageKey])
useEffect(() => {
const container = containerRef?.current
let rafId = 0
const syncClamp = () => {
rafId = 0
if (document.body.classList.contains('an-is-resizing')) return
const containerW = container?.clientWidth || window.innerWidth
if (!Number.isFinite(containerW) || containerW <= 0) return
const next = clampSplitPaneWidth(
preferredWidthRef.current,
minWidth,
maxWidth,
containerW,
minOppositeWidth,
)
if (cssVarName && container) {
container.style.setProperty(cssVarName, `${next}px`)
}
setWidth((prev) => {
if (prev === next) return prev
window.dispatchEvent(new Event(SPLIT_RESIZE_END_EVENT))
return next
})
}
const scheduleSync = () => {
if (!rafId) {
rafId = window.requestAnimationFrame(syncClamp)
}
}
scheduleSync()
if (typeof ResizeObserver !== 'undefined' && container) {
const observer = new ResizeObserver(scheduleSync)
observer.observe(container)
return () => {
if (rafId) window.cancelAnimationFrame(rafId)
observer.disconnect()
}
}
window.addEventListener('resize', scheduleSync)
return () => {
if (rafId) window.cancelAnimationFrame(rafId)
window.removeEventListener('resize', scheduleSync)
}
}, [containerRef, cssVarName, maxWidth, minOppositeWidth, minWidth])
useEffect(() => () => {
dragCleanupRef.current?.()
@@ -138,6 +198,7 @@ export function useSplitPaneResize({
if (cssVarName && containerRef?.current) {
containerRef.current.style.setProperty(cssVarName, `${latestWidth}px`)
}
preferredWidthRef.current = latestWidth
setIsDragging(false)
setWidth(latestWidth)
writeStoredSplitWidth(storageKey, latestWidth)
@@ -169,10 +230,15 @@ export function useSplitPaneResize({
step === Number.NEGATIVE_INFINITY || step === Number.POSITIVE_INFINITY
? clampSplitPaneWidth(defaultWidth, minWidth, maxWidth, containerW, minOppositeWidth)
: clampSplitPaneWidth(width + step, minWidth, maxWidth, containerW, minOppositeWidth)
preferredWidthRef.current = next
if (cssVarName && containerRef?.current) {
containerRef.current.style.setProperty(cssVarName, `${next}px`)
}
setWidth(next)
writeStoredSplitWidth(storageKey, next)
window.dispatchEvent(new Event(SPLIT_RESIZE_END_EVENT))
},
[containerRef, defaultWidth, maxWidth, minOppositeWidth, minWidth, side, storageKey, width],
[containerRef, cssVarName, defaultWidth, maxWidth, minOppositeWidth, minWidth, side, storageKey, width],
)
return { width, isDragging, onPointerDown, onKeyDown }
@@ -0,0 +1,70 @@
const SEMVER_PATTERN = /^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/
let cachedRuntimeVersion: string | null = null
let inFlightPromise: Promise<string> | null = null
export function parseHealthVersion(payload: unknown): string | null {
if (!payload || typeof payload !== 'object') {
return null
}
const rawVersion = (payload as { version?: unknown }).version
if (typeof rawVersion !== 'string') {
return null
}
const normalized = rawVersion.trim().replace(/^v/i, '')
if (!normalized || !SEMVER_PATTERN.test(normalized)) {
return null
}
return normalized
}
export function getCachedRuntimeVersion(): string | null {
return cachedRuntimeVersion
}
export function resetRuntimeVersionCache(): void {
cachedRuntimeVersion = null
inFlightPromise = null
}
async function requestRuntimeVersion(
fallback: string,
fetcher: typeof fetch,
): Promise<string> {
try {
const response = await fetcher('/api/health', { cache: 'no-store' })
if (!response.ok) {
return fallback
}
const data: unknown = await response.json()
const version = parseHealthVersion(data)
if (!version) {
return fallback
}
cachedRuntimeVersion = version
return version
} catch {
return fallback
}
}
export async function fetchRuntimeVersion(
fallback: string,
fetcher: typeof fetch = fetch,
): Promise<string> {
if (cachedRuntimeVersion) {
return cachedRuntimeVersion
}
if (fetcher === fetch && inFlightPromise) {
return inFlightPromise
}
const promise = requestRuntimeVersion(fallback, fetcher).finally(() => {
if (fetcher === fetch) {
inFlightPromise = null
}
})
if (fetcher === fetch) {
inFlightPromise = promise
}
return promise
}
+3 -2
View File
@@ -78,7 +78,6 @@ export function ConfirmDialog({
open={open}
onOpenChange={onOpenChange}
title={title}
description={description}
width={420}
footer={(
<>
@@ -91,7 +90,9 @@ export function ConfirmDialog({
</>
)}
>
<span className="sr-only">{description || t('common.confirm')}</span>
<DialogPrimitive.Description className="an-confirm-dialog__body">
{description || t('common.confirm')}
</DialogPrimitive.Description>
</Dialog>
)
}
+16 -13
View File
@@ -1,5 +1,6 @@
import * as SelectPrimitive from '@radix-ui/react-select'
import { Check, ChevronDown } from 'lucide-react'
import Scrollbar from '../../../components/Scrollbar/Scrollbar'
import { cn } from '../../utils'
const EMPTY_OPTION_VALUE = '__an_select_empty__'
@@ -39,19 +40,21 @@ export function Select({ value, onValueChange, options, placeholder, disabled, c
</SelectPrimitive.Trigger>
<SelectPrimitive.Portal>
<SelectPrimitive.Content className="an-select__content" position="popper" sideOffset={4}>
<SelectPrimitive.Viewport>
{options.map((option) => {
const itemValue = option.value === '' ? EMPTY_OPTION_VALUE : option.value
return (
<SelectPrimitive.Item key={itemValue} value={itemValue} className="an-select__item">
<SelectPrimitive.ItemText>{option.label}</SelectPrimitive.ItemText>
<SelectPrimitive.ItemIndicator className="an-select__indicator">
<Check size={14} />
</SelectPrimitive.ItemIndicator>
</SelectPrimitive.Item>
)
})}
</SelectPrimitive.Viewport>
<Scrollbar className="an-select__scroll" axis="y">
<SelectPrimitive.Viewport>
{options.map((option) => {
const itemValue = option.value === '' ? EMPTY_OPTION_VALUE : option.value
return (
<SelectPrimitive.Item key={itemValue} value={itemValue} className="an-select__item">
<SelectPrimitive.ItemText>{option.label}</SelectPrimitive.ItemText>
<SelectPrimitive.ItemIndicator className="an-select__indicator">
<Check size={14} />
</SelectPrimitive.ItemIndicator>
</SelectPrimitive.Item>
)
})}
</SelectPrimitive.Viewport>
</Scrollbar>
</SelectPrimitive.Content>
</SelectPrimitive.Portal>
</SelectPrimitive.Root>
+45 -36
View File
@@ -1081,41 +1081,6 @@
letter-spacing: 0;
}
.an-advisor-textarea,
.an-chat-textarea,
.an-advisor-page .an-json-editor {
scrollbar-width: thin;
scrollbar-color: var(--an-border-strong) transparent;
}
.an-advisor-textarea::-webkit-scrollbar,
.an-chat-textarea::-webkit-scrollbar,
.an-advisor-page .an-json-editor::-webkit-scrollbar {
width: 6px;
height: 6px;
}
.an-advisor-textarea::-webkit-scrollbar-button,
.an-chat-textarea::-webkit-scrollbar-button,
.an-advisor-page .an-json-editor::-webkit-scrollbar-button {
display: none;
width: 0;
height: 0;
}
.an-advisor-textarea::-webkit-scrollbar-track,
.an-chat-textarea::-webkit-scrollbar-track,
.an-advisor-page .an-json-editor::-webkit-scrollbar-track {
background: transparent;
}
.an-advisor-textarea::-webkit-scrollbar-thumb,
.an-chat-textarea::-webkit-scrollbar-thumb,
.an-advisor-page .an-json-editor::-webkit-scrollbar-thumb {
border-radius: 999px;
background: var(--an-border-strong);
}
/* React Flow 3-Column Workflow Studio with Resizer Tracks */
.an-workflow-studio {
flex: 1 1 0;
@@ -1283,6 +1248,14 @@
box-shadow: var(--an-shadow);
}
.an-workflow-compact-rail-toggle.tui-button {
display: none;
}
.an-workflow-rail-backdrop {
display: none;
}
.an-workflow-mobile-node-bar {
display: none;
position: absolute;
@@ -2000,8 +1973,44 @@
@media (max-width: 1360px) and (min-width: 1025px) {
.an-workflow-studio {
grid-template-columns: var(--an-wf-rail-width, 244px) 14px minmax(300px, 1fr) 14px var(--an-wf-inspector-width, 356px);
position: relative;
grid-template-columns: minmax(460px, 1fr) 14px var(--an-wf-inspector-width, 340px);
}
.an-workflow-studio > .an-detail-resizer:first-of-type {
display: none;
}
.an-workflow-rail {
display: none;
}
.an-workflow-studio.is-compact-rail-open .an-workflow-rail-backdrop {
display: block;
position: absolute;
inset: 0;
z-index: 24;
border-radius: 10px;
background: rgba(15, 23, 42, 0.24);
}
.admin-theme-root[data-theme='dark'] .an-workflow-studio.is-compact-rail-open .an-workflow-rail-backdrop {
background: rgba(2, 6, 23, 0.48);
}
.an-workflow-studio.is-compact-rail-open .an-workflow-rail {
display: flex;
position: absolute;
inset: 0 auto 0 0;
width: min(300px, calc(100% - 48px));
z-index: 25;
box-shadow: 12px 0 32px rgba(2, 6, 23, 0.34);
}
.an-workflow-compact-rail-toggle.tui-button {
display: inline-flex;
}
.an-playground-shell.has-drawer {
grid-template-columns: minmax(0, 1fr) 14px var(--an-pg-drawer-width, 332px);
}
+62 -3
View File
@@ -602,6 +602,8 @@ export default function AdvisorWorkflows() {
const [inspectorWidth, setInspectorWidth] = useState<number>(() =>
readStoredWidth(WF_INSPECTOR_WIDTH_KEY, 396, 340, 560),
)
const [studioContainerWidth, setStudioContainerWidth] = useState(0)
const [compactRailOpen, setCompactRailOpen] = useState(false)
const [draggingResizer, setDraggingResizer] = useState<'rail' | 'inspector' | null>(null)
const [historyMeta, setHistoryMeta] = useState<{ canUndo: boolean; canRedo: boolean }>({
canUndo: false,
@@ -991,6 +993,34 @@ export default function AdvisorWorkflows() {
window.addEventListener('pointerup', stopMove, { once: true })
}, [inspectorWidth, railWidth])
useEffect(() => {
const el = studioRef.current
if (!el) return
const sync = () => {
const next = el.clientWidth
if (next > 0) setStudioContainerWidth(next)
}
sync()
if (typeof ResizeObserver === 'undefined') {
window.addEventListener('resize', sync)
return () => window.removeEventListener('resize', sync)
}
const observer = new ResizeObserver(sync)
observer.observe(el)
return () => observer.disconnect()
}, [])
useEffect(() => {
if (!compactRailOpen) return
const handleKeyDown = (event: globalThis.KeyboardEvent) => {
if (event.key === 'Escape') {
setCompactRailOpen(false)
}
}
window.addEventListener('keydown', handleKeyDown)
return () => window.removeEventListener('keydown', handleKeyDown)
}, [compactRailOpen])
const commitNodePositions = useCallback(
(movedNodes: Node<FlowNodeData>[]) => {
if (!movedNodes.length) return
@@ -1488,6 +1518,7 @@ export default function AdvisorWorkflows() {
(wfId: string, switchToCanvas = false) => {
setSelectedWfId(wfId)
setDeleteConfirmPending(false)
setCompactRailOpen(false)
setSearchParams({ workflow: wfId }, { replace: true })
if (switchToCanvas) setMobilePane('canvas')
},
@@ -2398,15 +2429,32 @@ export default function AdvisorWorkflows() {
<div
ref={studioRef}
className="an-workflow-studio"
className={`an-workflow-studio${compactRailOpen ? ' is-compact-rail-open' : ''}`}
data-mobile-pane={mobilePane}
style={
{
'--an-wf-rail-width': `${railWidth}px`,
'--an-wf-inspector-width': `${inspectorWidth}px`,
'--an-wf-rail-width': `${
studioContainerWidth > 0 && studioContainerWidth < railWidth + inspectorWidth + 376
? Math.max(230, Math.min(railWidth, studioContainerWidth - Math.min(inspectorWidth, 356) - 376))
: railWidth
}px`,
'--an-wf-inspector-width': `${
studioContainerWidth > 0
? typeof window !== 'undefined' && window.innerWidth <= 1360 && window.innerWidth > 1024
? Math.max(300, Math.min(inspectorWidth, studioContainerWidth - 474))
: Math.max(300, Math.min(inspectorWidth, studioContainerWidth - railWidth - 376))
: inspectorWidth
}px`,
} as CSSProperties
}
>
{compactRailOpen ? (
<div
className="an-workflow-rail-backdrop"
aria-hidden="true"
onClick={() => setCompactRailOpen(false)}
/>
) : null}
<aside className="an-workflow-rail" aria-label={tx('工作流目录', 'Workflow catalog')}>
<header className="an-drawer-pane__header">
<h3>{tx(`工作流目录 (${workflows.length})`, `Workflows (${workflows.length})`)}</h3>
@@ -2556,6 +2604,17 @@ export default function AdvisorWorkflows() {
</div>
<div className="an-workflow-canvas-actions">
<Button
type="button"
size="icon"
variant={compactRailOpen ? 'primary' : 'subtle'}
className="an-workflow-compact-rail-toggle"
onClick={() => setCompactRailOpen((open) => !open)}
title={tx(compactRailOpen ? '收起工作流目录' : '展开工作流目录', compactRailOpen ? 'Hide workflows' : 'Show workflows')}
aria-label={tx(compactRailOpen ? '收起工作流目录' : '展开工作流目录', compactRailOpen ? 'Hide workflows' : 'Show workflows')}
>
<Workflow size={14} />
</Button>
<Button
type="button"
size="icon"
@@ -139,7 +139,7 @@ export function CardImageSettings({active}:{active:boolean}) {
<Button size="icon" variant="subtle" title={t('重新加载','Reload')} aria-label={t('重新加载','Reload')} disabled={busy} onClick={()=>dirty?setConfirmation({label:t('放弃未保存的修改并重新加载?','Discard unsaved edits and reload?'),run:refresh}):refresh()}><RefreshCw size={16}/></Button>
<Button onClick={()=>void save()} disabled={!dirty || busy} loading={busy}><Save size={16}/>{t('保存','Save')}</Button>
</div>
{errorText?<p className="an-card-images-error" role="alert">{errorText}</p>:null}
{errorText?<Scrollbar className="an-card-images-error" axis="y"><p className="an-card-images-error__text" role="alert">{errorText}</p></Scrollbar>: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
ref={workspaceRef}
@@ -475,7 +475,7 @@ export function ComputeComparisonSettings({ active }: { active: boolean }) {
<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(`当前已发布版本:${(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}
{error ? <Scrollbar className="an-compute-error" axis="y"><p className="an-compute-error__text" role="alert">{error}</p></Scrollbar> : null}
{draft && saved ? <>
<div className="an-compute-toolbar">
<div className="an-compute-actions" role="group" aria-label={t('数据分类', 'Data categories')}>
@@ -936,7 +936,7 @@ export function ComputeComparisonSettings({ active }: { active: boolean }) {
<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">
<Scrollbar className="an-compute-table-wrap" axis="x">
<table className="an-compute-table">
<thead>
<tr>
@@ -959,9 +959,11 @@ export function ComputeComparisonSettings({ active }: { active: boolean }) {
))}
</tbody>
</table>
</div>
</Scrollbar>
) : (
<pre className="an-compute-code">{JSON.stringify(candidate.proposed_payload, null, 2)}</pre>
<Scrollbar className="an-compute-code-scroll" axis="x">
<pre className="an-compute-code">{JSON.stringify(candidate.proposed_payload, null, 2)}</pre>
</Scrollbar>
)}
{candidate.review_reason_code ? (
@@ -1042,7 +1044,7 @@ export function ComputeComparisonSettings({ active }: { active: boolean }) {
{revisions.length === 0 ? (
<p className="an-compute-lead">{t('暂无发布版本记录。', 'No revisions recorded yet.')}</p>
) : (
<div className="an-compute-table-wrap">
<Scrollbar className="an-compute-table-wrap" axis="x">
<table className="an-compute-table">
<thead>
<tr>
@@ -1073,7 +1075,7 @@ export function ComputeComparisonSettings({ active }: { active: boolean }) {
))}
</tbody>
</table>
</div>
</Scrollbar>
)}
</>}
</fieldset>
+50 -63
View File
@@ -10,7 +10,6 @@ import {
Globe2,
KeyRound,
Layers,
Maximize2,
PlugZap,
Power,
RefreshCw,
@@ -37,6 +36,7 @@ import { describeApiError, describeApiValue } from '../../i18n/api-errors'
import { translateLegacyAdminText } from '../../i18n/LegacyI18nBridge'
import { normalizeLocale } from '../../i18n/locale'
import { useAuthStore } from '../../stores/auth'
import Scrollbar from '../../components/Scrollbar/Scrollbar'
import { formatDateTimeZhCN, parseBackendDate } from '../../utils/datetime'
import { DataTable } from '../components/data-table/DataTable'
import { AdminLayout } from '../components/layout/AdminLayout'
@@ -1545,9 +1545,6 @@ function DashboardContent() {
</div>
<div className="an-dash-card__head-right">
{renderAssetDimTabs()}
<span className="an-dash-expand-cue" aria-hidden="true">
<Maximize2 size={13} />
</span>
</div>
</div>
<DashboardHorizontalBarChart
@@ -1571,9 +1568,6 @@ function DashboardContent() {
</div>
<div className="an-dash-card__head-right">
{renderRuntimeTabs()}
<span className="an-dash-expand-cue" aria-hidden="true">
<Maximize2 size={13} />
</span>
</div>
</div>
@@ -1651,9 +1645,6 @@ function DashboardContent() {
</div>
<div className="an-dash-card__head-right">
{renderOpsTabs()}
<span className="an-dash-expand-cue" aria-hidden="true">
<Maximize2 size={13} />
</span>
</div>
</div>
@@ -1709,7 +1700,7 @@ function DashboardContent() {
</div>
</div>
<div className="an-dash-hairline-list">
<Scrollbar className="an-dash-hairline-list" axis="y">
{opsTab === 'datasources' ? (
previewList.length > 0 ? (
(previewList as DashboardDatasourceRow[]).map((item) => {
@@ -1786,7 +1777,7 @@ function DashboardContent() {
) : (
<div className="an-dash-chart-empty">暂无采集器</div>
)}
</div>
</Scrollbar>
</div>
)
}
@@ -1812,13 +1803,10 @@ function DashboardContent() {
: '0 活跃告警'}
</span>
</span>
<span className="an-dash-expand-cue" aria-hidden="true">
<Maximize2 size={13} />
</span>
</div>
</div>
<div className="an-dash-hairline-list">
<Scrollbar className="an-dash-hairline-list" axis="y">
{activeAlerts.slice(0, 3).map((item) => {
const sev = alertSeverityBadge(item.severity)
return (
@@ -1862,7 +1850,7 @@ function DashboardContent() {
</div>
</div>
))}
</div>
</Scrollbar>
</div>
)
}
@@ -2169,7 +2157,7 @@ function DashboardContent() {
{isEnglish ? `${systemChannels.length} channels` : `${systemChannels.length} 条通道`}
</span>
</div>
<div className="an-dash-hairline-list">
<Scrollbar className="an-dash-hairline-list" axis="y">
{systemChannels.map((ch) => (
<div key={`hero-${ch.key}`} className="an-dash-hairline-row">
<div className="an-dash-hairline-row__main">
@@ -2180,7 +2168,7 @@ function DashboardContent() {
<span className={`an-dash-status-inline is-${ch.tone}`}>{ch.status}</span>
</div>
))}
</div>
</Scrollbar>
</div>
<div className="an-dash-hero__table">
@@ -2263,61 +2251,60 @@ function DashboardContent() {
{error ? <div className="an-alert an-alert--error">{error}</div> : null}
<div ref={stageRef} className="an-dash-stage" data-layout={activeHero ? 'focused' : 'bento'}>
<div className="an-dash-dock">
{dockedCards.map((card) => (
<section
key={card.id}
data-card-id={card.id}
className="an-dash-card is-docked"
role="button"
tabIndex={0}
aria-label={card.title}
onClick={() => switchFocus(card.id)}
onKeyDown={(event) => handleCardKeyDown(event, card.id)}
>
<div className="an-dash-card__dock">
<div className="an-dash-card__head">
<div className="an-dash-card__title">
<span className="an-dash-card__icon">{card.icon}</span>
<h2>{card.title}</h2>
</div>
<span className="an-dash-expand-cue" aria-hidden="true">
<Maximize2 size={13} />
</span>
</div>
<div className="an-dash-kpi-line">
<span className="an-dash-kpi-line__value">{card.dockKpi}</span>
<span className="an-dash-kpi-line__meta">{card.dockSub}</span>
</div>
</div>
</section>
))}
</div>
<div className="an-dash-hero-slot">
{activeHero ? (
<section key={activeHero.id} data-card-id={activeHero.id} className="an-dash-card is-hero">
{renderHeroBody(activeHero)}
</section>
) : (
cardDescriptors.map((card) => (
<Scrollbar className="an-dash-stage-scroll" axis="y">
<div ref={stageRef} className="an-dash-stage" data-layout={activeHero ? 'focused' : 'bento'}>
<div className="an-dash-dock">
{dockedCards.map((card) => (
<section
key={card.id}
data-card-id={card.id}
className="an-dash-card is-bento"
className="an-dash-card is-docked"
role="button"
tabIndex={0}
aria-label={card.title}
onClick={() => switchFocus(card.id)}
onKeyDown={(event) => handleCardKeyDown(event, card.id)}
>
{renderBentoCardBody(card)}
<div className="an-dash-card__dock">
<div className="an-dash-card__head">
<div className="an-dash-card__title">
<span className="an-dash-card__icon">{card.icon}</span>
<h2>{card.title}</h2>
</div>
</div>
<div className="an-dash-kpi-line">
<span className="an-dash-kpi-line__value">{card.dockKpi}</span>
<span className="an-dash-kpi-line__meta">{card.dockSub}</span>
</div>
</div>
</section>
))
)}
))}
</div>
<div className="an-dash-hero-slot">
{activeHero ? (
<section key={activeHero.id} data-card-id={activeHero.id} className="an-dash-card is-hero">
{renderHeroBody(activeHero)}
</section>
) : (
cardDescriptors.map((card) => (
<section
key={card.id}
data-card-id={card.id}
className="an-dash-card is-bento"
role="button"
tabIndex={0}
aria-label={card.title}
onClick={() => switchFocus(card.id)}
onKeyDown={(event) => handleCardKeyDown(event, card.id)}
>
{renderBentoCardBody(card)}
</section>
))
)}
</div>
</div>
</div>
</Scrollbar>
{stats?.last_updated ? (
<div className="an-page__footer-note">
+79 -125
View File
@@ -1,14 +1,17 @@
import type { ColumnDef } from '@tanstack/react-table'
import axios from 'axios'
import { Download, RefreshCw, RotateCcw, Search, X } from 'lucide-react'
import { useCallback, useEffect, useMemo, useRef, useState, type CSSProperties, type PointerEvent as ReactPointerEvent } from 'react'
import { useCallback, useEffect, useMemo, useRef, useState, type CSSProperties } from 'react'
import { useTranslation } from 'react-i18next'
import { useSearchParams } from 'react-router-dom'
import Scrollbar from '../../components/Scrollbar/Scrollbar'
import { formatDateTimeZhCN, formatDateZhCN, parseBackendDate } from '../../utils/datetime'
import { describeApiError } from '../../i18n/api-errors'
import { normalizeLocale } from '../../i18n/locale'
import { parseBackendDate } from '../../utils/datetime'
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 { SplitPaneResizer, useSplitPaneResize } 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'
@@ -19,6 +22,7 @@ import { useToast } from '../components/ui/toast'
import { ComputeLedger } from './data-ledger/ComputeLedger'
import { LayerItemsLedger } from './data-ledger/LayerItemsLedger'
import { LayerNav } from './data-ledger/LayerNav'
import { formatLedgerCountry, formatLedgerDate } from './data-ledger/ledger-display'
import type { LedgerLayerSummary } from './data-ledger/ledger-model'
import { formatDataTypeLabel } from './dashboardHelpers'
@@ -53,27 +57,18 @@ interface SourceOption {
}
const DETAIL_BASE_FIELDS = ['source', 'data_type', 'source_id', 'country', 'city', 'collected_at', 'reference_date']
const DETAIL_FIELD_LABELS: Record<string, string> = {
source: '数据源',
data_type: '数据类型',
source_id: '原始 ID',
country: '国家',
city: '城市',
collected_at: '采集时间',
reference_date: '参考日期',
}
function formatFieldLabel(key: string) {
return DETAIL_FIELD_LABELS[key] || key.split('_').filter(Boolean).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join(' ')
return key.split('_').filter(Boolean).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join(' ')
}
function formatDetailValue(key: string, value: unknown) {
function formatDetailValue(key: string, value: unknown, isEnglish: boolean) {
if (value === null || value === undefined || value === '') return '-'
if (key === 'data_type') return formatDataTypeLabel(String(value), false)
if (key === 'data_type') return formatDataTypeLabel(String(value), isEnglish)
if (key === 'country') return formatLedgerCountry(String(value), isEnglish)
if (key === 'collected_at' || key === 'reference_date') {
const date = parseBackendDate(String(value))
if (!date || Number.isNaN(date.getTime())) return String(value)
return key === 'reference_date' ? formatDateZhCN(String(value)) : formatDateTimeZhCN(String(value))
const dateValue = String(value)
if (!parseBackendDate(dateValue)) return dateValue
return formatLedgerDate(dateValue, isEnglish, key === 'reference_date')
}
if (typeof value === 'object') return JSON.stringify(value, null, 2)
return String(value)
@@ -96,21 +91,26 @@ function typeTone(type: string) {
}
export default function DataList() {
const { t, i18n } = useTranslation()
const locale = normalizeLocale(i18n.resolvedLanguage || i18n.language)
const isEnglish = locale === 'en-US'
const { toast } = useToast()
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 summaryResize = useSplitPaneResize({
storageKey: 'planet.admin.dataSummaryWidth',
defaultWidth: 260,
minWidth: 220,
maxWidth: 420,
minOppositeWidth: 420,
side: 'left',
containerRef: dataLayoutRef,
cssVarName: '--an-data-summary-width',
})
const [sourceFilter, setSourceFilter] = useState(() => searchParams.get('source') || '')
const [typeFilter, setTypeFilter] = useState(() => searchParams.get('type') || '')
@@ -146,52 +146,6 @@ export default function DataList() {
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 })
window.addEventListener('pointercancel', stopMove, { once: true })
}, [])
useEffect(() => {
const trimmed = searchText.trim()
if (!trimmed) {
@@ -229,11 +183,11 @@ export default function DataList() {
(error: unknown) => {
toast({
tone: 'error',
title: '加载采集数据失败',
description: error instanceof Error ? error.message : '请稍后重试',
title: t('dataLedger.loadRawFailed'),
description: describeApiError(error, t('dataLedger.retry')),
})
},
[toast],
[t, toast],
)
const {
@@ -312,21 +266,21 @@ export default function DataList() {
link.click()
link.remove()
window.URL.revokeObjectURL(url)
toast({ tone: 'success', title: `已导出 ${format.toUpperCase()}` })
toast({ tone: 'success', title: t('dataLedger.exported', { format: format.toUpperCase() }) })
} catch (error) {
toast({ tone: 'error', title: '导出失败', description: error instanceof Error ? error.message : '请稍后重试' })
toast({ tone: 'error', title: t('dataLedger.exportFailed'), description: describeApiError(error, t('dataLedger.retry')) })
}
}
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: formatDataTypeLabel(type, false), value: type }))]
const countryOptions = [{ value: 'all', label: '全部国家/地区' }, ...countries.map((country) => ({ label: country, value: country }))]
const sourceOptions = [{ value: 'all', label: t('dataLedger.allSources') }, ...sources.map((source) => ({ label: source.source_name, value: source.source }))]
const typeOptions = [{ value: 'all', label: t('dataLedger.allTypes') }, ...types.map((type) => ({ label: formatDataTypeLabel(type, isEnglish), value: type }))]
const countryOptions = [{ value: 'all', label: t('dataLedger.allCountries') }, ...countries.map((country) => ({ label: formatLedgerCountry(country, isEnglish), value: country }))]
const columns = useMemo<Array<ColumnDef<CollectedData>>>(() => [
{
accessorKey: 'name',
header: '名称',
header: t('dataLedger.column.name'),
size: 320,
cell: ({ row }) => (
<button
@@ -343,7 +297,7 @@ export default function DataList() {
},
{
accessorKey: 'source',
header: '数据源',
header: t('dataLedger.column.source'),
size: 180,
cell: ({ row }) => row.original.source
? <Badge tone={sourceTone(row.original.source)} title={row.original.source}>{row.original.source_name || row.original.source}</Badge>
@@ -351,39 +305,39 @@ export default function DataList() {
},
{
accessorKey: 'data_type',
header: '数据类型',
header: t('dataLedger.column.data_type'),
size: 160,
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> : '-',
cell: ({ row }) => row.original.data_type ? <Badge tone={typeTone(row.original.data_type)} title={row.original.data_type}>{formatDataTypeLabel(row.original.data_type, isEnglish)}</Badge> : '-',
},
{
accessorKey: 'collected_at',
header: '采集时间',
header: t('dataLedger.column.collected_at'),
size: 180,
cell: ({ row }) => formatDateTimeZhCN(row.original.collected_at),
cell: ({ row }) => formatLedgerDate(row.original.collected_at, isEnglish),
},
{
accessorKey: 'reference_date',
header: '参考日期',
header: t('dataLedger.column.reference_date'),
size: 140,
cell: ({ row }) => formatDateZhCN(row.original.reference_date),
cell: ({ row }) => formatLedgerDate(row.original.reference_date, isEnglish, true),
},
], [])
], [isEnglish, t])
const detailBaseItems = useMemo(() => {
if (!detailData) return []
return DETAIL_BASE_FIELDS.map((key) => ({
key,
label: formatFieldLabel(key),
value: formatDetailValue(key, key === 'source' ? detailData.source_name || detailData.source : detailData[key as keyof CollectedData]),
label: t('dataLedger.column.' + key, { defaultValue: formatFieldLabel(key) }),
value: formatDetailValue(key, key === 'source' ? detailData.source_name || detailData.source : detailData[key as keyof CollectedData], isEnglish),
})).filter((item) => item.value !== '-')
}, [detailData])
}, [detailData, isEnglish, t])
const detailMetadataItems = useMemo(() => {
if (!detailData?.metadata) return []
return Object.entries(detailData.metadata)
.filter(([key]) => key !== '_detail_url')
.map(([key, value]) => ({ key, label: formatFieldLabel(key), value: formatDetailValue(key, value), isBlock: typeof value === 'object' && value !== null }))
}, [detailData])
.map(([key, value]) => ({ key, label: t('dataLedger.column.' + key, { defaultValue: formatFieldLabel(key) }), value: formatDetailValue(key, value, isEnglish), isBlock: typeof value === 'object' && value !== null }))
}, [detailData, isEnglish, t])
const activeLayerMeta = useMemo(
() => layers.find((item) => item.id === activeLayer),
@@ -395,18 +349,18 @@ export default function DataList() {
<div className="an-page an-data-page">
<div className="an-page__header">
<div>
<h1>采集数据</h1>
<p>按地球图层分类复核基础设施、台账与原始采集元数据。</p>
<h1>{t('dataLedger.title')}</h1>
<p>{t('dataLedger.description')}</p>
</div>
{activeLayer === 'raw' ? (
<div className="an-toolbar">
<Badge tone="blue">{`结果 ${total.toLocaleString()} 条`}</Badge>
<Badge tone="slate">{`筛选 ${rawActiveFilterCount} 项`}</Badge>
<Badge tone="blue">{t('dataLedger.resultCount', { total: total.toLocaleString(locale) })}</Badge>
<Badge tone="slate">{t('dataLedger.filterCount', { count: rawActiveFilterCount })}</Badge>
</div>
) : null}
</div>
<div ref={dataLayoutRef} className="an-data-layout" style={{ '--an-data-summary-width': `${summaryWidth}px` } as CSSProperties}>
<div ref={dataLayoutRef} className="an-data-layout" style={{ '--an-data-summary-width': `${summaryResize.width}px` } as CSSProperties}>
<LayerNav
layers={layers}
activeLayer={activeLayer}
@@ -414,12 +368,12 @@ export default function DataList() {
onSelectLayer={handleSelectLayer}
/>
<button
type="button"
className="an-detail-resizer an-data-resizer"
onPointerDown={startSummaryResize}
aria-label="拖动调整图层导航宽度"
title="拖动调整图层导航宽度"
<SplitPaneResizer
label={t('dataLedger.resizeLayerNav')}
className="an-data-resizer"
isDragging={summaryResize.isDragging}
onPointerDown={summaryResize.onPointerDown}
onKeyDown={summaryResize.onKeyDown}
/>
{activeLayer === 'compute' ? (
@@ -428,13 +382,13 @@ export default function DataList() {
<Card className="an-data-table-card">
<CardHeader className="an-data-table-card__header">
<div>
<CardTitle>数据列表</CardTitle>
<p>{`共 ${total.toLocaleString()} 条结果`}</p>
<CardTitle>{t('dataLedger.list')}</CardTitle>
<p>{t('dataLedger.results', { total: total.toLocaleString(locale) })}</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>
<Button size="sm" variant="subtle" onClick={() => void fetchRawData()}><RefreshCw size={14} />{t('dataLedger.refresh')}</Button>
<Button size="sm" variant="subtle" onClick={() => void downloadExport('json')} title={t('dataLedger.exportFile', { format: 'JSON' })}><Download size={14} />JSON</Button>
<Button size="sm" variant="subtle" onClick={() => void downloadExport('csv')} title={t('dataLedger.exportFile', { format: 'CSV' })}><Download size={14} />CSV</Button>
</div>
</CardHeader>
<CardContent>
@@ -464,8 +418,8 @@ export default function DataList() {
<div className="an-search-box an-search-box--inline">
<Search size={14} aria-hidden="true" />
<Input
placeholder="搜索名称、描述、元数据等"
aria-label="搜索名称、描述、元数据等"
placeholder={t('dataLedger.rawSearch')}
aria-label={t('dataLedger.rawSearch')}
value={searchText}
onChange={(event) => setSearchText(event.target.value)}
/>
@@ -474,8 +428,8 @@ export default function DataList() {
size="icon"
variant="ghost"
onClick={() => setSearchText('')}
title="清空搜索"
aria-label="清空搜索"
title={t('dataLedger.clearSearch')}
aria-label={t('dataLedger.clearSearch')}
>
<X size={14} />
</Button>
@@ -486,8 +440,8 @@ export default function DataList() {
variant="subtle"
onClick={handleReset}
disabled={rawActiveFilterCount === 0}
title="重置筛选"
aria-label="重置筛选"
title={t('dataLedger.resetFilters')}
aria-label={t('dataLedger.resetFilters')}
>
<RotateCcw size={14} />
</Button>
@@ -515,25 +469,25 @@ export default function DataList() {
<LayerItemsLedger
key={activeLayer}
layerId={activeLayer}
layerName={activeLayerMeta?.name || activeLayer}
layerName={t('dataLedger.layer.' + activeLayer, { defaultValue: activeLayerMeta?.name || activeLayer })}
initialKinds={activeLayerMeta?.kinds || []}
/>
)}
</div>
</div>
<Dialog title="数据详情" open={detailVisible} onOpenChange={setDetailVisible} width={880}>
<Dialog title={t('dataLedger.rawDetail')} open={detailVisible} onOpenChange={setDetailVisible} width={880}>
{detailLoading ? (
<div className="an-loading"><span className="an-spinner" />加载中</div>
<div className="an-loading"><span className="an-spinner" />{t('common.loading')}</div>
) : detailData ? (
<div className="an-detail">
<section className="an-detail__hero">
<span>名称</span>
<span>{t('dataLedger.column.name')}</span>
<h2>{detailData.name || '-'}</h2>
</section>
{detailBaseItems.length > 0 ? (
<section className="an-detail__section">
<h3>基础信息</h3>
<h3>{t('dataLedger.basicInfo')}</h3>
<div className="an-detail__grid">
{detailBaseItems.map((item) => (
<div key={item.key}>
@@ -546,7 +500,7 @@ export default function DataList() {
) : null}
{detailMetadataItems.length > 0 ? (
<section className="an-detail__section">
<h3>扩展字段</h3>
<h3>{t('dataLedger.extraFields')}</h3>
<div className="an-detail__grid">
{detailMetadataItems.map((item) => (
<div key={item.key} className={item.isBlock ? 'is-block' : undefined}>
@@ -562,14 +516,14 @@ export default function DataList() {
</section>
) : null}
<section className="an-detail__section">
<h3>原始元数据</h3>
<h3>{t('dataLedger.rawMetadata')}</h3>
<Scrollbar className="an-code-scroll">
<pre className="an-json-view">{JSON.stringify(detailData.metadata || {}, null, 2)}</pre>
</Scrollbar>
</section>
</div>
) : (
<div className="an-empty">暂无数据</div>
<div className="an-empty">{t('common.noData')}</div>
)}
</Dialog>
</AdminLayout>
+3 -1
View File
@@ -673,7 +673,9 @@ export default function Logs() {
{event.occurrence_count > 1 ? <Badge tone="blue">{`${event.occurrence_count} 次`}</Badge> : null}
</div>
<p>{event.message}</p>
<pre>{stringifyContext(event.context)}</pre>
<Scrollbar className="an-log-occurrence__scroll">
<pre>{stringifyContext(event.context)}</pre>
</Scrollbar>
</div>
))}
{!groupEvents.length ? <EmptyState title="暂无发生明细" /> : null}
+76 -62
View File
@@ -43,7 +43,7 @@ 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 { 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'
@@ -836,12 +836,23 @@ function defaultColumns(onSelect: (record: TableRecord) => void, locale: Support
}
const EMPTY_TABLE_ROWS: TableRecord[] = []
const HIDDEN_DATASOURCE_COLUMNS_NONE: readonly string[] = []
const HIDDEN_DATASOURCE_COLUMNS_TABLET: readonly string[] = ['module']
const HIDDEN_DATASOURCE_COLUMNS_MOBILE: readonly string[] = ['module', 'metric', 'updated']
function getResponsiveColumnTier(): 'desktop' | 'tablet' | 'mobile' {
if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return 'desktop'
if (window.matchMedia('(max-width: 760px)').matches) return 'mobile'
if (window.matchMedia('(max-width: 1024px)').matches) return 'tablet'
return 'desktop'
}
const ModuleTable = memo(function ModuleTable({
rows,
selectedRowId,
onSelect,
columns,
hiddenColumnIds,
selection,
loading,
columnWidthStorageKey,
@@ -851,6 +862,7 @@ const ModuleTable = memo(function ModuleTable({
selectedRowId?: string | null
onSelect: (record: TableRecord) => void
columns?: Array<ColumnDef<TableRecord>>
hiddenColumnIds?: readonly string[]
selection?: {
selectedRowIds: Set<string>
onToggleAllVisible: (rowIds: string[]) => void
@@ -876,6 +888,7 @@ const ModuleTable = memo(function ModuleTable({
<DataTable
className={`an-resource-table${className ? ` ${className}` : ''}`}
columns={tableColumns}
hiddenColumnIds={hiddenColumnIds}
data={rows}
emptyText={localizeAdminText('当前模块暂无数据', locale)}
getRowClassName={getRowClassName}
@@ -2813,15 +2826,42 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
const [selectedHistory, setSelectedHistory] = useState<TableRecord[]>([])
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)
const [responsiveColumnTier, setResponsiveColumnTier] = useState<'desktop' | 'tablet' | 'mobile'>(
getResponsiveColumnTier,
)
useEffect(() => () => {
detailResizeCleanupRef.current?.()
useEffect(() => {
if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return
const mqTablet = window.matchMedia('(max-width: 1024px)')
const mqMobile = window.matchMedia('(max-width: 760px)')
const handleTierChange = () => {
setResponsiveColumnTier(mqMobile.matches ? 'mobile' : mqTablet.matches ? 'tablet' : 'desktop')
}
handleTierChange()
mqTablet.addEventListener('change', handleTierChange)
mqMobile.addEventListener('change', handleTierChange)
return () => {
mqTablet.removeEventListener('change', handleTierChange)
mqMobile.removeEventListener('change', handleTierChange)
}
}, [])
const hiddenDatasourceColumns = useMemo(() => {
if (responsiveColumnTier === 'mobile') return HIDDEN_DATASOURCE_COLUMNS_MOBILE
if (responsiveColumnTier === 'tablet') return HIDDEN_DATASOURCE_COLUMNS_TABLET
return HIDDEN_DATASOURCE_COLUMNS_NONE
}, [responsiveColumnTier])
const resourceLayoutRef = useRef<HTMLDivElement | null>(null)
const detailResize = useSplitPaneResize({
storageKey: 'planet.admin.resourceDetailWidth',
defaultWidth: 360,
minWidth: 300,
maxWidth: 640,
minOppositeWidth: 420,
side: 'right',
containerRef: resourceLayoutRef,
cssVarName: '--an-detail-width',
})
const hierarchyLayoutRef = useRef<HTMLDivElement | null>(null)
const hierarchyResize = useSplitPaneResize({
storageKey: 'planet.admin.hierarchyWidth',
@@ -2851,52 +2891,6 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
run: () => Promise<void>
}>(null)
const startDetailResize = useCallback((event: ReactPointerEvent<HTMLButtonElement>) => {
event.preventDefault()
detailResizeCleanupRef.current?.()
const startX = event.clientX
const startWidth = detailWidthRef.current
let latestWidth = startWidth
let rafId = 0
const applyFrame = () => {
rafId = 0
resourceLayoutRef.current?.style.setProperty('--an-detail-width', `${latestWidth}px`)
}
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()
const dialog = event.currentTarget.closest<HTMLElement>('.an-guide-modal')
@@ -3444,6 +3438,18 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
setMobileResourceDetailOpen(Boolean(record))
}, [])
useEffect(() => {
if (!mobileResourceDetailOpen && !mobileHierarchyDetailOpen) return
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === 'Escape') {
setMobileResourceDetailOpen(false)
setMobileHierarchyDetailOpen(false)
}
}
window.addEventListener('keydown', handleKeyDown)
return () => window.removeEventListener('keydown', handleKeyDown)
}, [mobileHierarchyDetailOpen, mobileResourceDetailOpen])
const goBackResourceDetail = () => {
setSelectedHistory((history) => {
const previous = history[history.length - 1]
@@ -7732,7 +7738,7 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
<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}
style={{ '--an-detail-width': `${detailResize.width}px` } as CSSProperties}
>
<Panel className="an-resource-main">
<div className="an-panel-heading">
@@ -7752,6 +7758,7 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
selectedRowId={selected?.__rowId ?? null}
onSelect={openResourceDetail}
columns={isDatasourceBuiltinSection ? datasourceColumns : config.columns}
hiddenColumnIds={isDatasourceBuiltinSection ? hiddenDatasourceColumns : undefined}
loading={loading && rows.length === 0}
columnWidthStorageKey={`planet.table.widths.resource.${activeSection?.key || config.listTitle}`}
selection={datasourceSelection}
@@ -7762,14 +7769,21 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
</div>
</Panel>
<button
type="button"
className="an-detail-resizer"
onPointerDown={startDetailResize}
aria-label="拖动调整详情宽度"
title="拖动调整详情宽度"
<SplitPaneResizer
label="拖动调整详情宽度"
isDragging={detailResize.isDragging}
onPointerDown={detailResize.onPointerDown}
onKeyDown={detailResize.onKeyDown}
/>
{mobileResourceDetailOpen ? (
<div
className="an-resource-drawer-backdrop"
aria-hidden="true"
onClick={() => setMobileResourceDetailOpen(false)}
/>
) : null}
<div className="an-resource-side">
<div className="an-mobile-detail-bar">
<Button size="icon" variant="subtle" title={localizeAdminText('返回列表', locale)} aria-label={localizeAdminText('返回列表', locale)} onClick={() => setMobileResourceDetailOpen(false)}><ArrowLeft size={15} /></Button>
@@ -7826,7 +7840,7 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
confirmLabel: '重置',
run: () => loadCredentialGuide(credentialGuideProviderName, 'reset'),
})} loading={actionLoading}><RefreshCw size={15} /></Button>
<Button size="icon" variant="subtle" title="关闭" aria-label="关闭" onClick={() => setCredentialGuideOpen(false)}>×</Button>
<Button size="icon" variant="subtle" title="关闭" aria-label="关闭" onClick={() => setCredentialGuideOpen(false)}><X size={16} /></Button>
</div>
</div>
<Scrollbar className="an-guide-modal__body">
+8 -8
View File
@@ -21,21 +21,21 @@
.an-card-images-field .an-input,.an-card-images-field .an-select { width:100%; min-width:0; }
.an-card-images-field input[type=range] { width:100%; }
.an-card-images-editor-actions { display:flex; flex-wrap:wrap; align-items:center; justify-content:space-between; gap:12px; margin-top:16px; }
.an-card-images-error,.an-card-images-message { margin:0; padding:8px 16px; overflow-wrap:anywhere; }
.an-card-images-error { color:var(--an-danger,#b42318); max-height:90px; overflow:auto; scrollbar-width:thin; scrollbar-color:var(--an-border-strong) transparent; }
.an-card-images-error::-webkit-scrollbar { width:6px; height:6px; }
.an-card-images-error::-webkit-scrollbar-button { display:none; width:0; height:0; }
.an-card-images-error::-webkit-scrollbar-track { background:transparent; }
.an-card-images-error::-webkit-scrollbar-thumb { border-radius:999px; background:var(--an-border-strong); }
.an-card-images-message { margin:0; padding:8px 16px; overflow-wrap:anywhere; }
.an-card-images-error { flex:0 0 auto; color:var(--an-danger,#b42318); }
.an-card-images-error > .tui-scrollbar__viewport { max-height:90px; padding:8px 16px; }
.an-card-images-error__text { margin:0; overflow-wrap:anywhere; }
.an-card-image-preview { max-width:440px; background:#091525; color:#e9f1fa; border:1px solid #315062; margin:16px 0; font-size:12px; }
.an-card-image-preview__title { background:#103546; padding:12px; font-weight:600; }
.an-card-image-preview__rows { padding:10px 14px; min-height:220px; }
.an-card-image-preview__rows>div { display:flex; align-items:flex-start; justify-content:space-between; gap:20px; border-bottom:1px solid rgba(255,255,255,.08); padding:12px 0; }
.an-card-image-preview__rows span { color:#a1b2c5; flex-shrink:0; }
.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); }
@media(max-width:1024px) {
.an-card-images-workspace { grid-template-columns:1fr; grid-template-rows:minmax(110px,28%) 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); }
}
@media(max-width:760px) {
.an-card-images-fields { grid-template-columns:1fr; }
}
+11 -17
View File
@@ -20,8 +20,10 @@
border-bottom: 1px solid var(--an-border);
flex: 0 0 auto;
}
.an-compute-status, .an-compute-error { padding: 8px 16px; margin: 0; overflow-wrap: anywhere; flex: 0 0 auto; }
.an-compute-error { color: var(--an-danger, #b42318); max-height: 96px; overflow: auto; scrollbar-width: thin; scrollbar-color: var(--an-border-strong) transparent; }
.an-compute-status { padding: 8px 16px; margin: 0; overflow-wrap: anywhere; flex: 0 0 auto; }
.an-compute-error { flex: 0 0 auto; color: var(--an-danger, #b42318); }
.an-compute-error > .tui-scrollbar__viewport { max-height: 96px; padding: 8px 16px; }
.an-compute-error__text { margin: 0; overflow-wrap: anywhere; }
.an-compute-scroll { flex: 1; min-height: 0; min-width: 0; }
.an-compute-content { min-width: 0; margin: 0; padding: 12px 16px 20px; border: 0; }
.an-compute-lead { margin: 8px 0 12px; font-size: 13px; color: var(--an-muted, #94a3b8); line-height: 1.5; }
@@ -119,7 +121,6 @@
}
.an-compute-table-wrap {
width: 100%;
overflow-x: auto;
}
.an-compute-table {
width: 100%;
@@ -153,26 +154,19 @@
padding-top: 4px;
border-top: 1px dashed var(--an-border);
}
.an-compute-code {
margin: 0;
padding: 8px 10px;
.an-compute-code-scroll {
border-radius: 6px;
border: 1px solid var(--an-border);
background: var(--an-bg-subtle, var(--an-surface));
}
.an-compute-code {
margin: 0;
padding: 8px 10px;
color: var(--an-text);
font-size: 12px;
overflow-x: auto;
scrollbar-width: thin;
scrollbar-color: var(--an-border-strong) transparent;
width: max-content;
min-width: 100%;
}
.an-compute-error::-webkit-scrollbar,
.an-compute-code::-webkit-scrollbar { width: 6px; height: 6px; }
.an-compute-error::-webkit-scrollbar-button,
.an-compute-code::-webkit-scrollbar-button { display: none; width: 0; height: 0; }
.an-compute-error::-webkit-scrollbar-track,
.an-compute-code::-webkit-scrollbar-track { background: transparent; }
.an-compute-error::-webkit-scrollbar-thumb,
.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); }
+74 -13
View File
@@ -1,4 +1,6 @@
import { useState, type CSSProperties, type MouseEvent } from 'react'
import { useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type MouseEvent } from 'react'
import { createPortal } from 'react-dom'
import { clampTooltipCoords, getTooltipViewportBounds } from '../../components/tactile-ui'
import { formatNumber } from '../utils'
import type {
AssetDistributionItem,
@@ -13,26 +15,85 @@ interface ChartTooltipState {
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 (
function positionChartTooltip(
tip: ChartTooltipState,
tipWidth: number,
tipHeight: number,
element?: Element | null,
): { left: number; top: number } {
const gap = 12
const bounds = getTooltipViewportBounds(8, element)
const rightX = tip.x + gap
const leftX = tip.x - tipWidth - gap
const preferredLeft = rightX + tipWidth > bounds.maxX && leftX >= bounds.minX ? leftX : rightX
const aboveY = tip.y - tipHeight - gap
const belowY = tip.y + gap + 4
const preferredTop = aboveY < bounds.minY && belowY + tipHeight <= bounds.maxY ? belowY : aboveY
return clampTooltipCoords(preferredLeft, preferredTop, tipWidth, tipHeight, 8, element)
}
function DashboardChartTooltip({
tip,
onDismiss,
}: {
tip: ChartTooltipState | null
onDismiss: () => void
}) {
const tooltipRef = useRef<HTMLDivElement | null>(null)
const [coords, setCoords] = useState<{ left: number; top: number } | null>(null)
useLayoutEffect(() => {
if (!tip) {
setCoords(null)
return
}
const rect = tooltipRef.current?.getBoundingClientRect()
const tipWidth = rect && rect.width > 0 ? rect.width : 200
const tipHeight = rect && rect.height > 0 ? rect.height : 44
setCoords(positionChartTooltip(tip, tipWidth, tipHeight, tooltipRef.current))
}, [tip])
useEffect(() => {
if (!tip) return
const handleDismiss = () => onDismiss()
window.addEventListener('scroll', handleDismiss, true)
window.addEventListener('wheel', handleDismiss, { passive: true })
window.addEventListener('resize', handleDismiss)
window.addEventListener('blur', handleDismiss)
const vv = window.visualViewport
vv?.addEventListener('resize', handleDismiss)
vv?.addEventListener('scroll', handleDismiss)
return () => {
window.removeEventListener('scroll', handleDismiss, true)
window.removeEventListener('wheel', handleDismiss)
window.removeEventListener('resize', handleDismiss)
window.removeEventListener('blur', handleDismiss)
vv?.removeEventListener('resize', handleDismiss)
vv?.removeEventListener('scroll', handleDismiss)
}
}, [onDismiss, tip])
if (!tip || typeof document === 'undefined') return null
const resolved = coords ?? positionChartTooltip(tip, 200, 44)
return createPortal(
<div
ref={tooltipRef}
className="an-dash-tooltip is-visible"
role="status"
aria-live="polite"
style={
{
'--an-tip-x': `${clampedX}px`,
'--an-tip-y': `${clampedY}px`,
'--an-tip-x': `${resolved.left}px`,
'--an-tip-y': `${resolved.top}px`,
} as CSSProperties
}
>
<div className="an-dash-tooltip__title">{tip.title}</div>
<div className="an-dash-tooltip__body">{tip.body}</div>
</div>
</div>,
document.body,
)
}
@@ -180,7 +241,7 @@ export function DashboardHorizontalBarChart({
)
})}
</svg>
<DashboardChartTooltip tip={tip} />
<DashboardChartTooltip tip={tip} onDismiss={() => setTip(null)} />
</div>
)
}
@@ -340,7 +401,7 @@ export function DashboardTaskTrendChart({
/>
))}
</svg>
<DashboardChartTooltip tip={tip} />
<DashboardChartTooltip tip={tip} onDismiss={() => setTip(null)} />
</div>
)
}
@@ -486,7 +547,7 @@ export function DashboardLayerDonutChart({
) : null}
</div>
</div>
<DashboardChartTooltip tip={tip} />
<DashboardChartTooltip tip={tip} onDismiss={() => setTip(null)} />
</div>
)
}
@@ -2,9 +2,11 @@ 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 { useTranslation } from 'react-i18next'
import { useNavigate } from 'react-router-dom'
import Scrollbar from '../../../components/Scrollbar/Scrollbar'
import { formatDateTimeZhCN } from '../../../utils/datetime'
import { describeApiError, describeApiValue } from '../../../i18n/api-errors'
import { normalizeLocale } from '../../../i18n/locale'
import { DataTable } from '../../components/data-table/DataTable'
import { useWaterfallQuery } from '../../components/data-table/useWaterfallQuery'
import { Badge } from '../../components/ui/badge'
@@ -16,21 +18,20 @@ 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 { formatLedgerCountry, formatLedgerDate } from './ledger-display'
import {
COMPUTE_SITE_TYPE_LABELS,
COMPUTE_SITE_TYPE_ORDER,
COMPUTE_STATUS_BUCKET_META,
EDITABLE_PRECISION_OPTIONS,
PRECISION_LABELS,
TERMINAL_STATUS_LABELS,
COMPUTE_STATUS_BUCKET_TONES,
EDITABLE_PRECISIONS,
type ComputeCandidate,
type ComputeLedgerResponse,
type ComputeLedgerRow,
type ComputeSiteType,
type ComputeStatusBucket,
} from './ledger-model'
export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
const { t, i18n } = useTranslation()
const locale = normalizeLocale(i18n.resolvedLanguage || i18n.language)
const isEnglish = locale === 'en-US'
const { toast } = useToast()
const navigate = useNavigate()
const [siteTypeFilter, setSiteTypeFilter] = useState('')
@@ -98,11 +99,11 @@ export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
(error: unknown) => {
toast({
tone: 'error',
title: '加载算力中心台账失败',
description: error instanceof Error ? error.message : '请稍后重试',
title: t('dataLedger.loadComputeFailed'),
description: describeApiError(error, t('dataLedger.retry')),
})
},
[toast],
[t, toast],
)
const {
@@ -153,12 +154,14 @@ export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
[row.source_id]: { items: candidates, workflowRunId: runId || null },
}))
if (data.success && candidates.length > 0) {
toast({ tone: 'success', title: `已获取 ${candidates.length} 个候选坐标`, description: '点击行可查看并采纳候选位置' })
toast({ tone: 'success', title: t('dataLedger.foundCandidates', { count: candidates.length }), description: t('dataLedger.adoptCandidatesHint') })
} 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 })
const label = t('dataLedger.terminal.' + data.terminal_status, { defaultValue: data.terminal_status })
toast({ tone: 'default', title: t('dataLedger.confirmedTerminal', { status: label }), description: data.failure_reason ? describeApiValue(data.failure_reason) : undefined })
} else {
toast({ tone: 'default', title: '未找到可用候选坐标', description: data.failure_reason || data.llm_failure_reason || undefined })
toast({ tone: 'default', title: t('dataLedger.noCandidates'), description: data.failure_reason || data.llm_failure_reason
? describeApiValue(data.failure_reason || data.llm_failure_reason)
: undefined })
}
setDetailRow({
...row,
@@ -172,8 +175,8 @@ export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
} catch (error) {
toast({
tone: 'error',
title: '重新定位失败',
description: error instanceof Error ? error.message : '请稍后重试',
title: t('dataLedger.relocateFailed'),
description: describeApiError(error, t('dataLedger.retry')),
})
} finally {
setRelocatingIds((prev) => {
@@ -182,7 +185,7 @@ export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
return next
})
}
}, [fetchComputeLedger, onMutated, toast])
}, [fetchComputeLedger, onMutated, t, toast])
const selectedRows = useMemo(
() => items.filter((row) => !row.is_anonymous_placeholder && selectedRowIds.has(`${row.source}:${row.source_id}`)),
@@ -294,12 +297,14 @@ export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
toast({
tone: failed > 0 && found === 0 ? 'error' : found > 0 ? 'success' : 'default',
title: batchStopRef.current
? `已停止批量定位(已完成 ${done} / ${queue.length} 条)`
: `批量定位完成:候选 ${found} 条,暂不可定位 ${terminal} 条,未命中 ${missed} 条${failed ? `,失败 ${failed} 条` : ''}`,
? t('dataLedger.stoppedBatch', { done, total: queue.length })
: t(failed ? 'dataLedger.finishedBatchWithFailures' : 'dataLedger.finishedBatch', {
found, terminal, missed, failed,
}),
})
await fetchComputeLedger()
onMutated?.()
}, [batchProgress?.running, fetchComputeLedger, onMutated, selectedRows, toast])
}, [batchProgress?.running, fetchComputeLedger, onMutated, selectedRows, t, toast])
const openEditDialog = useCallback((row: ComputeLedgerRow) => {
setEditTarget(row)
@@ -315,7 +320,7 @@ export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
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: '请输入有效的非零经纬度坐标' })
toast({ tone: 'error', title: t('dataLedger.invalidCoordinates') })
return
}
setSavingEdit(true)
@@ -333,15 +338,15 @@ export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
verification_status: 'verified',
needs_confirmation: false,
})
toast({ tone: 'success', title: '坐标已保存' })
toast({ tone: 'success', title: t('dataLedger.coordinatesSaved') })
setEditTarget(null)
await fetchComputeLedger()
onMutated?.()
} catch (error) {
toast({
tone: 'error',
title: '保存坐标失败',
description: error instanceof Error ? error.message : '请稍后重试',
title: t('dataLedger.saveCoordinatesFailed'),
description: describeApiError(error, t('dataLedger.retry')),
})
} finally {
setSavingEdit(false)
@@ -373,15 +378,15 @@ export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
needs_confirmation: false,
workflow_run_id: wfRunId || undefined,
})
toast({ tone: 'success', title: '已采纳候选坐标' })
toast({ tone: 'success', title: t('dataLedger.candidateAdopted') })
setDetailOpen(false)
await fetchComputeLedger()
onMutated?.()
} catch (error) {
toast({
tone: 'error',
title: '采纳候选失败',
description: error instanceof Error ? error.message : '请稍后重试',
title: t('dataLedger.adoptCandidateFailed'),
description: describeApiError(error, t('dataLedger.retry')),
})
} finally {
setAdoptingKey(null)
@@ -393,22 +398,26 @@ export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
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})` },
{ value: 'all', label: t('dataLedger.allStatuses') },
...Object.keys(COMPUTE_STATUS_BUCKET_TONES).map((value) => ({
value,
label: t('dataLedger.status.' + value) + ' (' + (byStatus[value] || 0).toLocaleString(locale) + ')',
})),
]
const countryOptions = useMemo(() => [
{ value: 'all', label: '全部国家/地区' },
...(payload?.countries || []).map((c) => ({ value: c, label: c })),
], [payload?.countries])
const countryOptions = [
{ value: 'all', label: t('dataLedger.allCountries') },
...(payload?.countries || []).map((value) => ({ value, label: formatLedgerCountry(value, isEnglish) })),
]
const precisionOptions = EDITABLE_PRECISIONS.map((value) => ({
value,
label: t('dataLedger.precision.' + value),
}))
const columns = useMemo<Array<ColumnDef<ComputeLedgerRow>>>(() => [
{
accessorKey: 'name',
header: '名称',
header: t('dataLedger.column.name'),
size: 220,
minSize: 160,
cell: ({ row }) => (
@@ -427,39 +436,39 @@ export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
},
{
accessorKey: 'site_type',
header: '设施类型',
header: t('dataLedger.column.site_type'),
size: 112,
minSize: 96,
cell: ({ row }) => (
<Badge tone="slate">
{COMPUTE_SITE_TYPE_LABELS[row.original.site_type as ComputeSiteType] || row.original.site_type}
{t('dataLedger.siteType.' + row.original.site_type, { defaultValue: row.original.site_type })}
</Badge>
),
},
{
accessorKey: 'operator',
header: '运营方',
header: t('dataLedger.column.operator'),
size: 140,
minSize: 100,
cell: ({ row }) => row.original.operator || '-',
},
{
accessorKey: 'country',
header: '国家',
header: t('dataLedger.column.country'),
size: 96,
minSize: 80,
cell: ({ row }) => row.original.country || '-',
cell: ({ row }) => formatLedgerCountry(row.original.country, isEnglish),
},
{
accessorKey: 'city',
header: '城市',
header: t('dataLedger.column.city'),
size: 112,
minSize: 84,
cell: ({ row }) => row.original.city || '-',
},
{
id: 'coordinates',
header: '坐标',
header: t('dataLedger.column.coordinates'),
size: 156,
minSize: 136,
cell: ({ row }) => (
@@ -470,54 +479,55 @@ export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
},
{
accessorKey: 'precision',
header: '精度',
header: t('dataLedger.column.precision'),
size: 76,
minSize: 68,
cell: ({ row }) => PRECISION_LABELS[row.original.precision] || row.original.precision || '-',
cell: ({ row }) => row.original.precision
? t('dataLedger.precision.' + row.original.precision, { defaultValue: row.original.precision })
: '-',
},
{
accessorKey: 'status_bucket',
header: '定位状态',
header: t('dataLedger.column.status_bucket'),
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
const { status_bucket: status, terminal_status: terminal } = row.original
const tone = COMPUTE_STATUS_BUCKET_TONES[status] || 'neutral'
const label = t('dataLedger.status.' + status, { defaultValue: status })
const terminalText = terminal ? t('dataLedger.terminal.' + terminal, { defaultValue: terminal }) : null
return (
<StatusText tone={meta.tone}>
{terminalText ? `${meta.label} · ${terminalText}` : meta.label}
<StatusText tone={tone}>
{terminalText ? `${label} · ${terminalText}` : label}
</StatusText>
)
},
},
{
accessorKey: 'updated_at',
header: '更新时间',
header: t('dataLedger.column.updated_at'),
size: 168,
minSize: 152,
cell: ({ row }) => (row.original.updated_at ? formatDateTimeZhCN(row.original.updated_at) : '-'),
cell: ({ row }) => formatLedgerDate(row.original.updated_at, isEnglish),
},
{
id: 'actions',
header: '操作',
header: t('dataLedger.column.actions'),
size: 80,
minSize: 80,
enableResizing: false,
cell: ({ row }) => {
const isAnonymousPlaceholder = Boolean(row.original.is_anonymous_placeholder)
const relocateTitle = isAnonymousPlaceholder
? '源数据为匿名占位条目,无可检索线索'
: '重新定位'
? t('dataLedger.anonymousPlaceholder')
: t('dataLedger.relocate')
return (
<div
className="an-table-actions"
onClick={(event) => event.stopPropagation()}
>
<TableActionButton
aria-label={isAnonymousPlaceholder ? `源数据为匿名占位条目,无可检索线索 ${row.original.name}` : `重新定位 ${row.original.name}`}
aria-label={isAnonymousPlaceholder ? t('dataLedger.anonymousPlaceholderRow', { name: row.original.name }) : t('dataLedger.relocateRow', { name: row.original.name })}
title={relocateTitle}
disabled={isAnonymousPlaceholder}
loading={relocatingIds.has(row.original.source_id)}
@@ -526,8 +536,8 @@ export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
<Compass size={14} aria-hidden="true" />
</TableActionButton>
<TableActionButton
aria-label={`编辑坐标 ${row.original.name}`}
title="编辑坐标"
aria-label={t('dataLedger.editCoordinatesRow', { name: row.original.name })}
title={t('dataLedger.editCoordinates')}
onClick={() => openEditDialog(row.original)}
>
<MapPin size={14} aria-hidden="true" />
@@ -536,7 +546,7 @@ export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
)
},
},
], [handleForceRelocate, openEditDialog, relocatingIds])
], [handleForceRelocate, isEnglish, openEditDialog, relocatingIds, t])
const activeCandidates = detailRow ? candidatesBySourceId[detailRow.source_id] : undefined
const hasActiveFilters = Boolean(siteTypeFilter || statusFilter || countryFilter || searchInput.trim())
@@ -546,18 +556,18 @@ export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
<Card className="an-data-table-card">
<CardHeader className="an-data-table-card__header">
<div>
<CardTitle>算力中心台账</CardTitle>
<p>{`共 ${total.toLocaleString()} 条结果`}</p>
<CardTitle>{t('dataLedger.computeTitle')}</CardTitle>
<p>{t('dataLedger.results', { total: total.toLocaleString(locale) })}</p>
</div>
{showBatchBar ? (
<div className="an-batch-bar" role="toolbar" aria-label="批量操作">
<div className="an-batch-bar" role="toolbar" aria-label={t('dataLedger.batchActions')}>
<span className="an-batch-bar__count">
<strong>
{batchProgress?.running
? `${batchProgress.done}/${batchProgress.total}`
: selectedRows.length}
</strong>
{batchProgress?.running ? '定位中' : '已选择'}
{batchProgress?.running ? t('dataLedger.batchLocating') : t('dataLedger.selected')}
</span>
{batchProgress?.running ? (
<Button
@@ -566,10 +576,10 @@ export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
onClick={() => {
batchStopRef.current = true
}}
title="停止批量定位"
title={t('dataLedger.stopBatch')}
>
<Square size={13} aria-hidden="true" />
停止
{t('dataLedger.stop')}
</Button>
) : (
<Button
@@ -577,10 +587,10 @@ export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
variant="primary"
onClick={() => void handleBatchRelocate()}
disabled={!selectedRows.length}
title="批量定位选中条目"
title={t('dataLedger.startBatchTitle')}
>
<Compass size={14} aria-hidden="true" />
批量定位
{t('dataLedger.startBatch')}
<span className="an-batch-bar__num">{selectedRows.length}</span>
</Button>
)}
@@ -589,27 +599,27 @@ export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
variant="subtle"
onClick={() => setSelectedRowIds(new Set())}
disabled={Boolean(batchProgress?.running)}
title="清除选择"
aria-label="清除选择"
title={t('dataLedger.clearSelection')}
aria-label={t('dataLedger.clearSelection')}
>
<X size={14} />
</Button>
</div>
) : (
<div className="an-toolbar">
<Button size="sm" variant="subtle" onClick={() => void fetchComputeLedger()}><RefreshCw size={14} />刷新</Button>
<Button size="sm" variant="subtle" onClick={() => void fetchComputeLedger()}><RefreshCw size={14} />{t('dataLedger.refresh')}</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="设施类型">
<div className="an-segmented an-segmented--counted" role="tablist" aria-label={t('dataLedger.column.site_type')}>
<button
type="button"
className={!siteTypeFilter ? 'is-active' : ''}
onClick={() => { setSiteTypeFilter('') }}
>
<span>全部</span>
<span>{t('dataLedger.all')}</span>
<span className="an-segmented__count">{allSiteTypeCount}</span>
</button>
{COMPUTE_SITE_TYPE_ORDER.map((typeKey) => (
@@ -619,7 +629,7 @@ export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
className={siteTypeFilter === typeKey ? 'is-active' : ''}
onClick={() => { setSiteTypeFilter(typeKey) }}
>
<span>{COMPUTE_SITE_TYPE_LABELS[typeKey]}</span>
<span>{t('dataLedger.siteType.' + typeKey)}</span>
<span className="an-segmented__count">{bySiteType[typeKey] || 0}</span>
</button>
))}
@@ -648,8 +658,8 @@ export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
<div className="an-search-box an-search-box--inline">
<Search size={14} aria-hidden="true" />
<Input
placeholder="搜索名称、运营方、城市、说明"
aria-label="搜索名称、运营方、城市、说明"
placeholder={t('dataLedger.computeSearch')}
aria-label={t('dataLedger.computeSearch')}
value={searchInput}
onChange={(event) => setSearchInput(event.target.value)}
/>
@@ -658,8 +668,8 @@ export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
size="icon"
variant="ghost"
onClick={() => setSearchInput('')}
title="清空搜索"
aria-label="清空搜索"
title={t('dataLedger.clearSearch')}
aria-label={t('dataLedger.clearSearch')}
>
<X size={14} />
</Button>
@@ -671,8 +681,8 @@ export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
variant="subtle"
onClick={handleReset}
disabled={!hasActiveFilters}
title="重置筛选"
aria-label="重置筛选"
title={t('dataLedger.resetFilters')}
aria-label={t('dataLedger.resetFilters')}
>
<RotateCcw size={14} />
</Button>
@@ -690,7 +700,7 @@ export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
selectedRowIds,
onToggleAllVisible: toggleAllVisibleSelection,
onToggleRow: (rowId) => toggleSingleSelection(rowId),
getCheckboxLabel: (row) => `选择 ${row.name}`,
getCheckboxLabel: (row) => t('dataLedger.selectRow', { name: row.name }),
isRowSelectable: (row) => !row.is_anonymous_placeholder,
}}
onRowClick={(row) => {
@@ -707,7 +717,7 @@ export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
/>
</CardContent>
<Dialog title={detailRow ? `${detailRow.name} 定位详情` : '算力中心详情'} open={detailOpen} onOpenChange={setDetailOpen} width={760}>
<Dialog title={detailRow ? t('dataLedger.locationDetails', { name: detailRow.name }) : t('dataLedger.computeDetails')} open={detailOpen} onOpenChange={setDetailOpen} width={760}>
{detailRow ? (
<div className="an-detail">
<div className="an-detail-links">
@@ -720,7 +730,7 @@ export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
navigate('/advisor/runs')
}}
>
<span>{`查看工作流运行记录 (${detailRow.workflow_run_id})`}</span>
<span>{t('dataLedger.viewWorkflowRun', { id: detailRow.workflow_run_id })}</span>
<ArrowRight size={14} />
</button>
) : null}
@@ -729,9 +739,9 @@ export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
className="an-detail-link"
onClick={() => void handleForceRelocate(detailRow)}
disabled={relocatingIds.has(detailRow.source_id) || Boolean(detailRow.is_anonymous_placeholder)}
title={detailRow.is_anonymous_placeholder ? '源数据为匿名占位条目,无可检索线索' : '重新定位'}
title={detailRow.is_anonymous_placeholder ? t('dataLedger.anonymousPlaceholder') : t('dataLedger.relocate')}
>
<span>{relocatingIds.has(detailRow.source_id) ? '正在重新定位...' : '重新定位'}</span>
<span>{relocatingIds.has(detailRow.source_id) ? t('dataLedger.relocating') : t('dataLedger.relocate')}</span>
<Compass size={14} />
</button>
<button
@@ -742,37 +752,38 @@ export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
openEditDialog(detailRow)
}}
>
<span>编辑坐标</span>
<span>{t('dataLedger.editCoordinates')}</span>
<MapPin size={14} />
</button>
</div>
<section className="an-detail__section">
<h3>核验依据与定位属性</h3>
<h3>{t('dataLedger.locationEvidence')}</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>{t('dataLedger.sourceIdentifier')}</span><strong>{`${detailRow.source} / ${detailRow.source_id}`}</strong></div>
<div><span>{t('dataLedger.column.site_type')}</span><strong>{t('dataLedger.siteType.' + detailRow.site_type, { defaultValue: detailRow.site_type })}</strong></div>
<div><span>{t('dataLedger.column.operator')}</span><strong>{detailRow.operator || '-'}</strong></div>
<div><span>{t('dataLedger.countryAndCity')}</span><strong>{[detailRow.country && formatLedgerCountry(detailRow.country, isEnglish), detailRow.city].filter(Boolean).join(' · ') || '-'}</strong></div>
<div><span>{t('dataLedger.locationSource')}</span><strong>{detailRow.location_source || '-'}</strong></div>
<div>
<span>核验状态</span>
<span>{t('dataLedger.column.verification_status')}</span>
<strong>
{t('dataLedger.status.' + detailRow.status_bucket, { defaultValue: detailRow.status_bucket })}
{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}
? ' · ' + t('dataLedger.terminal.' + detailRow.terminal_status, { defaultValue: detailRow.terminal_status })
: ''}
</strong>
</div>
</div>
<div className="an-ledger-note-box">
<span>依据说明</span>
<p>{detailRow.source_note || '暂无补充说明'}</p>
<span>{t('dataLedger.evidenceNote')}</span>
<p>{detailRow.source_note || t('dataLedger.noNotes')}</p>
</div>
</section>
{activeCandidates && activeCandidates.items.length > 0 ? (
<section className="an-detail__section">
<h3>{`新采集候选位置 (${activeCandidates.items.length})`}</h3>
<h3>{t('dataLedger.newCandidates', { count: activeCandidates.items.length })}</h3>
<Scrollbar className="an-ledger-candidate-scroll">
<div className="an-ledger-candidates">
{activeCandidates.items.map((cand, index) => {
@@ -781,7 +792,7 @@ export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
<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>
<p>{`${cand.latitude.toFixed(5)}, ${cand.longitude.toFixed(5)} · ${t('dataLedger.precision.' + cand.precision, { defaultValue: cand.precision })} · ${[cand.country && formatLedgerCountry(cand.country, isEnglish), cand.city].filter(Boolean).join(' / ') || '-'}`}</p>
{cand.source_note ? <small>{cand.source_note}</small> : null}
</div>
<Button
@@ -790,7 +801,7 @@ export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
loading={adoptingKey === key}
onClick={() => void handleAdoptCandidate(detailRow, cand, index, activeCandidates.workflowRunId)}
>
采纳
{t('dataLedger.adopt')}
</Button>
</div>
)
@@ -804,7 +815,7 @@ export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
</Dialog>
<Dialog
title={editTarget ? `编辑坐标:${editTarget.name}` : '编辑坐标'}
title={editTarget ? t('dataLedger.editCoordinatesTitle', { name: editTarget.name }) : t('dataLedger.editCoordinates')}
open={Boolean(editTarget)}
onOpenChange={(open) => {
if (!open) setEditTarget(null)
@@ -812,31 +823,31 @@ export function ComputeLedger({ onMutated }: { onMutated?: () => void }) {
width={480}
footer={(
<>
<Button variant="subtle" onClick={() => setEditTarget(null)} disabled={savingEdit}>取消</Button>
<Button variant="primary" onClick={() => void handleSaveManualLocation()} loading={savingEdit}>保存坐标</Button>
<Button variant="subtle" onClick={() => setEditTarget(null)} disabled={savingEdit}>{t('common.cancel')}</Button>
<Button variant="primary" onClick={() => void handleSaveManualLocation()} loading={savingEdit}>{t('dataLedger.saveCoordinates')}</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" />
<label htmlFor="ledger-edit-lat">{t('dataLedger.latitude')}</label>
<Input id="ledger-edit-lat" value={editLat} onChange={(e) => setEditLat(e.target.value)} placeholder={t('dataLedger.latitudeExample')} />
</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" />
<label htmlFor="ledger-edit-lon">{t('dataLedger.longitude')}</label>
<Input id="ledger-edit-lon" value={editLon} onChange={(e) => setEditLon(e.target.value)} placeholder={t('dataLedger.longitudeExample')} />
</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="城市名称" />
<label htmlFor="ledger-edit-city">{t('dataLedger.column.city')}</label>
<Input id="ledger-edit-city" value={editCity} onChange={(e) => setEditCity(e.target.value)} placeholder={t('dataLedger.cityPlaceholder')} />
</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="国家或地区" />
<label htmlFor="ledger-edit-country">{t('dataLedger.column.country')}</label>
<Input id="ledger-edit-country" value={editCountry} onChange={(e) => setEditCountry(e.target.value)} placeholder={t('dataLedger.countryPlaceholder')} />
</div>
<div className="an-field">
<label>精度</label>
<Select value={editPrecision} onValueChange={setEditPrecision} options={EDITABLE_PRECISION_OPTIONS} />
<label>{t('dataLedger.column.precision')}</label>
<Select value={editPrecision} onValueChange={setEditPrecision} options={precisionOptions} />
</div>
</div>
</Dialog>
@@ -2,13 +2,17 @@ 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 { useTranslation } from 'react-i18next'
import { describeApiError } from '../../../i18n/api-errors'
import { normalizeLocale } from '../../../i18n/locale'
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 { formatDataTypeLabel } from '../dashboardHelpers'
import { formatLedgerCountry, formatLedgerDate } from './ledger-display'
import type { GenericLayerItemsResponse, LedgerKind } from './ledger-model'
const TIMESTAMP_COLUMN_KEYS = new Set([
@@ -20,6 +24,16 @@ const TIMESTAMP_COLUMN_KEYS = new Set([
'published_at',
])
const COLUMN_OVERRIDES: Record<string, Record<string, string>> = {
satellites: { source_id: 'norad_id' },
vessels: { name: 'vessel_name' },
bgp: { title: 'incident_title' },
'news:items': { title: 'news_title' },
'news:live_streams': { name: 'channel_name' },
weather: { reference_date: 'observed_at' },
geo: { name: 'tile_dataset' },
}
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'])
@@ -42,6 +56,9 @@ export function LayerItemsLedger({
layerName: string
initialKinds: LedgerKind[]
}) {
const { t, i18n } = useTranslation()
const locale = normalizeLocale(i18n.resolvedLanguage || i18n.language)
const isEnglish = locale === 'en-US'
const { toast } = useToast()
const [kind, setKind] = useState<string>(initialKinds[0]?.id || 'all')
const [searchInput, setSearchInput] = useState('')
@@ -93,11 +110,11 @@ export function LayerItemsLedger({
(error: unknown) => {
toast({
tone: 'error',
title: `加载${layerName}台账失败`,
description: error instanceof Error ? error.message : '请稍后重试',
title: t('dataLedger.loadLayerFailed', { layer: layerName }),
description: describeApiError(error, t('dataLedger.retry')),
})
},
[layerName, toast],
[layerName, t, toast],
)
const {
@@ -121,24 +138,28 @@ export function LayerItemsLedger({
const columns = useMemo<Array<ColumnDef<Record<string, unknown>>>>(() => {
const defs = payload?.columns || []
const overrides = COLUMN_OVERRIDES[layerId + ':' + kind] || COLUMN_OVERRIDES[layerId]
return defs.map((col) => {
const sizing = columnWidthSpec(col.key)
const labelKey = overrides?.[col.key] || col.key
return {
accessorKey: col.key,
header: col.label,
header: isEnglish ? t('dataLedger.column.' + labelKey, { defaultValue: col.label }) : 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 formatLedgerDate(val, isEnglish)
}
if (col.key === 'country' || col.key === 'flag') return formatLedgerCountry(String(val), isEnglish)
if (col.key === 'data_type') return formatDataTypeLabel(String(val), isEnglish)
return String(val)
},
}
})
}, [payload?.columns])
}, [isEnglish, kind, layerId, payload?.columns, t])
const hasActiveFilters = Boolean(searchInput.trim() || (kinds.length > 0 && kind !== kinds[0].id))
@@ -146,17 +167,17 @@ export function LayerItemsLedger({
<Card className="an-data-table-card">
<CardHeader className="an-data-table-card__header">
<div>
<CardTitle>{`${layerName}台账`}</CardTitle>
<p>{`共 ${total.toLocaleString()} 条结果`}</p>
<CardTitle>{t('dataLedger.ledgerTitle', { layer: layerName })}</CardTitle>
<p>{t('dataLedger.results', { total: total.toLocaleString(locale) })}</p>
</div>
<div className="an-toolbar">
<Button size="sm" variant="subtle" onClick={() => void fetchItems()}><RefreshCw size={14} />刷新</Button>
<Button size="sm" variant="subtle" onClick={() => void fetchItems()}><RefreshCw size={14} />{t('dataLedger.refresh')}</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}子分类`}>
<div className="an-segmented an-segmented--counted" role="tablist" aria-label={t('dataLedger.layerKinds', { layer: layerName })}>
{kinds.map((item) => (
<button
key={item.id}
@@ -164,7 +185,7 @@ export function LayerItemsLedger({
className={kind === item.id ? 'is-active' : ''}
onClick={() => setKind(item.id)}
>
<span>{item.label}</span>
<span>{t('dataLedger.kind.' + item.id, { defaultValue: item.label })}</span>
</button>
))}
</div>
@@ -172,8 +193,8 @@ export function LayerItemsLedger({
<div className="an-search-box an-search-box--inline">
<Search size={14} aria-hidden="true" />
<Input
placeholder="搜索名称、标识或来源"
aria-label="搜索名称、标识或来源"
placeholder={t('dataLedger.layerSearch')}
aria-label={t('dataLedger.layerSearch')}
value={searchInput}
onChange={(event) => setSearchInput(event.target.value)}
/>
@@ -182,8 +203,8 @@ export function LayerItemsLedger({
size="icon"
variant="ghost"
onClick={() => setSearchInput('')}
title="清空搜索"
aria-label="清空搜索"
title={t('dataLedger.clearSearch')}
aria-label={t('dataLedger.clearSearch')}
>
<X size={14} />
</Button>
@@ -198,8 +219,8 @@ export function LayerItemsLedger({
if (kinds.length > 0) setKind(kinds[0].id)
}}
disabled={!hasActiveFilters}
title="重置筛选"
aria-label="重置筛选"
title={t('dataLedger.resetFilters')}
aria-label={t('dataLedger.resetFilters')}
>
<RotateCcw size={14} />
</Button>
@@ -1,3 +1,5 @@
import { useTranslation } from 'react-i18next'
import { normalizeLocale } from '../../../i18n/locale'
import Scrollbar from '../../../components/Scrollbar/Scrollbar'
import { Card, CardContent, CardHeader, CardTitle } from '../../components/ui/card'
import { Badge } from '../../components/ui/badge'
@@ -15,17 +17,20 @@ export function LayerNav({
loading: boolean
onSelectLayer: (layerId: string) => void
}) {
const { t, i18n } = useTranslation()
const locale = normalizeLocale(i18n.resolvedLanguage || i18n.language)
return (
<Card className="an-data-summary an-ledger-nav-card">
<CardHeader>
<CardTitle>图层分类</CardTitle>
<CardTitle>{t('dataLedger.layers')}</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="图层分类">
<div className="an-ledger-nav-list" role="tablist" aria-label={t('dataLedger.layers')}>
{loading && layers.length === 0 ? (
<div className="an-loading"><span className="an-spinner" />加载中</div>
<div className="an-loading"><span className="an-spinner" />{t('common.loading')}</div>
) : (
layers.map((layer) => {
const isActive = layer.id === activeLayer
@@ -39,8 +44,8 @@ export function LayerNav({
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>
<span className="an-ledger-nav-item__name">{t('dataLedger.layer.' + layer.id, { defaultValue: layer.name })}</span>
<span className="an-ledger-nav-item__count">{layer.count.toLocaleString(locale)}</span>
</button>
)
})
@@ -0,0 +1,62 @@
import { formatDateTimeZhCN, formatDateZhCN, parseBackendDate } from '../../../utils/datetime'
const REGION_NAME_OVERRIDES: Record<string, string> = {
中非: 'CF',
多米尼加: 'DO',
埃斯瓦蒂尼: 'SZ',
巴勒斯坦: 'PS',
阿联酋: 'AE',
'中国(香港)': 'HK',
'中国(澳门)': 'MO',
'中国(台湾)': 'TW',
科索沃: 'RS',
Kosovo: 'RS',
}
const ENGLISH_REGION_OVERRIDES: Record<string, string> = {
HK: 'Hong Kong, China',
MO: 'Macao, China',
TW: 'Taiwan, China',
XK: 'Serbia',
}
let chineseRegionCodes: Map<string, string> | undefined
let englishRegionNames: Intl.DisplayNames | undefined
function getChineseRegionCodes() {
if (chineseRegionCodes) return chineseRegionCodes
const chineseNames = new Intl.DisplayNames('zh-CN', { type: 'region', fallback: 'none' })
const letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
const codes = new Map<string, string>()
for (const first of letters) {
for (const second of letters) {
const code = first + second
const name = chineseNames.of(code)
if (name) codes.set(name, code)
}
}
chineseRegionCodes = codes
return codes
}
export function formatLedgerCountry(value: string | null | undefined, isEnglish: boolean) {
if (!value || !isEnglish) return value || '-'
const code = REGION_NAME_OVERRIDES[value] || getChineseRegionCodes().get(value)
|| (/^[A-Za-z]{2}$/.test(value) ? value.toUpperCase() : '')
if (!code) return value
englishRegionNames ??= new Intl.DisplayNames('en-US', { type: 'region', fallback: 'none' })
return ENGLISH_REGION_OVERRIDES[code] || englishRegionNames.of(code) || value
}
export function formatLedgerDate(value: string | null | undefined, isEnglish: boolean, dateOnly = false) {
if (!isEnglish) return dateOnly ? formatDateZhCN(value) : formatDateTimeZhCN(value)
const date = parseBackendDate(value)
if (!date) return '-'
return dateOnly
? date.toLocaleDateString('en-US')
: date.toLocaleString('en-US', { hour12: false })
}
@@ -99,41 +99,14 @@ export const COMPUTE_SITE_TYPE_ORDER: ComputeSiteType[] = [
'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<
export const COMPUTE_STATUS_BUCKET_TONES: Record<
ComputeStatusBucket,
{ label: string; tone: 'success' | 'warning' | 'neutral' | 'info' }
'success' | 'warning' | 'neutral' | 'info'
> = {
located: { label: '已定位', tone: 'success' },
needs_confirmation: { label: '待确认', tone: 'warning' },
terminal: { label: '暂不可定位', tone: 'neutral' },
pending: { label: '待定位', tone: 'info' },
located: 'success',
needs_confirmation: 'warning',
terminal: 'neutral',
pending: '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: '城市' },
]
export const EDITABLE_PRECISIONS = ['precise', 'site', 'city']
+7 -2
View File
@@ -273,7 +273,7 @@
padding-top: 8px;
border-top: 1px solid var(--an-border);
}
@media (max-width: 1080px) {
@media (max-width: 1024px) {
.an-cloud-workspace {
grid-template-columns: minmax(0, 1fr);
grid-template-rows: auto minmax(0, 1fr);
@@ -287,7 +287,12 @@
max-height: 46%;
}
}
@media (max-width: 680px) {
@media (max-height: 760px) and (max-width: 1024px) {
.an-cloud-pane--preview {
max-height: 36%;
}
}
@media (max-width: 760px) {
.an-cloud-kpis,
.an-cloud-regions,
.an-cloud-fields {
File diff suppressed because it is too large. Load diff
@@ -349,26 +349,28 @@ function MarkdownMermaidBlock({ code }: { code: string }) {
</button>
</div>
{svg ? (
<div
role="button"
tabIndex={0}
className="markdown-renderer__mermaid-canvas"
onClick={(event) => {
if (isMermaidTextTarget(event.target)) return
if (window.getSelection()?.toString()) return
openExpanded()
}}
onKeyDown={(event) => {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault()
<Scrollbar axis="x" className="markdown-renderer__mermaid-scroll">
<div
role="button"
tabIndex={0}
className="markdown-renderer__mermaid-canvas"
onClick={(event) => {
if (isMermaidTextTarget(event.target)) return
if (window.getSelection()?.toString()) return
openExpanded()
}
}}
aria-label={t('markdown.expandMermaid')}
title={t('markdown.clickToExpand')}
>
<span className="markdown-renderer__mermaid-canvas-inner" dangerouslySetInnerHTML={{ __html: svg }} />
</div>
}}
onKeyDown={(event) => {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault()
openExpanded()
}
}}
aria-label={t('markdown.expandMermaid')}
title={t('markdown.clickToExpand')}
>
<span className="markdown-renderer__mermaid-canvas-inner" dangerouslySetInnerHTML={{ __html: svg }} />
</div>
</Scrollbar>
) : error ? (
<div className="markdown-renderer__mermaid-error">
<strong>{t('markdown.mermaidRenderFailed')}</strong>
@@ -13,7 +13,7 @@ import {
type ReactNode,
} from 'react'
import { TactileTooltip, type TooltipSide } from './Tooltip'
import { isFocusVisible, TactileTooltip, type TooltipSide } from './Tooltip'
import { renderTactileIcon, type TactileIconValue } from './icons'
import { classNames, mergeTactileOptions, tactileStyle, type TactileControlOptions } from './types'
import './styles.css'
@@ -116,7 +116,7 @@ function useTooltipHandlers<T extends HTMLElement>(
},
onFocus: (event: FocusEvent<T>) => {
props.onFocus?.(event)
setOpen(true)
if (isFocusVisible(event.currentTarget)) setOpen(true)
},
onBlur: (event: FocusEvent<T>) => {
props.onBlur?.(event)
@@ -1,6 +1,6 @@
import { useRef, useState } from 'react'
import { TactileTooltip, type TooltipSide } from './Tooltip'
import { isFocusVisible, TactileTooltip, type TooltipSide } from './Tooltip'
import { classNames, tactileStyle, type TactileControlOptions } from './types'
import './styles.css'
@@ -43,7 +43,9 @@ export function TactileSwitch({
onClick={() => onCheckedChange(!checked)}
onMouseEnter={() => setTooltipOpen(true)}
onMouseLeave={() => setTooltipOpen(false)}
onFocus={() => setTooltipOpen(true)}
onFocus={(event) => {
if (isFocusVisible(event.currentTarget)) setTooltipOpen(true)
}}
onBlur={() => setTooltipOpen(false)}
>
<span />
+113 -19
View File
@@ -1,17 +1,88 @@
import { useLayoutEffect, useState, type CSSProperties } from 'react'
import { useLayoutEffect, useRef, useState, type CSSProperties } from 'react'
import { createPortal } from 'react-dom'
import './styles.css'
export type TooltipSide = 'top' | 'right' | 'bottom' | 'left'
export interface TooltipViewportBounds {
minX: number
maxX: number
minY: number
maxY: number
}
export function isFocusVisible(element: HTMLElement): boolean {
try {
return element.matches(':focus-visible')
} catch {
return true
}
}
export function getCssZoom(element?: Element | null): number {
if (typeof window === 'undefined' || typeof document === 'undefined') return 1
const target = element ?? document.body ?? document.documentElement
const currentZoom = (target as (Element & { currentCSSZoom?: number }) | null)?.currentCSSZoom
if (typeof currentZoom === 'number' && Number.isFinite(currentZoom) && currentZoom > 0) {
return currentZoom
}
const htmlZoom = Number.parseFloat(getComputedStyle(document.documentElement).zoom || '1') || 1
const bodyZoom = document.body ? Number.parseFloat(getComputedStyle(document.body).zoom || '1') || 1 : 1
const combined = htmlZoom * bodyZoom
return Number.isFinite(combined) && combined > 0 ? combined : 1
}
export function snapToDevicePixel(value: number): number {
const dpr = typeof window !== 'undefined' && window.devicePixelRatio > 0 ? window.devicePixelRatio : 1
return Math.round(value * dpr) / dpr
}
export function getTooltipViewportBounds(margin = 8, element?: Element | null): TooltipViewportBounds {
if (typeof window === 'undefined' || typeof document === 'undefined') {
return { minX: margin, maxX: 1280 - margin, minY: margin, maxY: 720 - margin }
}
const cssZoom = getCssZoom(element)
const clientW = (document.documentElement.clientWidth || window.innerWidth) * cssZoom
const clientH = (document.documentElement.clientHeight || window.innerHeight) * cssZoom
const vv = window.visualViewport
const offsetLeft = vv ? vv.offsetLeft : 0
const offsetTop = vv ? vv.offsetTop : 0
const width = vv ? Math.min(clientW, vv.width) : clientW
const height = vv ? Math.min(clientH, vv.height) : clientH
return {
minX: offsetLeft + margin,
maxX: offsetLeft + width - margin,
minY: offsetTop + margin,
maxY: offsetTop + height - margin,
}
}
export function clampTooltipCoords(
left: number,
top: number,
tipWidth: number,
tipHeight: number,
margin = 8,
element?: Element | null,
): { left: number; top: number } {
const bounds = getTooltipViewportBounds(margin, element)
const cssZoom = getCssZoom(element)
const clampedLeft = Math.min(Math.max(bounds.minX, left), Math.max(bounds.minX, bounds.maxX - tipWidth))
const clampedTop = Math.min(Math.max(bounds.minY, top), Math.max(bounds.minY, bounds.maxY - tipHeight))
return {
left: snapToDevicePixel(clampedLeft) / cssZoom,
top: snapToDevicePixel(clampedTop) / cssZoom,
}
}
export function TactileTooltip({
label,
anchor,
open,
side = 'bottom',
offset = 14,
crossOffset = 10,
offset = 8,
crossOffset = 0,
}: {
label?: string
anchor: HTMLElement | null
@@ -20,40 +91,63 @@ export function TactileTooltip({
offset?: number
crossOffset?: number
}) {
const tooltipRef = useRef<HTMLDivElement | null>(null)
const [style, setStyle] = useState<CSSProperties>({})
useLayoutEffect(() => {
if (!open || !label || !anchor) return
const update = () => {
const rect = anchor.getBoundingClientRect()
const estimatedWidth = Math.min(240, Math.max(48, label.length * 12))
const estimatedHeight = 32
const preferred = (() => {
if (side === 'top') return { left: rect.left + rect.width + crossOffset, top: rect.top - estimatedHeight - offset }
if (side === 'left') return { left: rect.left - estimatedWidth - offset, top: rect.top + rect.height + crossOffset }
if (side === 'right') return { left: rect.right + offset, top: rect.top + rect.height + crossOffset }
return { left: rect.left + rect.width + crossOffset, top: rect.bottom + offset }
})()
let left = preferred.left
let top = preferred.top
if (left + estimatedWidth > window.innerWidth - 8) left = window.innerWidth - estimatedWidth - 8
if (left < 8) left = 8
if (top + estimatedHeight > window.innerHeight - 8) top = Math.max(8, rect.top - estimatedHeight - offset)
if (top < 8) top = Math.min(window.innerHeight - estimatedHeight - 8, rect.bottom + offset)
setStyle({ left, top })
const tipRect = tooltipRef.current?.getBoundingClientRect()
const tipWidth = tipRect && tipRect.width > 0 ? tipRect.width : Math.min(240, Math.max(48, label.length * 12))
const tipHeight = tipRect && tipRect.height > 0 ? tipRect.height : 30
const bounds = getTooltipViewportBounds(8, tooltipRef.current)
let left = 0
let top = 0
if (side === 'top' || side === 'bottom') {
left = rect.left + (rect.width - tipWidth) / 2 + crossOffset
const preferTop = side === 'top'
const topY = rect.top - tipHeight - offset
const bottomY = rect.bottom + offset
if (preferTop) {
top = topY < bounds.minY && bottomY + tipHeight <= bounds.maxY ? bottomY : topY
} else {
top = bottomY + tipHeight > bounds.maxY && topY >= bounds.minY ? topY : bottomY
}
} else {
top = rect.top + (rect.height - tipHeight) / 2 + crossOffset
const preferLeft = side === 'left'
const leftX = rect.left - tipWidth - offset
const rightX = rect.right + offset
if (preferLeft) {
left = leftX < bounds.minX && rightX + tipWidth <= bounds.maxX ? rightX : leftX
} else {
left = rightX + tipWidth > bounds.maxX && leftX >= bounds.minX ? leftX : rightX
}
}
setStyle(clampTooltipCoords(left, top, tipWidth, tipHeight, 8, tooltipRef.current))
}
update()
window.addEventListener('scroll', update, true)
window.addEventListener('resize', update)
const vv = window.visualViewport
vv?.addEventListener('resize', update)
vv?.addEventListener('scroll', update)
return () => {
window.removeEventListener('scroll', update, true)
window.removeEventListener('resize', update)
vv?.removeEventListener('resize', update)
vv?.removeEventListener('scroll', update)
}
}, [anchor, crossOffset, label, offset, open, side])
if (!open || !label || typeof document === 'undefined') return null
return createPortal(
<div className="tui-tooltip" style={style} role="tooltip">
<div ref={tooltipRef} className="tui-tooltip" style={style} role="tooltip">
{label}
</div>,
document.body,
@@ -122,7 +122,9 @@ body[data-admin-theme='dark'] .tui-tooltip {
box-shadow: var(--tui-control-shadow-active, 0 1px 2px rgba(15, 23, 42, 0.14), 0 3px 8px rgba(15, 23, 42, 0.08));
}
[data-theme='dark'] .tui-button--tactile {
[data-theme='dark'] .tui-button--tactile,
body[data-admin-theme='dark'] .tui-button--tactile,
body:has(.admin-theme-root[data-theme='dark']) .tui-button--tactile {
background: var(--tui-control-dark-bg, var(--tui-surface-raised-dark));
box-shadow: var(--tui-control-dark-shadow, var(--tui-control-shadow, 0 2px 5px rgba(0, 0, 0, 0.38), 0 10px 20px rgba(0, 0, 0, 0.24)));
}
+352
View File
@@ -40,6 +40,7 @@ export const zhCN = {
logout: '退出登录',
greeting: '您好,{{name}}',
version: '版本号',
versionDetail: '服务端 v{{backend}} · 控制台镜像 v{{ui}}',
themeControl: '控制台主题',
languageControl: '控制台语言',
expandPreferences: '展开偏好设置',
@@ -207,6 +208,181 @@ export const zhCN = {
renderingDiagram: '正在渲染图表...',
viewerHint: '拖拽移动 · 滚轮缩放 · 点击空白关闭',
},
dataLedger: {
title: '采集数据',
description: '按地球图层分类复核基础设施、台账与原始采集元数据。',
layers: '图层分类',
resizeLayerNav: '拖动调整图层导航宽度',
results: '共 {{total}} 条结果',
resultCount: '结果 {{total}} 条',
filterCount: '筛选 {{count}} 项',
refresh: '刷新',
clearSearch: '清空搜索',
resetFilters: '重置筛选',
allCountries: '全部国家/地区',
allStatuses: '全部定位状态',
allSources: '全部数据源',
allTypes: '全部类型',
all: '全部',
list: '数据列表',
rawSearch: '搜索名称、描述、元数据等',
layerSearch: '搜索名称、标识或来源',
computeSearch: '搜索名称、运营方、城市、说明',
exportFile: '导出 {{format}}',
exported: '已导出 {{format}}',
exportFailed: '导出失败',
loadRawFailed: '加载采集数据失败',
loadLayerFailed: '加载{{layer}}台账失败',
retry: '请稍后重试',
ledgerTitle: '{{layer}}台账',
layerKinds: '{{layer}}子分类',
rawDetail: '数据详情',
basicInfo: '基础信息',
extraFields: '扩展字段',
rawMetadata: '原始元数据',
computeTitle: '算力中心台账',
loadComputeFailed: '加载算力中心台账失败',
relocate: '重新定位',
relocateRow: '重新定位 {{name}}',
relocating: '正在重新定位...',
relocateFailed: '重新定位失败',
anonymousPlaceholder: '源数据为匿名占位条目,无可检索线索',
anonymousPlaceholderRow: '源数据为匿名占位条目,无可检索线索 {{name}}',
editCoordinates: '编辑坐标',
editCoordinatesRow: '编辑坐标 {{name}}',
editCoordinatesTitle: '编辑坐标:{{name}}',
selectRow: '选择 {{name}}',
batchActions: '批量操作',
batchLocating: '定位中',
selected: '已选择',
stopBatch: '停止批量定位',
stop: '停止',
startBatchTitle: '批量定位选中条目',
startBatch: '批量定位',
clearSelection: '清除选择',
stoppedBatch: '已停止批量定位(已完成 {{done}} / {{total}} 条)',
finishedBatch: '批量定位完成:候选 {{found}} 条,暂不可定位 {{terminal}} 条,未命中 {{missed}} 条',
finishedBatchWithFailures: '批量定位完成:候选 {{found}} 条,暂不可定位 {{terminal}} 条,未命中 {{missed}} 条,失败 {{failed}} 条',
foundCandidates: '已获取 {{count}} 个候选坐标',
adoptCandidatesHint: '点击行可查看并采纳候选位置',
confirmedTerminal: '已确认:{{status}}',
noCandidates: '未找到可用候选坐标',
invalidCoordinates: '请输入有效的非零经纬度坐标',
coordinatesSaved: '坐标已保存',
saveCoordinatesFailed: '保存坐标失败',
candidateAdopted: '已采纳候选坐标',
adoptCandidateFailed: '采纳候选失败',
computeDetails: '算力中心详情',
locationDetails: '{{name}} 定位详情',
viewWorkflowRun: '查看工作流运行记录 ({{id}})',
locationEvidence: '核验依据与定位属性',
sourceIdentifier: '来源标识',
countryAndCity: '国家 / 城市',
locationSource: '定位来源',
evidenceNote: '依据说明',
noNotes: '暂无补充说明',
newCandidates: '新采集候选位置 ({{count}})',
adopt: '采纳',
saveCoordinates: '保存坐标',
latitude: '纬度',
longitude: '经度',
latitudeExample: '如 35.7804',
longitudeExample: '如 -78.6391',
cityPlaceholder: '城市名称',
countryPlaceholder: '国家或地区',
layer: {
compute: '算力',
satellites: '卫星',
cables: '海底光缆',
vessels: '船只',
bgp: 'BGP',
news: '新闻与直播',
weather: '气象',
geo: '地理/底图',
raw: '原始采集记录',
},
kind: {
submarine_cable: '海缆系统',
landing_point: '登陆点',
cable_landing_relation: '海缆登陆关系',
collectors: '观测站',
incidents: 'BGP 事件',
items: '新闻条目',
live_streams: 'Live 直播源',
all: '气象图层',
cloud_map_record: '云图记录',
wind_field_record: '风场记录',
},
siteType: {
supercomputer: '超算',
gpu_cluster: 'GPU 集群',
data_center: '数据中心',
cloud_center: '云计算中心',
edge_node: '边缘节点',
},
status: {
located: '已定位',
needs_confirmation: '待确认',
terminal: '暂不可定位',
pending: '待定位',
},
terminal: {
undisclosed: '位置未公开',
multi_site: '多地分布式部署',
planned: '规划中尚未建成',
cloud_only: '纯云服务无独立站点',
anonymous: '匿名设施',
},
precision: {
precise: '精确',
site: '园区',
city: '城市',
unknown: '未知',
},
column: {
name: '名称',
source: '数据源',
data_type: '数据类型',
source_id: '原始 ID',
country: '国家',
country_region: '国家/地区',
city: '城市',
collected_at: '采集时间',
reference_date: '参考日期',
site_type: '设施类型',
operator: '运营方',
coordinates: '坐标',
precision: '精度',
status_bucket: '定位状态',
updated_at: '更新时间',
verification_status: '核验状态',
actions: '操作',
international_designator: '国际编号',
constellation_group: '星座分组',
inclination: '轨道倾角',
region: '区域',
language: '语言',
mmsi: 'MMSI',
flag: '船旗',
vessel_type_name: '船型',
sog: '航速',
observed_at: '观测时间',
collector_id: '观测站 ID',
incident_type: '事件类型',
severity: '级别',
status: '状态',
started_at: '开始时间',
location_label: '地理落点',
enrichment_status: '处理状态',
published_at: '发布时间',
vessel_name: '船名',
channel_name: '频道名称',
tile_dataset: '瓦片数据集',
incident_title: '事件标题',
news_title: '新闻标题',
norad_id: 'NORAD ID',
},
},
users: {
actions: '操作',
active: '活跃',
@@ -286,6 +462,7 @@ export const enUS = {
logout: 'Log out',
greeting: 'Hi, {{name}}',
version: 'Version',
versionDetail: 'Server v{{backend}} · Console image v{{ui}}',
themeControl: 'Console theme',
languageControl: 'Console language',
expandPreferences: 'Expand preferences',
@@ -453,6 +630,181 @@ export const enUS = {
renderingDiagram: 'Rendering diagram...',
viewerHint: 'Drag to pan · Scroll to zoom · Click blank space to close',
},
dataLedger: {
title: 'Collected data',
description: 'Review infrastructure, ledgers, and raw collection metadata by Earth layer.',
layers: 'Earth layers',
resizeLayerNav: 'Resize the Earth layer navigation',
results: '{{total}} results',
resultCount: '{{total}} results',
filterCount: 'Active filters: {{count}}',
refresh: 'Refresh',
clearSearch: 'Clear search',
resetFilters: 'Reset filters',
allCountries: 'All countries and regions',
allStatuses: 'All location statuses',
allSources: 'All sources',
allTypes: 'All data types',
all: 'All',
list: 'Data records',
rawSearch: 'Search name, description, or metadata',
layerSearch: 'Search by name, ID, or source',
computeSearch: 'Search by name, operator, city, or notes',
exportFile: 'Export {{format}}',
exported: 'Exported {{format}}',
exportFailed: 'Export failed',
loadRawFailed: 'Failed to load collected data',
loadLayerFailed: 'Failed to load the {{layer}} ledger',
retry: 'Please try again later',
ledgerTitle: '{{layer}} ledger',
layerKinds: '{{layer}} categories',
rawDetail: 'Record details',
basicInfo: 'Basic information',
extraFields: 'Additional fields',
rawMetadata: 'Raw metadata',
computeTitle: 'Compute facility ledger',
loadComputeFailed: 'Failed to load the compute facility ledger',
relocate: 'Locate again',
relocateRow: 'Locate {{name}} again',
relocating: 'Locating…',
relocateFailed: 'Location lookup failed',
anonymousPlaceholder: 'The anonymous source record has no searchable location details',
anonymousPlaceholderRow: 'No searchable location details for anonymous record {{name}}',
editCoordinates: 'Edit coordinates',
editCoordinatesRow: 'Edit coordinates for {{name}}',
editCoordinatesTitle: 'Edit coordinates for {{name}}',
selectRow: 'Select {{name}}',
batchActions: 'Bulk actions',
batchLocating: 'Locating',
selected: 'Selected',
stopBatch: 'Stop bulk location lookup',
stop: 'Stop',
startBatchTitle: 'Look up locations for selected rows',
startBatch: 'Locate selected',
clearSelection: 'Clear selection',
stoppedBatch: 'Bulk lookup stopped after {{done}} of {{total}} rows',
finishedBatch: 'Bulk lookup complete. Candidates: {{found}}, unavailable: {{terminal}}, no match: {{missed}}',
finishedBatchWithFailures: 'Bulk lookup complete. Candidates: {{found}}, unavailable: {{terminal}}, no match: {{missed}}, failed: {{failed}}',
foundCandidates: 'Location candidates found: {{count}}',
adoptCandidatesHint: 'Open the row to review and adopt candidate locations',
confirmedTerminal: 'Confirmed: {{status}}',
noCandidates: 'No usable location candidates found',
invalidCoordinates: 'Enter valid nonzero latitude and longitude',
coordinatesSaved: 'Coordinates saved',
saveCoordinatesFailed: 'Failed to save coordinates',
candidateAdopted: 'Candidate coordinates adopted',
adoptCandidateFailed: 'Failed to adopt candidate coordinates',
computeDetails: 'Compute facility details',
locationDetails: 'Location details for {{name}}',
viewWorkflowRun: 'View workflow run ({{id}})',
locationEvidence: 'Verification and location details',
sourceIdentifier: 'Source identifier',
countryAndCity: 'Country / City',
locationSource: 'Location source',
evidenceNote: 'Evidence note',
noNotes: 'No additional notes',
newCandidates: 'New location candidates ({{count}})',
adopt: 'Adopt',
saveCoordinates: 'Save coordinates',
latitude: 'Latitude',
longitude: 'Longitude',
latitudeExample: 'e.g. 35.7804',
longitudeExample: 'e.g. -78.6391',
cityPlaceholder: 'City name',
countryPlaceholder: 'Country or region',
layer: {
compute: 'Compute',
satellites: 'Satellites',
cables: 'Submarine cables',
vessels: 'Vessels',
bgp: 'BGP',
news: 'News and livestreams',
weather: 'Weather',
geo: 'Geography and basemaps',
raw: 'Raw collection records',
},
kind: {
submarine_cable: 'Cable systems',
landing_point: 'Landing points',
cable_landing_relation: 'Cable landings',
collectors: 'Collectors',
incidents: 'BGP incidents',
items: 'News items',
live_streams: 'Livestream sources',
all: 'Weather layers',
cloud_map_record: 'Cloud map records',
wind_field_record: 'Wind field records',
},
siteType: {
supercomputer: 'Supercomputer',
gpu_cluster: 'GPU cluster',
data_center: 'Data center',
cloud_center: 'Cloud center',
edge_node: 'Edge node',
},
status: {
located: 'Located',
needs_confirmation: 'Needs confirmation',
terminal: 'Location unavailable',
pending: 'Pending location',
},
terminal: {
undisclosed: 'Location undisclosed',
multi_site: 'Distributed across multiple sites',
planned: 'Planned, not yet built',
cloud_only: 'Cloud-only service without a dedicated site',
anonymous: 'Anonymous facility',
},
precision: {
precise: 'Precise',
site: 'Campus',
city: 'City',
unknown: 'Unknown',
},
column: {
name: 'Name',
source: 'Source',
data_type: 'Data type',
source_id: 'Source ID',
country: 'Country',
country_region: 'Country / Region',
city: 'City',
collected_at: 'Collected at',
reference_date: 'Reference date',
site_type: 'Facility type',
operator: 'Operator',
coordinates: 'Coordinates',
precision: 'Precision',
status_bucket: 'Location status',
updated_at: 'Updated at',
verification_status: 'Verification status',
actions: 'Actions',
international_designator: 'International designator',
constellation_group: 'Constellation group',
inclination: 'Orbital inclination',
region: 'Region',
language: 'Language',
mmsi: 'MMSI',
flag: 'Flag',
vessel_type_name: 'Vessel type',
sog: 'Speed over ground',
observed_at: 'Observed at',
collector_id: 'Collector ID',
incident_type: 'Incident type',
severity: 'Severity',
status: 'Status',
started_at: 'Started at',
location_label: 'Location',
enrichment_status: 'Processing status',
published_at: 'Published at',
vessel_name: 'Vessel name',
channel_name: 'Channel name',
tile_dataset: 'Tile dataset',
incident_title: 'Incident title',
news_title: 'News headline',
norad_id: 'NORAD ID',
},
},
users: {
actions: 'Actions',
active: 'Active',
+4 -1
View File
@@ -680,6 +680,10 @@
border-bottom-color: var(--d-code-border);
}
.docs-markdown .markdown-renderer__mermaid-scroll {
width: 100%;
}
.docs-markdown .markdown-renderer__mermaid-canvas {
display: flex;
justify-content: center;
@@ -690,7 +694,6 @@
border: 0;
background: transparent;
color: inherit;
overflow-x: auto;
cursor: zoom-in;
user-select: none;
}
+6 -3
View File
@@ -10,12 +10,15 @@
.earth-desktop-handoff {
height: 100%;
min-height: 0;
overflow: auto;
background: radial-gradient(circle at 22% 18%, #0f2544 0%, #050c18 55%, #02040a 100%);
color: #e6f0ff;
}
.earth-desktop-handoff > .tui-scrollbar__viewport {
min-height: 100%;
display: grid;
place-items: center;
padding: 24px;
background: radial-gradient(circle at 22% 18%, #0f2544 0%, #050c18 55%, #02040a 100%);
color: #e6f0ff;
}
.earth-desktop-handoff__panel {
@@ -2,14 +2,16 @@ import { ArrowLeft, Download, ExternalLink } from 'lucide-react'
import { useTranslation } from 'react-i18next'
import { Link } from 'react-router-dom'
import Scrollbar from '../../components/Scrollbar/Scrollbar'
import './Earth.css'
export default function EarthDesktopRedirect() {
const { t } = useTranslation()
return (
<main className="earth-desktop-handoff">
<section className="earth-desktop-handoff__panel">
<Scrollbar className="earth-desktop-handoff" axis="y">
<main>
<section className="earth-desktop-handoff__panel">
<h1 className="earth-desktop-handoff__title">
{t('earth.desktopTitle')}
</h1>
@@ -34,6 +36,7 @@ export default function EarthDesktopRedirect() {
</Link>
</div>
</section>
</main>
</main>
</Scrollbar>
)
}
@@ -0,0 +1,82 @@
import { beforeEach, describe, expect, test } from 'bun:test'
import {
fetchRuntimeVersion,
getCachedRuntimeVersion,
parseHealthVersion,
resetRuntimeVersionCache,
} from '../src/admin/components/layout/runtimeVersion'
describe('runtimeVersion', () => {
beforeEach(() => {
resetRuntimeVersionCache()
})
test('parseHealthVersion validates and normalizes semver strings', () => {
expect(parseHealthVersion({ status: 'healthy', version: '0.84.1' })).toBe('0.84.1')
expect(parseHealthVersion({ version: ' v0.84.2-rc.1 ' })).toBe('0.84.2-rc.1')
expect(parseHealthVersion({ version: '' })).toBeNull()
expect(parseHealthVersion({ version: 'invalid' })).toBeNull()
expect(parseHealthVersion(null)).toBeNull()
})
test('fetchRuntimeVersion caches resolved backend version across calls', async () => {
let calls = 0
const fakeFetch = (async () => {
calls += 1
return new Response(JSON.stringify({ status: 'healthy', version: '0.84.1' }), {
status: 200,
headers: { 'Content-Type': 'application/json' },
})
}) as typeof fetch
expect(await fetchRuntimeVersion('0.84.0', fakeFetch)).toBe('0.84.1')
expect(getCachedRuntimeVersion()).toBe('0.84.1')
expect(await fetchRuntimeVersion('0.84.0', fakeFetch)).toBe('0.84.1')
expect(calls).toBe(1)
})
test('fetchRuntimeVersion deduplicates concurrent default fetch requests', async () => {
const originalFetch = globalThis.fetch
let calls = 0
globalThis.fetch = (async () => {
calls += 1
await Promise.resolve()
return new Response(JSON.stringify({ status: 'healthy', version: '0.84.1' }), {
status: 200,
headers: { 'Content-Type': 'application/json' },
})
}) as typeof fetch
try {
const [first, second] = await Promise.all([
fetchRuntimeVersion('0.84.0'),
fetchRuntimeVersion('0.84.0'),
])
expect(first).toBe('0.84.1')
expect(second).toBe('0.84.1')
expect(calls).toBe(1)
} finally {
globalThis.fetch = originalFetch
}
})
test('fetchRuntimeVersion falls back without caching errors', async () => {
const serverErrorFetch = (async () => new Response('error', { status: 500 })) as typeof fetch
expect(await fetchRuntimeVersion('0.84.0', serverErrorFetch)).toBe('0.84.0')
expect(getCachedRuntimeVersion()).toBeNull()
const networkErrorFetch = (async () => {
throw new Error('network down')
}) as typeof fetch
expect(await fetchRuntimeVersion('0.84.0', networkErrorFetch)).toBe('0.84.0')
expect(getCachedRuntimeVersion()).toBeNull()
const recoveryFetch = (async () =>
new Response(JSON.stringify({ status: 'healthy', version: '0.84.2' }), {
status: 200,
})) as typeof fetch
expect(await fetchRuntimeVersion('0.84.0', recoveryFetch)).toBe('0.84.2')
expect(getCachedRuntimeVersion()).toBe('0.84.2')
})
})
@@ -0,0 +1,114 @@
import { afterEach, describe, expect, mock, test } from 'bun:test'
import { readFileSync } from 'node:fs'
mock.module('satellite.js', () => ({
twoline2satrec: () => ({ satnum: '25544' }),
propagate: () => ({ position: { x: 6800, y: 0, z: 0 } }),
eciToEcf: (position: { x: number; y: number; z: number }) => position,
gstime: () => 0,
}))
const COMPACT_PAYLOAD = {
format: 'satellite_compact_v1',
count: 2,
fields: [
'id',
'norad_cat_id',
'name',
'constellation_group',
'tle_line1',
'tle_line2',
'fallback_elements',
],
satellites: [
[
1,
25544,
'ISS (ZARYA)',
'space_station',
'1 25544U 98067A 26338.50000000 .00016717 00000-0 10270-3 0 9005',
'2 25544 51.6400 200.0000 0005000 100.0000 260.0000 15.50000000123456',
null,
],
[
2,
44713,
'STARLINK-1007',
'starlink',
'1 44713U 19074A 26338.50000000 .00001000 00000-0 10000-3 0 9001',
'2 44713 53.0000 120.0000 0001500 90.0000 270.0000 15.06000000123456',
null,
],
],
}
describe('satellite refresh preservation', () => {
const originalWindow = globalThis.window
const originalFetch = globalThis.fetch
afterEach(async () => {
const { clearSatelliteData } = await import('../public/earth/js/satellites.js')
clearSatelliteData()
globalThis.window = originalWindow
globalThis.fetch = originalFetch
})
test('preserves rendered satellites when forced refresh fails and supports 304 ETag reuse', async () => {
const { getSatelliteCount, loadSatellites } = await import(
'../public/earth/js/satellites.js'
)
globalThis.window = {
location: { origin: 'https://earth.test' },
dispatchEvent: () => true,
addEventListener: () => {},
removeEventListener: () => {},
} as unknown as Window & typeof globalThis
const seenHeaders: Array<Record<string, string>> = []
let mode: 'ok' | 'fail' | '304' = 'ok'
globalThis.fetch = (async (_input: RequestInfo | URL, init?: RequestInit) => {
seenHeaders.push({ ...(init?.headers as Record<string, string> | undefined) })
if (mode === 'fail') {
return new Response('backend unavailable', { status: 502 })
}
if (mode === '304') {
return new Response(null, {
status: 304,
headers: { etag: '"sat-v1"' },
})
}
return new Response(JSON.stringify(COMPACT_PAYLOAD), {
status: 200,
headers: {
'Content-Type': 'application/json',
etag: '"sat-v1"',
},
})
}) as typeof fetch
const initial = await loadSatellites({ skipCache: true })
expect(initial.count).toBe(2)
expect(getSatelliteCount()).toBe(2)
mode = 'fail'
await expect(loadSatellites({ forceNetwork: true, skipCache: true })).rejects.toThrow('HTTP 502')
expect(getSatelliteCount()).toBe(2)
mode = '304'
const revalidated = await loadSatellites({ forceNetwork: true, skipCache: true })
expect(revalidated.notModified).toBe(true)
expect(revalidated.count).toBe(2)
expect(getSatelliteCount()).toBe(2)
expect(seenHeaders[2]?.['If-None-Match']).toBe('"sat-v1"')
})
test('ensureSatellitesEnabled does not clear satellites before loading new data', () => {
const mainSource = readFileSync(new URL('../public/earth/js/main.js', import.meta.url), 'utf8')
const startIdx = mainSource.indexOf('async function ensureSatellitesEnabled(')
expect(startIdx).toBeGreaterThan(-1)
const snippet = mainSource.slice(startIdx, mainSource.indexOf('await loadSatellites(', startIdx))
expect(snippet).not.toContain('clearSatelliteData()')
})
})
+6
View File
@@ -156,6 +156,12 @@ export default defineConfig({
https: frontendHttps,
allowedHosts: true,
proxy: {
'/api/health': {
target: backendHttpTarget,
changeOrigin: true,
secure: false,
rewrite: (reqPath) => reqPath.replace(/^\/api/, ''),
},
'/api': {
target: backendHttpTarget,
changeOrigin: true,