@nexgraph/core
v0.1.4
Published
GPU-first WebGL2 graph visualization engine (renderer, layout, parsers)
Maintainers
Readme
@nexgraph/core
GPU-first WebGL2 graph visualization for the browser — batched node discs, chunked edges, frustum-aware draws and LOD for large graphs. Built on typed arrays and first-party shaders, not a bundled scene engine.
Demo: nexgraph-demos.vercel.app
A React wrapper is published as @nexgraph/react.
Install
npm install @nexgraph/coreESM-only. You need a WebGL2 context (canvas.getContext('webgl2')) and a bundler that resolves workers for parsing and force layout (Vite and webpack 5 work out of the box).
Features
Renderer— canvas, orbit camera, instanced node discs, chunked edges, SDF labels, LOD, optional debug overlayGraphStore— typed-array positions, sizes, colours, edges and labels;setNodes/setEdges, partialupdatePositions/updateSizes, visibility masksForceLayout— Barnes–Hut worker simulation (FORCE_LAYOUT_DEFAULTS,createForceConfigPreset), plussetPinned/pin/unpinparseGraphAsync— JSON or CSV in a worker, typed arrays back on the main threadPickingSystem— CPU ray-vs-sphere picking (no GPU readback)- Bundled Ubuntu Medium label font, swappable via
labelFont/setLabelFont carryLayoutPositions— keep settled world positions across a refetch by matching node labelsapplyDegreeWeightFilters,computeNodeDegrees,degreeCentrality— visibility and degree helpers
Quick start
import { Renderer, parseGraphAsync } from '@nexgraph/core';
const mount = document.getElementById('graph')!;
const renderer = new Renderer({ parent: mount });
async function loadJson(text: string) {
const r = await parseGraphAsync('json', text);
if (r.nodeCount > 0) {
renderer.graph.setNodes(r.positions, undefined, undefined, r.labels);
}
if (r.edgeCount > 0) {
renderer.graph.setEdges(r.edgeIndices);
}
renderer.fitToData();
}
renderer.start();
void loadJson(
JSON.stringify({
nodeCount: 2,
labels: ['a', 'b'],
edges: [{ source: 0, target: 1 }],
}),
);Typical flow: create a Renderer with a DOM parent, fill renderer.graph (setNodes / setEdges) or load with parseGraphAsync, optionally run ForceLayout and push onTick positions into graph.updatePositions, then start(). Frame the graph with fitToData(). On teardown: forceLayout.dispose(), renderer.dispose().
Controls: left-drag rotates; right-drag or Shift-drag pans the look-at target; wheel zooms distance. The camera is not locked to the graph centroid — call fitToData() when you want it reframed.
When parseGraphAsync sets result.layoutSuggested, wire ForceLayout and call start with graph.positions, graph.edgeIndices, counts and a ForceConfig:
import { ForceLayout } from '@nexgraph/core';
const layout = new ForceLayout();
layout.onTick = (positions) => renderer.graph.updatePositions(positions);
layout.onStabilized = (positions, _iteration, viewTarget) => {
renderer.graph.updatePositions(positions);
if (viewTarget) renderer.setViewTarget(viewTarget);
else renderer.fitToData();
};Parsing and force simulation run in workers — avoid huge synchronous transforms on the main thread before handing data to GraphStore. Simulation stops when alpha cools below alphaMin, kinetic energy is below the quiet threshold, or maxIterations is reached (see FORCE_LAYOUT_DEFAULTS). Graphs in the millions of edges need LOD (edgeBudget, progressive chunks).
Renderer options
Everything in RendererOptions. Only parent is required.
| Option | Type | Default | Notes |
| -------------------- | ------------------------------ | ----------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| parent | HTMLElement | — | Container; the canvas is appended to it. A static parent is switched to position: relative. |
| pixelRatioCap | number | 2 | Upper bound for devicePixelRatio. |
| contextOptions | ContextOptions | see notes | Read once, when the context is created: alpha: false, antialias: false, preserveDrawingBuffer: false, powerPreference: 'high-performance'. |
| showOverlay | boolean | false | FPS / draw-call overlay. |
| lod | Partial<LODSettings> | all off | edgeBudget, edgeMaxDistance, edgeSampleBudget (0 = off), edgeSampleSeed (42), progressiveChunksPerFrame (4). |
| nodeSizeMultiplier | number | 1 | Scales node billboards and the pick sphere. |
| maxVisibleLabels | number | label cap (25 000) | -1 or Infinity = the cap; 0 or any other negative = no labels. |
| edgeOpacity | number | 1 | Multiplied with per-edge alpha; clamped to 0–1. |
| edgeWidth | number | 2 | Edge stroke in CSS px, max 64; invalid or negative falls back to 2. |
| nodeOpacity | number | 1 | Multiplied with per-node alpha. Discs still write depth, so edges stay hidden behind them. |
| backgroundColor | BackgroundColor | '#0f1217' | CSS hex (#RGB, #RRGGBB, #RRGGBBAA) or linear 0–1 [r, g, b] / [r, g, b, a]. |
| selectionHighlight | boolean | true | Selection rim on the clicked node; onSelect fires either way. |
| nodeDragMode | 'off' \| 'pin' \| 'snapBack' | 'off' | Drag nodes with the pointer; see Dragging nodes. |
| labelFont | LabelFontOptions | { family: 'Ubuntu', weight: 500 } | See Label font. |
| labelOutlineColor | [r, g, b, a] (0–1) | [0, 0, 0, 0.85] | Label halo; alpha 0 turns it off. |
| labelOutlineWidth | number | 0.15 | Halo thickness in SDF units, 0–0.45. |
Most options are also writable after construction: nodeSizeMultiplier, maxVisibleLabels, edgeOpacity, edgeWidth, nodeOpacity, backgroundColor, selectionHighlight, labelOutlineColor and labelOutlineWidth are plain properties; the rest have methods:
| Method | Purpose |
| ---------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
| start() / stop() / dispose() | Run, pause or tear down the render loop and release GPU resources. |
| fitToData() | Aim the orbit camera at the node centroid and set the distance from the bounding radius. |
| setViewTarget([x, y, z]) | Move the look-at target, keeping distance and angles (non-finite input is ignored). |
| setLabelFont(font?) | Load a font and rebuild the label atlas; resolves when done and never rejects. |
| setLabelsVisible(visible) | Show or hide all labels. |
| setNodeDragMode(mode) | Change nodeDragMode at any time. |
| setNodeDragPinCallback(cb) | Receive (indices, pinned, positions?) when a drag pins or releases a node — forward to ForceLayout.setPinned. |
| setPixelRatioCap(cap) | Change pixelRatioCap. |
| setShowOverlay(visible) | Toggle the debug overlay. |
| setDrawCallback(cb) | Your own GL draws each frame, after the built-in passes (labels included). |
| setBeforeFrameCallback(cb) | Work between Camera.update and the scene draws, e.g. layout smoothing. |
| lod.applySettings(patch) | Update LOD settings. |
Dragging nodes
With nodeDragMode: 'pin' a dropped node stays where you put it; 'snapBack' restores its position on release. To make the force layout respect the drag, connect the two objects:
const layout = new ForceLayout();
renderer.setNodeDragPinCallback((indices, pinned, positions) =>
layout.setPinned(indices, pinned, positions),
);
layout.onTick = (positions) => renderer.graph.updatePositions(positions);
layout.onStabilized = (positions, _iteration, viewTarget) => {
renderer.graph.updatePositions(positions);
// Set only when `recenterOnFinish` is on and nodes are pinned: positions were left alone.
if (viewTarget) renderer.setViewTarget(viewTarget);
};Label font
Labels use the bundled Ubuntu Medium (weight 500, Latin subset) by default; a system sans-serif shows until it has loaded. Pick another font at construction or later:
const renderer = new Renderer({
parent,
labelFont: { family: 'Inter', weight: 600, url: '/fonts/inter-600.woff2' },
});
await renderer.setLabelFont({ family: 'system-ui', weight: 600 });
await renderer.setLabelFont(); // back to the bundled UbuntuLabelFontOptions:
family— a family name or a CSS font-family list; a sans-serif fallback stack is always appended. Default'Ubuntu'.weight— CSS weight. Default500. The bundled Ubuntu has only Medium, so any weight on'Ubuntu'renders Medium.url— optional font file (woff2,woff,ttf,otf) loaded asfamilywithFontFace. Without it,familyis looked up among system fonts and your own@font-facerules. Loading a differenturlfor afamilyandweightthat already have one replaces the earlier file, so use distinct family names if you need both at once.
A later setLabelFont call supersedes one still loading, including the constructor font. A font that fails to load logs a warning and labels keep the fallback stack. The atlas contains printable ASCII only. labelOutlineColor / labelOutlineWidth control the dark halo around each letter. Lower-level pieces (loadLabelFont, resolveLabelFont, createSdfAtlas, DEFAULT_LABEL_FONT_FAMILY, DEFAULT_LABEL_FONT_WEIGHT, DEFAULT_LABEL_OUTLINE_WIDTH) are exported for custom renderers.
packages/core/src/index.ts also exports lower-level render helpers (NodeRenderer, EdgeRenderer, GL utilities, math namespaces). Treat those as power-user APIs — they may change more often than Renderer / GraphStore / ForceLayout.
License
MIT © see LICENSE in the repository.
The bundled default label font, Ubuntu Medium (© 2011 Canonical Ltd.), is licensed under the Ubuntu Font Licence 1.0.
