### Run SVG gallery examples Source: https://github.com/ashutoshmahala/zigraph/blob/main/README.md Commands to execute individual SVG gallery examples using the Zig build system. ```bash zig build run-svg_01_basic # Basic zig build run-svg_02_presets # Shape presets zig build run-svg_03_flowchart # Flowchart zig build run-svg_04_clusters # Clusters zig build run-svg_05_dark_theme # Dark theme zig build run-svg_06_interactive # Interactive zig build run-svg_07_heatmap # Heatmap ``` -------------------------------- ### Quick Start Graph Construction Source: https://github.com/ashutoshmahala/zigraph/blob/main/README.md Initialize a graph, add nodes and edges, and render it using a standard layout preset. ```zig const std = @import("std"); const zigraph = @import("zigraph"); pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const allocator = gpa.allocator(); // Build graph var graph = zigraph.Graph.init(allocator); defer graph.deinit(); try graph.addNode(1, "Parse"); try graph.addNode(2, "Compile"); try graph.addNode(3, "Link"); try graph.addDiEdge(1, 2); // directed edge (arrow) try graph.addDiEdgeLabeled(2, 3, "link"); // directed + labeled // try graph.addUnDiEdge(1, 3); // undirected (no arrow) // Layout using a preset (recommended) const output = try zigraph.render(&graph, allocator, zigraph.presets.sugiyama.standard()); defer allocator.free(output); std.debug.print("{s}\n", .{output}); } ``` -------------------------------- ### Run Zigraph Terminal Examples Source: https://github.com/ashutoshmahala/zigraph/blob/main/README.md Execute specific terminal rendering demonstrations using the Zig build system. ```bash zig build run-terminal-node-control # Node borders + colors zig build run-terminal-edge-styles # Edge weights + markers zig build run-terminal-color-system # Color modes + gradients zig build run-terminal-edge-labels # Label placement zig build run-terminal-subgraph-styles # Subgraph borders + nesting zig build run-output-formats # ASCII + HTML output zig build run-terminal-record-nodes # Record-style nodes zig build run-terminal-db-diagram # ER diagram zig build run-streaming # Streaming render zig build run-tui # Interactive TUI zig build run-terminal-text-attrs # Text attributes ``` -------------------------------- ### Initialize and render a graph in the terminal Source: https://github.com/ashutoshmahala/zigraph/blob/main/docs/terminal-customization.md Demonstrates basic graph setup, layout generation, and rendering using both default and custom configurations. ```zig const zigraph = @import("zigraph"); // Allocate + layout var g = zigraph.Graph.init(alloc); defer g.deinit(); try g.addNode(1, "Start"); try g.addNode(2, "End"); try g.addEdge(1, 2); var ir = try zigraph.layout(&g, alloc, .{}); defer ir.deinit(); // Zero-config render (ANSI-256, Unicode, bracket nodes) const output = try zigraph.terminal.render(&ir, alloc); defer alloc.free(output); std.debug.print("{s}\n", .{output}); // Custom config const output2 = try zigraph.terminal.renderWithConfig(&ir, alloc, .{ .node_style_fn = &zigraph.terminal_node_presets.roundedBox, .color_mode = .truecolor, }); defer alloc.free(output2); std.debug.print("{s}\n", .{output2}); ``` -------------------------------- ### Install zigraph via CLI Source: https://github.com/ashutoshmahala/zigraph/blob/main/README.md Use the Zig package manager to add zigraph as a dependency to your project. ```bash zig fetch --save git+https://github.com/AshutoshMahala/zigraph ``` -------------------------------- ### Apply Built-in Node Presets Source: https://github.com/ashutoshmahala/zigraph/blob/main/docs/terminal-customization.md Example usage of built-in presets for automatic implicit/explicit node styling. ```zig // One-liner wiring — built-in presets do the explicit/implicit split automatically: .node_style_fn = &zigraph.terminal_node_presets.singleBox, // ┌─┐ / ┌──╯ open .node_style_fn = &zigraph.terminal_node_presets.heavyBox, // ┏━┓ / ┏━━╯ open .node_style_fn = &zigraph.terminal_node_presets.doubleBox, // ╔═╗ / ╔══╯ open .node_style_fn = &zigraph.terminal_node_presets.roundedBox, // ╭─╮ / ╭──╯ open ``` -------------------------------- ### Apply Layout Presets in Zig Source: https://github.com/ashutoshmahala/zigraph/blob/main/README.md Configuration examples for Sugiyama hierarchical layouts and force-directed graph layouts using built-in presets. ```zig const zigraph = @import("zigraph"); // Sugiyama (hierarchical DAG layout) const ir = try zigraph.layout(&graph, allocator, zigraph.presets.sugiyama.standard()); const ir_fast = try zigraph.layout(&graph, allocator, zigraph.presets.sugiyama.fast()); const ir_quality = try zigraph.layout(&graph, allocator, zigraph.presets.sugiyama.quality()); // Force-directed (any graph type) const ir_fdg = try zigraph.layout(&graph, allocator, zigraph.presets.fdg_presets.standard()); const ir_fdg_fast = try zigraph.layout(&graph, allocator, zigraph.presets.fdg_presets.fast()); ``` -------------------------------- ### Apply Gradient Colors to Edges Source: https://github.com/ashutoshmahala/zigraph/blob/main/docs/terminal-customization.md Example of using a colormap to dynamically style edges based on their index. ```zig fn gradientEdges(ctx: zigraph.EdgeStyleContext) zigraph.TerminalEdgeStyle { const n = @as(f32, @floatFromInt(ctx.total_edges)); const i = @as(f32, @floatFromInt(ctx.edge_index)); return .{ .color = .{ .gradient = .{ .map = &zigraph.color.ColorMap.viridis, .from = i / n, .to = (i + 1.0) / n, } }, }; } ``` -------------------------------- ### Implement custom edge weights Source: https://github.com/ashutoshmahala/zigraph/blob/main/docs/terminal-customization.md Examples of functions that return a TerminalEdgeStyle with specific line weights based on context. ```zig fn heavyEdge(_: zigraph.EdgeStyleContext) zigraph.TerminalEdgeStyle { return .{ .weight = .heavy }; } // Critical path: first edge is heavy, rest are light fn criticalPath(ctx: zigraph.EdgeStyleContext) zigraph.TerminalEdgeStyle { return .{ .weight = if (ctx.edge_index == 0) .heavy else .light }; } ``` -------------------------------- ### JSON IR Quick Example Source: https://github.com/ashutoshmahala/zigraph/blob/main/JSON_SCHEMA.md A sample JSON structure representing a graph layout with nodes, edges, and a subgraph. ```json { "version": "1.2", "width": 25, "height": 10, "level_count": 3, "nodes": [ {"id": 1, "label": "Start", "x": 5, "y": 0, "width": 7, "height": 1, "center_x": 8, "center_y": 0, "level": 0, "level_position": 0, "kind": "explicit", "edge_index": null}, {"id": 2, "label": "Process", "x": 3, "y": 3, "width": 9, "height": 1, "center_x": 7, "center_y": 3, "level": 1, "level_position": 0, "kind": "explicit", "edge_index": null}, {"id": 3, "label": "End", "x": 7, "y": 6, "width": 5, "height": 1, "center_x": 9, "center_y": 6, "level": 2, "level_position": 0, "kind": "explicit", "edge_index": null} ], "edges": [ {"from": 1, "to": 2, "from_x": 8, "from_y": 1, "to_x": 7, "to_y": 3, "path": {"type": "direct"}, "edge_index": 0, "directed": true}, {"from": 2, "to": 3, "from_x": 7, "from_y": 4, "to_x": 9, "to_y": 6, "path": {"type": "direct"}, "edge_index": 1, "directed": true} ], "subgraphs": [ {"id": 0, "label": "Backend", "parent_id": null, "x": 2, "y": 2, "width": 12, "height": 6} ] } ``` -------------------------------- ### Apply Text Attributes Source: https://github.com/ashutoshmahala/zigraph/blob/main/docs/terminal-customization.md Example of applying bold and italic text attributes to a node. ```zig fn boldNode(_: zigraph.NodeStyleContext) zigraph.TerminalNodeStyle { return .{ .border = .single_box, .attrs = .{ .bold = true, .italic = false }, }; } ``` -------------------------------- ### Implement custom edge markers Source: https://github.com/ashutoshmahala/zigraph/blob/main/docs/terminal-customization.md Examples of functions that return a TerminalEdgeStyle with specific marker shapes based on context. ```zig // Bidirectional with different end markers fn biDi(_: zigraph.EdgeStyleContext) zigraph.TerminalEdgeStyle { return .{ .marker_start = .open_circle, .marker_end = .arrow }; } // Rotate through all shapes by edge index fn allMarkers(ctx: zigraph.EdgeStyleContext) zigraph.TerminalEdgeStyle { const shapes = [_]zigraph.MarkerShape{ .arrow, .filled_arrow, .open_arrow, .diamond, .open_diamond, .circle, .open_circle, }; return .{ .marker_end = shapes[ctx.edge_index % shapes.len] }; } ``` -------------------------------- ### Implement Custom Node Style Function Source: https://github.com/ashutoshmahala/zigraph/blob/main/docs/terminal-customization.md Example of a custom function to dynamically style nodes based on labels or implicit status. ```zig fn myNodeStyle(ctx: zigraph.NodeStyleContext) zigraph.TerminalNodeStyle { // Different border style per node label if (std.mem.eql(u8, ctx.label, "Error")) { return .{ .border = .heavy_box, .border_color = .{ .rgb = .{ .r = 220, .g = 50, .b = 50 } }, .text_color = .{ .rgb = .{ .r = 255, .g = 255, .b = 255 } }, }; } // Implicit nodes get open style if (ctx.is_implicit) return .{ .border = .open_single }; return .{ .border = .single_box }; } const output = try zigraph.terminal.renderWithConfig(&ir, alloc, .{ .node_style_fn = &myNodeStyle, }); ``` -------------------------------- ### Create Visual Subgraph Clusters Source: https://github.com/ashutoshmahala/zigraph/blob/main/README.md Group nodes into subgraphs using addSubgraph and putNodes. This example demonstrates rendering a clustered graph using the standard Sugiyama preset. ```zig var graph = zigraph.Graph.init(allocator); defer graph.deinit(); try graph.addNode(0, "Gateway"); try graph.addNode(1, "Auth"); try graph.addNode(2, "DB"); try graph.addDiEdge(0, 1); try graph.addDiEdge(1, 2); // Create a subgraph and assign nodes const backend = try graph.addSubgraph("backend"); try graph.putNodes(&.{ 1, 2 }).inside(backend); const output = try zigraph.render(&graph, allocator, zigraph.presets.sugiyama.standard()); defer allocator.free(output); std.debug.print("{s}\n", .{output}); ``` ```text [Gateway] │ ╔══╧═╤════╗ ║ backend ║ ║ ↓ ║ ║ [Auth] ║ ║ │ ║ ║ ↓ ║ ║ [DB] ║ ║ ║ ╚═════════╝ ``` -------------------------------- ### Apply built-in subgraph preset Source: https://github.com/ashutoshmahala/zigraph/blob/main/docs/terminal-customization.md Example of assigning a pre-defined style function that cycles border styles and colors based on nesting depth. ```zig // Cycles border style and ANSI color by nesting depth: .subgraph_style_fn = &zigraph.terminal_subgraph_presets.depthCycled, ``` -------------------------------- ### Build and Render a Manual Buffer2D Pipeline Source: https://github.com/ashutoshmahala/zigraph/blob/main/docs/terminal-customization.md Use this sequence to manually build a render plan, allocate a buffer, paint elements in Z-order, and serialize the output to a writer. ```zig // Build the render plan (resolves styles, Y-expansion, label placement) var plan = try zigraph.terminal.RenderPlan.build(alloc, &ir, config); defer plan.deinit(); // Allocate a 2D character + color buffer var buf = try zigraph.terminal.Buffer2D.init(alloc, plan.width, plan.height); defer buf.deinit(alloc); // Paint in Z-order using the public paint functions: for (plan.edge_plans) |ep| { zigraph.terminal.paintEdge(&buf, &ep.edge, ep.color, ep.weight, ep.marker_end, ep.marker_start); } const nodes = ir.getNodes(); for (plan.node_plans) |np| { zigraph.terminal.paintNode(&buf, &nodes[np.node_index], false, np.style, np.rendered_y, np.level_height); } // Serialize to any writer const stdout = std.io.getStdOut().writer(); try zigraph.terminal.serializeBuffer(&buf, stdout, config, buf.height); ``` -------------------------------- ### Initialize Graph with Resource Limits Source: https://github.com/ashutoshmahala/zigraph/blob/main/ARCHITECTURE.md Configure maximum node and edge counts to harden the graph against resource exhaustion in constrained environments. ```zig // Default: 100K nodes, 500K edges var graph = Graph.init(allocator); // Custom limits for constrained environments var graph = Graph.initWithOptions(allocator, .{ .max_nodes = 10_000, .max_edges = 50_000, }); ``` -------------------------------- ### Buffer2D Manual Rendering Pipeline Source: https://github.com/ashutoshmahala/zigraph/blob/main/docs/terminal-customization.md Demonstrates how to build a render plan, allocate a buffer, and manually paint nodes and edges to the terminal buffer. ```APIDOC ## Zig SDK: RenderPlan and Buffer2D Pipeline ### Description Builds a render plan to resolve styles and layout, then manually paints graph elements onto a 2D character buffer. ### Methods - **zigraph.terminal.RenderPlan.build(alloc, &ir, config)**: Builds the render plan. - **zigraph.terminal.Buffer2D.init(alloc, width, height)**: Initializes the 2D buffer. - **zigraph.terminal.paintEdge(...)**: Paints an edge to the buffer. - **zigraph.terminal.paintNode(...)**: Paints a node to the buffer. - **zigraph.terminal.serializeBuffer(...)**: Serializes the buffer to a writer. ``` -------------------------------- ### Use Fixed Buffer Arena for Memory Source: https://github.com/ashutoshmahala/zigraph/blob/main/ARCHITECTURE.md Shows how to initialize a graph using a FixedBufferAllocator for embedded or no_std environments. ```zig var buffer: [65536]u8 = undefined; var fba = std.heap.FixedBufferAllocator.init(&buffer); var graph = Graph.init(fba.allocator()); // ... build graph, layout, render - all in fixed buffer ``` -------------------------------- ### Render SVG with Custom Configurations Source: https://github.com/ashutoshmahala/zigraph/blob/main/docs/svg-customization.md Demonstrates basic rendering and applying custom node shapes or monochrome edge styles via SvgConfig. ```zig const zigraph = @import("zigraph"); const svg = zigraph.svg; // Default config — all defaults produce clean output const output = try svg.render(&layout, allocator, .{}); // Custom node shapes const output = try svg.render(&layout, allocator, .{ .node_style_fn = &svg.shapes.diamond, }); // Monochrome edges (no colored palette) const output = try svg.render(&layout, allocator, .{ .edge_style_fn = &svg.monoEdgeStyle, }); ``` -------------------------------- ### Sample and Quantize Colormaps Source: https://github.com/ashutoshmahala/zigraph/blob/main/docs/color-system.md Sample individual colors from a map or generate a lookup table at compile time. ```zig const ColorMap = @import("zigraph").color.ColorMap; // Sample a single color at position t ∈ [0, 1] const c = ColorMap.viridis.sample(0.75); const hex = c.toHexAlloc(arena); // runtime hex string // Pre-bake N stops at comptime for legends, gradients, etc. const lut = comptime ColorMap.turbo.quantize(32); // lut[0..31] are [7]u8 hex strings, baked into binary ``` -------------------------------- ### Manage Graph Memory Ownership Source: https://github.com/ashutoshmahala/zigraph/blob/main/ARCHITECTURE.md Demonstrates the explicit ownership lifecycle for Graph, LayoutIR, and rendered output, requiring manual deallocation for each. ```zig var graph = Graph.init(allocator); // graph owns nodes/edges defer graph.deinit(); const ir = try layout(&graph, allocator, .{}); // ir owns layout data defer ir.deinit(); const output = try terminal.render(ir, allocator); // caller owns output defer allocator.free(output); ``` -------------------------------- ### Color Module Quick Reference Source: https://github.com/ashutoshmahala/zigraph/blob/main/docs/color-system.md Common operations for color creation, manipulation, output, and palette sampling in Zig. ```zig const color = @import("zigraph").color; // ── From hex ──────────────────────────────────── const c = color.Color.fromHex("#3b82f6"); // ── Operations (Oklab space, perceptually uniform) ── const darker = c.darken(0.2); const lighter = c.lighten(0.15); const mid = c.lerp(color.Color.fromHex("#e5484d"), 0.5); // ── Output ────────────────────────────────────── const hex = c.toHex(); // comptime [7]u8 "#3b82f6" const hex_rt = c.toHexAlloc(arena); // runtime []const u8 // ── Continuous colormap ───────────────────────── const heat = color.ColorMap.turbo.sample(0.75); // Color at t=0.75 // ── Discrete palette ──────────────────────────── const edge_color = color.get(&color.radix, edge_index); // cycling "#rrggbb" ``` -------------------------------- ### Run Zigraph build commands Source: https://github.com/ashutoshmahala/zigraph/blob/main/README.md Use these commands in the terminal to execute specific demonstrations, benchmarks, or export tasks for the Zigraph project. ```bash zig build run-basic # Basic usage zig build run-hero # README hero diagram zig build run-presets # Presets demo (all presets side-by-side) zig build run-config # Configuration options demo zig build run-positioning # Positioning algorithms comparison zig build run-svg # SVG with splines zig build run-labels # Edge labels demo (exports SVG) zig build run-cycle # Cycle breaking demo (feedback loops, self-loops) zig build run-subgraph # Subgraph demo (clusters, nesting, SVG/JSON export) zig build run-ns-compare # Compare layering algorithms zig build run-json # JSON export zig build run-fdg # Force-directed layout (terminal + SVG) zig build run-fdg-bench # FDG performance benchmarks zig build run-stress # Stress test suite zig build run-benchmark # Sugiyama benchmarks zig build run-svg-gallery # All SVG gallery examples at once ``` -------------------------------- ### Implementing Radix 12-Step Scales Source: https://github.com/ashutoshmahala/zigraph/blob/main/docs/color-system.md Utilize Radix UI 12-step scales with support for light/dark modes and dynamic styling. ```zig const color = @import("zigraph").color; // Direct access — light mode background const panel_bg = color.scale.blue.light.step(2); // "#f4faff" // Dark mode equivalent const panel_bg_dark = color.scale.blue.dark.step(2); // "#111927" // Mode-switched — pass .light or .dark from app config const mode: color.Mode = if (user_prefers_dark) .dark else .light; const accent = color.scale.red.forMode(mode).step(9); // "#e5484d" (same both) const bg = color.scale.red.forMode(mode).step(2); // "#fff8f8" or "#201314" // As a cycling palette (light mode) const red_palette = color.scale.red.light.all(); // [12][]const u8 const c = color.get(&red_palette, edge_index); // Use in SVG style function fn nodeStyle(ctx: NodeStyleContext) NodeStyle { const s = color.scale.blue.light; // or .dark return .{ .fill = s.step(3), // light background .stroke = s.step(7), // medium border .label_color = s.step(12), // dark text }; } ``` -------------------------------- ### Configure zigraph in build.zig Source: https://github.com/ashutoshmahala/zigraph/blob/main/README.md Add the zigraph module to your executable's root module in the build configuration file. ```zig const zigraph = b.dependency("zigraph", .{}); exe.root_module.addImport("zigraph", zigraph.module("zigraph")); ``` -------------------------------- ### Apply UML marker shapes Source: https://github.com/ashutoshmahala/zigraph/blob/main/docs/svg-customization.md Configure marker_start and marker_end properties to represent relationships like UML composition. ```zig fn umlComposition(ctx: zigraph.EdgeStyleContext) zigraph.EdgeStyle { _ = ctx; return .{ .stroke = "#333", .marker_start = .diamond, // composition diamond at source .marker_end = .arrow, }; } ``` -------------------------------- ### Configure on-path labels Source: https://github.com/ashutoshmahala/zigraph/blob/main/docs/svg-customization.md Enable labels to follow the edge curve globally or per-edge. ```zig // Global setting const output = try svg.render(&layout, allocator, .{ .labels_on_path = true, }); // Or per-edge override via EdgeLabelStyle fn onPathLabels(_: zigraph.EdgeStyleContext) zigraph.EdgeLabelStyle { return .{ .on_path = true }; } ``` -------------------------------- ### Accessing Semantic Colors Source: https://github.com/ashutoshmahala/zigraph/blob/main/docs/color-system.md Use named constants for standard UI meanings like success, error, and warnings. ```zig color.semantic.success // "#30a46c" green color.semantic.warning // "#f76b15" orange color.semantic.error_ // "#e5484d" red color.semantic.info // "#3e63dd" blue color.semantic.neutral // "#666666" gray color.semantic.highlight // "#ffe629" yellow ``` -------------------------------- ### Apply Force-Directed Layout Source: https://github.com/ashutoshmahala/zigraph/blob/main/README.md Use Fruchterman-Reingold algorithm for non-hierarchical graphs via presets or manual configuration. ```zig const zigraph = @import("zigraph"); // Use preset (recommended) var ir = try zigraph.layout(&graph, allocator, zigraph.presets.fdg_presets.standard()); var ir_fast = try zigraph.layout(&graph, allocator, zigraph.presets.fdg_presets.fast()); // Or manual config for fine control var ir_custom = try zigraph.layout(&graph, allocator, .{ .algorithm = .{ .fruchterman_reingold = .{} }, }); defer ir_custom.deinit(); ``` -------------------------------- ### Construct CellColor Instances Source: https://github.com/ashutoshmahala/zigraph/blob/main/docs/terminal-customization.md Create CellColor values using RGB, ANSI 256 indices, or the default terminal color. ```zig const cc = zigraph.terminal.CellColor.rgb(70, 130, 180); // 24-bit const cc = zigraph.terminal.CellColor.ansi256(33); // ANSI 256 index const cc = zigraph.terminal.CellColor.none; // terminal default ``` -------------------------------- ### Implement custom label placement and coloring Source: https://github.com/ashutoshmahala/zigraph/blob/main/docs/terminal-customization.md Define functions to dynamically control label placement and color based on the edge context. ```zig fn nearSource(_: zigraph.EdgeStyleContext) zigraph.TerminalEdgeLabelStyle { return .{ .placement = .near_source }; } fn coloredLabels(ctx: zigraph.EdgeStyleContext) zigraph.TerminalEdgeLabelStyle { const palette = [_]zigraph.TerminalColor{ .{ .ansi256 = 196 }, .{ .ansi256 = 46 }, .{ .ansi256 = 33 }, }; return .{ .color = palette[ctx.edge_index % palette.len], .placement = .center, }; } ``` -------------------------------- ### Add a subgraph to a graph Source: https://github.com/ashutoshmahala/zigraph/blob/main/docs/terminal-customization.md Demonstrates the syntax for creating a subgraph and adding nodes to it during graph construction. ```zig const sg = try g.addSubgraph("Backend"); try g.putNodes(&.{ node1_id, node2_id }).inside(sg); ``` -------------------------------- ### zigraph.terminal.renderWithConfig Source: https://github.com/ashutoshmahala/zigraph/blob/main/README.md Renders a graph to a terminal-friendly box-drawing format with optional ANSI color configuration. ```APIDOC ## zigraph.terminal.renderWithConfig ### Description Generates a string representation of the graph using box-drawing characters suitable for terminal output. ### Signature `fn renderWithConfig(ir: *const Graph, allocator: Allocator, config: Config) ![]u8` ### Parameters - **ir** (*const Graph) - The graph structure to render. - **allocator** (Allocator) - Memory allocator for the output string. - **config** (struct) - Configuration object containing `edge_palette` and `show_dummy_nodes` settings. ``` -------------------------------- ### Render terminal output as HTML pre Source: https://github.com/ashutoshmahala/zigraph/blob/main/docs/terminal-customization.md Generates HTML output using
 tags and inline styles, suitable for embedding in web pages.

```zig
const html = try zigraph.terminal.renderWithConfig(&ir, alloc, .{
    .output_format   = .html_pre,
    .color_mode      = .truecolor,
    .html_pre_style  = "font-family: 'JetBrains Mono', monospace; line-height: 1.4",
});
```

--------------------------------

### Create paint wrapper for custom nodes

Source: https://github.com/ashutoshmahala/zigraph/blob/main/docs/terminal-customization.md

Provides a thin wrapper function to bridge the entity instance with the required paint_fn signature.

```zig
const server = Entity{ .name = "Server", .fields = &.{ ... } };

fn paintServer(buf: *T.Buffer2D, ctx: T.NodePaintContext) void {
    server.paint(buf, ctx);
}
```

--------------------------------

### Implement Type-erased Renderer

Source: https://github.com/ashutoshmahala/zigraph/blob/main/docs/svg-customization.md

Demonstrates how to write generic rendering functions that accept any Zigraph renderer backend.

```zig
const zigraph = @import("zigraph");

fn renderToFile(
    layout: *const zigraph.LayoutIR,
    renderer: zigraph.Renderer,
    path: []const u8,
    allocator: std.mem.Allocator,
) !void {
    const output = try renderer.render(layout, allocator);
    defer allocator.free(output);
    try std.fs.cwd().writeFile(.{ .sub_path = path, .data = output });
}

// Use with any backend:
const svg_config = zigraph.svg.SvgConfig{};
try renderToFile(&layout, zigraph.Renderer.initSvg(&svg_config), "out.svg", alloc);
try renderToFile(&layout, zigraph.Renderer.initJson(), "out.json", alloc);
```

--------------------------------

### zigraph.render

Source: https://github.com/ashutoshmahala/zigraph/blob/main/README.md

Configures and executes the graph rendering process using the provided graph and allocator.

```APIDOC
## zigraph.render

### Description
Configures and executes the graph rendering process. Users can specify layering strategies, node positioning, crossing reduction algorithms, edge routing, and spacing parameters.

### Parameters
- **graph** (Graph) - Required - The graph structure to render.
- **allocator** (Allocator) - Required - The memory allocator for the rendering process.
- **options** (struct) - Required - Configuration options including:
  - **layering** (enum) - Optional - Strategy for layering (e.g., .longest_path, .network_simplex).
  - **positioning** (enum) - Optional - Strategy for node positioning (e.g., .compact, .barycentric, .brandes_kopf).
  - **crossing_reducers** ([]Reducer) - Optional - Slice of crossing reduction algorithms.
  - **routing** (enum) - Optional - Edge routing style (.direct or .spline).
  - **node_spacing** (int) - Optional - Spacing between nodes.
  - **level_spacing** (int) - Optional - Spacing between levels.
  - **skip_validation** (bool) - Optional - Whether to skip graph validation.
```

--------------------------------

### Available Color Maps

Source: https://github.com/ashutoshmahala/zigraph/blob/main/docs/terminal-customization.md

List of available colormaps for gradient rendering.

```zig
zigraph.color.ColorMap.viridis    // blue–green–yellow
zigraph.color.ColorMap.inferno    // black–red–yellow
zigraph.color.ColorMap.turbo      // full rainbow
zigraph.color.ColorMap.coolwarm   // blue–white–red
zigraph.color.ColorMap.plasma     // purple–orange–yellow
zigraph.color.ColorMap.magma      // black–purple–white
```

--------------------------------

### Configure Crossing Reducer Pipelines

Source: https://github.com/ashutoshmahala/zigraph/blob/main/ARCHITECTURE.md

Apply preset crossing reduction strategies or define custom pipelines to optimize graph layout quality.

```zig
// Use a preset
const ir = try zigraph.layout(&graph, allocator, .{
    .crossing_reducers = &zigraph.crossing.quality,
});

// Or build custom pipeline
const custom = &[_]zigraph.crossing.Reducer{
    zigraph.crossing.medianReducer(6),
    zigraph.crossing.adjacentExchangeReducer(3),
};
const ir = try zigraph.layout(&graph, allocator, .{
    .crossing_reducers = custom,
});
```

--------------------------------

### Build and render graph with custom nodes

Source: https://github.com/ashutoshmahala/zigraph/blob/main/docs/terminal-customization.md

Adds nodes with custom dimensions and renders the graph using the custom style function.

```zig
try g.addNode(1, server.nodeOptions());  // width and height from content
var ir = try zigraph.layout(&g, alloc, .{});
const output = try T.renderWithConfig(&ir, alloc, .{ .node_style_fn = &nodeStyle });
```

--------------------------------

### Style Colored Nodes

Source: https://github.com/ashutoshmahala/zigraph/blob/main/docs/terminal-customization.md

Apply border, text, and background colors to nodes using the Color union.

```zig
fn coloredNode(ctx: zigraph.NodeStyleContext) zigraph.TerminalNodeStyle {
    return .{
        .border       = .single_box,
        .border_color = .{ .rgb = .{ .r = 70, .g = 130, .b = 180 } }, // steel-blue
        .text_color   = .{ .rgb = .{ .r = 255, .g = 255, .b = 255 } }, // white
        .bg_color     = .default,
    };
}
```

--------------------------------

### Render Zigraph Layout to SVG

Source: https://github.com/ashutoshmahala/zigraph/blob/main/JSON_SCHEMA.md

Demonstrates how to map layout coordinates to SVG elements using a cell-based grid system. Requires a layout object containing nodes and edges.

```javascript
function renderToSVG(layout) {
  const cellWidth = 10;  // pixels per character cell
  const cellHeight = 20;
  
  let svg = ``;
  
  // Render nodes as rectangles
  for (const node of layout.nodes) {
    svg += ``;
    svg += `${node.label}`;
  }
  
  // Render edges as paths
  for (const edge of layout.edges) {
    if (edge.path.type === "direct") {
      svg += ``;
    }
    // Handle other path types...
  }
  
  svg += '';
  return svg;
}
```

--------------------------------

### Implement custom subgraph style function

Source: https://github.com/ashutoshmahala/zigraph/blob/main/docs/terminal-customization.md

Shows how to define a custom function that returns a TerminalSubgraphStyle based on the provided SubgraphStyleContext.

```zig
fn mySubgraph(ctx: zigraph.SubgraphStyleContext) zigraph.TerminalSubgraphStyle {
    const borders = [_]zigraph.terminal.SubgraphBorder{ .double, .single, .dashed };
    const colors  = [_]u8{ 33, 34, 35 }; // blue, blue-green, magenta
    return .{
        .border    = borders[ctx.depth % borders.len],
        .color     = .{ .ansi256 = colors[ctx.depth % colors.len] },
        .label_pos = .top_center,
    };
}
```

--------------------------------

### Visualize Coordinate System

Source: https://github.com/ashutoshmahala/zigraph/blob/main/JSON_SCHEMA.md

Diagram illustrating the top-left origin (0,0) and axis orientation for the layout.

```text
(0,0) ────────────────────────▶ x
  │
  │    [Node A]       ← y=0, node box
  │       │
  │       ↓
  │    [Node B]       ← y=3 (after spacing)
  │
  ▼
  y
```

--------------------------------

### Terminal Rendering API Signatures

Source: https://github.com/ashutoshmahala/zigraph/blob/main/docs/terminal-customization.md

API methods for rendering graphs to terminal output, supporting buffered, streaming, and low-level pipeline operations.

```zig
// High-level (buffers output into []u8)
zigraph.terminal.render(&ir, alloc)                            -> ![]u8
zigraph.terminal.renderWithConfig(&ir, alloc, config)         -> ![]u8

// Streaming (writes directly to writer — zero allocation for output)
zigraph.terminal.renderStreaming(&ir, writer, alloc)           -> !void
zigraph.terminal.renderStreamingWithConfig(&ir, writer, alloc, config) -> !void

// Generic (accepts any coordinate type — converts to usize internally)
zigraph.terminal.renderGenericWithConfig(Coord, &ir, alloc, config) -> ![]u8
zigraph.terminal.renderGenericStreamingWithConfig(Coord, &ir, writer, alloc, config) -> !void

// Low-level pipeline
zigraph.terminal.RenderPlan.build(alloc, &ir, config)          -> !RenderPlan
zigraph.terminal.Buffer2D.init(alloc, width, height)           -> !Buffer2D
zigraph.terminal.paintNode(&buf, node, show_dummies, style, y, level_h) -> void
zigraph.terminal.paintEdge(&buf, edge, color, weight, end, start) -> void
zigraph.terminal.serializeBuffer(&buf, writer, config, height)  -> !void
```

--------------------------------

### Accessing Discrete Palettes

Source: https://github.com/ashutoshmahala/zigraph/blob/main/docs/color-system.md

Retrieve colors from predefined palettes or custom arrays using index-based access.

```zig
const color = @import("zigraph").color;

// Cycle through palette by index (wraps around)
const c = color.get(&color.radix, edge_index);  // "#rrggbb"

// Access specific entry
const first = color.radix[0];                    // "#e5484d"

// Any []const []const u8 works — bring your own palette
const my_palette = [_][]const u8{ "#ff0000", "#00ff00", "#0000ff" };
const c2 = color.get(&my_palette, i);
```

--------------------------------

### Apply Zigraph Layout Presets

Source: https://github.com/ashutoshmahala/zigraph/blob/main/ARCHITECTURE.md

Utilize predefined layout configurations for graph processing. Presets enforce specific validation requirements on the input graph.

```zig
// Use a preset (recommended)
const ir = try zigraph.layout(&graph, allocator, zigraph.presets.sugiyama.standard());

// Presets include validation requirements
const preset = zigraph.presets.sugiyama.preset(.quality);
// preset.requirements = { .non_empty = true, .acyclic = true, .all_directed = true }
```

--------------------------------

### zigraph.terminal.render

Source: https://github.com/ashutoshmahala/zigraph/blob/main/docs/terminal-customization.md

Renders the graph to a buffer.

```APIDOC
## zigraph.terminal.render

### Description
High-level rendering function that buffers output into a byte slice.

### Signature
zigraph.terminal.render(&ir, alloc) -> ![]u8

### Parameters
- **ir** (any) - The intermediate representation of the graph.
- **alloc** (Allocator) - The memory allocator.
```

--------------------------------

### Buffer2D API Methods

Source: https://github.com/ashutoshmahala/zigraph/blob/main/docs/terminal-customization.md

Directly manipulate the character and color buffer using these coordinate-based methods.

```zig
buf.set(x, y, codepoint: u21)                        // write glyph only
buf.setWithColor(x, y, codepoint, color: CellColor)  // write glyph + fg color
buf.setBgColor(x, y, color: CellColor)               // write bg color only
buf.get(x, y) -> u21                                  // read glyph
buf.getColor(x, y) -> CellColor                      // read fg color
```

--------------------------------

### Execute Comptime Color Patterns

Source: https://github.com/ashutoshmahala/zigraph/blob/main/docs/color-system.md

Perform color calculations at compile time to eliminate runtime overhead for static colors and colormaps.

```zig
// Baked into .rodata — no runtime computation
const warning_dark = comptime Color.fromHex("#f59e0b").darken(0.15).toHex();
// warning_dark = "#c47f09" — a [7]u8 string literal

// Pre-baked colormap LUT — 64 hex strings, zero runtime cost
const turbo_lut = comptime ColorMap.turbo.quantize(64);
// turbo_lut[0] = "#30123b", turbo_lut[63] = "#7a0403"
```

--------------------------------

### zigraph.terminal.renderStreamingWithConfig

Source: https://github.com/ashutoshmahala/zigraph/blob/main/docs/terminal-customization.md

Streams the rendered graph to a writer using a custom configuration.

```APIDOC
## zigraph.terminal.renderStreamingWithConfig

### Description
Streaming rendering function that writes directly to a writer using a provided configuration.

### Signature
zigraph.terminal.renderStreamingWithConfig(&ir, writer, alloc, config) -> !void

### Parameters
- **ir** (any) - The intermediate representation of the graph.
- **writer** (Writer) - The output writer.
- **alloc** (Allocator) - The memory allocator.
- **config** (Config) - The configuration struct.
```

--------------------------------

### Process Zigraph Data in Python

Source: https://github.com/ashutoshmahala/zigraph/blob/main/JSON_SCHEMA.md

Provides utility functions for loading JSON layout strings and calculating node bounding boxes. Assumes input is a valid JSON string matching the Zigraph schema.

```python
import json

def load_layout(json_str: str) -> dict:
    layout = json.loads(json_str)
    assert layout["version"] in ("1.0", "1.1")
    return layout

def node_bounds(node: dict) -> tuple:
    """Return (left, top, right, bottom) bounds."""
    return (
        node["x"],
        node["y"],
        node["x"] + node["width"],
        node["y"] + 1
    )
```

--------------------------------

### Apply Discrete ANSI Palette to Edges

Source: https://github.com/ashutoshmahala/zigraph/blob/main/docs/terminal-customization.md

Use the getAnsi helper to map an edge index to a color from a predefined palette.

```zig
fn paletteEdge(ctx: zigraph.EdgeStyleContext) zigraph.TerminalEdgeStyle {
    return .{ .color = .{
        .ansi256 = zigraph.color.getAnsi(&zigraph.color.ansi_dark, ctx.edge_index),
    } };
}
```

--------------------------------

### Apply Dynamic Styles with Arena Allocator

Source: https://github.com/ashutoshmahala/zigraph/blob/main/docs/svg-customization.md

Utilizes the provided arena allocator for dynamic string formatting within style functions, ensuring memory is automatically reclaimed after the render pass.

```zig
fn dynamicColor(ctx: zigraph.NodeStyleContext) zigraph.NodeStyle {
    const color = std.fmt.allocPrint(ctx.arena, "hsl({d}, 70%, 50%)", .{
        (ctx.node_id * 137) % 360,
    }) catch "#999";

    return .{
        .shape_svg = zigraph.shapes.rounded_rectangle(ctx).shape_svg,
        .fill = color,
        .stroke = "#333",
    };
}
```

--------------------------------

### Enable Cycle Breaking

Source: https://github.com/ashutoshmahala/zigraph/blob/main/README.md

Configure the renderer with .cycle_breaking = .depth_first to handle cyclic graphs. This performs virtual reversal of back-edges without mutating the original graph structure.

```zig
var graph = zigraph.Graph.init(allocator);
defer graph.deinit();

try graph.addNode(1, "Input");
try graph.addNode(2, "Process");
try graph.addNode(3, "Output");

try graph.addEdge(1, 2);
try graph.addEdge(2, 3);
try graph.addEdgeLabeled(3, 1, "feedback"); // Creates a cycle!

const output = try zigraph.render(&graph, allocator, .{
    .cycle_breaking = .depth_first,
});
defer allocator.free(output);
std.debug.print("{s}\n", .{output});
```

--------------------------------

### color.get

Source: https://github.com/ashutoshmahala/zigraph/blob/main/docs/color-system.md

Retrieves a color from a palette by index, with automatic wrapping.

```APIDOC
## color.get(palette, index)

### Description
Retrieves a color string from a provided palette slice. The index wraps around if it exceeds the palette length.

### Parameters
- **palette** ([]const []const u8) - Required - The palette slice to retrieve from.
- **index** (usize) - Required - The index of the color to retrieve.

### Response
- **color** (string) - The hex color string.
```

--------------------------------

### Composing WDP Error Codes at Comptime

Source: https://github.com/ashutoshmahala/zigraph/blob/main/ARCHITECTURE.md

Define error codes using semantic building blocks to ensure consistency across the project.

```zig
// Building blocks
const E = "E";           // Severity: Error
const Graph = "Graph";   // Component
const Node = "Node";     // Primary
const MISSING = "001";   // Sequence (WDP Part 6)

// Composed at comptime
pub const EMPTY_GRAPH = code(E, Graph, Node, MISSING); // → "E.Graph.Node.001"
```

--------------------------------

### Implement depth-aware subgraph styling

Source: https://github.com/ashutoshmahala/zigraph/blob/main/docs/svg-customization.md

Uses SubgraphStyleContext to dynamically assign colors and SVG structure based on the subgraph depth.

```zig
fn depthAwareSubgraph(ctx: zigraph.SubgraphStyleContext) zigraph.SubgraphStyle {
    const fills = [_][]const u8{ "#e8f4fd", "#e6f4ea", "#fff4e6" };
    const strokes = [_][]const u8{ "#3b82f6", "#30a46c", "#f59e0b" };

    return .{
        .box_svg = std.fmt.allocPrint(ctx.arena,
            \\
            \\{s}
        , .{ ctx.width, ctx.height, strokes[ctx.depth % 3], ctx.label }) catch "",
        .fill = fills[ctx.depth % fills.len],
        .stroke = strokes[ctx.depth % strokes.len],
    };
}
```

--------------------------------

### Define Terminal Configuration

Source: https://github.com/ashutoshmahala/zigraph/blob/main/docs/terminal-customization.md

The Config struct controls visual aspects like node visibility, color modes, and custom styling functions for edges, nodes, and subgraphs.

```zig
pub const Config = struct {
    show_dummy_nodes:    bool        = false,  // debug: show dummy layout nodes
    show_subgraphs:      bool        = true,
    edge_palette:        ?[]const u8 = null,   // ANSI palette fallback; priority: edge_style_fn color > edge_palette > no color
    color_mode:          ColorMode   = .ansi256,
    char_set:            CharSet     = .unicode,
    output_format:       OutputFormat = .raw,
    html_pre_style:      []const u8  = "font-family:monospace;line-height:1.2",

    edge_style_fn:       *const fn (EdgeStyleContext) TerminalEdgeStyle       = &defaultEdgeStyle,
    node_style_fn:       *const fn (NodeStyleContext) TerminalNodeStyle       = &defaultNodeStyle,
    edge_label_style_fn: *const fn (EdgeStyleContext) TerminalEdgeLabelStyle  = &defaultEdgeLabelStyle,
    subgraph_style_fn:   *const fn (SubgraphStyleContext) TerminalSubgraphStyle = &defaultSubgraphStyle,
};
```

--------------------------------

### Using ANSI Palettes for Terminals

Source: https://github.com/ashutoshmahala/zigraph/blob/main/docs/color-system.md

Retrieve terminal-optimized color codes and escape sequences for the Unicode renderer.

```zig
const ansi_code = color.getAnsi(&color.ansi_dark, edge_index);
const colored = color.escape.fg256(ansi_code);   // "\x1b[38;5;{code}m"
const reset = color.escape.reset;                 // "\x1b[0m"
```

--------------------------------

### Inject global CSS and JavaScript

Source: https://github.com/ashutoshmahala/zigraph/blob/main/docs/svg-customization.md

Configures global styles and scripts during SVG rendering to enable hover effects, custom fonts, and event listeners.

```zig
const output = try svg.render(&layout, allocator, .{
    .global_style =
        \\
    ,
    .global_script =
        \\
    ,
});
```

--------------------------------

### Color Module Structure

Source: https://github.com/ashutoshmahala/zigraph/blob/main/docs/color-system.md

Overview of the sub-modules available within zigraph.color.

```text
zigraph.color
  ├── Color        ← RGBA struct with color-space math
  ├── ColorMap     ← Continuous 0→1 scientific colormaps
  ├── gradient     ← SVG  /  generators
  └── palettes     ← Discrete hex + ANSI terminal palettes
```

--------------------------------

### zigraph.layout

Source: https://github.com/ashutoshmahala/zigraph/blob/main/ARCHITECTURE.md

Applies a layout preset to a graph using the specified allocator.

```APIDOC
## zigraph.layout

### Description
Computes a graph layout based on a provided preset configuration.

### Signature
`zigraph.layout(graph: *Graph, allocator: Allocator, preset: Preset) !LayoutResult`

### Parameters
- **graph** (*Graph) - Required - The graph structure to layout.
- **allocator** (Allocator) - Required - The memory allocator for the layout result.
- **preset** (Preset) - Required - The configuration preset (e.g., zigraph.presets.sugiyama.standard()).
```

--------------------------------

### Define a Direct Path

Source: https://github.com/ashutoshmahala/zigraph/blob/main/JSON_SCHEMA.md

Configures a straight vertical or single-bend connection between endpoints.

```json
{"type": "direct"}
```

--------------------------------

### Resolve Color for Manual Buffer Writes

Source: https://github.com/ashutoshmahala/zigraph/blob/main/docs/terminal-customization.md

Convert a standard Color type into a CellColor suitable for manual buffer operations.

```zig
const cc = zigraph.terminal.resolveColorAt(my_color, 0.0);  // t=0.0 for flat colors
```

--------------------------------

### Apply Conditional Node Styling

Source: https://github.com/ashutoshmahala/zigraph/blob/main/docs/svg-customization.md

Implement logic within a style function to return different NodeStyle configurations based on node labels.

```zig
fn styleByLabel(ctx: zigraph.NodeStyleContext) zigraph.NodeStyle {
    if (std.mem.eql(u8, ctx.label, "Error")) {
        return .{
            .shape_svg = zigraph.shapes.rounded_rectangle(ctx).shape_svg,
            .fill = "#fee2e2",
            .stroke = "#e5484d",
        };
    }
    return zigraph.shapes.rounded_rectangle(ctx);
}
```