import { easeOutCubic, smootherstep } from "./motion.ts"; export type TopologyTransitionPhase = | "idle" | "exiting" | "handoff" | "entering" | "complete" | "cancelled"; export interface TopologyTransitionFrame { phase: TopologyTransitionPhase; progress: number; outgoingOpacity: number; incomingOpacity: number; hierarchyProgress: number; gridOpacity: number; } export interface TopologyTransitionFrameOptions { elapsed: number; duration?: number; reducedMotion?: boolean; } export interface TopologyTransitionLayer { element: HTMLElement | SVGElement; } export interface TopologyTransitionControllerOptions { duration?: number; reducedMotion?: boolean | (() => boolean); onFrame?: (frame: TopologyTransitionFrame) => void; onPhase?: (phase: TopologyTransitionPhase) => void; } export interface TopologyTransitionController { run(input: { outgoing: TopologyTransitionLayer; incoming: TopologyTransitionLayer }): Promise; cancel(): void; } export interface CascadeTransitionNode { id: string; variant?: string; } export interface CascadeTransitionRelationship { from: string; to: string; } export interface CascadeTransitionFrameOptions { nodes: readonly CascadeTransitionNode[]; relationships?: readonly CascadeTransitionRelationship[]; progress: number; direction?: "incoming" | "outgoing"; } export interface CascadeTransitionFrame { nodeOpacity: Record; relationshipOpacity: Record; depthByNode: Record; maxDepth: number; } export interface ScatterTransitionNode { id: string; q: number; r: number; } export interface ScatterTransitionRelationship { from: string; to: string; } export interface ScatterTransitionFrameOptions { nodes: readonly ScatterTransitionNode[]; relationships?: readonly ScatterTransitionRelationship[]; progress: number; direction?: "scatter" | "assemble"; } export interface ScatterTransitionNodeFrame { opacity: number; offsetX: number; offsetY: number; scale: number; } export interface ScatterTransitionFrame { nodes: Record; relationshipOpacity: Record; } export interface CenterSplitTransitionFrameOptions { nodes: readonly ScatterTransitionNode[]; relationships?: readonly ScatterTransitionRelationship[]; progress: number; direction?: "split" | "reveal"; } export interface CenterSplitTransitionNodeFrame { opacity: number; offsetX: number; scale: number; } export interface CenterSplitTransitionFrame { nodes: Record; relationshipOpacity: Record; centerProjection: number; } export type SystemResetTransitionPhase = | "healthy" | "dropping" | "last-node" | "offline" | "booting" | "online"; export interface SystemResetTransitionFrameOptions { nodes: readonly CascadeTransitionNode[]; relationships?: readonly CascadeTransitionRelationship[]; progress: number; direction?: "shutdown" | "boot"; } export interface SystemResetTransitionFrame { phase: SystemResetTransitionPhase; nodeOpacity: Record; relationshipOpacity: Record; finalNodeId: string | null; } export interface SystemResetTimeline { shutdownProgress: number; bootProgress: number; gridOpacity: number; offline: boolean; } const defaultDuration = 1800; function clamp01(value: number) { return Math.min(1, Math.max(0, value)); } function fallbackCascadeDepth(node: CascadeTransitionNode) { if (node.variant === "root") return 0; if (node.variant === "anchor") return 1; return 2; } export function getCascadeTransitionFrame({ nodes, relationships = [], progress, direction = "incoming", }: CascadeTransitionFrameOptions): CascadeTransitionFrame { const nodeIds = new Set(nodes.map((node) => node.id)); const outgoing = new Map(); const incomingCount = new Map(nodes.map((node) => [node.id, 0])); for (const relationship of relationships) { if (!nodeIds.has(relationship.from) || !nodeIds.has(relationship.to)) continue; const targets = outgoing.get(relationship.from) ?? []; targets.push(relationship.to); outgoing.set(relationship.from, targets); incomingCount.set(relationship.to, (incomingCount.get(relationship.to) ?? 0) + 1); } const explicitRoots = nodes.filter((node) => node.variant === "root"); const roots = explicitRoots.length ? explicitRoots : nodes.filter((node) => (incomingCount.get(node.id) ?? 0) === 0); const queue = (roots.length ? roots : nodes.slice(0, 1)).map((node) => node.id); const depthByNode: Record = Object.fromEntries(queue.map((id) => [id, 0])); for (let index = 0; index < queue.length; index += 1) { const sourceId = queue[index]; const sourceDepth = depthByNode[sourceId] ?? 0; for (const targetId of outgoing.get(sourceId) ?? []) { const nextDepth = sourceDepth + 1; if (depthByNode[targetId] !== undefined && depthByNode[targetId] <= nextDepth) continue; depthByNode[targetId] = nextDepth; queue.push(targetId); } } for (const node of nodes) { depthByNode[node.id] ??= fallbackCascadeDepth(node); } const maxDepth = Math.max(0, ...Object.values(depthByNode)); const depthCount = maxDepth + 1; const resolvedProgress = clamp01(progress); const nodeOpacity: Record = {}; for (const node of nodes) { const depth = depthByNode[node.id] ?? 0; const order = direction === "incoming" ? depth : maxDepth - depth; const start = (order / depthCount) * 0.62; const activation = smootherstep(start, Math.min(1, start + 0.42), resolvedProgress); nodeOpacity[node.id] = direction === "incoming" ? activation : 1 - activation; } const relationshipOpacity: Record = {}; for (const relationship of relationships) { const key = relationship.from + "->" + relationship.to; relationshipOpacity[key] = Math.min( nodeOpacity[relationship.from] ?? 0, nodeOpacity[relationship.to] ?? 0, ); } return { nodeOpacity, relationshipOpacity, depthByNode, maxDepth }; } function scatterUnit(id: string) { let hash = 2166136261; for (let index = 0; index < id.length; index += 1) { hash ^= id.charCodeAt(index); hash = Math.imul(hash, 16777619); } return (hash >>> 0) / 4294967295; } export function getScatterTransitionFrame({ nodes, relationships = [], progress, direction = "scatter", }: ScatterTransitionFrameOptions): ScatterTransitionFrame { const resolvedProgress = clamp01(progress); const centerQ = nodes.length ? nodes.reduce((sum, node) => sum + node.q, 0) / nodes.length : 0; const centerR = nodes.length ? nodes.reduce((sum, node) => sum + node.r, 0) / nodes.length : 0; const nodeFrames: Record = {}; const fallbackDirections = [ { x: 1, y: 0 }, { x: 0.5, y: 0.8660254038 }, { x: -0.5, y: 0.8660254038 }, { x: -1, y: 0 }, { x: -0.5, y: -0.8660254038 }, { x: 0.5, y: -0.8660254038 }, ]; for (const node of nodes) { const stagger = scatterUnit(node.id); const start = stagger * 0.22; const motion = smootherstep(start, Math.min(1, start + 0.72), resolvedProgress); const scattered = direction === "scatter" ? motion : 1 - motion; const axialQ = node.q - centerQ; const axialR = node.r - centerR; const pixelX = Math.sqrt(3) * (axialQ + axialR / 2); const pixelY = 1.5 * axialR; const length = Math.hypot(pixelX, pixelY); const fallback = fallbackDirections[Math.floor(stagger * fallbackDirections.length) % fallbackDirections.length]; const directionX = length > 0.0001 ? pixelX / length : fallback.x; const directionY = length > 0.0001 ? pixelY / length : fallback.y; const travel = scattered * (0.82 + stagger * 0.38); nodeFrames[node.id] = { opacity: 1 - smootherstep(0.28, 0.96, scattered), offsetX: directionX * travel, offsetY: directionY * travel, scale: 1 - scattered * 0.2, }; } const relationshipOpacity: Record = {}; for (const relationship of relationships) { const from = nodeFrames[relationship.from]; const to = nodeFrames[relationship.to]; relationshipOpacity[relationship.from + "->" + relationship.to] = Math.min( from?.opacity ?? 0, to?.opacity ?? 0, ); } return { nodes: nodeFrames, relationshipOpacity }; } export function getCenterSplitTransitionFrame({ nodes, relationships = [], progress, direction = "split", }: CenterSplitTransitionFrameOptions): CenterSplitTransitionFrame { const resolvedProgress = clamp01(progress); const projections = nodes.map((node) => node.q + node.r / 2); const centerProjection = projections.length ? projections.reduce((sum, value) => sum + value, 0) / projections.length : 0; const maxDistance = Math.max(1, ...projections.map((value) => Math.abs(value - centerProjection))); const nodeFrames: Record = {}; for (let index = 0; index < nodes.length; index += 1) { const node = nodes[index]; const projection = projections[index] ?? centerProjection; const relative = projection - centerProjection; const distance = Math.abs(relative) / maxDistance; const side = Math.abs(relative) > 0.0001 ? Math.sign(relative) : scatterUnit(node.id) < 0.5 ? -1 : 1; if (direction === "reveal") { const start = distance * 0.48; const activation = smootherstep(start, Math.min(1, start + 0.46), resolvedProgress); nodeFrames[node.id] = { opacity: activation, offsetX: -side * (1 - activation) * (0.28 + distance * 0.42), scale: 0.84 + activation * 0.16, }; } else { const motion = smootherstep(0.04, 0.92, resolvedProgress); nodeFrames[node.id] = { opacity: 1 - smootherstep(0.56, 1, motion), offsetX: side * motion * (0.72 + distance * 0.28), scale: 1 - motion * 0.08, }; } } const relationshipOpacity: Record = {}; for (const relationship of relationships) { relationshipOpacity[relationship.from + "->" + relationship.to] = Math.min( nodeFrames[relationship.from]?.opacity ?? 0, nodeFrames[relationship.to]?.opacity ?? 0, ); } return { nodes: nodeFrames, relationshipOpacity, centerProjection }; } export function getSystemResetTransitionFrame({ nodes, relationships = [], progress, direction = "shutdown", }: SystemResetTransitionFrameOptions): SystemResetTransitionFrame { const resolvedProgress = clamp01(progress); const finalNodeId = nodes.find((node) => node.variant === "root")?.id ?? nodes[0]?.id ?? null; let phase: SystemResetTransitionPhase; let nodeOpacity: Record; if (direction === "boot") { const cascade = getCascadeTransitionFrame({ nodes, relationships, progress: smootherstep(0.04, 0.96, resolvedProgress), direction: "incoming", }); nodeOpacity = cascade.nodeOpacity; phase = resolvedProgress <= 0 ? "offline" : resolvedProgress >= 1 ? "online" : "booting"; } else { nodeOpacity = {}; for (const node of nodes) { const opacity = node.id === finalNodeId ? 1 - smootherstep(0.62, 0.82, resolvedProgress) : 1 - smootherstep(0.1 + scatterUnit(node.id) * 0.34, 0.24 + scatterUnit(node.id) * 0.34, resolvedProgress); nodeOpacity[node.id] = opacity; } phase = resolvedProgress < 0.1 ? "healthy" : resolvedProgress < 0.6 ? "dropping" : resolvedProgress < 0.82 ? "last-node" : "offline"; } const relationshipOpacity: Record = {}; for (const relationship of relationships) { relationshipOpacity[relationship.from + "->" + relationship.to] = Math.min( nodeOpacity[relationship.from] ?? 0, nodeOpacity[relationship.to] ?? 0, ); } return { phase, nodeOpacity, relationshipOpacity, finalNodeId }; } export function getSystemResetTimeline(progress: number): SystemResetTimeline { const resolvedProgress = clamp01(progress); return { shutdownProgress: smootherstep(0.02, 0.64, resolvedProgress), bootProgress: smootherstep(0.72, 0.98, resolvedProgress), gridOpacity: resolvedProgress < 0.68 ? 1 - smootherstep(0.46, 0.64, resolvedProgress) : smootherstep(0.72, 0.9, resolvedProgress), offline: resolvedProgress >= 0.64 && resolvedProgress <= 0.72, }; } export function getTopologyTransitionFrame({ elapsed, duration = defaultDuration, reducedMotion = false, }: TopologyTransitionFrameOptions): TopologyTransitionFrame { if (reducedMotion) { return { phase: "complete", progress: 1, outgoingOpacity: 0, incomingOpacity: 1, hierarchyProgress: 1, gridOpacity: 1, }; } const progress = clamp01(elapsed / Math.max(1, duration)); const exitEnd = 0.34; const handoffEnd = 0.44; const outgoingOpacity = progress < exitEnd ? 1 - easeOutCubic(progress / exitEnd) : 0; const incomingOpacity = progress < handoffEnd ? 0 : smootherstep(handoffEnd, 1, progress); const hierarchyProgress = progress < handoffEnd ? 0 : smootherstep(handoffEnd, 1, progress); let phase: TopologyTransitionPhase = "entering"; if (progress === 0) phase = "exiting"; else if (progress < exitEnd) phase = "exiting"; else if (progress < handoffEnd) phase = "handoff"; else if (progress < 1) phase = "entering"; else phase = "complete"; return { phase, progress, outgoingOpacity, incomingOpacity, hierarchyProgress, gridOpacity: 1, }; } export function getHierarchyRevealOpacity( depth: number, progress: number, depthCount = 3, ) { const normalizedDepth = Math.max(0, Math.min(depthCount - 1, depth)); const depthSpan = 0.72 / Math.max(1, depthCount); const start = normalizedDepth * depthSpan; const end = Math.min(1, start + depthSpan * 1.7); return smootherstep(start, end, clamp01(progress)); } function isReducedMotion(value: TopologyTransitionControllerOptions["reducedMotion"]) { return typeof value === "function" ? value() : Boolean(value); } function getOrderedRevealOpacity(order: number, progress: number, count: number) { const unit = 1 / Math.max(1, count); const start = order * unit * 0.78; const end = Math.min(1, start + unit * 1.35); return smootherstep(start, end, clamp01(progress)); } function applyLayerFrame( layer: HTMLElement | SVGElement, opacity: number, hierarchyProgress: number, isIncoming: boolean, ) { layer.style.opacity = String(opacity); layer.style.pointerEvents = opacity > 0.02 ? "auto" : "none"; layer.dataset.topologyTransitionVisibility = opacity > 0.02 ? "visible" : "hidden"; if (!isIncoming) return; const elements = Array.from(layer.querySelectorAll("[data-topology-transition-kind]")); const orderedCount = elements.reduce((maximum, element) => { const order = Number(element.getAttribute("data-topology-transition-order")); return Number.isFinite(order) ? Math.max(maximum, order + 1) : maximum; }, 0); elements.forEach((element) => { const order = Number(element.getAttribute("data-topology-transition-order")); const depth = Number(element.getAttribute("data-topology-transition-depth") ?? 0); const elementOpacity = Number.isFinite(order) ? getOrderedRevealOpacity(order, hierarchyProgress, orderedCount) : getHierarchyRevealOpacity(depth, hierarchyProgress); if (element.style) { element.style.opacity = String(elementOpacity); } }); } export function createTopologyTransitionController({ duration = defaultDuration, reducedMotion = false, onFrame, onPhase, }: TopologyTransitionControllerOptions = {}): TopologyTransitionController { let generation = 0; let frameHandle = 0; function cancel() { generation += 1; window.cancelAnimationFrame(frameHandle); onPhase?.("cancelled"); } function run({ outgoing, incoming }: { outgoing: TopologyTransitionLayer; incoming: TopologyTransitionLayer }) { cancel(); const currentGeneration = generation; const shouldReduce = isReducedMotion(reducedMotion); const startedAt = performance.now(); return new Promise((resolve) => { const render = (now: number) => { if (currentGeneration !== generation) { resolve(); return; } const frame = getTopologyTransitionFrame({ elapsed: now - startedAt, duration, reducedMotion: shouldReduce, }); onPhase?.(frame.phase); applyLayerFrame(outgoing.element, frame.outgoingOpacity, 0, false); applyLayerFrame(incoming.element, frame.incomingOpacity, frame.hierarchyProgress, true); onFrame?.(frame); if (frame.phase === "complete") { applyLayerFrame(outgoing.element, 0, 0, false); applyLayerFrame(incoming.element, 1, 1, true); resolve(); return; } frameHandle = window.requestAnimationFrame(render); }; frameHandle = window.requestAnimationFrame(render); }); } return { run, cancel }; }