import { createConnectorPath } from "./callout-connector.js"; import { placeObjectCallout } from "./object-callout-layout.js"; import { sharedCalloutStageArbitrator } from "./callout-stage-arbitrator.js"; const DEFAULT_CONNECTOR_READY_TIMEOUT_MS = 1200; import { CALLOUT_DRAW_MS } from "./callout-reveal.js"; function nextAnimationFrame() { return new Promise((resolve) => { window.requestAnimationFrame(() => resolve()); }); } function isCurrentContext(context) { return !context || typeof context.isCurrent !== "function" || context.isCurrent(); } function waitForContext(context, durationMs) { if (context && typeof context.wait === "function") { return context.wait(durationMs); } return new Promise((resolve) => { window.setTimeout(() => resolve(isCurrentContext(context)), durationMs); }); } export function isTargetElementVisible(el) { if (!el) return false; if (!(el instanceof HTMLElement)) { return (Number.isFinite(el.width) && el.width > 0 && Number.isFinite(el.height) && el.height > 0) || (Number.isFinite(el.x) && Number.isFinite(el.y)); } if (el.hasAttribute("hidden")) return false; const style = window.getComputedStyle ? window.getComputedStyle(el) : el.style; if (style && style.display === "none") return false; const rect = el.getBoundingClientRect ? el.getBoundingClientRect() : el; return rect.width > 0 && rect.height > 0; } function getDefaultCardTarget() { const isMobile = document.body.classList.contains("layout-mode-mobile"); if (isMobile) { const mobilePopup = document.getElementById("earth-mobile-popup"); if (isTargetElementVisible(mobilePopup)) { return mobilePopup; } } else { const infoPanel = document.getElementById("info-panel"); if (isTargetElementVisible(infoPanel)) { return infoPanel; } } const mobilePopup = document.getElementById("earth-mobile-popup"); if (isTargetElementVisible(mobilePopup)) return mobilePopup; const infoPanel = document.getElementById("info-panel"); if (isTargetElementVisible(infoPanel)) return infoPanel; return null; } export class PresentationController { constructor({ connector, pathFactory = createConnectorPath, requestAnimationFrame = nextAnimationFrame, stageArbitrator = sharedCalloutStageArbitrator, } = {}) { this.connector = connector; this.pathFactory = pathFactory; this.requestAnimationFrame = requestAnimationFrame; this.stageArbitrator = stageArbitrator; this.stageArbitrator?.clearByOwner?.("presentation"); this.active = null; this.timeoutId = null; } isActive(owner = null) { if (!this.active) return false; return owner ? this.active.request.owner === owner : true; } clearTimeout() { if (!this.timeoutId) return; window.clearTimeout(this.timeoutId); this.timeoutId = null; } dismiss(reason = "dismiss") { if (!this.active) return false; const active = this.active; this.active = null; this.stageArbitrator?.clearByOwner?.("presentation"); this.clearTimeout(); active.request.connector?.instance?.hide?.(); this.connector?.hide?.(); active.request.card?.hide?.(); active.request.onDismiss?.(reason); return true; } scheduleLifetime(request) { this.clearTimeout(); if (request.lifetime?.mode !== "timeout") return; const timeoutMs = Number(request.lifetime.timeoutMs); if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) return; this.timeoutId = window.setTimeout(() => { this.dismiss("timeout"); }, timeoutMs); } getConnectorInstance(request) { return request.connector?.instance || this.connector || null; } getConnectorPath(request) { const connectorRequest = request.connector; if (!connectorRequest?.enabled) return null; const source = connectorRequest.sourceProvider?.(); if (!source) return null; const target = connectorRequest.targetProvider?.() || getDefaultCardTarget(); if (!target) return null; // If source is on backside, project it to the limb silhouette of the globe let effectiveSource = source; const globe = source.globe; if (source.front === false && globe && Number.isFinite(globe.radius)) { const dx = source.x - globe.x; const dy = source.y - globe.y; const dist = Math.hypot(dx, dy) || 1; effectiveSource = { ...source, x: globe.x + (dx / dist) * globe.radius, y: globe.y + (dy / dist) * globe.radius, }; } const sourceIsRect = Number.isFinite(effectiveSource.x) && Number.isFinite(effectiveSource.y) && Number.isFinite(effectiveSource.width) && Number.isFinite(effectiveSource.height); const sourceAnchor = sourceIsRect ? { x: effectiveSource.x + effectiveSource.width * 0.5, y: effectiveSource.y + effectiveSource.height * 0.5 } : effectiveSource; const options = { ...(connectorRequest.options || {}), ...(sourceIsRect && !connectorRequest.options?.sourceRect ? { sourceRect: effectiveSource } : {}), globe: globe || effectiveSource.globe, }; return this.pathFactory(sourceAnchor, target, options); } computeIdealBalloonPosition(anchor, size, viewport, obstacles = []) { const width = size.width || 340; const height = size.height || 380; const globe = anchor.globe || viewport.globe || { x: viewport.width / 2, y: viewport.height / 2, radius: 360 }; const previousPosition = this._lastIdeal || (Number.isFinite(size.x) && Number.isFinite(size.y) ? { x: size.x, y: size.y } : null); return placeObjectCallout(anchor, { width, height }, { ...viewport, globe, previousPosition }, obstacles); } update({ animate = false } = {}) { if (!this.active) return false; if (!animate && this.active.phase === "preparing") return false; const { request } = this.active; const connector = this.getConnectorInstance(request); if (!connector || request.connector?.enabled !== true) return false; if (!animate && connector.isAnimating?.()) return true; // Balloon Leash & Inertia Dynamics (气球惯性动力学): const source = request.connector?.sourceProvider?.(); const target = request.connector?.targetProvider?.() || getDefaultCardTarget(); if (!target || !isTargetElementVisible(target)) { connector.hide?.(); return false; } const isTargetDragging = Boolean( target?.dataset?.dragged === "true" || target?.classList?.contains("is-dragging") ); const isTargetUserPlaced = Boolean( target?.dataset?.userPlaced === "true" ); if (target instanceof HTMLElement && isTargetDragging) { delete target.dataset.dragSyncedHemisphere; } if (source && target instanceof HTMLElement && !isTargetDragging) { const globe = source.globe; const rawPt = source.rawPoint || source; let effectiveAnchor = { x: rawPt.x, y: rawPt.y, globe }; if (rawPt.front === false && globe && Number.isFinite(globe.radius)) { const dx = rawPt.x - globe.x; const dy = rawPt.y - globe.y; const dist = Math.hypot(dx, dy) || 1; effectiveAnchor = { x: globe.x + (dx / dist) * globe.radius, y: globe.y + (dy / dist) * globe.radius, globe, }; } const rect = target.getBoundingClientRect(); const curLeft = parseFloat(target.style.left) || rect.x; const curTop = parseFloat(target.style.top) || rect.y; const cardW = rect.width || 340; const cardH = rect.height || 380; let shouldStayPinned = isTargetUserPlaced; if (isTargetUserPlaced) { // User explicitly placed this card: respect user intent permanently! // Only release user pin if anchor rotates into deep backside occlusion where real depth < -0.65 (>130 deg) const rawVis = Number.isFinite(source.rawVisibility) ? source.rawVisibility : (Number.isFinite(source.visibility) ? source.visibility : null); const isDeepRear = source.front === false && rawVis !== null && rawVis < -0.65; if (isDeepRear) { target.dataset.userPlaced = "false"; delete target.dataset.dragSyncedHemisphere; shouldStayPinned = false; this._balloonVx = 0; this._balloonVy = 0; } } const vpWidth = (typeof window !== "undefined" && Number.isFinite(window.innerWidth)) ? window.innerWidth : 1920; const vpHeight = (typeof window !== "undefined" && Number.isFinite(window.innerHeight)) ? window.innerHeight : 1080; // Read ONLY static HUD chrome obstacles; NEVER read live animated DOM rects of sibling callout cards: const obstacles = (typeof document !== "undefined" && typeof document.querySelectorAll === "function") ? [...document.querySelectorAll(".hud-panel:not(#info-panel):not(.compute-card):not(.news-region-card)")] .filter(element => !element.hidden && (typeof getComputedStyle !== "function" || getComputedStyle(element).visibility !== "hidden")) .map(element => { const r = element.getBoundingClientRect(); return { x: r.x, y: r.y, width: r.width, height: r.height }; }) .filter(r => r.width > 0 && r.height > 0) : []; const topToastEdge = obstacles.filter(o => o.y < 80 && o.height <= 80).reduce((max, o) => Math.max(max, o.y + o.height), 0); const safeMinY = topToastEdge > 0 ? (topToastEdge + 12) : 64; const bottomObs = obstacles.filter(o => o.y > vpHeight - 110); const safeMaxY = bottomObs.length > 0 ? bottomObs.reduce((min, o) => Math.min(min, o.y - 12), vpHeight - 14) : (vpHeight - 110); const leftHudEdge = obstacles.filter(o => o.x < 140 && o.y > 60 && o.height > 100).reduce((max, o) => Math.max(max, o.x + o.width), 0); const safeMinX = Math.max(14, leftHudEdge > 0 ? (leftHudEdge + 12) : 14); const safeBounds = { minX: safeMinX, maxX: vpWidth - 14, minY: safeMinY, maxY: safeMaxY }; if (shouldStayPinned) { this.stageArbitrator?.setCard?.("selection:detail", { owner: "presentation", kind: "selection", anchor: effectiveAnchor, size: { width: cardW, height: cardH }, isPrimary: true, userPinned: true, pinnedRect: { x: curLeft, y: curTop, width: cardW, height: cardH }, overlapDepth: 30, }); this.stageArbitrator?.arbitrate?.({ viewport: { width: vpWidth, height: vpHeight }, globe, safeBounds, }); } else { const isInteracting = (typeof document !== "undefined" && ( document.body?.classList?.contains("is-globe-dragging") || document.documentElement?.classList?.contains("is-globe-dragging") )) || Boolean(request?.context?.isDragging); this.stageArbitrator?.setCard?.("selection:detail", { owner: "presentation", kind: "selection", anchor: effectiveAnchor, size: { width: cardW, height: cardH }, isPrimary: true, userPinned: false, pinnedRect: null, overlapDepth: 30, }); const arbitration = this.stageArbitrator?.arbitrate?.({ viewport: { width: vpWidth, height: vpHeight }, globe, safeBounds, }); const arbitratedSlot = arbitration?.slots?.get("selection:detail") || null; const viewport = { width: vpWidth, height: vpHeight, globe, arbitratedSlot }; const ideal = this.computeIdealBalloonPosition(effectiveAnchor, rect, viewport, obstacles); this._lastIdeal = ideal; // When first appearing, snap immediately to ideal target: const now = (typeof performance !== "undefined" && performance.now) ? performance.now() : Date.now(); if (animate || this.active?.phase !== "visible") { target.style.left = `${ideal.x}px`; target.style.top = `${ideal.y}px`; target.style.right = "auto"; target.style.bottom = "auto"; this._balloonVx = 0; this._balloonVy = 0; this._lastBalloonTime = now; if (this.active) { this.active.settledSlot = { x: ideal.x, y: ideal.y }; this.active.lastSettledAnchor = { x: effectiveAnchor.x, y: effectiveAnchor.y }; this.active.state = "settled"; } } else { // Second-Order Direction-Heterogeneous Fluid Balloon Dynamics (符合物理规律的真惯性气球动力学,左右灵敏,上下沉稳): const dtSeconds = Math.max(0.005, Math.min(0.045, (now - (this._lastBalloonTime || now)) / 1000)); this._lastBalloonTime = now; const dx = ideal.x - curLeft; const dy = ideal.y - curTop; let vx = this._balloonVx || 0; let vy = this._balloonVy || 0; // True convergence threshold (1px position, 2px/s velocity): const xSettled = Math.abs(dx) <= 1.0 && Math.abs(vx) <= 2.0; const ySettled = Math.abs(dy) <= 1.0 && Math.abs(vy) <= 2.0; if (xSettled && ySettled) { target.style.left = `${ideal.x}px`; target.style.top = `${ideal.y}px`; this._balloonVx = 0; this._balloonVy = 0; if (this.active) { this.active.settledSlot = { x: ideal.x, y: ideal.y }; this.active.lastSettledAnchor = { x: effectiveAnchor.x, y: effectiveAnchor.y }; this.active.state = "settled"; } } else { // Direction-heterogeneous natural frequencies (左右灵敏,上下沉稳): const omega0x = isInteracting ? 11.5 : 9.5; const zetax = 0.85; const kOverMx = omega0x * omega0x; const cOverMx = 2 * zetax * omega0x; const ax = kOverMx * dx - cOverMx * vx; const omega0y = isInteracting ? 5.5 : 4.2; const zetay = 0.95; const kOverMy = omega0y * omega0y; const cOverMy = 2 * zetay * omega0y; const ay = kOverMy * dy - cOverMy * vy; vx += ax * dtSeconds; vy += ay * dtSeconds; const speedX = Math.abs(vx); const maxX = isInteracting ? 2200 : 1200; if (speedX > maxX) vx = (vx / speedX) * maxX; const speedY = Math.abs(vy); const maxY = isInteracting ? 900 : 500; if (speedY > maxY) vy = (vy / speedY) * maxY; this._balloonVx = vx; this._balloonVy = vy; const nextLeft = Math.round((curLeft + vx * dtSeconds) * 10) / 10; const nextTop = Math.round((curTop + vy * dtSeconds) * 10) / 10; target.style.left = `${nextLeft}px`; target.style.top = `${nextTop}px`; if (this.active) { this.active.settledSlot = { x: ideal.x, y: ideal.y }; this.active.lastSettledAnchor = { x: effectiveAnchor.x, y: effectiveAnchor.y }; this.active.state = "seeking"; } } } } } const path = this.getConnectorPath(request); if (!path) { connector.hide?.(); return false; } const rendered = connector.render(path, { animate }) === true; if (rendered && animate) this.active.phase = "drawing"; return rendered; } async waitForConnector(request, context) { const timeoutMs = Number(request.connector?.readyTimeoutMs) || DEFAULT_CONNECTOR_READY_TIMEOUT_MS; const startedAt = performance.now(); let ready = false; while (isCurrentContext(context) && this.active?.request === request) { ready = this.update({ animate: !ready }); if (ready) break; if (performance.now() - startedAt >= timeoutMs) break; await this.requestAnimationFrame(); } return ready; } async present(request, { context } = {}) { if (!request?.id || !request.card || !isCurrentContext(context)) return false; this.dismiss("replace"); this.active = { id: request.id, request, phase: "preparing" }; request.card.render?.({ reveal: false }); await this.requestAnimationFrame(); if (!isCurrentContext(context) || this.active?.request !== request) { if (this.active?.request === request) this.dismiss("interrupted"); return false; } const connectorReady = request.connector?.enabled === true ? await this.waitForConnector(request, context) : false; if (!isCurrentContext(context) || this.active?.request !== request) { if (this.active?.request === request) this.dismiss("interrupted"); return false; } if (request.connector?.enabled && !connectorReady) { this.dismiss("connector_unavailable"); return false; } if (connectorReady) { const drawMs = Number(request.connector?.drawMs) || CALLOUT_DRAW_MS; const connector = this.getConnectorInstance(request); const drawCompleted = connector?.waitForDraw ? await connector.waitForDraw() : await waitForContext(context, drawMs); if (!drawCompleted || this.active?.request !== request) { if (this.active?.request === request) this.dismiss("interrupted"); return false; } } this.active.phase = "visible"; request.card.render?.({ reveal: true }); await this.requestAnimationFrame(); if (!isCurrentContext(context) || this.active?.request !== request) { if (this.active?.request === request) this.dismiss("interrupted"); return false; } this.update(); this.scheduleLifetime(request); return true; } }