Skip to main content

oxirs_chat/
visualization.rs

1//! Result Visualization Helpers
2//!
3//! Provides utilities for generating visualizations and visual representations
4//! of query results, knowledge graph structures, and analytics data.
5
6use anyhow::Result;
7use serde::{Deserialize, Serialize};
8use std::collections::HashMap;
9use tracing::debug;
10
11/// Visualization type
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
13pub enum VisualizationType {
14    /// Table view
15    Table,
16    /// Bar chart
17    BarChart,
18    /// Line chart
19    LineChart,
20    /// Pie chart
21    PieChart,
22    /// Network/graph visualization
23    Network,
24    /// Tree visualization
25    Tree,
26    /// Timeline visualization
27    Timeline,
28    /// Heatmap
29    Heatmap,
30    /// Geographic map
31    GeoMap,
32    /// Custom visualization
33    Custom,
34}
35
36/// Visualization configuration
37#[derive(Debug, Clone, Serialize, Deserialize)]
38pub struct VisualizationConfig {
39    /// Visualization type
40    pub viz_type: VisualizationType,
41    /// Title
42    pub title: String,
43    /// Width (pixels or percentage)
44    pub width: String,
45    /// Height (pixels or percentage)
46    pub height: String,
47    /// Color scheme
48    pub color_scheme: ColorScheme,
49    /// Interactive features
50    pub interactive: bool,
51    /// Additional options
52    pub options: HashMap<String, serde_json::Value>,
53}
54
55impl Default for VisualizationConfig {
56    fn default() -> Self {
57        Self {
58            viz_type: VisualizationType::Table,
59            title: "Data Visualization".to_string(),
60            width: "100%".to_string(),
61            height: "400px".to_string(),
62            color_scheme: ColorScheme::Default,
63            interactive: true,
64            options: HashMap::new(),
65        }
66    }
67}
68
69/// Color scheme for visualizations
70#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
71pub enum ColorScheme {
72    /// Default colors
73    Default,
74    /// Blue theme
75    Blue,
76    /// Green theme
77    Green,
78    /// Red theme
79    Red,
80    /// Purple theme
81    Purple,
82    /// Grayscale
83    Grayscale,
84    /// Rainbow
85    Rainbow,
86    /// Custom
87    Custom,
88}
89
90/// Visualization data point
91#[derive(Debug, Clone, Serialize, Deserialize)]
92pub struct DataPoint {
93    /// X-axis value
94    pub x: String,
95    /// Y-axis value
96    pub y: f64,
97    /// Label
98    pub label: Option<String>,
99    /// Additional metadata
100    pub metadata: HashMap<String, String>,
101}
102
103/// Network node for graph visualizations
104#[derive(Debug, Clone, Serialize, Deserialize)]
105pub struct NetworkNode {
106    /// Node ID
107    pub id: String,
108    /// Node label
109    pub label: String,
110    /// Node type/category
111    pub node_type: String,
112    /// Node size (relative)
113    pub size: f32,
114    /// Node color
115    pub color: Option<String>,
116    /// Position (x, y)
117    pub position: Option<(f64, f64)>,
118    /// Metadata
119    pub metadata: HashMap<String, String>,
120}
121
122/// Network edge for graph visualizations
123#[derive(Debug, Clone, Serialize, Deserialize)]
124pub struct NetworkEdge {
125    /// Source node ID
126    pub source: String,
127    /// Target node ID
128    pub target: String,
129    /// Edge label
130    pub label: Option<String>,
131    /// Edge weight
132    pub weight: f32,
133    /// Edge color
134    pub color: Option<String>,
135    /// Is directed?
136    pub directed: bool,
137}
138
139/// Visualization specification
140#[derive(Debug, Clone, Serialize, Deserialize)]
141pub struct VisualizationSpec {
142    /// Configuration
143    pub config: VisualizationConfig,
144    /// Data (format depends on visualization type)
145    pub data: VisualizationData,
146    /// Rendering hints
147    pub rendering_hints: HashMap<String, String>,
148}
149
150/// Visualization data
151#[derive(Debug, Clone, Serialize, Deserialize)]
152#[serde(tag = "type")]
153pub enum VisualizationData {
154    /// Tabular data
155    Table {
156        columns: Vec<String>,
157        rows: Vec<Vec<String>>,
158    },
159    /// Chart data points
160    Chart { series: Vec<ChartSeries> },
161    /// Network/graph data
162    Network {
163        nodes: Vec<NetworkNode>,
164        edges: Vec<NetworkEdge>,
165    },
166    /// Tree data
167    Tree { root: TreeNode },
168    /// Timeline events
169    Timeline { events: Vec<TimelineEvent> },
170    /// Heatmap data
171    Heatmap {
172        data: Vec<Vec<f64>>,
173        x_labels: Vec<String>,
174        y_labels: Vec<String>,
175    },
176}
177
178/// Chart series
179#[derive(Debug, Clone, Serialize, Deserialize)]
180pub struct ChartSeries {
181    /// Series name
182    pub name: String,
183    /// Data points
184    pub data: Vec<DataPoint>,
185    /// Series color
186    pub color: Option<String>,
187}
188
189/// Tree node
190#[derive(Debug, Clone, Serialize, Deserialize)]
191pub struct TreeNode {
192    /// Node ID
193    pub id: String,
194    /// Node label
195    pub label: String,
196    /// Children
197    pub children: Vec<TreeNode>,
198    /// Metadata
199    pub metadata: HashMap<String, String>,
200}
201
202/// Timeline event
203#[derive(Debug, Clone, Serialize, Deserialize)]
204pub struct TimelineEvent {
205    /// Event ID
206    pub id: String,
207    /// Event title
208    pub title: String,
209    /// Event description
210    pub description: Option<String>,
211    /// Timestamp
212    pub timestamp: chrono::DateTime<chrono::Utc>,
213    /// Duration (if applicable)
214    pub duration: Option<chrono::Duration>,
215    /// Category
216    pub category: Option<String>,
217}
218
219/// Visualization builder
220pub struct VisualizationBuilder {
221    spec: VisualizationSpec,
222}
223
224impl VisualizationBuilder {
225    /// Create a new visualization builder
226    pub fn new(viz_type: VisualizationType) -> Self {
227        Self {
228            spec: VisualizationSpec {
229                config: VisualizationConfig {
230                    viz_type,
231                    ..Default::default()
232                },
233                data: VisualizationData::Table {
234                    columns: vec![],
235                    rows: vec![],
236                },
237                rendering_hints: HashMap::new(),
238            },
239        }
240    }
241
242    /// Set title
243    pub fn title(mut self, title: String) -> Self {
244        self.spec.config.title = title;
245        self
246    }
247
248    /// Set dimensions
249    pub fn dimensions(mut self, width: String, height: String) -> Self {
250        self.spec.config.width = width;
251        self.spec.config.height = height;
252        self
253    }
254
255    /// Set color scheme
256    pub fn color_scheme(mut self, scheme: ColorScheme) -> Self {
257        self.spec.config.color_scheme = scheme;
258        self
259    }
260
261    /// Set interactive mode
262    pub fn interactive(mut self, interactive: bool) -> Self {
263        self.spec.config.interactive = interactive;
264        self
265    }
266
267    /// Add option
268    pub fn option<K: Into<String>, V: Serialize>(mut self, key: K, value: V) -> Self {
269        self.spec.config.options.insert(
270            key.into(),
271            serde_json::to_value(value).expect("serializable value should convert to JSON"),
272        );
273        self
274    }
275
276    /// Set table data
277    pub fn table_data(mut self, columns: Vec<String>, rows: Vec<Vec<String>>) -> Self {
278        self.spec.data = VisualizationData::Table { columns, rows };
279        self
280    }
281
282    /// Set chart data
283    pub fn chart_data(mut self, series: Vec<ChartSeries>) -> Self {
284        self.spec.data = VisualizationData::Chart { series };
285        self
286    }
287
288    /// Set network data
289    pub fn network_data(mut self, nodes: Vec<NetworkNode>, edges: Vec<NetworkEdge>) -> Self {
290        self.spec.data = VisualizationData::Network { nodes, edges };
291        self
292    }
293
294    /// Set tree data
295    pub fn tree_data(mut self, root: TreeNode) -> Self {
296        self.spec.data = VisualizationData::Tree { root };
297        self
298    }
299
300    /// Set timeline data
301    pub fn timeline_data(mut self, events: Vec<TimelineEvent>) -> Self {
302        self.spec.data = VisualizationData::Timeline { events };
303        self
304    }
305
306    /// Set heatmap data
307    pub fn heatmap_data(
308        mut self,
309        data: Vec<Vec<f64>>,
310        x_labels: Vec<String>,
311        y_labels: Vec<String>,
312    ) -> Self {
313        self.spec.data = VisualizationData::Heatmap {
314            data,
315            x_labels,
316            y_labels,
317        };
318        self
319    }
320
321    /// Add rendering hint
322    pub fn hint<K: Into<String>, V: Into<String>>(mut self, key: K, value: V) -> Self {
323        self.spec.rendering_hints.insert(key.into(), value.into());
324        self
325    }
326
327    /// Build the visualization specification
328    pub fn build(self) -> VisualizationSpec {
329        self.spec
330    }
331}
332
333/// Visualization renderer (outputs various formats)
334pub struct VisualizationRenderer;
335
336impl VisualizationRenderer {
337    /// Render to JSON
338    pub fn to_json(spec: &VisualizationSpec) -> Result<String> {
339        Ok(serde_json::to_string_pretty(spec)?)
340    }
341
342    /// Render to Vega-Lite JSON (for web rendering)
343    pub fn to_vega_lite(spec: &VisualizationSpec) -> Result<String> {
344        debug!("Converting to Vega-Lite specification");
345
346        let vega_spec = match &spec.data {
347            VisualizationData::Chart { series } => {
348                // Convert chart to Vega-Lite spec
349                let mut data_values = Vec::new();
350                for s in series {
351                    for point in &s.data {
352                        data_values.push(serde_json::json!({
353                            "x": point.x,
354                            "y": point.y,
355                            "series": s.name,
356                        }));
357                    }
358                }
359
360                serde_json::json!({
361                    "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
362                    "title": spec.config.title,
363                    "width": 600,
364                    "height": 400,
365                    "data": {
366                        "values": data_values
367                    },
368                    "mark": "line",
369                    "encoding": {
370                        "x": {"field": "x", "type": "ordinal"},
371                        "y": {"field": "y", "type": "quantitative"},
372                        "color": {"field": "series", "type": "nominal"}
373                    }
374                })
375            }
376            _ => {
377                serde_json::json!({
378                    "error": "Visualization type not yet supported for Vega-Lite"
379                })
380            }
381        };
382
383        Ok(serde_json::to_string_pretty(&vega_spec)?)
384    }
385
386    /// Render to PlantUML (for diagrams)
387    pub fn to_plantuml(spec: &VisualizationSpec) -> Result<String> {
388        debug!("Converting to PlantUML");
389
390        match &spec.data {
391            VisualizationData::Network { nodes, edges } => {
392                let mut plantuml = String::from("@startuml\n");
393
394                // Add nodes
395                for node in nodes {
396                    plantuml.push_str(&format!("object {} {{\n", node.id));
397                    plantuml.push_str(&format!("  label = \"{}\"\n", node.label));
398                    plantuml.push_str("}\n");
399                }
400
401                // Add edges
402                for edge in edges {
403                    let arrow = if edge.directed { "-->" } else { "--" };
404                    if let Some(label) = &edge.label {
405                        plantuml.push_str(&format!(
406                            "{} {} {} : {}\n",
407                            edge.source, arrow, edge.target, label
408                        ));
409                    } else {
410                        plantuml.push_str(&format!("{} {} {}\n", edge.source, arrow, edge.target));
411                    }
412                }
413
414                plantuml.push_str("@enduml\n");
415                Ok(plantuml)
416            }
417            _ => Err(anyhow::anyhow!(
418                "PlantUML rendering only supported for network visualizations"
419            )),
420        }
421    }
422
423    /// Render to HTML table
424    pub fn to_html_table(spec: &VisualizationSpec) -> Result<String> {
425        match &spec.data {
426            VisualizationData::Table { columns, rows } => {
427                let mut html = String::from("<table>\n");
428
429                // Header
430                html.push_str("  <thead>\n    <tr>\n");
431                for col in columns {
432                    html.push_str(&format!("      <th>{}</th>\n", col));
433                }
434                html.push_str("    </tr>\n  </thead>\n");
435
436                // Body
437                html.push_str("  <tbody>\n");
438                for row in rows {
439                    html.push_str("    <tr>\n");
440                    for cell in row {
441                        html.push_str(&format!("      <td>{}</td>\n", cell));
442                    }
443                    html.push_str("    </tr>\n");
444                }
445                html.push_str("  </tbody>\n");
446
447                html.push_str("</table>");
448                Ok(html)
449            }
450            _ => Err(anyhow::anyhow!(
451                "HTML table rendering only supported for table visualizations"
452            )),
453        }
454    }
455
456    /// Render to Mermaid diagram
457    pub fn to_mermaid(spec: &VisualizationSpec) -> Result<String> {
458        match &spec.data {
459            VisualizationData::Network { nodes, edges } => {
460                let mut mermaid = String::from("graph TD\n");
461
462                // Add nodes with labels
463                for node in nodes {
464                    mermaid.push_str(&format!("  {}[\"{}\"]\n", node.id, node.label));
465                }
466
467                // Add edges
468                for edge in edges {
469                    if let Some(label) = &edge.label {
470                        mermaid.push_str(&format!(
471                            "  {} -->|{}| {}\n",
472                            edge.source, label, edge.target
473                        ));
474                    } else {
475                        mermaid.push_str(&format!("  {} --> {}\n", edge.source, edge.target));
476                    }
477                }
478
479                Ok(mermaid)
480            }
481            VisualizationData::Tree { root } => {
482                let mut mermaid = String::from("graph TD\n");
483
484                fn add_tree_node(mermaid: &mut String, node: &TreeNode, parent_id: Option<&str>) {
485                    mermaid.push_str(&format!("  {}[\"{}\"]\n", node.id, node.label));
486
487                    if let Some(parent) = parent_id {
488                        mermaid.push_str(&format!("  {} --> {}\n", parent, node.id));
489                    }
490
491                    for child in &node.children {
492                        add_tree_node(mermaid, child, Some(&node.id));
493                    }
494                }
495
496                add_tree_node(&mut mermaid, root, None);
497
498                Ok(mermaid)
499            }
500            _ => Err(anyhow::anyhow!(
501                "Mermaid rendering supported for network and tree visualizations"
502            )),
503        }
504    }
505}
506
507/// Helper functions for common visualizations
508pub mod helpers {
509    use super::*;
510
511    /// Create a simple bar chart
512    pub fn bar_chart(title: String, data: Vec<(String, f64)>) -> VisualizationSpec {
513        let series = ChartSeries {
514            name: "Values".to_string(),
515            data: data
516                .into_iter()
517                .map(|(x, y)| DataPoint {
518                    x,
519                    y,
520                    label: None,
521                    metadata: HashMap::new(),
522                })
523                .collect(),
524            color: None,
525        };
526
527        VisualizationBuilder::new(VisualizationType::BarChart)
528            .title(title)
529            .chart_data(vec![series])
530            .build()
531    }
532
533    /// Create a simple network graph
534    pub fn network_graph(
535        title: String,
536        nodes: Vec<(String, String)>,
537        edges: Vec<(String, String, Option<String>)>,
538    ) -> VisualizationSpec {
539        let network_nodes: Vec<NetworkNode> = nodes
540            .into_iter()
541            .map(|(id, label)| NetworkNode {
542                id,
543                label,
544                node_type: "default".to_string(),
545                size: 1.0,
546                color: None,
547                position: None,
548                metadata: HashMap::new(),
549            })
550            .collect();
551
552        let network_edges: Vec<NetworkEdge> = edges
553            .into_iter()
554            .map(|(source, target, label)| NetworkEdge {
555                source,
556                target,
557                label,
558                weight: 1.0,
559                color: None,
560                directed: true,
561            })
562            .collect();
563
564        VisualizationBuilder::new(VisualizationType::Network)
565            .title(title)
566            .network_data(network_nodes, network_edges)
567            .build()
568    }
569
570    /// Create a simple timeline
571    pub fn timeline(title: String, events: Vec<TimelineEvent>) -> VisualizationSpec {
572        VisualizationBuilder::new(VisualizationType::Timeline)
573            .title(title)
574            .timeline_data(events)
575            .build()
576    }
577}
578
579#[cfg(test)]
580mod tests {
581    use super::*;
582
583    #[test]
584    fn test_visualization_builder() {
585        let spec = VisualizationBuilder::new(VisualizationType::Table)
586            .title("Test Table".to_string())
587            .table_data(
588                vec!["Col1".to_string(), "Col2".to_string()],
589                vec![
590                    vec!["A".to_string(), "B".to_string()],
591                    vec!["C".to_string(), "D".to_string()],
592                ],
593            )
594            .build();
595
596        assert_eq!(spec.config.title, "Test Table");
597        match spec.data {
598            VisualizationData::Table { columns, rows } => {
599                assert_eq!(columns.len(), 2);
600                assert_eq!(rows.len(), 2);
601            }
602            _ => panic!("Expected table data"),
603        }
604    }
605
606    #[test]
607    fn test_bar_chart_helper() {
608        let spec = helpers::bar_chart(
609            "Sales".to_string(),
610            vec![
611                ("Q1".to_string(), 100.0),
612                ("Q2".to_string(), 150.0),
613                ("Q3".to_string(), 120.0),
614            ],
615        );
616
617        assert_eq!(spec.config.viz_type, VisualizationType::BarChart);
618        assert_eq!(spec.config.title, "Sales");
619    }
620
621    #[test]
622    fn test_network_graph_helper() {
623        let spec = helpers::network_graph(
624            "Knowledge Graph".to_string(),
625            vec![("A".to_string(), "Node A".to_string())],
626            vec![(
627                "A".to_string(),
628                "B".to_string(),
629                Some("relates".to_string()),
630            )],
631        );
632
633        assert_eq!(spec.config.viz_type, VisualizationType::Network);
634    }
635
636    #[test]
637    fn test_html_table_rendering() {
638        let spec = VisualizationBuilder::new(VisualizationType::Table)
639            .table_data(
640                vec!["Name".to_string(), "Value".to_string()],
641                vec![vec!["Test".to_string(), "123".to_string()]],
642            )
643            .build();
644
645        let html = VisualizationRenderer::to_html_table(&spec).expect("should succeed");
646        assert!(html.contains("<table>"));
647        assert!(html.contains("<th>Name</th>"));
648        assert!(html.contains("<td>Test</td>"));
649    }
650}