use std::collections::{BTreeMap, HashSet};
use std::sync::OnceLock;
use crate::options::ConversionOptions;
pub fn format_metadata_frontmatter(metadata: &BTreeMap<String, String>) -> Option<String> {
const OPEN: &str = "---\n";
let mut result = String::from(OPEN);
for (key, value) in metadata {
if key == "title" && value.is_empty() {
continue;
}
push_yaml_scalar(&mut result, key);
result.push_str(": ");
push_yaml_scalar(&mut result, value);
result.push('\n');
}
if result.len() == OPEN.len() {
return None;
}
result.push_str("---\n");
Some(result)
}
fn push_yaml_scalar(out: &mut String, value: &str) {
if is_plain_yaml_scalar(value) {
out.push_str(value);
return;
}
out.push('"');
for ch in value.chars() {
match ch {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
c if is_yaml_printable(c) => out.push(c),
c => {
use std::fmt::Write as _;
let _ = write!(out, "\\u{:04X}", u32::from(c));
}
}
}
out.push('"');
}
fn is_plain_yaml_scalar(value: &str) -> bool {
let Some(first) = value.chars().next() else {
return false;
};
!matches!(
first,
'-' | '?'
| ':'
| ','
| '['
| ']'
| '{'
| '}'
| '#'
| '&'
| '*'
| '!'
| '|'
| '>'
| '\''
| '"'
| '%'
| '@'
| '`'
) && !value.starts_with(' ')
&& !value.ends_with([' ', ':'])
&& !value.contains(": ")
&& !value.contains(" #")
&& value.chars().all(|c| c != '\t' && is_yaml_printable(c))
&& !yaml_non_string_scalar().is_match(value)
}
fn yaml_non_string_scalar() -> &'static regex::Regex {
static RE: OnceLock<regex::Regex> = OnceLock::new();
RE.get_or_init(|| {
regex::Regex::new(concat!(
r"^(?:~|null|Null|NULL",
r"|true|True|TRUE|false|False|FALSE|yes|Yes|YES|no|No|NO|on|On|ON|off|Off|OFF|y|Y|n|N",
r"|[-+]?(?:0b[01_]+|0o[0-7]+|0x[0-9a-fA-F_]+",
r"|[0-9][0-9_]*(?::[0-5]?[0-9])*(?:\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?",
r"|\.[0-9][0-9_]*(?:[eE][-+]?[0-9]+)?|\.(?:inf|Inf|INF))",
r"|\.(?:nan|NaN|NAN)",
r"|[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}",
r"(?:(?:[Tt]|[ \t]+)[0-9]{1,2}:[0-9]{2}:[0-9]{2}(?:\.[0-9]*)?(?:[ \t]*(?:Z|[-+][0-9]{1,2}(?::[0-9]{2})?))?)?",
r"|=|<<)$",
))
.expect("YAML scalar type regex is well-formed")
})
}
const fn is_yaml_printable(c: char) -> bool {
matches!(c, '\t' | ' '..='~' | '\u{A0}'..='\u{D7FF}' | '\u{E000}'..='\u{FFFD}' | '\u{10000}'..='\u{10FFFF}')
&& !matches!(c, '\u{2028}' | '\u{2029}' | '\u{FEFF}')
}
fn collect_meta_head_metadata(
child_tag: &tl::HTMLTag,
options: &ConversionOptions,
metadata: &mut BTreeMap<String, String>,
seen: &mut HashSet<String>,
) {
if !child_tag.name().as_utf8_str().eq_ignore_ascii_case("meta")
|| options.strip_tags.iter().any(|t| t == "meta")
|| options.preserve_tags.iter().any(|t| t == "meta")
{
return;
}
if let (Some(name), Some(content)) = (
child_tag.attributes().get("name").flatten(),
crate::converter::utility::attributes::decoded_attribute(child_tag, "content"),
) {
let key = format!("meta-{}", name.as_utf8_str());
if seen.insert(key.to_ascii_lowercase()) {
metadata.insert(key, content.into_owned());
}
}
if let (Some(property), Some(content)) = (
child_tag.attributes().get("property").flatten(),
crate::converter::utility::attributes::decoded_attribute(child_tag, "content"),
) {
let key = format!("meta-{}", property.as_utf8_str());
if seen.insert(key.to_ascii_lowercase()) {
metadata.insert(key, content.into_owned());
}
}
}
fn collect_title_head_metadata(
child_tag: &tl::HTMLTag,
parser: &tl::Parser,
options: &ConversionOptions,
metadata: &mut BTreeMap<String, String>,
seen_title: &mut bool,
) {
if !child_tag.name().as_utf8_str().eq_ignore_ascii_case("title") {
return;
}
let later_title = std::mem::replace(seen_title, true);
if later_title
|| options.strip_tags.iter().any(|t| t == "title")
|| options.preserve_tags.iter().any(|t| t == "title")
{
return;
}
let mut title_content = String::new();
let title_children = child_tag.children();
for title_child in title_children.top().iter() {
if let Some(tl::Node::Raw(raw)) = title_child.get(parser) {
title_content.push_str(raw.as_utf8_str().as_ref());
}
}
let title_content = crate::text::decode_html_entities_cow(title_content.trim()).into_owned();
metadata.insert("title".to_string(), title_content);
}
fn collect_link_head_metadata(child_tag: &tl::HTMLTag, metadata: &mut BTreeMap<String, String>) {
if !child_tag.name().as_utf8_str().eq_ignore_ascii_case("link") {
return;
}
let Some(rel_attr) = child_tag.attributes().get("rel").flatten() else {
return;
};
let rel_str = rel_attr.as_utf8_str();
if !rel_str.contains("canonical") {
return;
}
let Some(href) = crate::converter::utility::attributes::decoded_attribute(child_tag, "href") else {
return;
};
metadata
.entry("canonical".to_string())
.or_insert_with(|| href.into_owned());
}
pub fn extract_head_metadata(
roots: &[tl::NodeHandle],
parser: &tl::Parser,
options: &ConversionOptions,
document_base_href: Option<&str>,
metadata_end: usize,
) -> BTreeMap<String, String> {
let mut metadata = head_element_metadata(roots, parser, options, metadata_end);
if let Some(href) = document_base_href {
metadata.insert("base".to_string(), href.to_string());
}
metadata
}
fn head_element_metadata(
roots: &[tl::NodeHandle],
parser: &tl::Parser,
options: &ConversionOptions,
metadata_end: usize,
) -> BTreeMap<String, String> {
let mut metadata = BTreeMap::new();
let mut seen_meta = HashSet::new();
let mut seen_title = false;
let mut seen_head = false;
let mut work: Vec<_> = roots.iter().rev().map(|handle| (*handle, false)).collect();
while let Some((handle, in_head)) = work.pop() {
match handle.get(parser) {
Some(tl::Node::Tag(tag)) => {
if tag.boundaries(parser).0 >= metadata_end {
break;
}
let name = tag.name().as_bytes();
if name.eq_ignore_ascii_case(b"head") && std::mem::replace(&mut seen_head, true) {
continue;
}
if seen_head && name.contains(&b':') {
continue;
}
if name.eq_ignore_ascii_case(b"html") || name.eq_ignore_ascii_case(b"head") {
let first = work.len();
let children_in_head = in_head || name.eq_ignore_ascii_case(b"head");
work.extend(tag.children().top().iter().map(|child| (*child, children_in_head)));
work[first..].reverse();
} else if starts_body(&name.to_ascii_lowercase()) {
break;
} else {
collect_meta_head_metadata(tag, options, &mut metadata, &mut seen_meta);
if in_head {
collect_title_head_metadata(tag, parser, options, &mut metadata, &mut seen_title);
}
collect_link_head_metadata(tag, &mut metadata);
}
}
Some(tl::Node::Raw(text)) => {
let next_is_html = matches!(work.last().and_then(|(next, _)| next.get(parser)),
Some(tl::Node::Tag(tag)) if tag.name().as_bytes().eq_ignore_ascii_case(b"html"));
if !is_ignorable_before_head(&text.as_utf8_str(), next_is_html) {
break;
}
}
_ => {}
}
}
metadata
}
pub fn document_head(roots: &[tl::NodeHandle], parser: &tl::Parser) -> Option<tl::NodeHandle> {
document_head_search(roots, parser).head
}
pub(super) struct HeadSearch {
head: Option<tl::NodeHandle>,
pub(super) content_outside_head: bool,
}
pub(super) fn document_head_search(roots: &[tl::NodeHandle], parser: &tl::Parser) -> HeadSearch {
let mut head = None;
let mut content_before_head = false;
let mut saw_head_content = false;
let mut saw_title = false;
let mut misplaced_image = false;
let mut work: Vec<_> = roots.iter().rev().copied().collect();
while let Some(handle) = work.pop() {
match handle.get(parser) {
Some(tl::Node::Raw(text)) => {
let next_is_html = matches!(
work.last().and_then(|next| next.get(parser)),
Some(tl::Node::Tag(tag)) if tag.name().as_bytes().eq_ignore_ascii_case(b"html")
);
if !is_ignorable_before_head(&text.as_utf8_str(), next_is_html) {
break;
}
}
Some(tl::Node::Tag(tag)) => {
let name = tag.name().as_bytes().to_ascii_lowercase();
match name.as_slice() {
b"head" => {
if head.is_none() {
head = Some(handle);
content_before_head = saw_head_content;
misplaced_image = tag.children().top().iter().any(|child| {
matches!(child.get(parser), Some(tl::Node::Tag(child))
if child.name().as_bytes().eq_ignore_ascii_case(b"img"))
});
}
}
b"html" => {
let first = work.len();
work.extend(tag.children().top().iter().copied());
work[first..].reverse();
}
name if starts_body(name) => break,
name => {
saw_head_content = true;
saw_title |= name == b"title";
}
}
}
_ => {}
}
}
HeadSearch {
head,
content_outside_head: content_before_head || saw_title || misplaced_image,
}
}
pub fn is_ignorable_before_head(text: &str, next_tag_is_html: bool) -> bool {
next_tag_is_html
|| crate::text::decode_html_entities_cow(text)
.chars()
.all(char::is_whitespace)
}
pub const fn starts_body(name: &[u8]) -> bool {
!matches!(
name,
b"html"
| b"head"
| b"base"
| b"basefont"
| b"bgsound"
| b"link"
| b"meta"
| b"noframes"
| b"noscript"
| b"script"
| b"style"
| b"template"
| b"title"
)
}
pub const fn end_tag_starts_body(name: &[u8]) -> bool {
matches!(name, b"body" | b"html" | b"br")
}