use indexmap::IndexMap;
use markdoc::ast::Node;
use markdoc::next::compare::ValidateRecord;
use markdoc::next::index;
use markdoc::next::renderers::html as html_renderer;
use markdoc::next::schema::{Config, Partial, Value};
use markdoc::types::RenderableTreeNode;
use std::cell::RefCell;
use std::sync::Arc;
thread_local! {
static EXACT_VARIABLES: RefCell<Option<Value>> = const { RefCell::new(None) };
}
pub fn set_exact_variables(variables: Option<Value>) {
EXACT_VARIABLES.with(|v| *v.borrow_mut() = variables);
}
fn config_from_json(config: &serde_json::Value) -> Result<Config, String> {
let mut config = Config::from_json(config)?;
if config.variables.is_some()
&& let Some(exact) = EXACT_VARIABLES.with(|v| v.borrow().clone())
{
config.variables = Some(markdoc::next::schema::Variables::Value(exact));
}
Ok(config)
}
pub fn transform(
ast: &Node,
config: &serde_json::Value,
partials: &IndexMap<String, Node>,
) -> Result<Value, String> {
let mut config = config_from_json(config)?;
config.partials_null = false;
config.partials = Some(
partials
.iter()
.map(|(name, node)| (name.clone(), Partial::Node(Arc::new(node.clone()))))
.collect(),
);
index::transform(ast, &config).map_err(|e| index::thrown(&e).to_owned())
}
pub fn validate(ast: &Node, config: &serde_json::Value) -> Result<Vec<ValidateRecord>, String> {
let config = config_from_json(config)?;
let errors = index::validate(ast, &config).map_err(|e| index::thrown(&e).to_owned())?;
Ok(errors
.into_iter()
.map(|e| ValidateRecord {
node_type: e.node_type.to_string(),
lines: e.lines,
location: e.location.map(|l| l.to_json()),
error: e.error,
})
.collect())
}
pub fn html(tree: &Value) -> Result<String, String> {
html_renderer::render(tree).map_err(|e| index::thrown(&e).to_owned())
}
pub fn html_tree(tree: &RenderableTreeNode) -> Result<String, String> {
html_renderer::render_tree(tree).map_err(|e| index::thrown(&e).to_owned())
}