Skip to content

Local code intelligence for developers and AI agents. Connect code, docs and infrastructure in a persistent graph, with CBM Lens, MCP tools, agent integrations and change-aware test selection.

fix(ui): keep the galaxy root pinned, marked and framed

Bernhard Jackiewicz0e8b2c17ba59
diff --git a/graph-ui/src/galaxy/GalaxyPanel.stability.test.tsx b/graph-ui/src/galaxy/GalaxyPanel.stability.test.tsx
index b83a9fd6c..58b10f499 100644
--- a/graph-ui/src/galaxy/GalaxyPanel.stability.test.tsx
+++ b/graph-ui/src/galaxy/GalaxyPanel.stability.test.tsx
@@ -11,11 +11,11 @@ import { afterEach, beforeEach, expect, it, vi } from 'vitest';
import GalaxyPanel from './GalaxyPanel';
import type { GraphData, GraphEdge, GraphNode } from './types';
-const scene = vi.hoisted(() => ({ mounts: 0, unmounts: 0, renders: 0 }));
+const scene = vi.hoisted(() => ({ mounts: 0, unmounts: 0, renders: 0, roots: undefined as ReadonlySet<number> | undefined }));
vi.mock('./GraphScene', async importOriginal => ({
...await importOriginal<typeof import('./GraphScene')>(),
- GraphScene: ({ data }: { data: GraphData }) => {
- scene.renders += 1;
+ GraphScene: ({ data, rootIds }: { data: GraphData; rootIds?: ReadonlySet<number> }) => {
+ scene.renders += 1; scene.roots = rootIds;
useEffect(() => { scene.mounts += 1; return () => { scene.unmounts += 1; }; }, []);
return <output data-testid="scene-nodes">{data.nodes.length}</output>;
},
@@ -82,6 +82,9 @@ it('keeps one scene mounted through selection and expansion and fits once per se
});
expect(scene.mounts).toBe(1); expect(scene.unmounts).toBe(0);
expect(seam().fits).toBe(fitsBefore + 1);
+ // The root is marked, sits at the origin and the fit is centred on it.
+ expect([...scene.roots ?? []]).toEqual([1]);
+ expect(seam().lastFit?.center?.map(value => value + 0)).toEqual([0, 0, 0]);
const expand = [...host.querySelectorAll('button')].find(button => button.textContent === 'Expand +1')!;
await act(async () => expand.click());
diff --git a/graph-ui/src/galaxy/GalaxyPanel.tsx b/graph-ui/src/galaxy/GalaxyPanel.tsx
index afe25f54f..289446ef5 100644
--- a/graph-ui/src/galaxy/GalaxyPanel.tsx
+++ b/graph-ui/src/galaxy/GalaxyPanel.tsx
@@ -424,6 +424,8 @@ export interface AtlasGalaxySeam {
depth: number;
normal: [number, number, number];
up: [number, number, number];
+ /** Worauf die Kamera sieht: in einem Scope die Wurzel. */
+ center?: [number, number, number];
} | undefined;
/** Genau der Satz, der im Kopf steht. */
headline: string;
@@ -1511,7 +1513,18 @@ export default function GalaxyPanel(props: GalaxyPanelProps): JSX.Element {
if (nodes.length === 0) {
return;
}
- const target = computeFitTarget(nodes, aspect);
+ /*
+ * Die Wurzel steht in der Mitte (Review-Befund G4). Gerahmt wird um sie
+ * herum, weit genug, dass auch der fernste Knoten passt; ohne das stand
+ * die Mitte der Wolke im Bild und die Wurzel irgendwo darin.
+ */
+ const roots = fitScope === undefined ? [] : nodes.filter((node) => scope.result?.roots.has(node.id));
+ const center = roots.length === 0 ? undefined : {
+ x: roots.reduce((sum, node) => sum + node.x, 0) / roots.length,
+ y: roots.reduce((sum, node) => sum + node.y, 0) / roots.length,
+ z: roots.reduce((sum, node) => sum + node.z, 0) / roots.length,
+ };
+ const target = computeFitTarget(nodes, aspect, center);
if (target === null) {
return;
}
@@ -1531,8 +1544,11 @@ export default function GalaxyPanel(props: GalaxyPanelProps): JSX.Element {
depth: fit.depth,
normal: [fit.normal.x, fit.normal.y, fit.normal.z],
up: [fit.up.x, fit.up.y, fit.up.z],
+ center: [fit.center.x, fit.center.y, fit.center.z],
};
- }, [visible, mode, projection, picture, aspect, requestedFit, ownFit, coverageShadow, fitRequest, props.workspaceExpanded]);
+ // `scope.result` folgt dem Bild und loest selbst keine Einpassung aus.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [visible, mode, projection, picture, aspect, requestedFit, ownFit, coverageShadow, fitRequest, props.workspaceExpanded, fitScope]);
const [backgroundCleared, setBackgroundCleared] = useState(false);
useEffect(() => {
@@ -2421,6 +2437,7 @@ export default function GalaxyPanel(props: GalaxyPanelProps): JSX.Element {
separateNodes={mode === 'galaxy' && sceneScoped}
onRenderBusyChange={setSpacingBusy}
idleRotation={mode === 'galaxy' && !sceneScoped}
+ rootIds={mode === 'galaxy' && sceneScoped ? scope.result?.roots : undefined}
data={shown}
display={display}
highlightedIds={scope.scope && scope.depth > 1 ? null : highlighted}
diff --git a/graph-ui/src/galaxy/GraphScene.tsx b/graph-ui/src/galaxy/GraphScene.tsx
index 0167d9817..2593a7967 100644
--- a/graph-ui/src/galaxy/GraphScene.tsx
+++ b/graph-ui/src/galaxy/GraphScene.tsx
@@ -92,12 +92,16 @@
* Blickrichtung zurueck oder vor, solange der Leser sie nicht bewegt hat.
* 16. Neu (Review-Call 2026-10-02): die OrbitControls zoomen zum Mauszeiger
* (`zoomToCursor`), nicht mehr in die Bildmitte.
+ * 17. Neu (Review-Call 2026-10-02): die Prop `rootIds`. Die Wurzeln eines
+ * Scopes bekommen einen Ring und einen Namen, der immer zu sehen ist, und
+ * die Trennung auf dem Schirm schiebt sie nie weg. Ohne die Prop zeichnet
+ * die Szene wie vorher.
*/
import { useState, useRef, useEffect, useCallback, useMemo } from 'react';
import type { JSX, ReactNode, RefObject } from 'react';
import { Canvas, useThree, useFrame } from '@react-three/fiber';
-import { OrbitControls, OrthographicCamera } from '@react-three/drei';
+import { Html, OrbitControls, OrthographicCamera } from '@react-three/drei';
import type { OrbitControls as OrbitControlsImpl } from 'three-stdlib';
import { EffectComposer, Bloom } from '@react-three/postprocessing';
import * as THREE from 'three';
@@ -402,6 +406,33 @@ export function FitContainment({
return null;
}
+/*
+ * Aenderung 17: die Wurzel ist zu finden.
+ *
+ * Nach einem Expand stand die Wurzel als ein Punkt unter neunzig, ohne Namen,
+ * und die Trennung auf dem Schirm hatte sie aus der Mitte geschoben
+ * (Review-Befund G4). Der Ring ist DOM wie der Ring der Hierarchie (Html aus
+ * drei), also kein Neubau der Puffer, und sein Name steht immer da, nicht erst
+ * bei Fokus. Ein Ordner mit hundert Wurzeln bekommt keine hundert Ringe: ueber
+ * der Grenze markiert die Szene nichts und schiebt wie vorher.
+ */
+export const ROOT_MARKER_LIMIT = 12;
+
+function RootMarkers({ nodes }: { nodes: readonly GraphNode[] }): JSX.Element {
+ return (
+ <>
+ {nodes.map((node) => (
+ <Html key={node.id} position={[node.x, node.y, node.z]} zIndexRange={[10, 0]} style={{ pointerEvents: 'none' }}>
+ <span className="atlas-galaxy-root-marker" data-testid="atlas-galaxy-root-marker" data-qn={node.qualified_name ?? node.name}>
+ <i aria-hidden="true" />
+ <b>{node.name}</b>
+ </span>
+ </Html>
+ ))}
+ </>
+ );
+}
+
/* Bildratenmesser und Bildratendeckel (W10) */
/**
@@ -780,6 +811,8 @@ interface GraphSceneProps {
labelDistanceFactor?: number;
/* Bilder je Sekunde, hoechstens. 0 heisst: kein Deckel. */
frameCap?: number;
+ /* Die Wurzeln des gewaehlten Scopes (Aenderung 17). */
+ rootIds?: ReadonlySet<number>;
}
export type { CameraTarget };
@@ -818,6 +851,7 @@ export function GraphScene({
drawEdges = true,
labelDistanceFactor = 0,
frameCap = 0,
+ rootIds,
}: GraphSceneProps) {
const [hovered, setHovered] = useState<GraphNode | null>(null);
const [hoveredShadow, setHoveredShadow] = useState<CoverageShadowNode | null>(null);
@@ -837,6 +871,12 @@ export function GraphScene({
const nodes = renderedNodes.slice(data.nodes.length) as CoverageShadowNode[];
return { ...coverageShadow, nodes, nodeById: new Map(nodes.map(node => [node.id, node])) };
}, [coverageShadow, renderedNodes, sceneNodes, data.nodes.length]);
+ const markedRoots = rootIds !== undefined && rootIds.size > 0 && rootIds.size <= ROOT_MARKER_LIMIT ? rootIds : undefined;
+ const rootNodes = useMemo(() => markedRoots ? renderedCode.filter((node) => markedRoots.has(node.id)) : [],
+ [markedRoots, renderedCode]);
+ // Der Ring traegt den Namen der Wurzel; ein zweiter Name darunter waere doppelt.
+ const labelNodes = useMemo(() => markedRoots ? renderedCode.filter((node) => !markedRoots.has(node.id)) : renderedCode,
+ [markedRoots, renderedCode]);
const onCodeHover = useCallback((node: GraphNode | null) => {
setHovered(node);
if (node) setHoveredShadow(null);
@@ -966,7 +1006,7 @@ export function GraphScene({
/>
{showLabels && (
<NodeLabels
- nodes={renderedCode}
+ nodes={labelNodes}
highlightedIds={highlightedIds}
worldFontSize={labelWorldFontSize}
maxTextWidth={labelMaxTextWidth}
@@ -975,6 +1015,7 @@ export function GraphScene({
/>
)}
{landmarks && <HaloLayer nodes={renderedCode} />}
+ {rootNodes.length > 0 && <RootMarkers nodes={rootNodes} />}
{renderedShadow && renderedShadow.nodes.length > 0 && <group>
{drawEdges && <CoverageShadowEdges shadow={renderedShadow} brightness={display.edgeBrightness} />}
@@ -989,7 +1030,8 @@ export function GraphScene({
<CameraAnimator target={cameraTarget} controlsRef={controlsRef} flat={flat} />
<FitContainment nodes={renderedNodes} target={cameraTarget} controlsRef={controlsRef} moved={moved}
enabled={separateNodes && !flat} />
- {separateNodes && <ScreenNodeSeparation nodes={sceneNodes} active={active} onChange={receiveSeparation} onBusyChange={onRenderBusyChange} />}
+ {separateNodes && <ScreenNodeSeparation nodes={sceneNodes} active={active} onChange={receiveSeparation} onBusyChange={onRenderBusyChange}
+ pinned={markedRoots} />}
<FitProbe nodes={renderedNodes} />
<IdleAutoRotate controlsRef={controlsRef} enabled={!flat && idleRotation && !separateNodes} />
<FrameRateMeter nodes={sceneNodes.length} edges={data.edges.length + (coverageShadow?.edges.length ?? 0)} cap={frameCap} />
@@ -1075,8 +1117,10 @@ export function computeFrameTarget(box: FrameBox, aspect: number): CameraTarget
export function computeFitTarget(
nodes: readonly { x: number; y: number; z: number }[],
aspect: number,
+ /* Der Punkt in der Bildmitte, etwa die Wurzel eines Scopes (Review-Befund G4). */
+ center?: { x: number; y: number; z: number },
): (CameraTarget & { fit: CameraFit }) | null {
- const fit = fitCamera(nodes, GRAPH_CAMERA_FOV, aspect);
+ const fit = fitCamera(nodes, GRAPH_CAMERA_FOV, aspect, undefined, center);
if (fit === null) {
return null;
}
diff --git a/graph-ui/src/galaxy/ScreenNodeSeparation.tsx b/graph-ui/src/galaxy/ScreenNodeSeparation.tsx
index 2f8314d4e..3b76d7778 100644
--- a/graph-ui/src/galaxy/ScreenNodeSeparation.tsx
+++ b/graph-ui/src/galaxy/ScreenNodeSeparation.tsx
@@ -5,18 +5,20 @@ import type { GraphNode } from './types';
import { separateProjectedNodes } from './projected-node-spacing';
/** Arrange a new graph or viewport after its camera fit settles. Once committed,
- * positions stay fixed while zooming, panning or orbiting the same graph. */
-export function ScreenNodeSeparation({ nodes, active, onChange, onBusyChange }: {
+ * positions stay fixed while zooming, panning or orbiting the same graph.
+ * Pinned nodes are never moved, so a marked scope root stays where it is. */
+export function ScreenNodeSeparation({ nodes, active, onChange, onBusyChange, pinned }: {
nodes: GraphNode[];
active: boolean;
+ pinned?: ReadonlySet<number>;
onChange: (source: GraphNode[], positioned: GraphNode[]) => void;
onBusyChange?: (busy: boolean) => void;
}) {
const { camera, size, invalidate } = useThree();
const state = useRef({ matrix: new Matrix4(), projection: new Matrix4(), source: undefined as GraphNode[] | undefined,
width: 0, height: 0, changedAt: 0, dirty: true, queued: 0, busy: false });
- const callbacks = useRef({ onChange, onBusyChange });
- callbacks.current = { onChange, onBusyChange };
+ const callbacks = useRef({ onChange, onBusyChange, pinned });
+ callbacks.current = { onChange, onBusyChange, pinned };
useEffect(() => () => {
cancelAnimationFrame(state.current.queued);
callbacks.current.onBusyChange?.(false);
@@ -43,7 +45,7 @@ export function ScreenNodeSeparation({ nodes, active, onChange, onBusyChange }:
current.queued = requestAnimationFrame(() => {
current.queued = requestAnimationFrame(() => {
current.queued = 0;
- callbacks.current.onChange(nodes, separateProjectedNodes(nodes, camera, size.width, size.height));
+ callbacks.current.onChange(nodes, separateProjectedNodes(nodes, camera, size.width, size.height, callbacks.current.pinned));
current.dirty = false; current.busy = false;
callbacks.current.onBusyChange?.(false);
invalidate();
diff --git a/graph-ui/src/galaxy/camera-frame.test.ts b/graph-ui/src/galaxy/camera-frame.test.ts
index b7b08afde..6fbbf480e 100644
--- a/graph-ui/src/galaxy/camera-frame.test.ts
+++ b/graph-ui/src/galaxy/camera-frame.test.ts
@@ -325,6 +325,23 @@ describe('fitCamera', () => {
expect(fitCamera([{ x: Number.NaN, y: Number.NaN, z: Number.NaN }], FOV, ASPECT)).toBeNull();
});
+ it('steht auf der Wurzel und nicht auf der Mitte, und haelt trotzdem jeden Knoten im Bild', () => {
+ // Eine Wolke, deren Wurzel am Rand liegt: die Mitte des Kastens ist weit weg.
+ const points = cloud(300, [900, 500, 160], 31).map((point) => ({ x: point.x + 380, y: point.y, z: point.z }));
+ const root = { x: 0, y: 0, z: 0 };
+ const fit = fitCamera([...points, root], FOV, ASPECT, FRAME_MARGIN, root)!;
+ expect(fit.center).toEqual(root);
+ const seen = project(root, fit, FOV, ASPECT);
+ expect(Math.abs(seen.x)).toBeLessThan(1e-9);
+ expect(Math.abs(seen.y)).toBeLessThan(1e-9);
+ for (const point of points) {
+ const at = project(point, fit, FOV, ASPECT);
+ expect(at.z).toBeGreaterThan(0);
+ expect(Math.max(Math.abs(at.x), Math.abs(at.y))).toBeLessThanOrEqual(1);
+ }
+ expect(fit.distance).toBeGreaterThan(fitCamera(points, FOV, ASPECT)!.distance);
+ });
+
it('steht bei einem einzigen Punkt an der Untergrenze und sieht ihn an', () => {
const fit = fitCamera([{ x: 40, y: -12, z: 5 }], FOV, ASPECT)!;
expect(fit.distance).toBe(FRAME_MIN_DISTANCE);
diff --git a/graph-ui/src/galaxy/camera-frame.ts b/graph-ui/src/galaxy/camera-frame.ts
index 8359622bd..b390b464a 100644
--- a/graph-ui/src/galaxy/camera-frame.ts
+++ b/graph-ui/src/galaxy/camera-frame.ts
@@ -482,18 +482,38 @@ export interface CameraFit {
*
* Der Rand ist derselbe wie bei jeder anderen Rahmung dieser Datei
* ({@link FRAME_MARGIN}), damit "eingepasst" ueberall dasselbe heisst.
+ *
+ * Mit `center` (Review-Befund G4) steht die Kamera auf diesen Punkt und nicht
+ * auf die Mitte der Wolke: die Wurzel eines Scopes bleibt in der Bildmitte.
+ * Die Ausdehnungen werden dann symmetrisch um ihn gemessen, also ist der
+ * Rahmen so gross, dass auch der fernste Knoten auf der anderen Seite passt.
*/
export function fitCamera(
points: readonly Vector3Like[],
fovDegrees: number,
aspect: number,
margin: number = FRAME_MARGIN,
+ center?: Vector3Like,
): CameraFit | null {
const frame = principalFrame(points);
if (frame.counted === 0) {
return null;
}
- const [width, height, depth] = frame.extents;
+ let [width, height, depth] = frame.extents;
+ const pinned = center !== undefined && [center.x, center.y, center.z].every(Number.isFinite) ? center : undefined;
+ if (pinned !== undefined) {
+ [width, height, depth] = frame.axes.map((axis) => {
+ const offset = dot(pinned, axis);
+ let reach = 0;
+ for (const point of points) {
+ if (Number.isFinite(point.x) && Number.isFinite(point.y) && Number.isFinite(point.z)) {
+ reach = Math.max(reach, Math.abs(dot(point, axis) - offset));
+ }
+ }
+ return reach * 2;
+ }) as [number, number, number];
+ }
+ const middle = pinned ?? frame.center;
const planar = frameDistance(
{ centerX: 0, centerY: 0, width, height },
fovDegrees,
@@ -503,11 +523,11 @@ export function fitCamera(
const distance = planar + depth / 2;
const normal = (frame.axes[2] as Vector3Like);
return {
- center: frame.center,
+ center: middle,
eye: {
- x: frame.center.x + normal.x * distance,
- y: frame.center.y + normal.y * distance,
- z: frame.center.z + normal.z * distance,
+ x: middle.x + normal.x * distance,
+ y: middle.y + normal.y * distance,
+ z: middle.z + normal.z * distance,
},
up: frame.axes[1] as Vector3Like,
normal,
diff --git a/graph-ui/src/galaxy/graph-exploration.css b/graph-ui/src/galaxy/graph-exploration.css
index 2133a5195..ef32fb31c 100644
--- a/graph-ui/src/galaxy/graph-exploration.css
+++ b/graph-ui/src/galaxy/graph-exploration.css
@@ -43,3 +43,8 @@
.atlas-graph-render-spinner { width:12px; height:12px; box-sizing:border-box; flex:none; border:1.5px solid #99b7a52e; border-top-color:#a8c4b3; border-radius:50%; animation:atlas-graph-render-spin .8s linear infinite; }
@keyframes atlas-graph-render-spin { to { transform:rotate(360deg); } }
@media (prefers-reduced-motion:reduce) { .atlas-graph-render-spinner { animation:none; } }
+
+/* Die Wurzel eines Scopes: ein Ring auf dem Punkt und ihr Name darunter, immer sichtbar. */
+.atlas-galaxy-root-marker { position:relative; display:block; width:0; height:0; pointer-events:none; }
+.atlas-galaxy-root-marker > i { position:absolute; left:-15px; top:-15px; width:30px; height:30px; box-sizing:border-box; border:2px solid #f0cf73; border-radius:50%; box-shadow:0 0 0 4px rgba(240, 207, 115, .16), 0 0 16px rgba(240, 207, 115, .5); }
+.atlas-galaxy-root-marker > b { position:absolute; top:19px; left:0; transform:translateX(-50%); padding:1px 6px; border-radius:4px; background:rgba(13, 15, 18, .84); color:#f5e2a6; font:600 12px/1.4 var(--atlas-ui-font, system-ui, sans-serif); white-space:nowrap; }
diff --git a/graph-ui/src/galaxy/organic-clusters.test.ts b/graph-ui/src/galaxy/organic-clusters.test.ts
index a44106bec..d8d5cd148 100644
--- a/graph-ui/src/galaxy/organic-clusters.test.ts
+++ b/graph-ui/src/galaxy/organic-clusters.test.ts
@@ -98,6 +98,28 @@ describe('organic relationship clusters', () => {
expect(Math.hypot(added.x - neighbor.x, added.y - neighbor.y, added.z - neighbor.z)).toBeGreaterThan(0);
});
+ it('keeps the root at the origin across expansions, for a fresh trace and for a previous picture without it', () => {
+ const origin = { x: 0, y: 0, z: 0 };
+ const rootAt = (layout: { data: GraphData }, id: number) => {
+ const found = layout.data.nodes.find(candidate => candidate.id === id)!;
+ return { x: found.x + 0, y: found.y + 0, z: found.z + 0 };
+ };
+ const first = layoutOrganicClusters({ nodes: [node(0), node(1), node(2)], edges: [edge(0, 1), edge(2, 0)], total_nodes: 3 },
+ { rootIds: new Set([0]) });
+ expect(rootAt(first, 0)).toEqual(origin);
+ const second = layoutOrganicClusters({ nodes: [0, 1, 2, 3, 4].map(id => node(id)), edges: [edge(0, 1), edge(2, 0), edge(1, 3), edge(4, 2)], total_nodes: 5 },
+ { rootIds: new Set([0]), previous: first.data });
+ expect(rootAt(second, 0)).toEqual(origin);
+ expect(positions({ ...second.data, nodes: second.data.nodes.slice(0, 3) })).toEqual(positions(first.data));
+ // A different direction or edge filter starts without previous positions.
+ const fresh = layoutOrganicClusters({ ...second.data, nodes: second.data.nodes.map(candidate => ({ ...candidate, x: 500 })) }, { rootIds: new Set([0]) });
+ expect(rootAt(fresh, 0)).toEqual(origin);
+ const elsewhere = layoutOrganicClusters({ nodes: [node(0), node(1), node(2), node(9)], edges: [edge(0, 1), edge(9, 2)], total_nodes: 4 },
+ { rootIds: new Set([9]), previous: first.data });
+ expect(rootAt(elsewhere, 9)).toEqual(origin);
+ expect(positions({ ...elsewhere.data, nodes: elsewhere.data.nodes.slice(0, 3) })).toEqual(positions(first.data));
+ });
+
it('uses source folders only as labels, not artificial communities or layout coordinates', () => {
const source = cliques(), first = layoutOrganicClusters(source);
const renamed = layoutOrganicClusters({ ...source, nodes: source.nodes.map(candidate => ({ ...candidate, file_path: `other/folder-${candidate.id}/file.ts` })) });
diff --git a/graph-ui/src/galaxy/organic-clusters.ts b/graph-ui/src/galaxy/organic-clusters.ts
index 77239a6f6..b71382194 100644
--- a/graph-ui/src/galaxy/organic-clusters.ts
+++ b/graph-ui/src/galaxy/organic-clusters.ts
@@ -279,10 +279,17 @@ export function layoutOrganicClusters(data: GraphData, options: OrganicClusterOp
}), .006);
const adjacent: number[][] = nodes.map(() => []);
for (const pair of pairs) { adjacent[pair.a]!.push(pair.b); adjacent[pair.b]!.push(pair.a); }
+ const rootCount = nodes.filter(node => options.rootIds?.has(node.id)).length;
const particles: Particle[] = nodes.map((node, index) => {
const old = previous.get(node.id), anchor = anchors[groupIndex[index]!]!;
const radius = 8 + 1.5 * Math.sqrt(Math.max(0, Number.isFinite(node.size) ? node.size : 1));
if (old) return { x: old.x, y: old.y, z: old.z, radius, fixed: true, home: { x: old.x, y: old.y, z: old.z } };
+ // Pinned positions cannot be shifted, so a root they do not hold is
+ // placed at the origin directly instead of re-centering afterwards.
+ if (previous.size && options.rootIds?.has(node.id)) {
+ const offset = rootCount > 1 ? cloudPoint(`root:${node.id}`, 20) : { x: 0, y: 0, z: 0 };
+ return { ...offset, radius, fixed: rootCount === 1, home: { x: 0, y: 0, z: 0 } };
+ }
const neighboringOld = adjacent[index]!.flatMap(neighbor => previous.has(nodes[neighbor]!.id) ? [previous.get(nodes[neighbor]!.id)!] : []);
const home = neighboringOld.length ? { x: neighboringOld.reduce((sum, p) => sum + p.x, 0) / neighboringOld.length,
y: neighboringOld.reduce((sum, p) => sum + p.y, 0) / neighboringOld.length, z: neighboringOld.reduce((sum, p) => sum + p.z, 0) / neighboringOld.length }
@@ -295,6 +302,8 @@ export function layoutOrganicClusters(data: GraphData, options: OrganicClusterOp
distance: 42 + hash(`length:${nodes[pair.a]!.id}:${nodes[pair.b]!.id}`) / 0x100000000 * 26,
strength: groupIndex[pair.a] === groupIndex[pair.b] ? .034 : .0015,
}), .018);
+ // Roots sit at the origin: a fresh layout is re-centered on them, and an
+ // expansion keeps the earlier, already centered positions.
const roots = nodes.flatMap((node, index) => options.rootIds?.has(node.id) ? [particles[index]!] : []);
const origin = previous.size || !roots.length ? { x: 0, y: 0, z: 0 }
: { x: roots.reduce((sum, p) => sum + p.x, 0) / roots.length, y: roots.reduce((sum, p) => sum + p.y, 0) / roots.length,
diff --git a/graph-ui/src/galaxy/projected-node-spacing.ts b/graph-ui/src/galaxy/projected-node-spacing.ts
index 9ddcc5f30..eeb469279 100644
--- a/graph-ui/src/galaxy/projected-node-spacing.ts
+++ b/graph-ui/src/galaxy/projected-node-spacing.ts
@@ -30,8 +30,10 @@ export function projectNodeDisks(nodes: readonly GraphNode[], camera: Camera, wi
}
/** Display-only offsets: index coordinates, identities and relationships stay
- * intact. Keep depth and let the drawing grow outside the viewport if needed. */
-export function separateProjectedNodes(nodes: GraphNode[], camera: Camera, width: number, height: number): GraphNode[] {
+ * intact. Keep depth and let the drawing grow outside the viewport if needed.
+ * Pinned nodes (a scope root) keep their place; the others move around them. */
+export function separateProjectedNodes(nodes: GraphNode[], camera: Camera, width: number, height: number,
+ pinned: ReadonlySet<number> = new Set()): GraphNode[] {
if (width <= 0 || height <= 0 || nodes.length < 2) return nodes;
const view = new Vector3();
const perspective = camera.projectionMatrix.elements[15] === 0;
@@ -44,7 +46,7 @@ export function separateProjectedNodes(nodes: GraphNode[], camera: Camera, width
}) : nodes;
for (let pass = 0; pass < 4; pass++) {
const disks = projectNodeDisks(positioned, camera, width, height);
- const separated = separateScreenNodes(disks, 7);
+ const separated = separateScreenNodes(disks, 7, pinned);
const moved = new Map<number, GraphNode>(), point = new Vector3();
for (let index = 0; index < separated.length; index++) {
const disk = separated[index]!, original = disks[index]!;
@@ -57,7 +59,7 @@ export function separateProjectedNodes(nodes: GraphNode[], camera: Camera, width
// Lateral movement can enlarge perspective silhouettes. Verify against
// the actual reprojected bodies, not only the input circle estimates.
const actual = projectNodeDisks(positioned, camera, width, height);
- if (separateScreenNodes(actual, 5).every((disk, index) => disk === actual[index])) break;
+ if (separateScreenNodes(actual, 5, pinned).every((disk, index) => disk === actual[index])) break;
}
return positioned;
}
diff --git a/graph-ui/src/galaxy/screen-node-spacing.test.ts b/graph-ui/src/galaxy/screen-node-spacing.test.ts
index 4fb9feb3d..618191d2d 100644
--- a/graph-ui/src/galaxy/screen-node-spacing.test.ts
+++ b/graph-ui/src/galaxy/screen-node-spacing.test.ts
@@ -61,4 +61,12 @@ describe('projected node spacing', () => {
expect(separateScreenNodes(nodes)[0]).toBe(nodes[0]);
expect(separateScreenNodes([])).toEqual([]);
});
+
+ it('never moves a pinned root, even when larger disks sit on top of it', () => {
+ const nodes = [{ id: 1, x: 0, y: 0, radius: 3 }, ...Array.from({ length: 30 }, (_, index) =>
+ ({ id: index + 2, x: (index % 5) - 2, y: Math.floor(index / 5) - 3, radius: 6 + index % 9 }))];
+ const result = separateScreenNodes(nodes, 4, new Set([1]));
+ expect(result[0]).toBe(nodes[0]);
+ expect(smallestGap(result)).toBeGreaterThanOrEqual(4 - 1e-8);
+ });
});
diff --git a/graph-ui/src/galaxy/screen-node-spacing.ts b/graph-ui/src/galaxy/screen-node-spacing.ts
index 0054a729d..dea93b8f5 100644
--- a/graph-ui/src/galaxy/screen-node-spacing.ts
+++ b/graph-ui/src/galaxy/screen-node-spacing.ts
@@ -18,20 +18,23 @@ function directionSeed(id: number): number {
return ((seed ^ (seed >>> 16)) >>> 0) / 0x100000000 * Math.PI * 2;
}
-/** Screen-space presentation only. Largest disks are placed first, preserving
- * their preferred positions when possible. Existing graph IDs and metadata
- * are retained, and the result remains in the original input order.
+/** Screen-space presentation only. Pinned disks (a scope root) never move and
+ * are placed first; then the largest disks, preserving their preferred
+ * positions when possible. Existing graph IDs and metadata are retained, and
+ * the result remains in the original input order.
*
* Each radius scale has its own spatial hash. Earlier disks are at least as
- * large as the candidate, so only nine cells per occupied scale can overlap.
+ * large as the candidate, so only nine cells per occupied scale can overlap;
+ * pinned disks are hashed at the largest scale for the same guarantee.
* Local search is bounded; an outside-bounds fallback guarantees clearance
* without dropping nodes or squeezing them into a fixed viewport. */
-export function separateScreenNodes<T extends ScreenNode>(nodes: readonly T[], gap = 4): T[] {
+export function separateScreenNodes<T extends ScreenNode>(nodes: readonly T[], gap = 4, pinned: ReadonlySet<number> = new Set()): T[] {
if (!Number.isFinite(gap) || gap < 0 || nodes.some(node => ![node.x, node.y, node.radius].every(Number.isFinite) || node.radius < 0)) {
throw new RangeError('Screen node positions, radii and gap must be finite; radii and gap must be nonnegative.');
}
- const order = nodes.map((node, index) => ({ node, index }))
- .sort((a, b) => b.node.radius - a.node.radius || a.node.id - b.node.id || a.index - b.index);
+ const order = nodes.map((node, index) => ({ node, index, pinned: pinned.has(node.id) }))
+ .sort((a, b) => Number(b.pinned) - Number(a.pinned) || b.node.radius - a.node.radius || a.node.id - b.node.id || a.index - b.index);
+ const largest = nodes.reduce((max, node) => Math.max(max, node.radius + gap / 2), 0);
const result = new Array<T>(nodes.length), levels = new Map<number, Level>();
let left = Infinity, right = -Infinity, top = Infinity, bottom = -Infinity;
@@ -53,11 +56,11 @@ export function separateScreenNodes<T extends ScreenNode>(nodes: readonly T[], g
return found;
};
- const insert = (disk: Disk) => {
+ const insert = (disk: Disk, scale = disk.radius) => {
left = Math.min(left, disk.x - disk.radius); right = Math.max(right, disk.x + disk.radius);
top = Math.min(top, disk.y - disk.radius); bottom = Math.max(bottom, disk.y + disk.radius);
if (disk.radius === 0) return; // Zero-area disks cannot obstruct later zero-area disks.
- const width = 2 ** Math.ceil(Math.log2(disk.radius * 2));
+ const width = 2 ** Math.ceil(Math.log2(scale * 2));
let level = levels.get(width);
if (!level) { level = { width, columns: new Map() }; levels.set(width, level); }
const x = Math.floor(disk.x / width), y = Math.floor(disk.y / width);
@@ -65,8 +68,9 @@ export function separateScreenNodes<T extends ScreenNode>(nodes: readonly T[], g
const bucket = column.get(y) ?? []; bucket.push(disk); column.set(y, bucket);
};
- for (const { node, index } of order) {
+ for (const { node, index, pinned: fixed } of order) {
const radius = node.radius + gap / 2;
+ if (fixed) { result[index] = node; insert({ x: node.x, y: node.y, radius }, largest); continue; }
const blocked = collisions(node.x, node.y, radius);
let placed = { x: node.x, y: node.y };
if (blocked.length) {