Skip to main content

mdbook_plotly/
code_handler.rs

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