use std::borrow::Cow;
use super::exclusions;
use crate::converter::main_helpers::{has_custom_element_tags, preserves_menu, repair_with_html5ever_bounded};
#[cfg(feature = "metadata")]
use crate::converter::utility::preprocessing::strip_script_and_style_tags_for_second_pass;
use crate::converter::utility::preprocessing::{
KeptScripts, normalize_menu_elements, normalize_unclosed_list_items, owner_mark_numbers, preprocess_html,
strip_bogus_comments, strip_hidden_elements, strip_html_cdata, strip_script_and_style_tags,
strip_script_and_style_tags_with_kept_scripts,
};
use crate::error::Result;
use crate::options::{ConversionOptions, HiddenContent};
type Prepared<'a> = (String, Option<crate::types::WarningKind>, Option<&'a str>, KeptScripts);
pub(super) fn prepare_html<'a>(html: &'a str, options: &ConversionOptions) -> Result<Prepared<'a>> {
let hidden_content = options.hidden_content;
let (preprocessed, kept_scripts) = preprocess_initial_html_with_kept_scripts(html, options, hidden_content)?;
if has_custom_element_tags(&preprocessed) {
let (repaired, limit) = repair_custom_elements(
preprocessed,
preserves_menu(options),
hidden_content,
keep_inert_wrappers(options, hidden_content),
);
return Ok((repaired, limit, None, kept_scripts));
}
Ok((preprocessed, None, Some(html), kept_scripts))
}
fn strip_hidden(html: &str, hidden_content: HiddenContent) -> Cow<'_, str> {
match hidden_content {
HiddenContent::Drop => strip_hidden_elements(html),
HiddenContent::Reachable | HiddenContent::All => Cow::Borrowed(html),
}
}
pub(super) fn preprocess_initial_html(
html: &str,
options: &ConversionOptions,
hidden_content: HiddenContent,
) -> Result<String> {
Ok(preprocess_initial_html_with_kept_scripts(html, options, hidden_content)?.0)
}
pub fn owner_mark_numbers_after_cleanup(html: &str, options: &ConversionOptions) -> Result<Vec<usize>> {
let page = preprocess_initial_html(html, options, options.hidden_content)?;
Ok(owner_mark_numbers(page.as_bytes()).into_iter().collect())
}
fn preprocess_initial_html_with_kept_scripts(
html: &str,
options: &ConversionOptions,
hidden_content: HiddenContent,
) -> Result<(String, KeptScripts)> {
let stripped = strip_html_cdata(html);
let (first_pass, kept_scripts) = strip_script_and_style_tags_with_kept_scripts(&stripped);
let page = clean_up(&first_pass, options, hidden_content)?;
#[cfg(feature = "metadata")]
{
if let Some(reserving) = kept_scripts.reserving_owner_names_of(&page) {
let (first_pass, kept_scripts) = strip_script_and_style_tags_for_second_pass(&stripped, reserving);
return Ok((clean_up(&first_pass, options, hidden_content)?, kept_scripts));
}
}
Ok((page, kept_scripts))
}
fn clean_up(first_pass: &str, options: &ConversionOptions, hidden_content: HiddenContent) -> Result<String> {
let stripped = strip_bogus_comments(first_pass);
let stripped = strip_hidden(&stripped, hidden_content);
let stripped = if keep_inert_wrappers(options, hidden_content) {
Cow::Borrowed(stripped.as_ref())
} else {
exclusions::remove_kept_tags(&stripped, hidden_content, &options.exclude_selectors)?
};
let stripped = normalize_unclosed_list_items(&stripped);
let stripped = normalize_menu_elements(&stripped, preserves_menu(options));
Ok(preprocess_html(&stripped).into_owned())
}
pub(super) fn preprocess_repaired_html(html: &str, preserve_menu: bool, hidden_content: HiddenContent) -> String {
let stripped = strip_html_cdata(html);
let stripped = strip_script_and_style_tags(&stripped);
let stripped = strip_hidden(&stripped, hidden_content);
let stripped = normalize_unclosed_list_items(&stripped);
let stripped = normalize_menu_elements(&stripped, preserve_menu);
preprocess_html(&stripped).into_owned()
}
#[cfg(feature = "visitor")]
pub(super) fn keep_inert_wrappers(options: &ConversionOptions, hidden_content: HiddenContent) -> bool {
options.visitor.is_some()
&& hidden_content == HiddenContent::All
&& options.output_format != crate::options::OutputFormat::Plain
}
#[cfg(not(feature = "visitor"))]
pub(super) const fn keep_inert_wrappers(_options: &ConversionOptions, _hidden_content: HiddenContent) -> bool {
false
}
fn repair_custom_elements(
preprocessed: String,
preserve_menu: bool,
hidden_content: HiddenContent,
keep_templates: bool,
) -> (String, Option<crate::types::WarningKind>) {
let repair = if keep_templates {
crate::converter::main_helpers::repair_with_html5ever(&preprocessed, true)
} else {
repair_with_html5ever_bounded(&preprocessed)
};
let Some((repaired, warning)) = repair else {
tracing::warn!(
target: "html_to_markdown::convert",
"custom element tags detected; html5ever repair failed, proceeding with unrepaired markup"
);
return (preprocessed, None);
};
tracing::warn!(
target: "html_to_markdown::convert",
"custom element tags detected; re-parsed input with html5ever repair fallback"
);
(
preprocess_repaired_html(&repaired, preserve_menu, hidden_content),
warning,
)
}
#[cfg(test)]
mod tests {
use super::{ConversionOptions, HiddenContent, prepare_html, preprocess_initial_html, preprocess_repaired_html};
#[test]
fn should_keep_the_initial_inert_wrapper_as_a_metadata_boundary_after_cleanup() {
let html = r#"<template><p>inert</p></template><meta name="description" content="D"><p>body</p>"#;
let options = ConversionOptions::default();
let page = preprocess_initial_html(html, &options, HiddenContent::Drop).expect("cleaned page");
assert!(page.starts_with("<template>"), "{page}");
assert_eq!(
crate::converter::utility::preprocessing::metadata_prefix_end(&page),
0,
"{page}"
);
}
#[test]
fn the_page_of_a_choice_is_the_page_that_the_conversion_reads() {
let html = r#"<p>t</p><script type="application/ld+json">{"a":"<b>"}</script><p>after</p>"#;
let options = ConversionOptions::default();
let page = preprocess_initial_html(html, &options, HiddenContent::Drop).expect("the page");
let (read, _, _, _) = prepare_html(html, &options).expect("the page");
assert_eq!(page, read);
#[cfg(feature = "metadata")]
assert_eq!(page.matches("data-h2m-script-1=").count(), 1, "{page}");
}
#[test]
fn a_lt_of_a_kept_script_of_a_repaired_page_is_written_as_text() {
let html = r#"<p>t</p><script type="application/ld+json">{"a":"<b>"}</script><p>after</p>"#;
let page = preprocess_repaired_html(html, false, HiddenContent::Drop);
assert!(page.contains(r#"{"a":"<b>"}"#), "{page}");
}
}