use crate::parse::{ParseOptions, parse};
use crate::tree::Node;
#[must_use]
pub fn html(text: &str) -> String {
markdown::to_html_with_options(text, &markdown::Options::gfm())
.unwrap_or_else(|message| message.to_string())
}
#[must_use]
pub fn text(text: &str, options: &ParseOptions) -> String {
let mut lines = Vec::new();
blocks(&parse(text, options).root.children, &mut lines);
lines.join("\n")
}
fn blocks(nodes: &[Node], lines: &mut Vec<String>) {
for node in nodes {
match node {
Node::Paragraph(_) | Node::Heading(_) | Node::ComponentLeaf(_) => {
push(lines, &inline_text(node.children()));
}
Node::Code(code) => code.value.lines().for_each(|line| push(lines, line)),
Node::Math(math) => math.value.lines().for_each(|line| push(lines, line)),
Node::Table(table) => {
for row in &table.children {
let cells: Vec<String> = row
.children()
.iter()
.map(|cell| inline_text(cell.children()))
.collect();
push(lines, &cells.join(" "));
}
}
Node::ComponentContainer(container) => {
blocks(&container.children, lines);
for slot in &container.slots {
blocks(&slot.children, lines);
}
}
Node::Blockquote(_)
| Node::List(_)
| Node::ListItem(_)
| Node::FootnoteDefinition(_)
| Node::ComponentSlot(_) => {
blocks(node.children(), lines);
}
_ => {}
}
}
}
fn inline_text(nodes: &[Node]) -> String {
let mut text = String::new();
inline(nodes, &mut text);
text
}
fn inline(nodes: &[Node], text: &mut String) {
for node in nodes {
match node {
Node::Text(literal) | Node::InlineCode(literal) | Node::InlineMath(literal) => {
text.push_str(&literal.value);
}
Node::Break(_) => text.push(' '),
Node::Image(image) => text.push_str(&image.alt),
Node::ImageReference(image) => text.push_str(&image.alt),
Node::WikiLink(link) => text.push_str(&link.label),
Node::Html(_) | Node::Interpolation(_) | Node::FootnoteReference(_) => {}
other => inline(other.children(), text),
}
}
}
fn push(lines: &mut Vec<String>, line: &str) {
let line = line.split_whitespace().collect::<Vec<_>>().join(" ");
if !line.is_empty() {
lines.push(line);
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn plain(document: &str) -> String {
text(document, &ParseOptions::default())
}
#[test]
fn component_lines_stay_one_line_of_text() {
let html = html(
"::: card {title=\"Setup\"}\nInside.\n::: /card\n\n| a |\n|---|\n| 1 |\n\n<script>x</script>\n",
);
assert!(
html.contains("<p>::: card {title="Setup"}\nInside.\n::: /card</p>"),
"{html}"
);
assert!(html.contains("<table>"), "GFM tables: {html}");
assert!(
html.contains("<script>"),
"raw HTML is escaped: {html}"
);
}
#[test]
fn syntax_markers_go() {
let document = "## A *very* **big** ~~day~~\n\n- one\n- [x] two\n 1. nested\n\n> [!NOTE]\n> Quoted\n\n| a | b |\n|---|---|\n| 1 | 2 |\n\n---\n";
assert_eq!(
plain(document),
"A very big day\none\ntwo\nnested\nQuoted\na b\n1 2"
);
}
#[test]
fn labels_stay_and_urls_go() {
let document = "[Rome](https://example.com \"title\"), , [ref][r] and <https://bare.example>\n\n[r]: https://example.org\n";
assert_eq!(plain(document), "Rome, a map, ref and https://bare.example");
let wiki = text(
"See [[Books|my books]] and [[Rome]].\n",
&ParseOptions {
metadata: Some(json!({"md": {"syntax": ["wiki-links"]}})),
},
);
assert_eq!(wiki, "See my books and Rome.");
}
#[test]
fn code_and_math_stay_as_text() {
let document =
"Use `npm i` and $x^2$.\n\n```mermaid\ngraph LR\n a --> b\n```\n\n$$\ny = 1\n$$\n";
assert_eq!(
plain(document),
"Use npm i and x^2.\ngraph LR\na --> b\ny = 1"
);
}
#[test]
fn components_give_their_fallback_and_definitions_nothing() {
let document = "::: card {title=\"Setup\"}\nInside.\n\n:: #footer\nThe end.\n::: /card\n\n:: chart[Pages read] {rows=x}\n\nA :badge[beta]{tone=info} release.\n\n```compmd component=note\nslots: [default]\n---\nHidden body\n```\n\n```compmd component=stars signature\nparams:\n value: number\n```\n";
assert_eq!(
plain(document),
"Inside.\nThe end.\nPages read\nA beta release."
);
}
#[test]
fn components_inside_containers_give_theirs_at_any_depth() {
let document = "::: row {gap=m}\n::: card\nFirst :badge[new]{tone=info} card.\n\n:: chart[Pages read] {rows=x}\n\n:: #footer\n::: stack\nDeep inside.\n::: /stack\n::: /card\n::: /row\n\n::: if {when=(md.input.on)}\nShown when on.\n:: #else\nShown when off.\n::: /if\n";
assert_eq!(
plain(document),
"First new card.\nPages read\nDeep inside.\nShown when on.\nShown when off."
);
}
#[test]
fn frontmatter_html_and_interpolations_show_nothing() {
let document = "---\ntitle: Notes\n---\n\n<div>\n\nHello {{md.doc.title}}, <b>you</b>.[^1]\n\n</div>\n\n[^1]: A note.\n";
assert_eq!(plain(document), "Hello , you.\nA note.");
}
#[test]
fn one_line_per_block() {
assert_eq!(
plain("First line\nsame paragraph \nhard break\n\nSecond\n"),
"First line same paragraph hard break\nSecond"
);
assert_eq!(plain(""), "");
}
}