use crate::converter::DomContext;
use crate::converter::tier1::tags::{TagSpec, lookup};
const MAX_LOOKAHEAD_NODES: usize = 64;
pub fn writes_own_text(tag_name: &str) -> bool {
matches!(
tag_name,
"button" | "select" | "datalist" | "textarea" | "output" | "meter" | "progress"
)
}
pub fn needs_space_before(output: &str) -> bool {
output
.chars()
.next_back()
.is_some_and(|last| !last.is_whitespace() && !matches!(last, '(' | '[' | '{'))
}
pub fn line_goes_on_in(parent: Option<&TagSpec>) -> bool {
parent.is_none_or(|spec| !spec.is_block)
}
pub fn line_goes_on_after_parent(id: u32, parser: &tl::Parser, dom_ctx: &DomContext) -> bool {
dom_ctx
.parent_tag_name(id, parser)
.is_some_and(|name| line_goes_on_in(lookup(name.as_bytes())))
}
pub struct ControlStart {
at: usize,
separate: bool,
}
impl ControlStart {
pub fn new(output: &str) -> Self {
Self::at(output, output.len())
}
pub fn at(output: &str, at: usize) -> Self {
Self {
at,
separate: needs_space_before(&output[..at]),
}
}
pub fn finish(&self, output: &mut String) -> bool {
let Some(space_owed) = space_owed_before(self.separate, output.get(self.at..).unwrap_or_default()) else {
return false;
};
if space_owed {
output.insert(self.at, ' ');
}
true
}
}
pub fn space_owed_before(separate: bool, written: &str) -> Option<bool> {
(!written.is_empty()).then(|| separate && !written.starts_with(char::is_whitespace))
}
pub fn starts_with_word(text: &str) -> Option<bool> {
text.chars()
.next()
.map(|first| !first.is_whitespace() && !matches!(first, '.' | ',' | ';' | ':' | '!' | '?' | ')' | ']' | '}'))
}
pub fn separate_from_next_text(
output: &mut String,
node_handle: tl::NodeHandle,
parser: &tl::Parser,
dom_ctx: &DomContext,
) {
if needs_space_before(output) && word_follows(node_handle.get_inner(), parser, dom_ctx) {
output.push(' ');
}
}
pub fn option_word<'a>(list: &str, text: &'a str) -> Option<(&'static str, &'a str)> {
let word = text.trim();
if word.is_empty() {
return None;
}
let separator = if list.is_empty() || list.ends_with(char::is_whitespace) {
""
} else {
" "
};
Some((separator, word))
}
pub fn write_option(list: &mut String, text: &str) {
if let Some((separator, word)) = option_word(list, text) {
list.push_str(separator);
list.push_str(word);
}
}
pub fn option_list_text(options: &str, in_code: bool) -> Option<&str> {
let trimmed = options.trim();
if trimmed.is_empty() {
return None;
}
Some(if in_code { options } else { trimmed })
}
pub fn write_option_list(output: &mut String, options: &str, in_code: bool) -> bool {
let Some(list) = option_list_text(options, in_code) else {
return false;
};
let start = ControlStart::new(output);
output.push_str(list);
start.finish(output)
}
fn siblings_after(id: u32, dom_ctx: &DomContext) -> &[tl::NodeHandle] {
let siblings = match dom_ctx.parent_of(id) {
Some(parent_id) => dom_ctx.children_of(parent_id),
None => Some(&dom_ctx.root_children),
};
siblings
.zip(dom_ctx.sibling_index(id))
.and_then(|(siblings, position)| siblings.get(position + 1..))
.unwrap_or_default()
}
pub fn white_space_follows(id: u32, parser: &tl::Parser, dom_ctx: &DomContext) -> bool {
siblings_after(id, dom_ctx)
.iter()
.filter_map(|next| next.get(parser))
.find(|next| !matches!(next, tl::Node::Comment(_)))
.is_some_and(|next| matches!(next, tl::Node::Raw(raw) if raw.as_utf8_str().starts_with(char::is_whitespace)))
}
fn word_follows(mut id: u32, parser: &tl::Parser, dom_ctx: &DomContext) -> bool {
let mut budget = MAX_LOOKAHEAD_NODES;
loop {
for sibling in siblings_after(id, dom_ctx) {
if let Some(starts_with_word) = leading_word(*sibling, parser, dom_ctx, &mut budget) {
return starts_with_word;
}
}
let Some(parent_id) = dom_ctx.parent_of(id) else {
return false;
};
if !line_goes_on_after_parent(id, parser, dom_ctx) {
return false;
}
id = parent_id;
}
}
fn leading_word(handle: tl::NodeHandle, parser: &tl::Parser, dom_ctx: &DomContext, budget: &mut usize) -> Option<bool> {
if *budget == 0 {
return Some(false);
}
*budget -= 1;
match handle.get(parser)? {
tl::Node::Comment(_) => None,
tl::Node::Raw(raw) => starts_with_word(raw.as_utf8_str().as_ref()),
tl::Node::Tag(tag) => {
let name = dom_ctx.tag_name_for(handle, parser)?;
match name.as_ref() {
"input" | "script" | "style" | "template" | "noscript" => None,
"br" => Some(false),
"img" => Some(true),
_ => tag
.children()
.top()
.iter()
.find_map(|child| leading_word(*child, parser, dom_ctx, budget)),
}
}
}
}