Files
planet/frontend/public/earth/js/cluster-presentation.js
rayd1o 05377bf5c6
ci / backend (push) Has been cancelled
ci / frontend (push) Has been cancelled
ci / delivery (push) Has been cancelled
release / images (push) Has been cancelled
release: bump version to 0.76.0
2026-09-30 17:49:29 +08:00

300 lines
17 KiB
JavaScript

import * as THREE from "three";
import { CONFIG, BGP_CONFIG } from "./constants.js";
import { isSurfaceAnchorVisible } from "./surface-marker-occlusion.js";
import { createClusterTween } from "./cluster-motion.js";
import { markerPresentationId, markerStackGroups, markerStackLayout } from "./marker-stack.js";
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 types = new Set(members.map(marker => `${marker.userData.type}:${marker.userData.icon_kind}`));
const color = owner.getMarkerColor(members[0]);
entry.button.style.setProperty("--cluster-color", color);
entry.button.classList.toggle("is-mixed", types.size > 1);
entry.button.classList.toggle("has-bgp", members.some(marker => ["bgp","bgp_collector"].includes(marker.userData.type)));
const countText = String(members.length);
if (entry.count.textContent !== countText) entry.count.textContent = countText;
const title = `${members.length} · ${members.slice(0,3).map(marker => marker.userData.name || marker.userData.collector || marker.userData.type).join(" / ")}`;
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; },
};
}