Concepts

This page is the mental model for @kineviz/gl. Read it once; the API reference + recipes will make more sense afterward.

What the library is

@kineviz/gl is a GPU-first graph rendering engine wrapped in a single React component. It renders nodes + edges, runs a force-directed or geometric layout, handles user interaction (click, hover, drag, selection), and exposes an imperative RenderEngineApi for everything the declarative props don't cover.

It is renderer-and-layout, not a graph database. You bring the data; the engine draws it.

The three surfaces

You interact with the engine through three orthogonal surfaces:

Surface What it's for Example
Declarative props Configuration + controlled state + callbacks <GraphCanvas selection={s} onNodeClick={...} forceLayout />
Imperative API (apiRef) One-off actions, programmatic mutations api.nodes.add([...]); api.camera.flyToNodes(...)
Event stream (api.events.on) Anything not yet a declarative prop api.events.on("style:changed", ...)

Pick the leanest surface that does the job. Props for "what the canvas should look like"; API for "do this once"; events for "tell me when X happens." The recipe pages in this manual all show this in action.

Data model

The engine sees the graph as plain JS objects:

What you pass in:

interface NodeInput {
  id?: string;                                   // generated when omitted
  category: string;                              // required — styling, filtering, grouping
  labels?: string[];
  properties?: Record<string, PropertyValue>;
  position?: { x: number; y: number; z?: number };  // optional initial position
}

interface EdgeInput {
  id?: string;                                   // generated when omitted
  source: string;                                // source node id
  target: string;                                // target node id
  relationship: string;                          // required — styling, filtering
  properties?: Record<string, PropertyValue>;
}

What you read back — NodeData / EdgeData — is the same shape with id and properties filled in, and without position (positions live in the layout, not on the record).

category and relationship are the only interpreted fields: they key the per-category and per-relationship visual configuration. The engine does not interpret properties at all — it is payload your host code reads in filters, tooltips and callbacks.

Edges are addressed by source / target, not by index. Deletes are in-place swap-removes, so an index you held across a deletion is no longer valid — re-resolve by id.

You add data with api.nodes.add([...]) / api.edges.add([...]), replace everything by passing new data to <GraphCanvas data={{ nodes, edges }} />, clear with api.nodes.clear() / api.edges.clear(), and import a whole styled graph with api.io.

Coordinate spaces

Three coordinate spaces show up in callback payloads and API calls:

Space Unit Where it lives Example
Screen CSS pixels, viewport-relative Native pointer events event.clientX / clientY
Canvas CSS pixels, canvas-relative canvasPos field on every interaction event [12, 340] — useful for positioning tooltips
World Three.js scene units worldPos on interaction events; viewState.position [1.5, -2.0, 0] — useful for spatial logic

The engine handles the screen→world raycast for you; you receive both canvas and world coordinates in every callback. World space is what the layout produces and what setNodePosition writes.

Subsystems

The engine is composed of subsystems, each exposed as a property on RenderEngineApi. The major ones:

Subsystem Owns Typical props
nodes / edges CRUD on the graph data data
query Reading the graph without mutating it —
types / schema Category and relationship schemas —
io Import / export, including styled archives —
selection Which nodes/edges are selected selection / onSelectionChange
camera View position + zoom + rotation viewState / onViewStateChange, cameraZ
renderer Theme, projection mode, size scale, screenshot, render path theme / defaultTheme, enableWebGPURenderPath
layout Geometric layouts, and layouts you register — (called imperatively)
force layout Force-directed simulation forceLayout (subsystem mount toggle)
map Geographic tiled basemap map (subsystem mount toggle)
interaction Click / hover / drag detection the on*Click, on*Hover, on*Drag callbacks
hover Programmatic hover target hoveredId / onHoverChange
emphasis Click-neighbourhood dim, hover glow, focus + context clickDim
history Undo / redo of mutations onHistoryChange
style Per-node and per-category colour, size, icon, caption, badges —
filter Declarative subset hiding — (see the Filtering page)
groups Collapsible meta-nodes —
transform Geometric transforms over positions —
algorithms Centrality, communities, paths onAlgorithmStart/End/Error/Progress
animations Tween primitives and built-in effects —
markers / coverage / polygon / overlays Batteries-included visual layers —
cards HTML cards over the graph, including HTML nodes —
layers Mount your own LayerRenderer —
timeline / playback / flows Time-driven playback —
ui Toolbar, legend and panel surfaces toolbar, legend
skills Named, parameterised commands —
events Cross-cutting event bus every on*Change / on* callback ultimately reads this

You don't need to learn them all up front. Reach for an api.X namespace when you need a one-off action; the declarative props cover the 80% case.

Three style layers

Independently of the props, three layers decide a node's colour, size, shape and icon:

  1. mapping — data-driven, from the per-category visual configuration;
  2. imperative — what a user or your code set on purpose through api.style;
  3. transient — selection, hover and animation, resolved at draw time.

An imperative set claims that attribute, and a later re-map no longer overwrites it. That is a change in behaviour from earlier releases — see Node appearance.

Three configuration layers

When a prop overlaps with API ownership, the precedence is:

controlled prop  >  uncontrolled defaultX prop  >  engine default

The controlled / uncontrolled / onChange triple (Rule 4 from the schema) lets the host own state at any layer. See State Persistence for the patterns. The vast majority of props are uncontrolled-only (simple value, no callback) because they don't have engine-internal state.

Lifecycle

Mount → ready → interactive → unmount:

GraphCanvas mounts
  ├── Renderer constructed (WebGL, or WebGPU when allowed and available)
  ├── Scene + camera initialised
  ├── Subsystems wired (interaction, hover, drag, layout)
  ├── apiRef.current populated
  └── onReady(ctx) fires
     ↓
User mutations (api.nodes.add, drag, fly, filter, etc.)
  ├── Each mutation emits an engine event (graph:deltaApplied, etc.)
  ├── Controlled-state callbacks fire (onSelectionChange, onViewStateChange, etc.)
  └── Render loop runs every animation frame (RAF or invalidate-driven)
     ↓
GraphCanvas unmounts
  ├── onDestroy() fires
  ├── Subsystems disposed (interaction listeners removed, hover handlers detached)
  ├── Graphics context disposed
  └── apiRef.current set to null

onReady is the moment to stash apiRef.current into your own ref/store if you want to call engine methods from outside the React tree. Between onReady and onDestroy everything works.

Layout sources

The engine doesn't pick where nodes go; that's the layout's job. There are three sources, in increasing order of control:

  1. forceLayout prop — the built-in force-directed simulation (WebGPU or d3 CPU, auto-chosen). Best for "I have relational data and want a sensible arrangement out of the box." See the Force Layout page.

  2. layout.* namespace — one-shot geometric layouts (circle, grid, spiral, scatter, ego, …). They compute positions once and stop; no simulation.

  3. layoutController prop — bring your own. Pass any object that implements LayoutControllerInterface (a worker-thread layout, a server-computed layout, a custom GPU compute pipeline). The forceLayout prop is ignored when layoutController is set.

You can also bypass layout entirely by writing positions directly via api.layout.setPositions(...) or by including position: {x, y, z} on each NodeData.

Rendering: render-on-demand

The engine runs an invalidate-driven render loop. It does not re-render every frame unless something is animating. When you mutate data (api.nodes.add), change a prop, or the force simulation ticks, the affected subsystem flips a renderNeedsUpdate flag and the next animation frame renders. When nothing is happening, the GPU is idle.

This means:

  • Static graphs cost ~0 frames after the initial render.
  • A running force layout costs 60 fps until it converges (alpha decays).
  • Hover dim / selection ring transitions cost frames during their tween durations.

The engine can draw through WebGL or an opt-in WebGPU path; which one is active does not change the public API. See Rendering.

Subsystem mount toggles

Some subsystems are off by default (they cost memory / shader compile time on first paint). Toggle them on via boolean | Config props:

<GraphCanvas
  data={graph}
  forceLayout                            // on with defaults
  map                                    // on with cartoDark tiles
  toolbar={false}                        // off
  caption={{ property: "name" }}         // on with custom config
/>

Each subsystem-mount prop accepts true (defaults), false (off), or a config object (on with overrides). The pattern is uniform — see "Subsystem mount toggles" category in the GraphCanvasProps table.

Naming conventions

The schema rules from the prop redesign are:

  • Boolean toggles are bare names: drag, controls, antialias, clickDim. No enable* prefix. (Legacy enableDrag / enableControl are still accepted as @deprecated aliases.) They are off unless the prop table says otherwise — clickDim, for one, is now off by default.
  • Scalars carry a semantic suffix: cameraZ, pixelRatio, textScale, backgroundColor, edgeTextScale.
  • Callbacks are on<Subject><Event>, present-tense: onNodeClick, onSelectionChange, onError, onLayoutEnd.
  • Controlled triples are <state> + default<State> + on<State>Change, with one documented carve-out: hoveredId has no defaultHoveredId (mount-time hover is incoherent).
  • Subsystem props are boolean | <Subsystem>Config. true = on with defaults; false = off; object = on with overrides.

If a prop you expect doesn't follow these rules, it's almost certainly a legacy alias kept for back-compat — check the deprecated badge in the GraphCanvasProps table.

Where to go next