diff --git a/examples/jotdown_wasm/demo.html b/examples/jotdown_wasm/demo.html index 60f0308..1cd918e 100644 --- a/examples/jotdown_wasm/demo.html +++ b/examples/jotdown_wasm/demo.html @@ -3,6 +3,7 @@ import init, { jotdown_render, jotdown_parse, + jotdown_parse_indent, } from './pkg/jotdown_wasm.js'; await init(); @@ -17,6 +18,9 @@ } else if (fmt.value == "events") { output.classList.add("verbatim") output.innerText = jotdown_parse(input.innerText); + } else if (fmt.value == "events_indent") { + output.classList.add("verbatim") + output.innerText = jotdown_parse_indent(input.innerText); } else if (fmt.value == "preview") { output.classList.remove("verbatim") output.innerHTML = jotdown_render(input.innerText); @@ -36,6 +40,7 @@ +
diff --git a/examples/jotdown_wasm/src/lib.rs b/examples/jotdown_wasm/src/lib.rs index ec1f63a..ba72c80 100644 --- a/examples/jotdown_wasm/src/lib.rs +++ b/examples/jotdown_wasm/src/lib.rs @@ -1,6 +1,7 @@ use wasm_bindgen::prelude::*; use jotdown::Render; +use std::fmt::Write; #[must_use] #[wasm_bindgen] @@ -20,3 +21,44 @@ pub fn jotdown_parse(djot: &str) -> String { .map(|e| format!("{:?}\n", e)) .collect() } + +#[must_use] +#[wasm_bindgen] +pub fn jotdown_parse_indent(djot: &str) -> String { + let mut level = 0; + let mut out = String::new(); + for e in jotdown::Parser::new(djot) { + if !matches!(e, jotdown::Event::End(..)) { + // use non-breaking space for indent because normal spaces gets squeezed by browser + let nbsp = '\u{00a0}'; + (0..4 * level).for_each(|_| out.push(nbsp)); + } + match e { + jotdown::Event::Start(c, attrs) => { + level += 1; + if c.is_block() { + out.push('['); + } else { + out.push('('); + } + out.write_fmt(format_args!("{:?}", c)).unwrap(); + if c.is_block() { + out.push(']'); + } else { + out.push(')'); + } + if !attrs.is_empty() { + out.write_fmt(format_args!(" {:?}", attrs)).unwrap(); + } + out.push('\n'); + } + jotdown::Event::End(..) => { + level -= 1; + } + e => { + out.write_fmt(format_args!("{:?}\n", e)).unwrap(); + } + }; + } + out +}