Widgets
@practic/bui
@practic/bui
@practic/persist
@practic/bui-theme-editor
@practic/passkey
@practic/tsconfig-builder
@practic/force-directed
@practic/force-directed
3D force-directed graphs and a 2D node editor for React Three Fiber, with settings panels, JSON import and export, and storage in IndexedDB.
@practic/force-directedv1.0.0Demo ↗API docs ↗
Force-directed layout for your own graphs, in 1, 2 or 3 dimensions, plus the React Three Fiber pieces to draw and edit them, and two finished graph apps built from those pieces.
A graph view needs a layout simulation, a worker so it does not freeze the page, thousands of instanced meshes, a camera, controls, storage and a settings UI. This package gives you each of those as a separate tool:
ForceGraph and NodesGraph, assembled from those pieces, which store everything in the
browser.To get coordinates for your own data, install the package on its own:
npm install @practic/force-directed
Or bun add, pnpm add, yarn add.
import { forceGraphLayout, forceGraphToJson } from '@practic/force-directed/layout'
const laidOut = forceGraphLayout({
nodes: [
{ id: 'ada', team: 'compilers' },
{ id: 'grace', team: 'compilers' },
{ id: 'alan', team: 'theory' },
],
links: [
{ source: 'ada', target: 'grace' },
{ source: 'grace', target: 'alan' },
],
})
// Plain JSON. Each node keeps your fields, gets x, y and z, and gets a fixed `node#<uuid>` id, with yours in `key`.
console.log(JSON.stringify(forceGraphToJson(laidOut), null, 2))
The same input always gives the same coordinates and node ids. To draw graphs, install the rendering peers too:
npm install @practic/force-directed @practic/bui @practic/persist @base-ui/react three @react-three/fiber @react-three/drei react react-dom
Then, in explorer.tsx:
import { FORCE_GRAPH_HELP, ForceGraph, type ForceGraphProps } from '@practic/force-directed'
import '@practic/bui/themes/barebones.css'
export const forceGraphLabelsEn: ForceGraphProps['labels'] = {
search: { name: 'Search node labels', placeholder: 'Search labels', noMatch: 'No label matches.', noneLabelled: 'No node is labelled yet.' },
node: {
title: 'Node',
coordinates: 'Coordinates',
label: 'Label',
noLabel: 'No label',
editHint: 'Double-click the node to move it and edit its label.',
emptyHint: 'Click a node to see its coordinates; double-click it to move it and label it.',
},
generate: {
nodes: 'Nodes',
linkDistance: 'Link distance',
label: 'Label',
unnamed: (count) => `${count} nodes`,
generate: 'Generate',
note: 'Each node count and link distance pair is stored separately; an existing pair is opened instead.',
},
camera: { type: 'Type', types: { perspective: 'Perspective', orthographic: 'Orthographic' }, fieldOfView: 'Field of view' },
file: {
download: 'Download',
load: 'Load file',
invalidJson: 'The file is not valid JSON.',
invalidFile: 'Expected an object with "nodes" and "links" arrays.',
},
settings: {
menu: 'Force graph settings',
graphSection: 'Graph',
cameraSection: 'Camera',
generateSection: 'Generate',
contentSection: 'Content',
graph: 'Graph',
summary: ({ count, distance }) => `${count} nodes · link distance ${distance}`,
label: 'Label',
geometry: 'Geometry',
geometries: { box: 'Box', sphere: 'Sphere', tetrahedron: 'Tetrahedron' },
deleteGraph: 'Delete graph',
deleteTitle: (label) => `Delete the graph "${label}"?`,
deleteDescription: ({ count, distance }) => `Its ${count} nodes (link distance ${distance}) and camera view are removed.`,
delete: 'Delete',
replaceTitle: (label) => `Replace the graph "${label}"?`,
replaceDescription: ({ count, distance }) =>
`The file has ${count} nodes and link distance ${distance}, the same as this stored graph, which it overwrites.`,
replace: 'Replace',
cancel: 'Cancel',
},
defaultGraph: 'Default',
rendering: 'Rendering',
help: { title: 'Force graph help', close: 'Close Force graph help', markdown: FORCE_GRAPH_HELP },
}
export function Explorer() {
return (
<div style={{ height: '100vh' }}>
<ForceGraph labels={forceGraphLabelsEn} />
</div>
)
}
The graph fills its parent. It has no default texts: labels words every one, so the same object in another language
translates it, and FORCE_GRAPH_HELP is its help in English. Open the cog in the top-right corner to generate another graph, change the geometry or
camera, or download the current one. Click a node to fly to it; double-click it to move it and label it.
forceGraphLayout takes your nodes and links, keeps every field you put on them, and
never changes your arrays. Pinned nodes stay put, and nodes with coordinates start from them.uuidv5 ids, the same on every run; nodes and links without one get a fresh uuidv4.d3-force takes: one value for all, or a function per node or link.ForceGraph goes up to 100,000 nodes),
reports progress and can be cancelled. Its handler also runs in a worker of your own.@practic/force-directed/layout has no React, three.js or DOM, and no 'use client' banner,
so server code can call it.color
or a palette, with perspective or orthographic cameras.nodesGraphCreateTools gives the same tools over a graph of your own.localStorage, under a
namespace of your choice.d3-force's, so they stay in step with it.| Import | What it gives you |
|---|---|
@practic/force-directed/layout | The layout, ids, JSON output and worker tools. No peers needed. |
@practic/force-directed | Everything in /layout, plus the components, drawing pieces and 2D editing tools. |
@practic/force-directed/html-in-canvas | Experimental: HtmlInCanvas renders React HTML onto a plane in an R3F scene. |
@practic/force-directed/demo | Demo: the force graph, the nodes graph and the layout tools behind a header. |
forceGraphLayout(options) lays out a graph until it settles and returns its nodes and links. Link ends are the
laid-out nodes, as d3 leaves them; forceGraphToJson turns that into plain JSON. Every option is optional.
| Option | Default | Description |
|---|---|---|
nodes | generated | Your nodes. An id not already node#<uuid> becomes node#<uuidv5(id, idNamespace)>, with the original in key. |
links | generated | Your links between nodes, by node id. Links without an id get a new one. |
len | 1000 | Nodes to generate when no nodes are given, with len / 3 links between them. |
dimensions | 3 | 1, 2 or 3. With fewer than three, the missing coordinates stay unset. |
source | 'fixed' | The simulation's random source: seeded ('fixed') or Math.random ('random'). |
idNamespace | FORCE_GRAPH_ID_NAMESPACE | Uuid namespace your fixed ids are derived in. |
forces.linkDistance | 30 | Target length of links: a number, or a function of the link. |
forces.linkStrength | d3's | How hard links pull toward their length. |
forces.charge | d3's (-30) | Repulsion (negative) or attraction (positive) between nodes. |
forces.center | [0, 0, 0] | Point the graph is centred on, or false to leave it where the forces put it. |
forces.collide | none | Radius each node keeps clear, so nodes drawn with a size never overlap. |
simulation.alphaMin | d3's (0.001) | Alpha at which the layout stops. |
simulation.alphaDecay | d3's | How fast alpha cools: higher settles sooner, less precisely. |
simulation.velocityDecay | d3's | Friction on node velocities. |
simulation.maxTicks | none | Most ticks to run, to stop early. |
onProgress | Receives { min, max, current, percent } before each tick. | |
signal | An AbortSignal; aborting stops between ticks and throws its reason. |
Nodes may carry x, y, z to start from, and fx, fy, fz to stay pinned. A duplicate id or a link to an
unknown node throws an error that names it. A result can be laid out again: its ids are kept.
| Export | Description |
|---|---|
forceGraphToJson(graph, { linkEnds }) | Drops index and velocities, keeps your fields. Link ends become ids ('id', default) or { id, x, y, z } ('coords'). |
forceGraphCoords3D({ len, distance, source, nodes, links, setProgress }) | The older form of forceGraphLayout, in 3D, kept for its distance and setProgress names. |
forceGraphCreateLayoutWorker() | Starts a worker that lays out graphs, bundled inline, so it needs no bundler setup. Terminate it when done. |
forceGraphLayoutInWorker(worker, options, { onProgress, signal }) | Lays out in that worker and resolves with the JSON. Options are forceGraphLayout's, without functions, plus linkEnds. |
forceGraphHandleLayoutMessages(self) | Makes a worker of your own answer forceGraphLayoutInWorker. |
nodeCreateId(key?, namespace?), linkCreateId(key?, namespace?) | node#<uuidv4> / link#<uuidv4>, or the fixed uuidv5 of a key. |
isGraphId(value, kind) | Whether a value already is a node#<uuid> or link#<uuid> id. |
forceGraphCreateSeededRandom(seed) | A seeded generator of numbers from 0 to 1, for repeatable randomness of your own. |
forceGraphMoveNode, forceGraphLabelNode, linkGetNodeId | Small immutable edits of a graph, and reading a link end's node id. |
Lay the graph out in the worker, then hand the JSON to ForceGraphCanvas, the 3D view with no storage or panels:
import {
forceGraphCreateLayoutWorker,
forceGraphLayoutInWorker,
ForceGraphCanvas,
FORCE_GRAPH_INITIAL_VIEW,
type ForceGraphCoords3DRes,
type ForceGraphView,
} from '@practic/force-directed'
import { useEffect, useState } from 'react'
const nodes = [
{ id: 'ada', label: 'Ada' },
{ id: 'grace', label: 'Grace' },
{ id: 'alan', label: 'Alan' },
{ id: 'edsger', label: 'Edsger' },
]
const links = [
{ source: 'ada', target: 'grace' },
{ source: 'grace', target: 'alan' },
{ source: 'alan', target: 'ada' },
{ source: 'edsger', target: 'alan' },
]
// close enough to read the labels, which show once a node is drawn 24 pixels wide
const view: ForceGraphView = { ...FORCE_GRAPH_INITIAL_VIEW, position: [0, 0, 3] }
export function LaidOutNetwork() {
const [graph, setGraph] = useState<ForceGraphCoords3DRes | null>(null)
useEffect(() => {
const worker = forceGraphCreateLayoutWorker()
const controller = new AbortController()
forceGraphLayoutInWorker(worker, { nodes, links, forces: { linkDistance: 60 } }, { signal: controller.signal })
.then(setGraph)
.catch((error: unknown) => {
if (!controller.signal.aborted) console.error(error)
})
return () => {
controller.abort()
worker.terminate()
}
}, [])
return (
<div style={{ height: '100vh' }}>
{graph ? (
<ForceGraphCanvas
graph={graph}
view={view}
linkColor='#888888'
/>
) : (
'Laying out…'
)}
</div>
)
}
ForceGraphCanvas prop | Description |
|---|---|
graph | The laid-out graph. |
view, onViewChange | Camera position, target, type, field of view and zoom; onViewChange gets the view it settles in. |
onNodeClick | Receives a clicked node's id and world position. The camera flies there either way. |
onNodeMove | Makes nodes movable: double-click one, drag the arrows, and this receives where it was dropped. |
onNodeDrag | Receives where the selected node is dragged, before it is dropped. |
onSelectedNodeChange | Receives the id of the node selected to move, or null. |
geometry | 'sphere', 'box', 'tetrahedron', or a component built on GraphInstances. |
scale, size, palette, getNodeColor, linkColor, rotate | How nodes and links are drawn. A node's #rrggbb color wins over the palette. |
ref | clickNode(id) and deselect(). |
children | More of the scene, drawn with the graph. |
ForceGraphGeometries, ForceGraphLabels, ForceGraphLabelPlacer, ForceGraphCamera, ForceGraphCameraControls
and flyToPoint are the canvas's own pieces, for a <Canvas> of your own.
| Export | Description |
|---|---|
ForceGraph | The 3D app: generates, stores and switches graphs, with its settings panel. labels words every text it shows (required, no defaults); storageKey keeps several apart. |
NodesGraph | The 2D app: stored graphs, presets and settings around NodesGraphEditor. labels words every text it shows (required, no defaults). |
ForceGraphCanvas | The 3D view of a graph you hold, with no storage or panels. |
NodesGraphEditor | The 2D editor of a graph you hold: graph, settings and view, each with its change handler, and its texts as labels; toolsStyle styles its panel's corner. |
New nodes and links in both apps get ids of the form node#<uuid> and link#<uuid>; graphs saved earlier keep the
ids they have.
Give each its own storageKey, and each keeps its own graphs, views and panel pins. The texts come from the quick
start's explorer.tsx:
import { ForceGraph } from '@practic/force-directed'
import '@practic/bui/themes/barebones.css'
import { forceGraphLabelsEn } from './explorer'
export function TeamGraphs() {
return (
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', height: '100vh' }}>
<ForceGraph
storageKey='left'
labels={forceGraphLabelsEn}
/>
<ForceGraph
storageKey='right'
labels={forceGraphLabelsEn}
/>
</div>
)
}
NodesGraph stores its graphs and opens with the presets. Like ForceGraph, it has no default texts; in
nodes-graph.tsx:
import { NODES_GRAPH_HELP, NodesGraph, type NodesGraphProps } from '@practic/force-directed'
import '@practic/bui/themes/barebones.css'
export const nodesGraphLabelsEn: NodesGraphProps['labels'] = {
editor: {
addNode: 'Add node',
arrange: 'Arrange',
selected: (count) => `${count} nodes selected`,
deleteNodes: 'Delete nodes',
zoomIn: 'Zoom in',
zoomOut: 'Zoom out',
fit: 'Fit all nodes',
node: { label: 'Label', color: 'Color', edit: 'Edit', remove: 'Remove', deleteNode: 'Delete node' },
link: {
label: 'Label',
color: 'Color',
curve: 'Curve',
animation: 'Animation',
curves: { straight: 'Straight', quadratic: 'Quadratic', cubic: 'Cubic', step: 'Step' },
animations: { none: 'None', flow: 'Flow', pulse: 'Pulse' },
reverse: 'Reverse',
removeLink: 'Remove link',
},
},
file: {
download: 'Download',
load: 'Load file',
invalidJson: 'The file is not valid JSON.',
invalidFile: 'Expected an object with "nodes" and "links" arrays.',
},
presets: { 'berlin-u-bahn': 'Berlin U-Bahn', 'old-world-languages': 'Old World Language Families', 'vitruvian-man': 'Vitruvian Man' },
settings: {
menu: 'Nodes graph settings',
graphSection: 'Graph',
graph: 'Graph',
summary: ({ nodes, links }) => `${nodes} nodes · ${links} links`,
label: 'Label',
deleteGraph: 'Delete graph',
deleteTitle: (label) => `Delete the graph "${label}"?`,
deleteDescription: ({ nodes, links }) => `Its ${nodes} nodes, ${links} links and view are removed.`,
delete: 'Delete',
cancel: 'Cancel',
newNodesSection: 'New nodes',
newNodesHint: 'Click a node to use its color.',
newLinksSection: 'New links',
followColorMode: 'Follow the color mode',
newLinksHint: 'Click a link to use its curve, animation and color.',
newGraphSection: 'New graph',
unnamed: (position) => `Graph ${position}`,
newGraph: 'New graph',
newGraphNote: 'Starts an empty graph, kept separately from the others.',
contentSection: 'Content',
},
help: { title: 'Nodes graph help', close: 'Close Nodes graph help', markdown: NODES_GRAPH_HELP },
}
export function GraphNotebook() {
return (
<div style={{ height: '100vh' }}>
<NodesGraph labels={nodesGraphLabelsEn} />
</div>
)
}
NodesGraphEditor stores nothing; keep its graph wherever you like. Its texts are the 2D app's editor group, from
nodes-graph.tsx:
import { NODES_GRAPH_DEFAULT_SETTINGS, NODES_GRAPH_INITIAL_VIEW, NodesGraphEditor, type ForceGraphCoords3DRes } from '@practic/force-directed'
import { useState } from 'react'
import '@practic/bui/themes/barebones.css'
import { nodesGraphLabelsEn } from './nodes-graph'
export function DiagramEditor() {
const [graph, setGraph] = useState<ForceGraphCoords3DRes>({ nodes: [], links: [] })
const [settings, setSettings] = useState(NODES_GRAPH_DEFAULT_SETTINGS)
const [view, setView] = useState(NODES_GRAPH_INITIAL_VIEW)
return (
<div style={{ position: 'relative', height: '100vh' }}>
<NodesGraphEditor
graph={graph}
onGraphChange={setGraph}
settings={settings}
onSettingsChange={setSettings}
view={view}
onViewChange={setView}
labels={nodesGraphLabelsEn.editor}
/>
<p style={{ position: 'absolute', right: 8, bottom: 8 }}>{graph.nodes.length} nodes</p>
</div>
)
}
Its pieces work alone too: NodesGraphScene, NodeBase, NodesGraphViewControls, NodesGraphBackground,
NodeEditor and LinkEditor, which take the node and link groups of the editor's texts. The graph operations are plain functions: nodeCreate, linkCreate, nodePatch,
nodesMove, nodesRemove, linkSet, linkReverse, linkRemove, linkUpdate, and nodesGraphArrange(graph, pinnedIds), which lays out a graph in 2D from where its nodes are, keeping the pinned ones in place.
| Export | Description |
|---|---|
ForceGraphNodePanel, ForceGraphNodeSearch | A node's coordinates and label, and a search that picks a node by its label. |
ForceGraphCameraSettings, ForceGraphGenerateForm | Camera type and field of view; node count, link distance and label to generate. |
ForceGraphFileActions | Download and load a force graph file, validated by forceGraphValidateFile. |
forceGraphValidateJson, nodesGraphValidate | Read any graph file as layout input, or as nodes graph content. |
FORCE_GRAPH_HELP, NODES_GRAPH_HELP | Every gesture and shortcut, as Markdown, for a help dialog of your own. |
NODES_GRAPH_PRESETS | The sample graphs by id (berlin-u-bahn, old-world-languages, vitruvian-man); NodesGraph's labels.presets names them. |
nodesGraphCreateTools(context) | The WebMCP tools below, over any graph: getGraph, setGraph, getSettings, getLinkThemeColor. |
Each panel takes its texts as a required labels prop, the same group ForceGraph's labels gives it: search,
node, generate, camera and file.
ForceGraph| Action | How |
|---|---|
| Fly to a node | Click it. The camera turns to it and closes in, keeping the side it looks from. |
| Find a node | Type in Search labels, beside the Node button, and pick a label to fly to its node as a click would. |
| Get help | ?, beside the settings cog, opens every gesture and shortcut. |
| Inspect a node | With the Node panel open, click a node to see its id, coordinates and label, read only. |
| Move a node | Double-click it, then drag the arrows. The panel's coordinates follow live. Esc clears the selection. |
| Label a node | Double-click it and type in the Node panel's label (up to 50 characters). |
| Read labels | Labels show beneath their nodes once you are close enough, and hide again from afar. |
| Navigate | Drag to orbit, right-drag to pan, scroll to zoom. |
NodesGraph| Action | How |
|---|---|
| Add a node | Double-click empty space, or Add node. It is labelled with the date and time. |
| Move a node | Drag it. |
| Select a node | Click it. Click empty space or press Esc to clear the selection. |
| Connect or disconnect | Select a node, then Shift+click another. Two nodes hold at most one link each way. |
| Select several nodes | Shift+drag a box over the background, or Shift+click to add or remove one; drag any of them to move them together. |
| Arrange | Arrange lays the graph out again so no labels overlap, keeping the selected nodes in place. |
| Delete a node | Delete or Backspace, or Delete node in the side panel. |
| Edit a node | Label (up to 50 characters, wrapping over three lines) and colour. |
| Edit a link | Label, colour, curve, animation and direction, in the side panel. |
| Copy a look | Click a node to give new nodes its colour; click a link to give new links its curve, animation and colour. |
| Get help | ?, beside the settings cog, opens every gesture and shortcut. |
| Navigate | Drag the background to pan, scroll to zoom, ⤢ to fit every node. |
While NodesGraph or NodesGraphEditor is mounted, it registers these tools with document.modelContext, and
removes them when it unmounts. Browsers without WebMCP skip this. Tools name links by their source and target node
ids. Adding or reversing a link onto a direction that already has one overwrites it. Every tool returns
{ ok: true, value }, or { ok: false, error } explaining what was wrong, and leaves the graph unchanged on error.
| Tool | Input | Does |
|---|---|---|
get_nodes_graph | none | Lists every node and link as drawn |
add_graph_node | label?, color?, x?, y? | Adds a node and returns it with its new id |
update_graph_node | id, label?, color?, x?, y? | Relabels, recolours or moves a node |
delete_graph_node | id | Deletes a node and its links |
add_graph_link | source, target, label?, color?, curve?, animation? | Links two nodes, with the new-link defaults |
update_graph_link | source, target, label?, color?, curve?, animation? | Changes a link |
reverse_graph_link | source, target | Points a link the other way |
delete_graph_link | source, target | Deletes a link |
Colours are #rrggbb, labels hold up to 50 characters, curves are straight, quadratic, cubic or step, and
animations are none, flow or pulse.
ForceGraph with a storageKey writes practic_force-directed_<storageKey>-<subkey> instead of
practic_force-directed_<subkey>.
| Key | Storage | Holds |
|---|---|---|
practic_force-directed_generations | localStorage | The graph list, the active graph, the panels' pins |
practic_force-directed_graph-<count>-<dist> | IndexedDB | One graph's coordinates |
practic_force-directed_view-<count>-<dist> | localStorage | One graph's camera |
practic_force-directed_nodes-graph | localStorage | The graph list, each graph and its view, the settings |
The layout entry needs nothing else. @practic/force-directed/layout depends only on d3-force-3d and uuid.
Everything below is for the components.
Peer dependencies: react and react-dom 19.2 or later (for useEffectEvent), three, @react-three/fiber 9, and @react-three/drei 10.
Tailwind CSS 4. The components lay themselves out with Tailwind classes. Point your Tailwind stylesheet at the package, with the path relative to that stylesheet:
@import 'tailwindcss';
@source '../node_modules/@practic/force-directed';
A theme for the panels. Panels and controls come from @practic/bui. Import a theme, such as
@practic/bui/themes/barebones.css, or your own.
One store for everything (recommended). The apps persist through @practic/persist. Register it as
@practic/bui's layer too, so the panels' pins and the colour mode share the same store:
import { persistRegisterLayer } from '@practic/bui/persist'
import { persistLayer } from '@practic/persist'
persistRegisterLayer(persistLayer)
Give the graph a height. The components fill their parent, so the parent needs a height (100vh, a grid row,
and so on).
MIT © Felipe Penno. See LICENSE.