Giter Site home page Giter Site logo

vasturiano / react-force-graph Goto Github PK

View Code? Open in Web Editor NEW
1.9K 26.0 253.0 1.33 MB

React component for 2D, 3D, VR and AR force directed graphs

Home Page: https://vasturiano.github.io/react-force-graph/example/large-graph/

License: MIT License

JavaScript 27.31% HTML 72.69%
react force-directed-graphs 3d vr canvas webgl d3-force augmented-reality

react-force-graph's Introduction

react-force-graph

NPM package NPM Downloads

React bindings for the force-graph suite of components: force-graph (2D HTML Canvas), 3d-force-graph (ThreeJS/WebGL), 3d-force-graph-vr (A-Frame) and 3d-force-graph-ar (AR.js).

This module exports 4 React components with identical interfaces: ForceGraph2D, ForceGraph3D, ForceGraphVR and ForceGraphAR. Each can be used to represent a graph data structure in a 2 or 3-dimensional space using a force-directed iterative layout.

For dependency convenience, all of the components are also available as stand-alone packages: react-force-graph-2d, react-force-graph-3d, react-force-graph-vr and react-force-graph-ar.

Uses canvas/WebGL for rendering and d3-force-3d for the underlying physics engine. Supports zooming/panning, node dragging and node/link hover/click interactions.

Examples

Quick start

import ForceGraph2D from 'react-force-graph-2d';
import ForceGraph3D from 'react-force-graph-3d';
import ForceGraphVR from 'react-force-graph-vr';
import ForceGraphAR from 'react-force-graph-ar';

or

import { ForceGraph2D, ForceGraph3D, ForceGraphVR, ForceGraphAR } from 'react-force-graph';

or using a script tag

<script src="//unpkg.com/react-force-graph-2d"></script>
<script src="//unpkg.com/react-force-graph-3d"></script>
<script src="//unpkg.com/react-force-graph-vr"></script>
<script src="//unpkg.com/react-force-graph-ar"></script>

then

<ForceGraph3D
  graphData={myData}
/>

API reference

Note that not all props listed below apply to all 4 components. The last 4 columns in these tables indicate the specific component availability of each prop/method.

Data input

Prop Type Default Description 2D 3D VR AR
graphData object { nodes: [], links: [] } Graph data structure (see below for syntax details). Can also be used to apply incremental updates. ✔️ ✔️ ✔️ ✔️
nodeId string id Node object accessor attribute for unique node id (used in link objects source/target). ✔️ ✔️ ✔️ ✔️
linkSource string source Link object accessor attribute referring to id of source node. ✔️ ✔️ ✔️ ✔️
linkTarget string target Link object accessor attribute referring to id of target node. ✔️ ✔️ ✔️ ✔️

Container layout

Prop Type Default Description 2D 3D VR AR
width number <window width> Canvas width, in px. ✔️ ✔️ ✔️ ✔️
height number <window height> Canvas height, in px. ✔️ ✔️ ✔️ ✔️
backgroundColor string (2D - light / 3D - dark) Chart background color. ✔️ ✔️ ✔️
showNavInfo bool true Whether to show the navigation controls footer info. ✔️ ✔️
yOffset number 1.5 In AR mode, defines the offset distance above the marker where to place the center coordinates <0,0,0> of the force directed graph. Measured in terms of marker width units. ✔️
glScale number 200 In AR mode, defines the translation scale between real world distances and WebGL units, determining the overall size of the graph. Defined in terms of how many GL units fit in a full marker width. ✔️
markerAttrs object { preset: 'hiro' } Set of attributes that define the marker where the AR force directed graph is mounted, according to the a-marker specification. This prop only has an effect on component mount. ✔️

Node styling

Prop Type Default Description 2D 3D VR AR
nodeRelSize number 4 Ratio of node circle area (square px) [2D] or sphere volume (cubic px) [3D] per value unit. ✔️ ✔️ ✔️ ✔️
nodeVal number, string or func val Node object accessor function, attribute or a numeric constant for the node numeric value (affects node size). ✔️ ✔️ ✔️ ✔️
nodeLabel string or func name Node object accessor function or attribute for name (shown in label). Supports plain text or HTML content (except in VR). ✔️ ✔️ ✔️
nodeDesc string or func desc For VR only. Node object accessor function or attribute for description (shown under label). ✔️
nodeVisibility bool, string or func true Node object accessor function, attribute or a boolean constant for whether to display the node. ✔️ ✔️ ✔️ ✔️
nodeColor string or func color Node object accessor function or attribute for node color. ✔️ ✔️ ✔️ ✔️
nodeAutoColorBy string or func Node object accessor function or attribute to automatically group colors by. Only affects nodes without a color attribute. ✔️ ✔️ ✔️ ✔️
nodeOpacity number 0.75 Nodes sphere opacity, between [0,1]. ✔️ ✔️ ✔️
nodeResolution number 8 Geometric resolution of each node's sphere, expressed in how many slice segments to divide the circumference. Higher values yield smoother spheres. Only applicable to 3D modes. ✔️ ✔️ ✔️
nodeCanvasObject func default 2D node object is a circle, sized according to val and styled according to color. Callback function for painting a custom 2D canvas object to represent graph nodes. Should use the provided canvas context attribute to perform drawing operations for each node. The callback function will be called for each node at every frame, and has the signature: nodeCanvasObject(<node>, <canvas context>, <current global scale>). ✔️
nodeCanvasObjectMode string or func () => 'replace' Node object accessor function or attribute for the custom drawing mode. Use in combination with nodeCanvasObject to specify how to customize nodes painting. Possible values are:
  • replace: the node is rendered using just nodeCanvasObject.
  • before: the node is rendered by invoking nodeCanvasObject and then proceeding with the default node painting.
  • after: nodeCanvasObject is applied after the default node painting takes place.
Any other value will be ignored and the default drawing will be applied.
✔️
nodeThreeObject Object3d, string or func default 3D node object is a sphere, sized according to val and styled according to color. Node object accessor function or attribute for generating a custom 3d object to render as graph nodes. Should return an instance of ThreeJS Object3d. If a falsy value is returned, the default 3d object type will be used instead for that node. ✔️ ✔️ ✔️
nodeThreeObjectExtend bool, string or func false Node object accessor function, attribute or a boolean value for whether to replace the default node when using a custom nodeThreeObject (false) or to extend it (true). ✔️ ✔️ ✔️

Link styling

Prop Type Default Description 2D 3D VR AR
linkLabel string or func name Link object accessor function or attribute for name (shown in label). Supports plain text or HTML content (except in VR). ✔️ ✔️ ✔️
linkDesc string or func desc For VR only. Link object accessor function or attribute for description (shown under label). ✔️
linkVisibility bool, string or func true Link object accessor function, attribute or a boolean constant for whether to display the link line. ✔️ ✔️ ✔️ ✔️
linkColor string or func color Link object accessor function or attribute for line color. ✔️ ✔️ ✔️ ✔️
linkAutoColorBy string or func Link object accessor function or attribute to automatically group colors by. Only affects links without a color attribute. ✔️ ✔️ ✔️ ✔️
linkOpacity number 0.2 Line opacity of links, between [0,1]. ✔️ ✔️ ✔️
linkLineDash number[], string or func] Link object accessor function, attribute or number array (e.g. [5, 15]) to determine if a line dash should be applied to this rendered link. Refer to the HTML canvas setLineDash API for example values. Either a falsy value or an empty array will disable dashing. ✔️
linkWidth number, string or func 1 Link object accessor function, attribute or a numeric constant for the link line width. ✔️ ✔️ ✔️ ✔️
linkResolution number 6 Geometric resolution of each link 3D line, expressed in how many radial segments to divide the cylinder. Higher values yield smoother cylinders. Applicable only to links with positive width. ✔️ ✔️ ✔️
linkCurvature number, string or func 0 Link object accessor function, attribute or a numeric constant for the curvature radius of the link line. A value of 0 renders a straight line. 1 indicates a radius equal to half of the line length, causing the curve to approximate a semi-circle. For self-referencing links (source equal to target) the curve is represented as a loop around the node, with length proportional to the curvature value. ✔️ ✔️ ✔️ ✔️
linkCurveRotation number, string or func 0 Link object accessor function, attribute or a numeric constant for the rotation along the line axis to apply to the curve. Has no effect on straight lines. At 0 rotation, the curve is oriented in the direction of the intersection with the XY plane. The rotation angle (in radians) will rotate the curved line clockwise around the "start-to-end" axis from this reference orientation. ✔️ ✔️ ✔️
linkMaterial Material, string or func default link material is MeshLambertMaterial styled according to color and opacity. Link object accessor function or attribute for specifying a custom material to style the graph links with. Should return an instance of ThreeJS Material. If a falsy value is returned, the default material will be used instead for that link. ✔️ ✔️ ✔️
linkCanvasObject func default 2D link object is a line, styled according to width and color. Callback function for painting a custom canvas object to represent graph links. Should use the provided canvas context attribute to perform drawing operations for each link. The callback function will be called for each link at every frame, and has the signature: .linkCanvasObject(<link>, <canvas context>, <current global scale>). ✔️
linkCanvasObjectMode string or func () => 'replace' Link object accessor function or attribute for the custom drawing mode. Use in combination with linkCanvasObject to specify how to customize links painting. Possible values are:
  • replace: the link is rendered using just linkCanvasObject.
  • before: the link is rendered by invoking linkCanvasObject and then proceeding with the default link painting.
  • after: linkCanvasObject is applied after the default link painting takes place.
Any other value will be ignored and the default drawing will be applied.
✔️
linkThreeObject Object3d, string or func default 3D link object is a line or cylinder, sized according to width and styled according to material. Link object accessor function or attribute for generating a custom 3d object to render as graph links. Should return an instance of ThreeJS Object3d. If a falsy value is returned, the default 3d object type will be used instead for that link. ✔️ ✔️ ✔️
linkThreeObjectExtend bool, string or func false Link object accessor function, attribute or a boolean value for whether to replace the default link when using a custom linkThreeObject (false) or to extend it (true). ✔️ ✔️ ✔️
linkPositionUpdate func(linkObject, { start, end }, link) Custom function to call for updating the position of links at every render iteration. It receives the respective link ThreeJS Object3d, the start and end coordinates of the link ({x,y,z} each), and the link's data. If the function returns a truthy value, the regular position update function will not run for that link. ✔️ ✔️ ✔️
linkDirectionalArrowLength number, string or func 0 Link object accessor function, attribute or a numeric constant for the length of the arrow head indicating the link directionality. The arrow is displayed directly over the link line, and points in the direction of source > target. A value of 0 hides the arrow. ✔️ ✔️ ✔️ ✔️
linkDirectionalArrowColor string or func color Link object accessor function or attribute for the color of the arrow head. ✔️ ✔️ ✔️ ✔️
linkDirectionalArrowRelPos number, string or func 0.5 Link object accessor function, attribute or a numeric constant for the longitudinal position of the arrow head along the link line, expressed as a ratio between 0 and 1, where 0 indicates immediately next to the source node, 1 next to the target node, and 0.5 right in the middle. ✔️ ✔️ ✔️ ✔️
linkDirectionalArrowResolution number 8 Geometric resolution of the arrow head, expressed in how many slice segments to divide the cone base circumference. Higher values yield smoother arrows. ✔️ ✔️ ✔️
linkDirectionalParticles number, string or func 0 Link object accessor function, attribute or a numeric constant for the number of particles (small spheres) to display over the link line. The particles are distributed equi-spaced along the line, travel in the direction source > target, and can be used to indicate link directionality. ✔️ ✔️ ✔️ ✔️
linkDirectionalParticleSpeed number, string or func 0.01 Link object accessor function, attribute or a numeric constant for the directional particles speed, expressed as the ratio of the link length to travel per frame. Values above 0.5 are discouraged. ✔️ ✔️ ✔️ ✔️
linkDirectionalParticleWidth number, string or func 0.5 Link object accessor function, attribute or a numeric constant for the directional particles width. Values are rounded to the nearest decimal for indexing purposes. ✔️ ✔️ ✔️ ✔️
linkDirectionalParticleColor string or func color Link object accessor function or attribute for the directional particles color. ✔️ ✔️ ✔️ ✔️
linkDirectionalParticleResolution number 4 Geometric resolution of each 3D directional particle, expressed in how many slice segments to divide the circumference. Higher values yield smoother particles. ✔️ ✔️ ✔️
Method Arguments Description 2D 3D VR AR
emitParticle (link) An alternative mechanism for generating particles, this method emits a non-cyclical single particle within a specific link. The emitted particle shares the styling (speed, width, color) of the regular particle props. A valid link object that is included in graphData should be passed as a single parameter. ✔️ ✔️ ✔️ ✔️

Render control

Prop Type Default Description 2D 3D VR AR
rendererConfig object { antialias: true, alpha: true } Configuration parameters to pass to the ThreeJS WebGLRenderer constructor. This prop only has an effect on component mount. ✔️
extraRenderers array [] If you wish to include custom objects that require a dedicated renderer besides WebGL, such as CSS3DRenderer, include in this array those extra renderer instances. ✔️
autoPauseRedraw bool true Enable performance optimization to automatically pause redrawing the 2D canvas at every frame whenever the simulation engine is halted. If you have custom dynamic objects that rely on a constant redraw of the canvas, it's recommended to switch this option off. ✔️
minZoom number 0.01 Lowest zoom out level permitted on the 2D canvas. ✔️
maxZoom number 1000 Highest zoom in level permitted on the 2D canvas. ✔️
onRenderFramePre func - Callback function to invoke at every frame, immediately before any node/link is rendered to the canvas. This can be used to draw additional external items on the canvas. The canvas context and the current global scale are included as parameters: .onRenderFramePre(<canvas context>, <global scale>). ✔️
onRenderFramePost func - Callback function to invoke at every frame, immediately after the last node/link is rendered to the canvas. This can be used to draw additional external items on the canvas. The canvas context and the current global scale are included as parameters: .onRenderFramePost(<canvas context>, <global scale>). ✔️
Method Arguments Description 2D 3D VR AR
pauseAnimation - Pauses the rendering cycle of the component, effectively freezing the current view and cancelling all user interaction. This method can be used to save performance in circumstances when a static image is sufficient. ✔️ ✔️
resumeAnimation - Resumes the rendering cycle of the component, and re-enables the user interaction. This method can be used together with pauseAnimation for performance optimization purposes. ✔️ ✔️
centerAt ([x], [y], [ms]) Set the coordinates of the center of the viewport. This method can be used to perform panning on the 2D canvas programmatically. Each of the x, y coordinates is optional, allowing for motion in just one dimension. An optional 3rd argument defines the duration of the transition (in ms) to animate the canvas motion. ✔️
zoom ([number], [ms]) Set the 2D canvas zoom amount. The zoom is defined in terms of the scale transform of each px. A value of 1 indicates unity, larger values zoom in and smaller values zoom out. An optional 2nd argument defines the duration of the transition (in ms) to animate the canvas motion. By default the zoom is set to a value inversely proportional to the amount of nodes in the system. ✔️
zoomToFit ([ms], [px], [nodeFilterFn]) Automatically zooms/pans the canvas so that all of the nodes fit inside it. If no nodes are found no action is taken. It accepts two optional arguments: the first defines the duration of the transition (in ms) to animate the canvas motion (default: 0ms). The second argument is the amount of padding (in px) between the edge of the canvas and the outermost node (default: 10px). The third argument specifies a custom node filter: node => <boolean>, which should return a truthy value if the node is to be included. This can be useful for focusing on a portion of the graph. ✔️ ✔️
cameraPosition ([{x,y,z}],[lookAt], [ms]) Re-position the camera, in terms of x, y, z coordinates. Each of the coordinates is optional, allowing for motion in just some dimensions. The optional second argument can be used to define the direction that the camera should aim at, in terms of an {x,y,z} point in the 3D space. The 3rd optional argument defines the duration of the transition (in ms) to animate the camera motion. A value of 0 (default) moves the camera immediately to the final position. By default the camera will face the center of the graph at a z distance proportional to the amount of nodes in the system. ✔️
lights ([array]) Getter/setter for the list of lights to use in the scene. Each item should be an instance of Light. ✔️
scene - Access the internal ThreeJS Scene. ✔️
camera - Access the internal ThreeJS Camera. ✔️
renderer - Access the internal ThreeJS WebGL renderer. ✔️
postProcessingComposer - Access the post-processing composer. Use this to add post-processing rendering effects to the scene. By default the composer has a single pass (RenderPass) that directly renders the scene without any effects. ✔️
controls - Access the internal ThreeJS controls object. ✔️
refresh - Redraws all the nodes/links. ✔️ ✔️ ✔️

Force engine configuration

Prop Type Default Description 2D 3D VR AR
numDimensions 1, 2 or 3 3 Not applicable to 2D mode. Number of dimensions to run the force simulation on. ✔️ ✔️ ✔️
forceEngine string d3 Which force-simulation engine to use (d3 or ngraph). ✔️ ✔️ ✔️
dagMode string - Apply layout constraints based on the graph directionality. Only works correctly for DAG graph structures (without cycles). Choice between td (top-down), bu (bottom-up), lr (left-to-right), rl (right-to-left), zout (near-to-far), zin (far-to-near), radialout (outwards-radially) or radialin (inwards-radially). ✔️ ✔️ ✔️ ✔️
dagLevelDistance number auto-derived from the number of nodes If dagMode is engaged, this specifies the distance between the different graph depths. ✔️ ✔️ ✔️ ✔️
dagNodeFilter func node => true Node accessor function to specify nodes to ignore during the DAG layout processing. This accessor method receives a node object and should return a boolean value indicating whether the node is to be included. Excluded nodes will be left unconstrained and free to move in any direction. ✔️ ✔️ ✔️ ✔️
onDagError func - Callback to invoke if a cycle is encountered while processing the data structure for a DAG layout. The loop segment of the graph is included for information, as an array of node ids. By default an exception will be thrown whenever a loop is encountered. You can override this method to handle this case externally and allow the graph to continue the DAG processing. Strict graph directionality is not guaranteed if a loop is encountered and the result is a best effort to establish a hierarchy. ✔️ ✔️ ✔️ ✔️
d3AlphaMin number 0 Sets the simulation alpha min parameter. Only applicable if using the d3 simulation engine. ✔️ ✔️ ✔️ ✔️
d3AlphaDecay number 0.0228 Sets the simulation intensity decay parameter. Only applicable if using the d3 simulation engine. ✔️ ✔️ ✔️ ✔️
d3VelocityDecay number 0.4 Nodes' velocity decay that simulates the medium resistance. Only applicable if using the d3 simulation engine. ✔️ ✔️ ✔️ ✔️
ngraphPhysics object - Specify custom physics configuration for ngraph, according to its configuration object syntax. Only applicable if using the ngraph simulation engine. ✔️ ✔️ ✔️
warmupTicks number 0 Number of layout engine cycles to dry-run at ignition before starting to render. ✔️ ✔️ ✔️ ✔️
cooldownTicks number Infinity How many build-in frames to render before stopping and freezing the layout engine. ✔️ ✔️ ✔️ ✔️
cooldownTime number 15000 How long (ms) to render for before stopping and freezing the layout engine. ✔️ ✔️ ✔️ ✔️
onEngineTick func - Callback function invoked at every tick of the simulation engine. ✔️ ✔️ ✔️ ✔️
onEngineStop func - Callback function invoked when the simulation engine stops and the layout is frozen. ✔️ ✔️ ✔️ ✔️
Method Arguments Description 2D 3D VR AR
d3Force (string, [func]) Access to the internal forces that control the d3 simulation engine. Follows the same interface as d3-force-3d's simulation.force. Three forces are included by default: 'link' (based on forceLink), 'charge' (based on forceManyBody) and 'center' (based on forceCenter). Each of these forces can be reconfigured, or new forces can be added to the system. Only applicable if using the d3 simulation engine. ✔️ ✔️ ✔️ ✔️
d3ReheatSimulation () Reheats the force simulation engine, by setting the alpha value to 1. Only applicable if using the d3 simulation engine. ✔️ ✔️ ✔️ ✔️

Interaction

Prop Type Default Description 2D 3D VR AR
onNodeClick func - Callback function for node (left-button) clicks. The node object and the event object are included as arguments onNodeClick(node, event). ✔️ ✔️ ✔️ ✔️
onNodeRightClick func - Callback function for node right-clicks. The node object and the event object are included as arguments onNodeRightClick(node, event). ✔️ ✔️
onNodeHover func - Callback function for node mouse over events. The node object (or null if there's no node under the pointer line of sight) is included as the first argument, and the previous node object (or null) as second argument: onNodeHover(node, prevNode). ✔️ ✔️ ✔️ ✔️
onNodeDrag func - Callback function for node drag interactions. This function is invoked repeatedly while dragging a node, every time its position is updated. The node object is included as the first argument, and the change in coordinates since the last iteration of this function are included as the second argument in format {x,y,z}: onNodeDrag(node, translate). ✔️ ✔️
onNodeDragEnd func - Callback function for the end of node drag interactions. This function is invoked when the node is released. The node object is included as the first argument, and the change in coordinates from the node's initial postion are included as the second argument in format {x,y,z}: onNodeDragEnd(node, translate). ✔️ ✔️
onLinkClick func - Callback function for link (left-button) clicks. The link object and the event object are included as arguments onLinkClick(link, event). ✔️ ✔️ ✔️ ✔️
onLinkRightClick func - Callback function for link right-clicks. The link object and the event object are included as arguments onLinkRightClick(link, event). ✔️ ✔️
onLinkHover func - Callback function for link mouse over events. The link object (or null if there's no link under the pointer line of sight) is included as the first argument, and the previous link object (or null) as second argument: onLinkHover(link, prevLink). ✔️ ✔️ ✔️ ✔️
onBackgroundClick func - Callback function for click events on the empty space between the nodes and links. The event object is included as single argument onBackgroundClick(event). ✔️ ✔️
onBackgroundRightClick func - Callback function for right-click events on the empty space between the nodes and links. The event object is included as single argument onBackgroundRightClick(event). ✔️ ✔️
linkHoverPrecision number 4 Whether to display the link label when gazing the link closely (low value) or from far away (high value). ✔️ ✔️
onZoom func - Callback function for zoom/pan events. The current zoom transform is included as single argument onZoom({ k, x, y }). Note that onZoom is triggered by user interaction as well as programmatic zooming/panning with zoom() and centerAt(). ✔️
onZoomEnd func - Callback function for on 'end' of zoom/pan events. The current zoom transform is included as single argument onZoomEnd({ k, x, y }). Note that onZoomEnd is triggered by user interaction as well as programmatic zooming/panning with zoom() and centerAt(). ✔️
controlType string trackball Which type of control to use to control the camera on 3D mode. Choice between trackball, orbit or fly. ✔️
enableZoomInteraction bool true Whether to enable zooming user interactions on a 2D canvas. ✔️
enablePanInteraction bool true Whether to enable panning user interactions on a 2D canvas. ✔️
enableNavigationControls bool true Whether to enable the trackball navigation controls used to move the camera using mouse interactions (rotate/zoom/pan). ✔️
enablePointerInteraction bool true Whether to enable the mouse tracking events. This activates an internal tracker of the canvas mouse position and enables the functionality of object hover/click and tooltip labels, at the cost of performance. If you're looking for maximum gain in your graph performance it's recommended to switch off this property. ✔️ ✔️
enableNodeDrag bool true Whether to enable the user interaction to drag nodes by click-dragging. If enabled, every time a node is dragged the simulation is re-heated so the other nodes react to the changes. Only applicable if enablePointerInteraction is true. ✔️ ✔️
nodePointerAreaPaint func default interaction area is a circle centered on the node and sized according to val. Callback function for painting a canvas area used to detect node pointer interactions. The provided paint color uniquely identifies the node and should be used to perform drawing operations on the provided canvas context. This painted area will not be visible, but instead be used to detect pointer interactions with the node. The callback function has the signature: nodePointerAreaPaint(<node>, <color>, <canvas context>, <current global scale>). ✔️
linkPointerAreaPaint func default interaction area is a straight line between the source and target nodes. Callback function for painting a canvas area used to detect link pointer interactions. The provided paint color uniquely identifies the link and should be used to perform drawing operations on the provided canvas context. This painted area will not be visible, but instead be used to detect pointer interactions with the link. The callback function has the signature: linkPointerAreaPaint(<link>, <color>, <canvas context>, <current global scale>). ✔️

Utility

Method Arguments Description 2D 3D VR AR
getGraphBbox ([nodeFilterFn]) Returns the current bounding box of the nodes in the graph, formatted as { x: [<num>, <num>], y: [<num>, <num>], z: [<num>, <num>] }. If no nodes are found, returns null. Accepts an optional argument to define a custom node filter: node => <boolean>, which should return a truthy value if the node is to be included. This can be useful to calculate the bounding box of a portion of the graph. ✔️ ✔️ ✔️ ✔️
screen2GraphCoords (x, y[, distance]) Utility method to translate viewport coordinates to the graph domain. Given a pair of x,y screen coordinates, and optionally distance from camera for 3D mode, returns the current equivalent {x, y (, z)} in the domain of graph node coordinates. ✔️ ✔️
graph2ScreenCoords (x, y[, z]) Utility method to translate node coordinates to the viewport domain. Given a set of x,y(,z) graph coordinates, returns the current equivalent {x, y} in viewport coordinates. ✔️ ✔️

Input JSON syntax

{
    "nodes": [ 
        { 
          "id": "id1",
          "name": "name1",
          "val": 1 
        },
        { 
          "id": "id2",
          "name": "name2",
          "val": 10 
        },
        ...
    ],
    "links": [
        {
            "source": "id1",
            "target": "id2"
        },
        ...
    ]
}

Giving Back

paypal If this project has helped you and you'd like to contribute back, you can always buy me a ☕!

react-force-graph's People

Contributors

carljoachim avatar dreierf avatar micahstubbs avatar muralimulagalapati avatar nathanpovo avatar vasturiano avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-force-graph's Issues

Randomize timing link particle emission

Feature request to randomize the timing of link particle emission. It feels too uniform currently because they all emit at the same time. Perhaps introduce linkDirectionalParticleRandomizationFactor?

d3Force link distance example

Hi @vasturiano
I have calculated the distance between each of my variables and included that distance in the links data. What is the simplest way to use this as the distance between nodes my component? d3Force=??? I know below is incorrect, but just to give an idea.

export default class TextGraph extends React.Component {
        render() {
          const {data} = this.props;        

          return <ForceGraph3D       
              graphData={data}
              d3Force = { ('link', "distance")}

              nodeLabel = "desc"       
              cooldownTime={15000}
              d3AlphaDecay={0}
              d3VelocityDecay={0}
              nodeAutoColorBy="group"
              enableNodeDrag={false}     

              nodeThreeObject={node => {
                const sprite = new SpriteText(node.id);
                sprite.color = node.color;
                sprite.textHeight = node.revenue;
                return sprite;
          }}
        />;
        }
      }

Thank you.

Access to Three.js renderer

Is there any possibility to access scene renderer from my component?
I need to add a shadow to my graph, and add a parameter { antialias: true } to make it less sharp.

THREE not defined problem when changing the node shape

        <ForceGraph3D
          ref={el => { this.fg = el; }}
          graphData={this.props.GraphReducer}
          nodeThreeObject={() => 
          new THREE.Mesh(new THREE.DodecahedronGeometry(Math.random() * 10),
          new THREE.MeshLambertMaterial({color: Math.round(Math.random() * Math.pow(2, 24)),transparent: true,opacity: 0.75}))}
        />

Do you have some methods help me import THREE into react environment?

I need your help

Hello
I can't see the nodeLabel.
How can I solve this?
This is an excellent module..
I want to solve this ASAP.
Best Regards,

Gordal18

Node shape as SVG image?

Hello,

I see there is an option to use custom shapes for nodes.. Is it possible to use that approach to set an SVG image for different nodes? Or maybe there is a different node to do so... something like

    "nodes": [ 
        { 
          "id": "id1",
          "name": "name1",
          "val": 1 ,
          "icon": svg_object_here // <----- is something like that possible?
        },
....

Thanks!

Link directional particle on-demand emission

Feature request:

Would be awesome to have a function to emit particles on-demand.

this.graph.emitDirectionalParticle(linkId)
// or
this.graph.emitDirectionalParticle(linkSrc, linkDest)

Zoom / Pan Listener or Camera Idle Callback

Is it possible to add a callback to the Graph so that it fires a callback on idle of the camera? When a user interacts via mouse scrolling and panning I'd like to actively memorize where they left off for later usage. Currently I have a zoom in and zoom out button in my own implementation and these keep track of zoom value but mouse panning/zooming disrupts this binding of zoom value.

Many thanks again for this excellent library!

Smoother interpolation of centerAt()

I was wondering what the best approach to smoothly moving to a point would be given (x,y,z)?

I'm currently using a 2D graph and when I add a node I'd like to smoothly pan the camera to wherever it ends up being made. I took a look at some underlying d3 code and see you can use interpolators to "tween" from one value to another but I'm not sure how to expose that via this library.

Also, for now I've just added an arbitrary timeout to wait for the graph to stop animating since the location of the new node is unknown/fluid until the animation completes but I'm sure there is a better solution to this.

Thoughts?

Can't import ForceGraph3D in an a-frame application

It seems like the THREE imports are clashing when I import ForceGraph3D from react-force-graph into an existing AFrame application (which has its own THREE dependency).

NotSupportedError: Failed to execute 'registerElement' on 'Document': Registration failed for type 'a-node'. A type with that name is already registered.

Is there a way around this issue?

Position of disconnected Nodes

Is there any control available to dictate the framing of the nodes in the graph on load?

The reason I ask is that I'm building a project where you can add a node at any time (disconnected) and boom it appears there in the graph for you to then grab and connect to others or leave on its own. The issue is that these are sometimes incredibly far from the pre-existing cluster of nodes.

For instance if I add 6-7 new disconnected nodes in a row they end up so far away that I have to zoom far out, pan for a while and drag the little buggers back over to the remainder of the graph.

At first I thought this was an effect of the Node radius I had set rather high but it appears this happens at all values of 'r'. I'm wondering if some constraint value that lets you tighten loose nodes closer to the average centroid of all other nodes is possible in an efficient manner.

Thoughts?

NOTE: I am working in 2D mode specifically.

Cannot install

I tried npm i react-force-graph and kept hitting the same error:

warning: templates not found C:\Users\USERNAME\AppData\Local\Temp\pacote-git-template-tmp\git-clone-169f0298
Fatal: The remote end hung up unexpectedly

when trying with --verbose, it seems to hang on https://registry.npmjs.org/@tweenjs%2ftween.js

any idea why?

onDrag detection

While the API shows methods for onHover and onClick of both nodes and links, there doesn't readily appear to be a way of detecting drag events. In my own project I save the locations of elements and would like to do this at the end of a drag event. Are there plans / an existing strategy to accomplish this detection of drag states?

Any tips on setting up tests with Enzyme + react-force-graph?

I'm adding a new component to my app. The component uses react-force-graph. I test my app using Enzyme + jsdom. But when I try to test my new component, I run into: "screen is not defined" error that causes the tests to crash.

I noticed the error disappears if I comment out import { ForceGraph2D } from 'react-force-graph';.

At first, I simply added globals to my test setup.js file as seen in this example: https://gist.github.com/yan130/386d6c79d975de580c8c343a0423b66d (notice how it adds window.screen and global.screen). But then the error became "self is not defined". I added self to my setup.js, and now the error is "XMLHttpRequest is not defined".

So now I imagine there is something very wrong with my approach. I must be doing something wrong. I can't just keep adding every browser API to my setup.js. And it seems odd that the error occurs when I import the ForceGraph2D component.

Anybody have success using ForceGraph2D in their app and testing it with Enzyme?

Change Scale or Center

Hello

Is it somehow possible to set the cursor to 'pointer' when hovering over nodes?

I've tried different approaches now, like setting body css if mouse enters a node and back to auto if it leaves. But i can't figure out how to do it. Maybe you can help me with this problem.

Thank you in advance

Best regards,

PatStadler

d3Force method

The way to use this method to change the charge of the nodes is very unclear!

Issue minifying

Seems with my production builds we are getting a minify issue with TweenLite:

║> react-scripts build ║
║Creating an optimized production build... ║
║Failed to compile. ║
║Failed to minify the code from this file: ║
║ ./node_modules/gsap/esm/TweenLite.js:1966 ║

Loading data from a state manger

@vasturiano have you tried any examples loading from a state manager like Mobx or Redux? Getting some errors populating data from a Mobx observable variable.

warning.js:33 Warning: Failed prop type: Invalid prop graphData.nodesof typeobjectsupplied toForceGraph2D, expected an array.

Looks like rendering the data gets caught in a wonky state.

How to update one specific node or edge?

If I want to change a specific node(or edge), how can I do it?

For example, suppose every node has an id, after drawing the graph, I want to change node one(id: node1)'s color if I click a button outside the graph.

After clicking the button, what I did is to iterate the node list of the graph, and find the id to change the graph's color. However, how can I update the graph? I don't want to redraw the layout. Only change the node's color is enough.

Thanks in advance.

Node label obscures dragging.

I've noticed that in the 2D graph, the hover label is centered directly on the mouse so it prevents the mouse from being able to directly drag the node.

I believe it's caused by the following CSS:

.graph-tooltip {
    ...
    transform: translate(-50%, 25px);
    ...
}

In my project I overwrote this by changing the 25px to 15px.

Thoughts?

linkCurvature onLinkHover causes a hit box glitch.

Love this library, saved me some serious start up time on my current project!

While attempting to use the linkCurvature property in conjunction with the onLinkHover property I noticed that the curvature does not apply to the hit box of the hover. So although the line visually curves properly, hovering over the curved line will not trigger the onHover. However, hovering over the space where a straight link would be will fire the event as though the link is still straight.

Easy to reproduce using a curvature of .5 with onLinkHover.

How to represent irregular polygon as sprite?

Thank you for this beautiful repo. How do I replace the 3D Text nodes with irregular shapes? For example, my shapes might look something California in this example.
https://threejs.org/examples/#webgl_geometry_shapes

EDIT/ SOLUTION: @vasturiano was extremely patient and helpful as I got up to speed on canvas and three.js; the rest of this post is my journey. Here is my bare-bones solution to my original question:

import { ForceGraph3D } from 'react-force-graph';
import { genRandomTree } from './random-data';
var THREE = require('three');

export default class SpriteGraph extends React.Component {

    generateMaterial = () => {  
      //create a canvas   
        let canvas = document.createElement('canvas');
        canvas.width = 160;
        canvas.height = 160;
        let ctx = canvas.getContext('2d');

       //draw a shape
        let PI2 = Math.PI * 2;
        ctx.beginPath();
        ctx.fillStyle = 'blue';
        ctx.arc(canvas.width/2, canvas.height/2, 80, 0, PI2, true);
        ctx.fill();

        //return a material
        let texture = new THREE.CanvasTexture(canvas);      
        let material = new THREE.SpriteMaterial({map: texture})      
        return material
    }

    render() {
        const data = genRandomTree(100);        
        return <ForceGraph3D           
            graphData={data}
            nodeLabel="id"
            nodeThreeObject={({ id }) => {
                let sprite = new THREE.Sprite(this.generateMaterial())
                sprite.scale.set(30,30,1)
                return sprite
            }}
        />;
    }
}

How to get the Graph instance in React

In Javascirpt verions, we can have:

const Graph = ForceGraph3D()

I want to access the Graph in React so I can do some changes.

I found this link and know someone has already implemented the feature:

#21

In the issue, we can have: Graph.nodeRelSize(this.relSize);

Can anyone tell me a method to do it? Thanks

How to use CDN version within React

Apologies, I know this isn't specifically a Force Graph issue, but I'm a bit confused about how to use ForceGraph when including the CDN reference:

<script src="//unpkg.com/react-force-graph"></script>

I'm getting the issue that it cannot find the 2d and 3d definition:

Line 623: 'ForceGraph3D' is not defined react/jsx-no-undef
Line 634: 'ForceGraph2D' is not defined react/jsx-no-undef

I'm not sure how to pull in from the CDN in a React friendly way:

import { ForceGraph3D } from 'react-force-graph'
import { ForceGraph2D } from 'react-force-graph'

Thanks!

Get node viewport absolute position

I need to open a context menu when clicking on the node. The problem is that the onNodeClick callback parameter gives me the values which don't look like absolute position:

fx: undefined, fy: undefined, vx: 0, vy: 0, x: 12.152664474162155, y: 12.520373695711815

Import and package only the 2D component

Hi,

and thanks for this great package you made available here.

Everything is working well for us but optimization wise, I'd like to know if there is a way to only import the <ForceGraph2D> component without having to load and embed in my package the VR and the 3D components and underlying libraries.

For know webpack produces builds with everything and I end up having to load AFrame and Three.js in the browser, even though I don't use them.

Thanks in advance for informations around that matter.

Retina display support for 2D graph / "onSimulationEnd" callback?

Web canvas requires additional scaling to support Retina displays. See here: https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio#Syntax

I would like to use the code snippet mentioned in the link above, but the ideal time to adjust the canvas scaling is when the animation/forceSimulation is done. Scaling the canvas on every tick causes major performance issues in my graph that has hundreds of nodes/links.

But I don't see any kind of "onSimulationEnd" callback/prop, so I'm not sure how to execute code specifically when the simulation has ended. Any ideas on how to scale the canvas for Retina displays without trying to re-scale the canvas through nodeCanvasObject prop?

Right now, the only solution I can think of is:

  • Set cooldownTime prop to X milliseconds.
  • Use a setTimeout to run canvas scaling code snippet after X+1 milliseconds.

But of course, the above solution is crummy because it's hard to pick a good value for X.

Correction?

Actually, it's worse than I thought. Pan/Zoom will undo the canvas scaling, causing bizarre painting. So even using a setTimeout doesn't work for graphs that allow pan/zoom.

show all the labels

Hi,
Thanks for this great library!! :)
How can I get the following one?
Addition to showing labels on hovering, need an option to show all the labels of a particular attribute across the graph. Like labeled nodes with name or id or val?

Painting Over Links

nodeCanvasObject is excellent for allowing custom painting code over nodes on the graph. Is it possible to also expose a similar method to draw over links?

Select node in 3d graph without restarting simulation

I'm trying to implement node selection in ForceGraph3D component.
As I can see, every time I'm calling setState(), graph restarts physics simulation even if graph data wasn't modified.
Part of code which shows selected links
linkWidth={link => this.state.DataProvider.isSelectedLink(link) ? 3 : 1}
Following code works pretty well and all needed links are changing their width, but graph also restarts physics simulation and all nodes are jumping and oscillating
If I'm not calling setState() and just update selected links in my DataProvider class, I can't see any changes in the graph

Without react bindings I've achieved pretty good effect just calling (without simulation restart on select)
Graph.nodeRelSize(this.relSize);

OnHover and OnClick not working after new data is passed to graph

Hello

I am trying to pass new data into the graph with

this.setState({graph: this.state.graph.concat(newGraph)})

and the graph ist bound to

graphData={this.state.graph}

It renders correctly but onhover and onclick are not working anymore, but only after i passed in new Data.
The nodeCanvasObject function is called, i logged it to the console.
I can pan and zoom on the canvas .

I hope i gave you enough information so that

Thank you in advance

Best regards,

PatStadler

zoom bug

Hi I cannot load graph because of Uncaught TypeError: selection.interrupt is not a function in my react app.
I tried:
import { ForceGraph2D} from 'react-force-graph';
or
const{ ForceGraph2D} = require('react-force-graph');
...

return (

)

Detail error:
Uncaught TypeError: selection.interrupt is not a function
at Function../node_modules/force-graph/node_modules/d3-zoom/src/zoom.js.webpack_exports.default.zoom.transform (zoom.js:90)
at Function../node_modules/force-graph/node_modules/d3-zoom/src/zoom.js.webpack_exports.default.zoom.translateBy (zoom.js:119)
at adjustCanvasSize (force-graph.module.js:605)
at Function.init (force-graph.module.js:852)
at u (kapsule.min.js:1)
at Object.r [as comp] (kapsule.min.js:1)
at FromKapsuleComp.componentDidMount (react-kapsule.module.js:85)
at commitLifeCycles (react-dom.development.js:14685)
at commitAllLifeCycles (react-dom.development.js:15905)
at HTMLUnknownElement.callCallback (react-dom.development.js:145)

I have newest version of package.

What's wrong with my code?

[ForceGraph2D] Node Label Position Incorrect

Hello! Thank you for writing this plugin - it has been extremely helpful.

I noticed a bug, which is that the label position is appears to be affected by how much content is "above" the graph renderer. I believe this may be the same issue referenced in #16. Here are screenshots demonstrating the effect:

The default functionality, which can be seen in demos, is that the label is just below the cursor:
ss_no_header

When I added a large header with buttons for testing things, the label appears above the cursor:
ss_large_header

In production, we'll have a much smaller toolbar. The labels are now displaying directly in front of the cursor, preventing interaction with the underlying nodes:
ss_small_header

For some context: the header is just some divs with buttons and a p tag (nothing remarkable).

Is there a property I can set to get the desired behavior (text is always below)? In the meantime I may dive into the source to find the original problem, but I'm not familiar with building applications using rollup

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.