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): lay out the Galaxy scope hierarchy left, centre and right

Bernhard Jackiewicz86af069f7643
diff --git a/graph-ui/src/galaxy/GalaxyPanel.hierarchy-scope.test.tsx b/graph-ui/src/galaxy/GalaxyPanel.hierarchy-scope.test.tsx
new file mode 100644
index 000000000..a51b30b3d
--- /dev/null
+++ b/graph-ui/src/galaxy/GalaxyPanel.hierarchy-scope.test.tsx
@@ -0,0 +1,91 @@
+// @vitest-environment jsdom
+/*
+ * Handtest K5: die Hierarchie eines Ausschnitts. Eingehendes links, Wurzel in
+ * der Mitte, Ausgehendes rechts, ein ehrlicher Hinweis, und Pfad und
+ * Aufrufreihe gibt es auch hier, mit Hervorhebung im Bild der Hierarchie.
+ */
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import GalaxyPanel from './GalaxyPanel';
+import type { GraphData } from './types';
+import type { ScenePath } from './PathLayer';
+import { scopeFetch, scopeNode } from './test-scope-fetch';
+import { GALAXY_LEGEND_KEY } from './galaxy-legend';
+
+const scene = vi.hoisted(() => ({ data: undefined as GraphData | undefined, path: undefined as ScenePath | undefined, highlighted: null as Set<number> | null,
+ labelMaxTextWidth: undefined as number | undefined, overlay: false }));
+vi.mock('./GraphScene', async importOriginal => ({
+ ...await importOriginal<typeof import('./GraphScene')>(),
+ GraphScene: ({ data, path, highlightedIds, labelMaxTextWidth, overlay }: { data: GraphData; path?: ScenePath; highlightedIds: Set<number> | null;
+ labelMaxTextWidth?: number; overlay?: unknown }) => {
+ scene.data = data; scene.path = path; scene.highlighted = highlightedIds; scene.labelMaxTextWidth = labelMaxTextWidth; scene.overlay = Boolean(overlay);
+ return <output data-testid="scene" />;
+ },
+}));
+
+let host: HTMLDivElement, root: Root;
+beforeEach(() => {
+ (globalThis as unknown as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = true;
+ host = document.createElement('div'); document.body.append(host); root = createRoot(host);
+});
+afterEach(async () => { await act(async () => root.unmount()); host.remove(); globalThis.__atlasGalaxy = undefined; });
+
+const seam = () => globalThis.__atlasGalaxy!;
+const settle = (check: () => void) => vi.waitFor(async () => {
+ await act(async () => { await new Promise(resolve => setTimeout(resolve, 0)); });
+ check();
+});
+const button = (label: string) => [...host.querySelectorAll('button')].find(entry => entry.textContent === label);
+
+it('K5: the hierarchy of a scope puts callers left and callees right, says so, and keeps Path to and Call order', async () => {
+ const nodes = [1, 2, 3, 4, 5].map(id => scopeNode(id));
+ const edges = [{ id: 1, source: 1, target: 2, type: 'CALLS', line: 30 }, { id: 2, source: 1, target: 3, type: 'CALLS', line: 12 },
+ { id: 3, source: 4, target: 1, type: 'CALLS', line: 2 }, { id: 4, source: 5, target: 1, type: 'TESTS' }];
+ await act(async () => root.render(<GalaxyPanel project="sample" visible workspaceExpanded onOpenNode={vi.fn()} fetch={scopeFetch({ nodes, edges }).fetch}
+ legendStore={{ getItem: (key: string) => (key === GALAXY_LEGEND_KEY ? 'open' : null), setItem: vi.fn() } as unknown as Storage} />));
+ await settle(() => expect(seam().nodes).toBe(5));
+ await act(async () => { seam().clickNode('sample.n1'); });
+ await settle(() => expect(host.querySelector('.atlas-graph-scope-count')?.textContent).toBe('5 nodes · 4 edges'));
+ await act(async () => host.querySelector<HTMLButtonElement>('[data-testid="atlas-graph-mode-chip"][data-mode="hierarchy"]')!.click());
+ expect(seam().mode).toBe('hierarchy');
+
+ const placed = Object.fromEntries(seam().hierarchy!.placements.map(placement => [placement.name, placement]));
+ expect(placed.n1).toMatchObject({ x: 0, y: 0 });
+ expect(placed.n4!.x).toBeLessThan(0); expect(placed.n5!.x).toBeLessThan(0);
+ expect(placed.n2!.x).toBeGreaterThan(0); expect(placed.n3!.y).toBeGreaterThan(placed.n2!.y); // line 12 above line 30
+ // Full names, the edge types at the lines, and an honest description.
+ expect(scene.labelMaxTextWidth).toBeGreaterThanOrEqual(1600);
+ expect(scene.overlay).toBe(true);
+ const chip = host.querySelector('[data-testid="atlas-graph-mode-chip"][data-mode="hierarchy"]')!.closest('[data-hint-name], span, div')!;
+ expect(host.innerHTML).toContain('incoming relationships on the left, the root in the middle, outgoing on the right');
+ expect(chip).toBeTruthy();
+ expect(host.querySelector('[data-entry="positions"]')?.textContent).toContain('Incoming relationships on the left');
+ expect(host.querySelector('[data-entry="positions"]')?.textContent).not.toContain('ordered by name');
+
+ // Call order and Path to work in this picture and highlight its own nodes.
+ await act(async () => button('Call order')!.click());
+ const sceneId = (name: string) => scene.data!.nodes.find(node => node.name === name)!.id;
+ expect(scene.path?.steps.map(step => [step.from, step.to])).toEqual([[sceneId('n1'), sceneId('n3')], [sceneId('n1'), sceneId('n2')]]);
+ expect([...scene.highlighted ?? []].sort()).toEqual([sceneId('n1'), sceneId('n2'), sceneId('n3')].sort());
+ await act(async () => button('Call order')!.click());
+ host.querySelector<HTMLDetailsElement>('.atlas-graph-path-picker')!.open = true;
+ await act(async () => [...host.querySelectorAll<HTMLButtonElement>('.atlas-graph-path-menu li button')]
+ .find(entry => entry.querySelector('strong')?.textContent === 'n5')!.click());
+ expect(host.querySelector('[data-testid="atlas-galaxy-path-panel"] strong')?.textContent).toBe('Path to n5 · 1 hop');
+ expect(scene.path?.steps.map(step => [step.edge.source, step.edge.target])).toEqual([[sceneId('n5'), sceneId('n1')]]);
+});
+
+it('K5: the hint follows the trace direction', async () => {
+ const nodes = [1, 2].map(id => scopeNode(id));
+ await act(async () => root.render(<GalaxyPanel project="sample" visible workspaceExpanded onOpenNode={vi.fn()}
+ fetch={scopeFetch({ nodes, edges: [{ id: 1, source: 1, target: 2, type: 'CALLS' }] }).fetch} />));
+ await settle(() => expect(seam().nodes).toBe(2));
+ await act(async () => { seam().clickNode('sample.n1'); });
+ await settle(() => expect(host.querySelector('.atlas-graph-scope-count')?.textContent).toBe('2 nodes · 1 edge'));
+ await act(async () => {
+ const select = host.querySelector<HTMLSelectElement>('select[aria-label="Trace direction"]')!;
+ select.value = 'outbound'; select.dispatchEvent(new Event('change', { bubbles: true }));
+ });
+ expect(host.innerHTML).toContain('what the root reaches, one column per layer to the right');
+});
diff --git a/graph-ui/src/galaxy/GalaxyPanel.tsx b/graph-ui/src/galaxy/GalaxyPanel.tsx
index 226d8d87e..34190a6a6 100644
--- a/graph-ui/src/galaxy/GalaxyPanel.tsx
+++ b/graph-ui/src/galaxy/GalaxyPanel.tsx
@@ -139,13 +139,14 @@ import GalaxyNavigator from './GalaxyNavigator';
import { TraceEdgeFilter } from './TraceEdgeFilter';
import { PathPicker, PathSteps } from './ScopePathControls';
import { callOrder, pathNodes, shortestScopePath, type ScopePathStep } from './scope-path';
-import { galaxyHistoryText, galaxyLayerText, galaxyPathText, galaxyToolbarText } from './galaxy-strings';
+import { galaxyHierarchyText, galaxyHistoryText, galaxyLayerText, galaxyPathText, galaxyToolbarText } from './galaxy-strings';
+import { HierarchyEdgeLabels } from './HierarchyEdgeLabels';
import { emptyNavigationHistory, moveNavigation, peekNavigation, pushNavigation } from '../graph/navigation-history';
import { galaxyHistoryOptions, historyEntryDetail, historyEntryLabel, scopeIdentity, type GalaxyHistoryEntry, type ScopeTrail } from './scope-history';
import { useOrganicLayout } from './use-organic-layout';
import RenderProgress from './RenderProgress';
import { useGraphScope } from './use-graph-scope';
-import { limitGraphRender, nextLayerEstimate, scenePictureFor, scopedHierarchy } from './graph-scope';
+import { SCOPED_HIERARCHY_LABEL_MAX_TEXT_WIDTH, limitGraphRender, nextLayerEstimate, scenePictureFor, scopedHierarchy } from './graph-scope';
import './graph-exploration.css';
import { layoutNodeForSelection } from './selected-node';
import { galaxyScopeEvidence, useSelectionEvidence, type SelectionEvidenceListener } from './selection-evidence';
@@ -1229,7 +1230,8 @@ export default function GalaxyPanel(props: GalaxyPanelProps): JSX.Element {
const rootCalls = useMemo(() => (data && trailRoot !== undefined ? callOrder(data.edges, trailRoot) : []), [data, trailRoot]);
const pathCandidates = useMemo(() => data?.nodes.filter(node => !scope.result?.roots.has(node.id)) ?? [], [data, scope.result]);
const trailView = useMemo(() => {
- if (!props.workspaceExpanded || mode !== 'galaxy' || trail?.key !== organicKey || !data || !scope.result) return undefined;
+ // Handtest K5: Pfad und Aufrufreihe auch in der Hierarchie eines Ausschnitts.
+ if (!props.workspaceExpanded || (mode !== 'galaxy' && !scopedProjection) || trail?.key !== organicKey || !data || !scope.result) return undefined;
const names = new Map(data.nodes.map(node => [node.id, node.name]));
const nameOf = (id: number) => names.get(id) ?? `#${id}`;
if (trail.kind === 'calls') {
@@ -1245,6 +1247,25 @@ export default function GalaxyPanel(props: GalaxyPanelProps): JSX.Element {
const trailActive = trailView ? Math.min(trailStep, Math.max(0, trailView.steps.length - 1)) : 0;
const trailIds = useMemo(() => trailView?.steps.length && scope.result ? pathNodes(trailView.steps, scope.result.roots) : undefined,
[trailView, scope.result]);
+ /*
+ * Die Hierarchie zeichnet mit eigenen IDs (K5). Der Pfad rechnet im Scope und
+ * wird fuer ihr Bild umgeschrieben, damit Linien, Ring und Abdunkeln an den
+ * Knoten liegen, die dort zu sehen sind.
+ */
+ const hierarchyIds = useMemo(() => mode === 'hierarchy' && scopedProjection?.sourceIds
+ ? new Map(scopedProjection.sourceIds.map((source, id) => [source, id])) : undefined, [mode, scopedProjection]);
+ const sceneTrailIds = useMemo(() => !trailIds || !hierarchyIds ? trailIds
+ : new Set([...trailIds].flatMap(id => hierarchyIds.get(id) ?? [])), [trailIds, hierarchyIds]);
+ const scenePathSteps = useMemo(() => {
+ if (!trailView) return undefined;
+ if (!hierarchyIds) return trailView.steps;
+ return trailView.steps.flatMap(step => {
+ const from = hierarchyIds.get(step.from), to = hierarchyIds.get(step.to);
+ const source = hierarchyIds.get(step.edge.source), target = hierarchyIds.get(step.edge.target);
+ return from === undefined || to === undefined || source === undefined || target === undefined ? []
+ : [{ edge: { ...step.edge, source, target }, from, to }];
+ });
+ }, [trailView, hierarchyIds]);
const clearTrail = useCallback(() => { setTrail(undefined); setTrailStep(0); }, []);
/*
* Escape gibt den Pfad frei, aber erst nach allen, die vorgehen: liegt eine
@@ -1274,9 +1295,9 @@ export default function GalaxyPanel(props: GalaxyPanelProps): JSX.Element {
// Graphen und nicht alle, die die Tabelle kennt.
const legend = useMemo(
() => (mode === 'hierarchy'
- ? hierarchyLegendEntries(picture, readerHierarchyActive)
+ ? hierarchyLegendEntries(picture, readerHierarchyActive, Boolean(scopedProjection))
: galaxyLegendEntries(picture)),
- [mode, picture, readerHierarchyActive],
+ [mode, picture, readerHierarchyActive, scopedProjection],
);
// Der Inhalt hat sich geaendert (aufgeklappt, Ansicht gewechselt, eine Art
@@ -2229,7 +2250,8 @@ export default function GalaxyPanel(props: GalaxyPanelProps): JSX.Element {
legendOpen,
legendEntries: legend.length,
bloom: display.bloom,
- labelBoxes: labelBoxes.current,
+ // Live: the scene publishes new name boxes from its frame loop, without a render of this panel.
+ get labelBoxes() { return labelBoxes.current; },
mode,
open: visible,
hierarchyAvailable: projection !== undefined,
@@ -2311,9 +2333,13 @@ export default function GalaxyPanel(props: GalaxyPanelProps): JSX.Element {
* GraphScene.tsx), und sie muss zwischen einem Ring und einer Ebene aus
* Koerpern nicht unterscheiden: was hier steht, ist ein Kind ihres Baums.
*/
- const overlay: ReactNode = (pulseRing === undefined && !liveOn) ? undefined : (
+ /* K5: die Kantenarten an den Linien der Hierarchie eines Ausschnitts, solange kein Pfad seine eigenen zeigt. */
+ const hierarchyEdgeLabels = mode === 'hierarchy' && scopedProjection && !sceneTrailIds && sceneShown
+ ? <HierarchyEdgeLabels nodes={sceneShown.nodes} edges={sceneShown.edges} nameBoxes={labelBoxes} /> : undefined;
+ const overlay: ReactNode = (pulseRing === undefined && !liveOn && hierarchyEdgeLabels === undefined) ? undefined : (
<>
{pulseRing}
+ {hierarchyEdgeLabels}
{liveOn && agentLayerOn && agentsView !== undefined && (
<AgentLayer
actors={agentsView.actors}
@@ -2392,6 +2418,7 @@ export default function GalaxyPanel(props: GalaxyPanelProps): JSX.Element {
: candidate === 'galaxy'
? 'galaxy: the whole project, laid out by the server'
: readerHierarchyActive ? 'hierarchy: incoming relationships, file definitions, and outgoing relationships'
+ : scopedProjection ? galaxyHierarchyText.hint(scope.direction)
: 'hierarchy: what the chosen symbol reaches, one column per call depth'
}
>
@@ -2534,7 +2561,7 @@ export default function GalaxyPanel(props: GalaxyPanelProps): JSX.Element {
<button type="button" disabled={scope.loading || scope.result?.exhausted || Boolean(scope.result?.partial)}
data-warning={expandWarning || undefined} title={expandTitle}
onClick={() => scope.setDepth(scope.depth + 1)}>Expand +1</button>
- {props.workspaceExpanded && mode === 'galaxy' && <>
+ {props.workspaceExpanded && (mode === 'galaxy' || scopedProjection) && <>
<PathPicker nodes={pathCandidates} onPick={node => { setTrail({ key: organicKey, kind: 'path', target: node.id, name: node.name }); setTrailStep(0); }} />
<button type="button" disabled={rootCalls.length === 0} aria-pressed={trail?.key === organicKey && trail.kind === 'calls'}
title={rootCalls.length ? galaxyPathText.callOrderTitle : galaxyPathText.callOrderUnavailable}
@@ -2728,8 +2755,8 @@ export default function GalaxyPanel(props: GalaxyPanelProps): JSX.Element {
rootIds={mode === 'galaxy' && sceneScoped ? scope.result?.roots : undefined}
data={sceneShown}
display={display}
- highlightedIds={trailIds ?? (scope.scope && scope.depth > 1 ? null : highlighted)}
- path={trailIds && trailView ? { steps: trailView.steps, active: trailActive, labels: trailView.labels } : undefined}
+ highlightedIds={sceneTrailIds ?? (scope.scope && scope.depth > 1 && mode === 'galaxy' ? null : highlighted)}
+ path={sceneTrailIds && trailView && scenePathSteps ? { steps: scenePathSteps, active: trailActive, labels: trailView.labels } : undefined}
emphasizeIncidentEdges={mode === 'galaxy' && Boolean(props.focusFilePath)}
cameraTarget={cameraTarget}
/*
@@ -2743,7 +2770,7 @@ export default function GalaxyPanel(props: GalaxyPanelProps): JSX.Element {
mode === 'hierarchy' ? HIERARCHY_LABEL_FONT_SIZE : undefined
}
labelMaxTextWidth={
- mode === 'hierarchy' ? HIERARCHY_LABEL_MAX_TEXT_WIDTH : undefined
+ mode === 'hierarchy' ? scopedProjection ? SCOPED_HIERARCHY_LABEL_MAX_TEXT_WIDTH : HIERARCHY_LABEL_MAX_TEXT_WIDTH : undefined
}
onLabelLayout={onLabelLayout}
/*
diff --git a/graph-ui/src/galaxy/GraphScene.tsx b/graph-ui/src/galaxy/GraphScene.tsx
index c71571607..2d678fd79 100644
--- a/graph-ui/src/galaxy/GraphScene.tsx
+++ b/graph-ui/src/galaxy/GraphScene.tsx
@@ -649,7 +649,11 @@ export interface FitMeasurement {
declare global {
// eslint-disable-next-line no-var
- var __atlasGalaxyFit: { measure: () => FitMeasurement } | undefined;
+ var __atlasGalaxyFit: {
+ measure: () => FitMeasurement;
+ /** Weltpunkte in Pixel der Zeichenflaeche, mit genau der Kamera, die zeichnet (Beweislauf K5). */
+ project: (points: readonly { x: number; y: number; z: number }[]) => { x: number; y: number }[];
+ } | undefined;
}
/**
@@ -740,7 +744,15 @@ function FitProbe({ nodes }: { nodes: GraphNode[] }): null {
worst: seen.slice(0, 5),
};
};
- globalThis.__atlasGalaxyFit = { measure };
+ const project = (points: readonly { x: number; y: number; z: number }[]) => {
+ camera.updateMatrixWorld();
+ const point = new THREE.Vector3();
+ return points.map((entry) => {
+ point.set(entry.x, entry.y, entry.z).project(camera);
+ return { x: ((point.x + 1) / 2) * size.width, y: ((1 - point.y) / 2) * size.height };
+ });
+ };
+ globalThis.__atlasGalaxyFit = { measure, project };
return () => {
globalThis.__atlasGalaxyFit = undefined;
};
diff --git a/graph-ui/src/galaxy/HierarchyEdgeLabels.tsx b/graph-ui/src/galaxy/HierarchyEdgeLabels.tsx
new file mode 100644
index 000000000..83f5330e3
--- /dev/null
+++ b/graph-ui/src/galaxy/HierarchyEdgeLabels.tsx
@@ -0,0 +1,96 @@
+/*
+ * Die Kantenarten an den Linien der Hierarchie (Handtest K5).
+ *
+ * In der Hierarchie eines Ausschnitts war nicht zu erkennen, welche Linie ein
+ * Aufruf, ein Test oder eine Definition ist. Jetzt steht die Art an der Linie,
+ * eine Beschriftung je Knotenpaar: ein Test, der JSONBAgg aufruft UND testet,
+ * traegt "CALLS · TESTS" statt zweier Schilder auf derselben Linie. Die Labels
+ * weichen den Namen der Knoten aus, wie die Labels eines Pfades
+ * (src/galaxy/path-frame.ts); die Namen sind hier Sprites der Szene, ihre
+ * Kaesten kommen aus NodeLabels (`onLabelLayout`) in Weltkoordinaten.
+ */
+import { useMemo, useRef, type RefObject } from 'react';
+import { useFrame, useThree } from '@react-three/fiber';
+import { Html } from '@react-three/drei';
+import * as THREE from 'three';
+import { placeAlongSegment, type ScreenRect } from './path-frame';
+import type { LabelBox } from './NodeLabels';
+import type { GraphEdge, GraphNode } from './types';
+
+/** Mehr Schilder waeren kein Text mehr, sondern eine Flaeche. */
+export const HIERARCHY_EDGE_LABEL_BUDGET = 80;
+
+export interface HierarchyEdgeLabel { key: string; source: number; target: number; text: string }
+
+/** Ein Schild je Knotenpaar, die Arten ohne Doppelte, CALLS zuerst. */
+export function hierarchyEdgeLabels(edges: readonly GraphEdge[]): HierarchyEdgeLabel[] {
+ const pairs = new Map<string, { source: number; target: number; types: Set<string> }>();
+ for (const edge of edges) {
+ if (edge.source === edge.target) continue;
+ const [a, b] = edge.source < edge.target ? [edge.source, edge.target] : [edge.target, edge.source];
+ const key = `${a}:${b}`;
+ const pair = pairs.get(key) ?? { source: edge.source, target: edge.target, types: new Set<string>() };
+ pair.types.add(edge.type); pairs.set(key, pair);
+ }
+ return [...pairs].map(([key, pair]) => ({ key, source: pair.source, target: pair.target,
+ text: [...pair.types].sort((x, y) => Number(y === 'CALLS') - Number(x === 'CALLS') || x.localeCompare(y)).join(' · ') }));
+}
+
+const PLACE_EVERY_FRAMES = 3;
+
+export function HierarchyEdgeLabels({ nodes, edges, nameBoxes }: {
+ nodes: readonly GraphNode[];
+ edges: readonly GraphEdge[];
+ /** Die gezeichneten Namen, in Weltkoordinaten (NodeLabels). */
+ nameBoxes: RefObject<LabelBox[]>;
+}) {
+ const byId = useMemo(() => new Map(nodes.map((node) => [node.id, node])), [nodes]);
+ const labels = useMemo(() => hierarchyEdgeLabels(edges).flatMap((label) => {
+ const from = byId.get(label.source), to = byId.get(label.target);
+ return from && to ? [{ ...label, from, to }] : [];
+ }).slice(0, HIERARCHY_EDGE_LABEL_BUDGET), [edges, byId]);
+ const groups = useRef(new Map<string, THREE.Group>());
+ const elements = useRef(new Map<string, HTMLElement>());
+ const camera = useThree((state) => state.camera);
+ const gl = useThree((state) => state.gl);
+ const tick = useRef(0);
+ const point = useMemo(() => new THREE.Vector3(), []);
+ const ends = useMemo(() => ({ from: new THREE.Vector3(), to: new THREE.Vector3() }), []);
+ useFrame(() => {
+ tick.current = (tick.current + 1) % PLACE_EVERY_FRAMES;
+ if (tick.current !== 0) return;
+ const box = gl.domElement.getBoundingClientRect();
+ const toScreen = (x: number, y: number, z = 0) => {
+ point.set(x, y, z).project(camera);
+ return { x: box.left + ((point.x + 1) / 2) * box.width, y: box.top + ((1 - point.y) / 2) * box.height };
+ };
+ const blockers: ScreenRect[] = (nameBoxes.current ?? []).map((name) => {
+ const a = toScreen(name.x - name.width / 2, name.y + name.height / 2), b = toScreen(name.x + name.width / 2, name.y - name.height / 2);
+ return { left: Math.min(a.x, b.x), right: Math.max(a.x, b.x), top: Math.min(a.y, b.y), bottom: Math.max(a.y, b.y) };
+ });
+ const placed: ScreenRect[] = [];
+ for (const { key, from, to } of labels) {
+ const group = groups.current.get(key), element = elements.current.get(key);
+ if (!group || !element || element.offsetWidth === 0) continue;
+ const a = toScreen(from.x, from.y, from.z), b = toScreen(to.x, to.y, to.z);
+ const choice = placeAlongSegment(a, b, { width: element.offsetWidth, height: element.offsetHeight }, blockers, placed);
+ placed.push(choice.rect);
+ group.position.lerpVectors(ends.from.set(from.x, from.y, from.z), ends.to.set(to.x, to.y, to.z), choice.t);
+ const onEdge = { x: a.x + (b.x - a.x) * choice.t, y: a.y + (b.y - a.y) * choice.t };
+ element.style.transform = `translate(${(choice.rect.left + choice.rect.right) / 2 - onEdge.x}px, ${(choice.rect.top + choice.rect.bottom) / 2 - onEdge.y}px)`;
+ }
+ });
+ return (
+ <>
+ {labels.map(({ key, text, from, to }) => (
+ <group key={key} position={[(from.x + to.x) / 2, (from.y + to.y) / 2, (from.z + to.z) / 2]}
+ ref={(group) => { if (group) groups.current.set(key, group); else groups.current.delete(key); }}>
+ <Html center zIndexRange={[8, 0]} style={{ pointerEvents: 'none' }}>
+ <span className="atlas-galaxy-path-label atlas-hierarchy-edge-label" data-testid="atlas-hierarchy-edge-label"
+ ref={(element) => { if (element) elements.current.set(key, element); else elements.current.delete(key); }}>{text}</span>
+ </Html>
+ </group>
+ ))}
+ </>
+ );
+}
diff --git a/graph-ui/src/galaxy/galaxy-legend.ts b/graph-ui/src/galaxy/galaxy-legend.ts
index 550684b36..fff4b129c 100644
--- a/graph-ui/src/galaxy/galaxy-legend.ts
+++ b/graph-ui/src/galaxy/galaxy-legend.ts
@@ -295,7 +295,9 @@ export function galaxyLegendEntries(data: GraphData | undefined): LegendEntry[]
* Die Schluessel sind dieselben wie in {@link galaxyLegendEntries}, damit ein
* Leser die Zeile, die er sucht, an derselben Stelle findet.
*/
-export function hierarchyLegendEntries(data: GraphData | undefined, fileRelationships = false): LegendEntry[] {
+export function hierarchyLegendEntries(data: GraphData | undefined, fileRelationships = false,
+ /* Die Hierarchie eines Galaxy-Ausschnitts (Handtest K5): keine Walk-Spalten, sondern Ebenen links und rechts der Wurzel. */
+ scoped = false): LegendEntry[] {
const swatches = edgeSwatches(data);
return [
{
@@ -311,7 +313,9 @@ export function hierarchyLegendEntries(data: GraphData | undefined, fileRelation
* Beziehungen auch, und der Griff zum Ausblenden steht am
* Punkt selbst (`title`).
*/
- detail: fileRelationships
+ detail: scoped
+ ? 'Every relationship of this scope, its type written at the line. Edge colours keep their types; this is not a runtime trace.'
+ : fileRelationships
? 'Recorded relationships touching the selected file or marked code. Edge colours retain their original types; this is not a complete call trace.'
: 'one line per call on this walk, cycles included rather than hidden. '
+ 'What else the index records between these symbols is drawn in its own colour: '
@@ -322,7 +326,10 @@ export function hierarchyLegendEntries(data: GraphData | undefined, fileRelation
{
key: 'positions',
title: 'positions',
- detail: fileRelationships
+ detail: scoped
+ ? 'Incoming relationships on the left, the root in the middle, outgoing relationships on the right; one column per layer. '
+ + 'Inside a column: by the neighbour that leads there, calls before other types, calls by call-site line.'
+ : fileRelationships
? 'Incoming relationships on the left, selected definitions in the middle, outgoing relationships on the right. Recorded containment orders the definition columns; source paths and lines order each column.'
: 'columns are the call depth from the entry point, and inside a column the symbols '
+ 'are ordered by name. A deterministic projection of the walk, not the server layout: '
diff --git a/graph-ui/src/galaxy/galaxy-strings.ts b/graph-ui/src/galaxy/galaxy-strings.ts
index fe10dd3eb..0c4093cef 100644
--- a/graph-ui/src/galaxy/galaxy-strings.ts
+++ b/graph-ui/src/galaxy/galaxy-strings.ts
@@ -57,6 +57,15 @@ export const galaxyHistoryText = {
pathTo: (name: string) => `path to ${name}`,
};
+/** The hierarchy of a Galaxy scope (hand test K5): what the columns mean, per trace direction. */
+export const galaxyHierarchyText = {
+ hint: (direction: 'both' | 'inbound' | 'outbound') => direction === 'inbound'
+ ? 'hierarchy: what reaches the root, one column per layer to the left; edge types at the lines'
+ : direction === 'outbound'
+ ? 'hierarchy: what the root reaches, one column per layer to the right; edge types at the lines'
+ : 'hierarchy: incoming relationships on the left, the root in the middle, outgoing on the right; one column per layer, edge types at the lines',
+};
+
const count = (value: number, one: string, many: string) => `${value.toLocaleString()} ${value === 1 ? one : many}`;
/** Loading, cancelling and the render limit of a scope layer (hand test K8). */
diff --git a/graph-ui/src/galaxy/graph-scope.test.ts b/graph-ui/src/galaxy/graph-scope.test.ts
index b9361cfca..9a5476e90 100644
--- a/graph-ui/src/galaxy/graph-scope.test.ts
+++ b/graph-ui/src/galaxy/graph-scope.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it, vi } from 'vitest';
-import { arrangeScopedGraph, graphEdgeTypesKey, limitGraphRender, loadGraphScope, nextLayerEstimate, readGraphPages, scenePictureFor, scopedHierarchy, type GraphQueryClient } from './graph-scope';
+import { arrangeScopedGraph, graphEdgeTypesKey, hierarchyLabelWidth, limitGraphRender, loadGraphScope, nextLayerEstimate, readGraphPages, scenePictureFor, scopedHierarchy, type GraphQueryClient } from './graph-scope';
import type { QueryGraphResult } from '../provider/rpc-schemas';
import type { GraphData, GraphNode } from './types';
@@ -229,6 +229,53 @@ it('retains simple columns for small hierarchy levels', () => {
expect(result.data.nodes.map(node => [node.x, node.y])).toEqual([[0, 0], [160, 16], [160, -16]]);
});
+describe('hand test K5: the scoped hierarchy reads incoming left, root in the middle, outgoing right', () => {
+ const at = (result: ReturnType<typeof scopedHierarchy>, name: string) => result.placements.find(placement => placement.name === name)!;
+ const scoped = (nodes: GraphNode[], edges: { id?: number; source: number; target: number; type: string; line?: number }[], levels: [number, number][]) =>
+ scopedHierarchy({ data: { nodes, edges, total_nodes: nodes.length }, roots: new Set([1]), depth: Math.max(...levels.map(([, hop]) => hop)), exhausted: false,
+ levels: new Map(levels) }, 'root');
+
+ it('puts callers and tests left of the root, its bases right, and keeps the root at the centre', () => {
+ // JSONBAgg: tests call and test it, its module defines it, it inherits two bases.
+ const nodes = [node(1), node(10), node(11), node(30), node(40), node(41)];
+ const result = scoped(nodes, [{ source: 10, target: 1, type: 'CALLS', line: 5 }, { source: 10, target: 1, type: 'TESTS' },
+ { source: 11, target: 1, type: 'CALLS', line: 9 }, { source: 30, target: 1, type: 'DEFINES' },
+ { source: 1, target: 40, type: 'INHERITS' }, { source: 1, target: 41, type: 'INHERITS' }],
+ [[1, 0], [10, 1], [11, 1], [30, 1], [40, 1], [41, 1]]);
+ expect([at(result, 'n1').x, at(result, 'n1').y]).toEqual([0, 0]);
+ for (const name of ['n10', 'n11', 'n30']) expect(at(result, name).x).toBeLessThan(0);
+ for (const name of ['n40', 'n41']) expect(at(result, name).x).toBeGreaterThan(0);
+ expect(result.placements.find(placement => placement.name === 'n10')?.side).toBe(-1);
+ // Every node maps back to its scope identity, for paths drawn in this picture.
+ expect(result.sourceIds?.[at(result, 'n40').id]).toBe(40);
+ });
+
+ it('orders outgoing calls by their call-site line, top to bottom, before other relationship types', () => {
+ const nodes = [node(1), node(2), node(3), node(4), node(5)];
+ const result = scoped(nodes, [{ source: 1, target: 2, type: 'CALLS', line: 30 }, { source: 1, target: 3, type: 'CALLS', line: 12 },
+ { source: 1, target: 4, type: 'CALLS', line: 20 }, { source: 1, target: 5, type: 'IMPORTS' }], [[1, 0], [2, 1], [3, 1], [4, 1], [5, 1]]);
+ const top = [...result.placements].filter(placement => placement.hop === 1).sort((a, b) => b.y - a.y).map(placement => placement.name);
+ expect(top).toEqual(['n3', 'n4', 'n2', 'n5']);
+ });
+
+ it('keeps a second layer on the side of its parent, next to it', () => {
+ const nodes = [node(1), node(2), node(3), node(4), node(5)];
+ // 1 calls 2, 2 calls 3, 4 calls 2 (reached from 2), 5 calls 1.
+ const result = scoped(nodes, [{ source: 1, target: 2, type: 'CALLS' }, { source: 2, target: 3, type: 'CALLS' },
+ { source: 4, target: 2, type: 'CALLS' }, { source: 5, target: 1, type: 'CALLS' }], [[1, 0], [2, 1], [5, 1], [3, 2], [4, 2]]);
+ expect(at(result, 'n3').x).toBeGreaterThan(at(result, 'n2').x);
+ expect(at(result, 'n4').x).toBe(at(result, 'n3').x);
+ expect(at(result, 'n5').x).toBeLessThan(0);
+ });
+
+ it('spaces columns by the names they carry, so long names keep their full width', () => {
+ const long = { ...node(2), name: 'test_jsonb_agg_jsonfield_order_by' };
+ const result = scoped([node(1), long], [{ source: 2, target: 1, type: 'CALLS' }], [[1, 0], [2, 1]]);
+ expect(Math.abs(at(result, long.name).x)).toBeGreaterThanOrEqual((hierarchyLabelWidth(long.name) + hierarchyLabelWidth('n1')) / 2);
+ expect(hierarchyLabelWidth(long.name)).toBeGreaterThan(200);
+ });
+});
+
it('keeps the whole graph on screen while the first scope picture is still empty', () => {
const graph = (count: number): GraphData => ({ nodes: Array.from({ length: count }, (_, id) => ({ id, name: `n${id}`, label: 'Function', x: 0, y: 0, z: 0, size: 1, color: '#999999' })), edges: [], total_nodes: count });
const layout = graph(5), stale = graph(2), current = graph(3), empty = graph(0);
diff --git a/graph-ui/src/galaxy/graph-scope.ts b/graph-ui/src/galaxy/graph-scope.ts
index a62600a4c..a1015bc13 100644
--- a/graph-ui/src/galaxy/graph-scope.ts
+++ b/graph-ui/src/galaxy/graph-scope.ts
@@ -1,4 +1,3 @@
-import { hierarchyBlockPositions } from './hierarchy-blocks';
import { RpcIntelligenceClient } from '../provider/rpc-client';
import { escapeLiteral } from '../provider/cypher';
import type { QueryGraphResult } from '../provider/rpc-schemas';
@@ -263,29 +262,133 @@ export function limitGraphRender(data: GraphData, nodeLimit: number, edgeLimit:
return { ...data, nodes, edges };
}
-/** The same evidence in successive hop blocks. Small hops keep one column;
- * large hops wrap into compact grids so fitting thousands of neighbors does
- * not turn the entire scene into a single vertical line.
+/** Hierarchy constants for a Galaxy scope (hand test K5). Labels are NodeLabels sprites at font 12. */
+export const SCOPED_HIERARCHY_LEVEL_GAP = 160;
+export const SCOPED_HIERARCHY_ROW_GAP = 32;
+/** Texture width of a hierarchy name in a scope: about forty characters before an ellipsis. */
+export const SCOPED_HIERARCHY_LABEL_MAX_TEXT_WIDTH = 1600;
+/** Up to this many nodes every name is drawn, and columns stay single columns; above it they wrap into grids. */
+export const SCOPED_HIERARCHY_LABEL_BUDGET = 60;
+const SCOPED_HIERARCHY_WRAP_AT = 12;
+const LABEL_UNITS_PER_CHAR = 7.1, LABEL_UNITS_PADDING = 12, LABEL_GUTTER = 40;
+const LABEL_MAX_CHARS = Math.floor((SCOPED_HIERARCHY_LABEL_MAX_TEXT_WIDTH - 64) / 38);
+
+/** The world width of a name in the scoped hierarchy, as NodeLabels draws it (about 38 texture pixels per character at 64 px). */
+export function hierarchyLabelWidth(name: string): number {
+ return Math.min(name.length, LABEL_MAX_CHARS) * LABEL_UNITS_PER_CHAR + LABEL_UNITS_PADDING;
+}
+
+/*
+ * Der Ausschnitt als Hierarchie (Handtest K5).
*
- * Hops come from the discovered levels. Only arranged rings encode them in z;
- * a preview built from the overall layout keeps its global coordinates. */
+ * Bis hierher stand alles einer Ebene in EINER Spalte rechts der Wurzel,
+ * Eingehendes und Ausgehendes aller Arten gemischt und alphabetisch, und der
+ * Hinweis behauptete "one column per call depth". Jetzt:
+ *
+ * - Eingehendes links, die Wurzel in der Mitte, Ausgehendes rechts. Ein
+ * Knoten der ersten Ebene steht dort, wohin seine Kante zur Wurzel zeigt;
+ * jeder tiefere Knoten auf der Seite seines Elternknotens, also des
+ * Nachbarn eine Ebene naeher an der Wurzel, ueber den er gefunden wurde.
+ * - In einer Spalte stehen die Knoten nach ihrem Elternknoten, dann CALLS vor
+ * den anderen Arten, CALLS nach Aufrufzeile (`edge.line`), dann nach Name.
+ * - Die Spalten stehen so weit auseinander, wie ihre Namen breit sind: kein
+ * Name wird gekuerzt, solange Platz ist.
+ *
+ * Die Ebene kommt aus den gefundenen `levels`; nur eine Ringanordnung legt sie
+ * in z ab, eine Vorschau aus dem ganzen Layout behaelt globale Koordinaten.
+ * Sehr grosse Ebenen (ohne Namen) brechen weiter in kompakte Raster um.
+ */
export function scopedHierarchy(scope: ScopedGraph, name: string): import('./hierarchy-layout').HierarchyProjection {
+ const levelOf = (node: GraphNode) => scope.roots.has(node.id) ? 0 : scope.levels?.get(node.id) ?? Math.max(0, Math.round(-node.z / 18));
+ const level = new Map(scope.data.nodes.map(node => [node.id, levelOf(node)] as const));
+ const incident = new Map<number, GraphEdge[]>();
+ for (const edge of scope.data.edges) {
+ for (const end of [edge.source, edge.target]) { const list = incident.get(end) ?? []; list.push(edge); incident.set(end, list); }
+ }
+ const typeRank = (edge: GraphEdge | undefined) => edge?.type === 'CALLS' ? 0 : 1;
+ const side = new Map<number, -1 | 0 | 1>(), parent = new Map<number, { id: number; edge: GraphEdge }>();
+ const ordered = [...scope.data.nodes].sort((a, b) => level.get(a.id)! - level.get(b.id)! || a.id - b.id);
+ for (const node of ordered) {
+ const hop = level.get(node.id)!;
+ if (hop === 0) { side.set(node.id, 0); continue; }
+ // The neighbour one layer closer to the root decides the side; a consistently directed edge wins, then CALLS.
+ const candidates = (incident.get(node.id) ?? []).flatMap(edge => {
+ const other = edge.source === node.id ? edge.target : edge.source;
+ const otherSide = side.get(other);
+ if (other === node.id || otherSide === undefined || level.get(other) !== hop - 1) return [];
+ const towards = otherSide !== 0 ? otherSide : edge.source === other ? 1 : -1;
+ const consistent = towards === 1 ? edge.source === other : edge.target === other;
+ return [{ other, edge, towards: towards as -1 | 1, consistent }];
+ }).sort((a, b) => Number(b.consistent) - Number(a.consistent) || typeRank(a.edge) - typeRank(b.edge)
+ || (a.edge.line ?? Number.MAX_SAFE_INTEGER) - (b.edge.line ?? Number.MAX_SAFE_INTEGER) || a.other - b.other);
+ const chosen = candidates[0];
+ side.set(node.id, chosen?.towards ?? 1);
+ if (chosen) parent.set(node.id, { id: chosen.other, edge: chosen.edge });
+ }
const columns = new Map<number, GraphNode[]>();
for (const node of scope.data.nodes) {
- const hop = scope.roots.has(node.id) ? 0 : scope.levels?.get(node.id) ?? Math.max(0, Math.round(-node.z / 18));
- const entries = columns.get(hop) ?? []; entries.push(node); columns.set(hop, entries);
+ const column = side.get(node.id)! * level.get(node.id)!;
+ const entries = columns.get(column) ?? []; entries.push(node); columns.set(column, entries);
+ }
+ const labelled = scope.data.nodes.length <= SCOPED_HIERARCHY_LABEL_BUDGET;
+ const row = new Map<number, number>();
+ const byText = (a: GraphNode, b: GraphNode) => (a.file_path ?? '').localeCompare(b.file_path ?? '') || a.name.localeCompare(b.name) || a.id - b.id;
+ const keys = [...columns.keys()].sort((a, b) => Math.abs(a) - Math.abs(b) || a - b);
+ for (const key of keys) {
+ const entries = columns.get(key)!;
+ entries.sort((a, b) => {
+ const pa = parent.get(a.id), pb = parent.get(b.id);
+ return (row.get(pa?.id ?? -1) ?? -1) - (row.get(pb?.id ?? -1) ?? -1) || typeRank(pa?.edge) - typeRank(pb?.edge)
+ || (pa?.edge.type ?? '').localeCompare(pb?.edge.type ?? '')
+ // Calls in source order; one line with two calls keeps the order of the call list (by identity).
+ || (pa?.edge.type === 'CALLS' ? (pa.edge.line ?? Number.MAX_SAFE_INTEGER) - (pb?.edge.line ?? Number.MAX_SAFE_INTEGER) || a.id - b.id : 0)
+ || byText(a, b);
+ });
+ entries.forEach((node, index) => row.set(node.id, index));
}
- const nodes: GraphNode[] = [], remap = new Map<number, number>();
+ // Column blocks: width from wrapping and from the widest name in them.
+ const block = new Map(keys.map(key => {
+ const entries = columns.get(key)!;
+ const cols = !labelled && entries.length > SCOPED_HIERARCHY_WRAP_AT ? Math.ceil(Math.sqrt(entries.length)) : 1;
+ const label = labelled ? Math.max(...entries.map(node => hierarchyLabelWidth(node.name))) : 0;
+ const gapX = labelled ? label + LABEL_GUTTER : SCOPED_HIERARCHY_ROW_GAP * 1.25;
+ return [key, { entries, cols, rows: Math.ceil(entries.length / cols), gapX, width: (cols - 1) * gapX, label }] as const;
+ }));
+ const left = new Map<number, number>();
+ const centre = block.get(0);
+ if (centre) left.set(0, -centre.width / 2);
+ for (const direction of [1, -1] as const) {
+ let previous = centre ? 0 : undefined;
+ for (const key of keys.filter(value => Math.sign(value) === direction).sort((a, b) => Math.abs(a) - Math.abs(b))) {
+ const current = block.get(key)!, before = previous === undefined ? undefined : block.get(previous)!;
+ const gap = Math.max(SCOPED_HIERARCHY_LEVEL_GAP, before ? (before.label + current.label) / 2 + LABEL_GUTTER : 0);
+ if (direction === 1) {
+ const edge = before ? left.get(previous!)! + before.width : 0;
+ left.set(key, edge + gap);
+ } else {
+ const edge = before ? left.get(previous!)! : 0;
+ left.set(key, edge - gap - current.width);
+ }
+ previous = key;
+ }
+ }
+ const nodes: GraphNode[] = [], remap = new Map<number, number>(), sourceIds: number[] = [];
const placements: import('./hierarchy-layout').HierarchyPlacement[] = [];
- const blocks = [...columns].map(([level, entries]) => ({ level,
- entries: entries.sort((a, b) => (a.file_path ?? '').localeCompare(b.file_path ?? '') || a.name.localeCompare(b.name)) }));
- for (const { node, level: hop, x, y } of hierarchyBlockPositions(blocks, { levelGap: 160, rowGap: 32 })) {
- const id = nodes.length;
- remap.set(node.id, id); nodes.push({ ...node, id, x, y, z: 0 });
- placements.push({ id, key: node.qualified_name ?? `node:${node.id}`, name: node.name, hop, x, y });
+ for (const key of keys) {
+ const { entries, cols, rows, gapX } = block.get(key)!;
+ // Outgoing blocks grow away from the root to the right, incoming ones to the left.
+ const start = left.get(key)!, width = (cols - 1) * gapX;
+ entries.forEach((node, index) => {
+ const column = index % cols;
+ const x = key < 0 ? start + width - column * gapX : start + column * gapX;
+ const y = ((rows - 1) / 2 - Math.floor(index / cols)) * SCOPED_HIERARCHY_ROW_GAP;
+ const id = nodes.length;
+ remap.set(node.id, id); sourceIds.push(node.id); nodes.push({ ...node, id, x, y, z: 0 });
+ placements.push({ id, key: node.qualified_name ?? `node:${node.id}`, name: node.name, hop: level.get(node.id)!, side: side.get(node.id)!, x, y });
+ });
}
return { data: { nodes, edges: scope.data.edges.map(edge => ({ ...edge, source: remap.get(edge.source)!, target: remap.get(edge.target)! })), total_nodes: nodes.length },
rootId: scope.roots.size === 1 ? remap.get([...scope.roots][0]!) ?? -1 : -1, rootKey: name, rootName: name,
- symbols: nodes.length, depth: columns.size, truncated: false, cap: nodes.length, walkDepth: scope.depth,
- missing: 0, placements };
+ symbols: nodes.length, depth: new Set(level.values()).size, truncated: false, cap: nodes.length, walkDepth: scope.depth,
+ missing: 0, placements, sourceIds };
}
diff --git a/graph-ui/src/galaxy/hierarchy-edge-labels.test.ts b/graph-ui/src/galaxy/hierarchy-edge-labels.test.ts
new file mode 100644
index 000000000..1297c7fd0
--- /dev/null
+++ b/graph-ui/src/galaxy/hierarchy-edge-labels.test.ts
@@ -0,0 +1,11 @@
+import { expect, it } from 'vitest';
+import { hierarchyEdgeLabels } from './HierarchyEdgeLabels';
+
+it('hand test K5: writes one label per node pair, its types without repeats and CALLS first', () => {
+ const labels = hierarchyEdgeLabels([
+ { source: 10, target: 1, type: 'TESTS' }, { source: 10, target: 1, type: 'CALLS', line: 5 }, { source: 10, target: 1, type: 'CALLS', line: 9 },
+ { source: 30, target: 1, type: 'DEFINES' }, { source: 1, target: 40, type: 'INHERITS' }, { source: 40, target: 1, type: 'USAGE' },
+ { source: 7, target: 7, type: 'CALLS' },
+ ]);
+ expect(labels.map(label => [label.key, label.text])).toEqual([['1:10', 'CALLS · TESTS'], ['1:30', 'DEFINES'], ['1:40', 'INHERITS · USAGE']]);
+});
diff --git a/graph-ui/src/galaxy/hierarchy-layout.ts b/graph-ui/src/galaxy/hierarchy-layout.ts
index 79f40c0a9..08e3b5f64 100644
--- a/graph-ui/src/galaxy/hierarchy-layout.ts
+++ b/graph-ui/src/galaxy/hierarchy-layout.ts
@@ -184,6 +184,8 @@ export interface HierarchyPlacement {
name: string;
/** Hops von der Wurzel. Die Wurzel selbst ist null. */
hop: number;
+ /** Im Ausschnitt (K5): links eingehend (-1), Mitte Wurzel (0), rechts ausgehend (+1). */
+ side?: -1 | 0 | 1;
/** Die `id` des erzeugten Szene-Knotens. */
id: number;
x: number;
@@ -214,6 +216,8 @@ export interface HierarchyProjection {
missing: number;
/** Je Knoten: wo er sitzt und warum. Der Beweislauf liest daran die Spalten. */
placements: HierarchyPlacement[];
+ /** Im Ausschnitt (K5): je Szene-ID die ID im Scope, damit Pfade auch in diesem Bild liegen. */
+ sourceIds?: number[];
}
/** Die Knoten, die eine Projektion aus dem Server-Layout uebernehmen darf. */
diff --git a/graph-ui/tools/handtest-fixes-galaxy.mjs b/graph-ui/tools/handtest-fixes-galaxy.mjs
index e64d65b66..579eb2304 100644
--- a/graph-ui/tools/handtest-fixes-galaxy.mjs
+++ b/graph-ui/tools/handtest-fixes-galaxy.mjs
@@ -557,8 +557,91 @@ async function checkK6(page) {
}
/* ------------------------------------------------------------------ */
+/* K5: Hierarchie links eingehend, rechts ausgehend */
-const CHECKS = { K9: checkK9, K2: checkK2, K8: checkK8, K3: checkK3, K13: checkK13, K6: checkK6 };
+async function hierarchyLayout(page) {
+ return page.evaluate(() => {
+ const galaxy = globalThis.__atlasGalaxy, fit = globalThis.__atlasGalaxyFit;
+ const canvas = document.querySelector('.atlas-galaxy canvas')?.getBoundingClientRect();
+ const boxes = galaxy?.labelBoxes ?? [];
+ // Namen: Weltkaesten der Szene, mit derselben Kamera in Pixel gerechnet.
+ const names = boxes.map((box) => {
+ // Stand vor K5: ohne `project` gibt es keine Namen-Messung.
+ const [a, b] = typeof fit?.project === 'function'
+ ? fit.project([{ x: box.x - box.width / 2, y: box.y + box.height / 2, z: 0 }, { x: box.x + box.width / 2, y: box.y - box.height / 2, z: 0 }]) : [];
+ return a && b && canvas ? { text: box.name, left: canvas.left + Math.min(a.x, b.x), right: canvas.left + Math.max(a.x, b.x), top: canvas.top + Math.min(a.y, b.y), bottom: canvas.top + Math.max(a.y, b.y), worldWidth: box.width } : null;
+ }).filter(Boolean);
+ const labels = [...document.querySelectorAll('[data-testid="atlas-hierarchy-edge-label"], .atlas-galaxy-path-label')].map((el) => {
+ const r = el.getBoundingClientRect(); return { text: el.textContent?.trim() ?? '', left: r.left, right: r.right, top: r.top, bottom: r.bottom };
+ }).filter((r) => r.right > r.left);
+ const hit = (a, b) => !(a.right <= b.left + 1 || b.right <= a.left + 1 || a.bottom <= b.top + 1 || b.bottom <= a.top + 1);
+ const overlaps = [];
+ for (const label of labels) for (const name of names) if (hit(label, name)) overlaps.push(`${label.text} x ${name.text}`);
+ for (let i = 0; i < names.length; i += 1) for (let j = i + 1; j < names.length; j += 1) if (hit(names[i], names[j])) overlaps.push(`${names[i].text} x ${names[j].text}`);
+ // Abgeschnitten heisst: der Kasten hat die Breitengrenze der Textur erreicht (1600 px bei Schrift 12, rund 312 Einheiten).
+ const truncated = names.filter((name) => name.worldWidth >= 305).map((name) => name.text);
+ const placements = galaxy?.hierarchy?.placements ?? [];
+ const chip = document.querySelector('[data-testid="atlas-graph-mode-chip"][data-mode="hierarchy"]');
+ const hint = chip?.closest('[data-hint]')?.getAttribute('data-hint') ?? chip?.getAttribute('data-hint') ?? '';
+ return { mode: galaxy?.mode, placements: placements.map((p) => ({ name: p.name, x: Math.round(p.x), y: Math.round(p.y), hop: p.hop })),
+ edgeLabels: labels.map((label) => label.text), names: names.length, overlaps, truncated, hint };
+ });
+}
+
+async function checkK5(page) {
+ await section(page, 'K5', 'Hierarchy of a scope: incoming left, root centred, outgoing right, typed edges, full names, call order by line, path and call order');
+ const truth = await relationCounts(ROOT);
+ await open(page);
+ await select(page, ROOT);
+ await settled(page);
+ await page.locator('[data-testid="atlas-graph-mode-chip"][data-mode="hierarchy"]').click();
+ await wait(2500);
+ const view = await hierarchyLayout(page);
+ await shot(page, 'K5', 'hierarchy-root', `${ROOT} at 1 layer in hierarchy: ${view.edgeLabels.length} edge labels, ${view.overlaps.length} overlaps`);
+ const root = view.placements.find((p) => p.name === ROOT);
+ const left = view.placements.filter((p) => p.x < 0), right = view.placements.filter((p) => p.x > 0);
+ const incoming = Object.values(truth.incoming).reduce((sum, n) => sum + n, 0);
+ await check('K5', 'Incoming on the left, root at the centre, outgoing on the right, typed edge labels, full names, no overlaps, honest hint',
+ root?.x === 0 && left.length > 0 && right.length === 2 && left.length + right.length + 1 === view.placements.length
+ && view.edgeLabels.some((text) => /CALLS · TESTS/.test(text)) && view.edgeLabels.some((text) => /DEFINES/.test(text)) && view.edgeLabels.some((text) => /INHERITS/.test(text))
+ && view.overlaps.length === 0 && view.truncated.length === 0 && /incoming relationships on the left/.test(view.hint),
+ { truth: { incomingEdges: incoming, ...truth }, left: left.map((p) => p.name), right: right.map((p) => p.name), edgeLabels: view.edgeLabels,
+ overlaps: view.overlaps, truncated: view.truncated, hint: view.hint });
+
+ // Pfad in der Hierarchie, zu einem Test links.
+ await pickPath(page, 'test_jsonb_agg_charfield_order_by');
+ await wait(2500);
+ const pathView = await hierarchyLayout(page);
+ const pathHeading = await page.locator('[data-testid="atlas-galaxy-path-panel"] strong').first().innerText().catch(() => '');
+ await shot(page, 'K5', 'hierarchy-path', `${pathHeading} in hierarchy: highlighted path, ${pathView.overlaps.length} overlaps`);
+ await check('K5', 'Path to works in the hierarchy and highlights its nodes', /Path to test_jsonb_agg_charfield_order_by · 1 hop/.test(pathHeading)
+ && pathView.mode === 'hierarchy' && pathView.edgeLabels.includes('CALLS'), { pathHeading, edgeLabels: pathView.edgeLabels, overlaps: pathView.overlaps });
+ await page.keyboard.press('Escape');
+ await wait(500);
+
+ // Aufrufreihe: Spalte rechts nach Aufrufzeile.
+ await select(page, 'call_command');
+ await settled(page);
+ await page.locator('[data-testid="atlas-graph-mode-chip"][data-mode="hierarchy"]').click();
+ await wait(2500);
+ const callView = await hierarchyLayout(page);
+ await page.getByRole('button', { name: 'Call order' }).click();
+ await wait(1500);
+ const panelText = await page.locator('[data-testid="atlas-galaxy-path-panel"]').innerText().catch(() => '');
+ const callees = [...panelText.matchAll(/line (\d+)\s+call_command --CALLS--> (\S+)/g)].map((m) => ({ line: Number(m[1]), name: m[2] }));
+ const firstSeen = [...new Map(callees.map((entry) => [entry.name, entry])).values()].map((entry) => entry.name);
+ const rightColumn = callView.placements.filter((p) => p.x > 0 && p.hop === 1).sort((a, b) => b.y - a.y).map((p) => p.name);
+ const columnOrder = rightColumn.filter((name) => firstSeen.includes(name));
+ await shot(page, 'K5', 'hierarchy-call-order', `Call order of call_command in hierarchy: ${callees.length} calls, right column top to bottom ${columnOrder.slice(0, 5).join(', ')}...`);
+ await check('K5', 'The outgoing column of call_command reads in call-site line order, and Call order works in hierarchy', callees.length > 1
+ && JSON.stringify(columnOrder) === JSON.stringify(firstSeen) && callView.overlaps.length === 0,
+ { callees, columnOrder, firstSeen, overlaps: callView.overlaps, truncated: callView.truncated });
+ await page.keyboard.press('Escape');
+}
+
+/* ------------------------------------------------------------------ */
+
+const CHECKS = { K9: checkK9, K2: checkK2, K8: checkK8, K3: checkK3, K13: checkK13, K6: checkK6, K5: checkK5 };
await mkdir(OUT, { recursive: true });
const context = await chromium.launchPersistentContext(PROFILE, {