1use std::env;
2
3use plotly::{
4 Layout,
5 Plot as Plotly,
6 Trace,
7};
8
9use serde::Serialize;
10
11pub trait Plot {
13 fn plot(&self);
14
15 fn write_html(&self, path: impl Into<String>);
16
17 fn to_json(&self) -> Result<String, serde_json::Error>;
18
19 fn to_html(&self) -> String;
20
21 fn to_inline_html(&self, plot_div_id: Option<&str>) -> String;
22
23 }
31
32pub(crate) trait PlotHelper {
34 fn get_layout(&self) -> &Layout;
35 fn get_traces(&self) -> &Vec<Box<dyn Trace + 'static>>;
36
37 }
44
45impl<T> Plot for T
47where
48 T: PlotHelper + Serialize + Clone,
49{
50 fn plot(&self) {
51 let mut plot = Plotly::new();
52 plot.set_layout(self.get_layout().to_owned());
53 plot.add_traces(self.get_traces().to_owned());
54
55 match env::var("EVCXR_IS_RUNTIME") {
56 Ok(_) => plot.notebook_display(),
57 _ => plot.show(),
58 }
59 }
60
61 fn write_html(&self, path: impl Into<String>) {
62 let mut plot = Plotly::new();
63 plot.set_layout(self.get_layout().to_owned());
64 plot.add_traces(self.get_traces().to_owned());
65 plot.write_html(path.into());
66 }
67
68 fn to_json(&self) -> Result<String, serde_json::Error> {
69 serde_json::to_string(self)
70 }
71
72 fn to_html(&self) -> String {
73 let mut plot = Plotly::new();
74 plot.set_layout(self.get_layout().to_owned());
75 plot.add_traces(self.get_traces().to_owned());
76 plot.to_html()
77 }
78
79 fn to_inline_html(&self, plot_div_id: Option<&str>) -> String {
80 let mut plot = Plotly::new();
81 plot.set_layout(self.get_layout().to_owned());
82 plot.add_traces(self.get_traces().to_owned());
83 plot.to_inline_html(plot_div_id)
84 }
85
86 }