use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::{Arc, LazyLock, Mutex, PoisonError};
use comrak::nodes::{Node, NodeHtmlBlock, NodeValue};
use comrak::{Arena, Options, format_html, parse_document};
use regex::{Captures, Regex};
use serde::Serialize;
use serde_json::{Map, Value};
use crate::conditionals;
use crate::config::{HtmlInput, MarkdownSettings};
use crate::support;
use crate::{Error, yaml};
static FRONTMATTER: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"(?s)\A---\r?\n(.*?)\r?\n---(?:\r?\n|\z)(.*)\z").expect("a valid pattern"));
static HEADING: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"(?is)<h2(\s[^>]*)?>(.*?)</h2>|<h3(\s[^>]*)?>(.*?)</h3>").expect("a valid pattern"));
static TAGS: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?s)<[^>]*>").expect("a valid pattern"));
static EXISTING_ID: LazyLock<Regex> = LazyLock::new(|| Regex::new(r#"\sid="([^"]+)""#).expect("a valid pattern"));
static ENTITY: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"&(#[0-9]+|#[xX][0-9a-fA-F]+|[A-Za-z][A-Za-z0-9]*);").expect("a valid pattern"));
static EXTERNAL: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"^(?:[A-Za-z][A-Za-z0-9+.-]*:)?//([^/?#]*)").expect("a valid pattern"));
static EXTERNAL_LINK: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"<!--larablog:external--><a href=").expect("a valid pattern"));
static DISALLOWED: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r"(?i)<(/?(?:title|textarea|style|xmp|iframe|noembed|noframes|script|plaintext))([\s/>]|$)")
.expect("a valid pattern")
});
static UNSAFE_URL: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"(?i)^\s*(?:javascript|vbscript|file|data):").expect("a valid pattern"));
static TASK_CHECKBOX: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r#"<input type="checkbox"((?: checked="")?) disabled="" />"#).expect("a valid pattern")
});
static OPENING_NEWLINE: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"(<!--larablog:if-published:[A-Za-z0-9_.-]+:[01]-->)\n").expect("a valid pattern"));
const EXTERNAL_MARK: &str = "<!--larablog:external-->";
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Heading {
pub level: u8,
pub id: String,
pub text: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Rendered {
pub html: String,
pub headings: Vec<Heading>,
}
type Cached = ((u64, u64), Arc<Rendered>);
pub struct Markdown {
cache: Mutex<HashMap<PathBuf, Cached>>,
}
impl Default for Markdown {
fn default() -> Self {
Self::new()
}
}
impl Markdown {
pub fn new() -> Self {
Self {
cache: Mutex::new(HashMap::new()),
}
}
pub fn split(content: &str) -> Result<(Map<String, Value>, String), Error> {
let content = content.strip_prefix('\u{feff}').unwrap_or(content);
let Some(found) = FRONTMATTER.captures(content) else {
return Ok((Map::new(), content.to_owned()));
};
let meta = yaml::parse(&found[1])
.map_err(|message| Error::InvalidPost(format!("The frontmatter is not valid YAML: {message}")))?;
Ok((
match meta {
Value::Object(map) => map,
_ => Map::new(),
},
found[2].to_owned(),
))
}
pub fn render(&self, file: &Path, caching: bool) -> Result<Arc<Rendered>, Error> {
let signature = signature(file);
if caching {
let cache = self.cache.lock().unwrap_or_else(PoisonError::into_inner);
if let Some((cached, rendered)) = cache.get(file)
&& *cached == signature
{
return Ok(Arc::clone(rendered));
}
}
let content = std::fs::read_to_string(file).map_err(|error| Error::Io(file.to_path_buf(), error))?;
let (_, body) = Self::split(&content)?;
let config = laravel::config();
let rendered = Arc::new(Self::convert(
&body,
&config.section::<crate::LarablogConfig>().markdown,
&config.app.url,
));
if caching {
self.cache
.lock()
.unwrap_or_else(PoisonError::into_inner)
.insert(file.to_path_buf(), (signature, Arc::clone(&rendered)));
}
Ok(rendered)
}
pub fn convert(markdown: &str, settings: &MarkdownSettings, app_url: &str) -> Rendered {
anchor(&to_html(markdown, settings, app_url))
}
}
fn signature(file: &Path) -> (u64, u64) {
std::fs::metadata(file).map_or((0, 0), |metadata| {
let modified = metadata
.modified()
.ok()
.and_then(|time| time.duration_since(std::time::UNIX_EPOCH).ok())
.map_or(0, |duration| u64::try_from(duration.as_nanos()).unwrap_or(0));
(modified, metadata.len())
})
}
fn options(settings: &MarkdownSettings) -> Options<'static> {
let mut options = Options::default();
options.extension.strikethrough = true;
options.extension.table = true;
options.extension.autolink = true;
options.extension.tasklist = true;
options.render.r#unsafe = settings.html_input == HtmlInput::Allow;
options.render.escape = settings.html_input == HtmlInput::Escape;
options
}
fn to_html(markdown: &str, settings: &MarkdownSettings, app_url: &str) -> String {
let options = options(settings);
let arena = Arena::new();
let source = conditionals::rewrite(markdown);
let root = parse_document(&arena, &source, &options);
let app_host = host_of(app_url);
for node in root.descendants() {
let mut data = node.data_mut();
if let NodeValue::HtmlBlock(block) = &data.value
&& is_marker(block.literal.trim())
{
let literal = block.literal.trim().to_owned();
data.value = NodeValue::Raw(literal);
} else if let NodeValue::HtmlBlock(NodeHtmlBlock { literal, .. }) | NodeValue::HtmlInline(literal) =
&mut data.value
{
*literal = DISALLOWED.replace_all(literal, "<$1$2").into_owned();
} else if !settings.allow_unsafe_links
&& let NodeValue::Link(target) | NodeValue::Image(target) = &mut data.value
&& UNSAFE_URL.is_match(&target.url)
{
target.url.clear();
}
}
hoist_list_items(&arena, root);
if settings.external_links {
mark_external_links(&arena, root, app_host.as_deref());
}
let mut html = String::new();
format_html(root, &options, &mut html).expect("writing to a String does not fail");
if settings.external_links {
html = EXTERNAL_LINK
.replace_all(&html, r#"<a rel="noopener noreferrer" target="_blank" href="#)
.into_owned();
}
let html = TASK_CHECKBOX.replace_all(&html, r#"<input$1 disabled="" type="checkbox">"#);
OPENING_NEWLINE
.replace_all(&html, "$1")
.replace("\n<!--larablog:endif-->", "<!--larablog:endif-->")
}
fn is_marker(text: &str) -> bool {
text == conditionals::ENDIF || (text.starts_with("<!--larablog:if-published:") && text.ends_with("-->"))
}
fn marker_kind(node: Node<'_>) -> Option<bool> {
match &node.data().value {
NodeValue::Raw(text) if text == conditionals::ENDIF => Some(false),
NodeValue::Raw(text) if text.starts_with("<!--larablog:if-published:") => Some(true),
_ => None,
}
}
fn keep_paragraphs<'a>(arena: &'a Arena<'a>, item: Node<'a>, everything: bool) {
let tight = item
.parent()
.is_some_and(|list| matches!(&list.data().value, NodeValue::List(list) if list.tight));
if !tight {
return;
}
let mut depth = i32::from(everything);
for child in item.children().collect::<Vec<_>>() {
match marker_kind(child) {
Some(true) => depth += 1,
Some(false) => depth -= 1,
None => {}
}
if depth > 0 && matches!(child.data().value, NodeValue::Paragraph) {
child.prepend(arena.alloc(NodeValue::Raw("<p>".to_owned()).into()));
child.append(arena.alloc(NodeValue::Raw("</p>".to_owned()).into()));
}
}
}
fn hoist_list_items<'a>(arena: &'a Arena<'a>, root: Node<'a>) {
let items: Vec<Node<'a>> = root
.descendants()
.filter(|node| matches!(node.data().value, NodeValue::Item(_)))
.collect();
for item in items {
let children: Vec<Node<'a>> = item.children().collect();
let (Some(first), Some(last)) = (children.first(), children.last()) else {
continue;
};
if children.len() < 2 || marker_kind(first) != Some(true) || marker_kind(last) != Some(false) {
keep_paragraphs(arena, item, false);
continue;
}
let mut depth = 0_i32;
let mut sole = true;
for (index, child) in children.iter().enumerate() {
match marker_kind(child) {
Some(true) => depth += 1,
Some(false) => depth -= 1,
None => {}
}
if depth == 0 && index + 1 < children.len() {
sole = false;
break;
}
}
if !sole || depth != 0 {
keep_paragraphs(arena, item, false);
continue;
}
let opening = match &first.data().value {
NodeValue::Raw(text) => text.clone(),
_ => continue,
};
first.detach();
last.detach();
keep_paragraphs(arena, item, true);
item.insert_before(arena.alloc(NodeValue::Raw(opening).into()));
item.insert_after(arena.alloc(NodeValue::Raw(conditionals::ENDIF.to_owned()).into()));
}
}
fn host_of(url: &str) -> Option<String> {
EXTERNAL.captures(url).map(|found| authority_host(&found[1]))
}
fn authority_host(authority: &str) -> String {
let without_user = authority.rsplit('@').next().unwrap_or(authority);
let host = if without_user.starts_with('[') {
without_user.split(']').next().unwrap_or(without_user)
} else {
without_user.split(':').next().unwrap_or(without_user)
};
host.to_ascii_lowercase()
}
fn mark_external_links<'a>(arena: &'a Arena<'a>, root: Node<'a>, internal: Option<&str>) {
let links: Vec<Node<'a>> = root
.descendants()
.filter(|node| matches!(node.data().value, NodeValue::Link(_)))
.collect();
for link in links {
let external = match &link.data().value {
NodeValue::Link(target) => EXTERNAL
.captures(&target.url)
.map(|found| authority_host(&found[1]))
.is_some_and(|host| Some(host.as_str()) != internal),
_ => false,
};
if external {
link.insert_before(arena.alloc(NodeValue::Raw(EXTERNAL_MARK.to_owned()).into()));
}
}
}
fn anchor(html: &str) -> Rendered {
let mut headings: Vec<Heading> = Vec::new();
let mut seen: HashMap<String, ()> = HashMap::new();
let anchored = HEADING.replace_all(html, |found: &Captures<'_>| {
let (level, attributes, inner) = match found.get(2) {
Some(inner) => (2, found.get(1).map_or("", |m| m.as_str()), inner.as_str()),
None => (
3,
found.get(3).map_or("", |m| m.as_str()),
found.get(4).map_or("", |m| m.as_str()),
),
};
let text = decode_entities(&TAGS.replace_all(inner, "")).trim().to_owned();
let mut attributes = attributes.to_owned();
let id = if let Some(existing) = EXISTING_ID.captures(&attributes) {
existing[1].to_owned()
} else {
let base = {
let slug = support::slug(&text);
if slug.is_empty() { "section".to_owned() } else { slug }
};
let mut id = base.clone();
let mut number = 2;
while seen.contains_key(&id) {
id = format!("{base}-{number}");
number += 1;
}
attributes.push_str(&format!(" id=\"{id}\""));
id
};
seen.insert(id.clone(), ());
headings.push(Heading { level, id, text });
format!("<h{level}{attributes}>{inner}</h{level}>")
});
Rendered {
html: anchored.into_owned(),
headings,
}
}
fn decode_entities(text: &str) -> String {
ENTITY
.replace_all(text, |found: &Captures<'_>| {
let name = &found[1];
if let Some(number) = name.strip_prefix('#') {
let code = match number.strip_prefix(['x', 'X']) {
Some(hex) => u32::from_str_radix(hex, 16).ok(),
None => number.parse().ok(),
};
return code
.and_then(char::from_u32)
.map_or_else(|| found[0].to_owned(), |c| c.to_string());
}
match name {
"amp" => "&",
"lt" => "<",
"gt" => ">",
"quot" => "\"",
"apos" => "'",
"nbsp" => "\u{a0}",
"copy" => "\u{a9}",
"hellip" => "\u{2026}",
"mdash" => "\u{2014}",
"ndash" => "\u{2013}",
"laquo" => "\u{ab}",
"raquo" => "\u{bb}",
_ => return found[0].to_owned(),
}
.to_owned()
})
.into_owned()
}