### React Three Fiber Scene Setup
Source: https://github.com/vasturiano/r3f-forcegraph/blob/master/example/text-nodes/index.html
Sets up the main scene using React Three Fiber's `Canvas`. It configures the camera, adds `TrackballControls` for user interaction, sets a background color, and includes ambient and directional lighting. The `GraphViz` component is rendered as a child within this scene.
```jsx
const Scene = () => {
return (
);
}
```
--------------------------------
### React Three Fiber Force Graph Setup
Source: https://github.com/vasturiano/r3f-forcegraph/blob/master/example/directional-links-arrows/index.html
This snippet demonstrates how to set up a React Three Fiber scene to render a force-directed graph using the r3f-forcegraph library. It includes component definitions for the graph visualization and the overall scene, along with necessary imports and rendering logic.
```javascript
import R3fForceGraph from 'https://esm.sh/r3f-forcegraph?external=three,react';
import React, { useRef } from 'react';
import ReactDOM from 'react-dom';
import { Canvas, useFrame } from '@react-three/fiber';
import { TrackballControls } from '@react-three/drei';
import { genRandomTree } from '../datasets/random-data.js';
const GraphViz = () => {
const fgRef = useRef();
useFrame(() => (fgRef.current.tickFrame()));
return ;
}
const Scene = () => {
return ;
};
ReactDOM.createRoot(document.getElementById('r3fScene'))
.render();
```
--------------------------------
### React Three Fiber Scene Setup and Rendering
Source: https://github.com/vasturiano/r3f-forcegraph/blob/master/example/tree/index.html
This snippet sets up the main 3D scene using React Three Fiber's `Canvas`. It configures the camera, adds interactive trackball controls, sets up ambient and directional lighting, and renders the `GraphViz` component. Finally, it mounts the React application to the DOM.
```jsx
const Scene = () => {
return ;
};
ReactDOM.createRoot(document.getElementById('r3fScene'))
.render();
```
--------------------------------
### React DOM Initialization
Source: https://github.com/vasturiano/r3f-forcegraph/blob/master/example/text-nodes/index.html
This snippet initializes the React application by targeting a DOM element with the ID 'r3fScene' and rendering the main `Scene` component into it. This is the entry point for mounting the React application to the web page.
```javascript
ReactDOM.createRoot(document.getElementById('r3fScene'))
.render();
```
--------------------------------
### React Three Fiber Scene Setup
Source: https://github.com/vasturiano/r3f-forcegraph/blob/master/example/large-graph/index.html
This React component, Scene, sets up the main canvas for the 3D visualization. It configures the canvas size, camera, background color, lighting, and includes essential R3F/Drei components like TrackballControls. It also renders the GraphViz component to display the force-directed graph.
```javascript
import React from 'react';
import ReactDOM from 'react-dom';
import { Canvas } from '@react-three/fiber';
import { TrackballControls } from '@react-three/drei';
// Assuming GraphViz component is defined in the same scope or imported
// import GraphViz from './GraphViz';
const Scene = () => {
return (
);
};
// Mount the scene to the DOM
ReactDOM.createRoot(document.getElementById('r3fScene'))
.render();
```
--------------------------------
### React Three Fiber Scene Setup
Source: https://github.com/vasturiano/r3f-forcegraph/blob/master/example/collision-detection/index.html
This snippet sets up the main 3D scene using React Three Fiber's `Canvas`. It includes essential components like `TrackballControls` for camera manipulation, background color, ambient and directional lighting, and renders the `GraphViz` component within the scene. It requires `@react-three/fiber` and `@react-three/drei`.
```javascript
import React, { useRef, useEffect, useState } from 'react';
import ReactDOM from 'react-dom';
import { Canvas, useFrame } from '@react-three/fiber';
import { TrackballControls } from '@react-three/drei';
// Assuming GraphViz component is defined elsewhere or above
// import GraphViz from './GraphViz';
const Scene = () => {
return (
);
};
```
--------------------------------
### DOM Rendering
Source: https://github.com/vasturiano/r3f-forcegraph/blob/master/example/collision-detection/index.html
This snippet shows how to render the React scene into the DOM. It uses `ReactDOM.createRoot` to mount the main `Scene` component into an HTML element with the ID 'r3fScene'. This is the standard way to initialize a React application.
```javascript
import ReactDOM from 'react-dom';
// Assuming Scene component is defined elsewhere or above
// import Scene from './Scene';
ReactDOM.createRoot(document.getElementById('r3fScene'))
.render();
```
--------------------------------
### R3F Force Graph Visualization
Source: https://github.com/vasturiano/r3f-forcegraph/blob/master/example/expandable-nodes/index.html
This snippet demonstrates a React component that utilizes the r3f-forcegraph library to render an interactive force-directed graph. It includes data generation, node collapsing/expanding logic, and scene setup with lighting and controls using React Three Fiber and Drei.
```javascript
import R3fForceGraph from 'https://esm.sh/r3f-forcegraph?external=three,react';
import React, { useMemo, useState, useRef, useCallback } from 'react';
import ReactDOM from 'react-dom';
import { Canvas, useFrame } from '@react-three/fiber';
import { TrackballControls } from '@react-three/drei';
import { genRandomTree } from '../datasets/random-data.js';
const GraphViz = () => {
const fgRef = useRef();
useFrame(() => (fgRef.current.tickFrame()));
const graphData = useMemo(() => genRandomTree(600, true), []);
const rootId = 0;
const nodesById = useMemo(() => {
const nodesById = Object.fromEntries(graphData.nodes.map(node => [node.id, node]));
// link parent/children
graphData.nodes.forEach(node => {
node.collapsed = node.id !== rootId;
node.childLinks = [];
});
graphData.links.forEach(link => nodesById[link.source].childLinks.push(link));
return nodesById;
}, [graphData]);
const getPrunedTree = useCallback(() => {
const visibleNodes = [];
const visibleLinks = [];
(function traverseTree(node = nodesById[rootId]) {
visibleNodes.push(node);
if (node.collapsed) return;
visibleLinks.push(...node.childLinks);
node.childLinks
.map(link => ((typeof link.target) === 'object') ? link.target : nodesById[link.target]) // get child node
.forEach(traverseTree);
})();
return { nodes: visibleNodes, links: visibleLinks };
}, [nodesById]);
const [prunedTree, setPrunedTree] = useState(getPrunedTree());
const handleNodeClick = useCallback(node => {
node.collapsed = !node.collapsed; // toggle collapse state
setPrunedTree(getPrunedTree())
}, []);
return !node.childLinks.length ? 'green' : node.collapsed ? 'red' : 'yellow'}
onNodeClick={handleNodeClick} />
}
const Scene = () => {
return ;
}
ReactDOM.createRoot(document.getElementById('r3fScene'))
.render();
```
--------------------------------
### Project Imports
Source: https://github.com/vasturiano/r3f-forcegraph/blob/master/example/text-nodes/index.html
Lists the essential libraries and modules imported for the project. This includes React for UI, Three.js for 3D rendering, React Three Fiber for integrating Three.js with React, Drei for helpful abstractions, and r3f-forcegraph for the graph visualization itself. SpriteText is imported for custom node labels.
```javascript
import R3fForceGraph from 'https://esm.sh/r3f-forcegraph?external=three,react';
import React, { useRef, useEffect, useState } from 'react';
import ReactDOM from 'react-dom';
import { Canvas, useFrame } from '@react-three/fiber';
import { TrackballControls } from '@react-three/drei';
import SpriteText from 'https://esm.sh/three-spritetext?external=three';
```
--------------------------------
### Quick Start Usage
Source: https://github.com/vasturiano/r3f-forcegraph/blob/master/README.md
Demonstrates how to import and use the R3fForceGraph component in a React Three Fiber application. It shows the basic import statement and how to integrate the component within a Canvas, including updating the graph simulation on each frame.
```javascript
import R3fForceGraph from 'r3f-forcegraph';
```
```jsx
useFrame(() => fgRef.current.tickFrame());
...
```
--------------------------------
### HTML Structure
Source: https://github.com/vasturiano/r3f-forcegraph/blob/master/example/collision-detection/index.html
This is the minimal HTML structure required to host the React Three Fiber application. It includes a `div` with the ID 'r3fScene' where the canvas will be mounted by ReactDOM, and basic CSS to remove default margins.
```html
R3F ForceGraph
```
--------------------------------
### React ForceGraph Component and Scene Setup
Source: https://github.com/vasturiano/r3f-forcegraph/blob/master/example/directional-links-particles/index.html
This snippet defines a React component `GraphViz` that utilizes `r3f-forcegraph` to render a force-directed graph. It fetches graph data from a JSON file and uses `useFrame` for animation ticks. The `Scene` component sets up the `@react-three/fiber` canvas, including camera, controls, lighting, and the `GraphViz` component. It targets an HTML element with the ID 'r3fScene' for rendering.
```javascript
import R3fForceGraph from 'https://esm.sh/r3f-forcegraph?external=three,react';
import React, { useCallback, useRef, useEffect, useState } from 'react';
import ReactDOM from 'react-dom';
import { Canvas, useFrame } from '@react-three/fiber';
import { TrackballControls } from '@react-three/drei';
const GraphViz = () => {
const fgRef = useRef();
useFrame(() => (fgRef.current.tickFrame()));
const [gData, setGData] = useState();
useEffect(() => {
fetch('../datasets/miserables.json').then(res => res.json())
.then(setGData);
}, []);
return node && console.log(node), [])} />;
}
const Scene = () => {
return ;
};
ReactDOM.createRoot(document.getElementById('r3fScene'))
.render();
```
--------------------------------
### R3F ForceGraph Integration
Source: https://github.com/vasturiano/r3f-forcegraph/blob/master/example/highlight/index.html
This snippet demonstrates how to import and use the R3F ForceGraph component within a React Three Fiber application. It sets up the graph data, handles node and link hover events for highlighting, and configures visual properties like node color and link width.
```javascript
import R3fForceGraph from 'https://esm.sh/r3f-forcegraph?external=three,react';
import React, { useMemo, useState, useRef } from 'react';
import ReactDOM from 'react-dom';
import { Canvas, useFrame } from '@react-three/fiber';
import { TrackballControls } from '@react-three/drei';
import { genRandomTree } from '../datasets/random-data.js';
const GraphViz = () => {
const fgRef = useRef();
useFrame(() => (fgRef.current.tickFrame()));
const data = useMemo(() => {
const gData = genRandomTree(80);
// cross-link node objects
gData.links.forEach(link => {
const a = gData.nodes[link.source];
const b = gData.nodes[link.target];
!a.neighbors && (a.neighbors = []);
!b.neighbors && (b.neighbors = []);
a.neighbors.push(b);
b.neighbors.push(a);
!a.links && (a.links = []);
!b.links && (b.links = []);
a.links.push(link);
b.links.push(link);
});
return gData;
}, []);
const [highlightNodes, setHighlightNodes] = useState(new Set());
const [highlightLinks, setHighlightLinks] = useState(new Set());
const [hoverNode, setHoverNode] = useState(null);
const handleNodeHover = node => {
highlightNodes.clear();
highlightLinks.clear();
if (node) {
highlightNodes.add(node);
node.neighbors.forEach(neighbor => highlightNodes.add(neighbor));
node.links.forEach(link => highlightLinks.add(link));
}
setHoverNode(node || null);
};
const handleLinkHover = link => {
highlightNodes.clear();
highlightLinks.clear();
if (link) {
highlightLinks.add(link);
highlightNodes.add(link.source);
highlightNodes.add(link.target);
}
setHighlightLinks(new Set(highlightLinks));
};
return highlightNodes.has(node) ? node === hoverNode ? 'rgb(255,0,0,1)' : 'rgba(255,160,0,0.8)' : 'rgba(0,255,255,0.6)'}
linkWidth={link => highlightLinks.has(link) ? 4 : 1}
linkDirectionalParticles={link => highlightLinks.has(link) ? 4 : 0}
linkDirectionalParticleWidth={4}
onNodeHover={handleNodeHover}
onLinkHover={handleLinkHover} />;
};
const Scene = () => {
return ;
};
ReactDOM.createRoot(document.getElementById('r3fScene'))
.render();
```
--------------------------------
### Force-Directed Graph Visualization Component
Source: https://github.com/vasturiano/r3f-forcegraph/blob/master/example/tree/index.html
This component, `GraphViz`, handles the core logic for rendering a force-directed graph. It fetches data from a CSV file, processes it into nodes and links, applies physics forces using d3-force-3d, and integrates with dat.gui for interactive control over graph layout (DAG orientation). It uses `r3f-forcegraph` for rendering the graph in a 3D environment.
```javascript
const useForceUpdate = () => {
const setToggle = useState(false)[1];
return () => setToggle(b => !b);
};
const GraphViz = () => {
const fgRef = useRef();
useFrame(() => (
fgRef.current.tickFrame()
));
const [data, setData] = useState();
useEffect(() => {
fetch('../datasets/d3-dependencies.csv')
.then(r => r.text())
.then(csvParse)
.then(data => {
const nodes = [], links = [];
data.forEach(({ size, path }) => {
const levels = path.split('/'),
level = levels.length - 1,
module = level > 0 ? levels[1] : null,
leaf = levels.pop(),
parent = levels.join('/');
const node = { path, leaf, module, size: +size || 20, level };
nodes.push(node);
if (parent) {
links.push({ source: parent, target: path, targetNode: node });
}
});
setData({ nodes, links });
});
}, []);
const [controls] = useState({ 'DAG Orientation': 'td' });
const forceUpdate = useForceUpdate();
useEffect(() => {
// add controls GUI
const gui = new GUI();
gui.add(controls, 'DAG Orientation', ['td', 'bu', 'lr', 'rl', 'radialout', 'radialin', null])
.onChange(forceUpdate);
}, []);
useEffect(() => {
// add collision force
fgRef.current.d3Force('collision', forceCollide(node => Math.cbrt(node.size)))
// Decrease repel intensity
.d3Force('charge').strength(-15);
}, []);
return 'rgba(255,255,255,0.2)'}
nodeRelSize={1}
nodeId="path"
nodeVal="size"
nodeAutoColorBy="module"
linkDirectionalParticles={2}
linkDirectionalParticleWidth={0.9}
linkDirectionalParticleSpeed={0.006}
d3VelocityDecay={0.3} />
}
```
--------------------------------
### R3F ForceGraph Integration with React Three Fiber
Source: https://github.com/vasturiano/r3f-forcegraph/blob/master/example/basic/index.html
This snippet demonstrates how to integrate the r3f-forcegraph library into a React Three Fiber scene. It includes setting up the canvas, generating graph data, handling node and link events, and rendering the graph with controls and lighting. Dependencies include react, react-dom, three, @react-three/fiber, @react-three/drei, and r3f-forcegraph.
```javascript
import R3fForceGraph from 'https://esm.sh/r3f-forcegraph?external=three,react';
import React, { useMemo, useCallback, useRef } from 'react';
import ReactDOM from 'react-dom';
import { Canvas, useFrame } from '@react-three/fiber';
import { TrackballControls } from '@react-three/drei';
const GraphViz = () => {
const fgRef = useRef();
useFrame(() => (
fgRef.current.tickFrame()
));
const N = 300;
const gData = useMemo(() => ({
nodes: [...Array(N).keys()].map(i => ({ id: i })),
links: [...Array(N).keys()]
.filter(id => id)
.map(id => ({ source: id, target: Math.round(Math.random() * (id - 1)) }))
}), [N]);
return (
console.log('node hover', ...args), [])}
onLinkHover={useCallback((...args) => console.log('link hover', ...args), [])}
onNodeClick={useCallback((...args) => console.log('node click', ...args), [])}
onLinkClick={useCallback((...args) => console.log('link click', ...args), [])}
/>
);
};
const Scene = () => {
return (
);
};
ReactDOM.createRoot(document.getElementById('r3fScene'))
.render();
```
--------------------------------
### R3F ForceGraph Visualization
Source: https://github.com/vasturiano/r3f-forcegraph/blob/master/example/collision-detection/index.html
This snippet defines the core `GraphViz` component which integrates `r3f-forcegraph` with React Three Fiber. It manages graph data, applies custom D3 forces like collision and boundary bouncing, and uses `useFrame` for simulation updates. It requires `react`, `react-three-fiber`, `r3f-forcegraph`, and `d3-force-3d`.
```javascript
import R3fForceGraph from 'https://esm.sh/r3f-forcegraph?external=three,react';
import React, { useRef, useEffect, useState } from 'react';
import { forceCollide } from 'https://esm.sh/d3-force-3d';
const GraphViz = () => {
const fgRef = useRef();
useFrame(() => (fgRef.current.tickFrame()));
const nodeRelSize = 4;
const [graphData, setGraphData] = useState({ nodes: [], links: [] });
useEffect(() => {
const fg = fgRef.current;
const N = 300; // Number of nodes
// Deactivate existing forces
fg.d3Force('center', null);
fg.d3Force('charge', null);
// Add collision and bounding box forces
fg.d3Force('collide', forceCollide(nodeRelSize));
fg.d3Force('box', () => {
const CUBE_HALF_SIDE = nodeRelSize * Math.cbrt(N) * 5;
// Bounce nodes off the box walls
fg.graphData().nodes.forEach(node => {
const x = node.x || 0, y = node.y || 0, z = node.z || 0;
if (Math.abs(x) > CUBE_HALF_SIDE) { node.vx *= -1; }
if (Math.abs(y) > CUBE_HALF_SIDE) { node.vy *= -1; }
if (Math.abs(z) > CUBE_HALF_SIDE) { node.vz *= -1; }
});
});
// Generate nodes with initial velocity in random direction
const nodes = [...Array(N).keys()].map(() => ({
vx: Math.random(),
vy: Math.random(),
vz: Math.random()
}));
setGraphData({ nodes, links: [] });
}, [nodeRelSize]);
return ;
};
```
--------------------------------
### R3F ForceGraph Component
Source: https://github.com/vasturiano/r3f-forcegraph/blob/master/example/text-nodes/index.html
Defines the `GraphViz` React component that wraps the `r3f-forcegraph` library. It manages graph data fetching from a JSON file and configures custom node rendering using `SpriteText` for labels. The `useFrame` hook is used to update the graph's internal state on each animation frame.
```jsx
const GraphViz = () => {
const fgRef = useRef();
useFrame(() => (
fgRef.current.tickFrame()
));
const [gData, setGData] = useState();
useEffect(() => {
fetch('../datasets/miserables.json')
.then(res => res.json())
.then(setGData);
}, []);
return {
const sprite = new SpriteText(node.id);
sprite.color = node.color;
sprite.textHeight = 8;
return sprite;
}} />;
}
```
--------------------------------
### ForceGraph Component with R3F Integration
Source: https://github.com/vasturiano/r3f-forcegraph/blob/master/example/large-graph/index.html
This React component, GraphViz, utilizes the r3f-forcegraph library to render a force-directed graph. It integrates with React Three Fiber's `useFrame` hook to drive the graph's animation loop and fetches graph data from a JSON file. It also includes node hover event handling.
```javascript
import R3fForceGraph from 'https://esm.sh/r3f-forcegraph?external=three,react';
import React, { useCallback, useRef, useEffect, useState } from 'react';
const GraphViz = () => {
const fgRef = useRef();
// Use useFrame to tick the graph's animation loop
useFrame(() => (
fgRef.current.tickFrame()
));
const [gData, setGData] = useState();
// Fetch graph data on component mount
useEffect(() => {
fetch('../datasets/blocks.json').then(res => res.json())
.then(setGData);
}, []);
return (
node && console.log(node), [])}
/>
);
}
```
--------------------------------
### Render Control Methods and Callbacks
Source: https://github.com/vasturiano/r3f-forcegraph/blob/master/README.md
Provides methods and callbacks for controlling the rendering process and simulation updates. Includes notifications for update completion and functions to advance the simulation or redraw the graph.
```APIDOC
onFinishUpdate()
- Callback function for notification that the component has finished updating.
- Triggered after the simulation engine has resumed and completed its warmup phase.
tickFrame()
- Iterates the underlying force simulation engine.
- Should be called on each cycle of the global renderer to update node/link positions.
refresh()
- Redraws all the nodes and links in the graph.
```
--------------------------------
### Input JSON Syntax
Source: https://github.com/vasturiano/r3f-forcegraph/blob/master/README.md
Defines the expected JSON structure for input data, specifying arrays for nodes and links with their respective properties.
```json
{
"nodes": [
{
"id": "id1",
"name": "name1",
"val": 1
},
{
"id": "id2",
"name": "name2",
"val": 10
},
...
],
"links": [
{
"source": "id1",
"target": "id2"
},
...
]
}
```
--------------------------------
### Interaction Callbacks
Source: https://github.com/vasturiano/r3f-forcegraph/blob/master/README.md
Defines callback functions for user interactions with nodes and links, including click and hover events. These callbacks receive relevant node/link objects and event data.
```APIDOC
onNodeClick(node, event)
- Callback function for node clicks.
- Parameters:
- node: The clicked node object.
- event: The event object associated with the click.
onNodeHover(node, prevNode)
- Callback function for node mouse over events.
- Parameters:
- node: The node object under the pointer (or null).
- prevNode: The previously hovered node object (or null).
onLinkClick(link, event)
- Callback function for link clicks.
- Parameters:
- link: The clicked link object.
- event: The event object associated with the click.
onLinkHover(link, prevLink)
- Callback function for link mouse over events.
- Parameters:
- link: The link object under the pointer (or null).
- prevLink: The previously hovered link object (or null).
```
--------------------------------
### Utility Methods
Source: https://github.com/vasturiano/r3f-forcegraph/blob/master/README.md
Provides utility functions for graph manipulation and information retrieval. Includes a method to calculate the bounding box of nodes.
```APIDOC
getGraphBbox([nodeFilterFn])
- Returns the current bounding box of the nodes in the graph.
- Format: `{ x: [, ], y: [, ], z: [, ] }`.
- Returns `null` if no nodes are found.
- Parameters:
- nodeFilterFn: Optional function `node => ` to filter nodes for bounding box calculation. Useful for calculating the bounding box of a subset of the graph.
```
--------------------------------
### Force Engine Configuration Properties
Source: https://github.com/vasturiano/r3f-forcegraph/blob/master/README.md
Defines the configurable properties for the force simulation engine. These options allow customization of simulation dimensions, engine choice (d3 or ngraph), directed acyclic graph (DAG) layout constraints, and various simulation tuning parameters like alpha decay and velocity decay. Specific properties are only applicable when using the d3 simulation engine.
```APIDOC
Force Engine Configuration:
- numDimensions: (1, 2, or 3) Number of dimensions for the force simulation. Default: 3.
- forceEngine: (string) Which force-simulation engine to use ('d3' or 'ngraph'). Default: 'd3'.
- dagMode: (string) Apply layout constraints based on graph directionality for DAG structures. Options: 'td', 'bu', 'lr', 'rl', 'zout', 'zin', 'radialout', 'radialin'. Default: '-'.
- dagLevelDistance: (number) Distance between graph depths when dagMode is engaged. Default: auto-derived.
- dagNodeFilter: (func) Node accessor function to ignore nodes during DAG layout processing. Receives a node object, returns boolean. Default: `node => true`.
- onDagError: (func) Callback invoked if a cycle is encountered during DAG processing. Receives loop segment (array of node ids). Default: throws exception.
- d3AlphaMin: (number) Sets the simulation alpha min parameter. Only for d3 engine. Default: 0.
- d3AlphaDecay: (number) Sets the simulation intensity decay parameter. Only for d3 engine. Default: 0.0228.
- d3AlphaTarget: (number) Sets the simulation alpha target parameter. Only for d3 engine. Default: 0.
- d3VelocityDecay: (number) Nodes' velocity decay simulating medium resistance. Only for d3 engine. Default: 0.4.
- ngraphPhysics: (object) Specify custom physics configuration for ngraph, according to its configuration object syntax. Only for ngraph engine. Default: '-'.
- warmupTicks: (number) Number of layout engine cycles to dry-run before rendering. Default: 0.
- cooldownTicks: (number) Frames to render before stopping and freezing the layout engine. Default: Infinity.
- cooldownTime: (number) Time (ms) to render before stopping and freezing the layout engine. Default: 15000.
- onEngineTick: (func) Callback function invoked at every tick of the simulation engine.
- onEngineStop: (func) Callback function invoked when the simulation engine stops.
```