use comrak::options::Plugins;
use comrak::{Options, markdown_to_html_with_plugins};
use crate::highlight::Highlighter;
use crate::markup::split_front_matter;
use crate::widgets::Widgets;
pub(crate) fn options() -> Options<'static> {
let mut options = Options::default();
options.extension.table = true;
options.extension.strikethrough = true;
options.extension.autolink = true;
options.extension.tasklist = true;
options.extension.footnotes = true;
options.extension.header_id_prefix = Some(String::new());
options.extension.front_matter_delimiter = Some("---".to_string());
options.render.r#unsafe = true;
options.render.github_pre_lang = true;
options
}
pub const FRAME_IDS: [&str; 8] = [
"devpage-page",
"devpage-nav",
"devpage-sidebar",
"devpage-navbar",
"devpage-corner",
"devpage-comments",
"devpage-comments-toggle",
"devpage-comment-mode",
];
pub fn markdown(source: &str) -> String {
let mut plugins = Plugins::default();
plugins.render.codefence_syntax_highlighter = Some(&Highlighter);
let mut html = markdown_to_html_with_plugins(source, &options(), &plugins)
.replace("<table>", "<div class=\"table-scroll\"><table>")
.replace("</table>", "</table></div>");
for id in FRAME_IDS {
if html.contains(&format!("id=\"{id}\"")) {
html = html
.replace(&format!("id=\"{id}\""), &format!("id=\"{id}-heading\""))
.replace(
&format!("href=\"#{id}\""),
&format!("href=\"#{id}-heading\""),
);
}
}
crate::diagrams::draw_fences(&embed_designs(&html))
}
pub fn markdown_in(widgets: &Widgets, source: &str) -> String {
markdown(&crate::widgets::expand(
source,
widgets.names(),
&mut Vec::new(),
))
}
fn embed_designs(html: &str) -> String {
let mut out = String::new();
let lower = html.to_ascii_lowercase();
let mut from = 0;
while let Some(at) = lower[from..].find("<img").map(|at| from + at) {
out.push_str(&html[from..at]);
let rest = &html[at..];
if !rest[4..].starts_with(|c: char| c.is_ascii_whitespace()) {
out.push_str(&rest[..4]);
from = at + 4;
continue;
}
let end = tag_end(rest);
let tag = &rest[..end];
let attributes = attributes(&tag[4..]);
let attribute = |name: &str| {
attributes
.iter()
.find(|(n, _)| n.eq_ignore_ascii_case(name))
.map(|(_, value)| value.as_str())
};
match attribute("src") {
Some(src)
if src
.split(['?', '#'])
.next()
.is_some_and(|p| p.ends_with(".design")) =>
{
out.push_str(&format!(
"<span class=\"design-embed\"><canvas class=\"design\" src=\"{}\" role=\"img\" aria-label=\"{}\"></canvas>{}</span>",
src.replace('"', """),
attribute("alt").unwrap_or_default().replace('"', """),
crate::navbar::design_theme_toggle()
));
}
_ => out.push_str(tag),
}
from = at + end;
}
out.push_str(&html[from..]);
out
}
fn attributes(tag: &str) -> Vec<(String, String)> {
let mut attributes = Vec::new();
let mut chars = tag.char_indices().peekable();
loop {
while chars
.next_if(|(_, c)| c.is_ascii_whitespace() || *c == '/')
.is_some()
{}
let Some(&(start, c)) = chars.peek() else {
break;
};
if c == '>' {
break;
}
let mut end = start;
while let Some((i, c)) =
chars.next_if(|(_, c)| !c.is_ascii_whitespace() && !matches!(c, '=' | '>' | '/'))
{
end = i + c.len_utf8();
}
let name = tag[start..end].to_string();
while chars.next_if(|(_, c)| c.is_ascii_whitespace()).is_some() {}
let mut value = String::new();
if chars.next_if(|(_, c)| *c == '=').is_some() {
while chars.next_if(|(_, c)| c.is_ascii_whitespace()).is_some() {}
match chars.peek() {
Some(&(_, quote @ ('"' | '\''))) => {
chars.next();
for (_, c) in chars.by_ref() {
if c == quote {
break;
}
value.push(c);
}
}
_ => {
while let Some((_, c)) =
chars.next_if(|(_, c)| !c.is_ascii_whitespace() && *c != '>')
{
value.push(c);
}
}
}
}
if name.is_empty() {
chars.next();
continue;
}
attributes.push((name, value));
}
attributes
}
fn tag_end(html: &str) -> usize {
let mut quote = None;
for (i, c) in html.char_indices() {
match (quote, c) {
(None, '"' | '\'') => quote = Some(c),
(Some(q), c) if c == q => quote = None,
(None, '>') => return i + 1,
_ => {}
}
}
html.len()
}
pub fn front_matter(source: &str) -> Option<&str> {
split_front_matter(source).map(|(yaml, _)| yaml)
}