use std::collections::BTreeMap;
use std::sync::LazyLock;
use regex::Regex;
static START: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r#"^:::[ \t]+if-published[ \t]+post=(?:"([A-Za-z0-9_.-]+)"|'([A-Za-z0-9_.-]+)')[ \t]*$"#)
.expect("a valid pattern")
});
static LIST_MARKER: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"^([-*+]|[0-9]{1,9}[.)])([ \t]+)").expect("a valid pattern"));
static FENCE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^(`{3,}|~{3,})(.*)$").expect("a valid pattern"));
static MARKERS: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r"(<!--larablog:(?:if-published:[A-Za-z0-9_.-]+:[01]|endif)-->)").expect("a valid pattern")
});
static OPENING: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"^<!--larablog:if-published:([A-Za-z0-9_.-]+):([01])-->$").expect("a valid pattern"));
static REFERENCE: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"<!--larablog:if-published:([A-Za-z0-9_.-]+):([01])-->").expect("a valid pattern"));
static EMPTY_LIST: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"(?i)<ul\b[^>]*>\s*</ul>|<ol\b[^>]*>\s*</ol>").expect("a valid pattern"));
pub const ENDIF: &str = "<!--larablog:endif-->";
pub fn open_marker(post: &str, closed: bool) -> String {
format!("<!--larablog:if-published:{post}:{}-->", u8::from(closed))
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Condition {
pub post: String,
pub closed: bool,
}
struct Scanned<'a> {
prefix: &'a str,
quote_depth: usize,
indent: usize,
item_column: Option<usize>,
token: &'a str,
}
fn columns(whitespace: &str) -> usize {
whitespace.chars().map(|c| if c == '\t' { 4 } else { 1 }).sum()
}
fn scan(line: &str) -> Scanned<'_> {
let mut rest = line;
let mut consumed = 0;
let mut quote_depth = 0;
loop {
let trimmed = rest.trim_start_matches(' ');
let spaces = rest.len() - trimmed.len();
if spaces <= 3 && trimmed.starts_with('>') {
let after = &trimmed[1..];
let optional = usize::from(after.starts_with(' '));
consumed += spaces + 1 + optional;
rest = &rest[spaces + 1 + optional..];
quote_depth += 1;
} else {
break;
}
}
let content = rest.trim_start_matches([' ', '\t']);
let indent = columns(&rest[..rest.len() - content.len()]);
consumed += rest.len() - content.len();
if let Some(marker) = LIST_MARKER.captures(content) {
let whole = marker.get(0).map_or(0, |m| m.end());
let spaces = marker.get(2).map_or(1, |m| columns(m.as_str()));
let width = marker.get(1).map_or(1, |m| m.as_str().chars().count());
if !content[whole..].is_empty() {
return Scanned {
prefix: &line[..consumed + whole],
quote_depth,
indent,
item_column: Some(indent + width + if spaces > 4 { 1 } else { spaces }),
token: &content[whole..],
};
}
}
Scanned {
prefix: &line[..consumed],
quote_depth,
indent,
item_column: None,
token: content,
}
}
enum Line {
Text(String),
Open { prefix: String, post: String, closed: bool },
}
struct Open {
quote_depth: usize,
column: usize,
continuation: String,
line: usize,
last: usize,
}
pub fn rewrite(body: &str) -> String {
if !body.contains("if-published") {
return body.to_owned();
}
let source = body.replace("\r\n", "\n");
let mut output: Vec<Line> = Vec::new();
let mut inserts: BTreeMap<usize, Vec<String>> = BTreeMap::new();
let mut open: Vec<Open> = Vec::new();
let mut lists: Vec<usize> = Vec::new();
let mut fence: Option<(char, usize)> = None;
for line in source.split('\n') {
let scanned = scan(line);
let blank = scanned.token.trim().is_empty();
if let Some((mark, length)) = fence {
let trimmed = scanned.token.trim();
if !trimmed.is_empty() && trimmed.chars().all(|c| c == mark) && trimmed.chars().count() >= length {
fence = None;
}
touch(&mut open, output.len());
output.push(Line::Text(line.to_owned()));
continue;
}
if blank {
output.push(Line::Text(line.to_owned()));
continue;
}
while lists.last().is_some_and(|column| *column > scanned.indent) {
lists.pop();
}
let base = lists.last().copied().unwrap_or(0);
while let Some(top) = open.last() {
if scanned.quote_depth < top.quote_depth || (top.column > 0 && scanned.indent < top.column) {
close(&mut open, &mut inserts);
} else {
break;
}
}
let relative = scanned.item_column.map_or(scanned.indent.saturating_sub(base), |_| 0);
if relative < 4 {
if let Some(found) = START.captures(scanned.token) {
let post = found
.get(1)
.or_else(|| found.get(2))
.map_or("", |m| m.as_str())
.to_owned();
let column = scanned.item_column.unwrap_or(base);
touch(&mut open, output.len());
open.push(Open {
quote_depth: scanned.quote_depth,
column,
continuation: continuation(&scanned, column),
line: output.len(),
last: output.len(),
});
output.push(Line::Open {
prefix: scanned.prefix.to_owned(),
post,
closed: false,
});
if let Some(column) = scanned.item_column {
lists.push(column);
}
continue;
}
if scanned.token.trim_end() == ":::" && !open.is_empty() {
let closing = open.pop().expect("an open condition");
if let Some(Line::Open { closed, .. }) = output.get_mut(closing.line) {
*closed = true;
}
touch(&mut open, output.len());
output.push(Line::Text(format!("{}{ENDIF}", scanned.prefix)));
continue;
}
}
if let Some(column) = scanned.item_column {
lists.push(column);
}
if let Some(opening) = FENCE.captures(scanned.token) {
let marks = opening.get(1).map_or("", |m| m.as_str());
let info = opening.get(2).map_or("", |m| m.as_str());
let mark = marks.chars().next().unwrap_or('`');
if !(mark == '`' && info.contains('`')) {
fence = Some((mark, marks.chars().count()));
}
}
touch(&mut open, output.len());
output.push(Line::Text(line.to_owned()));
}
while !open.is_empty() {
close(&mut open, &mut inserts);
}
let mut result: Vec<String> = Vec::with_capacity(output.len());
for (index, line) in output.into_iter().enumerate() {
result.push(match line {
Line::Text(text) => text,
Line::Open { prefix, post, closed } => format!("{prefix}{}", open_marker(&post, closed)),
});
if let Some(extra) = inserts.remove(&index) {
result.extend(extra);
}
}
result.join("\n")
}
fn continuation(scanned: &Scanned<'_>, column: usize) -> String {
let quotes: String = {
let mut text = String::new();
let mut rest = scanned.prefix;
for _ in 0..scanned.quote_depth {
let trimmed = rest.trim_start_matches(' ');
let after = &trimmed[1..];
let optional = usize::from(after.starts_with(' '));
text.push_str("> ");
rest = &after[optional..];
}
text
};
format!("{quotes}{}", " ".repeat(column))
}
fn touch(open: &mut [Open], index: usize) {
for condition in open {
condition.last = index;
}
}
fn close(open: &mut Vec<Open>, inserts: &mut BTreeMap<usize, Vec<String>>) {
if let Some(condition) = open.pop() {
inserts
.entry(condition.last)
.or_default()
.push(format!("{}{ENDIF}", condition.continuation));
}
}
pub fn references(html: &str) -> Vec<Condition> {
REFERENCE
.captures_iter(html)
.map(|found| Condition {
post: found[1].to_owned(),
closed: &found[2] == "1",
})
.collect()
}
pub fn resolve(html: &str, mut is_published: impl FnMut(&str) -> bool) -> String {
if !html.contains("<!--larablog:if-published:") {
return html.to_owned();
}
let mut stack: Vec<bool> = Vec::new();
let mut known: BTreeMap<String, bool> = BTreeMap::new();
let mut result = String::with_capacity(html.len());
let mut last = 0;
let mut handle = |part: &str, stack: &mut Vec<bool>, result: &mut String| {
if let Some(found) = OPENING.captures(part) {
let outer = stack.last().copied().unwrap_or(true);
let post = found[1].to_owned();
let visible =
outer && &found[2] == "1" && *known.entry(post.clone()).or_insert_with(|| is_published(&post));
stack.push(visible);
} else if part == ENDIF {
stack.pop();
} else if stack.last().copied().unwrap_or(true) {
result.push_str(part);
}
};
for found in MARKERS.find_iter(html) {
handle(&html[last..found.start()], &mut stack, &mut result);
handle(found.as_str(), &mut stack, &mut result);
last = found.end();
}
handle(&html[last..], &mut stack, &mut result);
EMPTY_LIST.replace_all(&result, "").into_owned()
}