use crate::converter::utility::escaping::is_block_level_name;
use crate::text;
use std::borrow::Cow;
#[cfg(feature = "visitor")]
use std::collections::BTreeMap;
pub use crate::converter::DomContext;
#[cfg(feature = "visitor")]
pub fn collect_tag_attributes(tag: &tl::HTMLTag) -> BTreeMap<String, String> {
tag.attributes()
.iter()
.filter_map(|(k, v)| v.as_ref().map(|val| (k.to_string(), val.to_string())))
.collect()
}
pub fn chomp_inline(text: &str) -> (&str, &str, &str) {
if text.is_empty() {
return ("", "", "");
}
let has_trailing_linebreak = text.ends_with(" \n") || text.ends_with("\\\n");
if text.trim().is_empty() && !has_trailing_linebreak {
return (" ", "", "");
}
let prefix = if text.starts_with(&[' ', '\t'][..]) { " " } else { "" };
let suffix = if has_trailing_linebreak {
if text.ends_with(" \n") { " \n" } else { "\\\n" }
} else if text.ends_with(&[' ', '\t'][..]) {
" "
} else {
""
};
let trimmed = if has_trailing_linebreak {
text.strip_suffix(" \n").map_or_else(
|| text.strip_suffix("\\\n").map_or_else(|| text.trim(), |s| s.trim()),
|s| s.trim(),
)
} else {
text.trim()
};
(prefix, suffix, trimmed)
}
pub fn merge_adjacent_emphasis(output: &mut String, symbol: char, count: usize) -> bool {
if count == 0 {
return false;
}
let mut rev = output.chars().rev();
for _ in 0..count {
match rev.next() {
Some(c) if c == symbol => {}
_ => return false,
}
}
if let Some(preceding) = rev.next() {
if preceding == symbol || preceding == '\\' {
return false;
}
}
let new_len = output.len() - symbol.len_utf8() * count;
output.truncate(new_len);
true
}
#[allow(clippy::trivially_copy_pass_by_ref)]
pub fn get_text_content(node_handle: &tl::NodeHandle, parser: &tl::Parser, dom_ctx: &DomContext) -> String {
dom_ctx.text_content(*node_handle, parser)
}
#[allow(clippy::trivially_copy_pass_by_ref)]
pub fn node_is_block_level(handle: &tl::NodeHandle, parser: &tl::Parser, dom_ctx: &DomContext) -> bool {
let Some(tl::Node::Tag(tag)) = handle.get(parser) else {
return false;
};
dom_ctx.tag_info(handle.get_inner(), parser).map_or_else(
|| {
let tag_name = normalized_tag_name(tag.name().as_utf8_str());
is_block_level_element(tag_name.as_ref())
},
|info| info.is_block,
)
}
#[allow(clippy::match_wildcard_for_single_variants)]
pub fn collect_link_label_text(
children: &[tl::NodeHandle],
parser: &tl::Parser,
dom_ctx: &DomContext,
) -> (String, Vec<tl::NodeHandle>, bool) {
let mut text = String::new();
let mut saw_block = false;
let mut block_nodes = Vec::new();
let mut stack: Vec<_> = children.iter().rev().copied().collect();
while let Some(handle) = stack.pop() {
let Some(node) = handle.get(parser) else {
continue;
};
match node {
tl::Node::Raw(bytes) => {
let raw = bytes.as_utf8_str();
let decoded = text::decode_html_entities_cow(raw.as_ref());
text.push_str(decoded.as_ref());
}
tl::Node::Tag(tag) if node_is_block_level(&handle, parser, dom_ctx) => {
saw_block = true;
block_nodes.push(handle);
}
tl::Node::Tag(tag) => push_label_children(&mut stack, handle, tag, dom_ctx),
_ => {}
}
}
(text, block_nodes, saw_block)
}
fn push_label_children(
stack: &mut Vec<tl::NodeHandle>,
handle: tl::NodeHandle,
tag: &tl::HTMLTag<'_>,
dom_ctx: &DomContext,
) {
if let Some(children) = dom_ctx.children_of(handle.get_inner()) {
stack.extend(children.iter().rev().copied());
return;
}
let mut children: Vec<_> = tag.children().top().iter().copied().collect();
children.reverse();
stack.extend(children);
}
const HARD_BREAK_MARKERS: [&str; 2] = [" \n", "\\\n"];
#[allow(clippy::trivially_copy_pass_by_ref)]
pub fn normalize_link_label(label: &str) -> String {
let mut segments: Vec<String> = Vec::new();
let mut markers: Vec<&'static str> = Vec::new();
let mut rest = label;
while let Some((marker_pos, marker)) = find_earliest_hard_break_marker(rest) {
let mut segment = String::new();
collapse_whitespace_into(&mut segment, &rest[..marker_pos]);
segments.push(segment);
markers.push(marker);
rest = &rest[marker_pos + marker.len()..];
}
let mut segment = String::new();
collapse_whitespace_into(&mut segment, rest);
segments.push(segment);
let label = assemble_label(segments, markers);
protect_adjacent_hard_breaks(&label).into_owned()
}
pub fn protect_adjacent_hard_breaks(label: &str) -> Cow<'_, str> {
if !label.contains(" \n \n") && !label.contains("\\\n \n") {
return Cow::Borrowed(label);
}
let protected = label.replace(" \n \n", " \n\\\n");
Cow::Owned(protected.replace("\\\n \n", "\\\n\\\n"))
}
fn assemble_label(mut segments: Vec<String>, mut markers: Vec<&'static str>) -> String {
if let Some(first) = segments.first_mut() {
*first = first.trim_start().to_string();
}
if let Some(last) = segments.last_mut() {
*last = last.trim_end().to_string();
}
let mut leading = "";
while segments.len() > 1 && segments[0].is_empty() {
segments.remove(0);
leading = markers.remove(0);
}
let mut trailing = "";
while segments.len() > 1 && segments.last().is_some_and(String::is_empty) {
segments.pop();
trailing = markers.pop().unwrap_or("");
}
if segments.iter().all(String::is_empty) {
return String::new();
}
let mut result = String::with_capacity(label_capacity(&segments, &markers, leading, trailing));
result.push_str(leading);
for (index, segment) in segments.iter().enumerate() {
if index > 0 {
result.push_str(markers.get(index - 1).copied().unwrap_or(""));
}
result.push_str(segment);
}
result.push_str(trailing);
result
}
fn label_capacity(segments: &[String], markers: &[&str], leading: &str, trailing: &str) -> usize {
segments.iter().map(String::len).sum::<usize>()
+ markers.iter().map(|marker| marker.len()).sum::<usize>()
+ leading.len()
+ trailing.len()
}
fn find_earliest_hard_break_marker(text: &str) -> Option<(usize, &'static str)> {
HARD_BREAK_MARKERS
.iter()
.filter_map(|marker| text.find(marker).map(|pos| (pos, *marker)))
.min_by_key(|(pos, _)| *pos)
}
fn collapse_whitespace_into(out: &mut String, segment: &str) {
if segment.is_empty() {
return;
}
let folded: Cow<'_, str> = if segment.contains(['\n', '\r']) {
Cow::Owned(segment.replace(['\n', '\r'], " "))
} else {
Cow::Borrowed(segment)
};
out.push_str(text::normalize_whitespace_cow(folded.as_ref()).as_ref());
}
pub fn normalized_tag_name(raw: Cow<'_, str>) -> Cow<'_, str> {
if raw.as_bytes().iter().any(u8::is_ascii_uppercase) {
let mut owned = raw.into_owned();
owned.make_ascii_lowercase();
Cow::Owned(owned)
} else {
raw
}
}
pub fn is_block_level_element(tag_name: &str) -> bool {
is_block_level_name(tag_name, crate::converter::main_helpers::is_inline_element(tag_name))
}
pub const fn floor_char_boundary(s: &str, index: usize) -> usize {
if index >= s.len() {
s.len()
} else {
let mut i = index;
while i > 0 && !s.is_char_boundary(i) {
i -= 1;
}
i
}
}