jotdown_wasm: add output option for indented events

make events more readable, more resembling an AST
This commit is contained in:
Noah Hellman 2023-03-26 23:09:23 +02:00
parent f3732693c6
commit 0ef3681b1b
2 changed files with 47 additions and 0 deletions

View file

@ -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 @@
<option value="preview">preview</option>
<option value="html">html</option>
<option value="events">events</option>
<option value="events_indent">events (indented)</option>
</select>
</div>
<div id="panes" style="display:flex;height:100%;gap:1rem">

View file

@ -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
}