use super::dom::{Dom, Id, Kind, Space};
use url::Url;
const DESCEND_SHARE_RATIO: f32 = 0.7;
const LOST_SHARE_MAX_RATIO: f32 = 0.01;
const LONG_PARAGRAPH_CHARS: usize = 80;
const TEASER_MAX_CHARS: usize = 300;
const TEASER_LABEL_CHARS: usize = 40;
const LINK_PARAGRAPH_MIN_CHARS: usize = 30;
const TEASERS_MIN_ARTICLE_CHARS: usize = 500;
const TRAILING_MAX_SHARE_RATIO: f32 = 0.15;
const WIDGET_LINK_SHARE_RATIO: f32 = 0.5;
const BEFORE_TITLE_MAX_CHARS: usize = 100;
const REPEATED_BLOCK_MIN_CHARS: usize = 10;
const CALL_TO_ACTION_MAX_CHARS: usize = 200;
const SEPARATORS: [char; 4] = ['|', '·', '•', '/'];
const COMMENT_LINK_MAX_CHARS: usize = 30;
const BYLINE_WORDS: [&str; 5] = ["by", "von", "par", "por", "bởi"];
const COUNT_MAX_CHARS: usize = 20;
const NO_ARTICLE_MAX_CHARS: usize = 200;
const SENTENCE_HEADING_CHARS: usize = 100;
const CLUTTER_MAX_SHARE_RATIO: f32 = 0.5;
const SURE_CLUTTER_WORDS: usize = 2;
pub(crate) const MIN_PICTURE_PX: f32 = 48.0;
const PREFERRED_PICTURE_WIDTH_PX: f32 = 1600.0;
const MAX_PICTURE_WIDTH_PX: f32 = 624.0;
const PLACEHOLDER_DATA_URL_CHARS: usize = 512;
const SELF_LINK_MARKS: [&str; 6] = ["", "¶", "#", "§", "🔗", "\u{1f517}"];
const HEADINGS: [&str; 6] = ["h1", "h2", "h3", "h4", "h5", "h6"];
const ICON_WORDS: [&str; 10] = [
"icon", "icons", "logo", "logos", "avatar", "avt", "avata", "emoji", "sprite", "favicon",
];
const ICON_ANCESTORS: usize = 2;
const TAILWIND_STEP_PX: f32 = 4.0;
const REM_PX: f32 = 16.0;
const MAX_AUTHORS: usize = 30;
const MAX_AUTHOR_CHARS: usize = 80;
const MAX_SITE_NAME_CHARS: usize = 40;
const REMOVED: [&str; 26] = [
"script", "style", "template", "iframe", "object", "embed", "applet", "video", "audio", "canvas", "button",
"input", "select", "textarea", "option", "datalist", "dialog", "nav", "menu", "link", "meta", "base", "param",
"track", "aside", "frameset",
];
const CLUTTER_ROLES: [&str; 15] = [
"navigation",
"banner",
"contentinfo",
"complementary",
"search",
"dialog",
"alertdialog",
"menu",
"menubar",
"toolbar",
"tablist",
"button",
"alert",
"status",
"tooltip",
];
const CLUTTER_WORDS: [&str; 42] = [
"ad",
"ads",
"adsbygoogle",
"ambox",
"advert",
"advertisement",
"advertising",
"breadcrumb",
"breadcrumbs",
"comment",
"comments",
"consent",
"disclaimer",
"cookie",
"cookies",
"disqus",
"editsection",
"feedback",
"keyboard",
"gdpr",
"modal",
"navbox",
"newsletter",
"outbrain",
"paywall",
"popup",
"promo",
"recommendations",
"related",
"share",
"sharing",
"sidebar",
"bio",
"skyscraper",
"social",
"sponsor",
"sponsored",
"subscribe",
"taboola",
"tags",
"toolbar",
"catlinks",
];
const WEAK_CLUTTER_WORDS: [&str; 12] = [
"banner",
"footer",
"header",
"masthead",
"menu",
"nav",
"navbar",
"navigation",
"noprint",
"pager",
"pagination",
"subscription",
];
const CITED_TITLE_MAX_CHARS: usize = 100;
const REFERENCE_SERVICES: [&str; 17] = [
"google scholar",
"pubmed",
"pubmed/ncbi",
"pmc free article",
"pubmed central",
"europe pmc",
"crossref",
"view article",
"article",
"ads",
"mathscinet",
"cas",
"isi",
"web of science",
"scopus",
"math review",
"zbmath",
];
const LINK_LIST_WORDS: [&str; 2] = ["toc", "download"];
const INLINE_ELEMENTS: [&str; 10] = ["span", "i", "b", "em", "strong", "cite", "small", "abbr", "q", "time"];
const CLUTTER_IDS: [&str; 1] = ["secondary"];
const AUTHOR_LINE_MAX_CHARS: usize = 200;
const AUTHOR_BOX_MAX_CHARS: usize = 1000;
const AUTHOR_PATHS: [&str; 4] = ["/author/", "/authors/", "/tac-gia/", "/tacgia/"];
const LEAD_WORDS: [&str; 6] = ["sapo", "lead", "standfirst", "summary", "dek", "excerpt"];
const CONTENT_WORDS: [&str; 7] = ["article", "body", "content", "entry", "main", "post", "story"];
const HIDDEN_CLASSES: [&str; 10] = [
"sr-only",
"visually-hidden",
"visuallyhidden",
"screen-reader-text",
"screenreader-only",
"a11y-hidden",
"hidden",
"d-none",
"is-hidden",
"skip-link",
];
const NEVER_CLUTTER: [&str; 12] = [
"html", "body", "main", "article", "a", "th", "td", "tr", "thead", "tbody", "tfoot", "caption",
];
const CONTAINERS: [&str; 13] = [
"body", "div", "main", "article", "section", "span", "form", "center", "font", "table", "tbody", "tr", "td",
];
const LAZY_SOURCES: [&str; 5] = [
"data-src",
"data-lazy-src",
"data-original",
"data-url",
"data-hi-res-src",
];
const MAX_FALLBACKS: usize = 2;
pub(crate) const FALLBACK_ATTR: &str = "data-kakemono-fallback";
const SRCSETS: [&str; 3] = ["srcset", "data-srcset", "data-lazy-srcset"];
const UNDRAWN_TYPES: [&str; 3] = ["image/avif", "image/jxl", "image/heic"];
pub(crate) enum Base<'a> {
None,
File(&'a Url),
Url(&'a Url),
}
pub(crate) struct Article {
pub(crate) root: Id,
pub(crate) styles: Vec<Id>,
pub(crate) sheets: Vec<Id>,
pub(crate) title: Option<String>,
pub(crate) authors: Vec<String>,
pub(crate) lang: Option<String>,
}
pub(crate) fn article(dom: &mut Dom, base: &Base<'_>) -> Article {
let (html, head, body) = dom.html_head_body();
let body = body.or(html).unwrap_or(0);
let lang = html
.and_then(|html| dom.attr(html, "lang").or_else(|| dom.attr(html, "xml:lang")))
.map(str::to_string);
let meta = Meta::read(dom, head);
let mut styles = Vec::new();
let mut sheets = Vec::new();
for node in dom.descendants(0) {
if dom.is(node, "style") {
styles.push(node);
} else if dom.is(node, "link")
&& dom.attr(node, "rel").is_some_and(|rel| {
rel.split_whitespace()
.any(|word| word.eq_ignore_ascii_case("stylesheet"))
})
{
sheets.push(node);
}
}
for &node in styles.iter().chain(&sheets) {
dom.detach(node);
}
for &sheet in &sheets {
if let Some(href) = dom.attr(sheet, "href").map(str::to_string) {
dom.set_attr(sheet, "href", &absolute(&href, base));
}
}
pictures(dom, body, base);
let lead = lead_picture(dom, body, &meta, base);
remove_clutter(dom, body);
let (root, trailing) = find_root(dom, body);
for node in trailing {
dom.detach(node);
}
let root = without_article(dom, root, &meta);
if let Some(lead) = lead {
place_lead_picture(dom, root, lead);
}
remove_teasers(dom, root, base, &meta);
teaser_title(dom, root, &meta);
before_title(dom, root);
repeated_links(dom, root);
repeated_blocks(dom, root);
comment_links(dom, root);
remove_counts(dom, root);
reference_links(dom, root);
item_labels(dom, root);
citations(dom, root);
heading_self_links(dom, root);
author_lines(dom, root, &meta);
sentence_headings(dom, root);
split_at_double_breaks(dom, root);
trailing_headings(dom, root);
let title = title(dom, body, root, &meta);
absolute_links(dom, root, base);
remove_icons(dom, root);
Article {
root,
styles,
sheets,
title,
authors: meta.authors,
lang,
}
}
struct Meta {
page_title: Option<String>,
meta_title: Option<String>,
authors: Vec<String>,
description: Option<String>,
url: Option<String>,
image: Option<String>,
}
impl Meta {
fn read(dom: &Dom, head: Option<Id>) -> Meta {
let scope = head.unwrap_or(0);
let metas: Vec<(String, String)> = dom
.find_all(scope, "meta")
.into_iter()
.filter_map(|meta| {
let key = dom.attr(meta, "name").or_else(|| dom.attr(meta, "property"))?;
let content = dom.attr(meta, "content")?.trim();
(!content.is_empty()).then(|| (key.to_ascii_lowercase(), content.to_string()))
})
.collect();
let first = |keys: &[&str]| {
keys.iter().find_map(|key| {
metas
.iter()
.find(|(name, _)| name == key)
.map(|(_, value)| value.clone())
})
};
let meta_title = first(&["citation_title", "og:title", "twitter:title", "dc.title"]);
let page_title = dom
.find(scope, "title")
.map(|title| dom.clean_text(title))
.filter(|title| !title.is_empty())
.map(|title| without_site_name(&title));
let mut authors: Vec<String> = metas
.iter()
.filter(|(name, _)| name == "citation_author" || name == "dc.creator")
.map(|(_, value)| value.clone())
.collect();
if authors.is_empty()
&& let Some(names) = first(&["author", "article:author", "parsely-author", "sailthru.author"])
{
authors = names
.split([',', ';', '|'])
.flat_map(|part| part.split(" and "))
.map(|name| name.trim().to_string())
.collect();
}
let site = site_names(dom, scope, &first);
authors.retain(|name| {
let lower = name.to_lowercase();
!name.is_empty()
&& name.chars().count() <= MAX_AUTHOR_CHARS
&& !name.contains("://")
&& !name.contains('@')
&& !(name.contains('.') && !name.contains(char::is_whitespace))
&& !site
.iter()
.any(|site| site.trim() == lower || format!(" {site} ").contains(&format!(" {lower} ")))
});
authors.dedup();
authors.truncate(MAX_AUTHORS);
let description = first(&["og:description", "description", "twitter:description"]);
let canonical = dom.find_all(scope, "link").into_iter().find_map(|link| {
let rel = dom.attr(link, "rel")?;
rel.eq_ignore_ascii_case("canonical")
.then(|| dom.attr(link, "href"))
.flatten()
.map(str::to_string)
});
let url = first(&["og:url"]).or(canonical);
let image = first(&["og:image", "twitter:image"]);
Meta {
page_title,
meta_title,
authors,
description,
url,
image,
}
}
}
fn site_names(dom: &Dom, scope: Id, first: &dyn Fn(&[&str]) -> Option<String>) -> Vec<String> {
let mut site: Vec<String> = first(&["og:site_name", "application-name"])
.into_iter()
.chain(
dom.find(scope, "title")
.and_then(|title| site_name(&dom.clean_text(title)).map(str::to_string)),
)
.map(|name| name.to_lowercase())
.collect();
let domain = first(&["og:url"]).or_else(|| first(&["og:site_name"])).and_then(|url| {
let host = url
.split("://")
.last()?
.split('/')
.next()?
.trim_start_matches("www.")
.to_lowercase();
host.split('.').next().map(|label| format!(" {label}"))
});
site.extend(domain);
let holder = first(&["copyright"]).and_then(|text| {
let text = text.to_lowercase();
let mark = |ch: char| ch == '©' || ch.is_ascii_digit() || ch.is_whitespace();
let text = text
.trim_start_matches(mark)
.trim_start_matches("copyright")
.trim_start_matches(mark);
let holder = SITE_SEPARATORS
.iter()
.filter_map(|separator| text.split_once(separator).map(|(holder, _)| holder))
.min_by_key(|holder| holder.len())
.unwrap_or(text)
.trim();
(!holder.is_empty()).then(|| holder.to_string())
});
site.extend(holder);
site
}
const SITE_SEPARATORS: [&str; 7] = [" | ", " - ", " – ", " — ", " \\ ", " · ", " :: "];
fn without_site_name(title: &str) -> String {
for separator in SITE_SEPARATORS {
if let Some((page, site)) = title.rsplit_once(separator)
&& site.chars().count() <= MAX_SITE_NAME_CHARS
&& !page.trim().is_empty()
{
return page.trim().to_string();
}
}
title.to_string()
}
fn site_name(title: &str) -> Option<&str> {
SITE_SEPARATORS.iter().find_map(|separator| {
let (page, site) = title.rsplit_once(separator)?;
(site.chars().count() <= MAX_SITE_NAME_CHARS && !page.trim().is_empty()).then(|| site.trim())
})
}
fn title(dom: &mut Dom, body: Id, root: Id, meta: &Meta) -> Option<String> {
if let Some(h1) = dom.find(root, "h1") {
let text = dom.clean_text(h1);
if !text.is_empty() {
dom.add_class(h1, "title");
repeated_title(dom, root, h1, &text);
return Some(text);
}
}
let known = [&meta.meta_title, &meta.page_title];
let outer = dom
.find(body, "h1")
.map(|h1| (h1, dom.clean_text(h1)))
.filter(|(h1, text)| {
let same_article = dom
.ancestor(*h1, |id| dom.is_any(id, &["article", "main"]))
.is_some_and(|ancestor| dom.contains(ancestor, root));
let is_title = known
.iter()
.any(|title| title.as_deref().is_some_and(|title| same_text(title, text)));
!text.is_empty() && (same_article || is_title)
});
if let Some((_, text)) = outer {
let text = known
.iter()
.find_map(|title| {
title
.as_deref()
.filter(|title| same_text(title, &text) && text.to_uppercase() == text)
})
.map_or(text.clone(), str::to_string);
let heading = dom.element("h1", &[("class", "title")]);
let words = dom.text_node(&text);
dom.append(heading, words);
dom.insert(root, 0, heading);
repeated_title(dom, root, heading, &text);
return Some(text);
}
meta.meta_title.clone().or_else(|| meta.page_title.clone())
}
fn author_lines(dom: &mut Dom, root: Id, meta: &Meta) {
if meta.authors.is_empty() {
return;
}
for node in dom.descendants(root) {
let front =
dom.has_class(node, "author") || dom.descendants(node).iter().any(|&id| dom.has_class(id, "author"));
if !dom.attached(node) || !dom.is_any(node, &["p", "div"]) || dom.find(node, "img").is_some() || front {
continue;
}
let mut rest = dom.clean_text(node);
if rest.trim().is_empty() || rest.chars().count() > AUTHOR_LINE_MAX_CHARS {
continue;
}
for name in &meta.authors {
rest = rest.replace(name.as_str(), " ");
}
let words: Vec<String> = rest
.split(|ch: char| !ch.is_alphanumeric())
.filter(|word| !word.is_empty())
.map(str::to_lowercase)
.collect();
let only_names = words
.iter()
.all(|word| word == "and" || BYLINE_WORDS.contains(&word.as_str()));
if only_names && rest.len() < dom.clean_text(node).len() {
dom.detach(node);
}
}
}
fn trailing_headings(dom: &mut Dom, root: Id) {
loop {
let last = dom
.descendants(root)
.into_iter()
.rev()
.find(|&id| match &dom.nodes[id].kind {
Kind::Text(text) => !text.trim().is_empty(),
Kind::Element { .. } => dom.is_any(id, &["img", "svg", "video", "iframe", "table", "math"]),
_ => false,
});
let Some(heading) = last.and_then(|last| {
dom.ancestor(last, |id| dom.is_any(id, &["h2", "h3", "h4", "h5", "h6"]))
.filter(|&heading| dom.contains(root, heading))
}) else {
return;
};
dom.detach(heading);
}
}
fn teaser_title(dom: &mut Dom, root: Id, meta: &Meta) {
let Some(h1) = dom.find(root, "h1") else {
return;
};
let in_link = dom
.ancestor(h1, |id| dom.is(id, "a"))
.is_some_and(|link| dom.attr(link, "href").is_some_and(|href| !href.trim().starts_with('#')));
let text = dom.clean_text(h1);
let other = meta
.meta_title
.as_deref()
.or(meta.page_title.as_deref())
.is_some_and(|title| !title.trim().is_empty() && !same_text(title, &text));
if in_link && other {
dom.rename(h1, "h2");
}
}
fn repeated_title(dom: &mut Dom, root: Id, h1: Id, title: &str) {
let inside = dom.descendants(h1);
let Some(text) = dom
.descendants(root)
.into_iter()
.skip_while(|&id| id != h1)
.filter(|id| !inside.contains(id))
.find(|&id| matches!(&dom.nodes[id].kind, Kind::Text(text) if !text.trim().is_empty()))
else {
return;
};
let block = dom.ancestor(text, |id| dom.is_any(id, &["p", "div", "h2", "h3", "h4", "h5", "h6"]));
if let Some(block) = block
&& block != root
&& dom.contains(root, block)
&& same_text(&dom.clean_text(block), title)
{
dom.detach(block);
}
}
fn same_text(one: &str, other: &str) -> bool {
let key = |text: &str| text.split_whitespace().collect::<Vec<_>>().join(" ").to_lowercase();
key(one) == key(other)
}
fn words(value: &str) -> impl Iterator<Item = String> {
value
.split(|ch: char| !ch.is_alphanumeric())
.filter(|word| !word.is_empty())
.map(str::to_lowercase)
}
fn clutter_words(dom: &Dom, node: Id) -> usize {
let names = format!(
"{} {}",
dom.attr(node, "class").unwrap_or_default(),
dom.attr(node, "id").unwrap_or_default()
);
let mut found: Vec<String> = words(&names)
.filter(|word| CLUTTER_WORDS.contains(&word.as_str()))
.collect();
found.sort();
found.dedup();
found.len()
}
fn is_heading_box(dom: &Dom, node: Id) -> bool {
if dom.is_any(node, &["h2", "h3", "h4", "h5", "h6"]) {
return true;
}
let text = dom.clean_text(node);
!text.is_empty()
&& dom.ancestor(node, |id| dom.is(id, "a")).is_some()
&& ["h2", "h3", "h4"]
.iter()
.flat_map(|name| dom.find_all(node, name))
.any(|heading| dom.clean_text(heading) == text)
}
fn has_hidden_class(dom: &Dom, node: Id) -> bool {
dom.classes(node).any(|class| {
let class = class.to_ascii_lowercase();
HIDDEN_CLASSES.iter().any(|hidden| {
class == *hidden
|| (hidden.contains('-') && class.strip_suffix(hidden).is_some_and(|rest| rest.ends_with('-')))
})
})
}
fn is_clutter_by_name(dom: &Dom, node: Id) -> bool {
let mut names = String::new();
names.push_str(dom.attr(node, "class").unwrap_or_default());
names.push(' ');
names.push_str(dom.attr(node, "id").unwrap_or_default());
names.push(' ');
names.push_str(dom.attr(node, "data-role").unwrap_or_default());
if has_hidden_class(dom, node) && !dom.is_any(node, &["h2", "h3", "h4", "h5", "h6"]) {
return true;
}
if dom
.attr(node, "id")
.is_some_and(|id| CLUTTER_IDS.contains(&id.to_ascii_lowercase().as_str()))
{
return true;
}
let words: Vec<String> = words(&names).collect();
let has = |list: &[&str]| words.iter().any(|word| list.contains(&word.as_str()));
if has(&LINK_LIST_WORDS) && link_share(dom, node) >= WIDGET_LINK_SHARE_RATIO {
return true;
}
let inline = dom.is_any(node, &INLINE_ELEMENTS)
&& !has(&["noprint"])
&& dom.nodes[node]
.parent
.is_some_and(|parent| dom.has_text_outside(parent, |id| id == node));
has(&CLUTTER_WORDS) || (has(&WEAK_CLUTTER_WORDS) && !has(&CONTENT_WORDS) && !is_heading_box(dom, node) && !inline)
}
fn is_hidden(dom: &Dom, node: Id) -> bool {
if dom.attr(node, "hidden").is_some() {
return true;
}
dom.attr(node, "style").is_some_and(|style| {
let style: String = style
.chars()
.filter(|ch| !ch.is_whitespace())
.collect::<String>()
.to_ascii_lowercase();
style.contains("display:none")
})
}
fn text_weights(dom: &Dom, root: Id) -> Vec<usize> {
let mut weight = vec![0; dom.nodes.len()];
for node in dom.descendants(root).into_iter().rev() {
weight[node] = match &dom.nodes[node].kind {
Kind::Text(text) => text.chars().filter(|ch| !ch.is_whitespace()).count(),
Kind::Element { .. } if dom.is_any(node, &["a", "script", "style", "template", "noscript"]) => 0,
_ => dom.nodes[node].children.iter().map(|&child| weight[child]).sum(),
};
}
weight
}
fn remove_clutter(dom: &mut Dom, body: Id) {
let calls = calls_to_action(dom, body);
let weight = text_weights(dom, body);
let total = weight[body].max(1);
let main_h1 = dom.find(body, "h1");
let size = dom.nodes.len();
let mut holds_title = vec![false; size];
let mut at = main_h1;
while let Some(id) = at {
holds_title[id] = true;
at = dom.nodes[id].parent;
}
let mut in_heading = vec![false; size];
let mut in_article = vec![false; size];
let mut gone = vec![false; size];
let mut removed: Vec<Id> = Vec::new();
for node in dom.descendants(body) {
if node == body || node >= size {
continue;
}
let parent = dom.nodes[node].parent.filter(|&parent| parent < size);
if let Some(parent) = parent {
gone[node] = gone[parent];
in_heading[node] = in_heading[parent] || dom.is_any(parent, &["h1", "h2", "h3", "h4", "h5", "h6"]);
in_article[node] = in_article[parent] || dom.is_any(parent, &["article", "main"]);
}
if gone[node] || (parent.is_none() && !dom.attached(node)) {
continue;
}
let Kind::Element { name, space, .. } = &dom.nodes[node].kind else {
continue;
};
if *space != Space::Html {
let decoration = dom.attr(node, "aria-hidden") == Some("true");
if *space == Space::Svg && (is_hidden(dom, node) || decoration) {
gone[node] = true;
removed.push(node);
}
continue;
}
let name = name.clone();
if name == "noscript" {
noscript(dom, node);
continue;
}
if name == "form" {
dom.unwrap(node);
continue;
}
let place = Place {
holds_title: holds_title[node],
in_heading: in_heading[node],
in_article: in_article[node],
share: weight[node] as f32 / total as f32,
};
let remove = is_clutter(dom, node, &name, &place);
if remove {
gone[node] = true;
removed.push(node);
}
}
removed.extend(calls);
dom.detach_all(&removed);
}
struct Place {
holds_title: bool,
in_heading: bool,
in_article: bool,
share: f32,
}
fn is_clutter(dom: &Dom, node: Id, name: &str, place: &Place) -> bool {
let role_clutter = is_tooltip(dom, node)
|| dom.attr(node, "role").is_some_and(|role| {
role.split_whitespace()
.any(|role| CLUTTER_ROLES.contains(&role.to_ascii_lowercase().as_str()))
});
let named_clutter = (!NEVER_CLUTTER.contains(&name)
&& !place.in_heading
&& (place.share <= CLUTTER_MAX_SHARE_RATIO || clutter_words(dom, node) >= SURE_CLUTTER_WORDS)
&& is_clutter_by_name(dom, node))
|| (name == "a" && has_hidden_class(dom, node));
let landmark = matches!(name, "header" | "footer") && !place.in_article;
let hidden = is_hidden(dom, node) && !place.holds_title && place.share <= CLUTTER_MAX_SHARE_RATIO;
let notes = dom.attr(node, "role").is_some_and(|role| role.starts_with("doc-"));
(REMOVED.contains(&name) && !notes)
|| hidden
|| ((role_clutter || named_clutter || landmark) && !place.holds_title)
|| (name == "footer" && !place.holds_title)
}
fn calls_to_action(dom: &Dom, body: Id) -> Vec<Id> {
let mut boxes: Vec<Id> = Vec::new();
for node in dom.descendants(body) {
let button = dom.is(node, "button")
|| dom
.attr(node, "role")
.is_some_and(|role| role.trim().eq_ignore_ascii_case("button"));
if !button {
continue;
}
let Some(block) = dom.ancestor(node, |id| id != node && dom.is_any(id, &["div", "section", "aside"])) else {
continue;
};
if block == body || boxes.contains(&block) {
continue;
}
let shown = |id: Id| {
dom.ancestor(id, |up| {
dom.contains(block, up) && (dom.is(up, "aside") || dom.attr(up, "aria-hidden") == Some("true"))
})
.is_none()
};
let text: usize = dom
.descendants(block)
.into_iter()
.filter(|&id| shown(id))
.map(|id| match &dom.nodes[id].kind {
Kind::Text(text) => text.chars().filter(|ch| !ch.is_whitespace()).count(),
_ => 0,
})
.sum();
let content = dom.descendants(block).into_iter().filter(|&id| shown(id)).any(|id| {
dom.is_any(
id,
&[
"img", "picture", "figure", "video", "table", "pre", "code", "h1", "h2", "h3", "math",
],
) || (dom.is(id, "p")
&& dom.ancestor(id, |up| up == node).is_none()
&& dom.clean_text(id).chars().count() >= CALL_TO_ACTION_MAX_CHARS)
});
if text <= CALL_TO_ACTION_MAX_CHARS && !content {
boxes.push(block);
}
}
boxes
}
fn noscript(dom: &mut Dom, node: Id) {
let Some(img) = dom.find(node, "img") else {
dom.detach(node);
return;
};
let lazy = dom.nodes[node].parent.and_then(|parent| {
dom.find_all(parent, "img")
.into_iter()
.find(|&other| !dom.contains(node, other))
});
match lazy {
Some(lazy) => {
let has_source = dom.attr(lazy, "src").is_some_and(|src| !is_placeholder(src));
if !has_source && let Some(src) = dom.attr(img, "src").map(str::to_string) {
dom.set_attr(lazy, "src", &src);
}
dom.detach(node);
}
None => {
dom.insert_after(node, img);
dom.detach(node);
}
}
}
fn is_placeholder(src: &str) -> bool {
let src = src.trim();
src.is_empty() || (src.starts_with("data:") && src.len() <= PLACEHOLDER_DATA_URL_CHARS)
}
fn find_root(dom: &Dom, body: Id) -> (Id, Vec<Id>) {
let weight = text_weights(dom, body);
let mut at = body;
let mut trailing = Vec::new();
loop {
let total = weight[at];
let children = dom.element_children(at);
let Some(&best) = children.iter().max_by_key(|&&child| weight[child]) else {
break;
};
if !dom.is_any(best, &CONTAINERS) || (weight[best] as f32) < DESCEND_SHARE_RATIO * total as f32 {
break;
}
let lost = total - weight[best];
let lost_matters = dom.nodes[at].children.iter().any(|&child| {
child != best
&& match &dom.nodes[child].kind {
Kind::Text(text) => text.trim().chars().count() >= LONG_PARAGRAPH_CHARS,
_ => has_article_text(dom, child),
}
});
if lost_matters && lost as f32 >= LOST_SHARE_MAX_RATIO * total as f32 {
let chars = |node: Id| dom.clean_text(node).chars().filter(|ch| !ch.is_whitespace()).count() as f32;
let all = chars(at);
let children = &dom.nodes[at].children;
let after = children.iter().skip_while(|&&child| child != best).skip(1);
trailing = after
.copied()
.filter(|&child| {
(weight[child] as f32) < TRAILING_MAX_SHARE_RATIO * total as f32
&& chars(child) < TRAILING_MAX_SHARE_RATIO * all
&& (is_widget(dom, child) || is_author_box(dom, child))
})
.collect();
break;
}
at = best;
}
if dom.is_any(at, &["tbody", "thead", "tfoot", "tr"])
&& let Some(table) = dom.ancestor(at, |id| dom.is(id, "table"))
{
at = table;
}
(at, trailing)
}
fn reference_links(dom: &mut Dom, root: Id) {
for link in dom.find_all(root, "a") {
let text = dom.clean_text(link).to_lowercase();
if !REFERENCE_SERVICES.contains(&text.trim())
|| dom.ancestor(link, |id| dom.is(id, "li")).is_none()
|| dom.find(link, "img").is_some()
{
continue;
}
let Some(parent) = dom.nodes[link].parent else {
continue;
};
let siblings = &dom.nodes[parent].children;
let at = siblings.iter().position(|&child| child == link).unwrap_or_default();
let before = at.checked_sub(1).and_then(|index| siblings.get(index)).copied();
let after = siblings.get(at + 1).copied();
let opens = before.is_some_and(
|before| matches!(&dom.nodes[before].kind, Kind::Text(text) if text.trim_end().ends_with('[')),
);
let closes =
after.is_some_and(|after| matches!(&dom.nodes[after].kind, Kind::Text(text) if text.starts_with(']')));
if opens
&& closes
&& let (Some(before), Some(after)) = (before, after)
{
if let Kind::Text(text) = &mut dom.nodes[before].kind {
*text = text.trim_end().trim_end_matches('[').to_string();
}
if let Kind::Text(text) = &mut dom.nodes[after].kind {
*text = text.trim_start_matches(']').to_string();
}
}
dom.detach(link);
let mut empty = parent;
while !dom.is(empty, "li")
&& dom.clean_text(empty).is_empty()
&& dom.find(empty, "img").is_none()
&& let Some(up) = dom.nodes[empty].parent
{
dom.detach(empty);
empty = up;
}
}
}
fn citations(dom: &mut Dom, root: Id) {
for cite in dom.find_all(root, "cite") {
let styled = ["i", "em", "b"].iter().any(|name| dom.find(cite, name).is_some());
if styled || dom.clean_text(cite).chars().count() > CITED_TITLE_MAX_CHARS {
dom.unwrap(cite);
}
}
}
fn item_labels(dom: &mut Dom, root: Id) {
for item in dom.find_all(root, "li") {
let Some(&first) = dom.nodes[item]
.children
.iter()
.find(|&&child| !matches!(&dom.nodes[child].kind, Kind::Text(text) if text.trim().is_empty()))
else {
continue;
};
if !matches!(dom.nodes[first].kind, Kind::Element { .. }) || dom.is(first, "a") {
continue;
}
let label = dom.clean_text(first);
let number = label.trim_end_matches(['.', ')']);
if number.is_empty() || !number.chars().all(|ch| ch.is_ascii_digit()) {
continue;
}
let numbered = dom.nodes[item].parent.is_some_and(|list| dom.is(list, "ol"));
if numbered {
dom.detach(first);
} else {
let space = dom.text_node(" ");
dom.insert_after(first, space);
}
}
}
fn is_tooltip(dom: &Dom, node: Id) -> bool {
let Kind::Element { attrs, .. } = &dom.nodes[node].kind else {
return false;
};
attrs.iter().any(|(name, value)| {
let name = name.to_ascii_lowercase();
name.starts_with("data-") && name.contains("tooltip") && value.to_ascii_lowercase().contains("target")
})
}
fn link_share(dom: &Dom, node: Id) -> f32 {
let all = dom.clean_text(node).chars().filter(|ch| !ch.is_whitespace()).count();
let linked: usize = dom
.find_all(node, "a")
.into_iter()
.filter(|&a| dom.ancestor(a, |up| dom.is(up, "a")).is_none())
.map(|a| dom.clean_text(a).chars().filter(|ch| !ch.is_whitespace()).count())
.sum();
if all == 0 { 1.0 } else { linked as f32 / all as f32 }
}
fn is_widget(dom: &Dom, node: Id) -> bool {
if !matches!(dom.nodes[node].kind, Kind::Element { .. }) {
return false;
}
let list_of_links = link_share(dom, node) >= WIDGET_LINK_SHARE_RATIO;
!dom.descendants(node).into_iter().any(|id| match &dom.nodes[id].kind {
Kind::Text(text) => !list_of_links && text.trim().chars().count() >= LONG_PARAGRAPH_CHARS,
Kind::Element { .. } => {
let picture = dom.is_any(id, &["img", "picture", "figure"])
&& !is_icon(dom, id)
&& dom.ancestor(id, |up| dom.is(up, "a")).is_none()
&& !(dom.is(id, "figure") && dom.find(id, "a").is_some() && dom.find(id, "figcaption").is_none());
picture
|| dom.is_any(id, &["table", "ol", "pre", "h1", "math"])
|| (!list_of_links && dom.is(id, "p") && dom.clean_text(id).chars().count() >= LONG_PARAGRAPH_CHARS)
|| dom.attr(id, "role").is_some_and(|role| role.starts_with("doc-"))
}
_ => false,
})
}
fn is_author_box(dom: &Dom, node: Id) -> bool {
if !matches!(dom.nodes[node].kind, Kind::Element { .. })
|| dom.clean_text(node).chars().count() > AUTHOR_BOX_MAX_CHARS
{
return false;
}
let author_link = dom.find_all(node, "a").into_iter().any(|a| {
dom.attr(a, "rel")
.is_some_and(|rel| rel.split_whitespace().any(|rel| rel.eq_ignore_ascii_case("author")))
|| dom.attr(a, "href").is_some_and(|href| {
let href = href.to_ascii_lowercase();
AUTHOR_PATHS.iter().any(|path| href.contains(path))
})
});
author_link
&& !dom
.descendants(node)
.into_iter()
.any(|id| dom.is_any(id, &["table", "ol", "pre", "h1", "figure"]))
}
fn lead_picture(dom: &Dom, body: Id, meta: &Meta, base: &Base<'_>) -> Option<Id> {
let image = absolute(meta.image.as_deref()?, base);
let file = |src: &str| {
let path = src.split(['?', '#']).next().unwrap_or(src);
path.rsplit('/').next().unwrap_or(path).to_ascii_lowercase()
};
let wanted = file(&image);
if wanted.is_empty() {
return None;
}
let img = dom
.find_all(body, "img")
.into_iter()
.find(|&img| dom.attr(img, "src").is_some_and(|src| file(src) == wanted))?;
let figure = dom
.ancestor(img, |id| dom.is(id, "figure"))
.filter(|&figure| dom.find_all(figure, "img").len() == 1);
Some(figure.unwrap_or(img))
}
fn place_lead_picture(dom: &mut Dom, root: Id, lead: Id) {
if dom.contains(root, lead) || dom.find(root, "img").is_some() || dom.contains(lead, root) {
return;
}
dom.detach(lead);
match dom.find(root, "h1") {
Some(h1) => dom.insert_after(h1, lead),
None => dom.insert(root, 0, lead),
}
}
fn without_article(dom: &mut Dom, root: Id, meta: &Meta) -> Id {
let Some(description) = &meta.description else {
return root;
};
let text = dom.clean_text(root);
if has_article_text(dom, root) || text.chars().count() > NO_ARTICLE_MAX_CHARS || description.len() <= text.len() {
return root;
}
let article = dom.element("div", &[]);
if let Some(h1) = dom.find(root, "h1") {
dom.append(article, h1);
}
let para = dom.element("p", &[]);
let words = dom.text_node(description);
dom.append(para, words);
dom.append(article, para);
if dom.nodes[root].parent.is_some() {
dom.insert_after(root, article);
dom.detach(root);
}
article
}
fn remove_teasers(dom: &mut Dom, root: Id, base: &Base<'_>, meta: &Meta) {
let weight = text_weights(dom, root);
if weight[root] < TEASERS_MIN_ARTICLE_CHARS {
return;
}
let own = meta.url.as_deref().and_then(|url| Url::parse(url).ok());
let address = match base {
Base::Url(url) => Some(*url),
_ => own.as_ref(),
};
let site = address
.and_then(Url::host_str)
.map(|host| host.trim_start_matches("www.").to_ascii_lowercase());
for node in dom.descendants(root) {
if node == root || !dom.attached(node) || dom.find(node, "h1").is_some() {
continue;
}
if let Some(teaser) = teaser(dom, root, node, &weight, site.as_deref()) {
dom.detach(teaser);
}
}
}
fn teaser(dom: &Dom, root: Id, node: Id, weight: &[usize], site: Option<&str>) -> Option<Id> {
let other_page = |node: Id| links_to_site(dom, node, site);
if dom.is(node, "article") {
return (weight[node] < TEASER_MAX_CHARS && other_page(node)).then_some(node);
}
if dom.is_any(node, &["div", "section"]) && weight[node] < TEASER_MAX_CHARS && is_link_box(dom, node) {
return other_page(node).then_some(node);
}
let link_paragraph = dom.is(node, "p")
&& weight[node] == 0
&& dom.find_all(node, "a").len() == 1
&& dom.find(node, "img").is_none()
&& dom.clean_text(node).chars().count() >= LINK_PARAGRAPH_MIN_CHARS
&& other_page(node);
if link_paragraph {
return Some(node);
}
let link_heading =
dom.is_any(node, &HEADINGS[1..]) && weight[node] == 0 && !dom.clean_text(node).is_empty() && other_page(node);
if !link_heading {
return None;
}
let mut teaser = node;
while let Some(parent) = dom.nodes[teaser].parent {
if parent == root || weight[parent] > TEASER_LABEL_CHARS || dom.find(parent, "h1").is_some() {
break;
}
teaser = parent;
}
Some(teaser)
}
fn links_to_site(dom: &Dom, node: Id, site: Option<&str>) -> bool {
dom.find_all(node, "a").into_iter().any(|a| {
dom.attr(a, "href").is_some_and(|href| {
let href = href.trim();
if href.is_empty() || href.contains('#') {
return false;
}
match Url::parse(href) {
Err(_) => true,
Ok(url) => url
.host_str()
.is_some_and(|host| site == Some(host.trim_start_matches("www.").to_ascii_lowercase().as_str())),
}
})
})
}
fn is_link_box(dom: &Dom, node: Id) -> bool {
let mut titles = 0;
let mut paragraphs = 0;
for &child in &dom.nodes[node].children {
match &dom.nodes[child].kind {
Kind::Text(text) if text.trim().is_empty() => {}
Kind::Element { .. } if dom.is(child, "a") => {
if dom.clean_text(child).chars().count() >= LINK_PARAGRAPH_MIN_CHARS {
titles += 1;
}
}
Kind::Element { .. } if dom.is_any(child, &["p", "div"]) && dom.find(child, "a").is_none() => {
paragraphs += 1
}
Kind::Element { .. } if dom.is_any(child, &["img", "picture", "figure"]) => {}
_ => return false,
}
}
titles == 1 && paragraphs <= 1
}
fn before_title(dom: &mut Dom, root: Id) {
let Some(h1) = dom.find(root, "h1") else {
return;
};
let mut at = h1;
while at != root {
let Some(parent) = dom.nodes[at].parent else {
break;
};
let before: Vec<Id> = dom.nodes[parent]
.children
.iter()
.copied()
.take_while(|&child| child != at)
.collect();
for node in before {
let picture = matches!(dom.nodes[node].kind, Kind::Element { .. })
&& dom
.descendants(node)
.into_iter()
.any(|id| dom.is_any(id, &["img", "picture", "figure", "svg"]));
let element = matches!(dom.nodes[node].kind, Kind::Element { .. });
let links = element && link_share(dom, node) >= WIDGET_LINK_SHARE_RATIO;
if !picture && (links || dom.clean_text(node).chars().count() <= BEFORE_TITLE_MAX_CHARS) {
dom.detach(node);
}
}
at = parent;
}
}
fn repeated_links(dom: &mut Dom, root: Id) {
let mut last: Option<String> = None;
for node in dom.descendants(root) {
if !dom.attached(node) {
continue;
}
match &dom.nodes[node].kind {
Kind::Text(text) if !text.trim().is_empty() => {
if dom.ancestor(node, |id| dom.is(id, "a")).is_none() {
last = None;
}
}
Kind::Element { .. } if dom.is(node, "a") => {
let text = dom.clean_text(node);
if text.is_empty() {
continue;
}
let href = dom.attr(node, "href").unwrap_or_default().trim();
let nowhere =
href.is_empty() || href.starts_with('#') || href.to_ascii_lowercase().starts_with("javascript:");
let link = if nowhere {
format!("text:{text}")
} else {
format!("href:{href}")
};
if last.as_ref() == Some(&link) {
dom.detach(node);
} else {
last = Some(link);
}
}
Kind::Element { .. } if dom.is_any(node, &["img", "figure", "table"]) => last = None,
_ => {}
}
}
}
fn repeated_blocks(dom: &mut Dom, root: Id) {
let mut last = String::new();
for node in dom.descendants(root) {
if node == root || !dom.attached(node) || !is_leaf_block(dom, node) {
continue;
}
let text = dom.clean_text(node);
if text.is_empty() {
continue;
}
if text == last && text.chars().count() >= REPEATED_BLOCK_MIN_CHARS {
dom.detach(node);
} else {
last = text;
}
}
}
fn is_leaf_block(dom: &Dom, node: Id) -> bool {
const BLOCKS: [&str; 10] = [
"p",
"figcaption",
"h2",
"h3",
"h4",
"h5",
"h6",
"blockquote",
"dd",
"dt",
];
const INLINE: [&str; 14] = [
"a", "span", "em", "strong", "i", "b", "time", "br", "code", "sup", "sub", "small", "abbr", "cite",
];
let is_block = dom.is_any(node, &BLOCKS) || dom.is(node, "div");
is_block
&& dom.nodes[node]
.children
.iter()
.all(|&child| match &dom.nodes[child].kind {
Kind::Element { .. } => {
dom.is_any(child, &INLINE)
&& dom
.descendants(child)
.into_iter()
.all(|id| !matches!(dom.nodes[id].kind, Kind::Element { .. }) || dom.is_any(id, &INLINE))
}
_ => true,
})
}
fn comment_links(dom: &mut Dom, root: Id) {
for link in dom.find_all(root, "a") {
let to_comments = dom.attr(link, "href").is_some_and(|href| {
href.split_once('#').is_some_and(|(_, fragment)| {
fragment.to_ascii_lowercase().starts_with("comment") || fragment == "respond"
})
});
if to_comments && dom.clean_text(link).chars().count() <= COMMENT_LINK_MAX_CHARS {
let before = dom.nodes[link].parent.and_then(|parent| {
let siblings = &dom.nodes[parent].children;
let at = siblings.iter().position(|&id| id == link)?;
siblings[..at]
.iter()
.rev()
.find(|&&id| !matches!(&dom.nodes[id].kind, Kind::Text(text) if text.trim().is_empty()))
.copied()
});
if let Some(before) = before {
let separator =
|text: &str| !text.trim().is_empty() && text.trim().chars().all(|ch| SEPARATORS.contains(&ch));
if let Kind::Text(text) = &mut dom.nodes[before].kind {
let kept = text.trim_end().trim_end_matches(SEPARATORS).trim_end().len();
text.truncate(kept);
} else if separator(&dom.clean_text(before)) {
dom.detach(before);
}
}
dom.detach(link);
}
}
}
fn remove_counts(dom: &mut Dom, root: Id) {
let mut gone = vec![false; dom.nodes.len()];
let mut removed = Vec::new();
let taken = |gone: &[bool], node: Id| {
let mut at = node;
loop {
if gone[at] {
return true;
}
match dom.nodes[at].parent {
Some(parent) => at = parent,
None => return at != 0,
}
}
};
for node in dom.descendants(root) {
if node == root || !dom.is_any(node, &["p", "div", "li"]) || taken(&gone, node) {
continue;
}
let kept = ["table", "pre", "code", "ol", "h1", "h2", "h3", "h4", "h5", "h6"];
if dom.ancestor(node, |id| dom.is_any(id, &kept)).is_some() {
continue;
}
let text = dom.clean_text(node);
if BYLINE_WORDS.contains(&text.to_lowercase().as_str()) {
gone[node] = true;
removed.push(node);
continue;
}
let count = text.chars().count() <= COUNT_MAX_CHARS
&& text.chars().any(|ch| ch.is_ascii_digit())
&& text.chars().all(|ch| ch.is_ascii_digit() || ch.is_whitespace());
let parent_too = || {
dom.nodes[node]
.parent
.is_some_and(|parent| parent != root && !dom.has_text_outside(parent, |id| id == node || gone[id]))
};
if count
&& !parent_too()
&& !dom
.descendants(node)
.into_iter()
.any(|id| dom.is_any(id, &["img", "svg"]))
{
gone[node] = true;
removed.push(node);
}
}
dom.detach_all(&removed);
}
fn has_article_text(dom: &Dom, node: Id) -> bool {
let weight = text_weights(dom, node);
dom.descendants(node).into_iter().any(|id| {
if weight[id] == 0 {
return false;
}
if dom.is_any(id, &HEADINGS[1..]) {
return !dom.clean_text(id).ends_with(':');
}
let lead = dom
.classes(id)
.any(|class| words(class).any(|word| LEAD_WORDS.contains(&word.as_str())));
(dom.is(id, "p") || lead) && dom.clean_text(id).chars().count() >= LONG_PARAGRAPH_CHARS
})
}
fn sentence_headings(dom: &mut Dom, root: Id) {
for heading in dom.descendants(root) {
if !dom.is_any(heading, &HEADINGS[1..]) {
continue;
}
let text = dom.clean_text(heading);
let sentence = text.ends_with(['.', '!', '?', '…']) && text.chars().count() >= SENTENCE_HEADING_CHARS;
if sentence {
dom.rename(heading, "p");
}
}
}
fn is_author_photo(dom: &Dom, img: Id) -> bool {
let is_author = |link: Id| {
dom.attr(link, "rel")
.is_some_and(|rel| rel.split_whitespace().any(|rel| rel.eq_ignore_ascii_case("author")))
};
dom.ancestor(img, |id| dom.is(id, "a")).is_some_and(|link| {
let href = dom.attr(link, "href").map(str::trim).unwrap_or_default();
is_author(link)
|| AUTHOR_PATHS.iter().any(|path| href.to_ascii_lowercase().contains(path))
|| (!href.is_empty()
&& dom.nodes[link].parent.is_some_and(|parent| {
let block = dom.ancestor(parent, |id| !dom.is_any(id, &INLINE_ELEMENTS) && !dom.is(id, "a")).unwrap_or(parent);
let around = dom.nodes[block].parent.unwrap_or(block);
dom.find_all(around, "a")
.into_iter()
.any(|other| other != link && is_author(other) && dom.attr(other, "href").map(str::trim) == Some(href))
}))
})
}
fn is_banner(dom: &Dom, img: Id, src: &str) -> bool {
let path = src.split(['?', '#']).next().unwrap_or(src);
let file = path.rsplit('/').next().unwrap_or(path);
if file.starts_with("data:") {
return false;
}
let mut names = words(file);
let first = names.next().is_some_and(|word| word.starts_with("banner"));
first || (dom.ancestor(img, |id| dom.is(id, "a")).is_some() && names.any(|word| word.starts_with("banner")))
}
fn pictures(dom: &mut Dom, body: Id, base: &Base<'_>) {
for img in dom.find_all(body, "img") {
let Some(src) = best_source(dom, img) else {
dom.detach(img);
continue;
};
let src = absolute(&src, base);
let others: Vec<String> = other_sources(dom, img, &src)
.into_iter()
.map(|other| absolute(&other, base))
.filter(|other| *other != src)
.take(MAX_FALLBACKS)
.collect();
if !others.is_empty() {
dom.set_attr(img, FALLBACK_ATTR, &others.join(" "));
}
dom.set_attr(img, "src", &src);
for key in SRCSETS.iter().chain(&LAZY_SOURCES).chain(&["sizes"]) {
dom.remove_attr(img, key);
}
let size = |key: &str| {
dom.attr(img, key)
.and_then(|value| value.trim().trim_end_matches("px").parse::<f32>().ok())
};
let (width, height) = (size("width"), size("height"));
if width.is_some_and(|width| width < MIN_PICTURE_PX)
|| height.is_some_and(|height| height < MIN_PICTURE_PX)
|| is_icon(dom, img)
|| is_author_photo(dom, img)
|| is_banner(dom, img, &src)
{
dom.detach(img);
continue;
}
if let Some(width) = width.filter(|&width| width > MAX_PICTURE_WIDTH_PX) {
dom.set_attr(img, "width", &format!("{MAX_PICTURE_WIDTH_PX}"));
if let Some(height) = height {
let fitted = height * MAX_PICTURE_WIDTH_PX / width;
dom.set_attr(img, "height", &format!("{fitted:.0}"));
}
}
let absolute_size = dom.attr(img, "style").is_some_and(|style| {
let style = style.to_ascii_lowercase();
["in", "cm", "mm", "pt"]
.iter()
.any(|unit| style.split(';').any(|decl| decl.trim_end().ends_with(unit)))
});
if !absolute_size {
dom.remove_attr(img, "style");
}
}
for source in dom.find_all(body, "source") {
dom.detach(source);
}
for node in dom.descendants(body) {
if dom.space(node) == Some(Space::Svg) && dom.name(node) == Some("image") {
for key in ["xlink:href", "href"] {
if let Some(href) = dom.attr(node, key).map(str::to_string) {
dom.set_attr(node, key, &absolute(&href, base));
}
}
}
}
}
fn best_source(dom: &Dom, img: Id) -> Option<String> {
let mut sets: Vec<String> = SRCSETS
.iter()
.filter_map(|key| dom.attr(img, key).map(str::to_string))
.collect();
if let Some(picture) = dom.nodes[img].parent.filter(|&parent| dom.is(parent, "picture")) {
for source in dom.element_children(picture) {
let drawn = dom
.attr(source, "type")
.is_none_or(|kind| !UNDRAWN_TYPES.contains(&kind.trim().to_ascii_lowercase().as_str()));
if dom.is(source, "source") && drawn {
sets.extend(
SRCSETS
.iter()
.filter_map(|key| dom.attr(source, key).map(str::to_string)),
);
}
}
}
let from_set = sets.iter().find_map(|set| best_in_srcset(set));
let src = dom.attr(img, "src").filter(|src| !is_placeholder(src));
let lazy = LAZY_SOURCES
.iter()
.find_map(|key| dom.attr(img, key).filter(|src| !is_placeholder(src)));
from_set
.or_else(|| lazy.map(str::to_string))
.or_else(|| src.map(str::to_string))
.map(|src| src.trim().to_string())
}
fn other_sources(dom: &Dom, img: Id, best: &str) -> Vec<String> {
let mut versions: Vec<(String, f32)> = SRCSETS
.iter()
.filter_map(|key| dom.attr(img, key))
.flat_map(parse_srcset)
.collect();
versions.sort_by(|a, b| b.1.total_cmp(&a.1));
let mut out: Vec<String> = Vec::new();
let plain = LAZY_SOURCES
.iter()
.chain(&["src"])
.filter_map(|key| dom.attr(img, key))
.filter(|src| !is_placeholder(src))
.map(|src| src.trim().to_string());
for url in versions.into_iter().map(|(url, _)| url).chain(plain) {
if url != best && !url.starts_with("data:") && !out.contains(&url) {
out.push(url);
}
}
out
}
fn best_in_srcset(set: &str) -> Option<String> {
let candidates = parse_srcset(set);
let wide = candidates
.iter()
.filter(|(_, width)| *width >= PREFERRED_PICTURE_WIDTH_PX)
.min_by(|a, b| a.1.total_cmp(&b.1));
wide.or_else(|| candidates.iter().max_by(|a, b| a.1.total_cmp(&b.1)))
.map(|(url, _)| url.clone())
}
fn parse_srcset(set: &str) -> Vec<(String, f32)> {
let mut out = Vec::new();
let mut rest = set;
loop {
rest = rest.trim_start_matches(|ch: char| ch.is_whitespace() || ch == ',');
if rest.is_empty() {
break;
}
let end = rest.find(char::is_whitespace).unwrap_or(rest.len());
let mut url = &rest[..end];
rest = &rest[end..];
let mut descriptor = "";
if url.ends_with(',') {
url = url.trim_end_matches(',');
} else {
let end = rest.find(',').unwrap_or(rest.len());
descriptor = rest[..end].trim();
rest = &rest[end..];
}
let size = if let Some(width) = descriptor.strip_suffix('w') {
width.parse().ok()
} else if let Some(density) = descriptor.strip_suffix('x') {
density.parse().ok()
} else {
Some(1.0)
};
if let Some(size) = size
&& !url.is_empty()
{
out.push((url.to_string(), size));
}
}
out
}
fn absolute(href: &str, base: &Base<'_>) -> String {
let href = href.trim();
match base {
Base::Url(base) | Base::File(base) => base.join(href).map_or_else(|_| href.to_string(), String::from),
Base::None => href.to_string(),
}
}
fn absolute_links(dom: &mut Dom, root: Id, base: &Base<'_>) {
for link in dom.find_all(root, "a") {
let Some(href) = dom.attr(link, "href").map(|href| href.trim().to_string()) else {
continue;
};
if href.to_ascii_lowercase().starts_with("javascript:") || href.is_empty() {
dom.remove_attr(link, "href");
continue;
}
if href.starts_with('#') {
continue;
}
let Base::Url(base) = base else {
continue;
};
let Ok(mut target) = base.join(&href) else {
continue;
};
let fragment = target.fragment().map(str::to_string);
target.set_fragment(None);
let mut page = (*base).clone();
page.set_fragment(None);
let href = match fragment {
Some(fragment) if target == page => format!("#{fragment}"),
_ => {
if let Some(fragment) = &fragment {
target.set_fragment(Some(fragment));
}
target.to_string()
}
};
dom.set_attr(link, "href", &href);
}
}
fn remove_icons(dom: &mut Dom, root: Id) {
for node in dom.descendants(root) {
if dom.space(node) != Some(Space::Svg) || dom.name(node) != Some("svg") || !dom.attached(node) {
continue;
}
let number = |key: &str| {
dom.attr(node, key)
.and_then(|value| value.trim().trim_end_matches("px").parse::<f32>().ok())
};
let view = dom.attr(node, "viewBox").and_then(|view| {
let numbers: Vec<f32> = view
.split([' ', ','])
.filter_map(|part| part.trim().parse().ok())
.collect();
(numbers.len() == 4).then(|| (numbers[2], numbers[3]))
});
let width = number("width").or(view.map(|view| view.0));
let height = number("height").or(view.map(|view| view.1));
if width.is_some_and(|width| width < MIN_PICTURE_PX)
|| height.is_some_and(|height| height < MIN_PICTURE_PX)
|| is_icon(dom, node)
{
dom.detach(node);
}
}
}
fn is_icon(dom: &Dom, node: Id) -> bool {
let elements: Vec<Id> = dom
.descendants(node)
.into_iter()
.filter(|&id| id != node && matches!(dom.nodes[id].kind, Kind::Element { .. }))
.collect();
let named = |id: Id, names: &[&str]| dom.name(id).is_some_and(|name| names.contains(&name));
let sprite = named(node, &["svg"])
&& elements.iter().any(|&id| named(id, &["use"]))
&& elements.iter().all(|&id| named(id, &["use", "g", "title", "desc"]));
if sprite {
return true;
}
let (width, height) = class_size_px(dom, node);
if width.is_some_and(|width| width < MIN_PICTURE_PX) || height.is_some_and(|height| height < MIN_PICTURE_PX) {
return true;
}
if dom.ancestor(node, |id| dom.is(id, "figure")).is_some() {
return false;
}
let mut at = Some(node);
for _ in 0..=ICON_ANCESTORS {
let Some(id) = at else {
break;
};
if dom.is_any(id, &["body", "main", "article"]) {
break;
}
let mut names = String::new();
names.push_str(dom.attr(id, "class").unwrap_or_default());
names.push(' ');
names.push_str(dom.attr(id, "id").unwrap_or_default());
if words(&names).any(|word| ICON_WORDS.contains(&word.as_str())) {
return true;
}
at = dom.nodes[id].parent;
}
false
}
fn class_size_px(dom: &Dom, node: Id) -> (Option<f32>, Option<f32>) {
let mut width: Option<f32> = None;
let mut height: Option<f32> = None;
for class in dom.classes(node) {
let class = class.rsplit(':').next().unwrap_or(class);
let Some((axis, value)) = class.split_once('-') else {
continue;
};
let px = if let Some(inner) = value.strip_prefix('[').and_then(|value| value.strip_suffix(']')) {
if let Some(number) = inner.strip_suffix("px") {
number.parse::<f32>().ok()
} else if let Some(number) = inner.strip_suffix("rem").or_else(|| inner.strip_suffix("em")) {
number.parse::<f32>().ok().map(|number| number * REM_PX)
} else {
None
}
} else {
value.parse::<f32>().ok().map(|steps| steps * TAILWIND_STEP_PX)
};
let Some(px) = px else {
continue;
};
let grow = |old: Option<f32>| Some(old.map_or(px, |old: f32| old.max(px)));
match axis {
"w" => width = grow(width),
"h" => height = grow(height),
"size" => {
width = grow(width);
height = grow(height);
}
_ => {}
}
}
(width, height)
}
fn heading_self_links(dom: &mut Dom, root: Id) {
for link in dom.find_all(root, "a") {
let Some(heading) = dom.ancestor(link, |id| dom.is_any(id, &HEADINGS)) else {
continue;
};
let Some(fragment) = dom.attr(link, "href").and_then(|href| href.strip_prefix('#')) else {
continue;
};
let text = dom.clean_text(link);
if SELF_LINK_MARKS.contains(&text.as_str()) {
dom.detach(link);
continue;
}
let mut at = Some(heading);
let mut targets_itself = false;
while let Some(id) = at {
if dom.attr(id, "id") == Some(fragment) {
targets_itself = true;
break;
}
at = dom.nodes[id].parent.filter(|&parent| parent != root);
}
if targets_itself || dom.attr(link, "id") == Some(fragment) {
dom.unwrap(link);
}
}
}
fn split_at_double_breaks(dom: &mut Dom, root: Id) {
let mut parents = Vec::new();
let mut seen = std::collections::HashSet::new();
for br in dom.find_all(root, "br") {
if let Some(parent) = dom.nodes[br].parent
&& seen.insert(parent)
{
parents.push(parent);
}
}
for parent in parents {
let mut pairs = Vec::new();
let mut open: Option<Id> = None;
for &child in &dom.nodes[parent].children {
if matches!(&dom.nodes[child].kind, Kind::Text(text) if text.trim().is_empty()) {
continue;
}
match open {
Some(first) if dom.is(child, "br") => {
pairs.push((first, child));
open = None;
}
_ => open = Some(child).filter(|&child| dom.is(child, "br")),
}
}
if pairs.is_empty() {
continue;
}
let mut blocks = std::collections::HashMap::new();
for &(first, second) in &pairs {
let block = dom.element("div", &[]);
dom.nodes[block].parent = Some(parent);
dom.nodes[first].parent = None;
dom.nodes[second].parent = None;
blocks.insert(first, Some(block));
blocks.insert(second, None);
}
let children = std::mem::take(&mut dom.nodes[parent].children);
dom.nodes[parent].children = children
.into_iter()
.filter_map(|child| blocks.get(&child).copied().unwrap_or(Some(child)))
.collect();
}
}
#[cfg(test)]
mod tests {
use super::{Dom, best_in_srcset, is_author_photo, is_banner, is_icon, parse_srcset, without_site_name};
#[test]
fn banners_and_author_photos() {
let dom = Dom::parse(
r#"<p><img id=a src="https://x.vn/images/banner_taiapp.jpg">
<img id=b src="https://x.vn/Museumplein-Amsterdam-banner.jpg">
<a href="https://sponsor.example"><img id=c src="/img/railway-banner.png"></a>
<a href="/tac-gia/chi-tue.htm"><img id=d src="/avatar/chi-tue.jpg"></a></p>"#,
);
let find = |dom: &Dom, id: &str| {
dom.find_all(0, "img")
.into_iter()
.find(|&img| dom.attr(img, "id") == Some(id))
.unwrap()
};
let banner = |dom: &Dom, id: &str| {
let img = find(dom, id);
let src = dom.attr(img, "src").unwrap().to_string();
is_banner(dom, img, &src)
};
assert!(banner(&dom, "a"));
assert!(!banner(&dom, "b"));
assert!(banner(&dom, "c"));
assert!(is_author_photo(&dom, find(&dom, "d")));
assert!(!is_author_photo(&dom, find(&dom, "c")));
}
#[test]
fn icons_are_known_by_their_classes() {
let dom = Dom::parse(
r#"<body><a class="view-comments"><svg class="h-4 w-4" viewBox="0 0 80 80"></svg></a>
<svg class="h-[36px] md:h-[65px]" viewBox="0 0 436 144"></svg>
<div class="div-logo"><a><img src="logo.png"></a></div>
<img class="info-icon" src="sun.png">
<figure><div class="logo"><img src="brand.png"></div><figcaption>The brand.</figcaption></figure>
<img class="w-full" src="photo.jpg"></body>"#,
);
let icons: Vec<bool> = dom
.descendants(0)
.into_iter()
.filter(|&id| dom.is(id, "img") || dom.name(id) == Some("svg"))
.map(|id| is_icon(&dom, id))
.collect();
assert_eq!(icons, [true, false, true, true, false, false]);
}
#[test]
fn srcsets_and_titles() {
let set = "a.jpg?c=16x9&q=h_27,w_640 640w, b.jpg 1920w,c.jpg 3840w";
assert_eq!(parse_srcset(set).len(), 3);
assert_eq!(best_in_srcset(set).as_deref(), Some("b.jpg"));
assert_eq!(best_in_srcset("a.png, b.png 2x").as_deref(), Some("b.png"));
assert_eq!(best_in_srcset("a.png 300w, b.png 800w").as_deref(), Some("b.png"));
assert_eq!(
without_site_name("Gravitational wave - Wikipedia"),
"Gravitational wave"
);
assert_eq!(
without_site_name("Writing effective tools for AI agents \\ Anthropic"),
"Writing effective tools for AI agents"
);
assert_eq!(without_site_name("A - B"), "A");
assert_eq!(without_site_name("Plain"), "Plain");
}
}