1584 lines
83 KiB
JavaScript
1584 lines
83 KiB
JavaScript
import { mountCardOverlayScrollbar } from "./card-overlay-scrollbar.js";
|
||
import {
|
||
buildBilateralDuelSummary,
|
||
buildDenominatorAttributionSummary,
|
||
buildDivergenceChartGeometry,
|
||
buildInnovationConvergenceGeometry,
|
||
COMPUTE_MODE_OPTIONS,
|
||
computeShareMeterValue,
|
||
DEFAULT_COMPUTE_PARTICIPANTS,
|
||
formatStructureSegments,
|
||
getComputeModeMeta,
|
||
memberCodes,
|
||
resolveObservationWindow,
|
||
selectComputeParticipant,
|
||
summarizeComputeTrend,
|
||
} from "./compute-topic-model.js";
|
||
import {
|
||
createMobileFacilitiesLoader,
|
||
nextMobileRegionExpansion,
|
||
shouldLoadMobileFacilities,
|
||
} from "./compute-topic-mobile-data.js";
|
||
import { createHUDPanel } from "./hud-panels.js";
|
||
import { sharedHudFocusStack } from "./hud-focus-stack.js";
|
||
import { getEarthLocale, localizeCountryName } from "./i18n.js";
|
||
|
||
const API = "/api/v1/data-products/compute";
|
||
const POSTURE_API = "/api/v1/situational-awareness/posture/compute";
|
||
const MAX_VISIBLE_REGIONS = 6;
|
||
const CONFIGURATION_REFRESH_MS = 60_000;
|
||
const LOCAL_FLAG_CODES = new Set([
|
||
"af", "ao", "au", "br", "ca", "ch", "cn", "co", "cr", "de", "do", "eg",
|
||
"es", "fi", "fr", "gb", "hu", "id", "ie", "in", "it", "jp", "ke", "kr",
|
||
"lu", "md", "mx", "mz", "ng", "nl", "np", "ph", "pk", "pl", "ro", "ru",
|
||
"sg", "sy", "th", "tr", "ua", "ug", "us", "ae", "za",
|
||
]);
|
||
const text = (zh, en) => getEarthLocale() === "en-US" ? en : zh;
|
||
const escape = (value) => String(value ?? "").replace(/[&<>"']/g, (character) => ({
|
||
"&": "&", "<": "<", ">": ">", '"': """, "'": "'",
|
||
})[character]);
|
||
const entryKind = (entry) => entry?.kind === "region" || entry?.kind === "group"
|
||
? "region"
|
||
: "country";
|
||
const nameOf = (entry) => getEarthLocale() === "en-US"
|
||
? entry.name_en || localizeCountryName(entry.name || entry.code)
|
||
: entry.name || entry.code;
|
||
|
||
function groupedCatalog(catalog) {
|
||
const groups = new Map();
|
||
const regionLabel = text("区域组合", "Regional groups");
|
||
for (const entry of catalog) {
|
||
let group = regionLabel;
|
||
if (entryKind(entry) === "country") {
|
||
const parent = catalog.find((item) => item.code === entry.parent_group_code);
|
||
group = parent ? nameOf(parent) :
|
||
(getEarthLocale() === "en-US" ? entry.region_en || entry.region : entry.region) ||
|
||
text("其他国家", "Other countries");
|
||
}
|
||
if (!groups.has(group)) groups.set(group, []);
|
||
groups.get(group).push(entry);
|
||
}
|
||
return groups;
|
||
}
|
||
|
||
function safeMediaUrl(value) {
|
||
if (typeof value !== "string" || !value.trim()) return "";
|
||
try {
|
||
const url = new URL(value, window.location.origin);
|
||
return ["http:", "https:"].includes(url.protocol) ? url.href : "";
|
||
} catch {
|
||
return "";
|
||
}
|
||
}
|
||
|
||
export function initComputeTopic({
|
||
setMapQuery,
|
||
focusFacility,
|
||
rotateToRegion,
|
||
toggleNationalHubs,
|
||
openCopilot,
|
||
startStageTour,
|
||
onConfigClose,
|
||
onDisable,
|
||
spatial,
|
||
rootParent = document.body,
|
||
}) {
|
||
const root = document.createElement("section");
|
||
root.id = "compute-workspace";
|
||
root.hidden = true;
|
||
rootParent.append(root);
|
||
|
||
const picker = document.createElement("aside");
|
||
picker.id = "compute-picker";
|
||
picker.className = "hud-panel hud-panel-draggable compute-picker";
|
||
picker.hidden = true;
|
||
root.append(picker);
|
||
sharedHudFocusStack.register(picker);
|
||
|
||
const evidencePanel = document.createElement("aside");
|
||
evidencePanel.id = "compute-evidence";
|
||
evidencePanel.className = "hud-panel hud-panel-draggable compute-evidence";
|
||
evidencePanel.hidden = true;
|
||
root.append(evidencePanel);
|
||
sharedHudFocusStack.register(evidencePanel, { pinned: true, priority: 3 });
|
||
|
||
const mobileRoot = document.createElement("div");
|
||
mobileRoot.className = "compute-mobile";
|
||
root.append(mobileRoot);
|
||
|
||
const cards = new Map();
|
||
const cardMarkup = new WeakMap();
|
||
const cardPanels = new Map();
|
||
const cardScrollbars = new Map();
|
||
const mobileCardPanels = new Map();
|
||
const expandedCards = new Set(["CN", "US"]);
|
||
let mobileView = "overview";
|
||
let mobileExpandedCode = "CN";
|
||
let mobileOverviewScrollTop = 0;
|
||
let configVisible = false;
|
||
let cardsEnabled = false;
|
||
let countries = [...DEFAULT_COMPUTE_PARTICIPANTS];
|
||
let year = "";
|
||
let mode = "global_share";
|
||
let history = null;
|
||
let historyKey = "";
|
||
let postureData = null;
|
||
let postureRequest = null;
|
||
let facilities = null;
|
||
let facilitiesKey = "";
|
||
let mobileFacilitiesLoadingKey = "";
|
||
let request = null;
|
||
let serial = 0;
|
||
let evidenceId = null;
|
||
let activeMilestoneId = null;
|
||
let hoveredChartYear = null;
|
||
let nationalHubsActive = false;
|
||
let error = "";
|
||
let facilityError = "";
|
||
let selectionNotice = "";
|
||
let returnFocus = null;
|
||
|
||
const mobileFacilitiesLoader = createMobileFacilitiesLoader();
|
||
const catalog = () => Array.isArray(history?.catalog) ? history.catalog : [];
|
||
const selectionKey = () => `${countries.join(",")}:${mode}`;
|
||
const facilitiesSelectionKey = () => `${countries.join(",")}:${year || "latest"}`;
|
||
const icon = (name, label, action, extraClass = "") => `<button type="button" class="hud-panel__action ${extraClass}" data-action="${action}" aria-label="${escape(label)}" title="${escape(label)}"><span class="material-symbols-rounded" aria-hidden="true">${name}</span></button>`;
|
||
|
||
function modeSelectOptions() {
|
||
return [
|
||
...COMPUTE_MODE_OPTIONS.map((opt) => [opt.mode, text(opt.labelZh, opt.labelEn)]),
|
||
["chip_inflow_share", text("高端算力芯片流向占比", "Tracked Frontier Chip Inflows")],
|
||
["bilateral_share", text("中美双边合计算力占比", "US + China Combined Share")],
|
||
];
|
||
}
|
||
|
||
function participantPoints(code) {
|
||
return (history?.compute || []).map((row) => ({
|
||
year: row.year,
|
||
periodLabel: row.period_label || String(row.year),
|
||
value: row.values?.[code] ?? null,
|
||
evidenceId: row.evidence_id || null,
|
||
coverage: row.coverage?.[code] || null,
|
||
globalTotal: row.global_total ?? null,
|
||
}));
|
||
}
|
||
|
||
function observation(code) {
|
||
const rows = history?.compute || [];
|
||
if (year) {
|
||
const targetYear = Number(year);
|
||
return rows.find((row) => row.year === targetYear) || rows.at(-1);
|
||
}
|
||
return rows.filter((row) => row.values?.[code] != null).at(-1) ||
|
||
rows.filter((row) => row.evidence_id).at(-1) ||
|
||
rows.at(-1);
|
||
}
|
||
|
||
function historyPoints(entry) {
|
||
const cutoffYear = year ? Number(year) : Infinity;
|
||
return (history?.compute || []).filter((row) =>
|
||
row.year <= cutoffYear && Number.isFinite(row.values?.[entry.code])).map((row) => ({
|
||
year: row.year,
|
||
periodLabel: row.period_label || String(row.year),
|
||
value: row.values[entry.code],
|
||
}));
|
||
}
|
||
|
||
function pickerHtml() {
|
||
const available = catalog().filter((entry) => !countries.includes(entry.code));
|
||
const options = [...groupedCatalog(available)].map(([region, entries]) =>
|
||
`<optgroup label="${escape(region)}">${entries.map((entry) =>
|
||
`<option value="${escape(entry.code)}">${escape(nameOf(entry))}</option>`).join("")}</optgroup>`).join("");
|
||
return `<header class="hud-panel__header hud-panel__header--inset hud-panel-drag-handle">
|
||
<div class="hud-panel__title-group"><span class="material-symbols-rounded" aria-hidden="true">memory</span><h2 class="hud-panel__title">${text("算力与资源态势", "Compute intelligence")}</h2></div>
|
||
<div class="hud-panel__actions">
|
||
${icon("movie", text("播放中美算力博弈战略导览", "Play US-China compute posture tour"), "start-tour")}
|
||
${icon("view_carousel", text("显示区域卡片", "Show region cards"), "toggle-cards")}
|
||
${icon("close", text("关闭配置", "Close settings"), "close")}
|
||
</div>
|
||
</header>
|
||
<div class="compute-picker__body hud-scroll-region">
|
||
<label>${text("添加地区", "Add region")} <select data-add aria-label="${text("添加比较地区", "Add comparison region")}"><option value="">${countries.length >= MAX_VISIBLE_REGIONS ? text("选择以替换重叠区域", "Select to replace an overlapping region") : text("选择地区", "Select region")}</option>${options}</select></label>
|
||
<div class="earth-settings-chip-group" role="group" aria-label="${text("比较地区", "Compared regions")}">${countries.map((code) => {
|
||
const entry = catalog().find((item) => item.code === code);
|
||
return `<button type="button" class="earth-settings-chip is-active" data-remove="${escape(code)}" aria-label="${text("移除", "Remove")} ${escape(entry ? nameOf(entry) : code)}"><span class="earth-settings-chip__label">${escape(entry ? nameOf(entry) : code)}</span><span class="earth-settings-chip__remove" aria-hidden="true">×</span></button>`;
|
||
}).join("")}</div>
|
||
<label>${text("参考期", "Period")} <select data-year aria-label="${text("参考年份", "Reference year")}"><option value="">${text("最新观测", "Latest observation")}</option>${(history?.years || []).map((value) => `<option value="${value}" ${String(value) === year ? "selected" : ""}>${value}</option>`).join("")}</select></label>
|
||
<label>${text("口径", "Measure")} <select data-mode aria-label="${text("指标口径", "Metric basis")}">${modeSelectOptions().map(([value, label]) => `<option value="${value}" ${mode === value ? "selected" : ""}>${label}</option>`).join("")}</select></label>
|
||
<div class="compute-picker__quick-actions">
|
||
<button type="button" class="earth-settings-chip compute-picker__tour-btn" data-action="start-tour"><span class="material-symbols-rounded" aria-hidden="true">smart_display</span><span>${text("四幕算力导览", "4-Act Posture Tour")}</span></button>
|
||
<button type="button" class="earth-settings-chip compute-picker__tour-btn" data-action="open-compute-workbench"><span class="material-symbols-rounded" aria-hidden="true">forum</span><span>${text("在工作台打开算力", "Open in Workbench")}</span></button>
|
||
</div>
|
||
${selectionNotice ? `<p class="compute-picker__notice" role="status">${escape(selectionNotice)}</p>` : ""}
|
||
${error ? `<p role="alert">${escape(error)} <button type="button" class="earth-settings-chip" data-action="retry">${text("重试", "Retry")}</button></p>` : !history ? `<span role="status">${text("正在读取观测…", "Loading observations…")}</span>` : ""}
|
||
</div>`;
|
||
}
|
||
|
||
function participantIdentity(entry) {
|
||
const code = String(entry.code || "").toLowerCase();
|
||
if (entryKind(entry) === "country" && LOCAL_FLAG_CODES.has(code)) {
|
||
const label = text(`${nameOf(entry)}国旗`, `Flag of ${nameOf(entry)}`);
|
||
return `<img class="compute-card__flag" src="assets/flags/${escape(code)}.svg" alt="${escape(label)}" loading="lazy" draggable="false">`;
|
||
}
|
||
if (entryKind(entry) === "country") {
|
||
return `<span class="material-symbols-rounded compute-card__country-icon" aria-hidden="true">outlined_flag</span>`;
|
||
}
|
||
if (entry.code === "EUROPE") return '<span class="compute-card__region-monogram" aria-hidden="true">EU</span>';
|
||
const symbol = { APAC: "🌏", OTHER: "🧭" }[entry.code] || "📍";
|
||
return `<span class="compute-card__region-icon compute-card__region-emoji" aria-hidden="true">${symbol}</span>`;
|
||
}
|
||
|
||
function shareMeterHtml(entry, value, basis) {
|
||
const numericValue = computeShareMeterValue(value, basis);
|
||
if (numericValue === null) return "";
|
||
const meta = getComputeModeMeta(basis);
|
||
const label = `${nameOf(entry)} ${text(meta.labelZh, meta.labelEn)} ${numericValue}%`;
|
||
return `<span class="compute-card__share-meter" role="meter" aria-label="${escape(label)}" aria-valuemin="0" aria-valuemax="100" aria-valuenow="${numericValue}"><span style="--compute-share:${numericValue}%"></span></span>`;
|
||
}
|
||
|
||
function bilateralDuelHtml(entry) {
|
||
if (!["CN", "US"].includes(entry.code)) return "";
|
||
const focusYr = year ? Number(year) : null;
|
||
const duel = buildBilateralDuelSummary(history, focusYr);
|
||
if (!duel) return "";
|
||
return `<div class="compute-card__duel" aria-label="${escape(text("中美双边相对平价对抗比例尺", "CN-US Relative Parity Duel Scale"))}">
|
||
<div class="compute-card__duel-meta">
|
||
<span class="compute-card__duel-side is-cn">${text("中国", "CN")} <strong>${escape(duel.cnValue)}%</strong></span>
|
||
<span class="compute-card__duel-rpi" title="${escape(text("中美相对平价指数 RPI = (中国 / 美国) × 100%", "Relative Parity Index = (CN / US) × 100%"))}">RPI <strong>${escape(duel.rpiPercent)}%</strong></span>
|
||
<span class="compute-card__duel-side is-us"><strong>${escape(duel.usValue)}%</strong> ${text("美国", "US")}</span>
|
||
</div>
|
||
<div class="compute-card__duel-track">
|
||
<span class="compute-card__duel-bar is-cn" style="width:${duel.cnBarWidthPct}%"></span>
|
||
<span class="compute-card__duel-divider" aria-hidden="true"></span>
|
||
<span class="compute-card__duel-bar is-us" style="width:${duel.usBarWidthPct}%"></span>
|
||
</div>
|
||
</div>`;
|
||
}
|
||
|
||
function denominatorAttributionHtml(entry) {
|
||
const attr = buildDenominatorAttributionSummary(history, entry.code);
|
||
if (!attr) return "";
|
||
if (attr.countryGrowthPct !== null && attr.globalGrowthPct !== null && attr.latestGlobalTotal !== null) {
|
||
const sign = attr.countryGrowthPct > 0 ? "+" : "";
|
||
const gSign = attr.globalGrowthPct > 0 ? "+" : "";
|
||
const copy = attr.dilutedByGlobalExpansion
|
||
? text(
|
||
`绝对规模 ${attr.latestValue.toLocaleString("en-US")} EFlops (${sign}${attr.countryGrowthPct}%) · 全球分母增至 ${attr.latestGlobalTotal.toLocaleString("en-US")} EFlops (${gSign}${attr.globalGrowthPct}% 扩张稀释)`,
|
||
`Capacity ${attr.latestValue.toLocaleString("en-US")} EFlops (${sign}${attr.countryGrowthPct}%) · Global total ${attr.latestGlobalTotal.toLocaleString("en-US")} EFlops (${gSign}${attr.globalGrowthPct}% denominator dilution)`,
|
||
)
|
||
: text(
|
||
`绝对规模 ${attr.latestValue.toLocaleString("en-US")} EFlops (${sign}${attr.countryGrowthPct}%) · 全球总计 ${attr.latestGlobalTotal.toLocaleString("en-US")} EFlops`,
|
||
`Capacity ${attr.latestValue.toLocaleString("en-US")} EFlops (${sign}${attr.countryGrowthPct}%) · Global ${attr.latestGlobalTotal.toLocaleString("en-US")} EFlops`,
|
||
);
|
||
return `<p class="compute-card__attribution"><span class="material-symbols-rounded" aria-hidden="true">stacked_bar_chart</span><span>${escape(copy)}</span></p>`;
|
||
}
|
||
return `<p class="compute-card__attribution"><span class="material-symbols-rounded" aria-hidden="true">memory</span><span>${escape(text(`${attr.latestPeriod} 算力规模 ${attr.latestValue.toLocaleString("en-US")} EFlops`, `${attr.latestPeriod} capacity ${attr.latestValue.toLocaleString("en-US")} EFlops`))}</span></p>`;
|
||
}
|
||
|
||
function modeSwitcherHtml(entry) {
|
||
const activeBasis = history?.mode || mode;
|
||
return `<div class="compute-card__modes" role="tablist" aria-label="${escape(text("算力对比口径切换", "Compute metric basis switcher"))}">
|
||
${COMPUTE_MODE_OPTIONS.map((opt) => {
|
||
const isActive = opt.mode === activeBasis;
|
||
return `<button type="button" role="tab" aria-selected="${String(isActive)}" class="compute-card__mode-pill ${isActive ? "is-active" : ""}" data-mode-pill="${escape(opt.mode)}" data-card="${escape(entry.code)}" title="${escape(text(opt.labelZh, opt.labelEn))}">${escape(text(opt.shortZh, opt.shortEn))}</button>`;
|
||
}).join("")}
|
||
</div>`;
|
||
}
|
||
|
||
function structureEnergyBarHtml(entry) {
|
||
const seg = formatStructureSegments(history?.structures, entry.code);
|
||
if (!seg) return "";
|
||
const globalRef = seg.globalIntelligentShare !== null
|
||
? text(` · 全球智算均值 ${seg.globalIntelligentShare}%`, ` · Global AI avg ${seg.globalIntelligentShare}%`)
|
||
: "";
|
||
const noteTitle = getEarthLocale() === "en-US" ? (seg.noteEn || seg.note) : seg.note;
|
||
return `<section class="compute-card__structure" title="${escape(noteTitle)}">
|
||
<div class="compute-card__structure-head">
|
||
<span>${escape(text(`本国算力设备内部构成 (${seg.periodLabel})`, `Domestic Compute Structure (${seg.periodLabel})`))}</span>
|
||
<strong>${escape(text(`智算 ${seg.intelligentShare}%${globalRef}`, `AI ${seg.intelligentShare}%${globalRef}`))}</strong>
|
||
</div>
|
||
<div class="compute-card__structure-bar" role="img" aria-label="${escape(text(`本国智能算力占比 ${seg.intelligentShare}%,通用及超算占比 ${seg.generalAndSuperShare}%`, `Domestic AI compute ${seg.intelligentShare}%, general and supercomputing ${seg.generalAndSuperShare}%`))}">
|
||
<span class="compute-card__structure-seg is-ai" style="width:${seg.intelligentShare}%"></span>
|
||
<span class="compute-card__structure-seg is-general" style="width:${seg.generalAndSuperShare}%"></span>
|
||
</div>
|
||
<div class="compute-card__structure-legend">
|
||
<span><i class="is-ai"></i>${escape(text(`智能算力 ${seg.intelligentShare}%`, `AI Compute ${seg.intelligentShare}%`))}</span>
|
||
<span><i class="is-general"></i>${escape(text(`通算/超算 ${seg.generalAndSuperShare}%`, `General/HPC ${seg.generalAndSuperShare}%`))}</span>
|
||
</div>
|
||
</section>`;
|
||
}
|
||
|
||
function dualBilateralChartsHtml(entry) {
|
||
if (!["CN", "US"].includes(entry.code)) return "";
|
||
const divGeo = buildDivergenceChartGeometry(history?.divergence_series, history?.milestones);
|
||
const innGeo = buildInnovationConvergenceGeometry(history?.innovation, history?.innovation_summary);
|
||
if (!divGeo && !innGeo) return "";
|
||
|
||
const activeMs = (divGeo?.milestones || []).find((m) => m.id === activeMilestoneId) ||
|
||
divGeo?.milestones?.at(-1) ||
|
||
null;
|
||
|
||
const divSvg = divGeo ? (() => {
|
||
const hoverEntry = hoveredChartYear
|
||
? divGeo.years.find((item) => item.year === hoveredChartYear)
|
||
: null;
|
||
return `<figure class="compute-card__mini-chart compute-card__mini-chart--divergence">
|
||
<figcaption>
|
||
<span>${escape(text("中美总算力份额剪刀差 (%)", "US-CN Share Corridor (%)"))}</span>
|
||
<span class="compute-card__chart-legend"><i class="is-us"></i>${text("美", "US")} <i class="is-cn"></i>${text("中", "CN")}</span>
|
||
</figcaption>
|
||
<svg viewBox="0 0 ${divGeo.width} ${divGeo.height}" role="img" aria-label="${escape(text("2020至2024年中美全球算力份额剪刀差趋势", "2020-2024 US-China global compute share divergence corridor"))}">
|
||
<line class="compute-card__chart-axis" x1="${divGeo.padLeft}" x2="${divGeo.width - divGeo.padRight}" y1="${divGeo.height - divGeo.padBottom}" y2="${divGeo.height - divGeo.padBottom}"></line>
|
||
${divGeo.corridorPaths.map((d) => `<path class="compute-card__corridor-area" d="${d}"></path>`).join("")}
|
||
${hoverEntry ? `<line class="compute-card__chart-crosshair" x1="${hoverEntry.x}" x2="${hoverEntry.x}" y1="${divGeo.padTop}" y2="${divGeo.height - divGeo.padBottom}"></line>` : ""}
|
||
${divGeo.usPath ? `<path class="compute-card__line-us" d="${divGeo.usPath}"></path>` : ""}
|
||
${divGeo.cnPath ? `<path class="compute-card__line-cn" d="${divGeo.cnPath}"></path>` : ""}
|
||
${divGeo.usPoints.map((pt) => `<circle class="compute-card__pt-us ${hoveredChartYear === pt.year ? "is-hovered" : ""}" cx="${pt.x}" cy="${pt.y}" r="${hoveredChartYear === pt.year ? 3.8 : 2.6}" data-chart-year="${pt.year}"><title>${pt.year} US: ${pt.value}%</title></circle>`).join("")}
|
||
${divGeo.cnPoints.map((pt) => `<circle class="compute-card__pt-cn ${hoveredChartYear === pt.year ? "is-hovered" : ""}" cx="${pt.x}" cy="${pt.y}" r="${hoveredChartYear === pt.year ? 3.8 : 2.6}" data-chart-year="${pt.year}"><title>${pt.year} CN: ${pt.value}%</title></circle>`).join("")}
|
||
${divGeo.milestones.map((ms) => `<g class="compute-card__milestone-flag ${activeMilestoneId === ms.id ? "is-active" : ""}" transform="translate(${ms.x}, ${ms.y})" data-milestone-id="${escape(ms.id)}" role="button" tabindex="0" aria-label="${escape(getEarthLocale() === "en-US" ? ms.titleEn : ms.title)}"><polygon points="0,-4.5 4.2,0 0,4.5 -4.2,0"></polygon><title>${escape(`${ms.year}${ms.month ? `.${ms.month}` : ""} · ${getEarthLocale() === "en-US" ? ms.titleEn : ms.title}`)}</title></g>`).join("")}
|
||
<text x="${divGeo.padLeft - 4}" y="${divGeo.padTop + 6}" text-anchor="end">${divGeo.yMax}</text>
|
||
<text x="${divGeo.padLeft - 4}" y="${divGeo.height - divGeo.padBottom}" text-anchor="end">0</text>
|
||
<text x="${divGeo.padLeft}" y="${divGeo.height - 5}">${divGeo.years[0]?.year ?? ""}</text>
|
||
<text x="${divGeo.width - divGeo.padRight}" y="${divGeo.height - 5}" text-anchor="end">${divGeo.years.at(-1)?.year ?? ""}</text>
|
||
</svg>
|
||
</figure>`;
|
||
})() : "";
|
||
|
||
const innSvg = innGeo ? (() => {
|
||
const hoverPt = hoveredChartYear
|
||
? innGeo.points.find((pt) => pt.year === hoveredChartYear)
|
||
: null;
|
||
const deltaBadge = innGeo.delta !== null
|
||
? `${innGeo.delta > 0 ? "+" : ""}${innGeo.delta}`
|
||
: "";
|
||
return `<figure class="compute-card__mini-chart compute-card__mini-chart--innovation">
|
||
<figcaption>
|
||
<span>${escape(text("AI 创新分差收敛", "AI Innovation Gap"))}</span>
|
||
${deltaBadge ? `<strong class="compute-card__converge-tag">${escape(deltaBadge)} ${text("分", "pts")}</strong>` : ""}
|
||
</figcaption>
|
||
<svg viewBox="0 0 ${innGeo.width} ${innGeo.height}" role="img" aria-label="${escape(text("2023至2025年中美AI创新指数分差连续收窄曲线", "2023-2025 US-China AI innovation index gap convergence"))}">
|
||
<line class="compute-card__chart-axis" x1="${innGeo.padLeft}" x2="${innGeo.width - 10}" y1="${innGeo.yBottom}" y2="${innGeo.yBottom}"></line>
|
||
${innGeo.areaPath ? `<path class="compute-card__converge-area" d="${innGeo.areaPath}"></path>` : ""}
|
||
${hoverPt ? `<line class="compute-card__chart-crosshair" x1="${hoverPt.x}" x2="${hoverPt.x}" y1="${innGeo.padTop}" y2="${innGeo.yBottom}"></line>` : ""}
|
||
<path class="compute-card__line-converge" d="${innGeo.linePath}"></path>
|
||
${innGeo.points.map((pt) => `<g data-chart-year="${pt.year}"><circle class="compute-card__pt-converge ${hoveredChartYear === pt.year ? "is-hovered" : ""}" cx="${pt.x}" cy="${pt.y}" r="${hoveredChartYear === pt.year ? 3.8 : 2.8}"><title>${pt.year}: ${pt.value}</title></circle><text class="compute-card__pt-label" x="${pt.x}" y="${Math.max(11, pt.y - 5)}" text-anchor="middle">${pt.value}</text></g>`).join("")}
|
||
<text x="${innGeo.points[0]?.x ?? innGeo.padLeft}" y="${innGeo.height - 5}" text-anchor="start">${innGeo.points[0]?.year ?? ""}</text>
|
||
<text x="${innGeo.points.at(-1)?.x ?? (innGeo.width - 10)}" y="${innGeo.height - 5}" text-anchor="end">${innGeo.points.at(-1)?.year ?? ""}</text>
|
||
</svg>
|
||
</figure>`;
|
||
})() : "";
|
||
|
||
const milestoneBanner = activeMs ? `<div class="compute-card__milestone-strip">
|
||
<span class="compute-card__milestone-diamond" aria-hidden="true">◆</span>
|
||
<div class="compute-card__milestone-copy">
|
||
<strong>${escape(`${activeMs.year}${activeMs.month ? `.${String(activeMs.month).padStart(2, "0")}` : ""} · ${getEarthLocale() === "en-US" ? activeMs.titleEn : activeMs.title}`)}</strong>
|
||
<span>${escape(getEarthLocale() === "en-US" ? activeMs.summaryEn : activeMs.summary)}</span>
|
||
</div>
|
||
${activeMs.sourceId && history?.evidence?.[activeMs.sourceId] ? `<button type="button" class="earth-settings-chip compute-card__ms-source" data-evidence="${escape(activeMs.sourceId)}">${text("出处", "Ref")}</button>` : ""}
|
||
</div>` : "";
|
||
|
||
return `<section class="compute-card__section compute-card__dual-charts-section">
|
||
<div class="compute-card__dual-charts">${divSvg}${innSvg}</div>
|
||
${milestoneBanner}
|
||
</section>`;
|
||
}
|
||
|
||
function historyChartHtml(entry) {
|
||
const points = historyPoints(entry);
|
||
if (points.length < 2) return `<p class="compute-card__empty">${text("暂无足够的同口径历史观测。", "Not enough comparable historical observations.")}</p>`;
|
||
const width = 300;
|
||
const height = 104;
|
||
const unit = history?.unit || "";
|
||
const maxValue = Math.max(...points.map((point) => point.value));
|
||
const step = history?.mode === "absolute" ? 50 : 10;
|
||
const ceiling = Math.max(step, Math.ceil(maxValue / step) * step);
|
||
const firstYear = points[0].year;
|
||
const lastYear = points.at(-1).year;
|
||
const yearRange = Math.max(1, lastYear - firstYear);
|
||
const coords = points.map((point) => ({
|
||
...point,
|
||
x: 32 + (point.year - firstYear) / yearRange * (width - 40),
|
||
y: height - 20 - point.value / ceiling * (height - 34),
|
||
}));
|
||
const polyline = coords.map((point) =>
|
||
`${point.x.toFixed(1)},${point.y.toFixed(1)}`).join(" ");
|
||
return `<figure class="compute-card__chart"><figcaption>${text("历史观测", "Historical observations")} · 0–${ceiling} ${escape(unit)}</figcaption><svg viewBox="0 0 ${width} ${height}" role="img" aria-label="${escape(nameOf(entry))} ${text("历史观测", "historical observations")}, 0–${ceiling} ${escape(unit)}"><line class="compute-card__chart-axis" x1="32" x2="${width - 8}" y1="${height - 20}" y2="${height - 20}"></line><polyline points="${polyline}"></polyline>${coords.map((point) => `<circle cx="${point.x.toFixed(1)}" cy="${point.y.toFixed(1)}" r="3"><title>${point.year}: ${point.value} ${escape(unit)}</title></circle>`).join("")}<text x="27" y="13" text-anchor="end">${ceiling}</text><text x="27" y="${height - 17}" text-anchor="end">0</text><text x="32" y="${height - 4}">${firstYear}</text><text x="${width - 8}" y="${height - 4}" text-anchor="end">${lastYear}</text></svg></figure>`;
|
||
}
|
||
|
||
function postureBriefHtml(entry, primaryEvidenceId) {
|
||
const payload = postureData?.payload;
|
||
if (!payload) return "";
|
||
const isEn = getEarthLocale() === "en-US";
|
||
const assertion = isEn
|
||
? (payload.executive_assertion_en || payload.executive_assertion)
|
||
: payload.executive_assertion;
|
||
const hubsAvailable = entry.code === "CN" && Array.isArray(history?.national_hubs) && history.national_hubs.length > 0;
|
||
const primaryEv = primaryEvidenceId ? history?.evidence?.[primaryEvidenceId] : null;
|
||
const evChipLabel = primaryEv
|
||
? text(`证据溯源 · ${primaryEv.report_year}报告`, `Evidence · ${primaryEv.report_year}`)
|
||
: text("证据溯源", "Evidence");
|
||
|
||
return `<section class="compute-card__section compute-card__posture-box">
|
||
<div class="compute-card__posture-header">
|
||
<span class="compute-card__posture-kicker">✦ ${escape(text("战略参谋研判", "Strategic Posture Brief"))}</span>
|
||
${postureData.revision ? `<span class="compute-card__posture-rev">Rev.${escape(postureData.revision)}</span>` : ""}
|
||
</div>
|
||
<p class="compute-card__posture-copy">${escape(assertion)}</p>
|
||
<div class="compute-card__action-bar">
|
||
${primaryEvidenceId ? `<button type="button" class="earth-settings-chip compute-card__action-pill" data-evidence="${escape(primaryEvidenceId)}"><span class="material-symbols-rounded" aria-hidden="true">menu_book</span><span>${escape(evChipLabel)}</span></button>` : ""}
|
||
${hubsAvailable ? `<button type="button" class="earth-settings-chip compute-card__action-pill compute-card__hubs-btn ${nationalHubsActive ? "is-active" : ""}" data-action="drilldown-hubs" aria-pressed="${String(nationalHubsActive)}"><span class="material-symbols-rounded" aria-hidden="true">bolt</span><span>${escape(nationalHubsActive ? text("收起八大枢纽", "Hide 8 Hubs") : text("下钻八大枢纽", "8 National Hubs"))}</span></button>` : ""}
|
||
<button type="button" class="earth-settings-chip compute-card__action-pill" data-action="open-copilot" data-card="${escape(entry.code)}"><span class="material-symbols-rounded" aria-hidden="true">forum</span><span>${escape(text("追问此态势", "Ask Copilot"))}</span></button>
|
||
</div>
|
||
</section>`;
|
||
}
|
||
|
||
function coverageState(entry, row) {
|
||
const coverage = row?.coverage?.[entry.code] || history?.coverage?.[entry.code];
|
||
if (!coverage) return null;
|
||
const coverageCount = (value, fallback = 0) => Array.isArray(value)
|
||
? value.length
|
||
: Number(value ?? fallback);
|
||
const required = coverageCount(coverage.required_members, memberCodes(entry).size);
|
||
const covered = coverageCount(coverage.covered_members, coverage.covered ?? 0);
|
||
const complete = coverage.status === "complete" || coverage.status === "available" ||
|
||
(required > 0 && covered >= required);
|
||
return { complete, covered, required };
|
||
}
|
||
|
||
function coverageHtml(entry, row) {
|
||
const coverage = coverageState(entry, row);
|
||
if (!coverage) return "";
|
||
const { complete, covered, required } = coverage;
|
||
const summary = complete
|
||
? text(`覆盖 ${covered}/${required} 个成员`, `${covered}/${required} members covered`)
|
||
: text(`覆盖 ${covered}/${required} 个成员;区域值暂不合成`, `${covered}/${required} members covered; regional value withheld`);
|
||
return `<p class="compute-card__coverage ${complete ? "is-complete" : "is-partial"}"><span class="material-symbols-rounded" aria-hidden="true">${complete ? "verified" : "data_info_alert"}</span>${escape(summary)}</p>`;
|
||
}
|
||
|
||
function memberNames(entry) {
|
||
if (entryKind(entry) !== "region") return [];
|
||
const byCode = new Map(catalog().map((item) => [item.code, item]));
|
||
return [...memberCodes(entry)].map((code) => byCode.get(code)).filter(Boolean);
|
||
}
|
||
|
||
function facilityMatches(entry, value) {
|
||
if (!value) return false;
|
||
const properties = value.properties || value;
|
||
if (properties.participant_code === entry.code) return true;
|
||
const members = memberCodes(entry);
|
||
if (members.has(properties.country_code)) return true;
|
||
const countryNames = new Set(catalog().filter((item) =>
|
||
entryKind(item) === "country" && members.has(item.code)).map((item) => item.name));
|
||
return countryNames.has(properties.country) || countryNames.has(properties.source_country);
|
||
}
|
||
|
||
function facilityRows(entry) {
|
||
const rows = Array.isArray(facilities?.participant_counts)
|
||
? facilities.participant_counts
|
||
: Array.isArray(facilities?.counts) ? facilities.counts : [];
|
||
const direct = rows.filter((item) => item.participant_code === entry.code);
|
||
return direct.length ? direct : rows.filter((item) => facilityMatches(entry, item));
|
||
}
|
||
|
||
function facilityFeatures(entry) {
|
||
return (facilities?.features || []).filter((feature) => facilityMatches(entry, feature));
|
||
}
|
||
|
||
function sourceName(source) {
|
||
return ({
|
||
epoch_ai_gpu: "Epoch AI",
|
||
top500: "TOP500",
|
||
})[source] || source || text("其他", "Other");
|
||
}
|
||
|
||
function mediaHtml(features) {
|
||
const items = [];
|
||
for (const feature of features) {
|
||
const properties = feature.properties || {};
|
||
const candidates = [
|
||
properties.image_url,
|
||
properties.photo_url,
|
||
...(Array.isArray(properties.images) ? properties.images : []),
|
||
];
|
||
const url = candidates.map((candidate) =>
|
||
safeMediaUrl(typeof candidate === "string" ? candidate : candidate?.url)).find(Boolean);
|
||
if (url) items.push({ url, name: properties.name || text("设施现场", "Facility") });
|
||
if (items.length >= 2) break;
|
||
}
|
||
if (!items.length) return "";
|
||
return `<section class="compute-card__section"><h4>${text("机房与设施影像", "Facility media")}</h4><div class="compute-card__media">${items.map((item) => `<figure><img src="${escape(item.url)}" alt="${escape(item.name)}" loading="lazy" referrerpolicy="no-referrer"><figcaption>${escape(item.name)}</figcaption></figure>`).join("")}</div></section>`;
|
||
}
|
||
|
||
function participantView(entry) {
|
||
const row = observation(entry.code);
|
||
const basis = history?.mode || mode;
|
||
const meta = getComputeModeMeta(basis);
|
||
const obsWindow = resolveObservationWindow(
|
||
participantPoints(entry.code),
|
||
year ? Number(year) : null,
|
||
);
|
||
const value = year ? (row?.values?.[entry.code] ?? null) : (obsWindow.activePoint?.value ?? row?.values?.[entry.code] ?? null);
|
||
const activeEvidenceId = (year ? row?.evidence_id : (obsWindow.activePoint?.evidenceId || row?.evidence_id)) ||
|
||
Object.keys(history?.evidence || {})[0] ||
|
||
null;
|
||
const evidence = activeEvidenceId ? history?.evidence?.[activeEvidenceId] : null;
|
||
|
||
const rows = facilityRows(entry);
|
||
const count = rows.reduce((total, item) => total + Number(item.count || 0), 0);
|
||
const locations = facilityFeatures(entry);
|
||
const label = text(meta.labelZh, meta.labelEn);
|
||
const periodText = (year ? (row?.period_label || year) : (obsWindow.latestReferenceLabel || row?.period_label || row?.year)) || "—";
|
||
|
||
const referenceBadge = obsWindow.isAfterLatestReference && obsWindow.latestReferenceLabel
|
||
? text(`${year} 待发布 · 最新核实 ${obsWindow.latestReferenceLabel}`, `${year} pending · latest ${obsWindow.latestReferenceLabel}`)
|
||
: evidence?.report_year
|
||
? text(`${periodText} 观测 · ${evidence.report_year}报告`, `${periodText} obs · ${evidence.report_year} report`)
|
||
: text(`${periodText} 观测`, `${periodText} obs`);
|
||
|
||
const missing = ["bilateral_share", "bilateral_rpi"].includes(basis) && !["CN", "US"].includes(entry.code)
|
||
? text("暂无可比数据:双边口径仅适用于中国与美国", "No comparable data: bilateral basis applies to China and the US")
|
||
: obsWindow.isAfterLatestReference && obsWindow.latestReferenceLabel
|
||
? text(`选定年份 (${year}) 晚于最新已核实参考期 (${obsWindow.latestReferenceLabel}),不静默回填冒充当年实测`, `Selected year (${year}) is later than latest verified period (${obsWindow.latestReferenceLabel}); withheld without backfill`)
|
||
: entryKind(entry) === "region"
|
||
? text("暂无可比数据:该区域缺少完整的同年同口径统计", "No comparable data: region lacks complete same-year statistics")
|
||
: text("暂无可比数据:缺少已核验同口径统计", "No comparable data: verified statistics unavailable");
|
||
|
||
const members = memberNames(entry);
|
||
const sampleStatus = facilityError ? text("暂不可用", "Unavailable") : facilities
|
||
? text(`${count} 条样本`, `${count} indexed`)
|
||
: text("读取中…", "Loading…");
|
||
const sourceBreakdown = rows.map((item) =>
|
||
`${sourceName(item.source)} ${item.count}`).join(" · ");
|
||
const primaryValue = value;
|
||
const primaryUnit = basis === "absolute" ? "EFlops" : "%";
|
||
const primaryCaption = text(`${label} · ${periodText}`, `${label} · ${periodText}`);
|
||
const basisNote = value == null
|
||
? missing
|
||
: history?.denominator || label;
|
||
const memberPreview = members.slice(0, 3).map(nameOf).join(text("、", ", "));
|
||
const remainingMembers = Math.max(0, members.length - 3);
|
||
const trendChange = summarizeComputeTrend(historyPoints(entry), basis);
|
||
|
||
return {
|
||
activeEvidenceId,
|
||
basis,
|
||
basisNote,
|
||
evidence,
|
||
locations,
|
||
memberPreview,
|
||
members,
|
||
obsWindow,
|
||
primaryCaption,
|
||
primaryUnit,
|
||
primaryValue,
|
||
referenceBadge,
|
||
remainingMembers,
|
||
row,
|
||
sampleStatus,
|
||
shareMeter: shareMeterHtml(entry, value, basis),
|
||
sourceBreakdown,
|
||
trendChange,
|
||
value,
|
||
};
|
||
}
|
||
|
||
function formatDeltaPill(trendChange) {
|
||
if (!trendChange) return "";
|
||
const sign = trendChange.change > 0 ? "+" : "";
|
||
const arrow = trendChange.change > 0 ? "▲" : trendChange.change < 0 ? "▼" : "•";
|
||
const unit = trendChange.unit === "percentage_points" ? "pp" : "EFlops";
|
||
const tone = trendChange.change > 0 ? "is-up" : trendChange.change < 0 ? "is-down" : "is-flat";
|
||
return `<span class="compute-card__delta-pill ${tone}" title="${escape(`${trendChange.fromYear} → ${trendChange.toYear}`)}">${arrow} ${sign}${trendChange.change} ${unit} <small>(${trendChange.fromYear}→${trendChange.toYear})</small></span>`;
|
||
}
|
||
|
||
function cardHtml(entry) {
|
||
const view = participantView(entry);
|
||
const {
|
||
activeEvidenceId,
|
||
basisNote,
|
||
evidence,
|
||
locations,
|
||
memberPreview,
|
||
members,
|
||
primaryCaption,
|
||
primaryUnit,
|
||
primaryValue,
|
||
referenceBadge,
|
||
remainingMembers,
|
||
row,
|
||
sampleStatus,
|
||
shareMeter,
|
||
sourceBreakdown,
|
||
trendChange,
|
||
value,
|
||
} = view;
|
||
|
||
const expanded = expandedCards.has(entry.code);
|
||
const toggleLabel = expanded ? text("收起详情", "Collapse details") : text("展开详情", "Expand details");
|
||
const analyzeLabel = text(
|
||
`在 AI 参谋中分析${nameOf(entry)}`,
|
||
`Analyze ${nameOf(entry)} in AI Copilot`,
|
||
);
|
||
const rotateLabel = text(
|
||
`将地球旋转对准${nameOf(entry)}正面`,
|
||
`Rotate globe to face ${nameOf(entry)}`,
|
||
);
|
||
const capsuleMetric = primaryValue == null ? "—" : `${primaryValue}${primaryUnit}`;
|
||
const isBilateralCountry = ["CN", "US"].includes(entry.code) &&
|
||
countries.includes("CN") &&
|
||
countries.includes("US");
|
||
|
||
return `<header class="hud-panel__header hud-panel__header--inset hud-panel-drag-handle">
|
||
<div class="hud-panel__title-group">
|
||
${participantIdentity(entry)}
|
||
<h3 class="hud-panel__title">${escape(nameOf(entry))}</h3>
|
||
<span class="compute-card__period-badge">${escape(referenceBadge)}</span>
|
||
</div>
|
||
<span class="compute-card__capsule-metric" aria-hidden="true">${escape(capsuleMetric)}</span>
|
||
<div class="hud-panel__actions">
|
||
<button type="button" class="hud-panel__action" data-action="open-copilot" data-card="${escape(entry.code)}" aria-label="${escape(analyzeLabel)}" title="${escape(analyzeLabel)}"><span class="material-symbols-rounded" aria-hidden="true">forum</span></button>
|
||
<button type="button" class="hud-panel__action compute-card__rotate-btn" data-action="rotate-to-front" data-card="${escape(entry.code)}" aria-label="${escape(rotateLabel)}" title="${escape(rotateLabel)}"><span class="material-symbols-rounded" aria-hidden="true">explore</span></button>
|
||
<button type="button" class="hud-panel__action" data-action="card-collapse" data-card="${escape(entry.code)}" aria-expanded="${String(expanded)}" aria-label="${escape(toggleLabel)}" title="${escape(toggleLabel)}"><span class="material-symbols-rounded" aria-hidden="true">${expanded ? "expand_less" : "expand_more"}</span></button>
|
||
</div>
|
||
</header>
|
||
<div class="compute-card__summary">
|
||
<div class="compute-card__hero-row">
|
||
<div class="compute-card__metric-block">
|
||
<div class="compute-card__metric ${primaryValue == null ? "is-missing" : ""}">
|
||
<strong>${primaryValue == null ? "—" : escape(primaryValue)}</strong>
|
||
<span>${escape(primaryUnit)}</span>
|
||
${formatDeltaPill(trendChange)}
|
||
</div>
|
||
<p class="compute-card__caption">${escape(primaryCaption)}</p>
|
||
</div>
|
||
</div>
|
||
${denominatorAttributionHtml(entry)}
|
||
${bilateralDuelHtml(entry)}
|
||
${!isBilateralCountry ? shareMeter : ""}
|
||
</div>
|
||
<div class="compute-card__essentials">
|
||
${modeSwitcherHtml(entry)}
|
||
${structureEnergyBarHtml(entry)}
|
||
${value == null ? `<p class="compute-card__note">${escape(basisNote)}</p>` : ""}
|
||
${members.length ? `<p class="compute-card__member-preview"><span>${text("区域成员", "Region members")} ${members.length}</span><span title="${escape(members.map(nameOf).join(text("、", ", ")))}">${escape(memberPreview)}${remainingMembers ? ` +${remainingMembers}` : ""}</span></p>` : ""}
|
||
</div>
|
||
<div class="compute-card__body hud-panel__body hud-panel__body--collapsible hud-scroll-region" aria-hidden="${String(!expanded)}" ${expanded ? "" : "inert"}>
|
||
${isBilateralCountry ? dualBilateralChartsHtml(entry) : `<section class="compute-card__section"><h4>${text("完整趋势", "Full trend")}</h4>${value == null ? coverageHtml(entry, row) : ""}${historyChartHtml(entry)}</section>`}
|
||
${postureBriefHtml(entry, activeEvidenceId)}
|
||
${members.length ? `<section class="compute-card__section"><h4>${text("区域成员", "Region members")} <span>${members.length}</span></h4><div class="compute-card__members">${members.map((member) => `<span class="earth-settings-chip earth-settings-chip--with-icon">${participantIdentity(member)}<span>${escape(nameOf(member))}</span></span>`).join("")}</div></section>` : ""}
|
||
<section class="compute-card__section">
|
||
<h4>${text("已核验重点集群样本", "Verified Facility Samples")} <span>${escape(sampleStatus)}</span></h4>
|
||
<p class="compute-card__empty">${text("设施条数仅代表公开已收录样本,不代表国家总算力。", "Facility counts reflect publicly indexed samples only, not national total compute.")}</p>
|
||
${sourceBreakdown ? `<p class="compute-card__sample"><span>${escape(sourceBreakdown)}</span></p>` : ""}
|
||
${locations.length ? `<div class="compute-card__facilities">${locations.slice(0, 4).map((feature) => `<button type="button" class="earth-settings-chip" data-facility="${escape(feature.id)}">${escape(feature.properties?.name || feature.id)}</button>`).join("")}</div>` : facilities && !facilityError ? `<p class="compute-card__empty">${text("当前快照没有已核验定位设施记录。", "No verified geolocated facility records in this snapshot.")}</p>` : ""}
|
||
</section>
|
||
${mediaHtml(locations)}
|
||
${!postureData && evidence ? `<section class="compute-card__section compute-card__sources"><h4>${text("权威来源", "Verified Source")}</h4><p class="compute-card__empty">${escape(evidence.publisher || "")} · ${escape(evidence.report_year || evidence.published_at || "")}</p><button type="button" class="earth-settings-chip" data-evidence="${escape(activeEvidenceId)}">${text("查看完整来源", "View full source")}</button></section>` : ""}
|
||
</div>`;
|
||
}
|
||
|
||
const isMobileLayout = () =>
|
||
document.documentElement.classList.contains("layout-mode-mobile");
|
||
const mobileSlot = () => document.querySelector('[data-drawer-slot="compute"]');
|
||
|
||
function loadMobileFacilities({ force = false } = {}) {
|
||
const shouldLoad = shouldLoadMobileFacilities({
|
||
cardsEnabled,
|
||
isMobile: isMobileLayout(),
|
||
mobileActive: mobileSlot()?.classList.contains("is-active") === true,
|
||
});
|
||
if (!shouldLoad) {
|
||
mobileFacilitiesLoader.cancel();
|
||
mobileFacilitiesLoadingKey = "";
|
||
return;
|
||
}
|
||
|
||
const key = facilitiesSelectionKey();
|
||
if (!force && facilities && facilitiesKey === key) return;
|
||
if (!force && mobileFacilitiesLoadingKey === key) return;
|
||
facilities = null;
|
||
facilitiesKey = "";
|
||
facilityError = "";
|
||
mobileFacilitiesLoadingKey = key;
|
||
renderMobile();
|
||
void mobileFacilitiesLoader.load({
|
||
countries,
|
||
year,
|
||
onSuccess(payload) {
|
||
if (key !== facilitiesSelectionKey() || cardsEnabled) return;
|
||
facilities = payload;
|
||
facilitiesKey = key;
|
||
facilityError = "";
|
||
mobileFacilitiesLoadingKey = "";
|
||
renderCards();
|
||
renderMobile();
|
||
},
|
||
onError() {
|
||
if (key !== facilitiesSelectionKey() || cardsEnabled) return;
|
||
facilities = null;
|
||
facilitiesKey = "";
|
||
mobileFacilitiesLoadingKey = "";
|
||
facilityError = text("设施快照暂不可用,请重试", "Facility snapshot unavailable. Please retry.");
|
||
renderMobile();
|
||
},
|
||
});
|
||
}
|
||
|
||
function mobileToggleHtml() {
|
||
return `<label class="earth-mobile-settings-card compute-mobile__toggle">
|
||
<div class="earth-mobile-settings-copy"><span class="earth-mobile-settings-label">${text("显示地图卡片", "Show map cards")}</span><span class="earth-mobile-settings-subtitle">${text("关闭后仍可在此浏览算力对比数据", "Browse compute comparisons here even when map cards are off")}</span></div>
|
||
<span class="earth-mobile-settings-switch"><input type="checkbox" data-enabled ${cardsEnabled ? "checked" : ""} aria-label="${text("显示地图算力卡片", "Show compute cards on the map")}"><span class="earth-mobile-settings-switch-track"></span></span>
|
||
</label>`;
|
||
}
|
||
|
||
function mobileStatusHtml() {
|
||
if (error) {
|
||
return `<div class="earth-mobile-detail-card compute-mobile__status" role="alert"><span>${escape(error)}</span><button type="button" class="earth-mobile-action-btn earth-mobile-action-btn--ghost" data-action="retry">${text("重新加载", "Retry")}</button></div>`;
|
||
}
|
||
if (!history) {
|
||
return `<div class="earth-mobile-detail-card compute-mobile__status" role="status">${text("正在读取算力观测…", "Loading compute observations…")}</div>`;
|
||
}
|
||
if (facilityError) {
|
||
return `<div class="earth-mobile-detail-card compute-mobile__status" role="alert"><span>${escape(facilityError)}</span><button type="button" class="earth-mobile-action-btn earth-mobile-action-btn--ghost" data-action="retry">${text("重新加载", "Retry")}</button></div>`;
|
||
}
|
||
return "";
|
||
}
|
||
|
||
function mobileRegionRowHtml(entry) {
|
||
const view = participantView(entry);
|
||
const expanded = mobileExpandedCode === entry.code;
|
||
const basis = view.value == null
|
||
? entryKind(entry) === "region"
|
||
? text(`${view.primaryCaption} · 暂无可比数据 · ${view.members.length} 个成员`, `${view.primaryCaption} · no comparable data · ${view.members.length} members`)
|
||
: text(`${view.primaryCaption} · 暂无可比数据`, `${view.primaryCaption} · no comparable data`)
|
||
: view.primaryCaption;
|
||
return `<article class="compute-mobile__region-item ${expanded ? "is-expanded" : "hud-panel--collapsed"}" data-mobile-region-card="${escape(entry.code)}">
|
||
<button type="button" class="earth-mobile-layer-card compute-mobile__region" data-mobile-region="${escape(entry.code)}" aria-expanded="${String(expanded)}">
|
||
<span class="compute-mobile__region-icon">${participantIdentity(entry)}</span>
|
||
<span class="earth-mobile-layer-card-copy"><span class="earth-mobile-layer-card-title">${escape(nameOf(entry))}</span><span class="earth-mobile-layer-card-subtitle">${escape(basis)}</span>${view.shareMeter}</span>
|
||
<span class="compute-mobile__metric ${view.primaryValue == null ? "is-missing" : ""}"><span><strong>${view.primaryValue == null ? "—" : escape(view.primaryValue)}</strong><small>${escape(view.primaryUnit)}</small></span><span class="material-symbols-rounded" data-mobile-chevron aria-hidden="true">${expanded ? "expand_less" : "expand_more"}</span></span>
|
||
</button>
|
||
<div class="compute-mobile__region-detail hud-panel__body--collapsible" aria-hidden="${String(!expanded)}" ${expanded ? "" : "inert"}><div class="compute-mobile__region-detail-inner">${mobileRegionDetailHtml(entry, view)}</div></div>
|
||
</article>`;
|
||
}
|
||
|
||
function mobileOverviewHtml() {
|
||
const selected = countries.map((code) =>
|
||
catalog().find((entry) => entry.code === code)).filter(Boolean);
|
||
const status = cardsEnabled
|
||
? text(`${selected.length} 个比较地区 · 地图卡片开启`, `${selected.length} comparisons · map cards on`)
|
||
: text(`${selected.length} 个比较地区 · 地图卡片关闭`, `${selected.length} comparisons · map cards off`);
|
||
return `<div class="earth-mobile-page earth-mobile-page--compute">
|
||
<div class="compute-mobile__page-header"><div class="earth-mobile-page-intro"><span class="earth-mobile-page-kicker">${text("算力态势", "Compute intelligence")}</span><span class="earth-mobile-page-summary">${status}</span></div><div class="compute-mobile__header-actions"><label class="compute-mobile__header-toggle"><span>${text("地图卡片", "Map cards")}</span><span class="earth-mobile-settings-switch"><input type="checkbox" data-enabled ${cardsEnabled ? "checked" : ""} aria-label="${text("显示地图算力卡片;关闭后仍可浏览算力数据", "Show compute cards on the map; data remains available when off")}"><span class="earth-mobile-settings-switch-track"></span></span></label><button type="button" class="earth-mobile-action-btn earth-mobile-action-btn--compact earth-mobile-action-btn--ghost" data-mobile-settings aria-label="${text("对比设置", "Comparison settings")}" title="${text("对比设置", "Comparison settings")}"><span class="material-symbols-rounded" aria-hidden="true">tune</span></button></div></div>
|
||
${history ? `<div class="compute-mobile__modes">${modeSwitcherHtml({ code: "MOBILE" })}</div>` : ""}
|
||
${mobileStatusHtml()}
|
||
${history ? `<div class="compute-mobile__region-list">${selected.map(mobileRegionRowHtml).join("")}</div>` : ""}
|
||
</div>`;
|
||
}
|
||
|
||
function mobileSettingsHtml() {
|
||
const available = catalog().filter((entry) => !countries.includes(entry.code));
|
||
const options = [...groupedCatalog(available)].map(([region, entries]) =>
|
||
`<optgroup label="${escape(region)}">${entries.map((entry) =>
|
||
`<option value="${escape(entry.code)}">${escape(nameOf(entry))}</option>`).join("")}</optgroup>`).join("");
|
||
return `<div class="earth-mobile-page earth-mobile-page--compute compute-mobile__settings">
|
||
<div class="compute-mobile__page-header"><button type="button" class="earth-mobile-action-btn earth-mobile-action-btn--compact earth-mobile-action-btn--ghost" data-mobile-back aria-label="${text("返回算力概览", "Back to compute overview")}" title="${text("返回", "Back")}"><span class="material-symbols-rounded" aria-hidden="true">arrow_back</span></button><div class="earth-mobile-page-intro"><span class="earth-mobile-page-kicker">${text("对比设置", "Comparison settings")}</span><span class="earth-mobile-page-summary">${text("调整地区、年份和指标口径", "Choose regions, year, and measure")}</span></div></div>
|
||
${mobileToggleHtml()}
|
||
<div class="earth-mobile-settings-group">
|
||
<label class="earth-mobile-settings-card earth-mobile-settings-card--stacked compute-mobile__field"><div class="earth-mobile-settings-copy"><span class="earth-mobile-settings-label">${text("添加地区", "Add region")}</span><span class="earth-mobile-settings-subtitle">${text("选择国家时会替换重叠的父区域", "Choosing a country replaces its overlapping parent region")}</span></div><select data-add aria-label="${text("添加比较地区", "Add comparison region")}"><option value="">${countries.length >= MAX_VISIBLE_REGIONS ? text("选择以替换重叠区域", "Select to replace an overlapping region") : text("选择地区", "Select region")}</option>${options}</select></label>
|
||
<div class="earth-mobile-settings-card earth-mobile-settings-card--stacked"><div class="earth-mobile-settings-copy"><span class="earth-mobile-settings-label">${text("比较地区", "Compared regions")}</span><span class="earth-mobile-settings-subtitle">${text("至少保留一个,最多六个", "Keep at least one, up to six")}</span></div><div class="earth-mobile-settings-chip-grid">${countries.map((code) => {
|
||
const entry = catalog().find((item) => item.code === code);
|
||
return `<button type="button" class="earth-mobile-settings-chip is-active" data-remove="${escape(code)}" aria-label="${text("移除", "Remove")} ${escape(entry ? nameOf(entry) : code)}"><span class="earth-settings-chip__label">${escape(entry ? nameOf(entry) : code)}</span><span class="earth-settings-chip__remove" aria-hidden="true">×</span></button>`;
|
||
}).join("")}</div></div>
|
||
<label class="earth-mobile-settings-card compute-mobile__field"><div class="earth-mobile-settings-copy"><span class="earth-mobile-settings-label">${text("参考期", "Period")}</span><span class="earth-mobile-settings-subtitle">${text("历史设施按年末快照读取", "Historical facilities use year-end snapshots")}</span></div><select data-year aria-label="${text("参考年份", "Reference year")}"><option value="">${text("最新观测", "Latest observation")}</option>${(history?.years || []).map((value) => `<option value="${value}" ${String(value) === year ? "selected" : ""}>${value}</option>`).join("")}</select></label>
|
||
<label class="earth-mobile-settings-card compute-mobile__field"><div class="earth-mobile-settings-copy"><span class="earth-mobile-settings-label">${text("指标口径", "Measure")}</span><span class="earth-mobile-settings-subtitle">${text("区域缺失值不会从设施样本反推", "Missing regional values are never inferred from facility samples")}</span></div><select data-mode aria-label="${text("指标口径", "Metric basis")}">${modeSelectOptions().map(([value, label]) => `<option value="${value}" ${mode === value ? "selected" : ""}>${label}</option>`).join("")}</select></label>
|
||
</div>
|
||
${selectionNotice ? `<p class="earth-mobile-page-summary" role="status">${escape(selectionNotice)}</p>` : ""}
|
||
${mobileStatusHtml()}
|
||
</div>`;
|
||
}
|
||
|
||
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>`
|
||
: !facilities ? `<p class="earth-mobile-detail-empty" role="status">${text("正在读取设施样本…", "Loading facility samples…")}</p>`
|
||
: view.locations.length ? `<div class="compute-mobile__facility-list hud-scroll-region">${view.locations.map((feature) => `<button type="button" class="earth-mobile-action-btn earth-mobile-action-btn--ghost" data-facility="${escape(feature.id)}">${escape(feature.properties?.name || feature.id)}</button>`).join("")}</div>`
|
||
: `<p class="earth-mobile-detail-empty">${text("当前快照没有已核验定位设施记录。", "No verified facility records in this snapshot.")}</p>`;
|
||
return `<p class="compute-card__note">${escape(view.basisNote)}</p>
|
||
${denominatorAttributionHtml(entry)}
|
||
${bilateralDuelHtml(entry)}
|
||
${structureEnergyBarHtml(entry)}
|
||
<section class="compute-mobile__detail-section"><h3>${text("趋势与分差", "Trend & Divergence")}</h3>${view.value == null ? coverageHtml(entry, view.row) : ""}${isBilateral ? dualBilateralChartsHtml(entry) : historyChartHtml(entry)}</section>
|
||
${postureBriefHtml(entry, view.activeEvidenceId)}
|
||
${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, not national total compute.")}</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>` : ""}`;
|
||
}
|
||
|
||
function destroyMobileCardPanels() {
|
||
for (const controller of mobileCardPanels.values()) controller.destroy();
|
||
mobileCardPanels.clear();
|
||
}
|
||
|
||
function setMobileCardExpanded(code, expanded) {
|
||
const item = mobileRoot.querySelector(`[data-mobile-region-card="${CSS.escape(code)}"]`);
|
||
const header = item?.querySelector("[data-mobile-region]");
|
||
const body = item?.querySelector(".compute-mobile__region-detail");
|
||
const chevron = header?.querySelector("[data-mobile-chevron]");
|
||
item?.classList.toggle("is-expanded", expanded);
|
||
mobileCardPanels.get(code)?.setCollapsed(!expanded);
|
||
if (header) header.setAttribute("aria-expanded", String(expanded));
|
||
if (body) {
|
||
body.inert = !expanded;
|
||
body.setAttribute("aria-hidden", String(!expanded));
|
||
}
|
||
if (chevron) chevron.textContent = expanded ? "expand_less" : "expand_more";
|
||
}
|
||
|
||
function attachMobileCardPanels() {
|
||
destroyMobileCardPanels();
|
||
for (const item of mobileRoot.querySelectorAll("[data-mobile-region-card]")) {
|
||
const code = item.dataset.mobileRegionCard;
|
||
const body = item.querySelector(".compute-mobile__region-detail");
|
||
const controller = createHUDPanel({
|
||
panel: item,
|
||
header: item.querySelector("[data-mobile-region]"),
|
||
body,
|
||
collapseBtn: null,
|
||
});
|
||
mobileCardPanels.set(code, controller);
|
||
controller.setCollapsed(code !== mobileExpandedCode);
|
||
}
|
||
}
|
||
|
||
function renderMobile() {
|
||
destroyMobileCardPanels();
|
||
if (!countries.includes(mobileExpandedCode)) mobileExpandedCode = null;
|
||
mobileRoot.innerHTML = mobileView === "settings"
|
||
? mobileSettingsHtml()
|
||
: mobileOverviewHtml();
|
||
if (mobileView === "overview") {
|
||
attachMobileCardPanels();
|
||
requestAnimationFrame(() => {
|
||
const slot = mobileSlot();
|
||
if (slot) slot.scrollTop = mobileOverviewScrollTop;
|
||
});
|
||
}
|
||
}
|
||
|
||
function renderPicker() {
|
||
const markup = pickerHtml();
|
||
if (!picker.hasChildNodes()) {
|
||
picker.innerHTML = markup;
|
||
} else {
|
||
const draft = document.createElement("div");
|
||
draft.innerHTML = markup;
|
||
const oldBody = picker.querySelector(".compute-picker__body");
|
||
const newBody = draft.querySelector(".compute-picker__body");
|
||
if (oldBody && newBody && oldBody.innerHTML !== newBody.innerHTML) {
|
||
const scrollTop = oldBody.scrollTop;
|
||
const active = oldBody.contains(document.activeElement) ? document.activeElement : null;
|
||
const activeSelector = active?.matches("[data-add]") ? "[data-add]" :
|
||
active?.matches("[data-year]") ? "[data-year]" :
|
||
active?.matches("[data-mode]") ? "[data-mode]" : null;
|
||
oldBody.innerHTML = newBody.innerHTML;
|
||
oldBody.scrollTop = scrollTop;
|
||
if (activeSelector) oldBody.querySelector(activeSelector)?.focus({ preventScroll: true });
|
||
}
|
||
picker.querySelector(".hud-panel__title").textContent =
|
||
draft.querySelector(".hud-panel__title").textContent;
|
||
for (const button of picker.querySelectorAll(".hud-panel__actions button")) {
|
||
const next = draft.querySelector(`[data-action="${button.dataset.action}"]`);
|
||
if (!next) continue;
|
||
button.setAttribute("aria-label", next.getAttribute("aria-label"));
|
||
button.title = next.title;
|
||
}
|
||
}
|
||
const toggle = picker.querySelector('[data-action="toggle-cards"]');
|
||
if (toggle) {
|
||
toggle.setAttribute("aria-pressed", String(cardsEnabled));
|
||
if (cardsEnabled) toggle.title = text("隐藏区域卡片", "Hide region cards");
|
||
}
|
||
const evidence = history?.evidence?.[evidenceId] || postureData?.evidence?.[evidenceId];
|
||
if (!evidencePanel.hasChildNodes()) {
|
||
evidencePanel.innerHTML = `<header class="hud-panel__header hud-panel__header--inset hud-panel-drag-handle"><div class="hud-panel__title-group"><span class="material-symbols-rounded" aria-hidden="true">menu_book</span><h3 class="hud-panel__title"></h3></div><div class="hud-panel__actions">${icon("close", text("关闭来源", "Close source"), "evidence-close", "hud-panel-close")}</div></header><div class="compute-evidence__body hud-scroll-region"></div>`;
|
||
}
|
||
evidencePanel.hidden = !evidence;
|
||
if (evidence) {
|
||
sharedHudFocusStack.focus(evidencePanel, { source: "user" });
|
||
const sourceUrl = /^https:\/\//i.test(evidence.url || "") ? evidence.url : "";
|
||
evidencePanel.querySelector(".hud-panel__title").textContent = evidence.title;
|
||
const close = evidencePanel.querySelector('[data-action="evidence-close"]');
|
||
close.title = text("关闭来源", "Close source");
|
||
close.setAttribute("aria-label", close.title);
|
||
const body = evidencePanel.querySelector(".compute-evidence__body");
|
||
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>` : ""}`;
|
||
if (body.innerHTML !== sourceMarkup) body.innerHTML = sourceMarkup;
|
||
}
|
||
spatial.invalidate();
|
||
}
|
||
|
||
function attachCardPanel(code, element) {
|
||
cardPanels.get(code)?.destroy();
|
||
cardScrollbars.get(code)?.destroy();
|
||
const controller = createHUDPanel({
|
||
panel: element,
|
||
header: element.querySelector(".hud-panel__header"),
|
||
body: element.querySelector(".compute-card__body"),
|
||
collapseBtn: element.querySelector('[data-action="card-collapse"]'),
|
||
expandLabel: text("展开详情", "Expand details"),
|
||
collapseLabel: text("收起详情", "Collapse details"),
|
||
});
|
||
controller.setCollapsed(!expandedCards.has(code));
|
||
cardPanels.set(code, controller);
|
||
const bodyEl = element.querySelector(".compute-card__body");
|
||
if (bodyEl) {
|
||
cardScrollbars.set(code, mountCardOverlayScrollbar(bodyEl, {
|
||
hostEl: element,
|
||
hoverTarget: element,
|
||
}));
|
||
}
|
||
}
|
||
|
||
function renderCards() {
|
||
const selected = countries.map((code) =>
|
||
catalog().find((entry) => entry.code === code)).filter(Boolean);
|
||
if (isMobileLayout()) {
|
||
for (const element of cards.values()) element.hidden = true;
|
||
spatial.set([]);
|
||
renderMobile();
|
||
return;
|
||
}
|
||
const keys = new Set(selected.map((entry) => entry.code));
|
||
const hasBilateralPair = keys.has("CN") && keys.has("US");
|
||
for (const [code, element] of cards) {
|
||
if (keys.has(code)) continue;
|
||
cardPanels.get(code)?.destroy();
|
||
cardPanels.delete(code);
|
||
cardScrollbars.get(code)?.destroy();
|
||
cardScrollbars.delete(code);
|
||
element.remove();
|
||
cards.delete(code);
|
||
}
|
||
for (const entry of selected) {
|
||
let element = cards.get(entry.code);
|
||
if (!element) {
|
||
element = document.createElement("article");
|
||
element.className = "hud-panel compute-card";
|
||
element.dataset.region = entry.code;
|
||
root.append(element);
|
||
cards.set(entry.code, element);
|
||
}
|
||
const expanded = expandedCards.has(entry.code);
|
||
element.hidden = !cardsEnabled;
|
||
element.dataset.kind = entryKind(entry);
|
||
element.classList.toggle("hud-panel--collapsed", !expanded);
|
||
element.classList.toggle("is-expanded", expanded);
|
||
const markup = cardHtml(entry);
|
||
if (cardMarkup.get(element) === markup) continue;
|
||
const focused = element.contains(document.activeElement) ? document.activeElement : null;
|
||
const focusKey = focused?.dataset.evidence || focused?.dataset.facility ||
|
||
focused?.dataset.modePill || focused?.dataset.action;
|
||
const scrollTop = element.querySelector(".compute-card__body")?.scrollTop || 0;
|
||
element.innerHTML = markup;
|
||
cardMarkup.set(element, markup);
|
||
attachCardPanel(entry.code, element);
|
||
const body = element.querySelector(".compute-card__body");
|
||
if (body) body.scrollTop = scrollTop;
|
||
if (focusKey) {
|
||
const replacement = [...element.querySelectorAll("button")].find((button) =>
|
||
button.dataset.evidence === focusKey || button.dataset.facility === focusKey ||
|
||
button.dataset.modePill === focusKey || button.dataset.action === focusKey);
|
||
replacement?.focus({ preventScroll: true });
|
||
}
|
||
}
|
||
spatial.set(cardsEnabled ? selected.map((entry) => ({
|
||
key: entry.code,
|
||
anchor: entry.anchor,
|
||
anchorCodes: [...memberCodes(entry)],
|
||
defaultSpotlight: entry.code === "CN" || entry.code === "US",
|
||
preferredSide: entry.code === "CN" ? "left" : entry.code === "US" ? "right" : null,
|
||
bilateralPeerKey: hasBilateralPair
|
||
? (entry.code === "CN" ? "US" : entry.code === "US" ? "CN" : null)
|
||
: null,
|
||
element: cards.get(entry.code),
|
||
})) : []);
|
||
}
|
||
|
||
function refreshFacilities() {
|
||
mobileFacilitiesLoader.cancel();
|
||
mobileFacilitiesLoadingKey = "";
|
||
facilities = null;
|
||
facilitiesKey = "";
|
||
facilityError = "";
|
||
if (cardsEnabled) setMapQuery({ countries: countries.join(","), year });
|
||
renderCards();
|
||
renderMobile();
|
||
}
|
||
|
||
async function loadPosture(token) {
|
||
postureRequest?.abort();
|
||
postureRequest = new AbortController();
|
||
try {
|
||
const params = new URLSearchParams({ countries: countries.join(","), mode });
|
||
const res = await fetch(`${POSTURE_API}?${params}`, {
|
||
signal: postureRequest.signal,
|
||
cache: "no-store",
|
||
});
|
||
if (!res.ok) return;
|
||
const data = await res.json();
|
||
if (token !== serial || (!configVisible && !cardsEnabled)) return;
|
||
postureData = data;
|
||
renderCards();
|
||
renderMobile();
|
||
} catch {
|
||
// Non-blocking: deterministic series data continues rendering cleanly
|
||
}
|
||
}
|
||
|
||
async function load({ refreshMap = true } = {}) {
|
||
request?.abort();
|
||
request = new AbortController();
|
||
const token = ++serial;
|
||
const key = selectionKey();
|
||
error = "";
|
||
renderPicker();
|
||
renderMobile();
|
||
loadMobileFacilities();
|
||
if (refreshMap && cardsEnabled) refreshFacilities();
|
||
try {
|
||
const params = new URLSearchParams({ countries: countries.join(","), mode });
|
||
const response = await fetch(`${API}/series?${params}`, { signal: request.signal, cache: "no-store" });
|
||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||
const payload = await response.json();
|
||
if (token !== serial || (!configVisible && !cardsEnabled)) return;
|
||
history = payload;
|
||
historyKey = key;
|
||
if (nationalHubsActive && Array.isArray(history.national_hubs) && history.national_hubs.length) {
|
||
toggleNationalHubs?.(history.national_hubs, true, { flyCamera: false });
|
||
} else if (nationalHubsActive && !countries.includes("CN")) {
|
||
nationalHubsActive = false;
|
||
toggleNationalHubs?.([], false, { flyCamera: false });
|
||
}
|
||
renderPicker();
|
||
renderCards();
|
||
renderMobile();
|
||
void loadPosture(token);
|
||
} catch (failure) {
|
||
if (failure.name === "AbortError" || token !== serial ||
|
||
(!configVisible && !cardsEnabled)) return;
|
||
error = text("观测暂不可用,请重试。", "Observations unavailable. Please retry.");
|
||
renderPicker();
|
||
renderMobile();
|
||
}
|
||
}
|
||
|
||
function syncLayout() {
|
||
const mobile = document.documentElement.classList.contains("layout-mode-mobile");
|
||
const slot = document.querySelector('[data-drawer-slot="compute"]');
|
||
const parent = mobile && slot ? slot : document.body;
|
||
if (root.parentElement !== parent) parent.append(root);
|
||
if (mobile && picker.parentElement !== root) root.prepend(picker);
|
||
if (mobile && evidencePanel.parentElement !== root) root.append(evidencePanel);
|
||
syncVisibility();
|
||
requestAnimationFrame(() => loadMobileFacilities());
|
||
spatial.invalidate();
|
||
}
|
||
|
||
function syncVisibility() {
|
||
const mobile = isMobileLayout();
|
||
root.hidden = mobile ? false : !configVisible && !cardsEnabled;
|
||
picker.hidden = mobile || !configVisible;
|
||
document.body.classList.toggle("compute-topic-open", cardsEnabled);
|
||
renderCards();
|
||
renderMobile();
|
||
loadMobileFacilities();
|
||
}
|
||
|
||
function closeConfig() {
|
||
if (!configVisible) return;
|
||
configVisible = false;
|
||
picker.hidden = true;
|
||
evidenceId = null;
|
||
evidencePanel.hidden = true;
|
||
root.hidden = !cardsEnabled;
|
||
onConfigClose?.({ cardsEnabled });
|
||
returnFocus?.focus();
|
||
}
|
||
|
||
function setCardsEnabled(enabled) {
|
||
if (enabled === cardsEnabled) return;
|
||
cardsEnabled = enabled;
|
||
if (!enabled) {
|
||
evidenceId = null;
|
||
evidencePanel.hidden = true;
|
||
nationalHubsActive = false;
|
||
toggleNationalHubs?.([], false, { flyCamera: false });
|
||
spatial.set([]);
|
||
setMapQuery(null);
|
||
onDisable?.();
|
||
} else {
|
||
if (countries.includes("CN")) expandedCards.add("CN");
|
||
if (countries.includes("US")) expandedCards.add("US");
|
||
}
|
||
syncVisibility();
|
||
if (enabled) {
|
||
if (history && historyKey === selectionKey()) {
|
||
refreshFacilities();
|
||
if (!postureData) void loadPosture(serial);
|
||
} else {
|
||
load();
|
||
}
|
||
}
|
||
renderPicker();
|
||
if (enabled) {
|
||
sharedHudFocusStack.focus([...cards.values()], { source: "user" });
|
||
}
|
||
}
|
||
|
||
function openConfig() {
|
||
if (configVisible) {
|
||
sharedHudFocusStack.focus(picker, { source: "user" });
|
||
return;
|
||
}
|
||
returnFocus = document.activeElement;
|
||
configVisible = true;
|
||
root.hidden = false;
|
||
picker.hidden = false;
|
||
sharedHudFocusStack.focus(picker, { source: "user" });
|
||
syncLayout();
|
||
renderPicker();
|
||
renderCards();
|
||
if (!history || error || historyKey !== selectionKey()) {
|
||
load({ refreshMap: cardsEnabled });
|
||
}
|
||
}
|
||
|
||
function toggleCard(code) {
|
||
const expanded = !expandedCards.has(code);
|
||
if (expanded) expandedCards.add(code);
|
||
else expandedCards.delete(code);
|
||
const element = cards.get(code);
|
||
element?.classList.toggle("is-expanded", expanded);
|
||
cardPanels.get(code)?.setCollapsed(!expanded);
|
||
const body = element?.querySelector(".compute-card__body");
|
||
if (body) {
|
||
body.inert = !expanded;
|
||
body.setAttribute("aria-hidden", String(!expanded));
|
||
}
|
||
const button = element?.querySelector('[data-action="card-collapse"]');
|
||
if (button) {
|
||
const label = expanded ? text("收起详情", "Collapse details") :
|
||
text("展开详情", "Expand details");
|
||
button.setAttribute("aria-expanded", String(expanded));
|
||
button.setAttribute("aria-label", label);
|
||
button.title = label;
|
||
}
|
||
if (element) cardMarkup.delete(element);
|
||
spatial.invalidate();
|
||
setTimeout(() => spatial.invalidate(), 300);
|
||
button?.focus({ preventScroll: true });
|
||
}
|
||
|
||
function toggleMobileRegion(code) {
|
||
const previous = mobileExpandedCode;
|
||
const next = nextMobileRegionExpansion(previous, code);
|
||
mobileExpandedCode = next;
|
||
if (previous) setMobileCardExpanded(previous, false);
|
||
if (next) setMobileCardExpanded(next, true);
|
||
}
|
||
|
||
function switchMode(nextMode) {
|
||
if (!nextMode || nextMode === mode) return;
|
||
mode = nextMode;
|
||
load({ refreshMap: false });
|
||
}
|
||
|
||
function handleClick(event) {
|
||
const msFlag = event.target.closest("[data-milestone-id]");
|
||
if (msFlag) {
|
||
activeMilestoneId = msFlag.dataset.milestoneId;
|
||
renderCards();
|
||
renderMobile();
|
||
return;
|
||
}
|
||
|
||
const button = event.target.closest("button");
|
||
if (!button) return;
|
||
|
||
if (button.dataset.modePill) {
|
||
switchMode(button.dataset.modePill);
|
||
return;
|
||
}
|
||
if (button.dataset.action === "rotate-to-front" && button.dataset.card) {
|
||
const entry = catalog().find((item) => item.code === button.dataset.card);
|
||
if (entry) rotateToRegion?.(entry);
|
||
return;
|
||
}
|
||
if (button.dataset.action === "drilldown-hubs") {
|
||
nationalHubsActive = !nationalHubsActive;
|
||
toggleNationalHubs?.(history?.national_hubs || [], nationalHubsActive, { flyCamera: nationalHubsActive });
|
||
renderCards();
|
||
renderMobile();
|
||
return;
|
||
}
|
||
if (button.dataset.action === "open-copilot") {
|
||
openCopilot?.({
|
||
domain: "compute",
|
||
selectedCodes: [...countries],
|
||
focusYear: year ? Number(year) : null,
|
||
mode: history?.mode || mode,
|
||
entityId: button.dataset.card || "CN",
|
||
revision: postureData?.revision || null,
|
||
evidence: history?.evidence || {},
|
||
});
|
||
return;
|
||
}
|
||
if (button.dataset.action === "start-tour") {
|
||
if (!cardsEnabled) setCardsEnabled(true);
|
||
startStageTour?.("compute-posture-cn-us");
|
||
return;
|
||
}
|
||
if (button.dataset.action === "open-compute-workbench") {
|
||
openCopilot?.({
|
||
domain: "compute",
|
||
selectedCodes: [...countries],
|
||
focusYear: year ? Number(year) : null,
|
||
mode: history?.mode || mode,
|
||
entityId: countries[0] || "CN",
|
||
revision: postureData?.revision || null,
|
||
evidence: history?.evidence || {},
|
||
});
|
||
return;
|
||
}
|
||
if (button.hasAttribute("data-mobile-settings")) {
|
||
mobileView = "settings";
|
||
renderMobile();
|
||
const slot = mobileSlot();
|
||
if (slot) slot.scrollTop = 0;
|
||
return;
|
||
}
|
||
if (button.hasAttribute("data-mobile-back")) {
|
||
mobileView = "overview";
|
||
renderMobile();
|
||
return;
|
||
}
|
||
if (button.dataset.mobileRegion) {
|
||
toggleMobileRegion(button.dataset.mobileRegion);
|
||
return;
|
||
}
|
||
if (button.dataset.action === "close") closeConfig();
|
||
if (button.dataset.action === "toggle-cards") setCardsEnabled(!cardsEnabled);
|
||
if (button.dataset.action === "retry") load();
|
||
if (button.dataset.action === "evidence-close") {
|
||
evidenceId = null;
|
||
renderPicker();
|
||
}
|
||
if (button.dataset.evidence) {
|
||
evidenceId = button.dataset.evidence;
|
||
renderPicker();
|
||
}
|
||
if (button.dataset.action === "card-collapse" && button.dataset.card) {
|
||
toggleCard(button.dataset.card);
|
||
}
|
||
if (button.dataset.remove && countries.length > 1) {
|
||
countries = countries.filter((code) => code !== button.dataset.remove);
|
||
expandedCards.delete(button.dataset.remove);
|
||
evidenceId = null;
|
||
selectionNotice = "";
|
||
renderCards();
|
||
load();
|
||
}
|
||
if (button.dataset.facility) focusFacility(button.dataset.facility);
|
||
}
|
||
|
||
function handlePointerOver(event) {
|
||
const yearEl = event.target.closest("[data-chart-year]");
|
||
const nextYear = yearEl ? Number(yearEl.dataset.chartYear) : null;
|
||
if (Number.isFinite(nextYear) && nextYear !== hoveredChartYear) {
|
||
hoveredChartYear = nextYear;
|
||
renderCards();
|
||
}
|
||
}
|
||
|
||
function handlePointerOut(event) {
|
||
if (!hoveredChartYear) return;
|
||
const leavingChart = event.target.closest(".compute-card__dual-charts");
|
||
if (leavingChart && !leavingChart.contains(event.relatedTarget)) {
|
||
hoveredChartYear = null;
|
||
renderCards();
|
||
}
|
||
}
|
||
|
||
function handleChange(event) {
|
||
if (event.target.matches("[data-enabled]")) {
|
||
setCardsEnabled(event.target.checked);
|
||
}
|
||
if (event.target.matches("[data-add]")) {
|
||
const code = event.target.value;
|
||
const result = selectComputeParticipant(
|
||
countries,
|
||
code,
|
||
catalog(),
|
||
MAX_VISIBLE_REGIONS,
|
||
);
|
||
if (result.limitReached) {
|
||
selectionNotice = text(
|
||
"最多同时比较 6 个地区。",
|
||
"Compare up to 6 regions at a time.",
|
||
);
|
||
renderPicker();
|
||
return;
|
||
}
|
||
if (result.codes.join(",") !== countries.join(",")) {
|
||
countries = result.codes;
|
||
if (code === "CN" || code === "US") expandedCards.add(code);
|
||
const replacements = result.replaced.map((item) =>
|
||
catalog().find((entry) => entry.code === item)).filter(Boolean);
|
||
selectionNotice = replacements.length
|
||
? text(
|
||
`已替换重叠区域:${replacements.map(nameOf).join("、")}`,
|
||
`Replaced overlapping region: ${replacements.map(nameOf).join(", ")}`,
|
||
)
|
||
: "";
|
||
for (const replaced of result.replaced) expandedCards.delete(replaced);
|
||
renderCards();
|
||
load();
|
||
}
|
||
}
|
||
if (event.target.matches("[data-year]")) {
|
||
year = event.target.value;
|
||
evidenceId = null;
|
||
if (cardsEnabled) refreshFacilities();
|
||
else {
|
||
renderCards();
|
||
renderMobile();
|
||
loadMobileFacilities({ force: true });
|
||
}
|
||
}
|
||
if (event.target.matches("[data-mode]")) {
|
||
mode = event.target.value;
|
||
load({ refreshMap: false });
|
||
}
|
||
}
|
||
|
||
const onHubsStateEvent = (event) => {
|
||
const nextActive = Boolean(event?.detail?.active);
|
||
if (nationalHubsActive !== nextActive) {
|
||
nationalHubsActive = nextActive;
|
||
renderCards();
|
||
renderMobile();
|
||
}
|
||
};
|
||
|
||
root.addEventListener("click", handleClick);
|
||
root.addEventListener("change", handleChange);
|
||
root.addEventListener("pointerover", handlePointerOver);
|
||
root.addEventListener("pointerout", handlePointerOut);
|
||
picker.addEventListener("click", (event) => {
|
||
event.stopPropagation();
|
||
handleClick(event);
|
||
});
|
||
picker.addEventListener("change", (event) => {
|
||
event.stopPropagation();
|
||
handleChange(event);
|
||
});
|
||
evidencePanel.addEventListener("click", (event) => {
|
||
event.stopPropagation();
|
||
handleClick(event);
|
||
});
|
||
window.addEventListener("earth:national-hubs-state", onHubsStateEvent);
|
||
|
||
const trigger = document.getElementById("open-compute-topic");
|
||
const mobileTrigger = document.querySelector('[data-drawer-card="compute"]');
|
||
const mobileSlotElement = mobileSlot();
|
||
const mobileSlotObserver = new MutationObserver(() => loadMobileFacilities());
|
||
const rememberMobileOverviewScroll = () => {
|
||
if (mobileView === "overview" && mobileSlotElement) {
|
||
mobileOverviewScrollTop = mobileSlotElement.scrollTop;
|
||
}
|
||
};
|
||
trigger?.addEventListener("click", openConfig);
|
||
const openMobile = () => {
|
||
if (isMobileLayout()) {
|
||
mobileView = "overview";
|
||
renderMobile();
|
||
requestAnimationFrame(() => loadMobileFacilities());
|
||
}
|
||
openConfig();
|
||
};
|
||
mobileTrigger?.addEventListener("click", openMobile);
|
||
mobileSlotElement?.addEventListener("scroll", rememberMobileOverviewScroll, { passive: true });
|
||
if (mobileSlotElement) {
|
||
mobileSlotObserver.observe(mobileSlotElement, {
|
||
attributes: true,
|
||
attributeFilter: ["class"],
|
||
});
|
||
}
|
||
const resize = () => syncLayout();
|
||
const layoutObserver = new MutationObserver(syncLayout);
|
||
layoutObserver.observe(document.documentElement, { attributes: true, attributeFilter: ["class"] });
|
||
const locale = () => {
|
||
if (configVisible || evidenceId) renderPicker();
|
||
if (cardsEnabled) renderCards();
|
||
renderMobile();
|
||
};
|
||
window.addEventListener("resize", resize);
|
||
window.addEventListener("earth:locale-change", locale);
|
||
const refreshConfiguration = () => {
|
||
if (!document.hidden && (configVisible || cardsEnabled)) load({ refreshMap: false });
|
||
};
|
||
const configurationChannel = typeof BroadcastChannel === "undefined" ? null
|
||
: new BroadcastChannel("planet-compute-configuration");
|
||
if (configurationChannel) configurationChannel.onmessage = refreshConfiguration;
|
||
const configurationTimer = setInterval(refreshConfiguration, CONFIGURATION_REFRESH_MS);
|
||
document.addEventListener("visibilitychange", refreshConfiguration);
|
||
renderPicker();
|
||
renderMobile();
|
||
|
||
return {
|
||
receiveFacilities(payload, failure) {
|
||
if (!cardsEnabled) return;
|
||
facilities = failure ? null : payload;
|
||
facilitiesKey = failure ? "" : facilitiesSelectionKey();
|
||
mobileFacilitiesLoadingKey = "";
|
||
facilityError = failure
|
||
? text("设施快照暂不可用", "Facility snapshot unavailable")
|
||
: "";
|
||
renderCards();
|
||
renderMobile();
|
||
},
|
||
openCardsAndEnsureLoaded() {
|
||
if (!countries.includes("CN") || !countries.includes("US")) {
|
||
countries = [...DEFAULT_COMPUTE_PARTICIPANTS];
|
||
}
|
||
expandedCards.add("CN");
|
||
expandedCards.add("US");
|
||
if (!cardsEnabled) {
|
||
setCardsEnabled(true);
|
||
} else if (!history) {
|
||
load();
|
||
}
|
||
},
|
||
closeCards() {
|
||
setCardsEnabled(false);
|
||
},
|
||
applyStageStep(step = {}) {
|
||
const suppressAutoOpen = Boolean(step.suppressAutoOpenCards);
|
||
if (!cardsEnabled && !suppressAutoOpen) {
|
||
expandedCards.add("CN");
|
||
expandedCards.add("US");
|
||
setCardsEnabled(true);
|
||
}
|
||
let needsLoad = false;
|
||
if (step.computeMode && step.computeMode !== mode) {
|
||
mode = step.computeMode;
|
||
needsLoad = true;
|
||
}
|
||
hoveredChartYear = Number.isFinite(step.focusYear) ? step.focusYear : null;
|
||
activeMilestoneId = step.highlightMilestoneId || null;
|
||
if (cardsEnabled && Array.isArray(step.spotlightCodes) && step.spotlightCodes.length) {
|
||
for (const c of step.spotlightCodes) expandedCards.add(c);
|
||
spatial.setSpotlightKeys?.(step.spotlightCodes);
|
||
}
|
||
if (typeof step.enableNationalHubs === "boolean") {
|
||
nationalHubsActive = step.enableNationalHubs;
|
||
if (nationalHubsActive && !Array.isArray(history?.national_hubs)) {
|
||
const params = new URLSearchParams({ countries: "CN,US", mode });
|
||
void fetch(`${API}/series?${params}`, { cache: "no-store" })
|
||
.then((r) => (r.ok ? r.json() : null))
|
||
.then((payload) => {
|
||
if (payload) history = payload;
|
||
if (nationalHubsActive && Array.isArray(payload?.national_hubs)) {
|
||
toggleNationalHubs?.(payload.national_hubs, true, { flyCamera: false });
|
||
}
|
||
})
|
||
.catch(() => {});
|
||
} else {
|
||
toggleNationalHubs?.(
|
||
history?.national_hubs || [],
|
||
nationalHubsActive,
|
||
{ flyCamera: false },
|
||
);
|
||
}
|
||
}
|
||
if (!cardsEnabled) {
|
||
return;
|
||
}
|
||
if (needsLoad) {
|
||
load({ refreshMap: false });
|
||
} else {
|
||
renderPicker();
|
||
renderCards();
|
||
renderMobile();
|
||
}
|
||
const focusSource = step.focusSource === "user" ? "user" : "system";
|
||
const spotlightCodes = Array.isArray(step.spotlightCodes) && step.spotlightCodes.length
|
||
? step.spotlightCodes
|
||
: ["CN", "US"];
|
||
const activeElements = spotlightCodes
|
||
.map((code) => cards.get(code))
|
||
.filter(Boolean);
|
||
if (activeElements.length) {
|
||
sharedHudFocusStack.focus(activeElements, {
|
||
source: focusSource,
|
||
kind: "stage_act",
|
||
});
|
||
}
|
||
},
|
||
refreshFromOutbox() {
|
||
if (configVisible || cardsEnabled) {
|
||
load({ refreshMap: false });
|
||
}
|
||
},
|
||
getState() {
|
||
return {
|
||
cardsEnabled,
|
||
countries: [...countries],
|
||
year,
|
||
mode: history?.mode || mode,
|
||
revision: postureData?.revision || null,
|
||
nationalHubsActive,
|
||
evidence: history?.evidence || {},
|
||
};
|
||
},
|
||
destroy() {
|
||
configVisible = false;
|
||
cardsEnabled = false;
|
||
serial++;
|
||
request?.abort();
|
||
postureRequest?.abort();
|
||
clearInterval(configurationTimer);
|
||
configurationChannel?.close();
|
||
document.removeEventListener("visibilitychange", refreshConfiguration);
|
||
window.removeEventListener("earth:national-hubs-state", onHubsStateEvent);
|
||
document.body.classList.remove("compute-topic-open");
|
||
for (const controller of cardPanels.values()) controller.destroy();
|
||
cardPanels.clear();
|
||
for (const sb of cardScrollbars.values()) sb.destroy();
|
||
cardScrollbars.clear();
|
||
destroyMobileCardPanels();
|
||
spatial.destroy();
|
||
layoutObserver.disconnect();
|
||
mobileSlotObserver.disconnect();
|
||
mobileFacilitiesLoader.cancel();
|
||
window.removeEventListener("resize", resize);
|
||
window.removeEventListener("earth:locale-change", locale);
|
||
trigger?.removeEventListener("click", openConfig);
|
||
mobileTrigger?.removeEventListener("click", openMobile);
|
||
mobileSlotElement?.removeEventListener("scroll", rememberMobileOverviewScroll);
|
||
picker.remove();
|
||
evidencePanel.remove();
|
||
root.remove();
|
||
},
|
||
};
|
||
}
|