# How Understand Anything's React Flow Dashboard Visualizes Knowledge Graphs with Architectural Layers

> Learn how Understand Anything's React Flow dashboard visualizes knowledge graphs. Discover its dual-view architecture, ELK layouts, and force-directed fallbacks for detailed topological insights.

- Repository: [Egonex/Understand-Anything](https://github.com/Egonex-AI/Understand-Anything)
- Tags: architecture
- Published: 2026-06-28

---

**The dashboard employs a dual-view architecture that renders architectural layers as color-coded ELK-layout clusters in overview mode, while using a two-stage ELK pipeline with force-directed fallbacks to display file-level topology, containers, and cross-layer portals in detail mode.**

Understand Anything, an open-source knowledge graph visualization tool from the `Egonex-AI/Understand-Anything` repository, transforms complex codebases into interactive, layer-aware diagrams. The React Flow dashboard bridges high-level architectural overview and granular code exploration through a sophisticated layout engine that handles thousands of nodes across distinct architectural layers.

## Dual-View Visualization Architecture

The [`GraphView.tsx`](https://github.com/Egonex-AI/Understand-Anything/blob/main/GraphView.tsx) component serves as the central orchestrator, switching between two distinct visual representations based on the `navigationLevel` state. Each view targets different user intents: the **overview** reveals system-wide layer dependencies, while the **layer detail** exposes internal file structures and relationships.

### Overview Mode: Layer Clusters with ELK Layout

In overview mode, the `useOverviewGraph()` hook aggregates the entire graph into **layer cluster nodes**. Each entry in `graph.layers` becomes a `LayerClusterFlowNode` with fixed dimensions defined by `LAYER_CLUSTER_WIDTH` and `LAYER_CLUSTER_HEIGHT` constants.

The system feeds these nodes into the **ELK (Eclipse Layout Kernel)** hierarchical layout engine via `applyElkLayout()`. First, `nodesToElkInput()` converts React Flow nodes into ELK's JSON format respecting `ELK_DEFAULT_LAYOUT_OPTIONS`. After layout computation, `mergeElkPositions()` maps the calculated coordinates back to the React Flow node structure.

```typescript
// src/components/GraphView.tsx – useOverviewGraph()
const built = useMemo(() => {
  if (!graph) return null;
  const layers = graph.layers ?? [];

  // Build a cluster node per layer
  const clusterNodes: LayerClusterFlowNode[] = layers.map((layer, i) => ({
    id: layer.id,
    type: "layer‑cluster",
    position: { x: 0, y: 0 },
    data: {
      layerId: layer.id,
      layerName: layer.name,
      fileCount: layer.nodeIds.length,
      layerColorIndex: i,
      onDrillIn: drillIntoLayer,
    },
  }));

  // Aggregate inter‑layer edges
  const aggEdges = aggregateLayerEdges(graph).map((agg, i) => ({
    id: `le-${i}`,
    source: agg.sourceLayerId,
    target: agg.targetLayerId,
    label: `${agg.count}`,
    style: { stroke: "rgba(212,165,116,0.4)", strokeWidth: Math.min(1 + Math.log2(agg.count + 1), 5) },
  }));

  // Fixed dimensions for each cluster node
  const dims = new Map<string, { width: number; height: number }>();
  clusterNodes.forEach(n => dims.set(n.id, { width: LAYER_CLUSTER_WIDTH, height: LAYER_CLUSTER_HEIGHT }));

  return { clusterNodes, flowEdges: aggEdges, dims };
}, [graph, drillIntoLayer]);

```

Inter-layer dependencies are visualized as aggregated edges created by `aggregateLayerEdges()`, with stroke widths scaling logarithmically based on connection counts. The [`LayerClusterNode.tsx`](https://github.com/Egonex-AI/Understand-Anything/blob/main/LayerClusterNode.tsx) component renders these clusters using the color palette defined in [`LayerLegend.tsx`](https://github.com/Egonex-AI/Understand-Anything/blob/main/LayerLegend.tsx).

### Layer Detail Mode: Containers and Portals

When drilling into a specific layer via `drillIntoLayer()`, the dashboard switches to `useLayerDetailTopology()`. This mode reveals individual files, classes, and functions using a **two-stage ELK pipeline** that balances performance with layout accuracy.

**Stage 1** treats containers (logical folders derived by `deriveContainers()`) as opaque atoms with estimated dimensions based on `sqrt(nodeCount)`. **Stage 2** lazily computes precise layouts when a user expands a container, caching results in `containerLayoutCache`. If the actual container size deviates more than 20% from the stage 1 estimate, the system triggers `bumpStage1Tick()` to adjust surrounding elements.

```typescript
// src/components/GraphView.tsx – useLayerDetailTopology()
const built = useMemo(() => {
  if (!graph || !activeLayerId) return null;

  const activeLayer = graph.layers.find(l => l.id === activeLayerId)!;
  const layerNodeIds = new Set(activeLayer.nodeIds);

  // Expand “contains” edges for class/function view
  const expandedLayerNodeIds = new Set(layerNodeIds);
  if (detailLevel !== "file") {
    for (const e of graph.edges) {
      if (e.type === "contains" && layerNodeIds.has(e.source)) {
        const child = nodesById.get(e.target);
        if (child && (child.type === "class" || (child.type === "function" && showFunctionsInClassView)))
          expandedLayerNodeIds.add(e.target);
      }
    }
  }

  // Derive containers (folders) and ungrouped nodes
  const { containers, ungrouped } = deriveContainers(
    graph.nodes.filter(n => expandedLayerNodeIds.has(n.id)),
    graph.edges,
  );

  // Build ELK input for stage‑1 (containers + pods)
  const stage1Children = [
    ...containers.map(c => ({ id: c.id, width: NODE_WIDTH, height: NODE_HEIGHT })),
    ...ungrouped.map(id => ({ id, width: NODE_WIDTH, height: NODE_HEIGHT })),
    ...portals.map(p => ({ id: `portal:${p.layerId}`, width: PORTAL_NODE_WIDTH, height: PORTAL_NODE_HEIGHT })),
  ];

  const elkInput: ElkInput = {
    id: "layer",
    layoutOptions: ELK_DEFAULT_LAYOUT_OPTIONS,
    children: stage1Children,
    edges: [...aggEdges, ...portalEdges],
  };

  // Run ELK → positions for containers/portals
  applyElkLayout(elkInput, …).then(({ positioned }) => {
    const nodes = mergeElkPositions([...containerFlowNodes, ...ungroupedFlowNodes, ...portalNodes], positioned);
    setTopology({ …, nodes });
  });
}, [graph, activeLayerId, detailLevel, showFunctionsInClassView]);

```

**Portals** represent cross-layer dependencies. The `computePortals()` function in [`src/utils/edgeAggregation.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/src/utils/edgeAggregation.ts) generates `PortalNode` elements—small rectangles that, when clicked, trigger navigation to the target layer. These appear as dotted edges connecting containers to external layers.

## Data Flow and State Management

The global state lives in [`src/store.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/src/store.ts), implemented with Zustand. It maintains:

- The core `graph` object (nodes, edges, and the `layers` array)
- Fast-lookup indexes: `nodeIdToLayerId` and `nodesById`
- UI state for selection, focus, and tour navigation

[`KnowledgeGraphView.tsx`](https://github.com/Egonex-AI/Understand-Anything/blob/main/KnowledgeGraphView.tsx) consumes this store for the force-directed knowledge graph view, computing node dimensions based on edge count and caching positions to prevent layout shifts during re-renders.

## Layout Algorithms and Performance Optimization

The dashboard implements **three layout strategies** depending on context:

1. **ELK Layered Layout**: Used for hierarchical structures in overview mode and container arrangements in detail mode. Handles edge routing and node placement respecting layer boundaries.
2. **Force-Directed Layout**: Implemented in `applyForceLayout()` within [`src/utils/layout.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/src/utils/layout.ts), used for the generic knowledge graph view when ELK is unnecessary or for small graph fallbacks.
3. **Hybrid Two-Stage ELK**: Combines fast initial placement (stage 1) with detailed expansion (stage 2) to maintain 60fps interactions while exploring deep hierarchies.

Asynchronous layout computation prevents UI blocking. The `TourFitView` and `SelectedNodeFitView` hooks automatically pan and zoom to highlight nodes after layout completion.

## Visual Design System

Layer identity is encoded through a centralized color system in [`LayerLegend.tsx`](https://github.com/Egonex-AI/Understand-Anything/blob/main/LayerLegend.tsx). The `LAYER_PALETTE` array defines background, border, and label colors for each architectural layer index.

```typescript
// src/components/LayerLegend.tsx
export const LAYER_PALETTE = [
  { bg: "rgba(74,124,155,0.12)", border: "rgba(74,124,155,0.4)", label: "#4a7c9b" }, // blue (API)
  { bg: "rgba(90,158,111,0.12)", border: "rgba(90,158,111,0.4)", label: "#5a9e6f" }, // green (Data)
  // … more entries …
];

export function getLayerColor(index: number) {
  return LAYER_PALETTE[index % LAYER_PALETTE.length];
}

```

The **MiniMap** component mirrors this palette, allowing users to maintain spatial awareness of layer distribution even when zoomed into specific regions. [`ContainerNode.tsx`](https://github.com/Egonex-AI/Understand-Anything/blob/main/ContainerNode.tsx) and [`PortalNode.tsx`](https://github.com/Egonex-AI/Understand-Anything/blob/main/PortalNode.tsx) inherit these colors through their `layerColorIndex` data properties.

## Summary

- The dashboard switches between **overview** (layer clusters) and **layer detail** (file topology) modes via [`GraphView.tsx`](https://github.com/Egonex-AI/Understand-Anything/blob/main/GraphView.tsx) and the `navigationLevel` state.
- **ELK layout** powers hierarchical positioning in both modes, with a two-stage pipeline optimizing performance for deep container hierarchies.
- **Containers** group files by folder structure, rendering initially as placeholder atoms that expand into precise layouts on interaction.
- **Portals** visualize cross-layer dependencies as clickable navigation targets between architectural boundaries.
- The **color system** in [`LayerLegend.tsx`](https://github.com/Egonex-AI/Understand-Anything/blob/main/LayerLegend.tsx) provides consistent visual encoding across nodes, the MiniMap, and the legend UI.
- All layout computation is **asynchronous** with position caching to ensure smooth React Flow interactions at scale.

## Frequently Asked Questions

### How does the dashboard handle thousands of nodes without performance degradation?

The system uses **edge aggregation** via `aggregateLayerEdges()` and `aggregateContainerEdges()` to collapse multiple relationships into single visual edges. In layer detail mode, the two-stage ELK pipeline renders containers as simplified atoms initially, computing exact child layouts only when expanded. This lazy evaluation strategy, combined with React Flow's virtualization and position caching in `containerLayoutCache`, maintains interactive frame rates even with large codebases.

### What triggers the transition from overview mode to layer detail mode?

The transition occurs when a user clicks a **layer cluster node** or a **portal node**, invoking the `drillIntoLayer` callback. This updates the `activeLayerId` in the global store ([`src/store.ts`](https://github.com/Egonex-AI/Understand-Anything/blob/main/src/store.ts)), causing [`GraphView.tsx`](https://github.com/Egonex-AI/Understand-Anything/blob/main/GraphView.tsx) to switch from `useOverviewGraph()` to `useLayerDetailTopology()`. The view automatically fits to the new nodes using `SelectedNodeFitView` after the ELK layout resolves.

### Why does the dashboard use ELK instead of React Flow's built-in layout algorithms?

**ELK (Eclipse Layout Kernel)** provides sophisticated hierarchical layout capabilities essential for architectural visualization, including proper handling of nested containers, edge routing that avoids overlaps, and layered graph drawing. While React Flow offers basic auto-layout, ELK's `layered` algorithm correctly positions architectural layers according to dependency direction and manages the complex constraints of **container atoms** versus **leaf nodes** required by the two-stage rendering pipeline.

### How are layer colors determined and kept consistent across views?

Colors are deterministic based on layer index. The `getLayerColor()` function in [`LayerLegend.tsx`](https://github.com/Egonex-AI/Understand-Anything/blob/main/LayerLegend.tsx) indexes into the `LAYER_PALETTE` array using modulo arithmetic, ensuring that the API layer (index 0) always renders as blue, the Data layer (index 1) as green, and so on. This palette is applied to `LayerClusterNode` backgrounds, `PortalNode` borders, and the MiniMap shading through a centralized `nodeColor` callback, guaranteeing visual consistency during navigation transitions.