oak-visualize 0.0.11

High-performance visualization and layout algorithms for the oak ecosystem with flexible configuration, emphasizing tree and graph visualization.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
#![doc = "Rendering module for converting layouts to visual formats"]

use crate::{
    geometry::{Point, Rect, Size},
    layout::{Edge, Layout},
};
use std::collections::HashMap;

/// Rendering configuration
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct RenderConfig {
    /// Width of the rendering canvas.
    pub canvas_width: f64,
    /// Height of the rendering canvas.
    pub canvas_height: f64,
    /// Background color of the canvas (hex string).
    pub background_color: String,
    /// Default fill color for nodes (hex string).
    pub node_fill_color: String,
    /// Default stroke color for nodes (hex string).
    pub node_stroke_color: String,
    /// Default stroke width for nodes.
    pub node_stroke_width: f64,
    /// Default color for edges (hex string).
    pub edge_color: String,
    /// Default width for edges.
    pub edge_width: f64,
    /// Default color for text (hex string).
    pub text_color: String,
    /// Default font size for text.
    pub text_size: f64,
    /// Font family for text.
    pub font_family: String,
    /// Padding around the visualization.
    pub padding: f64,
    /// Whether to show node and edge labels.
    pub show_labels: bool,
    /// Whether to show arrowheads on directed edges.
    pub show_arrows: bool,
    /// Size of the arrowheads.
    pub arrow_size: f64,
}

impl Default for RenderConfig {
    fn default() -> Self {
        Self {
            canvas_width: 800.0,
            canvas_height: 600.0,
            background_color: "#ffffff".to_string(),
            node_fill_color: "#e1f5fe".to_string(),
            node_stroke_color: "#0277bd".to_string(),
            node_stroke_width: 2.0,
            edge_color: "#666666".to_string(),
            edge_width: 1.5,
            text_color: "#333333".to_string(),
            text_size: 12.0,
            font_family: "Arial, sans-serif".to_string(),
            padding: 20.0,
            show_labels: true,
            show_arrows: true,
            arrow_size: 8.0,
        }
    }
}

/// Style information for rendering elements
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ElementStyle {
    /// Optional override for the fill color.
    pub fill_color: Option<String>,
    /// Optional override for the stroke color.
    pub stroke_color: Option<String>,
    /// Optional override for the stroke width.
    pub stroke_width: Option<f64>,
    /// Optional override for the text color.
    pub text_color: Option<String>,
    /// Optional override for the text size.
    pub text_size: Option<f64>,
    /// Optional override for the element opacity (0.0 to 1.0).
    pub opacity: Option<f64>,
    /// Optional CSS class name for the element.
    pub class_name: Option<String>,
    /// Custom attributes to be added to the SVG element.
    pub attributes: HashMap<String, String>,
}

impl Default for ElementStyle {
    fn default() -> Self {
        Self { fill_color: None, stroke_color: None, stroke_width: None, text_color: None, text_size: None, opacity: None, class_name: None, attributes: HashMap::new() }
    }
}

impl ElementStyle {
    /// Creates a new default element style.
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the fill color.
    pub fn with_fill(mut self, color: String) -> Self {
        self.fill_color = Some(color);
        self
    }

    /// Sets the stroke color and width.
    pub fn with_stroke(mut self, color: String, width: f64) -> Self {
        self.stroke_color = Some(color);
        self.stroke_width = Some(width);
        self
    }

    /// Sets the text color and size.
    pub fn with_text(mut self, color: String, size: f64) -> Self {
        self.text_color = Some(color);
        self.text_size = Some(size);
        self
    }

    /// Sets the element opacity.
    pub fn with_opacity(mut self, opacity: f64) -> Self {
        self.opacity = Some(opacity);
        self
    }

    /// Sets the CSS class name.
    pub fn with_class(mut self, class_name: String) -> Self {
        self.class_name = Some(class_name);
        self
    }

    /// Adds a custom attribute.
    pub fn with_attribute(mut self, key: String, value: String) -> Self {
        self.attributes.insert(key, value);
        self
    }
}

/// SVG renderer for layouts
pub struct SvgRenderer {
    config: RenderConfig,
    node_styles: HashMap<String, ElementStyle>,
    edge_styles: HashMap<String, ElementStyle>,
}

impl SvgRenderer {
    /// Creates a new SVG renderer with default configuration.
    pub fn new() -> Self {
        Self { config: RenderConfig::default(), node_styles: HashMap::new(), edge_styles: HashMap::new() }
    }

    /// Sets the rendering configuration.
    pub fn with_config(mut self, config: RenderConfig) -> Self {
        self.config = config;
        self
    }

    /// Returns the current rendering configuration.
    pub fn config(&self) -> &RenderConfig {
        &self.config
    }

    /// Sets the style for a specific node.
    pub fn set_node_style(&mut self, node_id: String, style: ElementStyle) {
        self.node_styles.insert(node_id, style);
    }

    /// Sets the style for a specific edge.
    pub fn set_edge_style(&mut self, edge_id: String, style: ElementStyle) {
        self.edge_styles.insert(edge_id, style);
    }

    /// Renders a layout as an SVG string.
    pub fn render_layout(&self, layout: &Layout) -> crate::Result<String> {
        let mut svg = String::new();

        // Calculate bounds and apply padding
        let bounds = self.calculate_bounds(layout);
        let canvas_width = bounds.size.width + 2.0 * self.config.padding;
        let canvas_height = bounds.size.height + 2.0 * self.config.padding;

        // SVG header
        svg.push_str(&format!(r#"<svg width="{}" height="{}" xmlns="http://www.w3.org/2000/svg">"#, canvas_width, canvas_height));
        svg.push('\n');

        // Background
        svg.push_str(&format!(r#"  <rect width="100%" height="100%" fill="{}"/>"#, self.config.background_color));
        svg.push('\n');

        // Define styles
        svg.push_str("  <defs>\n");
        svg.push_str("    <style>\n");
        svg.push_str("      .node { cursor: pointer }\n");
        svg.push_str("      .node:hover { opacity: 0.8 }\n");
        svg.push_str("      .edge { pointer-events: none }\n");
        svg.push_str("      .label { pointer-events: none; user-select: none }\n");
        svg.push_str("    </style>\n");

        // Arrow marker for directed edges
        if self.config.show_arrows {
            svg.push_str(&format!(
                r#"    <marker id="arrowhead" markerWidth="{}" markerHeight="{}" refX="{}" refY="{}" orient="auto">
      <polygon points="0 0, {} {}, {} 0" fill="{}"/>
    </marker>"#,
                self.config.arrow_size,
                self.config.arrow_size,
                self.config.arrow_size,
                self.config.arrow_size / 2.0,
                self.config.arrow_size,
                self.config.arrow_size,
                self.config.arrow_size,
                self.config.edge_color
            ));
            svg.push('\n')
        }

        svg.push_str("  </defs>\n");

        // Transform group to apply padding offset
        svg.push_str(&format!(r#"  <g transform="translate({}, {})">"#, self.config.padding - bounds.origin.x, self.config.padding - bounds.origin.y));
        svg.push('\n');

        // Render edges first (so they appear behind nodes)
        for edge in &layout.edges {
            self.render_edge(&mut svg, edge)?
        }

        // Render nodes
        for node in layout.nodes.values() {
            self.render_node(&mut svg, node)?
        }

        svg.push_str("  </g>\n");
        svg.push_str("</svg>");

        Ok(svg)
    }

    fn render_node(&self, svg: &mut String, node: &crate::layout::PositionedNode) -> crate::Result<()> {
        let style = self.node_styles.get(&node.id);
        let rect = &node.rect;

        let fill_color = style.and_then(|s| s.fill_color.as_ref()).unwrap_or(&self.config.node_fill_color);
        let stroke_color = style.and_then(|s| s.stroke_color.as_ref()).unwrap_or(&self.config.node_stroke_color);
        let stroke_width = style.and_then(|s| s.stroke_width).unwrap_or(self.config.node_stroke_width);

        // Node rectangle
        svg.push_str(&format!(r#"    <rect x="{}" y="{}" width="{}" height="{}" fill="{}" stroke="{}" stroke-width="{}" class="node""#, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height, fill_color, stroke_color, stroke_width));

        // Add custom attributes
        if let Some(style) = style {
            if let Some(opacity) = style.opacity {
                svg.push_str(&format!(r#" opacity="{}""#, opacity))
            }
            if let Some(class) = &style.class_name {
                svg.push_str(&format!(r#" class="node {}""#, class))
            }
            for (key, value) in &style.attributes {
                svg.push_str(&format!(r#" {}="{}""#, key, value))
            }
        }

        svg.push_str("/>\n");

        // Node label
        if self.config.show_labels {
            let text_color = style.and_then(|s| s.text_color.as_ref()).unwrap_or(&self.config.text_color);
            let text_size = style.and_then(|s| s.text_size).unwrap_or(self.config.text_size);

            let center = rect.center();
            svg.push_str(&format!(
                r#"    <text x="{}" y="{}" text-anchor="middle" dominant-baseline="central" fill="{}" font-size="{}" font-family="{}" class="label">{}</text>"#,
                center.x, center.y, text_color, text_size, self.config.font_family, node.label
            ));
            svg.push('\n')
        }

        Ok(())
    }

    fn render_edge(&self, svg: &mut String, edge: &Edge) -> crate::Result<()> {
        let edge_id = format!("{}_{}", edge.from, edge.to);
        let style = self.edge_styles.get(&edge_id);

        let stroke_color = style.and_then(|s| s.stroke_color.as_ref()).unwrap_or(&self.config.edge_color);
        let stroke_width = style.and_then(|s| s.stroke_width).unwrap_or(self.config.edge_width);

        if edge.points.len() < 2 {
            return Ok(());
        }

        // Create path from points
        let mut path_data = String::new();
        path_data.push_str(&format!("M {} {}", edge.points[0].x, edge.points[0].y));

        for point in &edge.points[1..] {
            path_data.push_str(&format!(" L {} {}", point.x, point.y))
        }

        svg.push_str(&format!(r#"    <path d="{}" stroke="{}" stroke-width="{}" fill="none" class="edge""#, path_data, stroke_color, stroke_width));

        // Add arrow marker for directed edges
        if self.config.show_arrows {
            svg.push_str(r#" marker-end="url(#arrowhead)""#)
        }

        // Add custom attributes
        if let Some(style) = style {
            if let Some(opacity) = style.opacity {
                svg.push_str(&format!(r#" opacity="{}""#, opacity))
            }
            if let Some(class) = &style.class_name {
                svg.push_str(&format!(r#" class="edge {}""#, class))
            }
            for (key, value) in &style.attributes {
                svg.push_str(&format!(r#" {}="{}""#, key, value))
            }
        }

        svg.push_str("/>\n");

        // Edge label
        if let Some(label) = &edge.label {
            let mid_point = if edge.points.len() >= 2 {
                let start = &edge.points[0];
                let end = &edge.points[edge.points.len() - 1];
                Point::new((start.x + end.x) / 2.0, (start.y + end.y) / 2.0)
            }
            else {
                edge.points[0]
            };

            let text_color = style.and_then(|s| s.text_color.as_ref()).unwrap_or(&self.config.text_color);
            let text_size = style.and_then(|s| s.text_size).unwrap_or(self.config.text_size * 0.8);

            svg.push_str(&format!(
                r#"    <text x="{}" y="{}" text-anchor="middle" dominant-baseline="central" fill="{}" font-size="{}" font-family="{}" class="label">{}</text>"#,
                mid_point.x,
                mid_point.y - 5.0, // Offset slightly above the edge
                text_color,
                text_size,
                self.config.font_family,
                label
            ));
            svg.push('\n')
        }

        Ok(())
    }

    fn calculate_bounds(&self, layout: &Layout) -> Rect {
        if layout.nodes.is_empty() {
            return Rect::new(Point::origin(), Size::new(self.config.canvas_width, self.config.canvas_height));
        }

        let mut min_x = f64::INFINITY;
        let mut min_y = f64::INFINITY;
        let mut max_x = f64::NEG_INFINITY;
        let mut max_y = f64::NEG_INFINITY;

        for node in layout.nodes.values() {
            let rect = &node.rect;
            min_x = min_x.min(rect.origin.x);
            min_y = min_y.min(rect.origin.y);
            max_x = max_x.max(rect.origin.x + rect.size.width);
            max_y = max_y.max(rect.origin.y + rect.size.height)
        }

        Rect::new(Point::new(min_x, min_y), Size::new(max_x - min_x, max_y - min_y))
    }
}

impl Default for SvgRenderer {
    fn default() -> Self {
        Self::new()
    }
}

/// Export formats for rendered layouts
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExportFormat {
    /// Scalable Vector Graphics format.
    Svg,
    /// HTML document with embedded SVG.
    Html,
    /// JSON representation of the layout.
    Json,
}

/// Layout exporter
pub struct LayoutExporter {
    format: ExportFormat,
    config: RenderConfig,
}

impl LayoutExporter {
    /// Creates a new layout exporter for the specified format.
    pub fn new(format: ExportFormat) -> Self {
        Self { format, config: RenderConfig::default() }
    }

    /// Sets the rendering configuration for the export.
    pub fn with_config(mut self, config: RenderConfig) -> Self {
        self.config = config;
        self
    }

    /// Exports a layout to a string in the configured format.
    pub fn export(&self, layout: &Layout) -> crate::Result<String> {
        match self.format {
            ExportFormat::Svg => {
                let renderer = SvgRenderer::new().with_config(self.config.clone());
                renderer.render_layout(layout)
            }
            ExportFormat::Html => self.export_html(layout),
            ExportFormat::Json => {
                #[cfg(feature = "serde")]
                {
                    self.export_json(layout)
                }
                #[cfg(not(feature = "serde"))]
                {
                    Err(crate::Error::msg("JSON export requires 'serde' feature"))
                }
            }
        }
    }

    fn export_html(&self, layout: &Layout) -> crate::Result<String> {
        let renderer = SvgRenderer::new().with_config(self.config.clone());
        let svg_content = renderer.render_layout(layout)?;

        let html = format!(
            r#"<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pex Visualization</title>
    <style>
        body {{
            margin: 0;
            padding: 20px;
            font-family: Arial, sans-serif;
            background-color: #f5f5f5
        }}
        .container {{
            max-width: 100%;
            margin: 0 auto;
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            padding: 20px
        }}
        svg {{
            max-width: 100%;
            height: auto;
            border: 1px solid #ddd;
            border-radius: 4px
        }}
    </style>
</head>
<body>
    <div class="container">
        <h1>Pex Visualization</h1>
        {}
    </div>
</body>
</html>"#,
            svg_content
        );

        Ok(html)
    }

    #[cfg(feature = "serde")]
    fn export_json(&self, layout: &Layout) -> crate::Result<String> {
        let mut nodes = std::collections::HashMap::new();
        for (id, node) in &layout.nodes {
            let rect = &node.rect;
            nodes.insert(
                id.clone(),
                serde_json::json!({
                    "x": rect.origin.x,
                    "y": rect.origin.y,
                    "width": rect.size.width,
                    "height": rect.size.height
                }),
            );
        }

        let mut edges = Vec::new();
        for edge in &layout.edges {
            let mut points = Vec::new();
            for p in &edge.points {
                points.push(serde_json::json!({
                    "x": p.x,
                    "y": p.y
                }))
            }
            edges.push(serde_json::json!({
                "from": edge.from.clone(),
                "to": edge.to.clone(),
                "points": points,
                "label": edge.label.clone()
            }))
        }

        let json_layout = serde_json::json!({
            "nodes": nodes,
            "edges": edges
        });

        Ok(json_layout.to_string())
    }
}