438 lines
21 KiB
JavaScript
438 lines
21 KiB
JavaScript
import * as THREE from "three";
|
|
import { CalloutConnector } from "./callout-connector.js";
|
|
import { advanceCallouts } from "./callout-routing.js";
|
|
import {
|
|
getCalloutMotionMode,
|
|
canRelocateUserCard,
|
|
rememberCalloutLayout,
|
|
reviewTangledLayout,
|
|
READING_INTERVAL_MS,
|
|
MANUAL_READING_HOLD_MS,
|
|
isResponsiveCalloutMotion,
|
|
rotationNeedsReflow,
|
|
} from "./callout-stability.js";
|
|
import { CONFIG } from "./constants.js";
|
|
import { projectedSphereRadius, smoothHighlightAnchor } from "./highlight-anchor.js";
|
|
import { bindHUDDrag } from "./hud-drag.js";
|
|
import { CALLOUT_POSITION_VERSION, restoreCalloutPlacement } from "./callout-saved-placement.js";
|
|
|
|
import { advanceCalloutReveal } from "./callout-reveal.js";
|
|
import { createRegionConnectorPath } from "./callout-region-path.js";
|
|
import { scoreCalloutLayout, improvesCalloutLayout } from "./callout-proximity.js";
|
|
|
|
const EDGE = 12;
|
|
const RESPONSIVE_LAYOUT_INTERVAL_MS = 72;
|
|
const STORAGE_KEY = "planet.compute.card-positions.v1";
|
|
const clamp = (value, min, max) => Math.max(min, Math.min(Math.max(min, max), value));
|
|
|
|
export function renderSpatialCalloutConnector(state, { animate = false } = {}) {
|
|
const point = state?.sourcePoint || state?.point;
|
|
if (!point || !state.connector) return false;
|
|
if (state.connector.isAnimating?.()) return true;
|
|
const rearChanged = state.lastConnectorFront !== point.front;
|
|
const sameRect = state.lastConnectorRect && ["x", "y", "width", "height"].every(
|
|
key => Math.abs(state[key] - state.lastConnectorRect[key]) < 0.5,
|
|
);
|
|
const positionSettled = Math.hypot(state.x - state.targetX, state.y - state.targetY) < 0.5;
|
|
if (state.connector.isVisible?.() === true && state.lastConnector &&
|
|
!rearChanged && sameRect && !state.dragging && positionSettled &&
|
|
Math.hypot(point.x - state.lastConnector.x, point.y - state.lastConnector.y) < 1) {
|
|
return true;
|
|
}
|
|
|
|
const path = createRegionConnectorPath(point, {
|
|
x: state.x,
|
|
y: state.y,
|
|
width: state.width,
|
|
height: state.height,
|
|
});
|
|
const rendered = path ? state.connector.render(path, { animate }) : false;
|
|
if (!rendered) state.connector.hide();
|
|
|
|
const connectorElement = state.connector.connectorEl;
|
|
if (connectorElement) {
|
|
const rear = !point.front;
|
|
connectorElement.classList.toggle("is-rear", rear);
|
|
connectorElement.dataset.anchorDepth = rear ? "rear" : "front";
|
|
connectorElement.dataset.calloutKey = state.key;
|
|
}
|
|
state.lastConnector = { x: point.x, y: point.y };
|
|
state.lastConnectorFront = point.front;
|
|
state.lastConnectorRect = { x: state.x, y: state.y, width: state.width, height: state.height };
|
|
return rendered;
|
|
}
|
|
|
|
export function createCalloutController({
|
|
root,
|
|
getSpatialContext,
|
|
getAnchorCandidates,
|
|
project,
|
|
solve,
|
|
}) {
|
|
const cards = new Map();
|
|
let saved = {};
|
|
try { saved = JSON.parse(localStorage.getItem(STORAGE_KEY) || "{}"); } catch { /* Optional layout preference. */ }
|
|
if (!saved || typeof saved !== "object" || Array.isArray(saved)) saved = {};
|
|
let obstacles = [], layoutJob = null, revision = 0, lastLayoutAt = -Infinity;
|
|
let dirty = true, mobile = false, lastObstacleAt = -Infinity, lastViewport = "";
|
|
let previousMotionMode = null, currentGlobe = null;
|
|
let layoutReview = null, lastQualityAt = -Infinity, pendingGroupReflow = false;
|
|
const reflowGate = { lastAttemptAt: -Infinity };
|
|
const invalidate = () => {
|
|
dirty = true;
|
|
if (layoutReview) pendingGroupReflow = true;
|
|
layoutJob = null; layoutReview = null; revision++;
|
|
};
|
|
const requestResponsiveLayout = () => { dirty = true; };
|
|
const persist = () => {
|
|
try { localStorage.setItem(STORAGE_KEY, JSON.stringify(saved)); } catch { /* Storage may be unavailable. */ }
|
|
};
|
|
const resizeObserver = new ResizeObserver(entries => {
|
|
for (const entry of entries) {
|
|
const state = cards.get(entry.target.dataset.region);
|
|
if (!state) continue;
|
|
const width = entry.target.offsetWidth, height = entry.target.offsetHeight;
|
|
if (state.width === width && state.height === height) continue;
|
|
state.width = width; state.height = height;
|
|
if (state.userPlaced && !mobile) savePosition(state);
|
|
invalidate();
|
|
}
|
|
});
|
|
function savePosition(state) {
|
|
saved[state.key] = { x: state.x, y: state.y, viewportWidth: innerWidth, viewportHeight: innerHeight,
|
|
width: state.element.style.width, height: state.element.style.height,
|
|
positionVersion: CALLOUT_POSITION_VERSION };
|
|
persist();
|
|
}
|
|
function writePosition(state) {
|
|
const transform = `translate3d(${state.x.toFixed(1)}px, ${state.y.toFixed(1)}px, 0)`;
|
|
if (transform === state.lastTransform) return;
|
|
state.element.style.transform = transform;
|
|
state.lastTransform = transform;
|
|
}
|
|
function attach(item) {
|
|
const stored = saved?.[item.key];
|
|
if (stored?.width) item.element.style.width = stored.width;
|
|
if (stored?.height) item.element.style.height = stored.height;
|
|
const state = { ...item, x: NaN, y: NaN, targetX: NaN, targetY: NaN,
|
|
width: item.element.offsetWidth, height: item.element.offsetHeight,
|
|
lockedUntil: 0, userPlaced: false, revealPhase: "pending",
|
|
connector: new CalloutConnector({ container: root, className: "callout-connector compute-connector" }) };
|
|
const restored = restoreCalloutPlacement(stored, { width: innerWidth, height: innerHeight }, state);
|
|
if (restored.migrated) { saved[item.key] = restored.stored; persist(); }
|
|
if (restored.position) {
|
|
state.x = restored.position.x;
|
|
state.y = restored.position.y;
|
|
state.targetX = state.x; state.targetY = state.y; state.userPlaced = true;
|
|
item.element.dataset.dragged = "true";
|
|
} else {
|
|
delete item.element.dataset.dragged;
|
|
}
|
|
const hold = () => {
|
|
state.lockedUntil = Infinity;
|
|
if (Number.isFinite(state.x)) {
|
|
state.targetX = state.x; state.targetY = state.y; state.route = null;
|
|
}
|
|
};
|
|
const release = () => {
|
|
state.interacting = state.hovering || state.focused || state.dragging;
|
|
if (!state.interacting) state.lockedUntil = Math.max(performance.now() + 1800,
|
|
state.expandedHoldUntil || 0, state.userHoldUntil || 0);
|
|
};
|
|
const enter = () => { state.hovering = true; state.interacting = true; hold(); };
|
|
const leave = () => { state.hovering = false; release(); };
|
|
const focus = event => {
|
|
state.focused = Boolean(event.target.matches(":focus-visible, input, textarea, select, [contenteditable=true]"));
|
|
if (state.focused) { state.interacting = true; hold(); }
|
|
};
|
|
const blur = event => {
|
|
if (event.relatedTarget && item.element.contains(event.relatedTarget)) return;
|
|
state.focused = false;
|
|
release();
|
|
};
|
|
const listeners = [
|
|
["pointerenter", enter],
|
|
["pointerleave", leave],
|
|
["focusin", focus],
|
|
["focusout", blur],
|
|
];
|
|
listeners.forEach(([event, handler]) => item.element.addEventListener(event, handler));
|
|
const stopDrag = bindHUDDrag(item.element, {
|
|
enabled: () => !mobile && Number.isFinite(state.x),
|
|
readPosition: () => ({ left: state.x, top: state.y }),
|
|
onStart: () => {
|
|
state.dragging = true;
|
|
state.interacting = true;
|
|
state.lockedUntil = Infinity;
|
|
state.route = null;
|
|
},
|
|
onMove: ({ left, top }) => {
|
|
state.x = state.targetX = clamp(left, EDGE, innerWidth - state.width - EDGE);
|
|
state.y = state.targetY = clamp(top, EDGE, innerHeight - state.height - EDGE);
|
|
state.userPlaced = true; state.relocate = false;
|
|
item.element.dataset.dragged = "true";
|
|
writePosition(state);
|
|
},
|
|
onEnd: (moved) => {
|
|
state.dragging = false;
|
|
release();
|
|
if (moved) {
|
|
const now = performance.now();
|
|
state.userHoldUntil = now + MANUAL_READING_HOLD_MS;
|
|
state.manualReferencePoint = state.sourcePoint ? { ...state.sourcePoint } : null;
|
|
if (state.sourcePoint && currentGlobe) rememberCalloutLayout(state, state.sourcePoint, currentGlobe, now);
|
|
release();
|
|
savePosition(state); invalidate();
|
|
}
|
|
},
|
|
});
|
|
state.cleanup = () => {
|
|
stopDrag();
|
|
listeners.forEach(([event, handler]) => item.element.removeEventListener(event, handler));
|
|
};
|
|
return state;
|
|
}
|
|
function set(items) {
|
|
const keys = new Set(items.map(item => item.key));
|
|
for (const [key, state] of cards) if (!keys.has(key)) {
|
|
state.cleanup(); state.connector.hide(); state.connector.connectorEl?.remove();
|
|
resizeObserver.unobserve(state.element); cards.delete(key); invalidate();
|
|
}
|
|
for (const item of items) {
|
|
const existing = cards.get(item.key);
|
|
if (existing) {
|
|
existing.anchor = item.anchor;
|
|
existing.anchorCandidates = item.anchorCandidates;
|
|
const nextCodes = Array.isArray(item.anchorCodes) ? item.anchorCodes : [];
|
|
const nextCodeKey = nextCodes.join(",");
|
|
if (existing.anchorCodeKey !== nextCodeKey) {
|
|
existing.anchorCodes = nextCodes;
|
|
existing.anchorCodeKey = nextCodeKey;
|
|
existing.highlightAnchorState = {
|
|
...existing.highlightAnchorState,
|
|
candidateKey: null,
|
|
};
|
|
}
|
|
continue;
|
|
}
|
|
const state = attach(item);
|
|
state.anchorCodeKey = Array.isArray(state.anchorCodes) ? state.anchorCodes.join(",") : "";
|
|
cards.set(item.key, state); resizeObserver.observe(item.element);
|
|
item.element.style.visibility = "hidden";
|
|
item.element.dataset.calloutPhase = "pending"; invalidate();
|
|
}
|
|
}
|
|
function measureObstacles(now) {
|
|
if (now - lastObstacleAt < 500) return;
|
|
lastObstacleAt = now;
|
|
const selector = ".hud-panel, #desktop-news-ticker, #info-panel, #legend, #toolbar-hub, .earth-toolbar-cluster.is-expanded .earth-toolbar-orb, .earth-stack-toolbar, .hud-panel-brand";
|
|
const next = [...document.querySelectorAll(selector)].filter(el => !el.matches(".compute-card") &&
|
|
(!root.contains(el) || el.matches(".compute-picker, .compute-evidence"))).filter(el => {
|
|
const style = getComputedStyle(el);
|
|
return !el.hidden && !el.classList.contains("hud-panel-hidden") && style.display !== "none" &&
|
|
style.visibility !== "hidden" && style.opacity !== "0" && el.getClientRects().length;
|
|
}).map(el => {
|
|
const { x, y, width, height } = el.getBoundingClientRect();
|
|
return { x, y, width, height, transient: el.matches(".compute-picker, .compute-evidence") };
|
|
});
|
|
if (JSON.stringify(next) !== JSON.stringify(obstacles)) { obstacles = next; invalidate(); }
|
|
}
|
|
function update(deltaMs, now) {
|
|
if (!cards.size || root.hidden) return;
|
|
mobile = document.documentElement.classList.contains("layout-mode-mobile");
|
|
const viewportKey = `${innerWidth}:${innerHeight}:${mobile}`;
|
|
if (viewportKey !== lastViewport) { lastViewport = viewportKey; invalidate(); }
|
|
if (mobile) {
|
|
for (const state of cards.values()) { state.connector.hide(); state.element.style.visibility = ""; }
|
|
return;
|
|
}
|
|
const context = getSpatialContext?.();
|
|
if (!context?.earth || !context?.camera) return;
|
|
const motionMode = getCalloutMotionMode(context);
|
|
const responsiveMotion = isResponsiveCalloutMotion(motionMode);
|
|
const settlingMotion = previousMotionMode !== null &&
|
|
isResponsiveCalloutMotion(previousMotionMode) && !responsiveMotion;
|
|
previousMotionMode = motionMode;
|
|
context.camera.updateMatrixWorld();
|
|
const center = new THREE.Vector3().setFromMatrixPosition(context.earth.matrixWorld);
|
|
const cameraPosition = new THREE.Vector3().setFromMatrixPosition(context.camera.matrixWorld);
|
|
const cameraDistance = cameraPosition.distanceTo(center);
|
|
const rim = center.clone().add(new THREE.Vector3().setFromMatrixColumn(context.camera.matrixWorld, 0).multiplyScalar(CONFIG.earthRadius)).project(context.camera);
|
|
center.project(context.camera);
|
|
const globe = { x: (center.x + 1) * innerWidth / 2, y: (1 - center.y) * innerHeight / 2,
|
|
radius: Math.abs(rim.x - center.x) * innerWidth / 2 };
|
|
const sourceGlobe = {
|
|
...globe,
|
|
radius: projectedSphereRadius(globe.radius, cameraDistance, CONFIG.earthRadius),
|
|
};
|
|
currentGlobe = sourceGlobe;
|
|
const items = [];
|
|
const sourceObstacles = [
|
|
...obstacles,
|
|
...[...cards.values()].filter(card => Number.isFinite(card.x) &&
|
|
Number.isFinite(card.y) && card.width > 0 && card.height > 0).map(card => ({
|
|
x: card.x,
|
|
y: card.y,
|
|
width: card.width,
|
|
height: card.height,
|
|
})),
|
|
];
|
|
let motionLayoutRequested = false;
|
|
for (const state of cards.values()) {
|
|
const point = project(state.anchor, context.earth, context.camera, innerWidth, innerHeight);
|
|
if (!point) { state.connector.hide(); continue; }
|
|
state.point = point;
|
|
const needsAlternateSource = state.highlightAnchorState?.candidateKey != null ||
|
|
!point.front || !Number.isFinite(point.visibility) || point.visibility < 0.34;
|
|
const candidateAnchors = needsAlternateSource
|
|
? state.anchorCandidates || getAnchorCandidates?.(state.anchorCodes) || []
|
|
: [];
|
|
const candidatePoints = candidateAnchors.map(anchor =>
|
|
project(anchor, context.earth, context.camera, innerWidth, innerHeight)).filter(Boolean);
|
|
const anchorResult = smoothHighlightAnchor({
|
|
...state.highlightAnchorState,
|
|
cardPoint: Number.isFinite(state.x) ? {
|
|
x: state.x + state.width / 2,
|
|
y: state.y + state.height / 2,
|
|
} : null,
|
|
}, {
|
|
preferred: point,
|
|
candidates: candidatePoints,
|
|
globe: sourceGlobe,
|
|
obstacles: sourceObstacles,
|
|
viewport: { width: innerWidth, height: innerHeight },
|
|
deltaMs,
|
|
});
|
|
state.highlightAnchorState = anchorResult.state;
|
|
state.sourcePoint = anchorResult.source || point;
|
|
const expanded = state.element.classList.contains("is-expanded");
|
|
if (expanded && !state.readingExpanded && Number.isFinite(state.x)) {
|
|
state.expandedHoldUntil = now + MANUAL_READING_HOLD_MS;
|
|
state.lockedUntil = Math.max(state.lockedUntil, state.expandedHoldUntil);
|
|
}
|
|
state.readingExpanded = expanded;
|
|
state.interacting = state.hovering || state.focused || state.dragging;
|
|
// A completed card interaction must not keep the layout frozen while the
|
|
// user deliberately turns the globe.
|
|
if (responsiveMotion && !state.interacting && Number.isFinite(state.lockedUntil)) {
|
|
state.lockedUntil = 0;
|
|
}
|
|
const reading = state.revealPhase === "drawing" || (responsiveMotion ? state.interacting :
|
|
state.lockedUntil > now || state.dragging);
|
|
if (reading) state.route = null;
|
|
if (state.wasReading && !reading) invalidate();
|
|
state.wasReading = reading;
|
|
state.element.classList.toggle("is-rear", !state.sourcePoint.front);
|
|
// Sizes are cached by ResizeObserver, not remeasured in the render loop.
|
|
if (!state.width || !state.height) continue;
|
|
if (rotationNeedsReflow(state, state.sourcePoint, sourceGlobe, now, motionMode)) {
|
|
motionLayoutRequested = true;
|
|
}
|
|
const layoutPoint = state.layoutReferencePoint || state.sourcePoint;
|
|
items.push({ key: state.key, point: layoutPoint, front: layoutPoint.front, size: { width: state.width, height: state.height },
|
|
previousPosition: Number.isFinite(state.x) ? { x: state.targetX, y: state.targetY } : null,
|
|
previousSide: state.side, previousAngle: state.angle, userPlaced: state.userPlaced,
|
|
locked: reading, relocate: state.relocate });
|
|
}
|
|
measureObstacles(now);
|
|
const viewport = { width: innerWidth, height: innerHeight, globe };
|
|
const freshItems = items.map(item => ({ ...item, point: cards.get(item.key).sourcePoint }));
|
|
const previous = new Map(items.filter(item => item.previousPosition).map(item =>
|
|
[item.key, { ...item.previousPosition, ...item.size }]));
|
|
let qualityRequested = false;
|
|
if (!responsiveMotion && previous.size === items.length && now - lastQualityAt > 250) {
|
|
lastQualityAt = now;
|
|
qualityRequested = reviewTangledLayout(reflowGate, scoreCalloutLayout(freshItems, previous, viewport), now);
|
|
}
|
|
pendingGroupReflow ||= qualityRequested || (motionLayoutRequested && (responsiveMotion ||
|
|
now - reflowGate.lastAttemptAt >= READING_INTERVAL_MS));
|
|
const groupReflow = pendingGroupReflow;
|
|
if (groupReflow) {
|
|
for (const item of items) {
|
|
const state = cards.get(item.key);
|
|
if (item.locked || !canRelocateUserCard(state, state.sourcePoint, sourceGlobe, now)) continue;
|
|
item.point = state.sourcePoint;
|
|
item.relocate = true;
|
|
item.userPlaced = false;
|
|
}
|
|
requestResponsiveLayout();
|
|
}
|
|
const eagerLayout = responsiveMotion || settlingMotion;
|
|
const layoutInterval = settlingMotion ? 0 : eagerLayout ? RESPONSIVE_LAYOUT_INTERVAL_MS : 400;
|
|
if (!layoutJob && dirty && now - lastLayoutAt >= layoutInterval) {
|
|
layoutReview = groupReflow && !responsiveMotion && previous.size === items.length
|
|
? { items: freshItems, before: scoreCalloutLayout(freshItems, previous, viewport) } : null;
|
|
if (groupReflow && !responsiveMotion) reflowGate.lastAttemptAt = now;
|
|
pendingGroupReflow = false;
|
|
layoutJob = solve(items, obstacles, viewport);
|
|
dirty = false; lastLayoutAt = now;
|
|
}
|
|
let result = layoutJob?.next();
|
|
// A yielded job can otherwise be invalidated by the next fast-motion
|
|
// sample forever. The bounded card set is cheap enough to finish here.
|
|
if (eagerLayout) while (result && !result.done) result = layoutJob.next();
|
|
if (result?.done) {
|
|
layoutJob = null;
|
|
const next = new Map([...result.value].map(([key, target]) =>
|
|
[key, { ...target, width: cards.get(key)?.width, height: cards.get(key)?.height }]));
|
|
const accept = !layoutReview || improvesCalloutLayout(layoutReview.before,
|
|
scoreCalloutLayout(layoutReview.items, next, viewport));
|
|
if (accept) for (const [key, target] of result.value) {
|
|
const state = cards.get(key);
|
|
const activelyReading = state?.revealPhase === "drawing" || state?.hovering || state?.focused || state?.dragging;
|
|
if (!state || (Number.isFinite(state.x) && (activelyReading || (!responsiveMotion && state.lockedUntil > now)))) continue;
|
|
const moved = Number.isFinite(state.targetX) && Math.hypot(target.x - state.targetX, target.y - state.targetY) > 2;
|
|
if (moved && state.userPlaced && canRelocateUserCard(state, state.sourcePoint, sourceGlobe, now)) {
|
|
state.userPlaced = false;
|
|
delete state.element.dataset.dragged;
|
|
saved[key] = { width: state.element.style.width, height: state.element.style.height,
|
|
positionVersion: CALLOUT_POSITION_VERSION };
|
|
persist();
|
|
}
|
|
state.targetX = target.x; state.targetY = target.y; state.side = target.side; state.angle = target.angle;
|
|
state.relocate = false;
|
|
if (layoutReview || responsiveMotion) rememberCalloutLayout(state, state.sourcePoint, sourceGlobe, now);
|
|
}
|
|
layoutReview = null;
|
|
}
|
|
const reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
|
|
const placed = [...cards.values()].filter(state => state.point && Number.isFinite(state.targetX));
|
|
for (const state of placed) {
|
|
if (!Number.isFinite(state.x)) { state.x = state.targetX; state.y = state.targetY; }
|
|
if (!state.dragging) {
|
|
state.x = clamp(state.x, EDGE, innerWidth - state.width - EDGE);
|
|
state.y = clamp(state.y, EDGE, innerHeight - state.height - EDGE);
|
|
}
|
|
}
|
|
advanceCallouts(placed, obstacles, { width: innerWidth, height: innerHeight, globe, revision }, now, deltaMs);
|
|
for (const state of placed) {
|
|
writePosition(state);
|
|
const rendered = renderSpatialCalloutConnector(state, {
|
|
animate: state.revealPhase === "pending" && !reducedMotion,
|
|
});
|
|
const wasVisible = state.revealPhase === "visible";
|
|
const phase = advanceCalloutReveal(state, {
|
|
now, rendered, animating: state.connector.isAnimating(), reducedMotion,
|
|
});
|
|
state.element.dataset.calloutPhase = phase;
|
|
if (phase === "visible" && !wasVisible) {
|
|
state.element.style.visibility = "";
|
|
if (!reducedMotion) state.element.animate([{ opacity: 0 }, { opacity: 1 }], {
|
|
duration: 180, easing: "ease",
|
|
});
|
|
}
|
|
}
|
|
}
|
|
const reset = event => {
|
|
const button = event.target.closest('[data-action="card-auto"]');
|
|
if (!button) return;
|
|
const state = cards.get(button.dataset.card);
|
|
if (!state) return;
|
|
delete saved[state.key]; persist(); state.userPlaced = false; state.relocate = true;
|
|
delete state.element.dataset.dragged;
|
|
state.lockedUntil = 0; state.element.style.width = ""; state.element.style.height = ""; invalidate();
|
|
};
|
|
root.addEventListener("click", reset);
|
|
return { set, update, invalidate, destroy() { set([]); resizeObserver.disconnect(); root.removeEventListener("click", reset); } };
|
|
}
|