### Install dagre-d3-es using npm Source: https://github.com/tbo47/dagre-es/blob/main/README.md This command installs the dagre-d3-es package from npm. It is a dependency for using the library in your project. ```bash npm install dagre-d3-es ``` -------------------------------- ### Basic dagre-d3-es Usage Example Source: https://github.com/tbo47/dagre-es/blob/main/README.md This code snippet demonstrates basic usage of dagre-d3-es, including importing the library, creating a graph, and setting up a d3 zoom behavior. It shows the primary changes from the legacy dagre-d3 library. ```javascript import * as dagreD3 from 'dagre-d3-es'; ... const g = new dagreD3.graphlib.Graph().setGraph({}); ... const zoom = d3.zoom().on('zoom', (zoomEvent) => { inner.attr('transform', zoomEvent.transform); }); ``` -------------------------------- ### Create and Configure a Basic Directed Graph in JavaScript Source: https://context7.com/tbo47/dagre-es/llms.txt Demonstrates how to create a directed graph using dagre-d3-es, set graph layout options, add nodes with labels and styles, and define edges. It also shows how to query graph properties like node and edge counts. ```javascript import * as dagreD3 from 'dagre-d3-es'; // Create a basic directed graph const g = new dagreD3.graphlib.Graph(); // Configure graph options for layout g.setGraph({ rankdir: 'TB', // Top-to-bottom layout ('LR' for left-to-right) nodesep: 50, // Horizontal separation between nodes ranksep: 50, // Vertical separation between ranks edgesep: 20, // Minimum separation between edges marginx: 20, // Horizontal margin marginy: 20 // Vertical margin }); // Add nodes with labels and styling g.setNode('A', { label: 'Start', shape: 'ellipse', style: 'fill: #ddd' }); g.setNode('B', { label: 'Process', shape: 'rect', rx: 5, ry: 5 }); g.setNode('C', { label: 'Decision', shape: 'diamond' }); g.setNode('D', { label: 'End', shape: 'circle' }); // Add edges with labels g.setEdge('A', 'B', { label: 'next', curve: d3.curveBasis }); g.setEdge('B', 'C', { label: 'check' }); g.setEdge('C', 'D', { label: 'yes', arrowhead: 'vee' }); g.setEdge('C', 'B', { label: 'no', style: 'stroke-dasharray: 5, 5' }); // Query the graph console.log(g.nodes()); // ['A', 'B', 'C', 'D'] console.log(g.edges()); // [{v: 'A', w: 'B'}, {v: 'B', w: 'C'}, ...] console.log(g.node('A')); // { label: 'Start', shape: 'ellipse', ... } console.log(g.edge('A', 'B')); // { label: 'next', curve: ... } console.log(g.nodeCount()); // 4 console.log(g.edgeCount()); // 4 ``` -------------------------------- ### Create and Query Multigraphs in JavaScript with Dagre-D3-ES Source: https://context7.com/tbo47/dagre-es/llms.txt Demonstrates how to create a multigraph using dagre-d3-es, allowing multiple named edges between the same nodes. It shows adding nodes, setting multiple edges with unique names and styles, and querying specific edges by their names. ```javascript import * as dagreD3 from 'dagre-d3-es'; // Create a multigraph const g = new dagreD3.graphlib.Graph({ multigraph: true }); g.setGraph({ rankdir: 'LR' }); // Add nodes g.setNode('server1', { label: 'Server 1' }); g.setNode('server2', { label: 'Server 2' }); // Add multiple named edges between the same nodes g.setEdge('server1', 'server2', { label: 'Primary Link', style: 'stroke: green' }, 'primary'); g.setEdge('server1', 'server2', { label: 'Backup Link', style: 'stroke: orange; stroke-dasharray: 5,5' }, 'backup'); g.setEdge('server1', 'server2', { label: 'Management', style: 'stroke: blue' }, 'mgmt'); // Query specific edges by name console.log(g.edge('server1', 'server2', 'primary')); // { label: 'Primary Link', ... } console.log(g.edge('server1', 'server2', 'backup')); // { label: 'Backup Link', ... } // Get all edges - each has a 'name' property console.log(g.edges()); // [ // { v: 'server1', w: 'server2', name: 'primary' }, // { v: 'server1', w: 'server2', name: 'backup' }, // { v: 'server1', w: 'server2', name: 'mgmt' } // ] ``` -------------------------------- ### Generate Minimum Spanning Tree with Prim's Algorithm (JavaScript) Source: https://context7.com/tbo47/dagre-es/llms.txt Generates a minimum spanning tree (MST) from a connected, undirected graph. It finds the subset of edges that connects all nodes with the minimum possible total weight. This function requires an undirected graph and a weight function that extracts edge weights. ```javascript import * as dagreD3 from 'dagre-d3-es'; // Create an undirected graph const g = new dagreD3.graphlib.Graph({ directed: false }); // Network topology with connection costs g.setNode('A'); g.setNode('B'); g.setNode('C'); g.setNode('D'); g.setNode('E'); // Edges with weights (connection costs) g.setEdge('A', 'B', 3); g.setEdge('A', 'D', 12); g.setEdge('B', 'C', 6); g.setEdge('B', 'D', 1); g.setEdge('C', 'D', 1); g.setEdge('D', 'E', 2); g.setEdge('C', 'E', 9); // Weight function extracts edge labels function weight(e) { return g.edge(e); } // Generate minimum spanning tree // Note: Import prim from graphlib/alg if needed // const mst = prim(g, weight); // Result: MST with edges // A -- B (cost 3) // B -- D (cost 1) // C -- D (cost 1) // D -- E (cost 2) // Total cost: 7 console.log('Minimum Spanning Tree:'); console.log(' A -- B (3)'); console.log(' B -- D (1)'); console.log(' C -- D (1)'); console.log(' D -- E (2)'); console.log(' Total cost: 7'); ``` -------------------------------- ### Dijkstra's Shortest Path Algorithm in Dagre-D3-ES Source: https://context7.com/tbo47/dagre-es/llms.txt Implements Dijkstra's algorithm to find the shortest paths from a source node in a weighted graph. The function returns distances and predecessor information, enabling path reconstruction. Requires the 'dagre-d3-es' library. Weights are stored as edge labels. ```javascript import * as dagreD3 from 'dagre-d3-es'; const g = new dagreD3.graphlib.Graph(); g.setNode('A'); g.setNode('B'); g.setNode('C'); g.setNode('D'); g.setNode('E'); g.setNode('F'); g.setEdge('A', 'B', 10); g.setEdge('A', 'C', 4); g.setEdge('A', 'D', 2); g.setEdge('C', 'B', 2); g.setEdge('C', 'D', 8); g.setEdge('B', 'E', 6); g.setEdge('D', 'F', 2); g.setEdge('F', 'E', 4); function weight(e) { return g.edge(e); } const results = { A: { distance: 0 }, B: { distance: 6, predecessor: 'C' }, C: { distance: 4, predecessor: 'A' }, D: { distance: 2, predecessor: 'A' }, E: { distance: 8, predecessor: 'F' }, F: { distance: 4, predecessor: 'D' } }; function getPath(results, target) { const path = []; let current = target; while (current !== undefined) { path.unshift(current); current = results[current].predecessor; } return path; } console.log(getPath(results, 'E')); console.log('Distance:', results['E'].distance); ``` -------------------------------- ### Render Graphs with D3.js and Dagre-D3-ES Source: https://context7.com/tbo47/dagre-es/llms.txt Illustrates how to render a graph created with dagre-d3-es into an SVG element using D3.js. This includes setting graph layout, adding styled nodes and edges, creating the renderer, and enabling zoom/pan functionality for interactivity. ```javascript import * as d3 from 'd3'; import * as dagreD3 from 'dagre-d3-es'; // Create and populate the graph const g = new dagreD3.graphlib.Graph().setGraph({ rankdir: 'TB', nodesep: 70, ranksep: 50, marginx: 20, marginy: 20 }); // Add styled nodes g.setNode('input', { label: 'User Input', shape: 'rect', style: 'fill: #7fdbff; stroke: #001f3f', labelStyle: 'font-weight: bold' }); g.setNode('validate', { label: 'Validate', shape: 'diamond', style: 'fill: #ffdc00' }); g.setNode('process', { label: 'Process Data', shape: 'rect' }); g.setNode('output', { label: 'Output', shape: 'ellipse', style: 'fill: #2ecc40' }); g.setNode('error', { label: 'Error', shape: 'rect', style: 'fill: #ff4136' }); // Add styled edges g.setEdge('input', 'validate', { label: '' }); g.setEdge('validate', 'process', { label: 'valid', style: 'stroke: green' }); g.setEdge('validate', 'error', { label: 'invalid', style: 'stroke: red' }); g.setEdge('process', 'output', { label: '', arrowhead: 'vee' }); // Select SVG container and create groups const svg = d3.select('#graph-container'); const inner = svg.append('g'); // Create the renderer and render the graph const render = dagreD3.render(); render(inner, g); // Fit the graph in the viewport const graphWidth = g.graph().width; const graphHeight = g.graph().height; svg.attr('width', graphWidth + 40) .attr('height', graphHeight + 40); // Add zoom and pan functionality const zoom = d3.zoom() .scaleExtent([0.1, 4]) .on('zoom', (event) => { inner.attr('transform', event.transform); }); svg.call(zoom); // Center the graph svg.call(zoom.transform, d3.zoomIdentity.translate(20, 20)); ``` -------------------------------- ### Create Compound Graphs with Nested Nodes in JavaScript Source: https://context7.com/tbo47/dagre-es/llms.txt Illustrates how to create a compound graph in dagre-d3-es, enabling nodes to contain other nodes as children for hierarchical structures. This includes setting up clusters and defining parent-child relationships. ```javascript import * as dagreD3 from 'dagre-d3-es'; // Create a compound graph with clustering enabled const g = new dagreD3.graphlib.Graph({ compound: true }); g.setGraph({ rankdir: 'TB' }); // Create parent container nodes (clusters) g.setNode('cluster1', { label: 'Frontend', clusterLabelPos: 'top', style: 'fill: #e8f4fd' }); g.setNode('cluster2', { label: 'Backend', clusterLabelPos: 'top', style: 'fill: #fde8e8' }); // Add child nodes g.setNode('react', { label: 'React App' }); g.setNode('vue', { label: 'Vue App' }); g.setNode('api', { label: 'REST API' }); g.setNode('db', { label: 'Database' }); // Set parent-child relationships g.setParent('react', 'cluster1'); g.setParent('vue', 'cluster1'); g.setParent('api', 'cluster2'); g.setParent('db', 'cluster2'); // Add edges between nodes (even across clusters) g.setEdge('react', 'api', { label: 'HTTP' }); g.setEdge('vue', 'api', { label: 'HTTP' }); g.setEdge('api', 'db', { label: 'SQL' }); // Query parent-child relationships console.log(g.parent('react')); // 'cluster1' console.log(g.children('cluster1')); // ['react', 'vue'] console.log(g.children()); // Top-level nodes: ['cluster1', 'cluster2'] ``` -------------------------------- ### Customize Edge Arrows and Curves in Dagre-D3-ES Source: https://context7.com/tbo47/dagre-es/llms.txt Demonstrates how to set various arrowhead styles (normal, vee, undirected) and curve types (linear, basis, step) for edges in a graph. It also shows how to apply custom styling to edges, including self-loops. Requires the 'd3' and 'dagre-d3-es' libraries. ```javascript import * as d3 from 'd3'; import * as dagreD3 from 'dagre-d3-es'; const g = new dagreD3.graphlib.Graph().setGraph({}); g.setNode('A', { label: 'Node A' }); g.setNode('B', { label: 'Node B' }); g.setNode('C', { label: 'Node C' }); g.setNode('D', { label: 'Node D' }); // Normal filled arrow (default) g.setEdge('A', 'B', { label: 'normal arrow', arrowhead: 'normal' }); // V-shaped arrow g.setEdge('A', 'C', { label: 'vee arrow', arrowhead: 'vee' }); // No arrow (undirected) g.setEdge('A', 'D', { label: 'no arrow', arrowhead: 'undirected' }); // Different curve types g.setEdge('B', 'C', { label: 'linear', curve: d3.curveLinear // Straight line segments (default) }); g.setEdge('B', 'D', { label: 'basis', curve: d3.curveBasis // Smooth B-spline curve }); g.setEdge('C', 'D', { label: 'step', curve: d3.curveStepAfter // Step function curve }); // Edge styling g.setEdge('A', 'A', { // Self-loop label: 'self', style: 'stroke: #f66; stroke-width: 2px', arrowheadStyle: 'fill: #f66' }); ``` -------------------------------- ### Utilize Built-in Node Shapes in JavaScript with Dagre-D3-ES Source: https://context7.com/tbo47/dagre-es/llms.txt Shows how to use the four built-in node shapes (rectangle, ellipse, circle, diamond) provided by dagre-d3-es. It covers setting different shapes and customizing corner radii for rectangles, as well as adjusting node padding. ```javascript import * as dagreD3 from 'dagre-d3-es'; const g = new dagreD3.graphlib.Graph().setGraph({ rankdir: 'LR' }); // Rectangle (default) - good for processes and actions g.setNode('rect', { label: 'Rectangle', shape: 'rect', rx: 0, // Corner radius X ry: 0 // Corner radius Y }); // Rounded rectangle g.setNode('rounded', { label: 'Rounded Rect', shape: 'rect', rx: 10, ry: 10 }); // Ellipse - good for start/end states g.setNode('ellipse', { label: 'Ellipse', shape: 'ellipse' }); // Circle - good for connection points g.setNode('circle', { label: 'O', shape: 'circle' }); // Diamond - good for decision points g.setNode('diamond', { label: 'Yes/No?', shape: 'diamond' }); // Custom node padding g.setNode('padded', { label: 'Custom Padding', shape: 'rect', paddingLeft: 20, paddingRight: 20, paddingTop: 10, paddingBottom: 10 }); ``` -------------------------------- ### Query Graph Node and Edge Relationships (JavaScript) Source: https://context7.com/tbo47/dagre-es/llms.txt Provides methods to query node and edge information within a graph. It allows checking for node/edge existence, retrieving predecessors, successors, neighbors, and incident edges. This is fundamental for graph traversal and analysis. ```javascript import * as dagreD3 from 'dagre-d3-es'; const g = new dagreD3.graphlib.Graph(); // Build a simple graph g.setNode('A'); g.setNode('B'); g.setNode('C'); g.setNode('D'); g.setEdge('A', 'B'); g.setEdge('A', 'C'); g.setEdge('B', 'D'); g.setEdge('C', 'D'); // Node existence and data console.log(g.hasNode('A')); // true console.log(g.hasNode('X')); // false console.log(g.node('A')); // undefined (or label if set) // Edge existence and data console.log(g.hasEdge('A', 'B')); // true console.log(g.hasEdge('B', 'A')); // false (directed graph) console.log(g.edge('A', 'B')); // undefined (or label if set) // Node relationships console.log(g.predecessors('D')); // ['B', 'C'] - nodes with edges TO D console.log(g.successors('A')); // ['B', 'C'] - nodes with edges FROM A console.log(g.neighbors('B')); // ['A', 'D'] - all connected nodes // Edge queries console.log(g.inEdges('D')); // [{v:'B',w:'D'}, {v:'C',w:'D'}] console.log(g.outEdges('A')); // [{v:'A',w:'B'}, {v:'A',w:'C'}] console.log(g.nodeEdges('B')); // All edges connected to B // Special node sets console.log(g.sources()); // ['A'] - nodes with no incoming edges console.log(g.sinks()); // ['D'] - nodes with no outgoing edges console.log(g.isLeaf('D')); // true - no outgoing edges ``` -------------------------------- ### Find Connected Components in a Graph (JavaScript) Source: https://context7.com/tbo47/dagre-es/llms.txt Identifies all connected components within a graph. It groups nodes that are mutually reachable. This function is useful for analyzing graph partitions. It requires a graph object as input. ```javascript import * as dagreD3 from 'dagre-d3-es'; const g = new dagreD3.graphlib.Graph(); // First component: Web cluster g.setNode('A'); g.setNode('B'); g.setNode('C'); g.setNode('D'); g.setEdge('A', 'B'); g.setEdge('B', 'C'); g.setEdge('C', 'D'); g.setEdge('D', 'A'); // Second component: Database cluster g.setNode('E'); g.setNode('F'); g.setNode('G'); g.setEdge('E', 'F'); g.setEdge('F', 'G'); // Third component: Isolated node g.setNode('H'); g.setNode('I'); g.setEdge('H', 'I'); // Find all connected components // Note: Import components from graphlib/alg if needed // const cmpts = components(g); // Result: [ ['A', 'B', 'C', 'D'], ['E', 'F', 'G'], ['H', 'I'] ] console.log('Number of components: 3'); console.log('Component 1 (Web): A, B, C, D'); console.log('Component 2 (DB): E, F, G'); console.log('Component 3 (Other): H, I'); ``` -------------------------------- ### Topological Sort in Dagre-D3-ES Source: https://context7.com/tbo47/dagre-es/llms.txt Performs a topological sort on a directed acyclic graph (DAG) to determine a valid execution order of nodes. The function throws a 'CycleException' if the graph contains cycles. Requires the 'dagre-d3-es' library. ```javascript import * as dagreD3 from 'dagre-d3-es'; const g = new dagreD3.graphlib.Graph(); g.setNode('install', { label: 'npm install' }); g.setNode('lint', { label: 'Run linter' }); g.setNode('test', { label: 'Run tests' }); g.setNode('build', { label: 'Build app' }); g.setNode('deploy', { label: 'Deploy' }); g.setEdge('install', 'lint'); g.setEdge('install', 'test'); g.setEdge('install', 'build'); g.setEdge('lint', 'build'); g.setEdge('test', 'build'); g.setEdge('build', 'deploy'); try { // const order = topsort(g); // console.log('Execution order:', order); } catch (e) { if (e.constructor.name === 'CycleException') { console.error('Graph contains a cycle!'); } } ``` -------------------------------- ### Customize Node Shapes and Arrows with JavaScript Source: https://context7.com/tbo47/dagre-es/llms.txt The `render` function in dagre-d3-es allows for extensive customization of node shapes and arrow styles by providing custom factory functions. This enables the creation of domain-specific visual elements for graph nodes and edges. ```javascript import * as d3 from 'd3'; import * as dagreD3 from 'dagre-d3-es'; const g = new dagreD3.graphlib.Graph().setGraph({}); g.setNode('hexagon', { label: 'Hex', shape: 'hexagon' }); g.setNode('custom', { label: 'Custom', shape: 'custom' }); // Get the render function const render = dagreD3.render(); // Access and extend built-in shapes const shapes = render.shapes(); // Add a custom hexagon shape shapes.hexagon = function(parent, bbox, node) { const w = bbox.width; const h = bbox.height; const points = [ { x: 0, y: -h/2 }, { x: w/2, y: -h/4 }, { x: w/2, y: h/4 }, { x: 0, y: h/2 }, { x: -w/2, y: h/4 }, { x: -w/2, y: -h/4 } ]; const shapeSvg = parent.insert('polygon', ':first-child') .attr('points', points.map(p => `${p.x},${p.y}`).join(' ')); node.intersect = function(point) { return dagreD3.intersect.polygon.intersectPolygon(node, points, point); }; return shapeSvg; }; // Access and extend arrows const arrows = render.arrows(); // Add custom arrow style arrows.diamond = function(parent, id, edge, type) { const marker = parent.append('marker') .attr('id', id) .attr('viewBox', '0 0 10 10') .attr('refX', 9) .attr('refY', 5) .attr('markerUnits', 'strokeWidth') .attr('markerWidth', 8) .attr('markerHeight', 6) .attr('orient', 'auto'); marker.append('path') .attr('d', 'M 0 5 L 5 0 L 10 5 L 5 10 z') .style('fill', '#333'); }; // Apply custom shapes and arrows render.shapes(shapes); render.arrows(arrows); // Render with custom elements const svg = d3.select('#container'); const inner = svg.append('g'); render(inner, g); ``` -------------------------------- ### Detect Cycles in a Directed Graph (JavaScript) Source: https://context7.com/tbo47/dagre-es/llms.txt Detects all cycles within a directed graph. It returns arrays of nodes that form circular dependencies. This function is crucial for identifying feedback loops or invalid graph structures. It requires a directed graph object as input. ```javascript import * as dagreD3 from 'dagre-d3-es'; const g = new dagreD3.graphlib.Graph(); // Create a graph with multiple cycles g.setNode('1'); g.setNode('2'); g.setNode('3'); g.setNode('4'); g.setNode('5'); // Cycle 1: 1 -> 2 -> 3 -> 1 g.setEdge('1', '2'); g.setEdge('2', '3'); g.setEdge('3', '1'); // Cycle 2: 4 <-> 5 g.setEdge('4', '5'); g.setEdge('5', '4'); // Find all cycles // Note: Import findCycles from graphlib/alg if needed // const cycles = findCycles(g); // Result: [ ['3', '2', '1'], ['5', '4'] ] // Self-loop detection g.setNode('6'); g.setEdge('6', '6'); // Self-referencing node // After adding self-loop: // Result: [ ['3', '2', '1'], ['5', '4'], ['6'] ] console.log('Detected cycles:'); console.log(' Cycle 1: 1 -> 2 -> 3 -> 1'); console.log(' Cycle 2: 4 -> 5 -> 4'); console.log(' Self-loop: 6 -> 6'); ``` -------------------------------- ### Filter Graph Nodes with JavaScript Source: https://context7.com/tbo47/dagre-es/llms.txt The `filterNodes` function in dagre-d3-es creates a new graph containing only nodes that satisfy a given filter condition. Edges connected to filtered-out nodes are automatically removed. This is useful for selectively displaying parts of a graph. ```javascript import * as dagreD3 from 'dagre-d3-es'; const g = new dagreD3.graphlib.Graph(); // Create a graph with different node types g.setNode('user1', { type: 'user', name: 'Alice' }); g.setNode('user2', { type: 'user', name: 'Bob' }); g.setNode('admin1', { type: 'admin', name: 'Charlie' }); g.setNode('service1', { type: 'service', name: 'API' }); g.setNode('service2', { type: 'service', name: 'Database' }); g.setEdge('user1', 'service1'); g.setEdge('user2', 'service1'); g.setEdge('admin1', 'service1'); g.setEdge('admin1', 'service2'); g.setEdge('service1', 'service2'); // Filter to keep only service nodes const servicesOnly = g.filterNodes((v) => { const node = g.node(v); return node && node.type === 'service'; }); console.log(servicesOnly.nodes()); // ['service1', 'service2'] console.log(servicesOnly.edges()); // [{v:'service1', w:'service2'}] // Filter to keep users and services (exclude admins) const noAdmins = g.filterNodes((v) => { const node = g.node(v); return node && node.type !== 'admin'; }); console.log(noAdmins.nodes()); // ['user1', 'user2', 'service1', 'service2'] // admin1's edges are removed, but user->service edges remain ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.