Convert GraphContext objects to Mermaid.js diagram strings for visualization
context_to_mermaid
Converts a GraphContext into a Mermaid.js flowchart diagram string. The resulting string can be rendered in Markdown environments that support Mermaid (GitHub, Jupyter with extensions, documentation sites, etc.).
# Test with node color mappingcolor_map = {"Person": "#ffaaaa","Concept": "#aaaaff"}mermaid_styled = context_to_mermaid(ctx, node_color_map=color_map)print(mermaid_styled)
# Test with empty contextempty_ctx = GraphContext(nodes=[], edges=[])mermaid_empty = context_to_mermaid(empty_ctx)print(mermaid_empty)assert mermaid_empty =="graph TD"
graph TD
# Test node with special characters in namespecial_node = GraphNode(id=str(uuid.uuid4()), label="Quote", properties={"name": 'He said "hello"'})special_ctx = GraphContext(nodes=[special_node], edges=[])mermaid_special = context_to_mermaid(special_ctx)print(mermaid_special)assert"He said 'hello'"in mermaid_special # Double quotes replaced with single quotes
graph TD
N0["He said 'hello'"]
# Test fallback to label when no name/title propertylabel_only_node = GraphNode(id=str(uuid.uuid4()), label="UnnamedThing", properties={"other": "value"})label_ctx = GraphContext(nodes=[label_only_node], edges=[])mermaid_label = context_to_mermaid(label_ctx)print(mermaid_label)assert"UnnamedThing"in mermaid_label
graph TD
N0["UnnamedThing"]
# Test that edges referencing missing nodes are skippedorphan_edge = GraphEdge(id=str(uuid.uuid4()), source_id="nonexistent-1", target_id="nonexistent-2", relation_type="BROKEN")single_node = GraphNode(id=str(uuid.uuid4()), label="Lonely", properties={"name": "Solo"})orphan_ctx = GraphContext(nodes=[single_node], edges=[orphan_edge])mermaid_orphan = context_to_mermaid(orphan_ctx)print(mermaid_orphan)assert"BROKEN"notin mermaid_orphan # Orphan edge should not appear