forked from linkong/planet
1062 lines
57 KiB
JavaScript
1062 lines
57 KiB
JavaScript
import {
|
||
computeShareMeterValue,
|
||
DEFAULT_COMPUTE_PARTICIPANTS,
|
||
memberCodes,
|
||
selectComputeParticipant,
|
||
summarizeComputeTrend,
|
||
} from "./compute-topic-model.js";
|
||
import {
|
||
createMobileFacilitiesLoader,
|
||
nextMobileRegionExpansion,
|
||
shouldLoadMobileFacilities,
|
||
} from "./compute-topic-mobile-data.js";
|
||
import { createHUDPanel } from "./hud-panels.js";
|
||
import { getEarthLocale, localizeCountryName } from "./i18n.js";
|
||
|
||
const API = "/api/v1/data-products/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,
|
||
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);
|
||
const evidencePanel = document.createElement("aside");
|
||
evidencePanel.id = "compute-evidence";
|
||
evidencePanel.className = "hud-panel hud-panel-draggable compute-evidence";
|
||
evidencePanel.hidden = true;
|
||
root.append(evidencePanel);
|
||
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 mobileCardPanels = new Map();
|
||
const expandedCards = new Set();
|
||
let mobileView = "overview";
|
||
let mobileExpandedCode = null;
|
||
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 facilities = null;
|
||
let facilitiesKey = "";
|
||
let mobileFacilitiesLoadingKey = "";
|
||
let request = null;
|
||
let serial = 0;
|
||
let evidenceId = null;
|
||
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) => `<button type="button" class="hud-panel__action" data-action="${action}" aria-label="${escape(label)}" title="${escape(label)}"><span class="material-symbols-rounded" aria-hidden="true">${name}</span></button>`;
|
||
|
||
function observation(code) {
|
||
const rows = history?.compute || [];
|
||
if (year) return rows.find((row) => row.year === Number(year));
|
||
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,
|
||
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-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("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")}">${[["global_share", text("全球算力占比", "Global compute share")], ["bilateral_share", text("中美双边算力占比", "US + China compute share")], ["absolute", text("总算力(FP32)", "Total compute (FP32)")]].map(([value, label]) => `<option value="${value}" ${mode === value ? "selected" : ""}>${label}</option>`).join("")}</select></label>
|
||
${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 sparklineHtml(entry) {
|
||
const points = historyPoints(entry);
|
||
if (points.length < 2) return "";
|
||
const width = 108;
|
||
const height = 34;
|
||
const values = points.map((point) => point.value);
|
||
const minimum = Math.min(...values);
|
||
const maximum = Math.max(...values);
|
||
const range = Math.max(1, maximum - minimum);
|
||
const coords = points.map((point, index) => ({
|
||
...point,
|
||
x: 3 + index / Math.max(1, points.length - 1) * (width - 6),
|
||
y: 4 + (maximum - point.value) / range * (height - 8),
|
||
}));
|
||
const polyline = coords.map((point) => `${point.x.toFixed(1)},${point.y.toFixed(1)}`).join(" ");
|
||
const last = coords.at(-1);
|
||
return `<svg class="compute-card__sparkline" viewBox="0 0 ${width} ${height}" role="img" aria-label="${escape(nameOf(entry))} ${text("迷你历史趋势", "compact historical trend")}"><polyline points="${polyline}"></polyline><circle cx="${last.x.toFixed(1)}" cy="${last.y.toFixed(1)}" r="2.4"><title>${last.year}: ${last.value}</title></circle></svg>`;
|
||
}
|
||
|
||
function shareMeterHtml(entry, value, basis) {
|
||
const numericValue = computeShareMeterValue(value, basis);
|
||
if (numericValue === null) return "";
|
||
const measure = basis === "bilateral_share"
|
||
? text("中美双边算力占比", "US + China compute share")
|
||
: text("全球算力占比", "Global compute share");
|
||
const label = `${nameOf(entry)} ${measure} ${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 trendSummaryHtml(entry) {
|
||
const points = historyPoints(entry);
|
||
if (points.length < 2) {
|
||
return "";
|
||
}
|
||
const maximum = Math.max(...points.map((point) => point.value));
|
||
const step = history?.mode === "absolute" ? 50 : 10;
|
||
const ceiling = Math.max(step, Math.ceil(maximum / step) * step);
|
||
const period = `${points[0].year}–${points.at(-1).year}`;
|
||
return `<p class="compute-card__trend-summary"><span class="material-symbols-rounded" aria-hidden="true">show_chart</span><span>${period}</span><span>0–${ceiling} ${escape(history?.unit || "")}</span></p>`;
|
||
}
|
||
|
||
function trendChangeHtml(entry) {
|
||
const comparable = history?.cross_year_comparable === true ||
|
||
history?.comparability === "comparable";
|
||
if (!comparable) return "";
|
||
const change = summarizeComputeTrend(historyPoints(entry), history?.mode || mode);
|
||
if (!change) return "";
|
||
const sign = change.change > 0 ? "+" : "";
|
||
const formatted = Number(change.change.toFixed(2));
|
||
const unit = change.unit === "percentage_points"
|
||
? text("个百分点", "pp")
|
||
: change.unit;
|
||
return `<p class="compute-card__trend-change"><span>${change.fromYear}→${change.toYear}</span><strong>${sign}${formatted} ${unit}</strong></p>`;
|
||
}
|
||
|
||
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 = 112;
|
||
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 - 22 - point.value / ceiling * (height - 38),
|
||
}));
|
||
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 - 22}" y2="${height - 22}"></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 - 19}" 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 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 value = row?.values?.[entry.code];
|
||
const basis = history?.mode || mode;
|
||
const rows = facilityRows(entry);
|
||
const count = rows.reduce((total, item) => total + Number(item.count || 0), 0);
|
||
const locations = facilityFeatures(entry);
|
||
const evidence = history?.evidence?.[row?.evidence_id];
|
||
const label = basis === "absolute" ? text("总算力(FP32)", "Total compute (FP32)") :
|
||
basis === "bilateral_share" ? text("中美双边算力占比", "US + China compute share") :
|
||
text("全球算力占比", "Global compute share");
|
||
const observationYear = row?.year || year || "—";
|
||
const missing = basis === "bilateral_share" && !["CN", "US"].includes(entry.code)
|
||
? text("暂无可比数据:双边口径仅适用于中国和美国", "No comparable data: bilateral basis applies to China and the US")
|
||
: entryKind(entry) === "region"
|
||
? text("暂无可比数据:该区域缺少完整的同口径统计", "No comparable data: this region lacks complete like-for-like statistics")
|
||
: text("暂无可比数据:缺少同口径统计", "No comparable data: like-for-like statistics are unavailable");
|
||
const members = memberNames(entry);
|
||
const sampleStatus = facilityError ? text("暂不可用", "Unavailable") : facilities
|
||
? text(`${count} 条记录`, `${count} records`)
|
||
: text("读取中…", "Loading…");
|
||
const sourceBreakdown = rows.map((item) =>
|
||
`${sourceName(item.source)} ${item.count}`).join(" · ");
|
||
const primaryValue = value;
|
||
const primaryUnit = basis === "absolute" ? "EF/s" : "%";
|
||
const primaryCaption = text(
|
||
`${label} · ${observationYear} 观测`,
|
||
`${label} · ${observationYear} observation`,
|
||
);
|
||
const basisNote = value == null
|
||
? missing
|
||
: basis === "global_share"
|
||
? text("计算设备总规模 · 基础/智能/超算", "Total compute equipment · general/intelligent/supercomputing")
|
||
: basis === "bilateral_share"
|
||
? text("计算设备总规模 · 基础/智能/超算;中美合计为分母", "Total compute equipment · general/intelligent/supercomputing; US + China denominator")
|
||
: text("计算设备总规模 · FP32 口径", "Total compute equipment · FP32 basis");
|
||
const memberPreview = members.slice(0, 3).map(nameOf).join(text("、", ", "));
|
||
const remainingMembers = Math.max(0, members.length - 3);
|
||
return {
|
||
basisNote,
|
||
evidence,
|
||
locations,
|
||
memberPreview,
|
||
members,
|
||
primaryCaption,
|
||
primaryUnit,
|
||
primaryValue,
|
||
remainingMembers,
|
||
row,
|
||
sampleStatus,
|
||
shareMeter: shareMeterHtml(entry, value, basis),
|
||
sourceBreakdown,
|
||
value,
|
||
};
|
||
}
|
||
|
||
function cardHtml(entry) {
|
||
const {
|
||
basisNote,
|
||
evidence,
|
||
locations,
|
||
memberPreview,
|
||
members,
|
||
primaryCaption,
|
||
primaryUnit,
|
||
primaryValue,
|
||
remainingMembers,
|
||
row,
|
||
sampleStatus,
|
||
shareMeter,
|
||
sourceBreakdown,
|
||
value,
|
||
} = participantView(entry);
|
||
const expanded = expandedCards.has(entry.code);
|
||
const toggleLabel = expanded ? text("收起详情", "Collapse details") : text("展开详情", "Expand details");
|
||
const evidenceLabel = evidence ? text("来源", "Source") : "";
|
||
const sparkline = sparklineHtml(entry);
|
||
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></div><span class="compute-card__rear-label">${text("球体背面", "Far side")}</span><div class="hud-panel__actions"><button type="button" class="hud-panel__action" data-action="card-collapse" data-card="${escape(entry.code)}" aria-expanded="${String(expanded)}" aria-label="${toggleLabel}" title="${toggleLabel}"><span class="material-symbols-rounded" aria-hidden="true">${expanded ? "expand_less" : "expand_more"}</span></button></div></header>
|
||
<div class="compute-card__summary ${sparkline ? "has-trend" : ""}"><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></div><p class="compute-card__caption">${escape(primaryCaption)}</p>${shareMeter}</div>${sparkline}</div>
|
||
<div class="compute-card__essentials"><p class="compute-card__note">${escape(basisNote)}</p>
|
||
${trendChangeHtml(entry)}
|
||
${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 class="compute-card__summary-footer">${trendSummaryHtml(entry)}${evidence ? `<button type="button" class="earth-settings-chip compute-card__source-link" data-evidence="${escape(row.evidence_id)}">${evidenceLabel}</button>` : ""}</div></div>
|
||
<div class="compute-card__body hud-panel__body hud-panel__body--collapsible hud-scroll-region" aria-hidden="${String(!expanded)}" ${expanded ? "" : "inert"}>
|
||
<section class="compute-card__section"><h4>${text("完整趋势", "Full trend")}</h4>${value == null ? coverageHtml(entry, row) : ""}${historyChartHtml(entry)}</section>
|
||
${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("数据覆盖", "Data coverage")} <span>${text("已收录设施", "Indexed facilities")} ${escape(sampleStatus)}</span></h4><p class="compute-card__empty">${text("设施记录条数仅表示当前已收录记录,不代表算力规模或覆盖率。", "Facility record counts only describe indexed records, not compute capacity or coverage.")}</p><p class="compute-card__sample">${sourceBreakdown ? `<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 facility records in this snapshot.")}</p>` : ""}</section>
|
||
${mediaHtml(locations)}
|
||
${evidence ? `<section class="compute-card__section compute-card__sources"><h4>${text("完整证据", "Full evidence")}</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(row.evidence_id)}">${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>
|
||
${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")}">${[["global_share", text("全球算力占比", "Global compute share")], ["bilateral_share", text("中美双边算力占比", "US + China compute share")], ["absolute", text("总算力(FP32)", "Total compute (FP32)")]].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 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>
|
||
<section class="compute-mobile__detail-section"><h3>${text("趋势", "Trend")}</h3>${view.value == null ? coverageHtml(entry, view.row) : ""}${historyChartHtml(entry)}</section>
|
||
${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("数据覆盖", "Data coverage")} <span>${text("已收录设施", "Indexed facilities")} ${escape(view.sampleStatus)}</span></h3><p class="earth-mobile-detail-empty">${text("设施记录条数仅表示当前已收录记录,不代表算力规模或覆盖率。", "Facility record counts only describe indexed records, not compute capacity or coverage.")}</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}"]`);
|
||
button.setAttribute("aria-label", next.getAttribute("aria-label"));
|
||
button.title = next.title;
|
||
}
|
||
}
|
||
const toggle = picker.querySelector('[data-action="toggle-cards"]');
|
||
toggle.setAttribute("aria-pressed", String(cardsEnabled));
|
||
if (cardsEnabled) toggle.title = text("隐藏区域卡片", "Hide region cards");
|
||
const evidence = history?.evidence?.[evidenceId];
|
||
if (!evidencePanel.hasChildNodes()) {
|
||
evidencePanel.innerHTML = `<header class="hud-panel__header hud-panel-drag-handle"><h3 class="hud-panel__title"></h3>${icon("close", text("关闭来源", "Close source"), "evidence-close")}</header><div class="compute-evidence__body hud-scroll-region"></div>`;
|
||
}
|
||
evidencePanel.hidden = !evidence;
|
||
if (evidence) {
|
||
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 sourceMarkup = `<p>${escape(evidence.publisher)} · ${escape(evidence.report_year || evidence.published_at || "")}</p><p>${escape(evidence.locator || "")}</p>${sourceUrl ? `<a href="${escape(sourceUrl)}" target="_blank" rel="noopener noreferrer">${text("打开来源", "Open source")} ↗</a>` : ""}`;
|
||
if (body.innerHTML !== sourceMarkup) body.innerHTML = sourceMarkup;
|
||
}
|
||
spatial.invalidate();
|
||
}
|
||
|
||
function attachCardPanel(code, element) {
|
||
cardPanels.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);
|
||
}
|
||
|
||
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));
|
||
for (const [code, element] of cards) {
|
||
if (keys.has(code)) continue;
|
||
cardPanels.get(code)?.destroy();
|
||
cardPanels.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.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.action === focusKey);
|
||
replacement?.focus({ preventScroll: true });
|
||
}
|
||
}
|
||
spatial.set(cardsEnabled ? selected.map((entry) => ({
|
||
key: entry.code,
|
||
anchor: entry.anchor,
|
||
anchorCodes: [...memberCodes(entry)],
|
||
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 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;
|
||
renderPicker();
|
||
renderCards();
|
||
renderMobile();
|
||
} 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;
|
||
spatial.set([]);
|
||
setMapQuery(null);
|
||
onDisable?.();
|
||
}
|
||
syncVisibility();
|
||
if (enabled) {
|
||
if (history && historyKey === selectionKey()) refreshFacilities();
|
||
else load();
|
||
}
|
||
renderPicker();
|
||
}
|
||
|
||
function openConfig() {
|
||
if (configVisible) return;
|
||
returnFocus = document.activeElement;
|
||
configVisible = true;
|
||
root.hidden = false;
|
||
picker.hidden = false;
|
||
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 handleClick(event) {
|
||
const button = event.target.closest("button");
|
||
if (!button) 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 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;
|
||
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 });
|
||
}
|
||
}
|
||
|
||
root.addEventListener("click", handleClick);
|
||
root.addEventListener("change", handleChange);
|
||
picker.addEventListener("click", (event) => {
|
||
event.stopPropagation();
|
||
handleClick(event);
|
||
});
|
||
picker.addEventListener("change", (event) => {
|
||
event.stopPropagation();
|
||
handleChange(event);
|
||
});
|
||
evidencePanel.addEventListener("click", (event) => {
|
||
event.stopPropagation();
|
||
handleClick(event);
|
||
});
|
||
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();
|
||
// Responsive classes are applied after the resize event by the shared controls.
|
||
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();
|
||
},
|
||
destroy() {
|
||
configVisible = false;
|
||
cardsEnabled = false;
|
||
serial++;
|
||
request?.abort();
|
||
clearInterval(configurationTimer);
|
||
configurationChannel?.close();
|
||
document.removeEventListener("visibilitychange", refreshConfiguration);
|
||
document.body.classList.remove("compute-topic-open");
|
||
for (const controller of cardPanels.values()) controller.destroy();
|
||
cardPanels.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();
|
||
},
|
||
};
|
||
}
|