use crate::converter::block::container::HandlerContext;
#[cfg(feature = "metadata")]
use crate::converter::utility::preprocessing::{KeptScripts, ScriptType, script_type};
use crate::options::ConversionOptions;
use crate::text::escape;
use tl::{NodeHandle, Parser};
type Context = crate::converter::Context;
type DomContext = crate::converter::DomContext;
pub fn handle(
tag_name: &str,
node_handle: &NodeHandle,
parser: &Parser,
output: &mut String,
handler: HandlerContext<'_>,
) {
match tag_name {
"script" => {
handle_script(node_handle, parser, output, handler.ctx);
}
"style" => {}
"math" => {
handle_math(
node_handle,
parser,
output,
handler.options,
handler.ctx,
handler.dom_ctx,
);
}
_ => {}
}
}
pub fn is_body_content_in_head(name: &str) -> bool {
matches!(name, "body" | "main" | "article" | "section" | "div" | "p")
}
pub fn open_head(
node_handle: &NodeHandle,
parser: &Parser,
handler: HandlerContext<'_>,
children: &mut Vec<NodeHandle>,
) -> Option<crate::converter::walk::Open> {
let Some(tl::Node::Tag(tag)) = node_handle.get(parser) else {
return None;
};
let tag_children = tag.children();
let has_body_like = tag_children.top().iter().any(|child_handle| {
if let Some(child_name) = handler.dom_ctx.tag_name_for(*child_handle, parser) {
is_body_content_in_head(child_name.as_ref())
} else {
false
}
});
#[cfg(feature = "metadata")]
if handler.ctx.metadata_wants.structured_data {
collect_json_ld_from_children(&tag_children, parser, handler);
}
if !has_body_like {
return None;
}
children.extend(tag_children.top().iter().copied());
Some(crate::converter::walk::Open::children_only())
}
#[cfg(feature = "metadata")]
fn collect_json_ld_from_children(children: &tl::Children, parser: &Parser, handler: HandlerContext<'_>) {
let Some(collector) = handler.ctx.metadata_collector.as_ref() else {
return;
};
for child_handle in children.top().iter() {
let Some(tl::Node::Tag(child_tag)) = child_handle.get(parser) else {
continue;
};
let child_name = handler
.dom_ctx
.tag_name_for(*child_handle, parser)
.unwrap_or_else(|| crate::converter::normalized_tag_name(child_tag.name().as_utf8_str()));
if child_name.as_ref() != "script" {
continue;
}
if let Some(json) = json_ld_from_tag(child_handle.get_inner(), child_tag, parser, &handler.ctx.kept_scripts) {
collector.borrow_mut().add_json_ld(json);
}
}
}
#[cfg(feature = "metadata")]
fn json_ld_from_tag(node: u32, tag: &tl::HTMLTag<'_>, parser: &Parser, kept_scripts: &KeptScripts) -> Option<String> {
let type_value = crate::converter::utility::attributes::decoded_attribute(tag, "type")?;
if script_type(&type_value) != ScriptType::StructuredData {
return None;
}
let text = tag.inner_text(parser);
let json = kept_scripts.as_written(node, text.trim()).to_owned();
(!json.is_empty()).then_some(json)
}
#[cfg_attr(not(feature = "metadata"), allow(unused_variables))]
fn handle_script(node_handle: &NodeHandle, parser: &Parser, _output: &mut String, ctx: &Context) {
let Some(node) = node_handle.get(parser) else { return };
let tag = match node {
tl::Node::Tag(tag) => tag,
_ => return,
};
#[cfg(feature = "metadata")]
if ctx.metadata_wants.structured_data
&& let Some(collector) = ctx.metadata_collector.as_ref()
&& let Some(json) = json_ld_from_tag(node_handle.get_inner(), tag, parser, &ctx.kept_scripts)
{
collector.borrow_mut().add_json_ld(json);
}
}
fn handle_math(
node_handle: &NodeHandle,
parser: &Parser,
output: &mut String,
options: &ConversionOptions,
ctx: &Context,
dom_ctx: &DomContext,
) {
let text_content = crate::converter::get_text_content(node_handle, parser, dom_ctx)
.trim()
.to_string();
if text_content.is_empty() {
return;
}
let escaped_text = escape(
&text_content,
options.escape_misc,
options.escape_asterisks,
options.escape_underscores,
options.escape_ascii,
);
let Some(node) = node_handle.get(parser) else { return };
let tag = match node {
tl::Node::Tag(tag) => tag,
_ => return,
};
let is_display_block = tag
.attributes()
.get("display")
.flatten()
.is_some_and(|v| v.as_utf8_str() == "block");
if is_display_block && !ctx.in_paragraph && !ctx.convert_as_inline {
output.push_str("\n\n");
}
output.push_str(&escaped_text);
if is_display_block && !ctx.in_paragraph && !ctx.convert_as_inline {
output.push_str("\n\n");
}
}
#[cfg(all(test, feature = "metadata"))]
mod tests {
use super::json_ld_from_tag;
use crate::converter::utility::preprocessing::strip_script_and_style_tags_with_kept_scripts;
#[test]
fn a_script_with_no_owner_mark_gives_its_text_with_nothing_decoded() {
let (_, kept_scripts) = strip_script_and_style_tags_with_kept_scripts("");
let page = r#"<script type="application/ld+json">{"a":"<"}</script>"#;
let dom = tl::parse(page, tl::ParserOptions::default()).expect("the page");
let tag = dom.nodes()[0].as_tag().expect("the script");
let json = json_ld_from_tag(0, tag, dom.parser(), &kept_scripts);
assert_eq!(json.as_deref(), Some(r#"{"a":"<"}"#));
}
}