1use anyhow::Result;
7use serde::{Deserialize, Serialize};
8use std::collections::HashMap;
9use tracing::debug;
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
13pub enum VisualizationType {
14 Table,
16 BarChart,
18 LineChart,
20 PieChart,
22 Network,
24 Tree,
26 Timeline,
28 Heatmap,
30 GeoMap,
32 Custom,
34}
35
36#[derive(Debug, Clone, Serialize, Deserialize)]
38pub struct VisualizationConfig {
39 pub viz_type: VisualizationType,
41 pub title: String,
43 pub width: String,
45 pub height: String,
47 pub color_scheme: ColorScheme,
49 pub interactive: bool,
51 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
71pub enum ColorScheme {
72 Default,
74 Blue,
76 Green,
78 Red,
80 Purple,
82 Grayscale,
84 Rainbow,
86 Custom,
88}
89
90#[derive(Debug, Clone, Serialize, Deserialize)]
92pub struct DataPoint {
93 pub x: String,
95 pub y: f64,
97 pub label: Option<String>,
99 pub metadata: HashMap<String, String>,
101}
102
103#[derive(Debug, Clone, Serialize, Deserialize)]
105pub struct NetworkNode {
106 pub id: String,
108 pub label: String,
110 pub node_type: String,
112 pub size: f32,
114 pub color: Option<String>,
116 pub position: Option<(f64, f64)>,
118 pub metadata: HashMap<String, String>,
120}
121
122#[derive(Debug, Clone, Serialize, Deserialize)]
124pub struct NetworkEdge {
125 pub source: String,
127 pub target: String,
129 pub label: Option<String>,
131 pub weight: f32,
133 pub color: Option<String>,
135 pub directed: bool,
137}
138
139#[derive(Debug, Clone, Serialize, Deserialize)]
141pub struct VisualizationSpec {
142 pub config: VisualizationConfig,
144 pub data: VisualizationData,
146 pub rendering_hints: HashMap<String, String>,
148}
149
150#[derive(Debug, Clone, Serialize, Deserialize)]
152#[serde(tag = "type")]
153pub enum VisualizationData {
154 Table {
156 columns: Vec<String>,
157 rows: Vec<Vec<String>>,
158 },
159 Chart { series: Vec<ChartSeries> },
161 Network {
163 nodes: Vec<NetworkNode>,
164 edges: Vec<NetworkEdge>,
165 },
166 Tree { root: TreeNode },
168 Timeline { events: Vec<TimelineEvent> },
170 Heatmap {
172 data: Vec<Vec<f64>>,
173 x_labels: Vec<String>,
174 y_labels: Vec<String>,
175 },
176}
177
178#[derive(Debug, Clone, Serialize, Deserialize)]
180pub struct ChartSeries {
181 pub name: String,
183 pub data: Vec<DataPoint>,
185 pub color: Option<String>,
187}
188
189#[derive(Debug, Clone, Serialize, Deserialize)]
191pub struct TreeNode {
192 pub id: String,
194 pub label: String,
196 pub children: Vec<TreeNode>,
198 pub metadata: HashMap<String, String>,
200}
201
202#[derive(Debug, Clone, Serialize, Deserialize)]
204pub struct TimelineEvent {
205 pub id: String,
207 pub title: String,
209 pub description: Option<String>,
211 pub timestamp: chrono::DateTime<chrono::Utc>,
213 pub duration: Option<chrono::Duration>,
215 pub category: Option<String>,
217}
218
219pub struct VisualizationBuilder {
221 spec: VisualizationSpec,
222}
223
224impl VisualizationBuilder {
225 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 pub fn title(mut self, title: String) -> Self {
244 self.spec.config.title = title;
245 self
246 }
247
248 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 pub fn color_scheme(mut self, scheme: ColorScheme) -> Self {
257 self.spec.config.color_scheme = scheme;
258 self
259 }
260
261 pub fn interactive(mut self, interactive: bool) -> Self {
263 self.spec.config.interactive = interactive;
264 self
265 }
266
267 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 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 pub fn chart_data(mut self, series: Vec<ChartSeries>) -> Self {
284 self.spec.data = VisualizationData::Chart { series };
285 self
286 }
287
288 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 pub fn tree_data(mut self, root: TreeNode) -> Self {
296 self.spec.data = VisualizationData::Tree { root };
297 self
298 }
299
300 pub fn timeline_data(mut self, events: Vec<TimelineEvent>) -> Self {
302 self.spec.data = VisualizationData::Timeline { events };
303 self
304 }
305
306 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 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 pub fn build(self) -> VisualizationSpec {
329 self.spec
330 }
331}
332
333pub struct VisualizationRenderer;
335
336impl VisualizationRenderer {
337 pub fn to_json(spec: &VisualizationSpec) -> Result<String> {
339 Ok(serde_json::to_string_pretty(spec)?)
340 }
341
342 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 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 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 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 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 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 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 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 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 for node in nodes {
464 mermaid.push_str(&format!(" {}[\"{}\"]\n", node.id, node.label));
465 }
466
467 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
507pub mod helpers {
509 use super::*;
510
511 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 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 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}