The @fluxgraph/knowledge package includes a Mermaid-based visualization system that allows you to create clear, portable visualizations of your knowledge graphs.
- Mermaid Diagrams: Generate standard Mermaid diagram syntax
- Multiple Output Formats: Markdown, HTML, or Mermaid Live Editor
- Flexible Layouts: Top-Down (TD), Left-Right (LR), and other Mermaid layouts
- Custom Styling: Node and edge styling through Mermaid syntax
- Lightweight: No heavy dependencies, just text-based diagrams
- Version Control Friendly: Text format is easy to diff and merge
- Wide Compatibility: Works in GitHub, GitLab, documentation tools, etc.
import { KnowledgeGraph, SQLiteAdapter, MermaidGraphVisualizer, MermaidUtils } from '@fluxgraph/knowledge';
// Create a knowledge graph
const adapter = new SQLiteAdapter({
connection: './knowledge.db',
});
const graph = new KnowledgeGraph(adapter);
await graph.initialize();
// Create Mermaid visualizer
const visualizer = new MermaidGraphVisualizer(graph);
// Visualize a specific node's network
const diagram = await visualizer.generateFromNode('node-id', 2, {
direction: 'TD',
includeProperties: true,
});
// Output as Markdown
const markdown = MermaidUtils.toMarkdown(diagram, 'My Graph');
console.log(markdown);Visualize a specific node and its connections up to a certain depth:
const diagram = await visualizer.generateFromNode(nodeId, depth, {
direction: 'TD', // or 'LR', 'BT', 'RL'
includeProperties: true,
maxNodes: 50,
maxEdges: 100,
});Create a diagram from search results:
const diagram = await visualizer.generateFromSearch('engineer', {
maxNodes: 20,
includeProperties: false,
});Show all nodes of specific types:
const diagram = await visualizer.generateFromNodeTypes(['PERSON', 'ORGANIZATION'], {
direction: 'LR',
includeProperties: true,
});Create a diagram from any query result:
const queryResult = await graph.queryRelated(nodeId, { depth: 2 });
const diagram = visualizer.generateFromQueryResult(queryResult, {
direction: 'TD',
includeProperties: false,
});Perfect for documentation, README files, and wikis:
const markdown = MermaidUtils.toMarkdown(diagram, 'Knowledge Graph');
// Returns:
// # Knowledge Graph
//
// ```mermaid
// graph TD
// node1["Label"]
// ...
// ```
//
// **Graph Statistics:** X nodes, Y edgesGenerate a complete HTML page with embedded Mermaid viewer:
const html = MermaidUtils.wrapInHtml(diagram, {
title: 'My Knowledge Graph',
theme: 'default', // or 'dark', 'forest', 'neutral'
});
// Save to file
await fs.writeFile('graph.html', html);Get a URL to edit the diagram online:
const editorUrl = MermaidUtils.generateLiveEditorUrl(diagram);
console.log(`Edit online: ${editorUrl}`);Control the flow direction of the graph:
'TD'or'TB'- Top to Bottom'BT'- Bottom to Top'LR'- Left to Right'RL'- Right to Left
Customize node appearance by type:
const options = {
nodeTypeStyles: {
PERSON: 'fill:#4CAF50,stroke:#333,stroke-width:2px',
ORGANIZATION: 'fill:#2196F3,stroke:#333,stroke-width:2px',
LOCATION: 'fill:#FF9800,stroke:#333,stroke-width:2px',
}
};Control whether to show node/edge properties:
const options = {
includeProperties: true, // Show properties in labels
};Prevent diagrams from becoming too large:
const options = {
maxNodes: 50, // Maximum number of nodes
maxEdges: 100, // Maximum number of edges
};import { KnowledgeGraph, SQLiteAdapter, MermaidGraphVisualizer, MermaidUtils } from '@fluxgraph/knowledge';
import * as fs from 'fs/promises';
async function visualizeKnowledgeGraph() {
// Initialize graph
const adapter = new SQLiteAdapter({ connection: './knowledge.db' });
const graph = new KnowledgeGraph(adapter);
await graph.initialize();
// Create visualizer
const visualizer = new MermaidGraphVisualizer(graph);
// Generate diagram for a person's network
const person = await graph.findNodesByLabel('Alice Johnson');
const diagram = await visualizer.generateFromNode(person[0].id, 2, {
direction: 'TD',
includeProperties: true,
nodeTypeStyles: {
PERSON: 'fill:#4CAF50',
ORGANIZATION: 'fill:#2196F3',
},
});
// Output in multiple formats
// 1. Save as Markdown for documentation
const markdown = MermaidUtils.toMarkdown(diagram, "Alice's Network");
await fs.writeFile('docs/alice-network.md', markdown);
// 2. Generate HTML for web viewing
const html = MermaidUtils.wrapInHtml(diagram, {
title: "Alice's Professional Network",
theme: 'default',
});
await fs.writeFile('visualizations/alice-network.html', html);
// 3. Get Live Editor URL for interactive editing
const editorUrl = MermaidUtils.generateLiveEditorUrl(diagram);
console.log(`Edit diagram online: ${editorUrl}`);
// 4. Print diagram stats
console.log(`Generated diagram with ${diagram.nodeCount} nodes and ${diagram.edgeCount} edges`);
await graph.close();
}Mermaid diagrams in Markdown are automatically rendered by:
- GitHub
- GitLab
- Many documentation tools (MkDocs, Docusaurus, etc.)
- VS Code with Mermaid extensions
- Obsidian and other note-taking apps
Add Mermaid.js to your HTML:
<script src="https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js"></script>
<script>mermaid.initialize({ startOnLoad: true });</script>
<div class="mermaid">
<!-- Paste diagram content here -->
graph TD
A[Node] --> B[Another Node]
</div>Use the generated HTML or serve it through your web framework:
app.get('/graph/:nodeId', async (req, res) => {
const diagram = await visualizer.generateFromNode(req.params.nodeId, 2);
const html = MermaidUtils.wrapInHtml(diagram, {
title: 'Knowledge Graph Visualization',
});
res.send(html);
});Mermaid diagrams are lightweight and render quickly, but for very large graphs:
- Use
maxNodesandmaxEdgesto limit diagram size - Reduce depth when visualizing node networks
- Disable properties (
includeProperties: false) for cleaner diagrams - Use specific node types instead of visualizing everything
We chose Mermaid for knowledge graph visualization because:
- No Dependencies: Unlike D3, Three.js, or Cytoscape, Mermaid requires no heavy libraries
- Text-Based: Diagrams are just text, making them easy to version control
- Portable: Works everywhere - documentation, wikis, web pages
- Maintainable: Simple to understand and modify
- Accessible: Screen reader friendly when properly rendered
- Standard: Widely adopted format with excellent tooling support
If you're upgrading from a version that used D3/Three.js/Cytoscape backends:
- Replace
GraphVisualizationManagerwithMermaidGraphVisualizer - Update visualization method calls (see examples above)
- Remove any frontend dependencies on visualization libraries
- Update your rendering logic to use Mermaid.js or embed in Markdown
The API has been simplified while maintaining the core functionality of generating graph visualizations from your knowledge graph data.