import { axialToPixel } from "./hex.ts"; import { fitWorldCameraToEntities } from "./worldModel.ts"; import type { RelationshipContext } from "./relationshipContext.ts"; import { cameraPixelToAxial, cameraToViewBox as getCameraViewBox, clampCameraToWorld, ensureCameraTargetVisible, type CameraViewportInsets, } from "./cameraMath.ts"; export interface TopologyCameraState { center: { q: number; r: number }; zoom: number; viewportWidth: number; viewportHeight: number; } export interface TopologyWorldBounds { minX: number; maxX: number; minY: number; maxY: number; width: number; height: number; } export interface TopologyMiniMapNode { id: string; } export interface TopologyViewportControllerOptions { root: HTMLElement; sceneGrid: SVGSVGElement | null; miniFrame: SVGRectElement | null; miniReadout: HTMLElement | null; miniNodes: SVGElement[]; worldRadius: number; worldBounds: TopologyWorldBounds; topologyNodes: Array<{ id: string; q: number; r: number }>; cameraTransitionDuration: number; safeAreaRatio?: number; getViewportInsets?: () => CameraViewportInsets; initialCamera: TopologyCameraState; onCameraChange?: (camera: TopologyCameraState) => void; } export interface TopologyViewportController { getCamera(): TopologyCameraState; applyCamera(camera: TopologyCameraState): void; animateCameraTo(targetCamera: TopologyCameraState, duration?: number): void; fit(animated?: boolean): void; updateViewport(): void; centerOnPoint(point: { x: number; y: number }, animated?: boolean): void; centerOnNode(node: { q: number; r: number }, animated?: boolean): void; ensureVisible(entityId: string, animated?: boolean): boolean; panByScreen(dx: number, dy: number, animated?: boolean): void; zoomBy(delta: number): void; syncSelection(entityId: string): void; setTopology(nodes: Array<{ id: string; q: number; r: number }>, bounds?: TopologyWorldBounds): void; syncRelationshipContext(context: RelationshipContext): void; destroy(): void; } export function createTopologyViewportController( options: TopologyViewportControllerOptions, ): TopologyViewportController { const { root, sceneGrid, miniFrame, miniReadout, miniNodes: initialMiniNodes, worldRadius, worldBounds: initialWorldBounds, topologyNodes: initialTopologyNodes, cameraTransitionDuration, safeAreaRatio = 0.16, getViewportInsets = () => ({}), initialCamera, onCameraChange, } = options; const miniMap = root.querySelector("[data-topology-mini-map]"); let activeSelectionId = ""; let activeWorldBounds = initialWorldBounds; let activeTopologyNodes = [...initialTopologyNodes]; let miniNodes = [...initialMiniNodes]; let topologyNodeMap = new Map(activeTopologyNodes.map((node) => [node.id, node])); let currentCamera: TopologyCameraState = clampCamera(initialCamera); let preferredCamera: TopologyCameraState = { ...currentCamera, center: { ...currentCamera.center }, }; let cameraTransitionRaf = 0; function getViewportSize() { const rect = root.getBoundingClientRect(); const sceneRect = sceneGrid?.getBoundingClientRect(); return { width: Math.max(1, Math.round(rect.width || sceneRect?.width || 1)), height: Math.max(1, Math.round(sceneRect?.height || rect.height || 1)), }; } function cameraToViewBox(camera: TopologyCameraState) { return getCameraViewBox(camera, worldRadius); } function clampCamera(camera: TopologyCameraState) { return clampCameraToWorld(camera, activeWorldBounds, worldRadius); } function applyCamera(camera: TopologyCameraState, preservePreference = false) { currentCamera = clampCamera(camera); if (!preservePreference) { preferredCamera = { ...currentCamera, center: { ...currentCamera.center }, }; } const viewBox = cameraToViewBox(currentCamera); if (sceneGrid) { sceneGrid.setAttribute("viewBox", `${viewBox.x} ${viewBox.y} ${viewBox.width} ${viewBox.height}`); } if (miniFrame) { miniFrame.classList.remove("is-hidden"); miniFrame.setAttribute("x", String(viewBox.x)); miniFrame.setAttribute("y", String(viewBox.y)); miniFrame.setAttribute("width", String(viewBox.width)); miniFrame.setAttribute("height", String(viewBox.height)); } if (miniReadout) { miniReadout.textContent = `${Math.round(currentCamera.zoom * 100)}%`; } const persistedCamera = preservePreference ? preferredCamera : currentCamera; onCameraChange?.({ ...persistedCamera, center: { ...persistedCamera.center }, }); } function animateCameraTo(targetCamera: TopologyCameraState, duration = cameraTransitionDuration) { const startCamera = { ...currentCamera }; const startCenter = axialToPixel(startCamera.center || { q: 0, r: 0 }, worldRadius); const targetCenter = axialToPixel(targetCamera.center || { q: 0, r: 0 }, worldRadius); const startZoom = startCamera.zoom; const targetZoom = Number(targetCamera.zoom) || startZoom; const startTime = performance.now(); if (cameraTransitionRaf) { window.cancelAnimationFrame(cameraTransitionRaf); } const step = (now: number) => { const progress = Math.min(1, (now - startTime) / Math.max(1, duration)); const eased = 1 - Math.pow(1 - progress, 3); const nextCenterPx = { x: startCenter.x + (targetCenter.x - startCenter.x) * eased, y: startCenter.y + (targetCenter.y - startCenter.y) * eased, }; const nextZoom = startZoom + (targetZoom - startZoom) * eased; applyCamera({ center: cameraPixelToAxial(nextCenterPx, worldRadius), zoom: nextZoom, viewportWidth: currentCamera.viewportWidth, viewportHeight: currentCamera.viewportHeight, }); if (progress < 1) { cameraTransitionRaf = window.requestAnimationFrame(step); } else { cameraTransitionRaf = 0; } }; cameraTransitionRaf = window.requestAnimationFrame(step); } function fit(animated = false) { const { width, height } = getViewportSize(); const targetCamera = fitWorldCameraToEntities({ entities: activeTopologyNodes, viewportWidth: width, viewportHeight: height, radius: worldRadius, padding: worldRadius * 4, }); if (animated) { animateCameraTo(targetCamera); } else { applyCamera(targetCamera); } } function updateViewport() { const { width, height } = getViewportSize(); applyCamera({ ...preferredCamera, viewportWidth: width, viewportHeight: height, }, true); } function centerOnPoint(point: { x: number; y: number }, animated = false) { const targetCamera = { center: cameraPixelToAxial(point, worldRadius), zoom: currentCamera.zoom, viewportWidth: currentCamera.viewportWidth, viewportHeight: currentCamera.viewportHeight, }; if (animated) { animateCameraTo(targetCamera); } else { applyCamera(targetCamera); } } function centerOnNode(node: { q: number; r: number }, animated = false) { const targetCamera = { center: { q: node.q, r: node.r }, zoom: currentCamera.zoom, viewportWidth: currentCamera.viewportWidth, viewportHeight: currentCamera.viewportHeight, }; if (animated) { animateCameraTo(targetCamera); } else { applyCamera(targetCamera); } } function ensureVisible(entityId: string, animated = true) { const node = topologyNodeMap.get(entityId); if (!node) return false; const targetCamera = ensureCameraTargetVisible({ camera: currentCamera, target: node, radius: worldRadius, safeAreaRatio, viewportInsets: getViewportInsets(), }); if (!targetCamera) return false; if (animated) { animateCameraTo(targetCamera); } else { applyCamera(targetCamera); } return true; } function panByScreen(dx: number, dy: number, animated = false) { const center = axialToPixel(currentCamera.center, worldRadius); const zoom = Math.max(currentCamera.zoom, 0.0001); const targetCamera = { ...currentCamera, center: cameraPixelToAxial({ x: center.x + dx / zoom, y: center.y + dy / zoom, }, worldRadius), }; if (animated) { animateCameraTo(targetCamera); } else { applyCamera(targetCamera); } } function zoomBy(delta: number) { applyCamera({ ...currentCamera, zoom: currentCamera.zoom + delta, }); } function setTopology(nodes: Array<{ id: string; q: number; r: number }>, bounds = activeWorldBounds) { activeTopologyNodes = [...nodes]; activeWorldBounds = bounds; topologyNodeMap = new Map(activeTopologyNodes.map((node) => [node.id, node])); const miniNodeGroup = miniMap?.querySelector(".topology-mini-map__nodes"); if (miniNodeGroup) { miniNodes.forEach((node) => node.remove()); miniNodes = []; const miniCells = Array.from(miniMap?.querySelectorAll("[data-topology-mini-cell-id]") ?? []); for (const node of activeTopologyNodes) { const cellId = "hex-" + node.q + "-" + node.r; const cell = miniCells.find((candidate) => candidate.getAttribute("data-topology-mini-cell-id") === cellId); if (!cell) continue; const marker = cell.cloneNode(true) as SVGPathElement; marker.removeAttribute("data-topology-mini-cell-id"); marker.setAttribute("data-topology-mini-node-id", node.id); marker.classList.add("topology-mini-map__node-shape"); miniNodeGroup.append(marker); miniNodes.push(marker); } } applyCamera(currentCamera); syncSelection(activeSelectionId); } function syncSelection(entityId: string) { activeSelectionId = entityId; for (const node of miniNodes) { const isSelected = node.getAttribute("data-topology-mini-node-id") === entityId; node.classList.toggle("is-selected", isSelected); } if (miniReadout) { miniReadout.textContent = entityId ? `Selected: ${entityId.toUpperCase()}` : "Ready"; } } function syncRelationshipContext(context: RelationshipContext) { const relatedIds = new Set(context.relatedIds); const ancestorIds = new Set(context.ancestorIds); const descendantIds = new Set(context.descendantIds); for (const node of miniNodes) { const entityId = node.getAttribute("data-topology-mini-node-id") ?? ""; const state = ancestorIds.has(entityId) ? "ancestor" : descendantIds.has(entityId) ? "descendant" : relatedIds.has(entityId) ? "related" : "idle"; node.classList.toggle("is-ancestor", state === "ancestor"); node.classList.toggle("is-descendant", state === "descendant"); node.classList.toggle("is-related", state === "related"); node.dataset.relationshipState = state; } } function getCamera() { return { ...currentCamera }; } function destroy() { if (cameraTransitionRaf) { window.cancelAnimationFrame(cameraTransitionRaf); cameraTransitionRaf = 0; } } applyCamera(currentCamera); syncSelection(activeSelectionId); return { getCamera, applyCamera, animateCameraTo, fit, updateViewport, centerOnPoint, centerOnNode, ensureVisible, panByScreen, zoomBy, syncSelection, setTopology, syncRelationshipContext, destroy, }; }