Files
planet/frontend/public/earth/js/cluster-presentation.js
T
linkong 3b1b9ef68c
ci / backend (push) Canceled after 0s
ci / frontend (push) Canceled after 0s
ci / delivery (push) Canceled after 0s
release: bump version to 0.83.0
2026-12-02 18:53:58 +08:00

465 lines
22 KiB
JavaScript

import * as THREE from "three";
import { CONFIG, BGP_CONFIG } from "./constants.js";
import { COMPUTE_SITE_TYPES } from "./compute-site-types.js";
import { getEarthLocale, translateText } from "./i18n.js";
import { isSurfaceAnchorVisible } from "./surface-marker-occlusion.js";
import { createClusterTween } from "./cluster-motion.js";
import { markerPresentationId, markerStackGroups, markerStackLayout } from "./marker-stack.js";
const CLUSTER_RING_GAP_DEG = 4;
const CLUSTER_RING_DIVIDER_COLOR = "rgba(6, 13, 24, 0.92)";
export const CLUSTER_KIND_PRIORITY = Object.freeze({
supercomputer: 0,
gpu_cluster: 1,
data_center: 2,
cloud_center: 3,
edge_node: 4,
critical: 10,
high: 11,
medium: 12,
low: 13,
hot: 20,
idle: 24,
military: 30,
passenger: 31,
cargo: 32,
tanker: 33,
fishing: 34,
other: 35,
});
const BGP_SEVERITY_LABELS = Object.freeze({
critical: "严重事件",
high: "高危事件",
medium: "中危事件",
low: "低危事件",
});
const BGP_COLLECTOR_TIER_LABELS = Object.freeze({
hot: "高活跃观测站",
high: "高活跃观测站",
medium: "中活跃观测站",
low: "低活跃观测站",
idle: "静态观测站",
});
const VESSEL_KIND_LABELS = Object.freeze({
cargo: "货轮",
tanker: "油轮",
passenger: "客船",
fishing: "渔船",
military: "军舰",
other: "其他船只",
});
export function getClusterKindLabel(type, kind) {
if (kind && Object.hasOwn(COMPUTE_SITE_TYPES, kind)) {
return translateText(COMPUTE_SITE_TYPES[kind].label);
}
if (type === "bgp" && kind && Object.hasOwn(BGP_SEVERITY_LABELS, kind)) {
return translateText(BGP_SEVERITY_LABELS[kind]);
}
if (type === "bgp_collector" && kind && Object.hasOwn(BGP_COLLECTOR_TIER_LABELS, kind)) {
return translateText(BGP_COLLECTOR_TIER_LABELS[kind]);
}
if (type === "vessel" && kind && Object.hasOwn(VESSEL_KIND_LABELS, kind)) {
return translateText(VESSEL_KIND_LABELS[kind]);
}
return "";
}
function resolveKindPriority(type, kind) {
if (type === "bgp_collector" && kind === "high") return 21;
if (type === "bgp_collector" && kind === "medium") return 22;
if (type === "bgp_collector" && kind === "low") return 23;
if (kind && Object.hasOwn(CLUSTER_KIND_PRIORITY, kind)) {
return CLUSTER_KIND_PRIORITY[kind];
}
return 999;
}
export function summarizeClusterComposition(members, getOwner) {
const byTypeKind = new Map();
for (const marker of members) {
const type = String(marker?.userData?.type || "");
const kind = String(marker?.userData?.icon_kind || "");
const key = `${type}:${kind}`;
const existing = byTypeKind.get(key);
if (existing) {
existing.count += 1;
continue;
}
const owner = getOwner?.(marker);
const color = owner?.getMarkerColor?.(marker) || "#38bdf8";
byTypeKind.set(key, { key, type, kind, color, count: 1 });
}
const groups = [...byTypeKind.values()].sort((a, b) => (
b.count - a.count
|| resolveKindPriority(a.type, a.kind) - resolveKindPriority(b.type, b.kind)
|| a.key.localeCompare(b.key)
));
return {
groups,
total: members.length,
isMixed: groups.length > 1,
dominantColor: groups[0]?.color || "#38bdf8",
};
}
export function buildClusterRingGradient(groups, total) {
if (!Array.isArray(groups) || groups.length <= 1 || total <= 0) {
return "none";
}
const available = 360 - groups.length * CLUSTER_RING_GAP_DEG;
const minDeg = Math.min(20, available / (groups.length * 2));
const rawDegrees = groups.map((group) => (group.count / total) * available);
let deficit = 0;
let totalSurplus = 0;
for (const deg of rawDegrees) {
if (deg < minDeg) deficit += minDeg - deg;
else totalSurplus += deg - minDeg;
}
const degrees = rawDegrees.map((deg) => {
if (deg < minDeg) return minDeg;
if (deficit > 0 && totalSurplus > 0) {
return deg - deficit * ((deg - minDeg) / totalSurplus);
}
return deg;
});
const stops = [];
let cursor = 0;
groups.forEach((group, index) => {
const start = cursor;
const end = start + degrees[index];
const gapEnd = index === groups.length - 1 ? 360 : end + CLUSTER_RING_GAP_DEG;
stops.push(`${group.color} ${start.toFixed(1)}deg ${end.toFixed(1)}deg`);
stops.push(`${CLUSTER_RING_DIVIDER_COLOR} ${end.toFixed(1)}deg ${gapEnd.toFixed(1)}deg`);
cursor = gapEnd;
});
return `conic-gradient(from 0deg, ${stops.join(", ")})`;
}
export function formatClusterTitle(members, composition) {
const sampleNames = members
.slice(0, 3)
.map((marker) => marker.userData?.name || marker.userData?.collector || marker.userData?.title || marker.userData?.type)
.filter(Boolean)
.join(" / ");
if (composition.isMixed) {
const breakdown = composition.groups
.map((group) => {
const label = getClusterKindLabel(group.type, group.kind);
return label ? `${label} ${group.count}` : `${group.kind || group.type} ${group.count}`;
})
.join(" / ");
return `${members.length} · ${breakdown}${sampleNames ? ` · ${sampleNames}` : ""}`;
}
const sole = composition.groups[0];
const soleLabel = sole ? getClusterKindLabel(sole.type, sole.kind) : "";
if (soleLabel) {
return `${members.length} ${soleLabel}${sampleNames ? ` · ${sampleNames}` : ""}`;
}
return `${members.length} · ${sampleNames}`;
}
export function createClusterPresentation({ getOwner, onHiddenChange }) {
const entries = new Map();
let root = null, svg = null, expandedId = null, previousZoom = null;
const hidden = new Set(), point = new THREE.Vector3();
const interpolated = new THREE.Vector3(), visibilityPoint = new THREE.Vector3();
const parentViews = new WeakMap();
let projectionFrame = 0;
function parentView(parent, camera) {
let view = parentViews.get(parent);
if (!view) {
view = {frame: -1, cameraLocal: new THREE.Vector3(), world: new THREE.Matrix4(), inverse: new THREE.Matrix4()};
parentViews.set(parent, view);
}
if (view.frame !== projectionFrame) {
// Rotation is committed before presentation; all members of this parent
// use the same transform during this update, including spiderfy legs.
parent.updateWorldMatrix(true, false);
view.world.copy(parent.matrixWorld);
view.inverse.copy(view.world).invert();
view.cameraLocal.copy(camera.position).applyMatrix4(view.inverse);
view.frame = projectionFrame;
}
return view;
}
const idOf = markerPresentationId;
let stackMembers = [], geographicStacks = [];
const valid = marker => getOwner(marker)?.isMarkerVisible?.(marker);
const notifyHidden = next => {
const changed = new Set();
for (const marker of new Set([...hidden, ...next])) if (hidden.has(marker) !== next.has(marker)) {
marker.userData.icon_presentation_hidden = next.has(marker);
if (!next.has(marker)) marker.userData.icon_presentation_screen = null;
changed.add(getOwner(marker));
}
hidden.clear(); next.forEach(marker => hidden.add(marker));
changed.forEach(owner => onHiddenChange(owner));
};
function close() { expandedId = null; }
function ensureRoot() {
if (root) return;
root = document.createElement("div"); root.className = "map-clusters";
svg = document.createElementNS("http://www.w3.org/2000/svg", "svg"); svg.classList.add("map-clusters__legs"); root.append(svg);
document.getElementById("container").append(root);
root.addEventListener("pointerdown", event => event.stopPropagation());
root.addEventListener("pointermove", event => event.stopPropagation());
root.addEventListener("click", event => event.stopPropagation());
document.addEventListener("pointerdown", outside);
window.addEventListener("wheel", close, { passive: true });
window.addEventListener("resize", close);
}
const outside = event => { if (!root?.contains(event.target)) close(); };
function create(record, initial) {
const button = document.createElement("button"); button.type = "button";
button.className = "map-cluster-badge";
const pulse = document.createElement("span"); pulse.className = "map-cluster-bgp-pulse"; button.append(pulse);
button.style.setProperty("--bgp-pulse-duration", `${1 / BGP_CONFIG.ring.speed}ms`);
button.style.setProperty("--bgp-pulse-scale", BGP_CONFIG.ring.scaleA);
button.style.setProperty("--bgp-pulse-opacity", BGP_CONFIG.ring.opacity);
const count = document.createElement("span"); count.className = "map-cluster-badge__count"; button.append(count);
button.addEventListener("click", () => {
expandedId = expandedId === record.clusterId ? null : record.clusterId;
window.dispatchEvent(new CustomEvent("earth:cluster-open"));
});
root.append(button);
return { record, button, count, tween: createClusterTween(initial), children: new Map() };
}
function removeChild(child) {
child.button.remove(); child.line.remove(); child.hitLine.remove();
}
function remove(entry) {
entry.button.remove();
entry.children.forEach(removeChild);
}
function childFor(entry, marker) {
if (entry.children.has(marker)) return entry.children.get(marker);
const button = document.createElement("button"); button.type = "button"; button.className = "map-cluster-child";
const image = document.createElement("img"); image.alt = "";
if (marker.userData.type === "bgp") {
button.classList.add("has-bgp");
const pulse = document.createElement("span"); pulse.className = "map-cluster-bgp-pulse"; button.append(pulse);
button.style.setProperty("--bgp-pulse-duration", `${1 / BGP_CONFIG.ring.speed}ms`);
button.style.setProperty("--bgp-pulse-scale", BGP_CONFIG.ring.scaleA);
button.style.setProperty("--bgp-pulse-opacity", BGP_CONFIG.ring.opacity);
}
image.src = getOwner(marker).getMarkerImage(marker); button.append(image);
const label = marker.userData.name || marker.userData.collector || marker.userData.title || idOf(marker);
button.title = label; button.setAttribute("aria-label", label);
const line = document.createElementNS("http://www.w3.org/2000/svg", "line");
const hitLine = document.createElementNS("http://www.w3.org/2000/svg", "line");
hitLine.classList.add("map-cluster-leg-hit"); hitLine.setAttribute("aria-label", label);
svg.append(line); svg.append(hitLine);
const child = { button, line, hitLine, screen: null, highlighted:false,
ready: image.complete || typeof image.decode !== "function" };
if (!child.ready) image.decode().then(() => { child.ready = true; }, () => { child.ready = true; });
const activeSources = new Set();
const highlight = (source, active) => {
if (active) activeSources.add(source); else activeSources.delete(source);
child.highlighted = activeSources.size > 0;
button.classList.toggle("is-highlighted", child.highlighted);
line.classList.toggle("is-highlighted", child.highlighted);
};
for (const [node, source] of [[button,"point"],[hitLine,"leg"]]) {
node.addEventListener("pointerenter", () => highlight(source, true));
node.addEventListener("pointerleave", () => highlight(source, false));
node.addEventListener("click", () => window.dispatchEvent(new CustomEvent("earth:spiderfy-select", { detail: { marker, screen: child.screen } })));
}
button.addEventListener("focus", () => highlight("focus", true));
button.addEventListener("blur", () => highlight("focus", false));
const color = getOwner(marker).getMarkerColor(marker);
button.style.setProperty("--member-color", color); line.style.setProperty("--member-color", color);
root.append(button); entry.children.set(marker, child); return child;
}
function project(local, owner, camera, visibilityAnchor = local) {
const parent = owner?.group?.parent;
if (!parent) return null;
const view = parentView(parent, camera);
if (!isSurfaceAnchorVisible(visibilityAnchor, view.cameraLocal, CONFIG.earthRadius)) return null;
point.copy(local).applyMatrix4(view.world).project(camera);
if (point.z < -1 || point.z > 1 || Math.abs(point.x) > 1.1 || Math.abs(point.y) > 1.1) return null;
return { x: (point.x + 1) * innerWidth / 2, y: (1 - point.y) * innerHeight / 2 };
}
function update(records, camera, zoom, candidates = records.flatMap(record => record.markers), selectedMarker) {
projectionFrame += 1;
const selectedId = selectedMarker ? idOf(selectedMarker) : null;
const isSelected = marker => selectedMarker === undefined
? marker.userData.state === "locked" : idOf(marker) === selectedId;
if (candidates.length !== stackMembers.length || candidates.some((marker, index) => marker !== stackMembers[index])) {
stackMembers = [...candidates];
geographicStacks = markerStackGroups(stackMembers);
}
// Include otherwise independent members so cross-layer stacks share the
// same projection/picking owner instead of fighting GPU renderOrder.
const clustered = new Set(records.flatMap(record => record.markers));
const stackGroups = geographicStacks;
const standalone = [...new Set([
...stackGroups.flat(),
...candidates.filter(isSelected),
])].filter(marker => !clustered.has(marker) && valid(marker));
records = records.concat(standalone.map(marker => ({
clusterId: `stack:${idOf(marker)}`, markers: [marker], position: marker.position,
expanded: true, standalone: true,
})));
ensureRoot();
// Zoom-out reverses an active expansion from its current progress.
if (previousZoom !== null && zoom < previousZoom - 0.08) close();
previousZoom = zoom;
const active = new Set(records.map(record => record.clusterId));
for (const record of records) {
let entry = entries.get(record.clusterId);
if (!entry) { entry = create(record, record.standalone ? 1 : 0); entries.set(record.clusterId, entry); }
const currentMembers = new Set(record.markers);
for (const [marker, child] of entry.children) if (!currentMembers.has(marker)) {
removeChild(child); entry.children.delete(marker);
}
entry.record = record;
entry.expandRequested = expandedId === record.clusterId || record.expanded || record.markers.some(isSelected);
}
// Prepare textures/DOM before starting the clock. Otherwise the first
// visible frame can spend the entire tween budget encoding/decoding icons.
for (const [id, entry] of entries) if (active.has(id)) {
entry.prepared = true;
if (!entry.expandRequested || entry.tween.target() === 1) continue;
const centerVisible = project(entry.record.position, getOwner(entry.record.markers[0]), camera);
for (const marker of entry.record.markers.filter(valid)) {
if (!centerVisible && !project(marker.position, getOwner(marker), camera)) continue;
if (!childFor(entry, marker).ready) entry.prepared = false;
}
}
const now = performance.now();
for (const [id, entry] of entries) if (active.has(id)) {
entry.tween.set(entry.expandRequested && entry.prepared ? 1 : 0, now);
}
const expandedMarkers = new Set();
for (const [id, entry] of entries) if (active.has(id) && entry.tween.sample(now) > 0) {
entry.record.markers.filter(valid).forEach(marker => expandedMarkers.add(marker));
}
const stackOffsets = new Map();
for (const group of stackGroups) {
const members = group.filter(marker => expandedMarkers.has(marker));
if (members.length < 2) continue;
markerStackLayout(members.map(marker => ({ id: idOf(marker),
selected: isSelected(marker),
size: getOwner(marker).getMarkerSize?.(marker, camera) || 36,
}))).forEach((offset, id) => stackOffsets.set(id, offset));
}
const nextHidden = new Set(), renderedMarkers = new Set();
for (const [id, entry] of entries) {
const members = entry.record.markers.filter(valid);
if (members.length !== entry.record.markers.length) {
remove(entry); entries.delete(id); if(expandedId === id) close(); continue;
}
if (!active.has(id)) { remove(entry); entries.delete(id); continue; }
const progress = entry.tween.sample(now);
if (progress === 0 && !entry.expandRequested && entry.children.size) {
members.forEach(marker => { marker.userData.icon_presentation_screen = null; });
entry.children.forEach(removeChild);
entry.children.clear();
}
const owner = getOwner(members[0]);
const center = project(entry.record.position, owner, camera);
const composition = summarizeClusterComposition(members, getOwner);
const hasBgp = members.some(marker => ["bgp", "bgp_collector"].includes(marker.userData.type));
const visualKey = `${getEarthLocale()}|${composition.groups.map(group => `${group.key}:${group.count}:${group.color}`).join(",")}|${members.slice(0, 3).map(idOf).join(",")}|${hasBgp}`;
if (entry.visualKey !== visualKey) {
entry.visualKey = visualKey;
entry.button.style.setProperty("--cluster-color", composition.dominantColor);
entry.button.style.setProperty("--cluster-ring", buildClusterRingGradient(composition.groups, composition.total));
entry.button.classList.toggle("is-mixed", composition.isMixed);
entry.button.classList.toggle("has-bgp", hasBgp);
const countText = String(members.length);
if (entry.count.textContent !== countText) entry.count.textContent = countText;
const title = formatClusterTitle(members, composition);
if (entry.button.title !== title) {
entry.button.title = title;
entry.button.setAttribute("aria-label", title);
}
}
const ariaExpanded = String(progress > 0.5);
if (entry.ariaExpanded !== ariaExpanded) {
entry.ariaExpanded = ariaExpanded;
entry.button.setAttribute("aria-expanded", ariaExpanded);
}
// During the opening tween the aggregate badge remains visible, but it
// must not cover the focused member underneath it.
const hasSelectedMember = members.some(isSelected);
entry.button.style.zIndex = hasSelectedMember ? "90" : entry.expandRequested ? "20" : "1";
entry.button.hidden = entry.record.standalone || !center || progress > 0.95;
if (center) {
entry.button.style.left = `${center.x}px`; entry.button.style.top = `${center.y}px`;
entry.button.style.opacity = String(1 - progress);
entry.button.style.pointerEvents = progress > 0.4 ? "none" : "auto";
}
// Fully collapsed members have no visible child or leg. Their visibility
// bookkeeping still runs, but projecting two hidden endpoints cannot
// affect the badge, picking or the next expansion's tween.
if (progress < 0.01 && entry.children.size === 0) {
for (const marker of members) if (!renderedMarkers.has(marker)) {
renderedMarkers.add(marker); nextHidden.add(marker);
}
continue;
}
const projected = members.map(marker => {
// Interpolate in the same local coordinates used by the real marker.
// These exact children remain at the endpoint after the tween finishes.
const current = interpolated.copy(entry.record.position).lerp(marker.position, progress);
const visibilityAnchor = visibilityPoint.copy(current).normalize().multiplyScalar(
entry.record.position.length() + (marker.position.length() - entry.record.position.length()) * progress);
return { id:idOf(marker), marker,
screen:project(current, getOwner(marker), camera, visibilityAnchor),
anchor:project(marker.position, getOwner(marker), camera) };
});
const offsets = stackOffsets;
for (const item of projected) {
const { marker } = item;
if (progress < 0.01 && !entry.children.has(marker)) {
if (!renderedMarkers.has(marker)) { renderedMarkers.add(marker); nextHidden.add(marker); }
continue;
}
if (!item.screen && !entry.children.has(marker)) {
renderedMarkers.add(marker); nextHidden.add(marker);
marker.userData.icon_presentation_screen = null;
continue;
}
const child = childFor(entry, marker);
child.button.hidden = true; child.line.style.display = child.hitLine.style.display = "none";
marker.userData.icon_presentation_screen = null;
if (renderedMarkers.has(marker)) continue;
renderedMarkers.add(marker); nextHidden.add(marker);
if (!item.screen || !child.ready || progress < 0.01) continue;
const offset = offsets.get(item.id) || { x:0, y:0 };
const x = item.screen.x + offset.x * progress;
const y = item.screen.y + offset.y * progress;
child.screen = { x, y }; child.button.hidden = false;
marker.userData.icon_presentation_screen = child.screen;
const selected = isSelected(marker);
child.button.classList.toggle("is-selected", selected);
child.button.setAttribute("aria-pressed", String(selected));
child.button.style.zIndex = String(selected ? 1000 : offset.zIndex || 1);
const size = getOwner(marker).getMarkerSize?.(marker, camera) || 36;
child.button.style.width = `${size}px`; child.button.style.height = `${size}px`;
child.button.style.transform = `translate(${x}px,${y}px) translate(-50%,-50%) scale(${0.6 + progress * 0.4})`;
child.button.style.opacity = String(progress); child.button.style.pointerEvents = progress > 0.6 ? "auto" : "none";
child.line.style.display = child.hitLine.style.display = progress < 0.1 || !item.anchor || (!offset.x && !offset.y) ? "none" : "";
if (item.anchor) for (const [key,value] of Object.entries({x1:item.anchor.x,y1:item.anchor.y,x2:x,y2:y})) { child.line.setAttribute(key,value); child.hitLine.setAttribute(key,value); }
child.hitLine.style.pointerEvents = progress > 0.6 ? "stroke" : "none";
child.line.style.opacity = String(child.highlighted ? 1 : progress * 0.65);
}
}
notifyHidden(nextHidden);
}
function clear() {
entries.forEach(remove); entries.clear(); close(); notifyHidden(new Set());
stackMembers = []; geographicStacks = [];
}
return { update, close, clear,
destroy() { clear(); document.removeEventListener("pointerdown",outside); window.removeEventListener("wheel",close); window.removeEventListener("resize",close); root?.remove(); root = svg = null; },
};
}