{"$schema":"https:\/\/ui.particle.academy\/schema\/registry-item.json","name":"graph-view","type":"registry:ui","title":"GraphView","description":"2D canvas graph view: network, radial, hierarchy and clustered presets, controlled selection, hover, focus, search and camera, keyboard and gamepad stepping along links, stable data-fancy-graph handles.","package":"fancy-graph","dependencies":[],"registryDependencies":[],"files":[{"path":"components\/fancy\/graph-view\/GraphView.tsx","content":"import { useImperativeHandle, useLayoutEffect, useMemo, useRef, type CSSProperties, type Ref } from \"react\";\nimport type { Camera2D } from \"..\/lib\/camera\";\nimport type { GraphLayout } from \"..\/lib\/layout\/contract\";\nimport { CanvasEngine, type ClusterSource, type Engine2DOptions } from \"..\/lib\/render2d\/engine\";\nimport type { GraphRenderers2D } from \"..\/lib\/render2d\/types\";\nimport { neighborLinks, type NeighborLink, type StepDirection } from \"..\/lib\/interaction\";\nimport type { GraphActivitySource, GraphCluster, GraphNode } from \"..\/lib\/types\";\nimport { effectiveFocus, freshCycle, stepFocusIndex, type PendingFocus } from \".\/navigation\";\nimport { useGraphModel, type GraphViewBaseProps } from \".\/model\";\nimport { resolvePreset2D, type GraphPreset2D, type GraphPreset2DId } from \"..\/lib\/presets\/presets2d\";\nimport { applyThemeVars, resolveTheme, typeColorsFor } from \"..\/lib\/theme\";\nimport { DEFAULT_LAYERS, mergeLayerSpecs, type GraphLayerSpec } from \"..\/lib\/layers\";\nimport { controlsDataset, controlsHandle, controlsState, isAnimatedLayout, renderControls, type GraphControlsHandle, type GraphControlsState } from \".\/controls\";\n\nexport interface GraphViewHandleBase extends GraphControlsHandle {\n  \/** Select a node (or null), through the same controlled path a click takes. *\/\n  select(id: string | null, opts?: { source?: GraphActivitySource }): void;\n  \/** Search results, the selection and counts, for agents and tooling. *\/\n  getState(): GraphViewState;\n  getClusters(): GraphCluster[];\n  \/** Projected position (CSS px, relative to the canvas) of a node in the last frame. *\/\n  screenPosition(id: string): { x: number; y: number; radius: number } | null;\n  \/** The node under a canvas point, or null. *\/\n  pick(x: number, y: number): string | null;\n  \/** Renders one frame synchronously; returns its cost in ms. *\/\n  renderFrame(dt?: number): { ms: number };\n  \/** The root element (`[data-fancy-graph]`). *\/\n  readonly root: HTMLElement | null;\n  \/** A node's links in a stable order (input link order), each with the node at the other end. *\/\n  neighbors(id: string): NeighborLink[];\n  \/**\n   * Moves the focus: along a link in a screen direction, or to the next \/\n   * previous link of the node where cycling began. Returns the focused id.\n   *\/\n  stepFocus(direction: StepDirection, opts?: { source?: GraphActivitySource }): string | null;\n  \/** Sets the focus directly (null clears it). *\/\n  focus(id: string | null, opts?: { source?: GraphActivitySource }): void;\n  \/** Analog camera input, per frame. Rotates about the target by radians; returns false where there is no rotation (2D). *\/\n  orbit(dx: number, dy: number): boolean;\n  \/** Moves the view by screen px (x right, y down). Releases a follow. *\/\n  pan(dx: number, dy: number): void;\n  \/** Multiplies the zoom (greater than 1 is closer). *\/\n  zoom(factor: number): void;\n  \/** A node's position in the current layout (world units), or null. *\/\n  positionOf(id: string): [number, number, number] | null;\n}\n\nexport interface GraphViewState extends GraphControlsState {\n  selected: string | null;\n  hovered: string | null;\n  focused: string | null;\n  matches: string[];\n  nodeCount: number;\n  linkCount: number;\n  dropped: { nodes: number; links: number; invalidLinks: number; duplicateNodes: number };\n}\n\nexport interface GraphViewHandle extends GraphViewHandleBase {\n  flyTo(id: string, opts?: { zoom?: number; instant?: boolean }): boolean;\n  fit(ids?: string[], opts?: { instant?: boolean }): void;\n  reset(): void;\n  getCamera(): Camera2D;\n  setCamera(camera: Camera2D, opts?: { instant?: boolean }): void;\n  follow(id: string | null): void;\n}\n\nexport interface GraphViewProps extends GraphViewBaseProps {\n  ref?: Ref<GraphViewHandle>;\n  \/**\n   * A ready-made view: `\"network\"` (default), `\"radial\"`, `\"hierarchy\"`,\n   * `\"clustered\"`, or a preset object (see `GRAPH_PRESETS_2D` and the preset\n   * factories). Any of `layout`, `renderers`, `clusters`, `clusterLabel` and\n   * `linkVisibility` passed as well overrides that piece of the preset.\n   *\/\n  preset?: GraphPreset2DId | GraphPreset2D;\n  \/** A layout function or stepper. Overrides the preset's. *\/\n  layout?: GraphLayout;\n  renderers?: GraphRenderers2D;\n  \/** `\"group\"`, a fixed list, or a function of the live positions. Defaults to the layout's own clusters, if any. *\/\n  clusters?: ClusterSource;\n  clusterLabel?: (cluster: GraphCluster) => string | null;\n  nodeColor?: (node: GraphNode, index: number) => string;\n  \/** World-space radius per node. *\/\n  nodeSize?: (node: GraphNode, index: number) => number;\n  \/** Requested camera. When it changes the view flies there; `onCameraChange` reports where it settled. *\/\n  camera?: Camera2D;\n  onCameraChange?: (camera: Camera2D) => void;\n  \/** Canvas fill. Defaults to the theme's background; `\"transparent\"` lets the container show. *\/\n  background?: string;\n  \/** Link stroke colour. Defaults to the theme's. *\/\n  linkColor?: string;\n  \/** Fixed size in CSS px. Omit to fill the container (it needs a height). *\/\n  width?: number;\n  height?: number;\n}\n\nexport const visuallyHidden: CSSProperties = { position: \"absolute\", width: 1, height: 1, overflow: \"hidden\", clip: \"rect(0 0 0 0)\", whiteSpace: \"nowrap\" };\n\n\/**\n * A knowledge-graph viewer on a 2D canvas. Controlled: selection, hover,\n * focus, search and camera come in as props and go out through callbacks.\n * Layout and drawing are pluggable; picking, labels, camera and motion\n * preferences are the kit's.\n *\/\nexport function GraphView(props: GraphViewProps) {\n  const preset = useMemo(() => resolvePreset2D(props.preset), [props.preset]);\n  \/\/ The preset's layers, plus any the props add (a cluster source, a background renderer).\n  const hasClusters = props.clusters !== undefined || preset.clusters !== undefined;\n  const hasBackground = !!(props.renderers?.background ?? preset.renderers?.background);\n  const layerSpecs = useMemo<readonly GraphLayerSpec[]>(\n    () =>\n      mergeLayerSpecs(\n        preset.layers ?? DEFAULT_LAYERS,\n        hasClusters ? [{ id: \"clusters\", label: \"Clusters\" }] : [],\n        hasBackground ? [{ id: \"background\", label: \"Background\" }] : [],\n      ),\n    [preset, hasClusters, hasBackground],\n  );\n  const model = useGraphModel(props, { layers: layerSpecs, linkVisibility: preset.linkVisibility });\n  const { graph, limits } = model;\n  const rootRef = useRef<HTMLDivElement | null>(null);\n  const canvasRef = useRef<HTMLCanvasElement | null>(null);\n  const labelsRef = useRef<HTMLDivElement | null>(null);\n  const engineRef = useRef<CanvasEngine | null>(null);\n  const latest = useRef({ props, model, preset });\n  latest.current = { props, model, preset };\n\n  \/\/ The preset's layout, rebuilt only when its key changes (the radial view's centre).\n  const presetState = { graph, selected: model.selectedId, focused: model.focusedId };\n  const layoutKey = preset.layoutKey ? preset.layoutKey(presetState) : \"\";\n  \/\/ eslint-disable-next-line react-hooks\/exhaustive-deps\n  const presetLayout = useMemo(() => preset.layout(presetState), [preset, layoutKey, graph]);\n  const layout = props.layout ?? presetLayout;\n  const animated = isAnimatedLayout(layout);\n  const animatedRef = useRef(animated);\n  animatedRef.current = animated;\n\n  const options = (): Engine2DOptions => {\n    const { props: p, model: m, preset: pr } = latest.current;\n    \/\/ Resolved against the container, not the root, so the variables the root sets for its labels never feed back.\n    const themeEl = rootRef.current?.parentElement ?? null;\n    const theme = resolveTheme(p.theme, themeEl);\n    if (rootRef.current) {\n      applyThemeVars(rootRef.current, theme);\n      rootRef.current.dataset.fancyGraphTheme = theme.mode;\n    }\n    const typeColorOf = typeColorsFor(theme, m.graph.nodes, themeEl);\n    return {\n      renderers: { ...(pr.renderers ?? {}), ...(p.renderers ?? {}) },\n      clusters: p.clusters ?? pr.clusters,\n      clusterLabel: p.clusterLabel ?? pr.clusterLabel,\n      nodeColor: (i) => {\n        const node = m.graph.nodes[i];\n        return p.nodeColor ? p.nodeColor(node, i) : (node.color ?? typeColorOf(node.group));\n      },\n      nodeSize: p.nodeSize ? (i) => p.nodeSize!(m.graph.nodes[i], i) : undefined,\n      labelOf: m.labelOf,\n      linkVisibility: m.linkVisibility,\n      layers: m.layers,\n      background: p.background ?? theme.background,\n      linkColor: p.linkColor ?? theme.link,\n      focusColor: theme.focus,\n      paused: m.paused,\n    };\n  };\n\n  \/\/ The engine lives as long as the canvas does.\n  useLayoutEffect(() => {\n    const canvas = canvasRef.current!;\n    const engine = new CanvasEngine(\n      canvas,\n      labelsRef.current!,\n      latest.current.model.limits,\n      options(),\n      {\n        onSelect: (i) => {\n          const m = latest.current.model;\n          const id = i >= 0 ? m.graph.nodes[i].id : null;\n          \/\/ A click on the selected node clears it: in a dense view there may be no empty space to click.\n          m.select(id !== null && id === m.selectedId ? null : id, { source: \"user\" });\n        },\n        onHover: (i) => {\n          const m = latest.current.model;\n          m.hover(i >= 0 ? m.graph.nodes[i].id : null, { source: \"user\" });\n        },\n        onCamera: (c) => {\n          latest.current.props.onCameraChange?.(c);\n          latest.current.model.emit(\"camera\", null, \"user\");\n        },\n        onEscape: () => {\n          const m = latest.current.model;\n          if (m.selectedId !== null) m.select(null, { source: \"user\" });\n        },\n      },\n      latest.current.model.reducedMotion,\n    );\n    engineRef.current = engine;\n    return () => {\n      engine.destroy();\n      engineRef.current = null;\n    };\n    \/\/ eslint-disable-next-line react-hooks\/exhaustive-deps\n  }, []);\n\n  useLayoutEffect(() => {\n    engineRef.current?.setReducedMotion(model.reducedMotion);\n  }, [model.reducedMotion]);\n  useLayoutEffect(() => {\n    engineRef.current?.setLimits(limits);\n  }, [limits]);\n  useLayoutEffect(() => {\n    engineRef.current?.setGraph(graph, layout);\n  }, [graph, layout]);\n  const themeKey = JSON.stringify(props.theme ?? \"auto\");\n  useLayoutEffect(() => {\n    engineRef.current?.setOptions(options());\n    \/\/ eslint-disable-next-line react-hooks\/exhaustive-deps\n  }, [preset, themeKey, props.renderers, props.clusters, props.clusterLabel, props.nodeColor, props.nodeSize, model.labelOf, model.linkVisibility, model.layers, props.background, props.linkColor, model.paused]);\n  useLayoutEffect(() => {\n    engineRef.current?.setInteraction(model.selectedIndex, model.hoveredIndex, model.matches, model.focusedIndex, !!props.neighborhood);\n  }, [model.selectedIndex, model.hoveredIndex, model.matches, model.focusedIndex, props.neighborhood]);\n  const followFocused = props.followFocused ?? true;\n  useLayoutEffect(() => {\n    if (followFocused && model.focusedIndex >= 0) engineRef.current?.setFocus(model.focusedIndex);\n  }, [followFocused, model.focusedIndex, graph]);\n  const cycle = useRef(freshCycle());\n  const pendingFocus = useRef<PendingFocus | null>(null);\n  useLayoutEffect(() => {\n    pendingFocus.current = null;\n  });\n  const flyOnSelect = props.flyOnSelect ?? false;\n  useLayoutEffect(() => {\n    if (flyOnSelect && model.selectedIndex >= 0) engineRef.current?.flyToIndex(model.selectedIndex);\n  }, [flyOnSelect, model.selectedIndex]);\n  const camKey = props.camera ? `${props.camera.x},${props.camera.y},${props.camera.zoom}` : \"\";\n  useLayoutEffect(() => {\n    const c = latest.current.props.camera;\n    const e = engineRef.current;\n    if (!c || !e) return;\n    const cur = e.getCamera();\n    if (cur.x !== c.x || cur.y !== c.y || cur.zoom !== c.zoom) e.setCamera(c);\n  }, [camKey]);\n\n  \/\/ Size: fixed props, else follow the container.\n  useLayoutEffect(() => {\n    const root = rootRef.current!;\n    const apply = () => {\n      const w = props.width ?? (root.clientWidth || 300);\n      const h = props.height ?? (root.clientHeight || 150);\n      engineRef.current?.setSize(w, h, typeof window !== \"undefined\" ? window.devicePixelRatio : 1);\n    };\n    apply();\n    if (props.width !== undefined && props.height !== undefined) return;\n    if (typeof ResizeObserver === \"undefined\") return;\n    const ro = new ResizeObserver(apply);\n    ro.observe(root);\n    return () => ro.disconnect();\n  }, [props.width, props.height]);\n\n  useImperativeHandle(\n    props.ref,\n    (): GraphViewHandle => {\n      const e = () => engineRef.current;\n      const m = () => latest.current.model;\n      const index = (id: string) => m().graph.index.get(id) ?? -1;\n      return {\n        ...controlsHandle(m),\n        neighbors: (id) => (m().graph.index.has(id) ? neighborLinks(m().graph, index(id)) : []),\n        positionOf: (id) => e()?.positionOf(index(id)) ?? null,\n        stepFocus(direction, opts) {\n          const mm = m();\n          const screen = e()?.getScreen() ?? new Float32Array(0);\n          const current = effectiveFocus(mm.focusedId, pendingFocus.current);\n          const from = current !== null ? (mm.graph.index.get(current) ?? -1) : -1;\n          const next = stepFocusIndex(mm.graph, cycle.current, from, mm.selectedIndex, direction, screen);\n          const id = next >= 0 ? mm.graph.nodes[next].id : null;\n          if (id !== current) {\n            pendingFocus.current = { id, from: mm.focusedId };\n            mm.setFocused(id, { source: opts?.source ?? \"api\" });\n          }\n          return id;\n        },\n        focus(id, opts) {\n          const mm = m();\n          if (id !== null && !mm.graph.index.has(id)) return;\n          mm.setFocused(id, { source: opts?.source ?? \"api\" });\n        },\n        orbit: () => false,\n        pan: (dx, dy) => e()?.pan(dx, dy),\n        zoom: (f) => e()?.zoomBy(f),\n        select(id, opts) {\n          const mm = m();\n          if (id !== null && !mm.graph.index.has(id)) return;\n          mm.select(id, { source: opts?.source ?? \"api\" });\n        },\n        flyTo(id, opts) {\n          const ok = !!e()?.flyToIndex(index(id), opts?.zoom, opts?.instant);\n          if (ok) m().emit(\"focus\", id, \"api\");\n          return ok;\n        },\n        fit(ids, opts) {\n          e()?.fit(ids ? ids.map(index).filter((i) => i >= 0) : null, opts?.instant);\n        },\n        reset() {\n          e()?.fit(null);\n        },\n        getCamera: () => e()?.getCamera() ?? { x: 0, y: 0, zoom: 1 },\n        setCamera(c, opts) {\n          e()?.setCamera(c, opts?.instant);\n        },\n        follow(id) {\n          e()?.setFollow(id === null ? -1 : index(id));\n        },\n        screenPosition: (id) => e()?.screenPosition(index(id)) ?? null,\n        pick(x, y) {\n          const i = e()?.pick(x, y) ?? -1;\n          return i >= 0 ? m().graph.nodes[i].id : null;\n        },\n        renderFrame: (dt) => e()?.renderFrame(dt) ?? { ms: 0 },\n        getClusters: () => e()?.getClusters() ?? [],\n        getState() {\n          const mm = m();\n          return {\n            selected: mm.selectedId,\n            hovered: mm.hoveredId,\n            focused: mm.focusedId,\n            matches: mm.matchIds,\n            nodeCount: mm.graph.nodes.length,\n            linkCount: mm.graph.links.length,\n            dropped: { ...mm.graph.dropped },\n            ...controlsState(mm, animatedRef.current),\n          };\n        },\n        get root() {\n          return rootRef.current;\n        },\n      };\n    },\n    [],\n  );\n\n  const selectedLabel = model.selectedIndex >= 0 ? model.labelOf(model.selectedIndex) : \"\";\n  const label = `${props[\"aria-label\"] ?? \"Graph\"}: ${graph.nodes.length} nodes, ${graph.links.length} links`;\n  return (\n    <div\n      ref={rootRef}\n      className={props.className}\n      style={{ position: \"relative\", overflow: \"hidden\", touchAction: \"none\", width: props.width, height: props.height, ...props.style }}\n      data-fancy-graph=\"\"\n      data-fancy-graph-renderer=\"2d\"\n      data-fancy-graph-preset={preset.id}\n      data-fancy-graph-node-count={graph.nodes.length}\n      data-fancy-graph-link-count={graph.links.length}\n      data-fancy-graph-selected={model.selectedId ?? \"\"}\n      data-fancy-graph-hovered={model.hoveredId ?? \"\"}\n      data-fancy-graph-focused={model.focusedId ?? \"\"}\n      data-fancy-graph-matches={model.matchIds.length}\n      {...controlsDataset(model)}\n    >\n      <canvas ref={canvasRef} tabIndex={0} role=\"img\" aria-label={label} data-fancy-graph-canvas=\"\" style={{ display: \"block\", width: \"100%\", height: \"100%\", outline: \"none\", cursor: \"grab\" }} \/>\n      <div ref={labelsRef} aria-hidden=\"true\" data-fancy-graph-labels=\"\" style={{ position: \"absolute\", inset: 0, pointerEvents: \"none\", overflow: \"hidden\" }} \/>\n      <div aria-live=\"polite\" style={visuallyHidden} data-fancy-graph-announcer=\"\">\n        {selectedLabel ? `Selected ${selectedLabel}` : \"\"}\n      <\/div>\n      {renderControls(props.controls, model, animated)}\n    <\/div>\n  );\n}\n\n\n","type":"registry:ui","target":"components\/fancy\/graph-view\/GraphView.tsx"},{"path":"components\/fancy\/graph-view\/navigation.ts","content":"import { cycleNeighbor, neighborLinks, stepInDirection, type StepDirection } from \"..\/lib\/interaction\";\nimport type { IndexedGraph } from \"..\/lib\/types\";\n\n\/** Where link cycling is: the node whose links are being walked, and the position in them. *\/\nexport interface CycleState {\n  anchor: number;\n  position: number;\n}\n\nexport const freshCycle = (): CycleState => ({ anchor: -1, position: -1 });\n\n\/**\n * A focus change asked for but not yet rendered. A gamepad can step twice in\n * one tick; the second step must start where the first one went, not where the\n * last render left the focus. Cleared after every commit.\n *\/\nexport interface PendingFocus {\n  id: string | null;\n  \/** The rendered focus when the change was asked for. *\/\n  from: string | null;\n}\n\n\/** The focus a step should start from: the pending one while the render has not caught up. *\/\nexport function effectiveFocus(rendered: string | null, pending: PendingFocus | null): string | null {\n  return pending && pending.from === rendered ? pending.id : rendered;\n}\n\n\/**\n * One gamepad \/ keyboard step. With nothing focused, focus lands on the\n * selection, else on the best-connected node. Directions follow links on\n * screen; next \/ previous walk the anchor's links in their stable order, where\n * the anchor is the node focused when cycling began. Returns the node index to\n * focus (unchanged when there is nowhere to go).\n *\/\nexport function stepFocusIndex(graph: IndexedGraph, cycle: CycleState, focused: number, selected: number, dir: StepDirection, screen: Float32Array): number {\n  const n = graph.nodes.length;\n  if (!n) return -1;\n  if (focused < 0 || focused >= n) {\n    cycle.anchor = cycle.position = -1;\n    if (selected >= 0 && selected < n) return selected;\n    let best = 0;\n    for (let i = 1; i < n; i++) if (graph.degree[i] > graph.degree[best]) best = i;\n    return best;\n  }\n  if (dir === \"next\" || dir === \"previous\") {\n    const links = cycle.anchor >= 0 ? neighborLinks(graph, cycle.anchor) : [];\n    const onCycle = cycle.position >= 0 && links[cycle.position]?.index === focused;\n    if (!onCycle) {\n      cycle.anchor = focused;\n      cycle.position = -1;\n    }\n    const next = cycleNeighbor(graph, cycle.anchor, cycle.position, dir === \"next\" ? 1 : -1);\n    if (!next) return focused;\n    cycle.position = next.position;\n    return next.index;\n  }\n  cycle.anchor = cycle.position = -1;\n  const j = stepInDirection(graph, focused, dir, screen);\n  return j >= 0 ? j : focused;\n}\n","type":"registry:ui","target":"components\/fancy\/graph-view\/navigation.ts"},{"path":"components\/fancy\/graph-view\/model.ts","content":"import { useCallback, useEffect, useMemo, useRef, useState, type ComponentType, type CSSProperties } from \"react\";\nimport { normalizeGraph } from \"..\/lib\/graph\";\nimport { searchNodes } from \"..\/lib\/interaction\";\nimport { DEFAULT_LAYERS, layerMap, resolveLayers, type GraphLayerSpec, type GraphLayerState, type GraphLayerVisibility, type LinkVisibility } from \"..\/lib\/layers\";\nimport type { GraphControlsProps } from \".\/controls\";\nimport { resolveLimits, type GraphLimits } from \"..\/lib\/limits\";\nimport type { GraphThemeInput } from \"..\/lib\/theme\";\nimport type { GraphActivity, GraphActivitySource, GraphData, GraphNode, IndexedGraph } from \"..\/lib\/types\";\n\nexport interface ChangeMeta {\n  source: GraphActivitySource;\n}\n\n\/** The props every renderer shares: data, controlled interaction state, search, limits, motion. *\/\nexport interface GraphViewBaseProps {\n  \/** Plain JSON. A new object means a new graph; mutate nothing in place. *\/\n  data: GraphData;\n  \/** Controlled selection (a node id or null). Omit to let the view own it. *\/\n  selected?: string | null;\n  defaultSelected?: string | null;\n  onSelectedChange?: (id: string | null, meta: ChangeMeta) => void;\n  \/** Controlled hover. *\/\n  hovered?: string | null;\n  onHoveredChange?: (id: string | null, meta: ChangeMeta) => void;\n  \/**\n   * `\"light\"`, `\"dark\"`, `\"auto\"` (default: a `.dark` \/ `[data-theme=dark]`\n   * ancestor, else the system), or overrides such as per-type colours:\n   * `{ base: \"dark\", typeColors: { person: \"#f472b6\" } }`. CSS variables\n   * (`--fancy-graph-background`, `--fancy-graph-type-<type>`, ...) override the base.\n   *\/\n  theme?: GraphThemeInput;\n  \/**\n   * Controlled keyboard \/ gamepad focus: a cursor distinct from the selection,\n   * drawn with its own ring, labelled with its neighbours, and kept in view.\n   * Move it with the handle's `stepFocus`.\n   *\/\n  focused?: string | null;\n  defaultFocused?: string | null;\n  onFocusedChange?: (id: string | null, meta: ChangeMeta) => void;\n  \/** Keep the focused node in view (the camera follows it). Default true. *\/\n  followFocused?: boolean;\n  \/** Neighbourhood mode: dim everything but the focused node and its neighbours, and label only them. *\/\n  neighborhood?: boolean;\n  \/** Search query. Matches are highlighted, labelled, and reported. *\/\n  search?: string;\n  onSearchResults?: (ids: string[]) => void;\n  \/** Label text per node. Defaults to the label, then the id. Always rendered as text. *\/\n  label?: (node: GraphNode, index: number) => string;\n  \/** Fly to a node when it becomes selected. 2D defaults to false, 3D to true. *\/\n  flyOnSelect?: boolean;\n  \/**\n   * `\"all\"`, `\"focus\"` (only the focus's links while something is focused or\n   * searched), or `\"none\"`. Controlled when given; else `defaultLinkVisibility`,\n   * else the preset's, else `\"all\"`. Switching the `links` layer off overrides it.\n   *\/\n  linkVisibility?: LinkVisibility;\n  defaultLinkVisibility?: LinkVisibility;\n  onLinkVisibilityChange?: (mode: LinkVisibility, meta: ChangeMeta) => void;\n  \/**\n   * Which of the preset's layers are drawn, as JSON: `{ orbits: true, labels: false }`.\n   * Ids are the preset's (`getLayers()` lists them: `links`, `labels`,\n   * `clusters`, `background`, `orbits`, ...); one left out keeps its default.\n   * Controlled when given.\n   *\/\n  layers?: Partial<GraphLayerVisibility>;\n  defaultLayers?: Partial<GraphLayerVisibility>;\n  \/** Gets the full map, one key per declared layer. *\/\n  onLayersChange?: (layers: GraphLayerVisibility, meta: ChangeMeta) => void;\n  \/** Freezes animated layouts (orbits). Controlled when given. *\/\n  paused?: boolean;\n  defaultPaused?: boolean;\n  onPausedChange?: (paused: boolean, meta: ChangeMeta) => void;\n  \/**\n   * A view-controls overlay drawn over the view, wired to all of the above and\n   * the selection: pass `GraphViewControls` from\n   * `@particle-academy\/fancy-graph\/controls`, or your own component. Off by default.\n   *\/\n  controls?: ComponentType<GraphControlsProps> | null | false;\n  \/** `\"auto\"` (default) follows `prefers-reduced-motion`. *\/\n  reducedMotion?: boolean | \"auto\";\n  limits?: Partial<GraphLimits>;\n  onActivity?: (event: GraphActivity) => void;\n  className?: string;\n  style?: CSSProperties;\n  \"aria-label\"?: string;\n}\n\n\/** Reads `prefers-reduced-motion` and follows changes to it. *\/\nexport function useReducedMotion(pref: boolean | \"auto\" | undefined): boolean {\n  const query = () => typeof window !== \"undefined\" && typeof window.matchMedia === \"function\" && window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches;\n  const [system, setSystem] = useState<boolean>(query);\n  useEffect(() => {\n    if (pref !== \"auto\" && pref !== undefined) return;\n    if (typeof window === \"undefined\" || typeof window.matchMedia !== \"function\") return;\n    const mq = window.matchMedia(\"(prefers-reduced-motion: reduce)\");\n    const on = () => setSystem(mq.matches);\n    mq.addEventListener?.(\"change\", on);\n    return () => mq.removeEventListener?.(\"change\", on);\n  }, [pref]);\n  return pref === true ? true : pref === false ? false : system;\n}\n\nfunction useControllable<T>(value: T | undefined, defaultValue: T, onChange?: (v: T, meta: ChangeMeta) => void) {\n  const [inner, setInner] = useState<T>(defaultValue);\n  const controlled = value !== undefined;\n  const current = controlled ? value : inner;\n  const set = useCallback(\n    (next: T, meta: ChangeMeta) => {\n      if (!controlled) setInner(next);\n      onChange?.(next, meta);\n    },\n    [controlled, onChange],\n  );\n  return [current, set] as const;\n}\n\nexport interface GraphModel {\n  graph: IndexedGraph;\n  limits: GraphLimits;\n  matches: Set<number> | null;\n  matchIds: string[];\n  selectedId: string | null;\n  hoveredId: string | null;\n  selectedIndex: number;\n  hoveredIndex: number;\n  focusedId: string | null;\n  focusedIndex: number;\n  reducedMotion: boolean;\n  select: (id: string | null, meta: ChangeMeta) => void;\n  hover: (id: string | null, meta: ChangeMeta) => void;\n  setFocused: (id: string | null, meta: ChangeMeta) => void;\n  emit: (type: GraphActivity[\"type\"], id: string | null | undefined, source: GraphActivitySource) => void;\n  labelOf: (index: number) => string;\n  \/** The declared layers, resolved. *\/\n  layerStates: GraphLayerState[];\n  \/** `{ id: visible }` for every declared layer. *\/\n  layers: GraphLayerVisibility;\n  \/** False for an id the view does not declare. *\/\n  setLayer: (id: string, visible: boolean, meta: ChangeMeta) => boolean;\n  \/** The mode asked for; the `links` layer may still hide them. *\/\n  linkVisibility: LinkVisibility;\n  setLinkVisibility: (mode: LinkVisibility, meta: ChangeMeta) => void;\n  paused: boolean;\n  setPaused: (paused: boolean, meta: ChangeMeta) => void;\n}\n\n\/** What the view (its preset) tells the model: the layers it draws and its default link mode. *\/\nexport interface GraphModelView {\n  layers?: readonly GraphLayerSpec[];\n  linkVisibility?: LinkVisibility;\n}\n\nexport function useGraphModel(props: GraphViewBaseProps, view: GraphModelView = {}): GraphModel {\n  const limitsKey = JSON.stringify(props.limits ?? {});\n  \/\/ eslint-disable-next-line react-hooks\/exhaustive-deps\n  const limits = useMemo(() => resolveLimits(props.limits), [limitsKey]);\n  const graph = useMemo(() => normalizeGraph(props.data, limits), [props.data, limits]);\n  const matchIdx = useMemo(() => searchNodes(graph, props.search ?? \"\", { limit: limits.maxSearchResults }), [graph, props.search, limits]);\n  const matches = useMemo(() => (matchIdx.length ? new Set(matchIdx) : null), [matchIdx]);\n  const matchIds = useMemo(() => matchIdx.map((i) => graph.nodes[i].id), [matchIdx, graph]);\n\n  const onActivity = useRef(props.onActivity);\n  onActivity.current = props.onActivity;\n  const emit = useCallback((type: GraphActivity[\"type\"], id: string | null | undefined, source: GraphActivitySource) => {\n    onActivity.current?.({ type, id: id ?? null, source, at: Date.now() });\n  }, []);\n\n  const onSelectedChange = props.onSelectedChange;\n  const onSelected = useCallback(\n    (id: string | null, meta: ChangeMeta) => {\n      onSelectedChange?.(id, meta);\n      emit(\"select\", id, meta.source);\n    },\n    [onSelectedChange, emit],\n  );\n  const onHoveredChange = props.onHoveredChange;\n  const onHovered = useCallback(\n    (id: string | null, meta: ChangeMeta) => {\n      onHoveredChange?.(id, meta);\n      emit(\"hover\", id, meta.source);\n    },\n    [onHoveredChange, emit],\n  );\n  const [selectedId, select] = useControllable<string | null>(props.selected, props.defaultSelected ?? null, onSelected);\n  const [hoveredId, hover] = useControllable<string | null>(props.hovered, null, onHovered);\n  const onFocusedChange = props.onFocusedChange;\n  const onFocused = useCallback(\n    (id: string | null, meta: ChangeMeta) => {\n      onFocusedChange?.(id, meta);\n      emit(\"focus\", id, meta.source);\n    },\n    [onFocusedChange, emit],\n  );\n  const [focusedId, setFocused] = useControllable<string | null>(props.focused, props.defaultFocused ?? null, onFocused);\n\n  const onSearchResults = useRef(props.onSearchResults);\n  onSearchResults.current = props.onSearchResults;\n  useEffect(() => {\n    onSearchResults.current?.(matchIds);\n  }, [matchIds]);\n\n  const reducedMotion = useReducedMotion(props.reducedMotion);\n  const idx = (id: string | null | undefined) => (id != null ? (graph.index.get(id) ?? -1) : -1);\n  const labelFn = props.label;\n  const labelOf = useCallback(\n    (i: number) => {\n      const node = graph.nodes[i];\n      if (!node) return \"\";\n      const raw = labelFn ? labelFn(node, i) : (node.label ?? node.id);\n      return typeof raw === \"string\" ? raw : String(raw ?? \"\");\n    },\n    [graph, labelFn],\n  );\n\n  \/\/ Layers: a partial map in, the full map out.\n  const specs = view.layers ?? DEFAULT_LAYERS;\n  const [innerLayers, setInnerLayers] = useState<Partial<GraphLayerVisibility>>(() => props.defaultLayers ?? {});\n  const layerInput = props.layers !== undefined ? props.layers : innerLayers;\n  const layerStates = useMemo(() => resolveLayers(specs, layerInput), [specs, layerInput]);\n  const layers = useMemo(() => layerMap(layerStates), [layerStates]);\n  const live = useRef({ props, layers, specs });\n  live.current = { props, layers, specs };\n  const setLayer = useCallback(\n    (id: string, visible: boolean, meta: ChangeMeta) => {\n      const { props: p, layers: cur, specs: sp } = live.current;\n      if (!sp.some((s) => s.id === id) || typeof visible !== \"boolean\") return false;\n      const next = { ...cur, [id]: visible };\n      \/\/ Two calls before a render must both land.\n      live.current.layers = next;\n      if (p.layers === undefined) setInnerLayers(next);\n      p.onLayersChange?.(next, meta);\n      emit(\"layer\", id, meta.source);\n      return true;\n    },\n    [emit],\n  );\n\n  const [innerLinks, setInnerLinks] = useState<LinkVisibility | null>(() => props.defaultLinkVisibility ?? null);\n  const linkVisibility: LinkVisibility = props.linkVisibility ?? innerLinks ?? view.linkVisibility ?? \"all\";\n  const setLinkVisibility = useCallback(\n    (mode: LinkVisibility, meta: ChangeMeta) => {\n      if (mode !== \"all\" && mode !== \"focus\" && mode !== \"none\") return;\n      const p = live.current.props;\n      if (p.linkVisibility === undefined) setInnerLinks(mode);\n      p.onLinkVisibilityChange?.(mode, meta);\n      emit(\"links\", mode, meta.source);\n    },\n    [emit],\n  );\n\n  const [innerPaused, setInnerPaused] = useState<boolean>(() => !!props.defaultPaused);\n  const paused = props.paused ?? innerPaused;\n  const setPaused = useCallback(\n    (next: boolean, meta: ChangeMeta) => {\n      const p = live.current.props;\n      if (p.paused === undefined) setInnerPaused(!!next);\n      p.onPausedChange?.(!!next, meta);\n      emit(\"motion\", next ? \"paused\" : \"running\", meta.source);\n    },\n    [emit],\n  );\n\n  return {\n    graph,\n    limits,\n    matches,\n    matchIds,\n    selectedId,\n    hoveredId,\n    selectedIndex: idx(selectedId),\n    hoveredIndex: idx(hoveredId),\n    focusedId,\n    focusedIndex: idx(focusedId),\n    reducedMotion,\n    select,\n    hover,\n    setFocused,\n    emit,\n    labelOf,\n    layerStates,\n    layers,\n    setLayer,\n    linkVisibility,\n    setLinkVisibility,\n    paused,\n    setPaused,\n  };\n}\n","type":"registry:ui","target":"components\/fancy\/graph-view\/model.ts"},{"path":"components\/fancy\/graph-view\/controls.ts","content":"import { createElement, type ComponentType, type ReactElement } from \"react\";\nimport type { GraphLayerState, GraphLayerVisibility, LinkVisibility } from \"..\/lib\/layers\";\nimport type { GraphActivitySource } from \"..\/lib\/types\";\nimport type { GraphModel } from \".\/model\";\n\n\/**\n * What a view-controls component gets from `<GraphView controls={...}>` \/\n * `<GraphView3D controls={...}>`: the view's state as JSON, and callbacks that\n * go through the same controlled paths a click takes (source `\"user\"`).\n * `GraphViewControls` in `@particle-academy\/fancy-graph\/controls` is one;\n * write your own to the same shape.\n *\/\nexport interface GraphControlsProps {\n  selected: string | null;\n  \/** The selected node's label (as text), or null. *\/\n  selectedLabel: string | null;\n  onClearSelection(): void;\n  \/** The view's declared layers, in order. *\/\n  layers: GraphLayerState[];\n  onLayerChange(id: string, visible: boolean): void;\n  linkVisibility: LinkVisibility;\n  onLinkVisibilityChange(mode: LinkVisibility): void;\n  \/** True when the layout moves every frame (the cosmos's orbits): a pause control makes sense. *\/\n  animated: boolean;\n  paused: boolean;\n  onPausedChange(paused: boolean): void;\n}\n\n\/** The handle methods every view shares for these controls. *\/\nexport interface GraphControlsHandle {\n  \/** Clears the selection through the controlled path. *\/\n  clearSelection(opts?: { source?: GraphActivitySource }): void;\n  \/** The declared layers and whether each is drawn. *\/\n  getLayers(): GraphLayerState[];\n  \/** Switches one layer through `onLayersChange`. False for an id the view does not declare. *\/\n  setLayer(id: string, visible: boolean, opts?: { source?: GraphActivitySource }): boolean;\n  setLinkVisibility(mode: LinkVisibility, opts?: { source?: GraphActivitySource }): void;\n  \/** Pauses or resumes an animated layout through `onPausedChange`. *\/\n  setPaused(paused: boolean, opts?: { source?: GraphActivitySource }): void;\n}\n\n\/** The view state these controls add to `getState()`. *\/\nexport interface GraphControlsState {\n  layers: GraphLayerVisibility;\n  linkVisibility: LinkVisibility;\n  paused: boolean;\n  animated: boolean;\n}\n\nexport function controlsHandle(m: () => GraphModel): GraphControlsHandle {\n  return {\n    clearSelection: (opts) => m().select(null, { source: opts?.source ?? \"api\" }),\n    getLayers: () => m().layerStates.map((l) => ({ ...l })),\n    setLayer: (id, visible, opts) => m().setLayer(id, visible, { source: opts?.source ?? \"api\" }),\n    setLinkVisibility: (mode, opts) => m().setLinkVisibility(mode, { source: opts?.source ?? \"api\" }),\n    setPaused: (paused, opts) => m().setPaused(paused, { source: opts?.source ?? \"api\" }),\n  };\n}\n\nexport function controlsState(m: GraphModel, animated: boolean): GraphControlsState {\n  return { layers: { ...m.layers }, linkVisibility: m.linkVisibility, paused: m.paused, animated };\n}\n\n\/** Stable handles for the root element: visible layer ids, the link mode, paused. *\/\nexport function controlsDataset(m: GraphModel): Record<string, string> {\n  return {\n    \"data-fancy-graph-layers\": m.layerStates.filter((l) => l.visible).map((l) => l.id).join(\" \"),\n    \"data-fancy-graph-link-visibility\": m.linkVisibility,\n    \"data-fancy-graph-paused\": String(m.paused),\n  };\n}\n\n\/** Renders the host's controls component, wrapped so only the controls themselves take pointer events. *\/\nexport function renderControls(Controls: ComponentType<GraphControlsProps> | null | false | undefined, m: GraphModel, animated: boolean): ReactElement | null {\n  if (!Controls) return null;\n  const props: GraphControlsProps = {\n    selected: m.selectedId,\n    selectedLabel: m.selectedIndex >= 0 ? m.labelOf(m.selectedIndex) : null,\n    onClearSelection: () => m.select(null, { source: \"user\" }),\n    layers: m.layerStates,\n    onLayerChange: (id, visible) => m.setLayer(id, visible, { source: \"user\" }),\n    linkVisibility: m.linkVisibility,\n    onLinkVisibilityChange: (mode) => m.setLinkVisibility(mode, { source: \"user\" }),\n    animated,\n    paused: m.paused,\n    onPausedChange: (paused) => m.setPaused(paused, { source: \"user\" }),\n  };\n  return createElement(\n    \"div\",\n    { \"data-fancy-graph-controls-root\": \"\", style: { position: \"absolute\", inset: 0, pointerEvents: \"none\" } },\n    createElement(Controls, props),\n  );\n}\n\n\/** True for a layout that moves every frame. *\/\nexport function isAnimatedLayout(layout: unknown): boolean {\n  return typeof layout === \"object\" && layout !== null && !!(layout as { animated?: boolean }).animated;\n}\n","type":"registry:ui","target":"components\/fancy\/graph-view\/controls.ts"},{"path":"components\/fancy\/lib\/camera.ts","content":"import { DEFAULT_LIMITS, type GraphLimits } from \".\/limits\";\nimport type { Vec3 } from \".\/types\";\n\n\/** The 2D view: the world point at the centre of the viewport, and px per world unit. *\/\nexport interface Camera2D {\n  x: number;\n  y: number;\n  zoom: number;\n}\n\n\/** The 3D view: an orbit about `target`. yaw about +y from +z, pitch up from the horizon (radians). *\/\nexport interface Camera3D {\n  target: Vec3;\n  distance: number;\n  yaw: number;\n  pitch: number;\n}\n\nexport function worldToScreen2D(c: Camera2D, w: number, h: number, x: number, y: number): [number, number] {\n  return [(x - c.x) * c.zoom + w \/ 2, (y - c.y) * c.zoom + h \/ 2];\n}\n\nexport function screenToWorld2D(c: Camera2D, w: number, h: number, sx: number, sy: number): [number, number] {\n  return [(sx - w \/ 2) \/ c.zoom + c.x, (sy - h \/ 2) \/ c.zoom + c.y];\n}\n\nexport function clampCamera2D(c: Camera2D, limits: Pick<GraphLimits, \"minZoom\" | \"maxZoom\">): Camera2D {\n  const zoom = Math.min(limits.maxZoom, Math.max(limits.minZoom, Number.isFinite(c.zoom) && c.zoom > 0 ? c.zoom : 1));\n  return { x: Number.isFinite(c.x) ? c.x : 0, y: Number.isFinite(c.y) ? c.y : 0, zoom };\n}\n\n\/** Zooms by `factor` about a screen point, which stays under the cursor. *\/\nexport function zoomAt2D(c: Camera2D, w: number, h: number, sx: number, sy: number, factor: number, limits: Pick<GraphLimits, \"minZoom\" | \"maxZoom\">): Camera2D {\n  const [wx, wy] = screenToWorld2D(c, w, h, sx, sy);\n  const zoom = clampCamera2D({ ...c, zoom: c.zoom * factor }, limits).zoom;\n  return { zoom, x: wx - (sx - w \/ 2) \/ zoom, y: wy - (sy - h \/ 2) \/ zoom };\n}\n\n\/**\n * A camera that fits `indices` (or every node) into the viewport, inside `padding` px.\n * `radii` are the nodes' drawn radii in world units (a node is drawn `radius * zoom`\n * px around its centre); with them every node lies wholly inside the padded view,\n * not only its centre. The zoom never exceeds `fitMaxZoom` (else\n * `DEFAULT_LIMITS.fitMaxZoom`), so a small graph is not blown up to fill the view.\n *\/\nexport function fitCamera2D(\n  positions: Float32Array,\n  indices: ArrayLike<number> | null,\n  w: number,\n  h: number,\n  padding: number,\n  limits: Pick<GraphLimits, \"minZoom\" | \"maxZoom\"> & Partial<Pick<GraphLimits, \"fitMaxZoom\">>,\n  radii?: ArrayLike<number> | null,\n): Camera2D {\n  let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;\n  const count = indices ? indices.length : positions.length \/ 3;\n  for (let k = 0; k < count; k++) {\n    const i = indices ? indices[k] : k;\n    const x = positions[i * 3], y = positions[i * 3 + 1];\n    if (!Number.isFinite(x) || !Number.isFinite(y)) continue;\n    const rr = radii ? radii[i] : 0;\n    const r = typeof rr === \"number\" && Number.isFinite(rr) && rr > 0 ? rr : 0;\n    minX = Math.min(minX, x - r);\n    maxX = Math.max(maxX, x + r);\n    minY = Math.min(minY, y - r);\n    maxY = Math.max(maxY, y + r);\n  }\n  if (!Number.isFinite(minX)) return { x: 0, y: 0, zoom: 1 };\n  const bw = Math.max(1e-6, maxX - minX), bh = Math.max(1e-6, maxY - minY);\n  const single = maxX - minX < 1e-6 && maxY - minY < 1e-6;\n  const zoom = single ? 1 : Math.min((w - padding * 2) \/ bw, (h - padding * 2) \/ bh);\n  const f = limits.fitMaxZoom;\n  const ceiling = typeof f === \"number\" && Number.isFinite(f) && f > 0 ? f : DEFAULT_LIMITS.fitMaxZoom;\n  return clampCamera2D({ x: (minX + maxX) \/ 2, y: (minY + maxY) \/ 2, zoom: Math.min(zoom, ceiling) }, limits);\n}\n\n\/** Interpolates two cameras; zoom moves in log space so a fly feels even. *\/\nexport function lerpCamera2D(a: Camera2D, b: Camera2D, t: number): Camera2D {\n  return {\n    x: a.x + (b.x - a.x) * t,\n    y: a.y + (b.y - a.y) * t,\n    zoom: Math.exp(Math.log(a.zoom) + (Math.log(b.zoom) - Math.log(a.zoom)) * t),\n  };\n}\n\n\/** The eye position for an orbit camera. *\/\nexport function orbitPosition(c: Camera3D): Vec3 {\n  const cp = Math.cos(c.pitch);\n  return [c.target[0] + c.distance * cp * Math.sin(c.yaw), c.target[1] + c.distance * Math.sin(c.pitch), c.target[2] + c.distance * cp * Math.cos(c.yaw)];\n}\n\n\/** The orbit camera for an eye and a target. *\/\nexport function orbitFrom(eye: Vec3, target: Vec3): Camera3D {\n  const dx = eye[0] - target[0], dy = eye[1] - target[1], dz = eye[2] - target[2];\n  const distance = Math.hypot(dx, dy, dz) || 1;\n  return { target: [...target] as Vec3, distance, yaw: Math.atan2(dx, dz), pitch: Math.asin(Math.max(-1, Math.min(1, dy \/ distance))) };\n}\n","type":"registry:lib","target":"components\/fancy\/lib\/camera.ts"},{"path":"components\/fancy\/lib\/layout\/contract.ts","content":"import type { GraphLimits } from \"..\/limits\";\nimport type { GraphCluster, IndexedGraph } from \"..\/types\";\n\nexport interface LayoutEnv {\n  dimensions: 2 | 3;\n  limits: GraphLimits;\n  \/** True when the person asked for reduced motion. Physics settles before first paint; animated time is frozen. *\/\n  reducedMotion: boolean;\n}\n\nexport interface LayoutFrame {\n  \/** Seconds of animated time, frozen while paused or under reduced motion. *\/\n  time: number;\n  \/** Seconds since the previous step. *\/\n  dt: number;\n}\n\n\/**\n * A layout that runs over time. `init` writes starting positions; `step` is\n * called once per frame and writes new ones, returning `true` while it is still\n * moving. Positions are a flat `Float32Array`, 3 floats per node (z is 0 in 2D).\n *\/\nexport interface GraphLayoutStepper {\n  name?: string;\n  \/** Positions change every frame forever (orbits, timelines). The view never idles. *\/\n  animated?: boolean;\n  init(graph: IndexedGraph, positions: Float32Array, env: LayoutEnv): void;\n  step?(positions: Float32Array, frame: LayoutFrame): boolean | void;\n  \/** Read once after `init`: true when there is nothing left to step (a wrapper whose work already finished). *\/\n  isSettled?(): boolean;\n  \/** Clusters this layout knows about (galaxies, communities), in world space. *\/\n  clusters?(positions: Float32Array): GraphCluster[];\n  \/** Anything the layout wants its renderers to read: star\/planet kinds, orbit planes. *\/\n  meta?: unknown;\n  dispose?(): void;\n}\n\n\/** A layout that places every node once. *\/\nexport type GraphLayoutFunction = (graph: IndexedGraph, positions: Float32Array, env: LayoutEnv) => void;\n\nexport type GraphLayout = GraphLayoutStepper | GraphLayoutFunction;\n\nexport interface LayoutRunner {\n  readonly positions: Float32Array;\n  readonly settled: boolean;\n  readonly animated: boolean;\n  readonly meta: unknown;\n  readonly time: number;\n  \/** Advances one frame. Returns true when positions changed. *\/\n  tick(dt: number): boolean;\n  clusters(): GraphCluster[] | null;\n  setPaused(paused: boolean): void;\n  dispose(): void;\n}\n\n\/**\n * Drives any layout through the contract, so the view treats a function, a\n * physics stepper, an orbiting cosmos and an off-thread worker the same way.\n *\/\nexport function createLayoutRunner(layout: GraphLayout, graph: IndexedGraph, env: LayoutEnv): LayoutRunner {\n  const n = graph.nodes.length;\n  const positions = new Float32Array(n * 3);\n  const stepper: GraphLayoutStepper = typeof layout === \"function\" ? { init: (g, p, e) => layout(g, p, e) } : layout;\n  const fixed: number[] = [];\n  graph.nodes.forEach((node, i) => {\n    if (node.fixed && Number.isFinite(node.x) && Number.isFinite(node.y)) fixed.push(i);\n  });\n  const pin = () => {\n    for (const i of fixed) {\n      const node = graph.nodes[i];\n      positions[i * 3] = node.x!;\n      positions[i * 3 + 1] = node.y!;\n      positions[i * 3 + 2] = env.dimensions === 3 && Number.isFinite(node.z) ? node.z! : 0;\n    }\n  };\n\n  stepper.init(graph, positions, env);\n  pin();\n  const animated = !!stepper.animated;\n  let settled = !stepper.step || stepper.isSettled?.() === true;\n  let paused = false;\n  let time = 0;\n\n  if (!settled && env.reducedMotion) {\n    if (animated) {\n      stepper.step!(positions, { time: 0, dt: 0 });\n      pin();\n    } else {\n      for (let k = 0; k < env.limits.maxSettleTicks; k++) {\n        const moving = stepper.step!(positions, { time: 0, dt: 1 \/ 60 });\n        if (moving === false || moving === undefined) {\n          settled = true;\n          break;\n        }\n      }\n      pin();\n      settled = true;\n    }\n  }\n\n  return {\n    positions,\n    get settled() {\n      return settled && !animated;\n    },\n    animated,\n    get meta() {\n      return stepper.meta;\n    },\n    get time() {\n      return time;\n    },\n    tick(dt) {\n      if (!stepper.step) return false;\n      if (animated) {\n        if (env.reducedMotion || paused) return false;\n        time += dt;\n        stepper.step(positions, { time, dt });\n        pin();\n        return true;\n      }\n      if (settled || paused) return false;\n      const moving = stepper.step(positions, { time, dt });\n      time += dt;\n      pin();\n      if (moving === false || moving === undefined) settled = true;\n      return true;\n    },\n    clusters() {\n      return stepper.clusters ? stepper.clusters(positions) : null;\n    },\n    setPaused(p) {\n      paused = p;\n    },\n    dispose() {\n      stepper.dispose?.();\n    },\n  };\n}\n","type":"registry:lib","target":"components\/fancy\/lib\/layout\/contract.ts"},{"path":"components\/fancy\/lib\/render2d\/engine.ts","content":"import { clampCamera2D, fitCamera2D, lerpCamera2D, zoomAt2D, type Camera2D } from \"..\/camera\";\nimport { groupClusters } from \"..\/clusters\";\nimport { colorFor } from \"..\/color\";\nimport { computeLinkStates, computeNodeStates, focusOf, hasHighlightRing, LINK_ACTIVE, LINK_DIMMED, NODE_ACTIVE, NODE_DIMMED, pickScreen } from \"..\/interaction\";\nimport { effectiveLinkVisibility, isLayerVisible } from \"..\/layers\";\nimport { LabelLayer, labelCandidates, placeLabels, type ClusterLabel, type PlacedLabel } from \"..\/labels\";\nimport { createLayoutRunner, type GraphLayout, type LayoutRunner } from \"..\/layout\/contract\";\nimport { truncateLabel, type GraphLimits } from \"..\/limits\";\nimport type { GraphCluster, IndexedGraph } from \"..\/types\";\nimport type { GraphRenderers2D } from \".\/types\";\n\nexport type ClusterSource = \"group\" | GraphCluster[] | ((graph: IndexedGraph, positions: Float32Array) => GraphCluster[]);\n\nexport interface Engine2DOptions {\n  renderers: GraphRenderers2D;\n  clusters?: ClusterSource;\n  clusterLabel?: (cluster: GraphCluster) => string | null;\n  nodeColor?: (index: number) => string;\n  nodeSize?: (index: number) => number;\n  labelOf: (index: number) => string;\n  linkVisibility: \"all\" | \"focus\" | \"none\";\n  \/** Layer visibility by id (`links`, `labels`, `clusters`, `background`); a missing id is visible. *\/\n  layers?: Partial<Record<string, boolean>>;\n  background?: string;\n  linkColor: string;\n  \/** Focus ring colour. Defaults to --fancy-focus, else blue. *\/\n  focusColor: string;\n  paused: boolean;\n}\n\nexport interface Engine2DCallbacks {\n  onSelect(index: number): void;\n  onHover(index: number): void;\n  onCamera(camera: Camera2D): void;\n  onEscape(): void;\n}\n\nconst MIN_DT = 1 \/ 240;\nconst MAX_DT = 1 \/ 20;\nconst DRAG_PX = 4;\n\n\/**\n * The 2D renderer: a canvas, a label layer, the frame loop and the input\n * handling. React owns the state; this owns the pixels. No three, no WebGL.\n *\/\nexport class CanvasEngine {\n  private ctx: CanvasRenderingContext2D | null;\n  private labels: LabelLayer;\n  private graph: IndexedGraph | null = null;\n  private runner: LayoutRunner | null = null;\n  private screen = new Float32Array(0);\n  private states = new Uint8Array(0);\n  private linkStates = new Uint8Array(0);\n  private sizes = new Float32Array(0);\n  private colors: string[] = [];\n  private camera: Camera2D = { x: 0, y: 0, zoom: 1 };\n  private goal: Camera2D | null = null;\n  private follow = -1;\n  private selected = -1;\n  private hovered = -1;\n  private focused = -1;\n  private neighborhood = false;\n  private matches: Set<number> | null = null;\n  private userMoved = false;\n  private fitPending = true;\n  private raf = 0;\n  private last = 0;\n  private dirty = true;\n  private width = 300;\n  private height = 150;\n  private dpr = 1;\n  private destroyed = false;\n  private pointers = new Map<number, { x: number; y: number }>();\n  private down: { x: number; y: number; dragging: boolean; cam: Camera2D } | null = null;\n  private pinch: { dist: number; cam: Camera2D; mx: number; my: number } | null = null;\n  private clusterCache: GraphCluster[] = [];\n  \/** Clusters are recomputed only when positions moved or their source changed, never on a settled frame. *\/\n  private clustersStale = true;\n\n  constructor(\n    private readonly canvas: HTMLCanvasElement,\n    labelRoot: HTMLElement,\n    private limits: GraphLimits,\n    private opts: Engine2DOptions,\n    private readonly cb: Engine2DCallbacks,\n    private reducedMotion: boolean,\n  ) {\n    this.ctx = canvas.getContext(\"2d\");\n    this.labels = new LabelLayer(labelRoot, { pool: limits.maxLabels + limits.maxForcedLabels });\n    canvas.addEventListener(\"pointerdown\", this.onDown);\n    canvas.addEventListener(\"pointermove\", this.onMove);\n    canvas.addEventListener(\"pointerup\", this.onUp);\n    canvas.addEventListener(\"pointercancel\", this.onCancel);\n    canvas.addEventListener(\"pointerleave\", this.onLeave);\n    canvas.addEventListener(\"wheel\", this.onWheel, { passive: false });\n    canvas.addEventListener(\"keydown\", this.onKey);\n  }\n\n  \/\/ ---------------------------------------------------------------- state in\n\n  setGraph(graph: IndexedGraph, layout: GraphLayout) {\n    this.clustersStale = true;\n    this.runner?.dispose();\n    this.graph = graph;\n    const n = graph.nodes.length;\n    this.runner = createLayoutRunner(layout, graph, { dimensions: 2, limits: this.limits, reducedMotion: this.reducedMotion });\n    this.runner.setPaused(this.opts.paused);\n    this.screen = new Float32Array(n * 4);\n    this.states = new Uint8Array(n);\n    this.linkStates = new Uint8Array(graph.links.length);\n    this.refreshStyle();\n    if (!this.userMoved) this.fitPending = true;\n    this.invalidate();\n  }\n\n  setOptions(opts: Engine2DOptions) {\n    if (opts.clusters !== this.opts.clusters) this.clustersStale = true;\n    this.opts = opts;\n    this.runner?.setPaused(opts.paused);\n    this.refreshStyle();\n    this.invalidate();\n  }\n\n  setLimits(limits: GraphLimits) {\n    if (limits.maxLabels + limits.maxForcedLabels !== this.limits.maxLabels + this.limits.maxForcedLabels) {\n      const root = this.canvas.parentElement?.querySelector<HTMLElement>(\"[data-fancy-graph-labels]\");\n      this.labels.dispose();\n      if (root) this.labels = new LabelLayer(root, { pool: limits.maxLabels + limits.maxForcedLabels });\n    }\n    this.limits = limits;\n    this.invalidate();\n  }\n\n  setReducedMotion(r: boolean) {\n    this.reducedMotion = r;\n  }\n\n  setSize(width: number, height: number, dpr: number) {\n    const ratio = Math.min(this.limits.maxPixelRatio, Math.max(1, dpr || 1));\n    if (width === this.width && height === this.height && ratio === this.dpr) return;\n    this.width = Math.max(1, width);\n    this.height = Math.max(1, height);\n    this.dpr = ratio;\n    this.canvas.width = Math.round(this.width * ratio);\n    this.canvas.height = Math.round(this.height * ratio);\n    if (!this.userMoved) this.fitPending = true;\n    this.invalidate();\n  }\n\n  setInteraction(selected: number, hovered: number, matches: Set<number> | null, focused = -1, neighborhood = false) {\n    \/\/ Clearing the selection lets go of the node the camera was following because it was selected.\n    if (selected < 0 && this.selected >= 0 && this.follow === this.selected) this.follow = -1;\n    this.selected = selected;\n    this.hovered = hovered;\n    this.matches = matches;\n    this.focused = focused;\n    this.neighborhood = neighborhood;\n    this.invalidate();\n  }\n\n  \/** Keep a node in view: fly to it at the current zoom, then follow it. *\/\n  setFocus(index: number) {\n    if (index >= 0) {\n      this.flyToIndex(index, this.camera.zoom, this.reducedMotion);\n      this.follow = index;\n    } else this.follow = -1;\n  }\n\n  \/** The projected screen buffer of the last frame: x, y, radius, visible, per node. *\/\n  getScreen(): Float32Array {\n    return this.screen;\n  }\n\n  \/** Moves the camera by screen px (positive x right, positive y down). Releases any follow, so it never fights one. *\/\n  pan(dx: number, dy: number) {\n    if (!Number.isFinite(dx) || !Number.isFinite(dy)) return;\n    this.goal = null;\n    this.follow = -1;\n    this.userMoved = true;\n    this.fitPending = false;\n    this.camera = clampCamera2D({ ...this.camera, x: this.camera.x + dx \/ this.camera.zoom, y: this.camera.y + dy \/ this.camera.zoom }, this.limits);\n    this.cb.onCamera(this.getCamera());\n    this.invalidate();\n  }\n\n  \/** Zooms about the viewport centre (factor greater than 1 zooms in). A follow continues. *\/\n  zoomBy(factor: number) {\n    if (!Number.isFinite(factor) || factor <= 0) return;\n    this.goal = null;\n    this.userMoved = true;\n    this.fitPending = false;\n    this.camera = zoomAt2D(this.camera, this.width, this.height, this.width \/ 2, this.height \/ 2, factor, this.limits);\n    this.cb.onCamera(this.getCamera());\n    this.invalidate();\n  }\n\n  \/\/ ----------------------------------------------------------------- camera\n\n  getCamera(): Camera2D {\n    return { ...this.camera };\n  }\n\n  setCamera(cam: Camera2D, instant = this.reducedMotion) {\n    const next = clampCamera2D(cam, this.limits);\n    this.userMoved = true;\n    this.fitPending = false;\n    if (instant) {\n      this.camera = next;\n      this.goal = null;\n      this.cb.onCamera(this.getCamera());\n    } else this.goal = next;\n    this.invalidate();\n  }\n\n  flyToIndex(index: number, zoom?: number, instant = this.reducedMotion): boolean {\n    const p = this.runner?.positions;\n    if (!p || index < 0 || index * 3 >= p.length) return false;\n    this.setCamera({ x: p[index * 3], y: p[index * 3 + 1], zoom: zoom ?? Math.max(this.camera.zoom, 1) }, instant);\n    return true;\n  }\n\n  fit(indices: number[] | null, instant = this.reducedMotion) {\n    const p = this.runner?.positions;\n    if (!p) return;\n    const cam = this.fitCamera(p, indices);\n    this.setCamera(cam, instant);\n    if (!indices) this.userMoved = false;\n  }\n\n  setFollow(index: number) {\n    this.follow = index;\n    this.invalidate();\n  }\n\n  screenPosition(index: number): { x: number; y: number; radius: number } | null {\n    if (index < 0 || index * 4 >= this.screen.length) return null;\n    return { x: this.screen[index * 4], y: this.screen[index * 4 + 1], radius: this.screen[index * 4 + 2] };\n  }\n\n  pick(x: number, y: number): number {\n    return pickScreen(this.screen, x, y, { minReach: this.limits.pickRadius, mode: \"nearest\" });\n  }\n\n  getClusters(): GraphCluster[] {\n    return this.clusterCache;\n  }\n\n  \/** A node's world position in the current layout. *\/\n  positionOf(index: number): [number, number, number] | null {\n    const p = this.runner?.positions;\n    if (!p || index < 0 || index * 3 >= p.length) return null;\n    return [p[index * 3], p[index * 3 + 1], p[index * 3 + 2]];\n  }\n\n  \/\/ ------------------------------------------------------------------ frame\n\n  invalidate() {\n    this.dirty = true;\n    this.schedule();\n  }\n\n  private schedule() {\n    if (this.destroyed || this.raf || typeof requestAnimationFrame !== \"function\") return;\n    this.raf = requestAnimationFrame((t) => {\n      this.raf = 0;\n      const dt = this.last ? (t - this.last) \/ 1000 : 1 \/ 60;\n      this.last = t;\n      this.renderFrame(dt);\n      if (this.needsFrame()) this.schedule();\n      else this.last = 0;\n    });\n  }\n\n  private needsFrame(): boolean {\n    const r = this.runner;\n    return this.dirty || !!this.goal || (!!r && (!r.settled || (r.animated && !this.opts.paused && !this.reducedMotion))) || this.follow >= 0;\n  }\n\n  \/** Renders one frame now. Returns how long it took (ms). Tests and benchmarks drive this directly. *\/\n  renderFrame(dtIn = 1 \/ 60): { ms: number } {\n    const t0 = typeof performance !== \"undefined\" ? performance.now() : Date.now();\n    this.dirty = false;\n    const g = this.graph;\n    const r = this.runner;\n    if (!g || !r) return { ms: 0 };\n    const dt = Math.min(MAX_DT, Math.max(MIN_DT, dtIn));\n    const wasSettled = r.settled;\n    if (r.tick(dt)) this.clustersStale = true;\n    const p = r.positions;\n    const n = g.nodes.length;\n    \/\/ Sizes first: a fit frames each node's drawn radius, so it needs them.\n    this.refreshSizes();\n\n    if (this.fitPending) {\n      this.fitPending = false;\n      this.camera = this.fitAll(p);\n    } else if (!wasSettled && r.settled && !this.userMoved) {\n      \/\/ The layout just came to rest: frame it, unless the person already moved the view.\n      const cam = this.fitAll(p);\n      if (this.reducedMotion) this.camera = cam;\n      else this.goal = cam;\n    }\n\n    if (this.goal) {\n      const ease = this.reducedMotion ? 1 : 1 - Math.exp(-dt * 6);\n      this.camera = lerpCamera2D(this.camera, this.goal, ease);\n      const g2 = this.goal;\n      if (ease >= 1 || (Math.abs(g2.x - this.camera.x) * g2.zoom < 0.5 && Math.abs(g2.y - this.camera.y) * g2.zoom < 0.5 && Math.abs(Math.log(g2.zoom \/ this.camera.zoom)) < 0.002)) {\n        this.camera = g2;\n        this.goal = null;\n        this.cb.onCamera(this.getCamera());\n      }\n    }\n    if (this.follow >= 0 && this.follow < n && !this.goal) {\n      this.camera = { ...this.camera, x: p[this.follow * 3], y: p[this.follow * 3 + 1] };\n    }\n\n    const W = this.width, H = this.height, cam = this.camera;\n    for (let i = 0; i < n; i++) {\n      const x = p[i * 3], y = p[i * 3 + 1];\n      this.screen[i * 4] = (x - cam.x) * cam.zoom + W \/ 2;\n      this.screen[i * 4 + 1] = (y - cam.y) * cam.zoom + H \/ 2;\n      this.screen[i * 4 + 2] = Math.max(1.5, this.sizes[i] * cam.zoom);\n      this.screen[i * 4 + 3] = Number.isFinite(x) && Number.isFinite(y) ? 1 : 0;\n    }\n    const focus = { selected: this.selected, hovered: this.hovered, matches: this.matches, focused: this.focused, neighborhood: this.neighborhood };\n    computeNodeStates(g, focus, this.states);\n    computeLinkStates(g, focus, this.linkStates);\n    if (this.clustersStale) {\n      this.clusterCache = this.resolveClusters(g, p);\n      this.clustersStale = false;\n    }\n\n    const ctx = this.ctx;\n    if (ctx) this.paint(ctx, g);\n    this.paintLabels(g);\n    const t1 = typeof performance !== \"undefined\" ? performance.now() : Date.now();\n    return { ms: t1 - t0 };\n  }\n\n  \/** A cluster's own colour, else its members' (so it follows the theme), else a palette guess. *\/\n  private clusterColor(c: GraphCluster): string {\n    return c.color ?? (c.members[0] !== undefined ? this.colors[c.members[0]] : undefined) ?? colorFor(c.id);\n  }\n\n  \/** Each node's radius in world units: its resolved size (the nodeSize option, else its own, else by degree). *\/\n  private refreshSizes() {\n    const g = this.graph;\n    if (!g) return;\n    const n = g.nodes.length;\n    if (this.sizes.length !== n) this.sizes = new Float32Array(n);\n    for (let i = 0; i < n; i++) {\n      const s = this.opts.nodeSize ? this.opts.nodeSize(i) : g.nodes[i].size;\n      this.sizes[i] = typeof s === \"number\" && Number.isFinite(s) && s > 0 ? s : 3 + Math.min(9, Math.sqrt(g.degree[i]) * 1.5);\n    }\n  }\n\n  \/** A fit of `indices` (or everything) that frames each node's drawn radius. *\/\n  private fitCamera(p: Float32Array, indices: number[] | null): Camera2D {\n    this.refreshSizes();\n    return fitCamera2D(p, indices, this.width, this.height, Math.min(60, Math.min(this.width, this.height) * 0.1), this.limits, this.sizes);\n  }\n\n  private fitAll(p: Float32Array): Camera2D {\n    return this.fitCamera(p, null);\n  }\n\n  private resolveClusters(g: IndexedGraph, p: Float32Array): GraphCluster[] {\n    const src = this.opts.clusters;\n    if (src === \"group\") return groupClusters(g, p);\n    if (typeof src === \"function\") return src(g, p);\n    if (Array.isArray(src)) return src;\n    return this.runner?.clusters() ?? [];\n  }\n\n  private refreshStyle() {\n    const g = this.graph;\n    if (!g) return;\n    this.colors = g.nodes.map((node, i) => (this.opts.nodeColor ? this.opts.nodeColor(i) : (node.color ?? colorFor(node.group))));\n  }\n\n  private paint(ctx: CanvasRenderingContext2D, g: IndexedGraph) {\n    const { width: W, height: H, dpr, camera: cam } = this;\n    const meta = this.runner?.meta;\n    const time = this.runner?.time ?? 0;\n    const R = this.opts.renderers;\n    ctx.setTransform(dpr, 0, 0, dpr, 0, 0);\n    ctx.clearRect(0, 0, W, H);\n    if (this.opts.background) {\n      ctx.fillStyle = this.opts.background;\n      ctx.fillRect(0, 0, W, H);\n    }\n    if (isLayerVisible(this.opts.layers, \"background\")) R.background?.(ctx, { width: W, height: H, camera: { ...cam }, time, pixelRatio: dpr, meta });\n\n    for (const c of isLayerVisible(this.opts.layers, \"clusters\") ? this.clusterCache : []) {\n      const x = (c.center[0] - cam.x) * cam.zoom + W \/ 2;\n      const y = (c.center[1] - cam.y) * cam.zoom + H \/ 2;\n      const radius = c.radius * cam.zoom;\n      if (R.cluster) R.cluster(ctx, { cluster: c, x, y, radius, zoom: cam.zoom, meta });\n      else {\n        const colour = this.clusterColor(c);\n        ctx.beginPath();\n        ctx.arc(x, y, radius, 0, Math.PI * 2);\n        ctx.globalAlpha = 0.07;\n        ctx.fillStyle = colour;\n        ctx.fill();\n        ctx.globalAlpha = 0.25;\n        ctx.strokeStyle = colour;\n        ctx.lineWidth = 1;\n        ctx.stroke();\n        ctx.globalAlpha = 1;\n      }\n    }\n\n    const vis = effectiveLinkVisibility(this.opts.linkVisibility, isLayerVisible(this.opts.layers, \"links\"));\n    const anyFocus = focusOf({ selected: this.selected, hovered: this.hovered, focused: this.focused, neighborhood: this.neighborhood }) >= 0 || !!this.matches;\n    if (vis !== \"none\") {\n      const s = this.screen;\n      if (R.link) {\n        for (const l of g.links) {\n          const st = this.linkStates[l.index];\n          if (vis === \"focus\" && anyFocus && st !== LINK_ACTIVE) continue;\n          R.link(ctx, { index: l.index, link: l, ax: s[l.a * 4], ay: s[l.a * 4 + 1], bx: s[l.b * 4], by: s[l.b * 4 + 1], state: st as 0 | 1 | 2, zoom: cam.zoom, meta });\n        }\n      } else {\n        \/\/ Batched: one path per state, so 6,000 links cost three strokes.\n        ctx.strokeStyle = this.opts.linkColor;\n        for (const [state, alpha, width] of [[0, 0.32, 1], [LINK_DIMMED, 0.06, 1], [LINK_ACTIVE, 0.9, 1.6]] as const) {\n          if (vis === \"focus\" && anyFocus && state !== LINK_ACTIVE) continue;\n          ctx.beginPath();\n          let any = false;\n          for (const l of g.links) {\n            if (this.linkStates[l.index] !== state) continue;\n            ctx.moveTo(s[l.a * 4], s[l.a * 4 + 1]);\n            ctx.lineTo(s[l.b * 4], s[l.b * 4 + 1]);\n            any = true;\n          }\n          if (!any) continue;\n          ctx.globalAlpha = alpha;\n          ctx.lineWidth = width;\n          ctx.stroke();\n        }\n        ctx.globalAlpha = 1;\n      }\n    }\n\n    const s = this.screen;\n    const n = g.nodes.length;\n    const time2 = time;\n    for (let i = 0; i < n; i++) {\n      const x = s[i * 4], y = s[i * 4 + 1], r = s[i * 4 + 2];\n      if (x < -r || y < -r || x > W + r || y > H + r || s[i * 4 + 3] <= 0) continue;\n      const state = this.states[i] as 0 | 1 | 2 | 3;\n      if (R.node) {\n        R.node(ctx, { index: i, node: g.nodes[i], x, y, radius: r, color: this.colors[i], state, selected: i === this.selected, hovered: i === this.hovered, focused: i === this.focused, zoom: cam.zoom, time: time2, meta });\n        continue;\n      }\n      ctx.globalAlpha = state === NODE_DIMMED ? 0.18 : 1;\n      ctx.fillStyle = this.colors[i];\n      ctx.beginPath();\n      ctx.arc(x, y, r, 0, Math.PI * 2);\n      ctx.fill();\n      if (state === NODE_ACTIVE && hasHighlightRing(i, { selected: this.selected, hovered: this.hovered, matches: this.matches })) {\n        ctx.globalAlpha = 1;\n        ctx.strokeStyle = this.opts.linkColor;\n        ctx.lineWidth = i === this.selected ? 2.5 : 1.5;\n        ctx.beginPath();\n        ctx.arc(x, y, r + 3, 0, Math.PI * 2);\n        ctx.stroke();\n      }\n      if (i === this.focused) {\n        \/\/ Dashed, in the focus colour, and outside the selection ring: never mistaken for it.\n        ctx.globalAlpha = 1;\n        ctx.strokeStyle = this.opts.focusColor;\n        ctx.lineWidth = 2;\n        ctx.setLineDash([4, 3]);\n        ctx.beginPath();\n        ctx.arc(x, y, r + 7, 0, Math.PI * 2);\n        ctx.stroke();\n        ctx.setLineDash([]);\n      }\n    }\n    ctx.globalAlpha = 1;\n  }\n\n  private paintLabels(g: IndexedGraph) {\n    const W = this.width, H = this.height;\n    const max = this.limits.maxLabelLength;\n    const cands = labelCandidates({\n      screen: this.screen,\n      states: this.states,\n      selected: this.selected,\n      hovered: this.hovered,\n      matches: this.matches,\n      width: W,\n      height: H,\n      labelMinPx: this.limits.labelMinPx * 2.5,\n      text: (i) => truncateLabel(this.opts.labelOf(i), max),\n      focused: this.focused,\n      focusNeighbors: this.focused >= 0 ? g.neighbors[this.focused] : undefined,\n      cullOthers: this.neighborhood,\n    });\n    const placed: PlacedLabel[] = placeLabels(cands, { maxLabels: this.limits.maxLabels, maxForced: this.limits.maxForcedLabels, width: W, height: H });\n    for (const l of placed) {\n      l.id = g.nodes[l.index].id;\n      const st = this.states[l.index];\n      l.state = st === NODE_ACTIVE ? \"active\" : st === 2 ? \"neighbor\" : \"normal\";\n    }\n    this.labels.render(isLayerVisible(this.opts.layers, \"labels\") ? placed : []);\n    const cl: ClusterLabel[] = [];\n    const cam = this.camera;\n    for (const c of isLayerVisible(this.opts.layers, \"clusters\") ? this.clusterCache : []) {\n      const text = this.opts.clusterLabel ? this.opts.clusterLabel(c) : (c.label ?? null);\n      if (!text) continue;\n      const radius = c.radius * cam.zoom;\n      if (radius < 12 || radius > Math.min(W, H) * 0.6) continue;\n      \/\/ Kept on screen: a hull reaching past the top edge still shows its name.\n      const y = Math.max(18, (c.center[1] - cam.y) * cam.zoom + H \/ 2 - radius - 4);\n      cl.push({ id: c.id, text: truncateLabel(text, max), x: (c.center[0] - cam.x) * cam.zoom + W \/ 2, y, color: this.clusterColor(c) });\n    }\n    this.labels.renderClusters(cl);\n  }\n\n  \/\/ ------------------------------------------------------------------ input\n\n  private local(e: { clientX: number; clientY: number }) {\n    const r = this.canvas.getBoundingClientRect();\n    return { x: e.clientX - r.left, y: e.clientY - r.top };\n  }\n\n  private onDown = (e: PointerEvent) => {\n    const p = this.local(e);\n    this.pointers.set(e.pointerId ?? 0, p);\n    try {\n      this.canvas.setPointerCapture?.(e.pointerId);\n    } catch {\n      \/* not capturable (synthetic event) *\/\n    }\n    if (this.pointers.size === 2) {\n      const [a, b] = [...this.pointers.values()];\n      this.pinch = { dist: Math.hypot(a.x - b.x, a.y - b.y) || 1, cam: { ...this.camera }, mx: (a.x + b.x) \/ 2, my: (a.y + b.y) \/ 2 };\n      this.down = null;\n      return;\n    }\n    this.down = { x: p.x, y: p.y, dragging: false, cam: { ...this.camera } };\n  };\n\n  private onMove = (e: PointerEvent) => {\n    const p = this.local(e);\n    if (this.pointers.has(e.pointerId ?? 0)) this.pointers.set(e.pointerId ?? 0, p);\n    if (this.pinch && this.pointers.size === 2) {\n      const [a, b] = [...this.pointers.values()];\n      const d = Math.hypot(a.x - b.x, a.y - b.y) || 1;\n      const next = zoomAt2D(this.pinch.cam, this.width, this.height, this.pinch.mx, this.pinch.my, d \/ this.pinch.dist, this.limits);\n      this.camera = next;\n      this.goal = null;\n      this.follow = -1;\n      this.userMoved = true;\n      this.invalidate();\n      return;\n    }\n    if (this.down) {\n      const dx = p.x - this.down.x, dy = p.y - this.down.y;\n      if (!this.down.dragging && Math.abs(dx) + Math.abs(dy) >= DRAG_PX) this.down.dragging = true;\n      if (this.down.dragging) {\n        this.goal = null;\n        this.follow = -1;\n        this.userMoved = true;\n        this.camera = { ...this.down.cam, x: this.down.cam.x - dx \/ this.camera.zoom, y: this.down.cam.y - dy \/ this.camera.zoom };\n        this.canvas.style.cursor = \"grabbing\";\n        this.invalidate();\n      }\n      return;\n    }\n    if (e.pointerType && e.pointerType !== \"mouse\") return;\n    const h = this.pick(p.x, p.y);\n    if (h !== this.hovered) {\n      this.canvas.style.cursor = h >= 0 ? \"pointer\" : \"grab\";\n      this.cb.onHover(h);\n    }\n  };\n\n  private onUp = (e: PointerEvent) => {\n    this.pointers.delete(e.pointerId ?? 0);\n    if (this.pinch) {\n      if (this.pointers.size < 2) {\n        this.pinch = null;\n        this.cb.onCamera(this.getCamera());\n      }\n      return;\n    }\n    const start = this.down;\n    this.down = null;\n    this.canvas.style.cursor = this.hovered >= 0 ? \"pointer\" : \"grab\";\n    if (!start) return;\n    if (start.dragging) {\n      this.cb.onCamera(this.getCamera());\n      return;\n    }\n    if ((e.button ?? 0) !== 0) return;\n    const p = this.local(e);\n    this.cb.onSelect(this.pick(p.x, p.y));\n  };\n\n  private onCancel = (e: PointerEvent) => {\n    this.pointers.delete(e.pointerId ?? 0);\n    this.down = null;\n    this.pinch = null;\n  };\n\n  private onLeave = (e: PointerEvent) => {\n    if (e.pointerType && e.pointerType !== \"mouse\") return;\n    if (this.hovered >= 0 && !this.down) this.cb.onHover(-1);\n  };\n\n  private onWheel = (e: WheelEvent) => {\n    e.preventDefault();\n    const p = this.local(e);\n    const unit = e.deltaMode === 1 ? 16 : e.deltaMode === 2 ? 400 : 1;\n    this.camera = zoomAt2D(this.camera, this.width, this.height, p.x, p.y, Math.exp(-e.deltaY * unit * 0.0015), this.limits);\n    this.goal = null;\n    this.follow = -1;\n    this.userMoved = true;\n    this.fitPending = false;\n    this.cb.onCamera(this.getCamera());\n    this.invalidate();\n  };\n\n  private onKey = (e: KeyboardEvent) => {\n    const k = e.key;\n    const step = 60 \/ this.camera.zoom;\n    let cam: Camera2D | null = null;\n    if (k === \"Escape\") {\n      this.cb.onEscape();\n    } else if (k === \"+\" || k === \"=\") cam = zoomAt2D(this.camera, this.width, this.height, this.width \/ 2, this.height \/ 2, 1.2, this.limits);\n    else if (k === \"-\" || k === \"_\") cam = zoomAt2D(this.camera, this.width, this.height, this.width \/ 2, this.height \/ 2, 1 \/ 1.2, this.limits);\n    else if (k === \"ArrowLeft\") cam = { ...this.camera, x: this.camera.x - step };\n    else if (k === \"ArrowRight\") cam = { ...this.camera, x: this.camera.x + step };\n    else if (k === \"ArrowUp\") cam = { ...this.camera, y: this.camera.y - step };\n    else if (k === \"ArrowDown\") cam = { ...this.camera, y: this.camera.y + step };\n    else if (k === \"0\") {\n      this.fit(null);\n      e.preventDefault();\n      return;\n    } else return;\n    e.preventDefault();\n    if (cam) {\n      this.follow = -1;\n      this.goal = null;\n      this.userMoved = true;\n      this.camera = cam;\n      this.cb.onCamera(this.getCamera());\n      this.invalidate();\n    }\n  };\n\n  destroy() {\n    this.destroyed = true;\n    if (this.raf && typeof cancelAnimationFrame === \"function\") cancelAnimationFrame(this.raf);\n    this.raf = 0;\n    this.runner?.dispose();\n    this.labels.dispose();\n    const c = this.canvas;\n    c.removeEventListener(\"pointerdown\", this.onDown);\n    c.removeEventListener(\"pointermove\", this.onMove);\n    c.removeEventListener(\"pointerup\", this.onUp);\n    c.removeEventListener(\"pointercancel\", this.onCancel);\n    c.removeEventListener(\"pointerleave\", this.onLeave);\n    c.removeEventListener(\"wheel\", this.onWheel);\n    c.removeEventListener(\"keydown\", this.onKey);\n  }\n}\n","type":"registry:lib","target":"components\/fancy\/lib\/render2d\/engine.ts"},{"path":"components\/fancy\/lib\/render2d\/types.ts","content":"import type { Camera2D } from \"..\/camera\";\nimport type { NodeState, LinkState } from \"..\/interaction\";\nimport type { GraphCluster, GraphNode, IndexedLink } from \"..\/types\";\n\n\/** Everything a 2D node renderer needs. Coordinates are CSS px on the canvas. *\/\nexport interface NodeDraw2D {\n  index: number;\n  node: GraphNode;\n  x: number;\n  y: number;\n  \/** Projected radius, px. *\/\n  radius: number;\n  color: string;\n  state: NodeState;\n  selected: boolean;\n  hovered: boolean;\n  \/** The keyboard \/ gamepad focus. The default look draws a dashed ring. *\/\n  focused: boolean;\n  zoom: number;\n  time: number;\n  \/** Whatever the layout exposed as `meta`. *\/\n  meta: unknown;\n}\n\nexport interface LinkDraw2D {\n  index: number;\n  link: IndexedLink;\n  ax: number;\n  ay: number;\n  bx: number;\n  by: number;\n  state: LinkState;\n  zoom: number;\n  meta: unknown;\n}\n\nexport interface ClusterDraw2D {\n  cluster: GraphCluster;\n  x: number;\n  y: number;\n  radius: number;\n  zoom: number;\n  meta: unknown;\n}\n\nexport interface BackgroundDraw2D {\n  width: number;\n  height: number;\n  camera: Camera2D;\n  time: number;\n  pixelRatio: number;\n  meta: unknown;\n}\n\nexport type NodeRenderer2D = (ctx: CanvasRenderingContext2D, d: NodeDraw2D) => void;\nexport type LinkRenderer2D = (ctx: CanvasRenderingContext2D, d: LinkDraw2D) => void;\nexport type ClusterRenderer2D = (ctx: CanvasRenderingContext2D, d: ClusterDraw2D) => void;\nexport type BackgroundRenderer2D = (ctx: CanvasRenderingContext2D, d: BackgroundDraw2D) => void;\n\n\/** Replace any part of the 2D look. Anything omitted uses the kit default. *\/\nexport interface GraphRenderers2D {\n  node?: NodeRenderer2D;\n  link?: LinkRenderer2D;\n  cluster?: ClusterRenderer2D;\n  background?: BackgroundRenderer2D;\n}\n","type":"registry:lib","target":"components\/fancy\/lib\/render2d\/types.ts"},{"path":"components\/fancy\/lib\/interaction.ts","content":"import type { IndexedGraph } from \".\/types\";\n\n\/** Node draw states. Renderers receive one of these per node, per frame. *\/\nexport const NODE_NORMAL = 0;\n\/** Selected, hovered, or a search match. *\/\nexport const NODE_ACTIVE = 1;\n\/** A neighbour of the focus (the selection, else the hover). *\/\nexport const NODE_NEIGHBOR = 2;\n\/** Everything else while something is focused or searched. *\/\nexport const NODE_DIMMED = 3;\nexport type NodeState = typeof NODE_NORMAL | typeof NODE_ACTIVE | typeof NODE_NEIGHBOR | typeof NODE_DIMMED;\n\nexport const LINK_NORMAL = 0;\n\/** Touches the focus. *\/\nexport const LINK_ACTIVE = 1;\nexport const LINK_DIMMED = 2;\nexport type LinkState = typeof LINK_NORMAL | typeof LINK_ACTIVE | typeof LINK_DIMMED;\n\nexport interface FocusInput {\n  \/** Node index, or -1 \/ undefined for none. *\/\n  selected?: number;\n  hovered?: number;\n  matches?: ReadonlySet<number> | null;\n  \/** The keyboard \/ gamepad focus. Drawn as its own ring; drives dimming only in neighbourhood mode. *\/\n  focused?: number;\n  \/** Dim everything but the focused node and its neighbours. *\/\n  neighborhood?: boolean;\n}\n\nconst idx = (v: number | undefined) => (typeof v === \"number\" && v >= 0 ? v : -1);\n\n\/** The node that drives neighbour highlighting: the focused node in neighbourhood mode, else the selection, else the hover. *\/\nexport function focusOf(f: FocusInput): number {\n  if (f.neighborhood && idx(f.focused) >= 0) return idx(f.focused);\n  const s = idx(f.selected);\n  return s >= 0 ? s : idx(f.hovered);\n}\n\nexport function computeNodeStates(graph: IndexedGraph, f: FocusInput, out?: Uint8Array): Uint8Array {\n  const n = graph.nodes.length;\n  const states = out && out.length === n ? out : new Uint8Array(n);\n  const selected = idx(f.selected);\n  const hovered = idx(f.hovered);\n  const focus = focusOf(f);\n  const matches = f.matches && f.matches.size ? f.matches : null;\n  if (!matches && focus < 0) {\n    states.fill(NODE_NORMAL);\n    return states;\n  }\n  states.fill(NODE_DIMMED);\n  if (!matches) for (const j of graph.neighbors[focus] ?? []) states[j] = NODE_NEIGHBOR;\n  if (matches) for (const j of matches) if (j >= 0 && j < n) states[j] = NODE_ACTIVE;\n  if (selected >= 0 && selected < n) states[selected] = NODE_ACTIVE;\n  if (hovered >= 0 && hovered < n) states[hovered] = NODE_ACTIVE;\n  if (f.neighborhood && focus >= 0 && focus < n) states[focus] = NODE_ACTIVE;\n  return states;\n}\n\nexport function computeLinkStates(graph: IndexedGraph, f: FocusInput, out?: Uint8Array): Uint8Array {\n  const m = graph.links.length;\n  const states = out && out.length === m ? out : new Uint8Array(m);\n  const focus = focusOf(f);\n  const matches = f.matches && f.matches.size ? f.matches : null;\n  if (focus < 0 && !matches) {\n    states.fill(LINK_NORMAL);\n    return states;\n  }\n  states.fill(LINK_DIMMED);\n  if (focus >= 0) for (const li of graph.incident[focus] ?? []) states[li] = LINK_ACTIVE;\n  return states;\n}\n\nexport interface SearchOptions {\n  \/** Most results returned. Defaults to 500. *\/\n  limit?: number;\n  \/** Text searched per node. Defaults to the label, then the id. *\/\n  text?: (index: number) => string;\n}\n\n\/**\n * Case-insensitive substring search over labels and ids. Best-connected first,\n * so \"Enter to fly\" lands on the node most likely meant.\n *\/\nexport function searchNodes(graph: IndexedGraph, query: string, opts: SearchOptions = {}): number[] {\n  const q = query.trim().toLowerCase();\n  if (!q) return [];\n  const limit = opts.limit ?? 500;\n  const hits: number[] = [];\n  for (let i = 0; i < graph.nodes.length; i++) {\n    const node = graph.nodes[i];\n    const text = opts.text ? opts.text(i) : `${node.label ?? \"\"}\\u0000${node.id}`;\n    if (text.toLowerCase().includes(q)) hits.push(i);\n  }\n  hits.sort((a, b) => graph.degree[b] - graph.degree[a] || a - b);\n  return hits.slice(0, limit);\n}\n\nexport interface PickOptions {\n  \/** Minimum reach in px. *\/\n  minReach: number;\n  \/**\n   * `\"depth\"` (3D, default): of the nodes under the pointer, the nearest to the\n   * camera wins; a node only within `minReach` (a near miss) counts only when\n   * nothing is directly under it, and then the nearest on screen wins.\n   * `\"nearest\"` (2D): nearest centre wins.\n   *\/\n  mode?: \"depth\" | \"nearest\";\n}\n\n\/**\n * Picks against a projected screen buffer: 4 floats per node \u2014 x, y, radius\n * (px) and depth, where depth 0 means \"not visible\". Returns -1 for a miss.\n *\/\nexport function pickScreen(screen: Float32Array, x: number, y: number, opts: PickOptions): number {\n  const byDepth = (opts.mode ?? \"depth\") === \"depth\";\n  let best = -1;\n  let bestScore = Infinity;\n  \/\/ Depth mode: in a crowd, a tiny body a few px off but in front must not steal a click aimed dead at another.\n  let near = -1;\n  let nearD2 = Infinity;\n  const n = screen.length >> 2;\n  for (let i = 0; i < n; i++) {\n    const depth = screen[i * 4 + 3];\n    if (depth <= 0) continue;\n    const dx = screen[i * 4] - x;\n    const dy = screen[i * 4 + 1] - y;\n    const hit = screen[i * 4 + 2] + 2;\n    const reach = Math.max(opts.minReach, hit);\n    const d2 = dx * dx + dy * dy;\n    if (d2 > reach * reach) continue;\n    if (byDepth && d2 > hit * hit) {\n      if (d2 <= nearD2) {\n        nearD2 = d2;\n        near = i;\n      }\n      continue;\n    }\n    const score = byDepth ? depth : d2;\n    if (score <= bestScore) {\n      bestScore = score;\n      best = i;\n    }\n  }\n  return best >= 0 ? best : near;\n}\n\nexport interface NeighborLink {\n  \/** The node at the other end. *\/\n  id: string;\n  index: number;\n  link: IndexedGraph[\"links\"][number];\n  \/** \"out\" when this node is the link's source. *\/\n  direction: \"out\" | \"in\";\n}\n\n\/** A node's links in a stable order (input link order), each with the node at the other end. *\/\nexport function neighborLinks(graph: IndexedGraph, index: number): NeighborLink[] {\n  const out: NeighborLink[] = [];\n  for (const li of graph.incident[index] ?? []) {\n    const l = graph.links[li];\n    const other = l.a === index ? l.b : l.a;\n    out.push({ id: graph.nodes[other].id, index: other, link: l, direction: l.a === index ? \"out\" : \"in\" });\n  }\n  return out;\n}\n\nexport type ScreenDirection = \"up\" | \"down\" | \"left\" | \"right\";\nexport type StepDirection = ScreenDirection | \"next\" | \"previous\";\n\nconst DIRS: Record<ScreenDirection, [number, number]> = { up: [0, -1], down: [0, 1], left: [-1, 0], right: [1, 0] };\n\n\/**\n * The linked node to move to from a node in a screen direction, using a\n * projected screen buffer (4 floats per node, depth 0 = hidden). Candidates\n * must lie within 60 degrees of the direction; the nearest, weighted toward\n * the straightest, wins. -1 when there is none.\n *\/\nexport function stepInDirection(graph: IndexedGraph, from: number, dir: ScreenDirection, screen: Float32Array): number {\n  const [ux, uy] = DIRS[dir];\n  const fx = screen[from * 4], fy = screen[from * 4 + 1];\n  let best = -1;\n  let bestScore = Infinity;\n  for (const j of graph.neighbors[from] ?? []) {\n    if (screen[j * 4 + 3] <= 0) continue;\n    const dx = screen[j * 4] - fx, dy = screen[j * 4 + 1] - fy;\n    const d = Math.hypot(dx, dy);\n    if (d < 1e-6) continue;\n    const cos = (dx * ux + dy * uy) \/ d;\n    if (cos < 0.5) continue;\n    const score = d * (1 + 2 * (1 - cos));\n    if (score < bestScore || (score === bestScore && j < best)) {\n      bestScore = score;\n      best = j;\n    }\n  }\n  return best;\n}\n\n\/** The next (delta 1) or previous (-1) link of an anchor after link position (-1 = none yet). *\/\nexport function cycleNeighbor(graph: IndexedGraph, anchor: number, position: number, delta: 1 | -1): { position: number; index: number } | null {\n  const links = neighborLinks(graph, anchor);\n  if (!links.length) return null;\n  const p = position < 0 ? (delta > 0 ? 0 : links.length - 1) : (((position + delta) % links.length) + links.length) % links.length;\n  return { position: p, index: links[p].index };\n}\n\n\/**\n * Whether a node wears the selection \/ hover ring. Selection, hover and search\n * matches do; the focus alone never does (it has its own dashed ring), even in\n * neighbourhood mode where its state is ACTIVE.\n *\/\nexport function hasHighlightRing(index: number, f: FocusInput): boolean {\n  return index >= 0 && (index === f.selected || index === f.hovered || !!f.matches?.has(index));\n}\n","type":"registry:lib","target":"components\/fancy\/lib\/interaction.ts"},{"path":"components\/fancy\/lib\/types.ts","content":"\/** A point or direction in world space. 2D layouts leave z at 0. *\/\nexport type Vec3 = [number, number, number];\n\n\/**\n * A node, as plain JSON. Only `id` is required. Everything an app wants to\n * carry for its own renderers goes in `data`; the kit never reads it.\n *\/\nexport interface GraphNode {\n  id: string;\n  \/** Shown as TEXT, never HTML. Defaults to the id. *\/\n  label?: string;\n  \/** Used for default colours and for `clusters=\"group\"`. *\/\n  group?: string;\n  \/** World-space radius. Defaults to a size derived from the node's degree. *\/\n  size?: number;\n  \/** Any CSS colour the renderer can parse (`#rrggbb` works everywhere). *\/\n  color?: string;\n  \/** Seed position. With `fixed`, the node is pinned there. *\/\n  x?: number;\n  y?: number;\n  z?: number;\n  fixed?: boolean;\n  \/** Where this node sits in the 3D `cosmos` preset. Optional; other views ignore it. *\/\n  cosmos?: GraphCosmosPlacement;\n  data?: Record<string, unknown>;\n}\n\n\/**\n * Optional placement for the `cosmos` 3D preset, as plain JSON. Absent, the\n * procedural layout decides. A bad value (not finite numbers, the wrong\n * length, past `limits.maxPlacement`) is ignored with one dev-mode warning and\n * listed in the layout's `meta.placementIssues`; it never throws.\n *\/\nexport interface GraphCosmosPlacement {\n  \/**\n   * Where this node's galaxy core sits, `[x, y, z]` in world units (the graph\n   * centre is the origin). A pinned galaxy stays there instead of orbiting the\n   * centre. Set it on any member; if members disagree, the first valid one in\n   * id order wins and the rest are reported.\n   *\/\n  galaxy?: [number, number, number];\n  \/**\n   * Where this node sits relative to its galaxy core, in the galaxy's disc:\n   * `[x, y]` in the disc plane or `[x, y, z]` with z out of it, world units.\n   * The node turns with its galaxy and no longer orbits a star.\n   *\/\n  offset?: [number, number] | [number, number, number];\n}\n\nexport interface GraphLink {\n  id?: string;\n  source: string;\n  target: string;\n  \/** Defaults to 1. Used by layouts, and to keep the strongest links when capped. *\/\n  weight?: number;\n  kind?: string;\n  data?: Record<string, unknown>;\n}\n\nexport interface GraphData {\n  nodes: GraphNode[];\n  links: GraphLink[];\n}\n\nexport interface IndexedLink {\n  \/** Position in `IndexedGraph.links`. *\/\n  index: number;\n  a: number;\n  b: number;\n  weight: number;\n  link: GraphLink;\n}\n\n\/** A graph after validation, with indices instead of ids. Built by `normalizeGraph`. *\/\nexport interface IndexedGraph {\n  nodes: GraphNode[];\n  links: IndexedLink[];\n  index: Map<string, number>;\n  \/** Sum of link weights per node. *\/\n  degree: Float64Array;\n  \/** Unique neighbour indices per node. *\/\n  neighbors: number[][];\n  \/** Link indices touching each node. *\/\n  incident: number[][];\n  dropped: {\n    \/** Nodes beyond `limits.maxNodes`. *\/\n    nodes: number;\n    \/** Valid links beyond `limits.maxLinks` (the weakest are dropped). *\/\n    links: number;\n    \/** Links to a missing node, self-links, and malformed links. *\/\n    invalidLinks: number;\n    duplicateNodes: number;\n  };\n}\n\n\/**\n * A group of nodes drawn as one thing: a galaxy, a community, a hull. Either a\n * layout supplies them (`GraphLayoutStepper.clusters`) or the view computes them\n * from `clusters=\"group\"`.\n *\/\nexport interface GraphCluster {\n  id: string;\n  label?: string;\n  center: Vec3;\n  radius: number;\n  \/** Indices of member nodes. *\/\n  members: number[];\n  color?: string;\n  \/** For flat clusters in 3D (a galaxy disc): the plane's normal. *\/\n  normal?: Vec3;\n  data?: Record<string, unknown>;\n}\n\n\/** Where a change came from. Agents act through `\"agent\"`; the kit never guesses. *\/\nexport type GraphActivitySource = \"user\" | \"agent\" | \"api\";\n\nexport interface GraphActivity {\n  \/**\n   * `\"layer\"`: a layer was switched (`id` is the layer's id). `\"links\"`: the\n   * link visibility mode changed (`id` is the mode). `\"motion\"`: animation was\n   * paused or resumed (`id` is `\"paused\"` or `\"running\"`).\n   *\/\n  type: \"select\" | \"hover\" | \"focus\" | \"camera\" | \"search\" | \"layer\" | \"links\" | \"motion\";\n  id?: string | null;\n  source: GraphActivitySource;\n  at: number;\n}\n","type":"registry:lib","target":"components\/fancy\/lib\/types.ts"},{"path":"components\/fancy\/lib\/presets\/presets2d.ts","content":"import type { GraphLayout } from \"..\/layout\/contract\";\nimport { forceLayout, type ForceLayoutOptions } from \"..\/layout\/force\";\nimport { hierarchyLayout, radialLayout, type HierarchyLayoutOptions, type RadialLayoutOptions } from \"..\/layout\/static\";\nimport type { ClusterSource } from \"..\/render2d\/engine\";\nimport type { GraphRenderers2D } from \"..\/render2d\/types\";\nimport type { GraphCluster, IndexedGraph } from \"..\/types\";\nimport { DEFAULT_LAYERS, type GraphLayerSpec } from \"..\/layers\";\n\n\/** Links and labels, plus a layer for the cluster hulls. *\/\nconst WITH_CLUSTERS: GraphLayerSpec[] = [...DEFAULT_LAYERS, { id: \"clusters\", label: \"Clusters\" }];\n\n\/** What a preset's layout may depend on. A change of `layoutKey` re-runs the layout. *\/\nexport interface PresetState {\n  graph: IndexedGraph;\n  selected: string | null;\n  focused: string | null;\n}\n\n\/**\n * A ready-made 2D view: a layout plus renderers plus defaults. Pass one (or its\n * id) as `preset`; any prop you also pass (`layout`, `renderers.node`,\n * `clusters`, ...) overrides that piece and keeps the rest.\n *\/\nexport interface GraphPreset2D {\n  id: string;\n  title: string;\n  description: string;\n  layout: (state: PresetState) => GraphLayout;\n  \/** When it changes, the layout is rebuilt (e.g. the radial view's centre). Default: never. *\/\n  layoutKey?: (state: PresetState) => string;\n  renderers?: GraphRenderers2D;\n  clusters?: ClusterSource;\n  clusterLabel?: (cluster: GraphCluster) => string | null;\n  linkVisibility?: \"all\" | \"focus\" | \"none\";\n  \/** The layers this preset draws, for `layers` \/ `onLayersChange` and the controls. Default: links and labels. *\/\n  layers?: GraphLayerSpec[];\n}\n\n\/** A force-directed network: the default view. *\/\nexport function networkPreset(options: ForceLayoutOptions = {}): GraphPreset2D {\n  return {\n    id: \"network\",\n    title: \"Network\",\n    description: \"A force-directed network: linked nodes pull together, everything else spreads out. The default view for any graph.\",\n    layout: () => forceLayout({ gravity: 0.05, ...options }),\n    layers: [...DEFAULT_LAYERS],\n  };\n}\n\n\/** An ego view: the focused node (else the selection, else the best-connected node) at the centre, neighbours on rings by distance. *\/\nexport function radialPreset(options: Omit<RadialLayoutOptions, \"root\"> = {}): GraphPreset2D {\n  const centre = (s: PresetState) => s.focused ?? s.selected ?? \"\";\n  return {\n    id: \"radial\",\n    title: \"Radial (ego)\",\n    description: \"An ego view centred on the focused node, else the selection: its neighbours on the first ring, theirs on the next, re-centred whenever the centre moves.\",\n    layout: (s) => radialLayout({ ...options, ringGap: options.ringGap ?? 90, root: centre(s) || undefined }),\n    layoutKey: centre,\n    layers: [...DEFAULT_LAYERS],\n  };\n}\n\n\/** A layered tree for directed links: roots on top, children below their parents. *\/\nexport function hierarchyPreset(options: HierarchyLayoutOptions = {}): GraphPreset2D {\n  return {\n    id: \"hierarchy\",\n    title: \"Hierarchy\",\n    description: \"A layered tree for directed links (source above target): roots on top, each child under its parents, crossings reduced. Cycles are broken, not looped.\",\n    layout: () => hierarchyLayout({ layerGap: 90, nodeGap: 46, ...options }),\n    layers: [...DEFAULT_LAYERS],\n  };\n}\n\n\/** A clustered map: a force layout that gathers each node type, with a labelled hull per type. *\/\nexport function clusteredPreset(options: ForceLayoutOptions = {}): GraphPreset2D {\n  return {\n    id: \"clustered\",\n    title: \"Clustered map\",\n    description: \"A map grouped by node type: each type gathers into its own region with a labelled hull, links still drawn across regions.\",\n    layout: () => forceLayout({ groupPull: 0.3, gravity: 0.05, ...options }),\n    clusters: \"group\",\n    clusterLabel: (c) => `${c.label ?? c.id} \u00b7 ${c.members.length}`,\n    layers: WITH_CLUSTERS,\n  };\n}\n\n\/** Every built-in 2D preset, by id. `network` is the default. *\/\nexport const GRAPH_PRESETS_2D: Readonly<Record<\"network\" | \"radial\" | \"hierarchy\" | \"clustered\", GraphPreset2D>> = Object.freeze({\n  network: networkPreset(),\n  radial: radialPreset(),\n  hierarchy: hierarchyPreset(),\n  clustered: clusteredPreset(),\n});\n\nexport type GraphPreset2DId = keyof typeof GRAPH_PRESETS_2D;\n\n\/** A preset from an id or an object; an unknown id is an error, never a silent default. *\/\nexport function resolvePreset2D(preset: GraphPreset2DId | string | GraphPreset2D | undefined): GraphPreset2D {\n  if (preset === undefined) return GRAPH_PRESETS_2D.network;\n  if (typeof preset === \"object\") return preset;\n  const found = (GRAPH_PRESETS_2D as Record<string, GraphPreset2D>)[preset];\n  if (!found) throw new Error(`Unknown fancy-graph 2D preset \"${preset}\". Built in: ${Object.keys(GRAPH_PRESETS_2D).join(\", \")}.`);\n  return found;\n}\n","type":"registry:lib","target":"components\/fancy\/lib\/presets\/presets2d.ts"},{"path":"components\/fancy\/lib\/theme.ts","content":"import { DEFAULT_PALETTE, colorFor } from \".\/color\";\n\n\/**\n * The look every preset draws with. Light and dark ship built in; anything can\n * be overridden by the `theme` prop, and every colour by a CSS variable, so a\n * kit theme (Tailwind v4 tokens, react-fancy's) can drive the graph:\n *\n *   --fancy-graph-background, --fancy-graph-link, --fancy-graph-label,\n *   --fancy-graph-label-halo, --fancy-focus, --fancy-graph-selection,\n *   --fancy-graph-type-<type>   (one per node type, e.g. --fancy-graph-type-agent)\n *\n * e.g. `.my-app { --fancy-graph-background: var(--color-zinc-950); }`.\n *\/\nexport interface GraphTheme {\n  mode: \"light\" | \"dark\";\n  background: string;\n  link: string;\n  label: string;\n  labelHalo: string;\n  focus: string;\n  selection: string;\n  \/** Colours for node types with no explicit colour, assigned by a stable hash. *\/\n  palette: readonly string[];\n  \/** Per-type colours, by node `group`. *\/\n  typeColors: Readonly<Record<string, string>>;\n}\n\nexport const LIGHT_THEME: Readonly<GraphTheme> = Object.freeze({\n  mode: \"light\",\n  background: \"#f8fafc\",\n  link: \"#64748b\",\n  label: \"#0f172a\",\n  labelHalo: \"#ffffff\",\n  focus: \"#2563eb\",\n  selection: \"#0f172a\",\n  palette: [\"#2563eb\", \"#db2777\", \"#059669\", \"#d97706\", \"#7c3aed\", \"#dc2626\", \"#0891b2\", \"#65a30d\", \"#ea580c\", \"#c026d3\"],\n  typeColors: Object.freeze({}),\n});\n\nexport const DARK_THEME: Readonly<GraphTheme> = Object.freeze({\n  mode: \"dark\",\n  background: \"#0b1020\",\n  link: \"#94a3b8\",\n  label: \"#e8eef5\",\n  labelHalo: \"#000000\",\n  focus: \"#60a5fa\",\n  selection: \"#f8fafc\",\n  palette: DEFAULT_PALETTE,\n  typeColors: Object.freeze({}),\n});\n\n\/** `\"light\"`, `\"dark\"`, `\"auto\"` (from a `.dark` \/ `[data-theme=dark]` ancestor, else the system), or overrides on a base. *\/\nexport type GraphThemeInput = \"light\" | \"dark\" | \"auto\" | (Partial<Omit<GraphTheme, \"mode\">> & { base?: \"light\" | \"dark\" | \"auto\" });\n\n\/** A CSS custom property, from the element up through its ancestors (inline or computed). *\/\nexport function cssVar(el: Element | null, name: string): string {\n  for (let e: Element | null = el; e; e = e.parentElement) {\n    const inline = (e as HTMLElement).style?.getPropertyValue(name).trim();\n    if (inline) return inline;\n    if (typeof getComputedStyle === \"function\") {\n      const computed = getComputedStyle(e).getPropertyValue(name).trim();\n      if (computed) return computed;\n    }\n  }\n  return \"\";\n}\n\nfunction prefersDark(el: Element | null): boolean {\n  if (el?.closest?.('.dark, [data-theme=\"dark\"]')) return true;\n  if (el?.closest?.('.light, [data-theme=\"light\"]')) return false;\n  return typeof window !== \"undefined\" && typeof window.matchMedia === \"function\" && window.matchMedia(\"(prefers-color-scheme: dark)\").matches;\n}\n\n\/** The theme to draw with: the base, the prop's overrides, then CSS variables on or above `el`. *\/\nexport function resolveTheme(input: GraphThemeInput | undefined, el: Element | null): GraphTheme {\n  const spec = typeof input === \"object\" && input !== null ? input : { base: input ?? \"auto\" };\n  const base = spec.base ?? \"auto\";\n  const dark = base === \"dark\" || (base === \"auto\" && prefersDark(el));\n  const t: GraphTheme = { ...(dark ? DARK_THEME : LIGHT_THEME) };\n  for (const key of [\"background\", \"link\", \"label\", \"labelHalo\", \"focus\", \"selection\"] as const) {\n    if (typeof spec[key] === \"string\") t[key] = spec[key] as string;\n  }\n  if (Array.isArray(spec.palette) && spec.palette.length) t.palette = spec.palette;\n  t.typeColors = { ...(spec.typeColors ?? {}) };\n  const vars: Record<string, keyof GraphTheme> = {\n    \"--fancy-graph-background\": \"background\",\n    \"--fancy-graph-link\": \"link\",\n    \"--fancy-graph-label\": \"label\",\n    \"--fancy-graph-label-halo\": \"labelHalo\",\n    \"--fancy-focus\": \"focus\",\n    \"--fancy-graph-selection\": \"selection\",\n  };\n  for (const [name, key] of Object.entries(vars)) {\n    \/\/ The prop wins over the stylesheet; the stylesheet wins over the base.\n    if (typeof spec[key as keyof typeof spec] === \"string\") continue;\n    const v = cssVar(el, name);\n    if (v) (t as unknown as Record<string, unknown>)[key] = v;\n  }\n  return t;\n}\n\n\/** A node type's colour: the theme's map, then `--fancy-graph-type-<type>`, then the palette. *\/\nexport function typeColor(theme: GraphTheme, group: string | undefined, el: Element | null): string {\n  if (group && theme.typeColors[group]) return theme.typeColors[group];\n  if (group) {\n    const v = cssVar(el, `--fancy-graph-type-${group.replace(\/[^a-zA-Z0-9_-]\/g, \"-\")}`);\n    if (v) return v;\n  }\n  return colorFor(group, theme.palette);\n}\n\n\/**\n * A lookup from type to colour for one graph, built by `assignTypeColors` on\n * first use, so a view walks its nodes once per graph and theme, not per node.\n *\/\nexport function typeColorsFor(theme: GraphTheme, nodes: readonly { group?: string }[], el: Element | null): (group: string | undefined) => string {\n  let map: Map<string, string> | null = null;\n  return (group) => {\n    if (!group) return typeColor(theme, group, el);\n    map ??= assignTypeColors(theme, nodes.map((n) => n.group), el);\n    return map.get(group) ?? typeColor(theme, group, el);\n  };\n}\n\n\/** A type's set colour (the theme's map, then its CSS variable), or null when the palette decides. *\/\nfunction setTypeColor(theme: GraphTheme, group: string, el: Element | null): string | null {\n  if (theme.typeColors[group]) return theme.typeColors[group];\n  return cssVar(el, `--fancy-graph-type-${group.replace(\/[^a-zA-Z0-9_-]\/g, \"-\")}`) || null;\n}\n\n\/**\n * Every type in a graph, coloured so the types tell apart. A set colour (the\n * theme's map, then `--fancy-graph-type-<type>`) wins. The rest share the\n * palette: each type keeps its hashed slot unless another type already holds\n * it, then takes the next free one, visiting types in sorted order so the input\n * order changes nothing. Slots are reused only once every one is taken.\n *\/\nexport function assignTypeColors(theme: GraphTheme, groups: Iterable<string | undefined>, el: Element | null): Map<string, string> {\n  const out = new Map<string, string>();\n  const rest: string[] = [];\n  for (const g of new Set(groups)) {\n    if (!g) continue;\n    const set = setTypeColor(theme, g, el);\n    if (set) out.set(g, set);\n    else rest.push(g);\n  }\n  const palette = theme.palette;\n  if (!palette.length) return out;\n  const taken = new Set<string>(out.values());\n  rest.sort();\n  for (const g of rest) {\n    if (palette.every((c) => taken.has(c))) taken.clear();\n    let i = palette.indexOf(colorFor(g, palette));\n    while (taken.has(palette[i])) i = (i + 1) % palette.length;\n    out.set(g, palette[i]);\n    taken.add(palette[i]);\n  }\n  return out;\n}\n\n\/** Sets the label colours on the root, so the label layer (pure CSS) follows the theme. *\/\nexport function applyThemeVars(el: HTMLElement | null, theme: GraphTheme): void {\n  if (!el) return;\n  el.style.setProperty(\"--fancy-graph-label\", theme.label);\n  el.style.setProperty(\"--fancy-graph-label-halo\", theme.labelHalo);\n}\n","type":"registry:lib","target":"components\/fancy\/lib\/theme.ts"},{"path":"components\/fancy\/lib\/layers.ts","content":"\/**\n * Layer visibility, headless. A preset declares the layers it draws (links,\n * labels, clusters, a background, the cosmos's orbit paths, ...); the view\n * takes a partial JSON map `{ [id]: boolean }` over those, so a host, the\n * built-in controls and an agent all switch them the same way.\n *\/\n\n\/** `\"all\"`, `\"focus\"` (only the focus's links while something is focused or searched), or `\"none\"`. *\/\nexport type LinkVisibility = \"all\" | \"focus\" | \"none\";\n\n\/** A layer a preset can switch on and off. *\/\nexport interface GraphLayerSpec {\n  \/** Stable id: `links`, `labels`, `clusters`, `background`, `orbits`, or a custom layer's own. *\/\n  id: string;\n  \/** What the controls call it (\"Galaxies\", \"Orbit paths\"). *\/\n  label: string;\n  \/** Shown unless the map says otherwise. Default true. *\/\n  visible?: boolean;\n}\n\n\/** One layer as the view currently has it. *\/\nexport interface GraphLayerState {\n  id: string;\n  label: string;\n  visible: boolean;\n}\n\n\/** Partial on the way in (`layers`, `defaultLayers`); full, one key per declared layer, on the way out (`onLayersChange`). *\/\nexport type GraphLayerVisibility = Record<string, boolean>;\n\n\/** What every view draws: links and node labels. *\/\nexport const DEFAULT_LAYERS: readonly GraphLayerSpec[] = Object.freeze([\n  { id: \"links\", label: \"Links\" },\n  { id: \"labels\", label: \"Labels\" },\n]);\n\n\/** The declared layers, each resolved against the map. Ids the preset does not declare are ignored. *\/\nexport function resolveLayers(specs: readonly GraphLayerSpec[], value?: Partial<Record<string, boolean>> | null): GraphLayerState[] {\n  return specs.map((s) => {\n    const v = value?.[s.id];\n    return { id: s.id, label: s.label, visible: typeof v === \"boolean\" ? v : s.visible !== false };\n  });\n}\n\n\/** Several declarations as one list, in order; the first declaration of an id wins. *\/\nexport function mergeLayerSpecs(...lists: readonly (readonly GraphLayerSpec[] | undefined)[]): GraphLayerSpec[] {\n  const out: GraphLayerSpec[] = [];\n  const seen = new Set<string>();\n  for (const list of lists)\n    for (const s of list ?? []) {\n      if (seen.has(s.id)) continue;\n      seen.add(s.id);\n      out.push(s);\n    }\n  return out;\n}\n\n\/** `{ id: visible }` for every layer. *\/\nexport function layerMap(states: readonly GraphLayerState[]): GraphLayerVisibility {\n  const out: GraphLayerVisibility = {};\n  for (const s of states) out[s.id] = s.visible;\n  return out;\n}\n\n\/** A layer nobody declared (the nodes, a custom layer) is always visible. *\/\nexport function isLayerVisible(map: Readonly<Partial<Record<string, boolean>>> | undefined, id: string): boolean {\n  return map?.[id] !== false;\n}\n\n\/** The links layer switched off means no links, whatever the mode. *\/\nexport function effectiveLinkVisibility(mode: LinkVisibility, linksVisible: boolean): LinkVisibility {\n  return linksVisible ? mode : \"none\";\n}\n","type":"registry:lib","target":"components\/fancy\/lib\/layers.ts"},{"path":"components\/fancy\/lib\/graph.ts","content":"import { resolveLimits, type GraphLimits } from \".\/limits\";\nimport type { GraphData, GraphNode, IndexedGraph, IndexedLink } from \".\/types\";\n\n\/**\n * Validates plain JSON into an indexed graph. Input is never trusted: ids must\n * be strings, weights must be finite, links must join two different existing\n * nodes, and both counts are capped by `limits`.\n *\/\nexport function normalizeGraph(data: GraphData, limitOverrides?: Partial<GraphLimits>): IndexedGraph {\n  const limits = resolveLimits(limitOverrides);\n  const nodes: GraphNode[] = [];\n  const index = new Map<string, number>();\n  let duplicateNodes = 0;\n  let overNodes = 0;\n  for (const n of Array.isArray(data?.nodes) ? data.nodes : []) {\n    if (!n || typeof n.id !== \"string\") continue;\n    if (index.has(n.id)) {\n      duplicateNodes++;\n      continue;\n    }\n    if (nodes.length >= limits.maxNodes) {\n      overNodes++;\n      continue;\n    }\n    index.set(n.id, nodes.length);\n    nodes.push(n);\n  }\n\n  let invalidLinks = 0;\n  const valid: IndexedLink[] = [];\n  for (const l of Array.isArray(data?.links) ? data.links : []) {\n    const a = l && typeof l.source === \"string\" ? index.get(l.source) : undefined;\n    const b = l && typeof l.target === \"string\" ? index.get(l.target) : undefined;\n    if (a === undefined || b === undefined || a === b) {\n      invalidLinks++;\n      continue;\n    }\n    const w = typeof l.weight === \"number\" && Number.isFinite(l.weight) && l.weight > 0 ? l.weight : 1;\n    valid.push({ index: valid.length, a, b, weight: w, link: l });\n  }\n\n  let links = valid;\n  if (valid.length > limits.maxLinks) {\n    \/\/ Strongest first; Array.prototype.sort is stable, so ties keep input order.\n    links = [...valid].sort((x, y) => y.weight - x.weight).slice(0, limits.maxLinks);\n    links.forEach((l, i) => (l.index = i));\n  }\n\n  const n = nodes.length;\n  const degree = new Float64Array(n);\n  const neighborSets: Set<number>[] = Array.from({ length: n }, () => new Set());\n  const incident: number[][] = Array.from({ length: n }, () => []);\n  for (const l of links) {\n    degree[l.a] += l.weight;\n    degree[l.b] += l.weight;\n    neighborSets[l.a].add(l.b);\n    neighborSets[l.b].add(l.a);\n    incident[l.a].push(l.index);\n    incident[l.b].push(l.index);\n  }\n\n  return {\n    nodes,\n    links,\n    index,\n    degree,\n    neighbors: neighborSets.map((s) => [...s]),\n    incident,\n    dropped: { nodes: overNodes, links: valid.length - links.length, invalidLinks, duplicateNodes },\n  };\n}\n","type":"registry:lib","target":"components\/fancy\/lib\/graph.ts"},{"path":"components\/fancy\/lib\/limits.ts","content":"\/**\n * Every limit the kit applies, in one place, and every one configurable through\n * the `limits` prop. The defaults are the measured comfortable range (see the\n * README's benchmark section), not hard ceilings.\n *\/\nexport interface GraphLimits {\n  \/** Nodes beyond this are dropped (first come, first kept). *\/\n  maxNodes: number;\n  \/** Links beyond this are dropped, weakest first. *\/\n  maxLinks: number;\n  \/** Node labels on screen at once. *\/\n  maxLabels: number;\n  \/** Labels that must show (selection, hover, the focused node and its neighbours), even past maxLabels. *\/\n  maxForcedLabels: number;\n  \/** Characters per label before it is cut with an ellipsis. *\/\n  maxLabelLength: number;\n  \/** Projected radius (CSS px) a node needs before its label competes for space. *\/\n  labelMinPx: number;\n  \/** Minimum pick reach (CSS px), so tiny nodes stay clickable. *\/\n  pickRadius: number;\n  \/** Search results kept and highlighted. *\/\n  maxSearchResults: number;\n  \/** Node count above which `workerLayout` moves a built-in layout off the main thread. *\/\n  workerThreshold: number;\n  \/** Steps a layout may take to settle before first paint under reduced motion. *\/\n  maxSettleTicks: number;\n  \/** Device pixel ratio cap for the canvas. *\/\n  maxPixelRatio: number;\n  \/** 2D zoom range. *\/\n  minZoom: number;\n  maxZoom: number;\n  \/**\n   * Highest zoom an automatic fit (first view, `fit()`, Home) picks, so a small\n   * graph is not blown up to fill the view. Zooming by hand still reaches `maxZoom`.\n   *\/\n  fitMaxZoom: number;\n  \/** 3D camera distance range, as multiples of the graph's extent. *\/\n  maxDistanceFactor: number;\n  minDistance: number;\n  \/**\n   * Largest absolute coordinate a placement taken from data may ask for (the\n   * cosmos's `node.cosmos.galaxy` \/ `offset`, in world units). A bigger value\n   * is ignored and reported, never clamped.\n   *\/\n  maxPlacement: number;\n}\n\nexport const DEFAULT_LIMITS: Readonly<GraphLimits> = Object.freeze({\n  maxNodes: 20000,\n  maxLinks: 60000,\n  maxLabels: 40,\n  maxForcedLabels: 64,\n  maxLabelLength: 48,\n  labelMinPx: 3.5,\n  pickRadius: 7,\n  maxSearchResults: 500,\n  workerThreshold: 1500,\n  maxSettleTicks: 600,\n  maxPixelRatio: 2,\n  minZoom: 0.01,\n  maxZoom: 40,\n  fitMaxZoom: 2,\n  maxDistanceFactor: 4,\n  minDistance: 2,\n  maxPlacement: 100000,\n});\n\n\/** Overrides merged onto the defaults. A non-finite or non-positive override is ignored, never \"unlimited\". *\/\nexport function resolveLimits(overrides?: Partial<GraphLimits> | null): GraphLimits {\n  const out = { ...DEFAULT_LIMITS } as GraphLimits;\n  if (!overrides) return out;\n  for (const key of Object.keys(DEFAULT_LIMITS) as (keyof GraphLimits)[]) {\n    const v = overrides[key];\n    if (typeof v === \"number\" && Number.isFinite(v) && v > 0) out[key] = v;\n  }\n  return out;\n}\n\n\/** Cuts a label to `max` characters, ending in an ellipsis when it was cut. *\/\nexport function truncateLabel(text: string, max: number): string {\n  const chars = Array.from(text);\n  if (chars.length <= max) return text;\n  return `${chars.slice(0, Math.max(0, max - 1)).join(\"\")}\u2026`;\n}\n","type":"registry:lib","target":"components\/fancy\/lib\/limits.ts"},{"path":"components\/fancy\/lib\/clusters.ts","content":"import type { GraphCluster, IndexedGraph } from \".\/types\";\n\n\/**\n * Clusters by a key per node (the group, by default): centre is the members'\n * median position, radius reaches `coverage` of the members (85% by default, so\n * one far outlier cannot inflate the hull) plus `padding`. Cheap enough to\n * recompute every frame for moving layouts.\n *\/\nexport function groupClusters(graph: IndexedGraph, positions: Float32Array, key: (index: number) => string | undefined = (i) => graph.nodes[i].group, padding = 12, coverage = 0.85): GraphCluster[] {\n  const members = new Map<string, number[]>();\n  for (let i = 0; i < graph.nodes.length; i++) {\n    const k = key(i);\n    if (k === undefined || k === \"\") continue;\n    const list = members.get(k);\n    if (list) list.push(i);\n    else members.set(k, [i]);\n  }\n  const out: GraphCluster[] = [];\n  for (const [id, list] of members) {\n    \/\/ Per-axis median: a far outlier moves neither the centre nor (below) the radius.\n    const median = (axis: number) => {\n      const v = list.map((i) => positions[i * 3 + axis]).sort((a, b) => a - b);\n      const m = v.length >> 1;\n      return v.length % 2 ? v[m] : (v[m - 1] + v[m]) \/ 2;\n    };\n    const cx = median(0), cy = median(1), cz = median(2);\n    const d = list.map((i) => Math.hypot(positions[i * 3] - cx, positions[i * 3 + 1] - cy, positions[i * 3 + 2] - cz)).sort((a, b) => a - b);\n    const r = d[Math.min(d.length - 1, Math.floor(Math.max(0, Math.min(1, coverage)) * (d.length - 1)))] ?? 0;\n    out.push({ id, label: id, center: [cx, cy, cz], radius: r + padding, members: list });\n  }\n  return out;\n}\n","type":"registry:lib","target":"components\/fancy\/lib\/clusters.ts"},{"path":"components\/fancy\/lib\/color.ts","content":"import { hash01 } from \".\/random\";\n\n\/** Ten distinguishable hues that read on dark and light backgrounds. *\/\nexport const DEFAULT_PALETTE: readonly string[] = [\"#60a5fa\", \"#f472b6\", \"#34d399\", \"#fbbf24\", \"#a78bfa\", \"#f87171\", \"#22d3ee\", \"#a3e635\", \"#fb923c\", \"#e879f9\"];\n\n\/** A stable palette colour for a group key. *\/\nexport function colorFor(key: string | undefined, palette: readonly string[] = DEFAULT_PALETTE): string {\n  if (!key) return \"#94a3b8\";\n  return palette[Math.floor(hash01(key) * palette.length) % palette.length];\n}\n\n\/** `#rgb` \/ `#rrggbb` to 0..1 rgb. Anything else is a neutral grey rather than an exception. *\/\nexport function parseColor(css: string | undefined): [number, number, number] {\n  const m = typeof css === \"string\" ? \/^#([0-9a-f]{3}|[0-9a-f]{6})$\/i.exec(css.trim()) : null;\n  if (!m) return [0.58, 0.64, 0.72];\n  const h = m[1].length === 3 ? m[1].replace(\/.\/g, (c) => c + c) : m[1];\n  const n = parseInt(h, 16);\n  return [((n >> 16) & 255) \/ 255, ((n >> 8) & 255) \/ 255, (n & 255) \/ 255];\n}\n","type":"registry:lib","target":"components\/fancy\/lib\/color.ts"},{"path":"components\/fancy\/lib\/labels.ts","content":"import { NODE_ACTIVE, NODE_NEIGHBOR } from \".\/interaction\";\n\nexport interface LabelCandidate {\n  index: number;\n  \/** Projected node centre and radius, CSS px. *\/\n  x: number;\n  y: number;\n  radius: number;\n  text: string;\n  \/** Higher places first. *\/\n  priority: number;\n  \/** Placed even when it overlaps (the selection, the hover). *\/\n  forced?: boolean;\n}\n\nexport interface PlacedLabel {\n  index: number;\n  id?: string;\n  text: string;\n  x: number;\n  y: number;\n  w: number;\n  h: number;\n  state?: \"active\" | \"neighbor\" | \"normal\";\n}\n\nexport interface PlaceOptions {\n  \/** Labels in total; forced labels may go past it. *\/\n  maxLabels: number;\n  \/** Forced labels (selection, hover, the focused node and its neighbours). Default: no cap. *\/\n  maxForced?: number;\n  width: number;\n  height: number;\n  \/** Estimated px per character. Defaults to 6.2 (11px UI font). *\/\n  charWidth?: number;\n  \/** Label box height. Defaults to 14. *\/\n  lineHeight?: number;\n  \/** Gap between the node edge and its label. Defaults to 4. *\/\n  gap?: number;\n}\n\n\/**\n * Greedy label placement: highest priority first, each label to the right of\n * its node, rejected when its box overlaps one already placed (forced labels\n * are never rejected). A uniform grid keeps the overlap test cheap at a few\n * thousand candidates.\n *\/\nexport function placeLabels(candidates: LabelCandidate[], opts: PlaceOptions): PlacedLabel[] {\n  const cw = opts.charWidth ?? 6.2;\n  const lh = opts.lineHeight ?? 14;\n  const gap = opts.gap ?? 4;\n  const sorted = [...candidates].sort((a, b) => b.priority - a.priority);\n  const placed: PlacedLabel[] = [];\n  const cell = 64;\n  const grid = new Map<number, PlacedLabel[]>();\n  const key = (cx: number, cy: number) => cx * 100003 + cy;\n  const maxForced = opts.maxForced ?? Infinity;\n  let forcedCount = 0;\n  for (const c of sorted) {\n    if (c.forced) {\n      if (forcedCount >= maxForced) continue;\n    } else if (placed.length >= opts.maxLabels) continue;\n    const w = Array.from(c.text).length * cw;\n    const x = c.x + Math.max(3, c.radius) + gap;\n    const y = c.y - lh \/ 2;\n    if (x > opts.width || x + w < 0 || y > opts.height || y + lh < 0) continue;\n    const x0 = Math.floor(x \/ cell), x1 = Math.floor((x + w) \/ cell), y0 = Math.floor(y \/ cell), y1 = Math.floor((y + lh) \/ cell);\n    if (!c.forced) {\n      let hit = false;\n      for (let gx = x0; gx <= x1 && !hit; gx++)\n        for (let gy = y0; gy <= y1 && !hit; gy++)\n          for (const p of grid.get(key(gx, gy)) ?? []) if (x < p.x + p.w && x + w > p.x && y < p.y + p.h && y + lh > p.y) {\n            hit = true;\n            break;\n          }\n      if (hit) continue;\n    }\n    const label: PlacedLabel = { index: c.index, text: c.text, x, y, w, h: lh };\n    placed.push(label);\n    if (c.forced) forcedCount++;\n    for (let gx = x0; gx <= x1; gx++)\n      for (let gy = y0; gy <= y1; gy++) {\n        const k = key(gx, gy);\n        const list = grid.get(k);\n        if (list) list.push(label);\n        else grid.set(k, [label]);\n      }\n  }\n  return placed;\n}\n\nexport interface CandidateInput {\n  \/** 4 floats per node: x, y, radius px, depth (0 = hidden). *\/\n  screen: Float32Array;\n  states: Uint8Array;\n  selected: number;\n  hovered: number;\n  matches: ReadonlySet<number> | null;\n  width: number;\n  height: number;\n  labelMinPx: number;\n  text: (index: number) => string;\n  \/** The keyboard \/ gamepad focus: it and its neighbours are always labelled. *\/\n  focused?: number;\n  focusNeighbors?: readonly number[];\n  \/** Label nothing else while something is focused (neighbourhood mode). *\/\n  cullOthers?: boolean;\n}\n\n\/**\n * Which nodes compete for a label: the selection and hover always; matches and\n * the focus's neighbours next; otherwise only nodes drawn large enough, and\n * none at all while something is selected or searched (it would be noise).\n *\/\nexport function labelCandidates(input: CandidateInput): LabelCandidate[] {\n  const { screen, states, selected, hovered, matches, width, height } = input;\n  const out: LabelCandidate[] = [];\n  const focused = input.focused ?? -1;\n  const near = new Set(focused >= 0 ? (input.focusNeighbors ?? []) : []);\n  const quiet = selected >= 0 || (matches && matches.size > 0) || (!!input.cullOthers && focused >= 0);\n  const n = screen.length >> 2;\n  for (let i = 0; i < n; i++) {\n    const depth = screen[i * 4 + 3];\n    if (depth <= 0) continue;\n    const x = screen[i * 4], y = screen[i * 4 + 1], r = screen[i * 4 + 2];\n    if (x < -40 || y < -20 || x > width + 40 || y > height + 20) continue;\n    let priority = r;\n    let forced = false;\n    if (i === focused) {\n      priority += 9e6;\n      forced = true;\n    } else if (near.has(i)) {\n      priority += 2e6;\n      forced = true;\n    } else if (i === selected) {\n      priority += 1e7;\n      forced = true;\n    } else if (i === hovered) {\n      priority += 1e6;\n      forced = true;\n    } else if (matches?.has(i)) priority += 1e5;\n    else if (states[i] === NODE_NEIGHBOR) priority += 1e4;\n    else if (quiet || r < input.labelMinPx) continue;\n    else if (states[i] !== NODE_ACTIVE && hovered >= 0) priority *= 0.5;\n    out.push({ index: i, x, y, radius: r, text: input.text(i), priority, forced });\n  }\n  return out;\n}\n\nexport interface ClusterLabel {\n  id: string;\n  text: string;\n  x: number;\n  y: number;\n  color?: string;\n}\n\nconst LABEL_CSS =\n  \"position:absolute;left:0;top:0;white-space:nowrap;pointer-events:none;will-change:transform;display:none;\" +\n  \"font:11px\/14px ui-sans-serif,system-ui,sans-serif;color:var(--fancy-graph-label,#e8eef5);\" +\n  \"text-shadow:0 0 4px var(--fancy-graph-label-halo,#000),0 0 2px var(--fancy-graph-label-halo,#000)\";\nconst CLUSTER_CSS =\n  \"position:absolute;left:0;top:0;white-space:nowrap;pointer-events:none;will-change:transform;display:none;\" +\n  \"font:600 12px\/16px ui-sans-serif,system-ui,sans-serif;letter-spacing:.14em;text-transform:uppercase;\" +\n  \"text-shadow:0 0 6px var(--fancy-graph-label-halo,#000),0 0 2px var(--fancy-graph-label-halo,#000)\";\n\n\/**\n * A pooled DOM layer for labels. Text goes in through `textContent` only, so a\n * label is inert whatever it contains. Elements are reused and moved with a\n * transform, never created per frame.\n *\/\nexport class LabelLayer {\n  private readonly pool: HTMLDivElement[] = [];\n  private readonly clusters: HTMLDivElement[] = [];\n\n  constructor(\n    private readonly root: HTMLElement,\n    opts: { pool: number },\n  ) {\n    for (let i = 0; i < opts.pool; i++) {\n      const el = root.ownerDocument.createElement(\"div\");\n      el.style.cssText = LABEL_CSS;\n      el.setAttribute(\"data-fancy-graph-label\", \"\");\n      root.appendChild(el);\n      this.pool.push(el);\n    }\n  }\n\n  render(labels: PlacedLabel[]): void {\n    const used = Math.min(labels.length, this.pool.length);\n    for (let i = 0; i < used; i++) {\n      const l = labels[i];\n      const el = this.pool[i];\n      if (el.textContent !== l.text) el.textContent = l.text;\n      const id = l.id ?? String(l.index);\n      if (el.dataset.fancyGraphLabel !== id) el.dataset.fancyGraphLabel = id;\n      const state = l.state ?? \"normal\";\n      if (el.dataset.fancyGraphLabelState !== state) el.dataset.fancyGraphLabelState = state;\n      el.style.fontWeight = state === \"active\" ? \"700\" : \"400\";\n      el.style.transform = `translate(${l.x.toFixed(1)}px,${l.y.toFixed(1)}px)`;\n      if (el.style.display !== \"block\") el.style.display = \"block\";\n    }\n    for (let i = used; i < this.pool.length; i++) {\n      const el = this.pool[i];\n      if (el.style.display !== \"none\") {\n        el.style.display = \"none\";\n        el.dataset.fancyGraphLabel = \"\";\n      }\n    }\n  }\n\n  renderClusters(labels: ClusterLabel[]): void {\n    while (this.clusters.length < labels.length) {\n      const el = this.root.ownerDocument.createElement(\"div\");\n      el.style.cssText = CLUSTER_CSS;\n      this.root.appendChild(el);\n      this.clusters.push(el);\n    }\n    this.clusters.forEach((el, i) => {\n      const l = labels[i];\n      if (!l) {\n        el.style.display = \"none\";\n        return;\n      }\n      if (el.textContent !== l.text) el.textContent = l.text;\n      el.setAttribute(\"data-fancy-graph-cluster-label\", l.id);\n      el.style.color = l.color ?? \"var(--fancy-graph-label,#e8eef5)\";\n      el.style.transform = `translate(${l.x.toFixed(1)}px,${l.y.toFixed(1)}px) translate(-50%,-100%)`;\n      el.style.display = \"block\";\n    });\n  }\n\n  dispose(): void {\n    for (const el of [...this.pool, ...this.clusters]) el.remove();\n    this.pool.length = 0;\n    this.clusters.length = 0;\n  }\n}\n","type":"registry:lib","target":"components\/fancy\/lib\/labels.ts"},{"path":"components\/fancy\/lib\/layout\/force.ts","content":"import { seeded } from \"..\/random\";\nimport type { IndexedGraph } from \"..\/types\";\nimport { BarnesHutTree } from \".\/barnes-hut\";\nimport type { GraphLayoutStepper, LayoutEnv } from \".\/contract\";\n\nexport interface ForceLayoutOptions {\n  \/** Many-body strength; negative repels. Default -30. *\/\n  charge?: number;\n  \/** Rest length of a link. Default 30. *\/\n  linkDistance?: number;\n  \/** Multiplier on the per-link strength (1 \/ the smaller endpoint's link count). Default 1. *\/\n  linkStrength?: number;\n  \/** Barnes-Hut accuracy: 0 is exact, larger is faster. Default 0.9. *\/\n  theta?: number;\n  \/** Ticks until the layout settles. Default 300. *\/\n  iterations?: number;\n  \/** Fraction of velocity lost per tick. Default 0.4. *\/\n  velocityDecay?: number;\n  \/** Keep the centre of mass at the origin. Default true. *\/\n  center?: boolean;\n  \/** Ticks per frame. Default 1. *\/\n  ticksPerFrame?: number;\n  \/** Seed for the starting arrangement and for separating coincident nodes. Default 1. *\/\n  seed?: number;\n  \/** Force 2 or 3 dimensions regardless of the view. *\/\n  dimensions?: 2 | 3;\n  \/** Pull toward the centre of the node's group, so groups form visible clusters. 0 (default) is off; 0.1 to 0.3 is typical. *\/\n  groupPull?: number;\n  \/** The group key per node. Defaults to `node.group`. *\/\n  groupOf?: (index: number, graph: IndexedGraph) => string | undefined;\n  \/** A weak pull toward the origin, so unlinked nodes and small islands do not drift off. 0 (default) is off; 0.03 to 0.1 is typical. *\/\n  gravity?: number;\n}\n\nconst GOLDEN = Math.PI * (3 - Math.sqrt(5));\n\n\/**\n * A force-directed layout (velocity Verlet with alpha cooling, the model d3-force\n * popularised), written by hand: Barnes-Hut repulsion, link springs and\n * centring, in 2D or 3D.\n *\/\nexport function forceLayout(options: ForceLayoutOptions = {}): GraphLayoutStepper & { readonly alpha: number; reheat(alpha?: number): void } {\n  const o = {\n    charge: options.charge ?? -30,\n    linkDistance: options.linkDistance ?? 30,\n    linkStrength: options.linkStrength ?? 1,\n    theta: options.theta ?? 0.9,\n    iterations: Math.max(1, options.iterations ?? 300),\n    velocityDecay: options.velocityDecay ?? 0.4,\n    center: options.center ?? true,\n    ticksPerFrame: Math.max(1, Math.floor(options.ticksPerFrame ?? 1)),\n    seed: options.seed ?? 1,\n    groupPull: Math.max(0, options.groupPull ?? 0),\n    gravity: Math.max(0, options.gravity ?? 0),\n  };\n  const alphaMin = 0.001;\n  const alphaDecay = 1 - Math.pow(alphaMin, 1 \/ o.iterations);\n  let graph: IndexedGraph;\n  let dims: 2 | 3 = 2;\n  let n = 0;\n  let v = new Float64Array(0);\n  let pinned = new Uint8Array(0);\n  let count = new Float64Array(0);\n  let tree: BarnesHutTree;\n  let alpha = 1;\n  let ticks = 0;\n  let groupIdx = new Int32Array(0);\n  let groupCount = 0;\n  let groupSum = new Float64Array(0);\n  let rand = seeded(o.seed);\n  const jiggle = () => (rand() - 0.5) * 1e-6;\n\n  function tick(p: Float32Array) {\n    alpha += (0 - alpha) * alphaDecay;\n    ticks++;\n\n    \/\/ Links.\n    for (const l of graph.links) {\n      const a = l.a, b = l.b;\n      let x = p[b * 3] + v[b * 3] - p[a * 3] - v[a * 3] || jiggle();\n      let y = p[b * 3 + 1] + v[b * 3 + 1] - p[a * 3 + 1] - v[a * 3 + 1] || jiggle();\n      let z = dims === 3 ? p[b * 3 + 2] + v[b * 3 + 2] - p[a * 3 + 2] - v[a * 3 + 2] || jiggle() : 0;\n      let len = Math.sqrt(x * x + y * y + z * z);\n      const strength = (o.linkStrength \/ Math.min(count[a], count[b])) * alpha;\n      len = ((len - o.linkDistance) \/ len) * strength;\n      x *= len;\n      y *= len;\n      z *= len;\n      const bias = count[a] \/ (count[a] + count[b]);\n      v[b * 3] -= x * bias;\n      v[b * 3 + 1] -= y * bias;\n      v[b * 3 + 2] -= z * bias;\n      v[a * 3] += x * (1 - bias);\n      v[a * 3 + 1] += y * (1 - bias);\n      v[a * 3 + 2] += z * (1 - bias);\n    }\n\n    \/\/ Many-body, Barnes-Hut.\n    tree.build(p, n);\n    const theta2 = o.theta * o.theta;\n    const k = tree.arity;\n    const stack = new Int32Array(Math.max(64, tree.count));\n    for (let i = 0; i < n; i++) {\n      const px = p[i * 3], py = p[i * 3 + 1], pz = p[i * 3 + 2];\n      let fx = 0, fy = 0, fz = 0;\n      let sp = 0;\n      stack[sp++] = 0;\n      while (sp > 0) {\n        const c = stack[--sp];\n        const m = tree.mass[c];\n        if (m === 0) continue;\n        if (tree.leaf[c]) {\n          for (let b = tree.body[c]; b >= 0; b = tree.next[b]) {\n            if (b === i) continue;\n            let dx = p[b * 3] - px, dy = p[b * 3 + 1] - py, dz = dims === 3 ? p[b * 3 + 2] - pz : 0;\n            let d2 = dx * dx + dy * dy + dz * dz;\n            if (d2 === 0) {\n              dx = jiggle();\n              dy = jiggle();\n              if (dims === 3) dz = jiggle();\n              d2 = dx * dx + dy * dy + dz * dz;\n            }\n            if (d2 < 1) d2 = Math.sqrt(d2);\n            const f = (o.charge * alpha) \/ d2;\n            fx += dx * f;\n            fy += dy * f;\n            fz += dz * f;\n          }\n          continue;\n        }\n        const dx = tree.mx[c] \/ m - px, dy = tree.my[c] \/ m - py, dz = dims === 3 ? tree.mz[c] \/ m - pz : 0;\n        let d2 = dx * dx + dy * dy + dz * dz;\n        const w = tree.half[c] * 2;\n        if (d2 > 0 && (w * w) \/ d2 < theta2) {\n          if (d2 < 1) d2 = Math.sqrt(d2);\n          const f = (o.charge * alpha * m) \/ d2;\n          fx += dx * f;\n          fy += dy * f;\n          fz += dz * f;\n          continue;\n        }\n        if (sp + k > stack.length) continue;\n        for (let q = 0; q < k; q++) {\n          const ch = tree.child[c * k + q];\n          if (ch >= 0) stack[sp++] = ch;\n        }\n      }\n      v[i * 3] += fx;\n      v[i * 3 + 1] += fy;\n      v[i * 3 + 2] += fz;\n    }\n\n    \/\/ Group pull: toward the group's centroid.\n    if (o.groupPull > 0 && groupCount) {\n      groupSum.fill(0);\n      for (let i = 0; i < n; i++) {\n        const k = groupIdx[i];\n        if (k < 0) continue;\n        groupSum[k * 4] += p[i * 3];\n        groupSum[k * 4 + 1] += p[i * 3 + 1];\n        groupSum[k * 4 + 2] += p[i * 3 + 2];\n        groupSum[k * 4 + 3]++;\n      }\n      const s = o.groupPull * alpha;\n      for (let i = 0; i < n; i++) {\n        const k = groupIdx[i];\n        if (k < 0 || groupSum[k * 4 + 3] < 2) continue;\n        const c = groupSum[k * 4 + 3];\n        v[i * 3] += (groupSum[k * 4] \/ c - p[i * 3]) * s;\n        v[i * 3 + 1] += (groupSum[k * 4 + 1] \/ c - p[i * 3 + 1]) * s;\n        if (dims === 3) v[i * 3 + 2] += (groupSum[k * 4 + 2] \/ c - p[i * 3 + 2]) * s;\n      }\n    }\n\n    \/\/ Gravity: toward the origin.\n    if (o.gravity > 0) {\n      const s = o.gravity * alpha;\n      for (let i = 0; i < n; i++) {\n        v[i * 3] -= p[i * 3] * s;\n        v[i * 3 + 1] -= p[i * 3 + 1] * s;\n        if (dims === 3) v[i * 3 + 2] -= p[i * 3 + 2] * s;\n      }\n    }\n\n    \/\/ Integrate.\n    for (let i = 0; i < n; i++) {\n      if (pinned[i]) {\n        v[i * 3] = v[i * 3 + 1] = v[i * 3 + 2] = 0;\n        continue;\n      }\n      for (let d = 0; d < 3; d++) {\n        v[i * 3 + d] *= 1 - o.velocityDecay;\n        p[i * 3 + d] += v[i * 3 + d];\n      }\n      if (dims === 2) p[i * 3 + 2] = 0;\n    }\n\n    if (o.center && n) {\n      let sx = 0, sy = 0, sz = 0;\n      for (let i = 0; i < n; i++) {\n        sx += p[i * 3];\n        sy += p[i * 3 + 1];\n        sz += p[i * 3 + 2];\n      }\n      sx \/= n;\n      sy \/= n;\n      sz = dims === 3 ? sz \/ n : 0;\n      for (let i = 0; i < n; i++) {\n        if (pinned[i]) continue;\n        p[i * 3] -= sx;\n        p[i * 3 + 1] -= sy;\n        p[i * 3 + 2] -= sz;\n      }\n    }\n  }\n\n  const layout = {\n    name: \"force\",\n    get alpha() {\n      return alpha;\n    },\n    reheat(a = 1) {\n      alpha = a;\n      ticks = 0;\n    },\n    init(g: IndexedGraph, p: Float32Array, env: LayoutEnv) {\n      graph = g;\n      dims = options.dimensions ?? env.dimensions;\n      n = g.nodes.length;\n      v = new Float64Array(n * 3);\n      pinned = new Uint8Array(n);\n      count = new Float64Array(n);\n      for (const l of g.links) {\n        count[l.a]++;\n        count[l.b]++;\n      }\n      tree = new BarnesHutTree(dims);\n      const keys = new Map<string, number>();\n      groupIdx = new Int32Array(n).fill(-1);\n      if (o.groupPull > 0)\n        for (let i = 0; i < n; i++) {\n          const k = options.groupOf ? options.groupOf(i, g) : g.nodes[i].group;\n          if (k === undefined || k === \"\") continue;\n          if (!keys.has(k)) keys.set(k, keys.size);\n          groupIdx[i] = keys.get(k)!;\n        }\n      groupCount = keys.size;\n      groupSum = new Float64Array(groupCount * 4);\n      alpha = 1;\n      ticks = 0;\n      rand = seeded(o.seed);\n      const spin = rand() * Math.PI * 2;\n      for (let i = 0; i < n; i++) {\n        const node = g.nodes[i];\n        pinned[i] = node.fixed ? 1 : 0;\n        if (Number.isFinite(node.x) && Number.isFinite(node.y)) {\n          p[i * 3] = node.x!;\n          p[i * 3 + 1] = node.y!;\n          p[i * 3 + 2] = dims === 3 && Number.isFinite(node.z) ? node.z! : 0;\n          continue;\n        }\n        if (dims === 2) {\n          const r = 10 * Math.sqrt(0.5 + i);\n          const a = i * GOLDEN + spin;\n          p[i * 3] = r * Math.cos(a);\n          p[i * 3 + 1] = r * Math.sin(a);\n          p[i * 3 + 2] = 0;\n        } else {\n          const r = 10 * Math.cbrt(0.5 + i);\n          const y = 1 - (2 * (i + 0.5)) \/ Math.max(1, n);\n          const ring = Math.sqrt(Math.max(0, 1 - y * y));\n          const a = i * GOLDEN + spin;\n          p[i * 3] = r * ring * Math.cos(a);\n          p[i * 3 + 1] = r * y;\n          p[i * 3 + 2] = r * ring * Math.sin(a);\n        }\n      }\n    },\n    step(p: Float32Array) {\n      if (alpha < alphaMin || ticks >= o.iterations) return false;\n      for (let t = 0; t < o.ticksPerFrame && ticks < o.iterations; t++) tick(p);\n      return alpha >= alphaMin && ticks < o.iterations;\n    },\n  };\n  return layout;\n}\n","type":"registry:lib","target":"components\/fancy\/lib\/layout\/force.ts"},{"path":"components\/fancy\/lib\/layout\/static.ts","content":"import type { IndexedGraph } from \"..\/types\";\nimport type { GraphLayoutFunction } from \".\/contract\";\n\nconst GOLDEN = Math.PI * (3 - Math.sqrt(5));\n\nfunction bestConnected(g: IndexedGraph): number {\n  let best = 0;\n  for (let i = 1; i < g.nodes.length; i++) if (g.degree[i] > g.degree[best]) best = i;\n  return best;\n}\n\nexport interface RadialLayoutOptions {\n  \/** Id of the centre node. Defaults to the best-connected node. *\/\n  root?: string;\n  \/** Distance between rings. Default 80. *\/\n  ringGap?: number;\n}\n\n\/**\n * Rings by distance from a root (breadth-first). Each subtree gets an angular\n * wedge proportional to its size, so branches stay together. Nodes unreachable\n * from the root sit on one more ring outside. In 3D the rings are spherical\n * shells and each depth is spread over its shell.\n *\/\nexport function radialLayout(options: RadialLayoutOptions = {}): GraphLayoutFunction {\n  const gap = options.ringGap ?? 80;\n  return (g, p, env) => {\n    const n = g.nodes.length;\n    if (!n) return;\n    const root = options.root !== undefined && g.index.has(options.root) ? g.index.get(options.root)! : bestConnected(g);\n    const depth = new Int32Array(n).fill(-1);\n    const parent = new Int32Array(n).fill(-1);\n    const order: number[] = [root];\n    depth[root] = 0;\n    for (let h = 0; h < order.length; h++) {\n      const u = order[h];\n      const next = [...g.neighbors[u]].sort((a, b) => a - b);\n      for (const w of next)\n        if (depth[w] < 0) {\n          depth[w] = depth[u] + 1;\n          parent[w] = u;\n          order.push(w);\n        }\n    }\n    let maxDepth = 0;\n    for (const u of order) maxDepth = Math.max(maxDepth, depth[u]);\n    const outer: number[] = [];\n    for (let i = 0; i < n; i++) if (depth[i] < 0) outer.push(i);\n\n    if (env.dimensions === 3) {\n      const byDepth = new Map<number, number[]>();\n      for (const u of order) byDepth.set(depth[u], [...(byDepth.get(depth[u]) ?? []), u]);\n      if (outer.length) byDepth.set(maxDepth + 1, outer);\n      for (const [d, list] of byDepth) {\n        const r = d * gap;\n        list.forEach((u, k) => {\n          if (d === 0) {\n            p.set([0, 0, 0], u * 3);\n            return;\n          }\n          const y = 1 - (2 * (k + 0.5)) \/ list.length;\n          const ring = Math.sqrt(Math.max(0, 1 - y * y));\n          const a = k * GOLDEN;\n          p[u * 3] = r * ring * Math.cos(a);\n          p[u * 3 + 1] = r * y;\n          p[u * 3 + 2] = r * ring * Math.sin(a);\n        });\n      }\n      return;\n    }\n\n    \/\/ Subtree sizes, leaves first.\n    const children: number[][] = Array.from({ length: n }, () => []);\n    for (const u of order) if (parent[u] >= 0) children[parent[u]].push(u);\n    const size = new Float64Array(n);\n    for (let h = order.length - 1; h >= 0; h--) {\n      const u = order[h];\n      size[u] = 1 + children[u].reduce((s, c) => s + size[c], 0);\n    }\n    const start = new Float64Array(n);\n    const span = new Float64Array(n);\n    span[root] = Math.PI * 2;\n    for (const u of order) {\n      let a = start[u];\n      for (const c of children[u]) {\n        start[c] = a;\n        span[c] = (span[u] * size[c]) \/ Math.max(1, size[u] - 1);\n        a += span[c];\n      }\n      const r = depth[u] * gap;\n      const mid = start[u] + span[u] \/ 2;\n      p[u * 3] = u === root ? 0 : r * Math.cos(mid);\n      p[u * 3 + 1] = u === root ? 0 : r * Math.sin(mid);\n      p[u * 3 + 2] = 0;\n    }\n    const r = (maxDepth + 1) * gap;\n    outer.forEach((u, k) => {\n      const a = (k \/ outer.length) * Math.PI * 2;\n      p[u * 3] = r * Math.cos(a);\n      p[u * 3 + 1] = r * Math.sin(a);\n      p[u * 3 + 2] = 0;\n    });\n  };\n}\n\nexport interface HierarchyLayoutOptions {\n  \/** `\"down\"` (default): roots on top. `\"right\"`: roots on the left. *\/\n  direction?: \"down\" | \"right\";\n  \/** Distance between layers. Default 80. *\/\n  layerGap?: number;\n  \/** Minimum distance between neighbours in a layer. Default 40. *\/\n  nodeGap?: number;\n  \/** Barycentre sweeps to reduce crossings. Default 4. *\/\n  sweeps?: number;\n}\n\n\/**\n * Layered (Sugiyama-style) placement for directed graphs: links point\n * source \u2192 target. Roots are nodes nothing points at (or, in a cycle, the\n * best-connected node); a node's layer is its breadth-first depth from the\n * roots, so cycles cannot loop. Each layer is then ordered by the mean position\n * of its parents to keep children under them, and spaced by `nodeGap`.\n *\/\nexport function hierarchyLayout(options: HierarchyLayoutOptions = {}): GraphLayoutFunction {\n  const layerGap = options.layerGap ?? 80;\n  const nodeGap = options.nodeGap ?? 40;\n  const sweeps = options.sweeps ?? 4;\n  const right = options.direction === \"right\";\n  return (g, p) => {\n    const n = g.nodes.length;\n    if (!n) return;\n    const out: number[][] = Array.from({ length: n }, () => []);\n    const indeg = new Int32Array(n);\n    for (const l of g.links) {\n      out[l.a].push(l.b);\n      indeg[l.b]++;\n    }\n    const layer = new Int32Array(n).fill(-1);\n    const queue: number[] = [];\n    const seed = (i: number) => {\n      layer[i] = 0;\n      queue.push(i);\n    };\n    for (let i = 0; i < n; i++) if (indeg[i] === 0) seed(i);\n    for (;;) {\n      for (let h = 0; h < queue.length; h++) {\n        const u = queue[h];\n        for (const w of out[u])\n          if (layer[w] < 0) {\n            layer[w] = layer[u] + 1;\n            queue.push(w);\n          }\n      }\n      \/\/ Anything left is in a cycle with no entry: start from its best-connected node.\n      let rest = -1;\n      for (let i = 0; i < n; i++) if (layer[i] < 0 && (rest < 0 || g.degree[i] > g.degree[rest])) rest = i;\n      if (rest < 0) break;\n      seed(rest);\n    }\n\n    const layers: number[][] = [];\n    for (const u of queue) (layers[layer[u]] ??= []).push(u);\n    const pos = new Float64Array(n);\n    for (const list of layers) list.forEach((u, k) => (pos[u] = k));\n    const parents: number[][] = Array.from({ length: n }, () => []);\n    for (const l of g.links) if (layer[l.a] < layer[l.b]) parents[l.b].push(l.a);\n    for (let s = 0; s < sweeps; s++)\n      for (let d = 1; d < layers.length; d++) {\n        const list = layers[d];\n        const bary = new Map<number, number>();\n        for (const u of list) bary.set(u, parents[u].length ? parents[u].reduce((a, q) => a + pos[q], 0) \/ parents[u].length : pos[u]);\n        list.sort((a, b) => bary.get(a)! - bary.get(b)! || a - b);\n        list.forEach((u, k) => (pos[u] = k));\n      }\n\n    for (let d = 0; d < layers.length; d++) {\n      const list = layers[d];\n      const width = (list.length - 1) * nodeGap;\n      list.forEach((u, k) => {\n        const along = k * nodeGap - width \/ 2;\n        const across = d * layerGap;\n        p[u * 3] = right ? across : along;\n        p[u * 3 + 1] = right ? along : across;\n        p[u * 3 + 2] = 0;\n      });\n    }\n  };\n}\n","type":"registry:lib","target":"components\/fancy\/lib\/layout\/static.ts"},{"path":"components\/fancy\/lib\/random.ts","content":"\/** A stable 0..1 hash of a string (FNV-1a, 32-bit). Layouts use it so a graph looks the same on every load. *\/\nexport function hash01(s: string): number {\n  let h = 0x811c9dc5;\n  for (let i = 0; i < s.length; i++) {\n    h ^= s.charCodeAt(i);\n    h = Math.imul(h, 0x01000193);\n  }\n  return (h >>> 0) \/ 4294967296;\n}\n\n\/** A seeded 0..1 generator (mulberry32). Layouts never call Math.random. *\/\nexport function seeded(seed: number): () => number {\n  let a = Math.floor((seed % 1) * 4294967296 + Math.floor(seed) * 2654435761) >>> 0;\n  return () => {\n    a = (a + 0x6d2b79f5) | 0;\n    let t = Math.imul(a ^ (a >>> 15), 1 | a);\n    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;\n    return ((t ^ (t >>> 14)) >>> 0) \/ 4294967296;\n  };\n}\n","type":"registry:lib","target":"components\/fancy\/lib\/random.ts"},{"path":"components\/fancy\/lib\/layout\/barnes-hut.ts","content":"\/**\n * A Barnes-Hut tree over flat positions: a quadtree in 2D, an octree in 3D.\n * Typed arrays throughout and no per-node allocation, so a rebuild every tick\n * stays cheap at several thousand nodes. Written for this package; nothing\n * third-party.\n *\/\nconst MAX_DEPTH = 24;\n\nexport class BarnesHutTree {\n  private k: number;\n  private cap = 0;\n  count = 0;\n  child = new Int32Array(0);\n  body = new Int32Array(0);\n  leaf = new Uint8Array(0);\n  parent = new Int32Array(0);\n  depth = new Uint8Array(0);\n  cx = new Float64Array(0);\n  cy = new Float64Array(0);\n  cz = new Float64Array(0);\n  half = new Float64Array(0);\n  mass = new Float64Array(0);\n  mx = new Float64Array(0);\n  my = new Float64Array(0);\n  mz = new Float64Array(0);\n  \/** Bodies sharing a leaf at MAX_DEPTH (coincident nodes), as a linked list. *\/\n  next = new Int32Array(0);\n\n  constructor(private readonly dims: 2 | 3) {\n    this.k = dims === 3 ? 8 : 4;\n  }\n\n  private grow(min: number) {\n    if (min <= this.cap) return;\n    const cap = Math.max(min, this.cap * 2, 64);\n    const g = <T extends Int32Array | Uint8Array | Float64Array>(a: T, size: number, C: new (n: number) => T): T => {\n      const b = new C(size);\n      b.set(a);\n      return b;\n    };\n    this.child = g(this.child, cap * this.k, Int32Array);\n    this.body = g(this.body, cap, Int32Array);\n    this.leaf = g(this.leaf, cap, Uint8Array);\n    this.parent = g(this.parent, cap, Int32Array);\n    this.depth = g(this.depth, cap, Uint8Array);\n    for (const key of [\"cx\", \"cy\", \"cz\", \"half\", \"mass\", \"mx\", \"my\", \"mz\"] as const) this[key] = g(this[key], cap, Float64Array);\n    this.cap = cap;\n  }\n\n  private cell(cx: number, cy: number, cz: number, half: number, parent: number, depth: number): number {\n    if (this.count >= this.cap) this.grow(this.count + 1);\n    const c = this.count++;\n    this.cx[c] = cx;\n    this.cy[c] = cy;\n    this.cz[c] = cz;\n    this.half[c] = half;\n    this.parent[c] = parent;\n    this.depth[c] = depth;\n    this.leaf[c] = 1;\n    this.body[c] = -1;\n    this.child.fill(-1, c * this.k, c * this.k + this.k);\n    return c;\n  }\n\n  private octant(c: number, p: Float32Array, i: number): number {\n    let o = (p[i * 3] >= this.cx[c] ? 1 : 0) | (p[i * 3 + 1] >= this.cy[c] ? 2 : 0);\n    if (this.dims === 3 && p[i * 3 + 2] >= this.cz[c]) o |= 4;\n    return o;\n  }\n\n  private childCell(c: number, o: number): number {\n    const h = this.half[c] \/ 2;\n    const cx = this.cx[c] + (o & 1 ? h : -h);\n    const cy = this.cy[c] + (o & 2 ? h : -h);\n    const cz = this.dims === 3 ? this.cz[c] + (o & 4 ? h : -h) : 0;\n    const id = this.cell(cx, cy, cz, h, c, this.depth[c] + 1);\n    this.child[c * this.k + o] = id;\n    return id;\n  }\n\n  \/** Rebuilds the tree over `n` bodies and computes each cell's mass and centre of mass. *\/\n  build(p: Float32Array, n: number, weight?: Float64Array) {\n    this.count = 0;\n    if (this.next.length < n) this.next = new Int32Array(n);\n    this.next.fill(-1, 0, n);\n    let minX = Infinity, minY = Infinity, minZ = Infinity, maxX = -Infinity, maxY = -Infinity, maxZ = -Infinity;\n    for (let i = 0; i < n; i++) {\n      const x = p[i * 3], y = p[i * 3 + 1], z = p[i * 3 + 2];\n      if (x < minX) minX = x;\n      if (x > maxX) maxX = x;\n      if (y < minY) minY = y;\n      if (y > maxY) maxY = y;\n      if (z < minZ) minZ = z;\n      if (z > maxZ) maxZ = z;\n    }\n    if (!n) return;\n    const half = Math.max(1, maxX - minX, maxY - minY, this.dims === 3 ? maxZ - minZ : 0) \/ 2 + 1e-3;\n    this.grow(n * 2 + 1);\n    this.cell((minX + maxX) \/ 2, (minY + maxY) \/ 2, this.dims === 3 ? (minZ + maxZ) \/ 2 : 0, half, -1, 0);\n\n    for (let i = 0; i < n; i++) {\n      let c = 0;\n      for (;;) {\n        if (this.leaf[c]) {\n          const b = this.body[c];\n          if (b < 0) {\n            this.body[c] = i;\n            break;\n          }\n          if (this.depth[c] >= MAX_DEPTH) {\n            this.next[i] = this.next[b];\n            this.next[b] = i;\n            break;\n          }\n          \/\/ Split: push the resident body down one level, then keep descending with i.\n          this.leaf[c] = 0;\n          this.body[c] = -1;\n          const ob = this.octant(c, p, b);\n          const nc = this.childCell(c, ob);\n          this.body[nc] = b;\n          \/\/ b may carry a chain of coincident bodies; they move together.\n          continue;\n        }\n        const o = this.octant(c, p, i);\n        const ch = this.child[c * this.k + o];\n        if (ch < 0) {\n          const nc = this.childCell(c, o);\n          this.body[nc] = i;\n          break;\n        }\n        c = ch;\n      }\n    }\n\n    \/\/ Cells are created after their parent, so a reverse sweep accumulates bottom-up.\n    this.mass.fill(0, 0, this.count);\n    this.mx.fill(0, 0, this.count);\n    this.my.fill(0, 0, this.count);\n    this.mz.fill(0, 0, this.count);\n    for (let c = this.count - 1; c >= 0; c--) {\n      if (this.leaf[c]) {\n        for (let b = this.body[c]; b >= 0; b = this.next[b]) {\n          const w = weight ? weight[b] : 1;\n          this.mass[c] += w;\n          this.mx[c] += p[b * 3] * w;\n          this.my[c] += p[b * 3 + 1] * w;\n          this.mz[c] += p[b * 3 + 2] * w;\n        }\n      }\n      const par = this.parent[c];\n      if (par >= 0) {\n        this.mass[par] += this.mass[c];\n        this.mx[par] += this.mx[c];\n        this.my[par] += this.my[c];\n        this.mz[par] += this.mz[c];\n      }\n    }\n  }\n\n  get arity() {\n    return this.k;\n  }\n}\n","type":"registry:lib","target":"components\/fancy\/lib\/layout\/barnes-hut.ts"}]}