use regex::Regex;
use std::sync::OnceLock;
static PROTECTED_RE: OnceLock<Regex> = OnceLock::new();
static BLOCK_COMMENT_RE: OnceLock<Regex> = OnceLock::new();
static BETWEEN_TAGS_RE: OnceLock<Regex> = OnceLock::new();
static HTML_COMMENT_RE: OnceLock<Regex> = OnceLock::new();
static NEWLINE_RE: OnceLock<Regex> = OnceLock::new();
static MULTI_SPACE_RE: OnceLock<Regex> = OnceLock::new();
fn protected_re() -> &'static Regex {
PROTECTED_RE.get_or_init(|| {
Regex::new(r"(?si)(<(pre|script|style)[^>]*>)(.*?)(</(?:pre|script|style)\s*>)")
.expect("Invalid protected block regex")
})
}
fn block_comment_re() -> &'static Regex {
BLOCK_COMMENT_RE
.get_or_init(|| Regex::new(r"(?s)/\*.*?\*/").expect("Invalid block comment regex"))
}
fn html_comment_re() -> &'static Regex {
HTML_COMMENT_RE
.get_or_init(|| Regex::new(r"(?s)<!--.*?-->").expect("Invalid HTML comment regex"))
}
fn between_tags_re() -> &'static Regex {
BETWEEN_TAGS_RE.get_or_init(|| Regex::new(r">\s+<").expect("Invalid between-tags regex"))
}
fn newline_re() -> &'static Regex {
NEWLINE_RE.get_or_init(|| Regex::new(r"[ \t]*\n[ \t]*").expect("Invalid newline regex"))
}
fn multi_space_re() -> &'static Regex {
MULTI_SPACE_RE.get_or_init(|| Regex::new(r"[ \t]{2,}").expect("Invalid multi-space regex"))
}
fn minify_css(css: &str) -> String {
let no_comments = block_comment_re().replace_all(css, "");
no_comments
.lines()
.map(|l| l.trim())
.filter(|l| !l.is_empty())
.collect::<Vec<_>>()
.join(" ")
}
fn minify_js(js: &str) -> String {
let no_block_comments = block_comment_re().replace_all(js, "");
no_block_comments
.lines()
.map(|l| l.trim())
.filter(|l| !l.is_empty())
.collect::<Vec<_>>()
.join("\n")
}
pub fn minify_html(html: &str) -> String {
let protected = protected_re();
let mut stash: Vec<String> = Vec::new();
let mut working = String::with_capacity(html.len());
let mut last_end = 0;
for cap in protected.captures_iter(html) {
let m = cap.get(0).unwrap();
working.push_str(&html[last_end..m.start()]);
let open_tag = cap.get(1).unwrap().as_str();
let tag_name = cap.get(2).unwrap().as_str().to_ascii_lowercase();
let inner = cap.get(3).unwrap().as_str();
let close_tag = cap.get(4).unwrap().as_str();
let processed = match tag_name.as_str() {
"script" => format!("{}{}{}", open_tag, minify_js(inner), close_tag),
"style" => format!("{}{}{}", open_tag, minify_css(inner), close_tag),
_ => m.as_str().to_string(), };
working.push_str(&format!("<rustf-pb-{}/>", stash.len()));
stash.push(processed);
last_end = m.end();
}
working.push_str(&html[last_end..]);
let working = html_comment_re().replace_all(&working, "");
let working = newline_re().replace_all(working.as_ref(), " ");
let working = between_tags_re().replace_all(working.as_ref(), "><");
let working = multi_space_re().replace_all(working.as_ref(), " ");
let mut result = working.trim().to_string();
for (idx, block) in stash.iter().enumerate() {
result = result.replace(&format!("<rustf-pb-{}/>", idx), block);
}
result
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn collapses_whitespace_between_tags() {
let input = "<div> \n <p>Hello</p> \n </div>";
let output = minify_html(input);
assert_eq!(output, "<div><p>Hello</p></div>");
}
#[test]
fn collapses_multiple_spaces_in_text() {
let input = "<p>Hello World</p>";
let output = minify_html(input);
assert_eq!(output, "<p>Hello World</p>");
}
#[test]
fn preserves_pre_block() {
let input = "<div>\n <pre> spaced\n content </pre>\n</div>";
let output = minify_html(input);
assert_eq!(output, "<div><pre> spaced\n content </pre></div>");
}
#[test]
fn minifies_script_block() {
let input = "<head>\n <script>\n var x = 1;\n /* unused */\n var y = 2;\n </script>\n</head>";
let output = minify_html(input);
assert_eq!(
output,
"<head><script>var x = 1;\nvar y = 2;</script></head>"
);
}
#[test]
fn minifies_style_block() {
let input = "<head>\n <style>\n /* reset */\n body { margin: 0; }\n p { color: red; }\n </style>\n</head>";
let output = minify_html(input);
assert_eq!(
output,
"<head><style>body { margin: 0; } p { color: red; }</style></head>"
);
}
#[test]
fn script_preserves_line_comments() {
let input = "<script>\n // init\n var url = 'https://example.com';\n</script>";
let output = minify_html(input);
assert_eq!(
output,
"<script>// init\nvar url = 'https://example.com';</script>"
);
}
#[test]
fn strips_html_comments() {
let input = "<div><!-- a comment --><p>Hello</p></div>";
assert_eq!(minify_html(input), "<div><p>Hello</p></div>");
}
#[test]
fn strips_multiline_html_comment() {
let input = "<div>\n <!-- \n multi\n line\n -->\n <p>Hi</p>\n</div>";
assert_eq!(minify_html(input), "<div><p>Hi</p></div>");
}
#[test]
fn preserves_script_html_comment_wrapper() {
let input = "<script><!--\nvar x = 1;\n//--></script>";
assert_eq!(
minify_html(input),
"<script><!--\nvar x = 1;\n//--></script>"
);
}
#[test]
fn collapses_newlines_in_attribute() {
let input = "<meta name=\"viewport\"\n content=\"width=device-width\">";
assert_eq!(
minify_html(input),
"<meta name=\"viewport\" content=\"width=device-width\">"
);
}
#[test]
fn collapses_newlines_in_text_node() {
let input = "<span>Hello\n World</span>";
assert_eq!(minify_html(input), "<span>Hello World</span>");
}
#[test]
fn handles_empty_input() {
assert_eq!(minify_html(""), "");
}
#[test]
fn handles_plain_text() {
assert_eq!(minify_html("Hello"), "Hello");
}
#[test]
fn real_world_layout() {
let input = r#"<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<div class="container">
<h1>Hello</h1>
<p>World</p>
</div>
</body>
</html>"#;
let output = minify_html(input);
assert_eq!(
output,
r#"<!DOCTYPE html><html><head><title>Test</title></head><body><div class="container"><h1>Hello</h1><p>World</p></div></body></html>"#
);
}
}