use crate::model::Span;
use crate::render::markdown::inline::merge_runs;
use crate::render::notes::{Segment, segments};
pub(crate) trait RunMarkup {
fn styled(&self, text: &str, style: u8) -> String;
fn link(&self, href: &str, body: &str) -> String;
fn note(&self, call: &Span) -> String;
fn line_break(&self) -> Option<&'static str> {
None
}
}
pub(crate) fn runs(markup: &impl RunMarkup, spans: &[Span]) -> String {
let mut out = String::new();
for segment in segments(spans) {
match segment {
Segment::Text(spans) => {
let line_break = markup.line_break();
for (text, style, href) in merge_runs(spans, line_break.is_some()) {
let body = match line_break {
Some(line_break) => text
.split('\n')
.map(|line| markup.styled(line, style))
.collect::<Vec<_>>()
.join(line_break),
None => markup.styled(&text, style),
};
match href.as_deref().filter(|_| !body.trim().is_empty()) {
Some(href) => {
let lead = &body[..body.len() - body.trim_start().len()];
let trail = &body[body.trim_end().len()..];
out.push_str(&format!("{lead}{}{trail}", markup.link(href, body.trim())));
}
None => out.push_str(&body),
}
}
}
Segment::Note(call) => out.push_str(&markup.note(call)),
}
}
out
}
pub(crate) fn trim_breaks<'a>(text: &'a str, line_break: &str) -> &'a str {
let mut text = text.trim();
while let Some(rest) = text.strip_prefix(line_break).or_else(|| text.strip_suffix(line_break)) {
text = rest.trim();
}
text
}
pub(crate) fn label_name(prefix: &str, anchor: &str, keep: &[char]) -> String {
let name: String = anchor
.chars()
.map(|ch| {
if ch.is_ascii_alphanumeric() || keep.contains(&ch) {
ch
} else {
'-'
}
})
.collect();
format!("{prefix}{name}")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn breaks_at_the_ends_are_trimmed() {
assert_eq!(trim_breaks(" <br>a<br>b <br><br> ", "<br>"), "a<br>b");
assert_eq!(trim_breaks("<br>", "<br>"), "");
}
}