How vasturiano/force-graph works
Project type and purpose
• This is an open-source, client‐side JavaScript library (“force-graph”) that provides a web component to render 2D force-directed graphs on an HTML5 canvas.
• It’s not a full-stack app but rather a visualization tool built atop the d3-force physics engine, packaged for NPM and usable directly in the browser or via frameworks (e.g., React).
File structure
• Top-level configs and build scripts:
– .babelrc (Babel transpiler settings)
– rollup.config.js / rollup.config.dev.js (bundle definitions)
– package.json (dependencies, build commands)
• src/: ES module source code split into:
– canvas-force-graph.js (main renderer + API)
– force-graph.js (entry point façade)
– force-graph.css (default styles)
– index.js / index.d.ts (TypeScript declarations)
• example/: dozens of static HTML demos feeding sample JSON into the built bundle
• CI, linting, issue templates, LICENSE, README
README for additional insights
• Core dependencies: d3-force for simulation, HTML5 canvas for rendering
• Illustrates features: node/link styling, interactivity, DAG modes, custom rendering hooks, performance options
• Usage pattern: import ForceGraph, instantiate with a container DOM element, call .graphData() and chain config methods
a. Build & packaging pipeline (offline/build time)
• SOURCE (src/*.js, .css)
→ Babel (transpile ES6+)
→ Rollup (bundle, tree-shake, minify)
→ OUTPUT (dist/force-graph.umd.js, ES module bundle, type definitions)
• package.json → NPM package registry
b. Runtime in Browser (client)
• User Code (app.js or script tag)
– Imports ForceGraph from NPM or CDN
– Calls new ForceGraph(container) → returns graph instance
– Invokes chainable setters (.graphData(), .nodeColor(), etc.)
• ForceGraph Library
– API façade (index.js)
– Internal state manager (kapsule)
– Exposes hooks to configure d3-force simulation, canvas callbacks, events
• d3-force Engine
– Simulates physics (forces, ticks)
– Emits “tick” events → positions updated
• Canvas Renderer
– Post-render hook → custom overlays
• Interaction Tracker
– Offscreen “pointer canvas” painting for hit-testing nodes/links
– Mouse events → onNodeHover/Click, onLinkHover/Click, zoom/pan handlers
• User Callback Handlers
– User-provided functions invoked on clicks, drags, engine stop, etc.
Architectural patterns & design principles
• Modular ES6 code + utility modules (SINGLE RESPONSIBILITY)
• Declarative, chainable API (FLUENT INTERFACE)
• Event-driven flow between simulation, rendering, user callbacks (PUBLISH-SUBSCRIBE)
• Separation between simulation logic (d3-force) and view (canvas)
• Build system abstracts transpilation and bundling (BUILD-TIME vs RUN-TIME)