Skip to main content

mdbook_plotly/
code_handler.rs

1pub mod color;
2pub(crate) mod eval;
3pub(crate) mod map;
4pub mod parse_context;
5pub mod plot_obj_parser;
6pub mod until;
7
8use crate::preprocessor::config::{MapEvalConfig, PlotlyInputType};
9use anyhow::Result;
10use plotly::Plot;
11use serde_json::Value;
12
13pub fn handle(
14    raw_code: String,
15    input_type: &PlotlyInputType,
16    map_eval: &MapEvalConfig,
17) -> Result<Plot> {
18    let result = match input_type {
19        PlotlyInputType::JSONInput => handle_json_input(raw_code, map_eval)?,
20        PlotlyInputType::TOMLInput => handle_toml_input(raw_code, map_eval)?,
21    };
22    Ok(result)
23}
24
25/// `Plot` does not implement `Deserialize`, so this routine is only an
26/// unofficial best-effort translation.
27///
28/// Do not be surprised if the output of `Plot::serialize` cannot be
29/// round-tripped through this function.
30///
31/// In addition, fields that cannot be translated are silently dropped.
32pub fn handle_json_input(raw_code: String, map_eval: &MapEvalConfig) -> Result<Plot> {
33    // Use Json5 to provide more flexible JSON.
34    let mut value: Value = json5::from_str(&raw_code)?;
35    plot_obj_parser::parse(&mut value, map_eval)
36}
37
38pub fn handle_toml_input(raw_code: String, map_eval: &MapEvalConfig) -> Result<Plot> {
39    let toml_value: toml::Value = toml::from_str(&raw_code)?;
40    let mut value = serde_json::to_value(toml_value)?;
41    plot_obj_parser::parse(&mut value, map_eval)
42}