use leptos::prelude::*;
use markdoc::ast::Node;
use markdoc::ext::bundle::Bundle;
use markdoc::ext::variables::frontmatter_variables;
use markdoc::ext::{Frontmatter, ParseOptions};
use markdoc::renderers::html;
use markdoc::schema::Config;
use markdoc::schema::value::Value;
use markdoc::types::Result;
#[component]
pub fn Markdoc(
content: String,
#[prop(optional)]
config: Option<Config>,
#[prop(optional)]
options: Option<ParseOptions>,
) -> impl IntoView {
let config = config.unwrap_or_else(default_config);
let options = options.unwrap_or_else(default_options);
let html = move || render_page(&content, &options, &config);
view! {
<div inner_html=html()></div>
}
}
#[component]
pub fn MarkdocReactive(
content: ReadSignal<String>,
#[prop(optional)]
config: Option<Config>,
#[prop(optional)]
options: Option<ParseOptions>,
) -> impl IntoView {
let config = config.unwrap_or_else(default_config);
let options = options.unwrap_or_else(default_options);
let html = move || render_page(&content.get(), &options, &config);
view! {
<div inner_html=html()></div>
}
}
pub fn default_config() -> Config {
Bundle::builtin().config()
}
pub fn default_options() -> ParseOptions {
ParseOptions {
frontmatter: Frontmatter::Yaml,
..ParseOptions::default()
}
}
pub fn parse_markdown(content: &str) -> Result<Node> {
parse_markdown_with(content, &default_options())
}
pub fn parse_markdown_with(content: &str, options: &ParseOptions) -> Result<Node> {
markdoc::ext::parse(content, options)
}
pub fn transform_ast(node: &Node, config: &Config) -> Result<Value> {
if !node.attributes.contains_key("frontmatter") {
return markdoc::transform(node, config);
}
let mut config = config.clone();
frontmatter_variables(node).apply(&mut config);
markdoc::transform(node, &config)
}
pub fn render_to_html(value: &Value) -> Result<String> {
html::render(value)
}
fn render_page(content: &str, options: &ParseOptions, config: &Config) -> String {
let node = match parse_markdown_with(content, options) {
Ok(node) => node,
Err(e) => return error_div("Parse error", &e.to_string()),
};
if let Some(e) = node.errors.iter().find(|e| e.id == "frontmatter-invalid") {
return error_div("Parse error", &e.message);
}
let value = match transform_ast(&node, config) {
Ok(value) => value,
Err(e) => return error_div("Transform error", &e.to_string()),
};
match render_to_html(&value) {
Ok(html) => html,
Err(e) => error_div("Render error", &e.to_string()),
}
}
fn error_div(stage: &str, message: &str) -> String {
leptos::logging::error!("Failed to render markdown: {stage}: {message}");
format!(
"<div class=\"markdoc-error\">{stage}: {}</div>",
html::escape_html(message)
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_simple_markdown() {
let content = "# Hello World\n\nThis is a test.";
let result = parse_markdown(content);
assert!(result.is_ok());
}
fn html_for(source: &str, config: &Config) -> String {
let node = parse_markdown(source).expect("parses");
render_to_html(&transform_ast(&node, config).expect("transforms")).expect("renders")
}
#[test]
fn an_aliased_tag_renders_under_its_canonical_name() {
let html = html_for(
"{% notice type=\"warning\" %}\nBody.\n{% /notice %}\n",
&default_config(),
);
assert!(html.contains("<callout"), "expected <callout>: {html}");
assert!(
!html.contains("<notice"),
"alias leaked to the page: {html}"
);
}
#[test]
fn the_schema_supplies_attribute_defaults() {
let html = html_for("{% notice %}\nBody.\n{% /notice %}\n", &default_config());
assert!(html.contains("type=\"note\""), "no default applied: {html}");
}
#[test]
fn a_corpus_overlay_reaches_the_rendered_page() {
let overlay = r#"
[tags.advisory]
description = "Alias of callout"
alias_of = "callout"
"#;
let mut bundle = Bundle::builtin();
assert!(bundle.config().tags.get("advisory").is_none());
bundle.overlay(overlay).expect("overlay merges");
let config = bundle.config();
assert!(config.tags.get("advisory").is_some_and(Option::is_some));
let html = html_for("{% advisory %}\nBody.\n{% /advisory %}\n", &config);
assert!(
html.contains("<callout"),
"overlay alias not resolved: {html}"
);
assert!(
html.contains("type=\"note\""),
"overlay alias lost defaults: {html}"
);
}
#[test]
fn without_the_overlay_the_same_tag_renders_only_its_children() {
let html = html_for(
"{% advisory %}\nBody.\n{% /advisory %}\n",
&default_config(),
);
assert_eq!(html, "<article><p>Body.</p></article>");
}
#[test]
fn the_frontmatter_is_bound_as_markdoc_frontmatter() {
let source = "---\ntitle: Hello\n---\n# {% $markdoc.frontmatter.title %}\n";
assert_eq!(
html_for(source, &default_config()),
"<article><h1>Hello</h1></article>"
);
let node = parse_markdown_with(source, &ParseOptions::default()).expect("parses");
let value = transform_ast(&node, &default_config()).expect("transforms");
assert_eq!(
render_to_html(&value).expect("renders"),
"<article><h1></h1></article>"
);
}
#[test]
fn frontmatter_that_is_no_mapping_shows_as_a_parse_error() {
let page = render_page(
"---\njust text\n---\n# Title\n",
&default_options(),
&default_config(),
);
assert!(
page.starts_with("<div class=\"markdoc-error\">Parse error: "),
"{page}"
);
assert!(!page.contains("<h1>"), "{page}");
}
#[test]
fn an_error_message_is_escaped() {
assert_eq!(
error_div("Parse error", "<b>&</b>"),
"<div class=\"markdoc-error\">Parse error: <b>&</b></div>"
);
}
}