Skip to main content

fats/
clean.rs

1//! CLEAN: tree → lines in three prune modes + loss guard → Doc (sections, links, info, loss, tokens).
2//! Links resolve with the WHATWG `url` crate.
3
4use crate::html::{Kid, Node, Tree, Visit, py_space, py_strip, unescape};
5use crate::settings::limit;
6use crate::tables::{COMBINING, FOLD, ND_ZEROS};
7use crate::{fetch::title_head, fetch::words_of, outline::sections_of};
8use indexmap::IndexMap;
9use serde::{Deserialize, Serialize};
10use serde_json::{Value, ser::PrettyFormatter};
11use std::collections::{BTreeSet, HashMap, HashSet};
12use std::sync::LazyLock;
13
14/// Doc schema version: a cached doc.json with another `v` is rebuilt from raw.html.
15pub const DOC_V: u32 = 18;
16/// A comment's section level: `COMMENT` + its depth in the thread (beyond `h6`, so no heading is one).
17pub const COMMENT: usize = 7;
18
19/// The renderer's tables (`src/data/clean.json`).
20#[derive(Deserialize)]
21#[serde(deny_unknown_fields, bound(deserialize = "'de: 'static"))]
22pub struct Lists {
23    /// Elements that end a line of text.
24    block: Vec<&'static str>,
25    /// Elements whose text is never page text.
26    drop_always: Vec<&'static str>,
27    /// Elements and ARIA roles that open a scope (a cookie banner is judged inside its scope only).
28    sectioning: Vec<&'static str>,
29    sectioning_roles: Vec<&'static str>,
30    /// A table's row and cell elements and ARIA roles (`part`).
31    row: Vec<&'static str>,
32    cell: Vec<&'static str>,
33    /// Words in an id or class that mark a cookie or consent banner.
34    cookie: Vec<&'static str>,
35    /// Path words of links that are site chrome (log in, share, vote), never page links.
36    skip_link: Vec<&'static str>,
37    /// DETECT by magic bytes (`sniff`): the files this build has no text converter for (pdf, zip = docx/xlsx/pptx).
38    magic: Vec<(String, &'static str)>,
39    /// Text documents (`kind_of`): served as they are, a line a row (`text::build`), never cleaned as a page.
40    pub text: Vec<&'static str>,
41    /// Media (`body_media`, `add`, `rank`): words in a `data-*` attribute that holds the real source; in a GIF's
42    /// name that make it a filler; picture file types; a link folder of a picture's own page (`links`); in an alt,
43    /// class or file name that make it not content (or only in a short alt); in a URL of a generated share card;
44    /// query keys that track.
45    lazy_src: Vec<&'static str>,
46    filler: Vec<&'static str>,
47    image_ext: Vec<&'static str>,
48    picture_page: Vec<&'static str>,
49    not_content: Vec<&'static str>,
50    not_content_alt: Vec<&'static str>,
51    share_card: Vec<&'static str>,
52    share_host: Vec<&'static str>,
53    tracking: Vec<&'static str>,
54    /// Whole words (or their plural) of a tag, class or id that name an ad slot (`ad_slot`).
55    ad_slot: Vec<&'static str>,
56    /// The post's own counts (`post`): an `info` key and the count words of an attribute name that give it
57    /// (`comment-count` → `comments`; the `comments` words also read a thread's stated `726 comments`,
58    /// `declared`), the count markers one of its words must be, the words that make it no count of the post
59    /// (`remaining-comments-count`), and the attribute names read from that element only (`score`, `posted`);
60    /// the posted time also from a name that holds a word of each `post_time` list (`created-timestamp`).
61    post_counts: Vec<(&'static str, Vec<&'static str>)>,
62    post_marker: Vec<&'static str>,
63    post_skip: Vec<&'static str>,
64    post_facts: Vec<(&'static str, Vec<&'static str>)>,
65    post_time: (&'static str, Vec<&'static str>, Vec<&'static str>),
66    /// `info` keys read from `<meta>` names, the first name present wins (`meta_info`).
67    info: Vec<(&'static str, Vec<&'static str>)>,
68    /// Currency marks a price number sits next to (`facts`, `Loss::price_pruned`).
69    currency: Vec<&'static str>,
70}
71
72pub static LISTS: LazyLock<Lists> = LazyLock::new(|| crate::settings::table("clean"));
73
74#[derive(Serialize, Deserialize, Clone, Default)]
75pub struct Section {
76    pub level: usize,
77    pub title: String,
78    pub lines: Vec<String>,
79}
80
81/// A doc.json missing a field (another build's) fails to read and is rebuilt from the raw body.
82#[derive(Serialize, Deserialize, Default)]
83pub struct Loss {
84    pub vs_light_lost: usize,
85    pub light_facts: usize,
86    /// Body chars the chrome prune keeps (the served doc's, or the last prune's when light is served):
87    /// the content check's "cleans to almost nothing" reads this, never the light fallback.
88    pub pruned_chars: usize,
89    /// Text chars in the bytes: the light render's, `<template>` contents and JSON-island prose (`inert_chars`);
90    /// `outline::thin` compares the served text with it.
91    pub visible_chars: usize,
92    /// Of `vs_light_lost`, the numbers next to a currency mark (`fats stats` `price_nums_pruned`): measured
93    /// before any rule acts on it.
94    pub price_pruned: usize,
95}
96
97/// One picture or video of a page (`media`): its URL, alt text (a JSON-LD caption), declared size, file type.
98#[derive(Serialize, Deserialize, Clone, Default, PartialEq, Debug)]
99pub struct Media {
100    pub src: String,
101    pub alt: String,
102    /// og:video, or a `<video>`'s poster; else a photo.
103    pub video: bool,
104    /// As the page declares it (attributes, og, JSON-LD), 0 = not declared: a size in the file name only filters
105    /// (`add`), it would print as if declared (`m1 photo 1287x836`).
106    pub w: u32,
107    pub h: u32,
108    /// `webp`: the declared type's subtype, else the URL's extension; "" = unknown.
109    pub ty: String,
110    /// Not content (`rank`): an avatar, a bare `@handle` alt, or the author's or site's name as alt; listed last,
111    /// never counted (`outline::photos`).
112    pub demoted: bool,
113    /// The picture's identity and largest side while the page is built (`add`).
114    #[serde(skip)]
115    key: (String, u32),
116    /// Links to its own page or file (`links`): a gallery's picture, never an avatar.
117    #[serde(skip)]
118    linked: bool,
119}
120
121/// A page's `info`, in document order: `<meta>` first, then JSON-LD; a key set again keeps its first place.
122pub type Info = IndexMap<String, String>;
123
124#[derive(Serialize, Deserialize, Default)]
125pub struct Tokens {
126    pub clean: usize,
127}
128
129/// As `Loss`: a doc.json missing a field is rebuilt; one with another `v` or `chunk` too.
130#[derive(Serialize, Deserialize, Default)]
131pub struct Doc {
132    pub v: u32,
133    /// Block size used for heading-less text (a doc built with another size is rebuilt).
134    pub chunk: usize,
135    pub url: String,
136    pub final_url: String,
137    pub title: String,
138    pub info: Info,
139    pub sections: Vec<Section>,
140    pub top: usize,
141    pub links: Vec<String>,
142    /// Each link's longest anchor text (`fats uN links <words>` matches it).
143    pub anchors: Vec<String>,
144    pub mode: String,
145    pub loss: Loss,
146    pub tokens: Tokens,
147    /// Left unread when the time budget ran out (0 = all of it): bytes of an HTML body, pages of a PDF.
148    pub cut: usize,
149    /// The last `islands` sections are islands: inert blocks in the bytes, opened on demand (`clean::islands`).
150    pub islands: usize,
151    /// Pictures and videos, best first (`clean::rank`).
152    pub media: Vec<Media>,
153}
154
155impl Doc {
156    /// A Doc carrying the schema version, the settings chunk, the URLs, the title, the clean-token count of
157    /// `sections` and the given mode; `top` = 1 and everything else defaults. The three builders
158    /// (`build_doc`, `text::build`, `pdf::build_pdf`) add the parts they alone have (info, loss, cut, links).
159    pub fn new(url: &str, final_url: &str, title: String, sections: Vec<Section>, mode: &str) -> Doc {
160        Doc {
161            v: DOC_V,
162            chunk: crate::settings::get().chunk.value,
163            url: url.into(),
164            final_url: final_url.into(),
165            title,
166            tokens: Tokens { clean: sections.iter().flat_map(|s| s.lines.iter()).map(|t| tok(t)).sum() },
167            sections,
168            top: 1,
169            mode: mode.into(),
170            ..Doc::default()
171        }
172    }
173
174    /// Sections of the page as served, before its islands.
175    pub fn served(&self) -> usize {
176        self.sections.len().saturating_sub(self.islands)
177    }
178}
179
180/// THE token figure (the `=` line's `Ntok`, every read and list cap): real tokens of `s` as printed, estimated as
181/// ASCII letters / 2.7 + other non-space chars / 0.8, an ASCII punctuation mark after another one as a letter (JSON's
182/// `":"`, `},{"`). Fitted on count_tokens of 42 printed reads (Claude 5.5 models; within ±10% on 37, worst 18%;
183/// older tokenizers count ~1.2× fewer, o200k ~1.4×).
184pub fn tok(s: &str) -> usize {
185    weights(s).sum::<usize>().div_ceil(216)
186}
187
188/// The byte length of the longest start of `s` within `cap` tok, in one pass: where a huge line is cut.
189pub fn tok_cut(s: &str, cap: usize) -> usize {
190    let mut w = 0;
191    s.char_indices().zip(weights(s)).find(|&(_, c)| (w += c, w > cap * 216).1).map_or(s.len(), |((i, _), _)| i)
192}
193
194/// Each char's share of a token, in 216ths (`tok`).
195fn weights(s: &str) -> impl Iterator<Item = usize> + '_ {
196    let mark = |c: char| c.is_ascii_punctuation();
197    s.chars().scan(' ', move |prev, c| {
198        let letter = c.is_ascii_alphabetic() || mark(*prev) && mark(c);
199        *prev = c;
200        Some(usize::from(!py_space(c)) * if letter { 80 } else { 270 })
201    })
202}
203
204/// `re.sub(r"\s+", " ", s).strip()`
205pub fn collapse(s: &str) -> String {
206    s.split(py_space).filter(|w| !w.is_empty()).collect::<Vec<_>>().join(" ")
207}
208
209/// A combining mark (`COMBINING`: sorted, disjoint code point ranges).
210fn combining(cp: u32) -> bool {
211    let at = COMBINING.partition_point(|&(_, hi)| hi < cp);
212    COMBINING.get(at).is_some_and(|&(lo, _)| lo <= cp)
213}
214
215/// NFKD, drop combining marks, lowercase (tables.rs holds the decompositions).
216pub fn fold(s: &str) -> String {
217    let mut out = String::with_capacity(s.len());
218    for c in s.chars() {
219        let cp = c as u32;
220        if cp < 0x80 {
221            out.push(c);
222        } else if (0xAC00..=0xD7A3).contains(&cp) {
223            // Hangul syllable → L V (T) jamo (Unicode §3.12)
224            let syl = cp - 0xAC00;
225            let jamo = [0x1100 + syl / 588, 0x1161 + (syl % 588) / 28, 0x11A7 + syl % 28];
226            let len = if syl.is_multiple_of(28) { 2 } else { 3 };
227            out.extend(jamo[..len].iter().filter_map(|&j| char::from_u32(j)));
228        } else if !combining(cp) {
229            let at = FOLD.binary_search_by_key(&cp, |&(k, _)| k);
230            if let Ok(at) = at { out.push_str(FOLD[at].1) } else { out.push(c) }
231        }
232    }
233    out.to_lowercase()
234}
235
236/// Bytes → UTF-8 in the WHATWG order: a BOM, the transport's charset (`Content-Type`), a `<meta>` charset in the
237/// first 1024 bytes, else UTF-8. Returns the text and the encoding's name for meta.json (`windows-1250`; "" = UTF-8).
238/// Valid UTF-8 comes back as it went in (no copy); invalid bytes become U+FFFD later, never an error.
239pub fn decode(raw: Vec<u8>, header: Option<&str>) -> (Vec<u8>, &'static str) {
240    use encoding_rs::{Encoding, UTF_8, UTF_16BE, UTF_16LE, WINDOWS_1252, X_USER_DEFINED};
241    let meta = || match prescan(&raw[..raw.len().min(1024)]).and_then(Encoding::for_label) {
242        // a page cannot declare UTF-16 in ASCII-compatible bytes; x-user-defined is a legacy alias (spec 13.2.3.3)
243        Some(e) if e == UTF_16BE || e == UTF_16LE => Some(UTF_8),
244        Some(e) if e == X_USER_DEFINED => Some(WINDOWS_1252),
245        e => e,
246    };
247    let bom = Encoding::for_bom(&raw).map(|b| b.0);
248    let sent = header.and_then(|h| Encoding::for_label(h.as_bytes()));
249    let enc = bom.or(sent).or_else(meta).unwrap_or(UTF_8);
250    let name = if enc == UTF_8 { "" } else { enc.name() };
251    if enc == UTF_8 && !raw.starts_with(b"\xEF\xBB\xBF") {
252        return (raw, name);
253    }
254    (enc.decode_with_bom_removal(&raw).0.into_owned().into_bytes(), name)
255}
256
257/// The label of the first `<meta charset=…>` or `<meta http-equiv … content="…; charset=…">` (ASCII only).
258fn prescan(head: &[u8]) -> Option<&[u8]> {
259    let low = head.to_ascii_lowercase();
260    let mut at = 0;
261    while let Some(i) = find(&low[at..], b"<meta").map(|i| i + at) {
262        let end = find(&low[i..], b">").map_or(low.len(), |e| i + e);
263        at = end;
264        let Some(c) = find(&low[i..end], b"charset").map(|c| i + c + 7) else { continue };
265        let rest = head[c..end].trim_ascii_start().strip_prefix(b"=").map(<[u8]>::trim_ascii_start);
266        let Some(v) = rest.map(|r| r.strip_prefix(b"\"").or(r.strip_prefix(b"'")).unwrap_or(r)) else { continue };
267        let n = v.iter().position(|b| b" \"';/>\t\n\r".contains(b)).unwrap_or(v.len());
268        if n > 0 {
269            return Some(&v[..n]);
270        }
271    }
272    None
273}
274
275fn find(hay: &[u8], needle: &[u8]) -> Option<usize> {
276    hay.windows(needle.len()).position(|w| w == needle)
277}
278
279/// DETECT, THE rule: what a body is, given its content type ("" when none came: a provider's answer, a local
280/// file). Magic bytes first (`sniff`), then a type that names a PDF or a zip; a body that opens like an HTML page
281/// (`<!doctype html` or `<html` in its first 1 KB) or a type that says HTML is `html`. Then the text documents:
282/// a JSON type, or a body that parses as JSON, is `json`; an XML type (RSS, Atom), or a body that opens with
283/// `<?xml`, `<rss`, `<feed`, `<urlset`, `<sitemapindex`, is `xml`; a `text/markdown` type is `md` (a server's own
284/// conversion of its page, `text::markdown`); any other `text/*` type (plain, CSV) is `text`. Anything else is `html`,
285/// the page path.
286pub fn kind_of(ctype: &str, body: &[u8]) -> &'static str {
287    let ct = ctype.split(';').next().unwrap_or_default().trim().to_ascii_lowercase();
288    let head = body.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(body).trim_ascii_start();
289    let low = head[..head.len().min(1024)].to_ascii_lowercase();
290    let opens = |tags: &[&[u8]]| tags.iter().any(|t| low.starts_with(t));
291    let bare = ct.is_empty() || ct == "text/plain";
292    match () {
293        _ if let Some(k) = sniff(body) => k,
294        _ if ct.contains("application/pdf") => "pdf",
295        _ if ct.contains("application/zip") || ct.contains("officedocument") => "zip",
296        _ if ct.contains("html") || opens(&[b"<!doctype html"]) || find(&low, b"<html").is_some() => "html",
297        _ if ct.contains("json") => "json",
298        _ if bare && opens(&[b"{", b"["]) && serde_json::from_slice::<serde::de::IgnoredAny>(body).is_ok() => "json",
299        _ if ct.contains("xml") || bare && opens(&[b"<?xml", b"<rss", b"<feed", b"<urlset", b"<sitemapindex"]) => "xml",
300        _ if ct == "text/markdown" => "md",
301        _ if ct.starts_with("text/") => "text",
302        _ => "html",
303    }
304}
305
306/// DETECT: a body this build has no text converter for (`pdf`, `zip` = docx/xlsx/pptx), by magic bytes.
307pub fn sniff(raw: &[u8]) -> Option<&'static str> {
308    LISTS.magic.iter().find(|m| raw.starts_with(m.0.as_bytes())).map(|m| m.1)
309}
310
311/// Regex `\d` on str = Unicode Nd.
312pub fn is_digit(c: char) -> bool {
313    let u = c as u32;
314    c.is_ascii_digit() || (u >= 0x660 && ND_ZEROS.iter().any(|&z| u >= z && u < z + 10))
315}
316
317/// Regex `\w` on str.
318pub fn is_word(c: char) -> bool {
319    c.is_alphanumeric() || c == '_'
320}
321
322/// A card row's mark (`Render::card`): the line is one card of a list.
323pub const CARD: &str = "▸ ";
324/// Between a card's pieces (`card`); not the page's text (`outline::is_thin`).
325pub const PIECE: &str = " · ";
326/// Our `[lN]` link ids in a line.
327pub static LREF: LazyLock<regex::Regex> = LazyLock::new(|| regex::Regex::new(r"\[l[0-9]+\]").expect("a pattern"));
328
329#[derive(Clone)]
330pub enum Line {
331    H(usize, String),
332    T(String),
333}
334
335impl Line {
336    pub fn text(&self) -> &str {
337        match self {
338            Line::H(_, t) | Line::T(t) => t,
339        }
340    }
341}
342
343#[derive(PartialEq, Clone, Copy)]
344enum Mode {
345    Light,
346    Hard,
347    Clean,
348}
349
350struct Render<'a> {
351    tree: &'a Tree,
352    tlen: &'a [usize],
353    /// The page URL without its fragment: the base of every link, and the link a page makes to itself.
354    base_url: Option<url::Url>,
355    mode: Mode,
356    js: bool,
357    lines: Vec<Line>,
358    /// Text pieces (Python list semantics: `a` checks the pieces added after its start index).
359    buf: String,
360    marks: Vec<usize>,
361    /// Link URLs in first-seen order (`[lN]` = position + 1) → their longest anchor text (a card's link around its
362    /// title, never a teaser link to the same page before it: `card_row`).
363    links: IndexMap<String, String>,
364    inline: usize,
365    /// The `<img>` and `<video>` elements the render kept (`body_media`), in document order.
366    media: Vec<usize>,
367    /// A nested thread's comments → their depth (`thread`).
368    thread: HashMap<usize, usize>,
369    /// A comment's head line while its byline runs: the line its `<time>` lands on ends it (`flush`).
370    by: Option<(usize, usize)>,
371    /// The link targets some link names in words (`worded_links`).
372    worded: HashSet<String>,
373    /// Links that show nothing but name a text beside them (a card's overlay): (first line, name, id), `pay`.
374    owed: Vec<(usize, String, usize)>,
375}
376
377/// Text chars under `id` that a page shows; a `<template>` shows none, its contents (the fragment after it) are
378/// measured for `islands`.
379fn measure(t: &Tree, id: usize, tlen: &mut [usize]) -> usize {
380    let mut s = 0;
381    for k in &t.nodes[id].kids {
382        match k {
383            Kid::Text(x) => s += py_strip(x).chars().count(),
384            Kid::Node(c) if t.nodes[*c].tag == "template" => tlen[*c] = measure(t, c + 1, tlen),
385            Kid::Node(c) if !LISTS.drop_always.contains(&t.nodes[*c].tag.as_str()) => s += measure(t, *c, tlen),
386            Kid::Node(_) => {}
387        }
388    }
389    tlen[id] = s;
390    s
391}
392
393/// `aria-hidden` hides from screen readers only: its text is on screen (star counts, ratings) and stays; an icon
394/// glyph (`text` ≤ 1 char) under it is still dropped.
395fn hidden(n: &Node, text: usize) -> bool {
396    if n.attr("hidden").is_some() || n.attr("aria-hidden") == Some("true") && text <= 1 {
397        return true;
398    }
399    let style = n.attr("style").unwrap_or("");
400    // display\s*:\s*none | visibility\s*:\s*hidden (case-sensitive)
401    [("display", "none"), ("visibility", "hidden")].iter().any(|(k, v)| {
402        style.match_indices(k).any(|(i, _)| {
403            let r = style[i + k.len()..].trim_start_matches(py_space);
404            r.strip_prefix(':').is_some_and(|r| r.trim_start_matches(py_space).starts_with(v))
405        })
406    })
407}
408
409impl Render<'_> {
410    fn chrome(&self, id: usize, scoped: bool) -> bool {
411        let n = &self.tree.nodes[id];
412        if self.tlen[id] as f64 > 0.5 * self.tlen[0].max(1) as f64 {
413            return false;
414        }
415        let (role, tag) = (n.attr("role").unwrap_or("").to_lowercase(), n.tag.as_str());
416        let nav = matches!(role.as_str(), "navigation" | "banner" | "contentinfo");
417        if nav || matches!(tag, "nav" | "aside" | "form") || (!scoped && matches!(tag, "header" | "footer")) {
418            return true;
419        }
420        let cid = format!("{} {}", n.attr("id").unwrap_or(""), n.attr("class").unwrap_or("")).to_lowercase();
421        LISTS.cookie.iter().any(|w| cid.contains(w))
422            || self.mode == Mode::Clean && (tag == "dialog" || role.ends_with("dialog") || hidden(n, self.tlen[id]))
423    }
424
425    /// A nested thread's comments → their depth, by structure. A block = `li`, `article` or a custom element (a `-`
426    /// in its tag). The comments' tag = the commonest tag of the blocks that are the nearest block of a paragraph (a
427    /// text of their own) above a served `<time>` (a sidebar card, the post: another tag). A comment = the nearest
428    /// ancestor of that tag of a served `<time>`, a short one too; one inside a list item of another tag is that item
429    /// (the replies beside it: `li > article + ol > li`); the top ones share their parent. Its depth = the comments
430    /// around it, or a spacer row's (below), clamped at `thread_depth` when rendered (`walk`).
431    fn comments(&self) -> HashMap<usize, usize> {
432        let t = self.tree;
433        let block = |i: &usize| matches!(t.nodes[*i].tag.as_str(), "li" | "article") || t.nodes[*i].tag.contains('-');
434        let says = |i: &usize| t.nodes[*i].kids.iter().any(|k| matches!(k, Kid::Text(s) if paragraph(s)));
435        let said: HashSet<usize> = (0..t.nodes.len()).filter(says).filter_map(|i| up(t, i).find(block)).collect();
436        // served: not in a template, nor in what the render prunes (a sidebar's cards are no thread's tops)
437        let pruned = |a: usize| self.mode != Mode::Light && self.chrome(a, true);
438        let served = |i: &usize| up(t, *i).last() == Some(0) && !up(t, *i).any(pruned);
439        let dated: Vec<usize> = (0..t.nodes.len()).filter(|i| t.nodes[*i].tag == "time" && served(i)).collect();
440        let tags = dated.iter().filter_map(|&i| up(t, i).find(|b| said.contains(b))).map(|b| t.nodes[b].tag.as_str());
441        let tag = commonest(tags.collect());
442        let item = |c: usize| t.nodes[c].parent.filter(|&p| t.nodes[p].tag == "li" && tag != Some("li")).unwrap_or(c);
443        let of = |i: &usize| up(t, *i).find(|&b| Some(t.nodes[b].tag.as_str()) == tag).map(item);
444        let comments: HashSet<usize> = dated.iter().filter_map(of).collect();
445        let mut depths: HashMap<usize, usize> =
446            comments.iter().map(|&c| (c, up(t, c).skip(1).filter(|a| comments.contains(a)).count())).collect();
447        // the top comments share their parent (a story, a sidebar card: alone elsewhere)
448        let list = commonest(depths.iter().filter(|e| *e.1 == 0).map(|e| t.nodes[*e.0].parent).collect()).flatten();
449        depths.retain(|&c, d| *d > 0 || t.nodes[c].parent == list);
450        // the old way to indent a reply: a text-less spacer 1 px high in its row (`<img height=1 width=40>`); the
451        // row's depth = the rank of its width; a row's first spacer is its indent (a second stands in for a vote arrow)
452        let width =
453            |n: &Node| n.attr("width").filter(|_| n.kids.is_empty() && n.attr("height") == Some("1"))?.parse().ok();
454        let in_row = |i: usize| up(t, i).find(|&r| t.nodes[r].tag == "tr");
455        let row = |i: usize| width(&t.nodes[i]).and_then(|w: usize| Some((in_row(i)?, w)));
456        let mut rows: Vec<(usize, usize)> = (0..t.nodes.len()).filter_map(row).filter(|r| served(&r.0)).collect();
457        rows.dedup_by_key(|r| r.0);
458        let steps: Vec<usize> = rows.iter().map(|r| r.1).collect::<BTreeSet<_>>().into_iter().collect();
459        // spacers are layout too (a gutter, a TOC or file tree indent): a reply ladder starts at 0 (a gutter never
460        // does) and ≥ `thread_rows` of its rows say something untitled (a TOC entry, a file name: no paragraph; a
461        // newsletter's story: its own heading)
462        let prose: HashSet<usize> = (0..t.nodes.len()).filter(says).filter_map(in_row).collect();
463        let head = |v: Visit| matches!(v, Visit::Node(n) if matches!(n.tag.as_bytes(), [b'h', b'1'..=b'6']));
464        let post = |r: &&(usize, usize)| prose.contains(&r.0) && !t.walk(r.0, &[]).any(head);
465        let talk = steps.first() == Some(&0) && rows.iter().filter(post).count() >= limit("thread_rows");
466        depths.extend(rows.iter().filter(|_| talk).map(|&(r, w)| (r, steps.partition_point(|&s| s < w))));
467        // a thread: ≥ `thread_rows` comments, ≥ 2 at the top and one deeper (dated flat posts are a feed)
468        let tops = depths.values().filter(|&&d| d == 0).count();
469        if depths.len() >= limit("thread_rows") && (2..depths.len()).contains(&tops) { depths } else { HashMap::new() }
470    }
471
472    /// THE place rule of the post's counts (`post`, `declared`): `x` is a list item (a related post's card, a
473    /// sidebar's) or chrome (`chrome`, scoped: nav, aside, a banner), where no count is the post's.
474    fn listed(&self, x: usize) -> bool {
475        self.tree.nodes[x].tag == "li" || self.chrome(x, true)
476    }
477
478    /// The post's own counts: the first element in document order with a count attribute (`count`) that is in no
479    /// list item or chrome (`listed`) = the post: `comments 296`; its `post_facts` attributes and its posted time
480    /// (`post_time`) from that element only (`score 26`, `posted 2025-12-11`). Later elements (the comments, each
481    /// with its own score) never. A shape, no site: runs on every page, a thread recognised or not (its comments
482    /// may sit in a `<template>`).
483    fn post(&self) -> Info {
484        let t = self.tree;
485        let counts = |i: usize| (i, t.nodes[i].attrs.iter().filter_map(count).collect::<Vec<_>>());
486        let placed = |c: &(usize, Vec<(String, String)>)| !c.1.is_empty() && !up(t, c.0).any(|a| self.listed(a));
487        let Some((i, found)) = (0..t.nodes.len()).map(counts).find(placed) else {
488            return Info::new();
489        };
490        let (key, when, unit) = &LISTS.post_time;
491        let named = |(k, v): &(String, String)| {
492            let name = bare(k);
493            let words: Vec<&str> = name.split(['-', '_', ':']).collect();
494            let has = |list: &[&str]| words.iter().any(|w| list.contains(w));
495            let fact = LISTS.post_facts.iter().find(|r| r.1.contains(&name.as_str())).map(|r| r.0);
496            let key = if has(when) && has(unit) { Some(*key) } else { fact };
497            Some((key?.to_string(), fact_value(v)?))
498        };
499        let mut info = Info::new();
500        for (k, v) in found.into_iter().chain(t.nodes[i].attrs.iter().filter_map(named)) {
501            info.entry(k).or_insert(v); // the first attribute of a key wins
502        }
503        info
504    }
505
506    /// The thread's size as the page states it in words (`726 comments`: the story's own line, an attribute's
507    /// value; a count attribute's name is the post's, `post`): the count nearest the thread before it, shown, never
508    /// in a list item or chrome (`listed`) nor on an element around the thread (its text may follow it); its scope
509    /// = the deepest of those elements at or before it, and two counts in that scope claim none.
510    fn declared(&self) -> Option<usize> {
511        let (t, path) = (self.tree, up(self.tree, *self.thread.keys().min()?).collect::<Vec<_>>());
512        let words = count_words("comments");
513        let said = |s: &str| match s.split_whitespace().collect::<Vec<_>>()[..] {
514            [n, w] if words.contains(&w.to_lowercase().as_str()) => n.replace(',', "").parse().ok(),
515            _ => None,
516        };
517        let attr = |(_, v): &(String, String)| said(v);
518        let text = |k: &Kid| if let Kid::Text(s) = k { said(s) } else { None };
519        let p = &path;
520        let shown = |i: &usize| !p.contains(i) && !up(t, *i).take_while(|a| !p.contains(a)).any(|a| self.listed(a));
521        let found = |i: usize| t.nodes[i].attrs.iter().filter_map(attr).chain(t.nodes[i].kids.iter().filter_map(text));
522        let mut near =
523            (0..path[0]).rev().filter(shown).flat_map(|i| found(i).map(move |n| (p.iter().find(|&&a| a <= i), n)));
524        let (at, n) = near.next()?;
525        near.take_while(|f| f.0 == at).all(|f| f.1 == n).then_some(n)
526    }
527
528    /// Two numbers in two elements stay two: a space between a digit and a digit at an element boundary
529    /// (`$109.72` `0.24%`, never `$109.720.24%`).
530    fn push(&mut self, s: &str) {
531        let gap = self.buf.ends_with(is_digit) && s.starts_with(is_digit);
532        self.buf.push_str(if gap { " " } else { "" });
533        self.marks.push(self.buf.len());
534        self.buf.push_str(s);
535    }
536
537    fn flush(&mut self) {
538        if self.inline > 0 {
539            self.push(" ");
540            return;
541        }
542        let t = collapse(&self.buf);
543        self.buf.clear();
544        self.marks.clear();
545        self.lines.extend((!t.is_empty() && t != "-" && t != "|" && t != "- |").then_some(Line::T(t)));
546    }
547
548    /// The URL a link lists under (no fragment), none for a same-page, script, mail or skipped one.
549    fn target(&self, href: &str) -> Option<String> {
550        let href = py_strip(href);
551        if href.is_empty() || ["#", "javascript:", "mailto:", "tel:", "data:"].iter().any(|p| href.starts_with(p)) {
552            return None;
553        }
554        let mut j = url::Url::options().base_url(self.base_url.as_ref()).parse(href).ok()?;
555        j.set_fragment(None);
556        let u = String::from(j);
557        let same = self.base_url.as_ref().is_some_and(|b| b.as_str() == u);
558        (u.starts_with("http") && !same && !skip_link(&u)).then_some(u)
559    }
560
561    /// The link targets some link names in words (`worded`): a picture linked beside its title is that title's.
562    fn worded_links(&self) -> HashSet<String> {
563        let t = self.tree;
564        let worded = |&a: &usize| t.nodes[a].tag == "a" && worded(&t.texts(a, &LISTS.drop_always).collect::<String>());
565        (0..t.nodes.len()).filter(worded).filter_map(|a| self.target(t.nodes[a].attr("href")?)).collect()
566    }
567
568    fn link(&mut self, href: &str, text: &str) -> Option<usize> {
569        let u = self.target(href)?;
570        let (i, a) = self.links.insert_full(u, collapse(text));
571        if let Some(a) = a.filter(|a| a.len() > text.len()) {
572            self.links[i] = a; // keep the longest
573        }
574        Some(i + 1)
575    }
576
577    fn text_of(&mut self, id: usize, scoped: bool) -> String {
578        let save = (std::mem::take(&mut self.buf), std::mem::take(&mut self.marks));
579        self.inline += 1;
580        self.kids(id, scoped);
581        self.inline -= 1;
582        let t = collapse(&self.buf);
583        (self.buf, self.marks) = save;
584        t
585    }
586
587    fn kids(&mut self, id: usize, scoped: bool) {
588        let kids = &self.tree.nodes[id].kids;
589        let cards = if self.inline == 0 { self.groups(id) } else { HashSet::new() };
590        let mut spans = vec![];
591        for k in kids {
592            match k {
593                Kid::Text(s) => self.push(s),
594                Kid::Node(c) if cards.contains(c) => {
595                    self.flush();
596                    let l0 = self.lines.len();
597                    self.walk(*c, scoped);
598                    self.flush();
599                    spans.push(l0..self.lines.len());
600                }
601                Kid::Node(c) => self.walk(*c, scoped),
602            }
603        }
604        self.cards(&spans);
605    }
606
607    /// The kids of `id` that are cards: a group of ≥ `card_repeats` siblings of one shape (tag and first class),
608    /// ≥ 60% of the block kids that show text, four in five of them holding no element of their own shape (a thread's
609    /// comment holds its replies), no code and no table (a shape, never a size; `cards` judges the rendered rows).
610    fn groups(&self, id: usize) -> HashSet<usize> {
611        let t = self.tree;
612        let kids: Vec<usize> = t.nodes[id].kids.iter().filter_map(Kid::node).collect();
613        let mut shapes: IndexMap<(&str, &str), Vec<usize>> = IndexMap::new();
614        // a block or a custom element (`<x-item>`), never a table row (`row`) or inline markup (citations)
615        let tag = |c: usize| t.nodes[c].tag.as_str();
616        let boxed =
617            |c: usize| !part(&t.nodes[c], &LISTS.row) && (LISTS.block.contains(&tag(c)) || tag(c).contains('-'));
618        for &c in kids.iter().filter(|&&c| boxed(c)) {
619            shapes.entry(shape(&t.nodes[c])).or_default().push(c);
620        }
621        // its own shape inside = a thread (replies); code or a table inside keeps its lines; a byline first = a comment
622        let own = |c: usize| held(t, c, &|n| shape(n) == shape(&t.nodes[c]) || n.tag == "pre" || n.tag == "table");
623        let card = |c: &&usize| !own(**c) && !byline(t, self.tlen, **c) && !self.thread.contains_key(*c);
624        // one group decides for all its members: never half a list as cards, half as sections
625        let shown = kids.iter().filter(|&&c| boxed(c) && self.tlen[c] > 0).count();
626        let most = |v: &Vec<usize>| v.len() >= limit("card_repeats") && 5 * v.len() >= 3 * shown;
627        let cards = shapes.into_values().filter(|v| most(v) && 5 * v.iter().filter(card).count() >= 4 * v.len());
628        cards.flatten().collect()
629    }
630
631    /// A card group (`groups`), each member's lines at `spans`: every member ONE row (`card_row`) when four in five
632    /// are one item, else none (never half a list as cards, half as sections): a filter hit inside it is the card.
633    /// The row takes its member's first line, the rest are emptied (no rendered text line is empty: `flush`; a
634    /// comment's heading is untitled, `COMMENT`, and stays), and the
635    /// group's lines are rebuilt once (a splice per member moved every later line: O(n²) on 100k cards).
636    /// A link in half the members or more (a "learn more" every card shares) names none of them (`card_row`).
637    fn cards(&mut self, spans: &[std::ops::Range<usize>]) {
638        let ids: Vec<Vec<(usize, usize)>> = spans.iter().map(|s| link_ids(&self.lines[s.clone()])).collect();
639        let mut uses: IndexMap<usize, usize> = IndexMap::new();
640        for i in ids.iter().flat_map(|v| v.iter().map(|i| i.1).collect::<HashSet<_>>()) {
641            *uses.entry(i).or_default() += 1;
642        }
643        let own = |v: Vec<(usize, usize)>| v.into_iter().filter(|i| 2 * uses[&i.1] < spans.len()).collect::<Vec<_>>();
644        let rows: Vec<_> = spans.iter().zip(ids).map(|(s, v)| self.card_row(&self.lines[s.clone()], &own(v))).collect();
645        let ok = 5 * rows.iter().flatten().filter(|r| r.1).count() >= 4 * rows.len();
646        for (s, (row, _)) in spans.iter().zip(rows).filter_map(|(s, r)| Some((s, r?))).filter(|_| ok) {
647            self.lines[s.start] = Line::T(row);
648            self.lines[s.start + 1..s.end].fill(Line::T(String::new()));
649        }
650        let tail: Vec<Line> = self.lines.drain(spans.first().map_or(self.lines.len(), |s| s.start)..).collect();
651        self.lines.extend(tail.into_iter().filter(|l| !matches!(l, Line::T(t) if t.is_empty())));
652    }
653
654    /// `▸ title [lN] · the other pieces in page order`, and whether it is one item: its heading is a link's
655    /// (`anchor` puts a link around a heading on it), else its main link (the one around the most text) is a title
656    /// of ≥ 2 words (never a name: forum posts), and that link holds ≥ 2/5 of its links' text (else a box of links:
657    /// filters, a menu, more stories). `ids` = its own links (`link_ids`), never one the group shares. The title =
658    /// the heading, else the line holding the main link, else the first. Pieces are never reordered (a post's prose
659    /// stays in its order); only a repeat of the title drops. One line (a paragraph, a reference) is already a row;
660    /// one holding cards is their list.
661    fn card_row(&self, lines: &[Line], ids: &[(usize, usize)]) -> Option<(String, bool)> {
662        if lines.len() < 2 || lines.iter().any(|l| l.text().starts_with(CARD)) {
663            return None;
664        }
665        let anchor = |i: usize| self.links.get_index(i - 1).map_or("", |(_, a)| a.as_str());
666        let head = lines.iter().position(|l| matches!(l, Line::H(..)));
667        // the heading's link, else the one around the most text
668        let key = |i: &&(usize, usize)| (anchor(i.1).len(), lines[i.0].text().len()); // then its longest line
669        let main = ids.iter().rev().filter(|i| head.is_none_or(|h| i.0 == h)).max_by_key(key);
670        let all: usize = ids.iter().map(|i| i.1).collect::<HashSet<_>>().into_iter().map(|i| anchor(i).len()).sum();
671        // titled: the link holds most of the heading (never a type named inside it), else ≥ 2 words (never a name)
672        let titled = |m: usize| {
673            head.map_or(anchor(m).split_whitespace().nth(1).is_some(), |h| 2 * anchor(m).len() >= lines[h].text().len())
674        };
675        // a second heading = an article (a post, a review, a version's notes), never one item
676        let article = lines.iter().filter(|l| matches!(l, Line::H(..))).nth(1).is_some();
677        let one = !article && main.is_some_and(|&(_, m)| titled(m) && 5 * anchor(m).len() >= 2 * all);
678        let mark = main.map_or(String::new(), |i| format!("[l{}]", i.1));
679        let mut ps: Vec<String> =
680            lines.iter().map(|l| collapse(&l.text().trim_start_matches("- ").replace(&mark, ""))).collect();
681        let title = ps.remove(head.or(main.map(|i| i.0)).unwrap_or(0));
682        ps.retain(|p| !p.is_empty() && *p != title); // the title's alt or aria repeat; the rest in page order
683        let title = collapse(&format!("{title} {mark}"));
684        Some((format!("{CARD}{}", [vec![title], ps].concat().join(PIECE)), one))
685    }
686
687    fn walk(&mut self, id: usize, scoped: bool) {
688        let tree = self.tree;
689        let n = &tree.nodes[id];
690        let tag = n.tag.as_str();
691        if LISTS.drop_always.contains(&tag) || (tag == "noscript" && self.js) {
692            return;
693        }
694        if self.mode != Mode::Light && self.chrome(id, scoped) {
695            return;
696        }
697        self.media.extend(matches!(tag, "img" | "video").then_some(id));
698        let role = n.attr("role").unwrap_or("").to_lowercase();
699        let scoped = scoped || LISTS.sectioning.contains(&tag) || LISTS.sectioning_roles.contains(&role.as_str());
700        let top = self.inline == 0;
701        // a comment opens a section at `COMMENT` + its depth, untitled: its first line follows (`thread`)
702        if let Some(&depth) = self.thread.get(&id).filter(|_| top) {
703            self.flush();
704            self.lines.push(Line::H(COMMENT + depth.min(limit("thread_depth")), String::new()));
705        }
706        // a heading inside a comment is its text: it never ends the comment's replies
707        let quoted = || up(tree, id).any(|a| self.thread.contains_key(&a));
708        // a comment's byline = the widest element around its `<time>` in it of ≤ `byline_chars` (author, age, a
709        // badge), one line: its text starts on the next (`outline::sec_preview`), a short `No.` too
710        if tag == "time" && quoted() {
711            let short = |x: &usize| !self.thread.contains_key(x) && self.tlen[*x] <= limit("byline_chars");
712            let head = self.lines.iter().rposition(|l| matches!(l, Line::H(lv, _) if *lv >= COMMENT));
713            self.by = head.zip(up(tree, id).take_while(short).last());
714        }
715        match tag.as_bytes() {
716            [b'h', d @ b'1'..=b'6'] if top && !quoted() => self.heading(id, scoped, usize::from(d - b'0')),
717            b"pre" if top => self.pre(id),
718            _ if top && part(n, &LISTS.row) => self.row(id, scoped),
719            _ => self.inline_or_block(id, scoped, top),
720        }
721        if let Some((h, _)) = self.by.take_if(|b| b.1 == id).filter(|_| self.inline == 0) {
722            self.flush();
723            if self.lines[h + 1..].iter().all(|l| !paragraph(l.text())) && self.lines.len() > h + 2 {
724                let by: Vec<String> = self.lines.drain(h + 1..).map(|l| l.text().to_string()).collect();
725                self.lines.push(Line::T(by.join(" ")));
726            }
727        }
728    }
729
730    fn heading(&mut self, id: usize, scoped: bool, level: usize) {
731        self.flush();
732        let t = self.text_of(id, scoped);
733        self.lines.extend((!t.is_empty()).then_some(Line::H(level, t)));
734    }
735
736    /// A table row (`part`): `| cell | cell |`. A layout row (a cell holds a table, shown) or one with no cell of its
737    /// own (a `role=row` around wrappers) is its blocks.
738    fn row(&mut self, id: usize, scoped: bool) {
739        self.flush();
740        let tree = self.tree;
741        let td: Vec<usize> =
742            tree.nodes[id].kids.iter().filter_map(Kid::node).filter(|&c| part(&tree.nodes[c], &LISTS.cell)).collect();
743        if td.is_empty() || held(tree, id, &|n| n.tag == "table") {
744            return self.kids(id, scoped);
745        }
746        let cells: Vec<String> = td.into_iter().map(|c| self.text_of(c, scoped)).collect();
747        self.lines.extend(cells.iter().any(|c| !c.is_empty()).then(|| Line::T(format!("| {} |", cells.join(" | ")))));
748    }
749
750    /// Preformatted text: its own lines, trailing space dropped.
751    fn pre(&mut self, id: usize) {
752        self.flush();
753        let t: String = self.tree.texts(id, &LISTS.drop_always).collect();
754        let text = t.replace("\r\n", "\n");
755        let kept = text.split(PY_NEWLINE).filter(|ln| !py_strip(ln).is_empty());
756        self.lines.extend(kept.map(|ln| Line::T(ln.trim_end_matches(py_space).to_string())));
757    }
758
759    /// A link's text, then its `[lN]` when it has text and an href worth listing. A link around blocks (a card's
760    /// heading or whole body) flushed them as lines: their text is its text, its id goes on their heading, else on
761    /// the longest that is no paragraph (a title, never a teaser or a button), else the first. Its name
762    /// (`accname`) follows its text: `1.7M · <the thumbnail's caption> [l40]`; a link showing nothing whose name
763    /// its parent shows is `owed` to that text.
764    fn anchor(&mut self, id: usize, scoped: bool) {
765        let blocks = self.inline == 0 && held(self.tree, id, &|n| LISTS.block.contains(&n.tag.as_str()));
766        if blocks {
767            self.flush();
768        }
769        let (b0, l0, m0) = (self.marks.len(), self.lines.len(), self.media.len());
770        self.kids(id, scoped);
771        if blocks {
772            self.flush();
773        }
774        let tail = self.marks.get(b0).map_or(String::new(), |&m| self.buf[m..].to_string());
775        let text = self.lines[l0..].iter().map(Line::text).chain([tail.as_str()]).collect::<Vec<_>>().join(" ");
776        let name = self.accname(id, m0, &text);
777        let name = if name.is_empty() || py_strip(&text).is_empty() { name } else { format!("{PIECE}{name}") };
778        if py_strip(&text).is_empty() && name.is_empty() {
779            return;
780        }
781        let Some(i) = self.link(self.tree.nodes[id].attr("href").unwrap_or(""), &format!("{text}{name}")) else {
782            return;
783        };
784        let near = |p| collapse(&self.tree.texts(p, &LISTS.drop_always).collect::<Vec<_>>().join(" "));
785        if py_strip(&text).is_empty() && self.tree.nodes[id].parent.is_some_and(|p| near(p).contains(&name)) {
786            return self.owed.push((self.lines.len(), name, i));
787        }
788        if !blocks {
789            return self.push(&format!(" {name} [l{i}] "));
790        }
791        if self.lines.len() == l0 {
792            self.lines.push(Line::T(String::new())); // a picture alone: its name is the line
793        }
794        let ls = self.lines[l0..].iter().enumerate();
795        let title = ls.clone().filter(|l| !paragraph(l.1.text())).max_by_key(|l| l.1.text().chars().count());
796        let at = ls.clone().find(|l| matches!(l.1, Line::H(..))).or(title).map_or(0, |l| l.0);
797        let (Line::T(t) | Line::H(_, t)) = &mut self.lines[l0 + at];
798        *t = collapse(&format!("{t}{name} [l{i}]"));
799    }
800
801    /// An `owed` link's id goes on the first line from its own that shows its name: a card's headline, never
802    /// the name twice.
803    fn pay(&mut self) {
804        for (l0, name, i) in std::mem::take(&mut self.owed) {
805            let line = self.lines.iter_mut().skip(l0).find(|l| l.text().contains(&name));
806            if let Some(Line::T(t) | Line::H(_, t)) = line {
807                t.push_str(&format!(" [l{i}]"));
808            }
809        }
810    }
811
812    /// The name of a link whose text holds no word (a count `1.7M`, an arrow, nothing), in the order of W3C
813    /// accname 1.2 §4.3.2: its `aria-label`, else the `alt` of the pictures it served (`media` from `m0`) in
814    /// page order (a `decorative` one or `alt=""` names nothing), else its
815    /// `title` when it shows nothing; shown when it holds ≥ `name_words` words (a caption: an icon's label,
816    /// `Share this page`, `Homepage`, names no content). A thumbnail grid's caption lives only in the alt.
817    /// Empty when its text names it or another link to its target does in words (an avatar beside its user's
818    /// name, a shop's photo beside the product's title link).
819    fn accname(&self, id: usize, m0: usize, text: &str) -> String {
820        let t = self.tree;
821        let href = t.nodes[id].attr("href").and_then(|h| self.target(h));
822        if worded(text) || href.is_none_or(|h| self.worded.contains(&h)) {
823            return String::new();
824        }
825        let shown = self.media[m0..].iter().map(|&i| &t.nodes[i]).filter(|n| !decorative(n));
826        let mut alts: Vec<&str> = shown.filter_map(|n| n.attr("alt")).collect();
827        alts.dedup();
828        let alt = alts.join(" ");
829        let n = &t.nodes[id];
830        let names = [n.attr("aria-label"), Some(alt.as_str()), n.attr("title").filter(|_| py_strip(text).is_empty())];
831        let name = names.into_iter().flatten().map(collapse).find(|s| !s.is_empty()).unwrap_or_default();
832        if name.split_whitespace().count() >= limit("name_words") { name } else { String::new() }
833    }
834
835    fn inline_or_block(&mut self, id: usize, scoped: bool, top: bool) {
836        let tree = self.tree;
837        let n = &tree.nodes[id];
838        let tag = n.tag.as_str();
839        match tag {
840            "br" => self.flush(),
841            // digits-only <sup> shows as superscript: glued, `419<sup>00</sup> €` read as 41900 €
842            "sup" if let Some(t) = sup_digits(n) => self.push(&t),
843            "a" => self.anchor(id, scoped),
844            "dt" if top => {
845                self.flush();
846                let t = self.text_of(id, scoped);
847                if !t.is_empty() {
848                    self.push(&format!("{t}: "));
849                }
850            }
851            "dd" | "li" if top => {
852                if tag == "li" {
853                    self.flush();
854                    self.push("- ");
855                }
856                self.kids(id, scoped);
857                self.flush();
858            }
859            _ => {
860                let block = LISTS.block.contains(&tag);
861                if block {
862                    self.flush();
863                }
864                self.kids(id, scoped);
865                if block {
866                    self.flush();
867                } else if (tag == "span" || tag == "label") && !top {
868                    self.push(" ");
869                }
870            }
871        }
872    }
873}
874
875/// A picture hidden from screen readers or marked as decoration (`aria-hidden`, `role=presentation|none`).
876fn decorative(n: &Node) -> bool {
877    n.attr("aria-hidden") == Some("true") || matches!(n.attr("role"), Some("presentation" | "none"))
878}
879
880/// A text holds a word: two letters in a row (`1.7M`, `x4`, `›`, `12` hold none; `user123` does).
881fn worded(text: &str) -> bool {
882    text.chars().zip(text.chars().skip(1)).any(|(a, b)| a.is_alphabetic() && b.is_alphabetic())
883}
884
885/// The `[lN]` link ids in `lines`: (line index, N).
886fn link_ids(lines: &[Line]) -> Vec<(usize, usize)> {
887    let id = |(k, m): (usize, regex::Match)| Some((k, m.as_str()[2..m.len() - 1].parse::<usize>().ok()?));
888    let ids = lines.iter().enumerate().flat_map(|(k, l)| LREF.find_iter(l.text()).map(move |m| (k, m)));
889    ids.filter_map(id).collect()
890}
891
892/// A member that opens with a byline (its first line: the first block, else the inline run before one, holding
893/// no block, so one line, and a `<time>`) and holds no heading: a comment, an author and its age, never a card
894/// (a dated post's title is a heading; a link around the whole card is no line).
895fn byline(t: &Tree, tlen: &[usize], id: usize) -> bool {
896    let block = |n: &Node| LISTS.block.contains(&n.tag.as_str());
897    let (line, time) = (|k: &usize| !held(t, *k, &block), |k: usize| held(t, k, &|n| n.tag == "time"));
898    let mut shown = t.nodes[id].kids.iter().filter_map(Kid::node).filter(|&k| tlen[k] > 0).peekable();
899    let first = shown.next_if(|&k| block(&t.nodes[k])).map(|k| vec![k]);
900    let first = first.unwrap_or_else(|| shown.take_while(|&k| !block(&t.nodes[k]) && line(&k)).collect());
901    let head = held(t, id, &|n| matches!(n.tag.as_bytes(), [b'h', b'1'..=b'6']));
902    !head && first.iter().all(line) && first.into_iter().any(|k| t.nodes[k].tag == "time" || time(k))
903}
904
905/// An element's shape for `groups`: its tag and first class.
906fn shape(n: &Node) -> (&str, &str) {
907    (n.tag.as_str(), n.attr("class").and_then(|c| c.split_whitespace().next()).unwrap_or(""))
908}
909
910/// A table's row or cell (`row`, `cell` in clean.json) by its tag or its ARIA role: the role is the element's
911/// meaning (WAI-ARIA 1.2), so a `div` grid of `role=row` / `role=cell` reads as the table it says it is.
912fn part(n: &Node, of: &[&str]) -> bool {
913    of.contains(&n.tag.as_str()) || n.attr("role").is_some_and(|r| of.contains(&r.to_lowercase().as_str()))
914}
915
916/// Some element below `id` (never `id` itself) is `f`.
917fn held(t: &Tree, id: usize, f: &impl Fn(&Node) -> bool) -> bool {
918    t.walk(id, &LISTS.drop_always).skip(1).any(|v| matches!(v, Visit::Node(n) if f(n)))
919}
920
921/// A `<sup>` holding only text of ASCII digits, as Unicode superscript digits.
922fn sup_digits(n: &Node) -> Option<String> {
923    let t = n.kids.iter().map(|k| if let Kid::Text(s) = k { Some(s.as_str()) } else { None });
924    let t: String = t.collect::<Option<_>>()?;
925    const SUP: [char; 10] = ['⁰', '¹', '²', '³', '⁴', '⁵', '⁶', '⁷', '⁸', '⁹'];
926    let sup = |c: char| SUP[c as usize - '0' as usize];
927    (!t.is_empty() && t.chars().all(|c| c.is_ascii_digit())).then(|| t.chars().map(sup).collect())
928}
929
930/// A Python `str.splitlines()` boundary (`\r\n` counts once: fold it to `\n` first).
931const PY_NEWLINE: [char; 10] = ['\n', '\r', '\x0b', '\x0c', '\x1c', '\x1d', '\x1e', '\u{85}', '\u{2028}', '\u{2029}'];
932
933fn skip_link(u: &str) -> bool {
934    u.match_indices('/').any(|(i, _)| {
935        let r = &u[i + 1..];
936        LISTS.skip_link.iter().any(|w| {
937            r.len() >= w.len()
938                && r.as_bytes()[..w.len()].eq_ignore_ascii_case(w.as_bytes())
939                && r[w.len()..].chars().next().is_none_or(|c| !is_word(c))
940        })
941    })
942}
943
944/// Host of a URL, lowercased; "" when it has none (local files, `stdin:`).
945pub fn host_of(url: &str) -> String {
946    let host = url::Url::parse(url).ok();
947    host.and_then(|u| u.host_str().map(|h| h.trim_matches(['[', ']']).to_lowercase())).unwrap_or_default()
948}
949
950// ------------------------------------------------------------------ facts + page info
951/// Numbers, prices, dates: `\d+(?:[.,:/-]\d+)*` tokens with ≥ 2 digits; `priced`: only those with a currency mark
952/// (`Lists::currency`) right before or after them, a space between allowed. Our own `[lN]` link ids are not the
953/// page's numbers: never counted (they made the loss guard serve the nav).
954pub fn facts(lines: &[Line], priced: bool) -> HashSet<String> {
955    let mut s = HashSet::new();
956    for ln in lines {
957        let cs: Vec<char> = LREF.replace_all(ln.text(), " ").chars().collect();
958        let digit = |k: usize| cs.get(k).is_some_and(|c| is_digit(*c));
959        let mut from = 0;
960        while let Some(st) = (from..cs.len()).find(|&k| digit(k)) {
961            // a separator joins when a digit of the match is before it and a digit after it
962            let joins =
963                |k: usize| k > st && matches!(cs[k], '.' | ',' | ':' | '/' | '-') && digit(k - 1) && digit(k + 1);
964            let end = (st..cs.len()).find(|&k| !digit(k) && !joins(k)).unwrap_or(cs.len());
965            let (before, after): (String, String) =
966                (cs[st.saturating_sub(4)..st].iter().collect(), cs[end..].iter().take(4).collect());
967            let mark = |c: &&str| before.trim_end().ends_with(c) || after.trim_start().starts_with(c);
968            let digits = cs[st..end].iter().filter(|c| is_digit(**c)).count();
969            if digits >= 2 && (!priced || LISTS.currency.iter().any(mark)) {
970                s.insert(cs[st..end].iter().collect());
971            }
972            from = end.max(st + 1);
973        }
974    }
975    s
976}
977
978/// og_only's page (`fetch::og_card`, a stored `og` body: `cache::build`): the shell's own og card, its text the
979/// title and info line; the shell's own text (enable JavaScript) is not the page.
980pub fn card(d: Doc) -> Doc {
981    let clean = tok(&d.title) + d.info.values().map(|v| tok(v)).sum::<usize>();
982    Doc { mode: "og".into(), sections: Vec::new(), tokens: Tokens { clean }, ..d }
983}
984
985/// Text as HTML text or a quoted attribute value: `&` `"` `<` `>` escaped.
986pub fn esc(v: &str) -> String {
987    v.replace('&', "&amp;").replace('"', "&quot;").replace('<', "&lt;").replace('>', "&gt;")
988}
989
990/// A server's Markdown (`kind_of` md: its own conversion of the page) → HTML (CommonMark, tables) cleaned like any
991/// page (`build_doc`: sections, `[lN]` links, media, the loss guard), `mode` md. The frontmatter's `title`
992/// `description` `image` become og tags, as the page's head has them; with no title there, the first `# ` heading.
993/// A code block holding JSON-LD is the page's JSON-LD (author, dates), as a `<script>` in HTML is.
994pub fn markdown(raw: &[u8], url: &str, fin: &str) -> Doc {
995    use pulldown_cmark::{Event, Options, Parser, Tag, TagEnd};
996    let text = String::from_utf8_lossy(raw);
997    let front = text.strip_prefix("---").and_then(|r| r.split_once("\n---")).map_or("", |(f, _)| f);
998    let og =
999        front.lines().filter_map(|l| l.split_once(':')).map(|(k, v)| (k.trim(), v.trim().trim_matches(['"', '\''])));
1000    let og = og.filter(|(k, _)| matches!(*k, "title" | "description" | "image"));
1001    // the title: the frontmatter's, else the first `# ` heading
1002    let h1 = text.lines().find_map(|l| l.strip_prefix("# ")).unwrap_or_default();
1003    let og: String = og.map(|(k, v)| format!("<meta property=\"og:{k}\" content=\"{}\">", esc(v))).collect();
1004    let mut html = format!("<title>{}</title>{og}", esc(h1));
1005    let opts = Options::ENABLE_YAML_STYLE_METADATA_BLOCKS | Options::ENABLE_TABLES;
1006    let mut ev: Vec<Event> = Parser::new_ext(&text, opts).collect();
1007    // JSON-LD comes as a code block (Markdown has no script): the page's JSON-LD, as in its HTML, never text
1008    let ld = |w: &[Event]| matches!(w, [Event::Start(Tag::CodeBlock(_)), Event::Text(t), Event::End(TagEnd::CodeBlock)] if t.trim_start().starts_with("{\"@context\""));
1009    while let Some(i) = ev.windows(3).position(ld) {
1010        let Event::Text(t) = &ev[i + 1] else { break };
1011        let script = format!("<script type=\"application/ld+json\">{t}</script>");
1012        ev.splice(i..i + 3, [Event::Html(script.into())]);
1013    }
1014    pulldown_cmark::html::push_html(&mut html, ev.into_iter());
1015    Doc { mode: "md".into(), ..build_doc(&crate::html::parse(&html), url, fin, false) }
1016}
1017
1018/// A key's value when truthy; a list there → its first item.
1019fn pick<'a>(v: &'a Value, k: &str) -> Option<&'a Value> {
1020    match v.get(k).filter(|x| truthy(x))? {
1021        Value::Array(v) => v.first(),
1022        x => Some(x),
1023    }
1024}
1025
1026/// Python's truth of a JSON value.
1027fn truthy(v: &Value) -> bool {
1028    match v {
1029        Value::Null => false,
1030        Value::Bool(b) => *b,
1031        Value::Number(n) => n.as_f64().is_some_and(|f| f != 0.0),
1032        Value::String(s) => !s.is_empty(),
1033        Value::Array(v) => !v.is_empty(),
1034        Value::Object(v) => !v.is_empty(),
1035    }
1036}
1037
1038/// Text of a value: strings as-is, numbers as written (`330`, `12.5`, as Python's `str()`), a list → its first
1039/// item, an object → its `name`.
1040fn py_str(v: &Value) -> String {
1041    match v {
1042        Value::Null => String::new(),
1043        Value::Bool(b) => if *b { "True" } else { "False" }.into(),
1044        Value::Number(n) => n.to_string(),
1045        Value::String(s) => s.clone(),
1046        Value::Array(v) => v.first().map(py_str).unwrap_or_default(),
1047        Value::Object(_) => v.get("name").map(py_str).unwrap_or_default(),
1048    }
1049}
1050
1051/// Chars of the strings holding a space (prose, not ids or URLs) in a JSON value; a string opening like JSON is read
1052/// as JSON (a store serialised twice).
1053fn prose_chars(j: &Value) -> usize {
1054    match j {
1055        Value::String(s) if s.starts_with(['{', '[']) => serde_json::from_str(s).map_or(0, |inner| prose_chars(&inner)),
1056        Value::String(s) if py_strip(s).contains(' ') => s.chars().count(),
1057        Value::Array(v) => v.iter().map(prose_chars).sum(),
1058        Value::Object(v) => v.values().map(prose_chars).sum(),
1059        _ => 0,
1060    }
1061}
1062
1063/// Text no render shows: `<template>` contents (`measure` put them in the element's `tlen`) and the prose of the
1064/// data scripts.
1065fn inert_chars(t: &Tree, tlen: &[usize]) -> usize {
1066    let templates = (0..t.nodes.len()).filter(|&i| t.nodes[i].tag == "template").map(|i| tlen[i]);
1067    let json = t.json.iter().filter_map(|(_, j, _)| serde_json::from_str::<Value>(py_strip(j)).ok());
1068    templates.sum::<usize>() + json.map(|j| prose_chars(&j)).sum::<usize>()
1069}
1070
1071fn walk_ld<'a>(j: &'a Value, depth: usize, out: &mut Vec<&'a Value>) {
1072    if depth > 6 {
1073        return;
1074    }
1075    match j {
1076        Value::Object(v) => {
1077            out.push(j);
1078            v.values().for_each(|x| walk_ld(x, depth + 1, out));
1079        }
1080        Value::Array(v) => v.iter().for_each(|x| walk_ld(x, depth + 1, out)),
1081        _ => {}
1082    }
1083}
1084
1085/// The head: `info`, its media (og:image, twitter:image, og:video, each with its `:alt` `:width` `:height`
1086/// `:type`; then JSON-LD, `<link rel=image_src>`) and how many of them are those og/twitter cards.
1087fn page_info(t: &Tree, base: &str) -> (Info, Vec<Media>, usize) {
1088    let (mut info, mut media) = (meta_info(t), Vec::new());
1089    for key in ["og:image", "twitter:image", "og:video"] {
1090        let get = |k: &str| t.meta(&format!("{key}{k}")).unwrap_or_default();
1091        let src = ["", ":url", ":secure_url"].iter().map(|k| get(k)).find(|s| !s.is_empty()).unwrap_or_default();
1092        let (alt, w, h, ty) = (get(":alt").into(), px(get(":width")), px(get(":height")), get(":type").into());
1093        add(&mut media, base, Media { src: src.into(), alt, video: key == "og:video", w, h, ty, ..Media::default() });
1094    }
1095    let og = media.len();
1096    for (_, blob, _) in t.json.iter().filter(|j| j.2).take(20) {
1097        let Ok(json) = serde_json::from_str::<Value>(py_strip(blob)) else { continue };
1098        let mut objs = Vec::new();
1099        walk_ld(&json, 0, &mut objs);
1100        for obj in objs {
1101            ld_info(obj, &mut info);
1102            ld_media(obj, base, &mut media);
1103        }
1104    }
1105    let rel =
1106        |n: &&Node| n.attr("rel").is_some_and(|r| r.split_whitespace().any(|w| w.eq_ignore_ascii_case("image_src")));
1107    for n in t.nodes.iter().filter(|n| n.tag == "link").filter(rel) {
1108        add(&mut media, base, Media { src: n.attr("href").unwrap_or_default().into(), ..Media::default() });
1109    }
1110    info.extend(t.meta("og:site_name").map(|s| ("site".to_string(), s.to_string())));
1111    let info = info.into_iter().filter(|(_, v)| !v.is_empty()).map(|(k, v)| (k, collapse(&unescape(&v))));
1112    (info.collect(), media, og)
1113}
1114
1115/// A declared size (`1200`, `1200px`); 0 = none or not a number.
1116fn px(v: &str) -> u32 {
1117    v.trim().trim_end_matches("px").parse().unwrap_or(0)
1118}
1119
1120/// A JSON-LD object's pictures: an `ImageObject` (`contentUrl` or `url`, its `caption` as the alt, its size), and
1121/// the URLs in `image` / `thumbnailUrl` (an object there is walked as its own too); its `logo` is not content (added
1122/// before the logo's own `ImageObject` is walked, so the picture keeps that verdict, `add`).
1123fn ld_media<'a>(obj: &'a Value, base: &str, out: &mut Vec<Media>) {
1124    let text = |k: &str| obj.get(k).map(py_str).unwrap_or_default();
1125    let list = |v: &'a Value| if let Value::Array(v) = v { v.as_slice() } else { std::slice::from_ref(v) };
1126    let url_of = |u: &Value| if let Value::String(s) = u.get("url").unwrap_or(u) { s.clone() } else { String::new() };
1127    for (k, demoted) in [("logo", true), ("image", false), ("thumbnailUrl", false)] {
1128        for u in obj.get(k).into_iter().flat_map(list) {
1129            add(out, base, Media { src: url_of(u), demoted, ..Media::default() });
1130        }
1131    }
1132    if text("@type") == "ImageObject" {
1133        let src = if text("contentUrl").is_empty() { text("url") } else { text("contentUrl") };
1134        let (alt, w, h) = (text("caption"), px(&text("width")), px(&text("height")));
1135        add(out, base, Media { src, alt, w, h, ..Media::default() });
1136    }
1137}
1138
1139/// A served `<img>` or a `<video>`'s poster, its alt and declared size; a `decorative` one is none. The source is the
1140/// tag's largest: a `srcset` candidate (its `<picture>`'s too), else a `data-*` source a script swaps in (named by a
1141/// `lazy_src` word: the lazy or hi-res copy where `src` is a placeholder or a thumbnail), else `src`. Demoted: classed
1142/// as a logo or an icon (`has_word`), or linked elsewhere.
1143fn body_media(t: &Tree, id: usize, base: &str) -> Option<Media> {
1144    let (n, page) = (&t.nodes[id], url::Url::parse(base).ok()?);
1145    if decorative(n) {
1146        return None;
1147    }
1148    let attr = |k: &str| n.attr(k).unwrap_or_default();
1149    let (w, h, alt) = (px(attr("width")), px(attr("height")), collapse(attr("alt")));
1150    if n.tag == "video" {
1151        return Some(Media { src: n.attr("poster")?.into(), video: true, w, h, ..Media::default() });
1152    }
1153    let pic = n.parent.filter(|&p| t.nodes[p].tag == "picture").map(|p| &t.nodes[p].kids[..]).unwrap_or_default();
1154    let source = |k: &Kid| k.node().and_then(|c| t.nodes[c].attr("srcset"));
1155    let set: Vec<&str> = pic.iter().filter_map(source).chain(n.attr("srcset")).chain(n.attr("data-srcset")).collect();
1156    let named = |k: &str| k.strip_prefix("data-").is_some_and(|k| LISTS.lazy_src.iter().any(|w| k.contains(w)));
1157    let data = n.attrs.iter().find(|(k, v)| named(k) && v.starts_with(['/', 'h']) && !v.contains(' '));
1158    let src = largest(&set.join(", ")).map(String::from).or(data.map(|d| d.1.clone()));
1159    let url = page.join(py_strip(&src.or(n.attr("src").map(String::from))?)).ok()?;
1160    let (away, linked) = links(t, id, &page);
1161    let demoted = has_word(attr("class"), &LISTS.not_content) || away || ad_slot(t, id);
1162    Some(Media { src: url.into(), alt, w, h, demoted, linked, ..Media::default() })
1163}
1164
1165/// The links on a picture: an `<a href>` around it, or an empty one laid over it in its box (a card's overlay
1166/// link), but none to the page itself or below it (`/post/1/photo/1`). `.0` = one goes to another page: a related
1167/// story's, another product's, a feed item's picture. `.1` = the one around it goes to the picture's own: a path
1168/// with an image file type in it (a lightbox, the original, a `File:x.jpg` page) or a `picture_page` word
1169/// (`/photos/1`, `/image-article/…`, `/attachment/…`; a gallery's).
1170fn links(t: &Tree, id: usize, page: &url::Url) -> (bool, bool) {
1171    let above: Vec<usize> = up(t, id).skip(1).collect();
1172    let empty = |c: &usize| t.nodes[*c].tag == "a" && t.texts(*c, &[]).all(|s| s.trim().is_empty());
1173    let kids = above.iter().take(2).flat_map(|&p| &t.nodes[p].kids);
1174    let overlay = kids.filter_map(Kid::node).filter(empty);
1175    let below = |u: &url::Url| page.path().len() > 1 && u.path().starts_with(page.path());
1176    let href =
1177        |a: usize| page.join(t.nodes[a].attr("href")?).ok().filter(|u| u.scheme().starts_with("http") && !below(u));
1178    let own = |u: &url::Url| has_word(u.path(), &LISTS.image_ext) || has_word(u.path(), &LISTS.picture_page);
1179    let around: Vec<url::Url> = above.iter().filter(|&&p| t.nodes[p].tag == "a").filter_map(|&a| href(a)).collect();
1180    let away = around.iter().chain(&overlay.filter_map(href).collect::<Vec<_>>()).any(|u| !own(u));
1181    (away, around.iter().any(own))
1182}
1183
1184/// A picture in an ad slot: it, or an element around it, is named an ad by a whole word (or its plural,
1185/// `has_word`) of its tag, class or id (`ad_slot`: `<x-ad-post>`, `class="ad-slot"`; never `advert`, `promoted`,
1186/// `sponsored`: classifieds sites name their real listings so) and holds under `ad_slot_words` words and no number
1187/// (`facts`: a listing's price, date or size keeps its photo). Demoted: listed, not counted.
1188fn ad_slot(t: &Tree, id: usize) -> bool {
1189    let max: usize = limit("ad_slot_words");
1190    let name = |n: &Node| format!("{} {} {}", n.tag, n.attr("class").unwrap_or(""), n.attr("id").unwrap_or(""));
1191    let small = |p: usize| {
1192        let text = || t.texts(p, &LISTS.drop_always).flat_map(str::split_whitespace);
1193        let few = text().filter(|w| w.chars().any(char::is_alphanumeric)).nth(max.saturating_sub(1)).is_none();
1194        few && facts(&[Line::T(text().collect::<Vec<_>>().join(" "))], false).is_empty()
1195    };
1196    up(t, id).any(|p| has_word(&name(&t.nodes[p]), &LISTS.ad_slot) && small(p))
1197}
1198
1199/// The largest candidate of a `srcset` (by its `w` or `x` descriptor; none = 1x).
1200fn largest(set: &str) -> Option<&str> {
1201    let size = |d: Option<&str>| d.and_then(|d| d.get(..d.len() - 1)?.parse::<f64>().ok()).unwrap_or(1.0);
1202    let all =
1203        set.split(", ").filter_map(|c| c.split_whitespace().next().map(|u| (u, size(c.split_whitespace().nth(1)))));
1204    all.max_by(|a, b| a.1.total_cmp(&b.1)).map(|c| c.0)
1205}
1206
1207/// A word of an alt, a class or a file name (lower case, or its singular) is in `list`: `not_content` says the
1208/// picture is a logo, an icon, a badge; `filler` that the file is a spacer.
1209fn has_word(text: &str, list: &[&str]) -> bool {
1210    words(text).iter().any(|w| list.contains(&w.strip_suffix('s').unwrap_or(w)))
1211}
1212
1213/// The words of a text, lower case, split on anything not a letter or a digit.
1214fn words(text: &str) -> Vec<String> {
1215    text.to_lowercase().split(|c: char| !c.is_alphanumeric()).filter(|w| !w.is_empty()).map(String::from).collect()
1216}
1217
1218/// Size words in a picture URL (lower case): `250px-`, `-150x84` `_389x557` `/1200x630wa`, `@2x`, `=s1600`, `w_1456`.
1219static SIZE: LazyLock<regex::Regex> = LazyLock::new(|| {
1220    regex::Regex::new(r"\d{2,4}px-|(?:[-_]|\b)(\d{2,4})x(\d{2,4})|@[1-4]x|=s\d{2,4}|\b[wh]_\d{2,4}\b")
1221        .expect("a pattern")
1222});
1223
1224/// Where a picture's file name ends: at its first image extension (`.jpg.webp`, `.jpg_960x960q75.jpg_.avif`) or
1225/// a transform chain after a `=` (`=w1060-fcrop64…`).
1226static NAME_END: LazyLock<regex::Regex> = LazyLock::new(|| {
1227    regex::Regex::new(&format!(r"\.(?:{})(?:[^a-z0-9]|$)|=", LISTS.image_ext.join("|"))).expect("a pattern")
1228});
1229
1230/// One picture's identity and size by its URL (one picture at several sizes is one row): the file's own name
1231/// (`NAME_END`) without size words (`SIZE`), never its folders or query, where CDNs put sizes and crops, but with
1232/// a proxied original (a query value with a `/` and a `.`: `_next/image?url=`, an image proxy's `?url=`); a name under
1233/// 8 chars or of one word with no digit (`image`, `hqdefault`) keeps its folders. Two different file names are
1234/// never one picture (`IMG_2026.10.11.jpg`, `.12.jpg`). The size: the largest number of its size words, or a `w`
1235/// or `width` query.
1236fn key_of(u: &url::Url) -> (String, u32) {
1237    let path = u.path().to_lowercase().replace("%2f", "/");
1238    let (dir, file) = path.rsplit_once('/').unwrap_or_default();
1239    let name = SIZE.replace_all(NAME_END.find(file).map_or(file, |m| &file[..m.start()]), "");
1240    let word = !name.contains(|c: char| c.is_ascii_digit() || !c.is_alphanumeric());
1241    let query: Vec<_> = u.query_pairs().map(|(_, v)| v).filter(|v| v.contains('/') && v.contains('.')).collect();
1242    let dir = if name.len() < 8 || word { SIZE.replace_all(dir, "") } else { "".into() };
1243    let key = format!("{dir}{name}?{}", query.join("&"));
1244    let words = SIZE.find_iter(&path).flat_map(|m| m.as_str().split(|c: char| !c.is_ascii_digit()).map(str::parse));
1245    let width = u.query_pairs().filter(|(k, _)| k == "w" || k == "width").map(|(_, v)| v.parse());
1246    (key, words.chain(width).filter_map(Result::ok).max().unwrap_or(0))
1247}
1248
1249/// One media row into `out`, its URL resolved against `base`, known tracking parameters (`tracking`) cut.
1250/// Refused: no URL, one that is not http(s) or file (data:), an svg, a declared side under `ICON`, a filler (a
1251/// GIF named as one, or any file named `placeholder`: `pxl.gif`, `grey-placeholder.png`). The same picture
1252/// (`key_of`) keeps its first place and verdict (`demoted`: a head card over a linked copy, a JSON-LD logo over
1253/// its own object, a share card: `og`, `share`, `card`… as a word of its file name, `share_card`, or an Open
1254/// Graph host label, `share_host`), gains the alt it lacked and takes the larger copy (declared side, else the
1255/// URL's size word).
1256fn add(out: &mut Vec<Media>, base: &str, m: Media) {
1257    let m = Media { alt: unjson(&m.alt), ..m };
1258    let url = url::Url::parse(base).and_then(|b| b.join(py_strip(&m.src))).ok().filter(|_| !m.src.trim().is_empty());
1259    let Some(mut url) = url.filter(|u| matches!(u.scheme(), "http" | "https" | "file")) else { return };
1260    let ext = url.path().rsplit_once('.').map(|e| e.1.to_ascii_lowercase()).filter(|e| (2..=4).contains(&e.len()));
1261    let ty = m.ty.rsplit('/').next().map(str::to_string).filter(|t| !t.is_empty()).or(ext).unwrap_or_default();
1262    let file = url.path_segments().and_then(|mut s| s.next_back()).unwrap_or_default();
1263    let filler = has_word(file, &["placeholder"]) || ty == "gif" && has_word(file, &LISTS.filler);
1264    // a share card: whole words of its own file name (a proxied one's last part), or a card host's first label
1265    let (host, last) = (url.host_str().and_then(|h| h.split('.').next()), file.to_lowercase().replace("%2f", "/"));
1266    let own = has_word(last.rsplit('/').next().unwrap_or_default(), &LISTS.share_card);
1267    let card = own || has_word(host.unwrap_or_default(), &LISTS.share_host);
1268    let side = |c: &regex::Captures, i| c.get(i).and_then(|n| n.as_str().parse().ok());
1269    let named = SIZE.captures_iter(&file.to_lowercase()).find_map(|c| side(&c, 1).zip(side(&c, 2)));
1270    // the file name's size filters (a strip, an icon) and picks the larger copy, never stored as declared
1271    let (w, h) = if m.w == 0 && m.h == 0 { named.unwrap_or_default() } else { (m.w, m.h) };
1272    // a strip (one side ≥ `strip_aspect` × the other), an icon or a spacer (a declared side under `icon_px`)
1273    let (aspect, icon): (u32, u32) = (limit("strip_aspect"), limit("icon_px"));
1274    let strip = w.min(h) > 0 && w.max(h) >= aspect * w.min(h);
1275    if filler || strip || ty.starts_with("svg") || (1..icon).contains(&w) || (1..icon).contains(&h) {
1276        return;
1277    }
1278    let tracking = |kv: &&str| LISTS.tracking.iter().any(|t| kv.to_lowercase().starts_with(t));
1279    let kept: Vec<&str> = url.query().into_iter().flat_map(|q| q.split('&')).filter(|kv| !tracking(kv)).collect();
1280    url.set_query(Some(kept.join("&")).filter(|q| !q.is_empty()).as_deref());
1281    let (key, by_url) = key_of(&url);
1282    let m = Media { key: (key, w.max(h).max(by_url)), src: url.into(), ty, demoted: m.demoted || card, ..m };
1283    let Some(x) = out.iter_mut().find(|x| x.key.0 == m.key.0) else { return out.push(m) };
1284    let alt = if x.alt.is_empty() { m.alt.clone() } else { std::mem::take(&mut x.alt) };
1285    if m.key.1 > x.key.1 {
1286        *x = Media { demoted: x.demoted, ..m };
1287    }
1288    x.alt = alt;
1289}
1290
1291/// Alt text as a reader sees it: JSON escapes a page left in an attribute (`\u2019`, a surrogate pair) decoded,
1292/// `\n` `\t` `\r` and runs of whitespace one space.
1293fn unjson(s: &str) -> String {
1294    let (mut out, mut rest) = (Vec::new(), s);
1295    while let Some(c) = rest.chars().next() {
1296        let hex = rest.strip_prefix("\\u").and_then(|r| r.get(..4)).filter(|h| !h.starts_with('+'));
1297        let (units, len) = match hex.map(|h| u16::from_str_radix(h, 16)) {
1298            Some(Ok(u)) => (vec![u], 6),
1299            _ if ["\\n", "\\t", "\\r"].iter().any(|e| rest.starts_with(e)) => (vec![32], 2),
1300            _ => (c.encode_utf16(&mut [0; 2]).to_vec(), c.len_utf8()),
1301        };
1302        out.extend(units);
1303        rest = &rest[len..];
1304    }
1305    collapse(&String::from_utf16_lossy(&out))
1306}
1307
1308/// MEDIA in rank order: the og/twitter cards as they came (`page_info`), then the rest of the head
1309/// and the served pictures (`body_media`, after the chrome prune) by alt length, then declared size, then
1310/// document order, one row per picture (`add`); the `demoted` go last: avatars (both sides ≤ `AVATAR`, square
1311/// within 0.8-1.25), a bare `@handle` alt, an alt that is the author's or the site's name (`info`), a logo or an
1312/// icon by its URL or an alt of ≤ 3 words (`has_word`: `/brand/site_logo.png`, an `avatars.` host). Never the title: a
1313/// shop or a listing alts its main photo with it, so that photo stays content, its alt dropped (`(no alt)`: the title
1314/// says nothing about the picture).
1315fn rank(cards: (Vec<Media>, usize), t: &Tree, body: &[usize], base: &str, info: &Info) -> Vec<Media> {
1316    let (mut out, head) = cards;
1317    body.iter().filter_map(|&id| body_media(t, id, base)).for_each(|m| add(&mut out, base, m));
1318    out[head..].sort_by_key(|m| std::cmp::Reverse((m.alt.chars().count(), u64::from(m.w) * u64::from(m.h))));
1319    let named = |a: &str, keys: &[&str]| info.iter().any(|(k, v)| keys.contains(&k.as_str()) && v.to_lowercase() == a);
1320    // the site's name as whole words in an alt of at most 2 more (site "X" never names "Red fox"); no name, none
1321    let site = words(info.get("site").map_or("", String::as_str));
1322    let has_site = |a: &str| words(a).windows(site.len().max(1)).any(|w| w == site) && words(a).len() <= site.len() + 2;
1323    // an avatar: both sides ≤ `avatar_px` and square-ish (last)
1324    let avatar_px: u32 = limit("avatar_px");
1325    for m in &mut out {
1326        let (alt, (small, big)) = (m.alt.to_lowercase(), (m.w.min(m.h), m.w.max(m.h)));
1327        let words = alt.split_whitespace().count();
1328        let avatar = small > 0 && big <= avatar_px && 4 * big <= 5 * small && words < 4 && !m.linked;
1329        let handle = alt.starts_with('@') && !alt.contains(' ');
1330        // a logo or a badge is named in a few words; a caption's "emoji" or "badge" describes a screenshot
1331        let few = words <= 3 && (has_word(&alt, &LISTS.not_content) || has_word(&alt, &LISTS.not_content_alt));
1332        let named_by = few || has_word(&m.src, &LISTS.not_content) || has_site(&alt);
1333        m.demoted |= avatar || handle || named(&alt, &["author"]) || named_by;
1334        if named(&alt, &["title"]) || alt == collapse(&t.title).to_lowercase() {
1335            m.alt.clear();
1336        }
1337    }
1338    out.sort_by_key(|m| m.demoted);
1339    out
1340}
1341
1342/// The `<meta>` half of `info`: title, description, author, dates, price. The title = `og:title`, else the first
1343/// `h1` when `<title>` is only the site's name and its tagline (one own word before a suffix: THE own-words rule,
1344/// `fetch::words_of`; `Reddit - The heart of the internet` on every thread; none = a wall's, no suffix = maybe
1345/// an error's, `Site Maintenance`) and shares none of its words with the `h1` (its text outside controls:
1346/// `tokio - Rust` over `<h1>Crate tokio <button>Copy item path</button></h1>` is the page's own title; `Home -
1347/// Away - League` with `<h1>Home</h1>`), else `<title>`. Either title up to its suffix that is the `h1` and one
1348/// bracketed qualifier (`NASA (@nasa) | Site` over `<h1>NASA</h1>`: a name and its handle) yields to the `h1`, so
1349/// a render caught before its script set the title (the site's name, the same `h1`) reads the same title.
1350fn meta_info(t: &Tree) -> Info {
1351    let mut info = IndexMap::new();
1352    let og = t.meta("og:title");
1353    let named = og.unwrap_or(&t.title);
1354    let site = og.is_none() && matches!(title_head(named), h if h.len() < named.len() && words_of(h).len() == 1);
1355    let text = |i| collapse(&t.texts(i, &["button", "input", "select"]).collect::<String>());
1356    let apart = |h: &str| site && words_of(named).iter().all(|w| !words_of(h).contains(w));
1357    let mine = |h: &String| !h.is_empty() && (apart(h) || qualified(title_head(named), h));
1358    let title = t.nodes.iter().position(|n| n.tag == "h1").map(text).filter(mine);
1359    info.insert("title".into(), title.unwrap_or_else(|| named.to_string()));
1360    for (key, names) in &LISTS.info {
1361        // an author that is a URL names no one; a description is cut to 300 chars
1362        let named = |v: &&str| *key != "author" || !v.starts_with("http");
1363        let Some(v) = names.iter().find_map(|k| t.meta(k)).filter(named) else { continue };
1364        let cut = if *key == "description" { 300 } else { usize::MAX };
1365        info.insert(key.to_string(), v.chars().take(cut).collect());
1366    }
1367    if let Some(price) = t.meta("product:price:amount").or(t.meta("og:price:amount")) {
1368        let cur = t.meta("product:price:currency").or(t.meta("og:price:currency")).unwrap_or("");
1369        info.insert("price".into(), format!("{price} {cur}"));
1370    }
1371    info
1372}
1373
1374/// `head` = `name` and one bracketed qualifier after it (`NASA (@nasa)`, `vitiral (u/vitiral)`).
1375fn qualified(head: &str, name: &str) -> bool {
1376    let rest = head.strip_prefix(name).unwrap_or_default().trim_start();
1377    rest.strip_prefix('(').and_then(|q| q.strip_suffix(')')).is_some_and(|q| !q.contains(['(', ')']))
1378}
1379
1380/// One JSON-LD object fills the `info` keys still missing: author, dates, price, rating.
1381fn ld_info(obj: &Value, info: &mut Info) {
1382    if !info.contains_key("author")
1383        && let Some(author @ (Value::Object(_) | Value::String(_))) = pick(obj, "author")
1384        && let Some(name) = author.get("name").or(Some(author).filter(|a| a.is_string()))
1385        && truthy(name)
1386        && !py_str(name).starts_with("http")
1387    {
1388        info.insert("author".into(), py_str(name));
1389    }
1390    for (key, ld) in [("published", "datePublished"), ("modified", "dateModified")] {
1391        if !info.contains_key(key)
1392            && let Some(date) = pick(obj, ld)
1393        {
1394            info.insert(key.into(), py_str(date));
1395        }
1396    }
1397    if !info.contains_key("price")
1398        && let Some(offer @ Value::Object(_)) = pick(obj, "offers")
1399        && let Some(price) = pick(offer, "price").or(pick(offer, "lowPrice"))
1400    {
1401        let cur = offer.get("priceCurrency").map(py_str).unwrap_or_default();
1402        info.insert("price".into(), py_strip(&format!("{} {cur}", py_str(price))).to_string());
1403    }
1404    if !info.contains_key("rating")
1405        && let Some(rating @ Value::Object(_)) = obj.get("aggregateRating")
1406        && let Some(value) = pick(rating, "ratingValue")
1407    {
1408        let count = pick(rating, "reviewCount").or(pick(rating, "ratingCount")).map_or("?".into(), py_str);
1409        info.insert("rating".into(), format!("{} ({count} reviews)", py_str(value)));
1410    }
1411}
1412
1413fn render<'a>(t: &'a Tree, tlen: &'a [usize], base: &str, mode: Mode, js: bool) -> Render<'a> {
1414    let mut r = Render {
1415        tree: t,
1416        tlen,
1417        base_url: url::Url::parse(base.split('#').next().unwrap_or(base)).ok(),
1418        mode,
1419        js,
1420        lines: Vec::new(),
1421        buf: String::new(),
1422        marks: Vec::new(),
1423        links: IndexMap::new(),
1424        inline: 0,
1425        media: Vec::new(),
1426        thread: HashMap::new(),
1427        by: None,
1428        worded: HashSet::new(),
1429        owed: Vec::new(),
1430    };
1431    r.thread = r.comments();
1432    r.worded = r.worded_links();
1433    r.kids(0, false);
1434    r.flush();
1435    r.pay();
1436    r
1437}
1438
1439/// JSON one value per line, nesting shown by one space (indent costs tokens).
1440pub fn pretty(v: &Value) -> String {
1441    let mut out = serde_json::Serializer::with_formatter(Vec::new(), PrettyFormatter::with_indent(b" "));
1442    v.serialize(&mut out).map_or_else(|_| v.to_string(), |()| String::from_utf8_lossy(&out.into_inner()).into())
1443}
1444
1445/// `pretty` with keys sorted (Python's `sort_keys=True` order); not JSON → as it is.
1446fn one_space(text: &str) -> Vec<u8> {
1447    let sorted = |mut v: Value| {
1448        v.sort_all_objects();
1449        pretty(&v).into_bytes()
1450    };
1451    serde_json::from_str::<Value>(text).map_or_else(|_| text.as_bytes().to_vec(), sorted)
1452}
1453
1454/// Islands (what the served copy hides in templates and data scripts), after the served sections: `<template>` contents
1455/// (`measure` put their text in the element's `tlen`) holding ≥ 1 in `island_template_1_in` of the page's, rendered by
1456/// the served render (links numbered on), then data scripts ≥ `island_json_bytes` as text documents (`one_space` JSON,
1457/// `lN` lines).
1458fn islands(tree: &Tree, r: &mut Render, url: &str) -> Vec<Section> {
1459    let sec = |label: String, bytes: usize, lines| Section {
1460        level: 0,
1461        title: format!("island {label} {} KB", bytes.div_ceil(1024)),
1462        lines,
1463    };
1464    let mut out = Vec::new();
1465    r.lines.clear();
1466    // a `<template>` holding ≥ 1 in `island_template_1_in` of the page's text, a data script ≥ `island_json_bytes`
1467    let (part, json): (usize, usize) = (limit("island_template_1_in"), limit("island_json_bytes"));
1468    let big = |i: &usize| tree.nodes[*i].tag == "template" && r.tlen[*i] > 0 && r.tlen[*i] * part >= r.tlen[0];
1469    for f in (0..tree.nodes.len()).filter(big).map(|i| i + 1).collect::<Vec<_>>() {
1470        r.kids(f, false);
1471        r.flush();
1472        r.pay();
1473        let lines = std::mem::take(&mut r.lines).into_iter().map(|l| match l {
1474            Line::H(lv, t) => format!("{} {t}", "#".repeat(lv)),
1475            Line::T(t) => t,
1476        });
1477        out.push(sec(tree.nodes[f - 1].label(), r.tlen[f - 1], lines.collect()));
1478    }
1479    for (label, text, _) in tree.json.iter().filter(|(_, t, _)| t.len() >= json) {
1480        let doc = crate::text::build(&one_space(text), "json", url, url);
1481        out.push(sec(label.clone(), text.len(), doc.sections.into_iter().flat_map(|s| s.lines).collect()));
1482    }
1483    out
1484}
1485
1486/// The value `v` holds most often (a tie: the greatest, `max_by_key` keeps the last).
1487fn commonest<T: Ord + Copy>(mut v: Vec<T>) -> Option<T> {
1488    v.sort_unstable();
1489    v.chunk_by(|a, b| a == b).max_by_key(|g| g.len()).map(|g| g[0])
1490}
1491
1492/// The count words of a `post_counts` key (`comments` → comment, comments).
1493fn count_words(key: &str) -> Vec<&'static str> {
1494    LISTS.post_counts.iter().filter(|r| r.0 == key).flat_map(|r| r.1.iter().copied()).collect()
1495}
1496
1497/// The `info` keys `post` may write, in table order (`outline::info_line` prints them).
1498pub fn post_keys() -> impl Iterator<Item = &'static str> {
1499    LISTS.post_counts.iter().chain(&LISTS.post_facts).map(|r| r.0)
1500}
1501
1502/// An attribute's name as the post's counts read it: lowercased, `data-` stripped.
1503fn bare(k: &str) -> String {
1504    let k = k.to_lowercase();
1505    match k.strip_prefix("data-") {
1506        Some(rest) => rest.to_string(),
1507        None => k,
1508    }
1509}
1510
1511/// A count attribute of the post: its name (`data-` stripped, split on `-_:`) holds a `post_counts` word and a
1512/// `post_marker` word and no `post_skip` word (`remaining-comments-count`: what the page does not show), its value
1513/// a whole number (`whole`) → (`comments`, `296`).
1514fn count((k, v): &(String, String)) -> Option<(String, String)> {
1515    let k = bare(k);
1516    let words: Vec<&str> = k.split(['-', '_', ':']).collect();
1517    let has = |list: &[&str]| words.iter().any(|w| list.contains(w));
1518    if !has(&LISTS.post_marker) || has(&LISTS.post_skip) {
1519        return None;
1520    }
1521    let key = LISTS.post_counts.iter().find(|r| has(&r.1))?.0;
1522    Some((key.to_string(), whole(v)?.to_string()))
1523}
1524
1525/// A count as a page writes it: `296`, `1,234`, `2.1k`, `3M` (a fraction only before `k`/`m`); none else.
1526fn whole(v: &str) -> Option<u64> {
1527    let v = v.trim().replace(',', "").to_lowercase();
1528    let suffix = [("k", 1e3), ("m", 1e6)].iter().find_map(|(s, m)| Some((v.strip_suffix(s)?, *m)));
1529    let (num, times) = suffix.unwrap_or((&v, 1.0));
1530    let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
1531    let fine = match num.split_once('.') {
1532        Some((a, b)) => times > 1.0 && digits(a) && digits(b),
1533        None => digits(num),
1534    };
1535    if !fine {
1536        return None;
1537    }
1538    Some((num.parse::<f64>().ok()? * times).round() as u64)
1539}
1540
1541/// A fact's value: its leading date (`2025-12-11T09:49:02+0000` → `2025-12-11`), else a number as written (`26`,
1542/// `-3`); none else.
1543fn fact_value(v: &str) -> Option<String> {
1544    let v = v.trim();
1545    let d = v.as_bytes();
1546    let date = d.len() >= 10
1547        && d[4] == b'-'
1548        && d[7] == b'-'
1549        && [0, 1, 2, 3, 5, 6, 8, 9].iter().all(|&i| d[i].is_ascii_digit());
1550    if date {
1551        return Some(v[..10].to_string());
1552    }
1553    let number = v.bytes().any(|b| b.is_ascii_digit()) && v.bytes().all(|b| b.is_ascii_digit() || b"+-.,".contains(&b));
1554    v.replace(',', "").parse::<f64>().ok().filter(|_| number).map(|_| v.to_string())
1555}
1556
1557/// `i` and its ancestors, nearest first.
1558fn up(t: &Tree, i: usize) -> impl Iterator<Item = usize> + '_ {
1559    std::iter::successors(Some(i), |&p| t.nodes[p].parent)
1560}
1561
1562/// `js` = the HTML came from a JS render: its `<noscript>` was never shown, so it is dropped. One parse per page:
1563/// the content check's tree.
1564pub fn build_doc(tree: &Tree, url: &str, final_url: &str, js: bool) -> Doc {
1565    let (mut info, cards, og) = page_info(tree, final_url);
1566    let mut tlen = vec![0; tree.nodes.len()];
1567    measure(tree, 0, &mut tlen);
1568    // LOSS GUARD: every prune is measured against light (nothing pruned), never against another prune: a
1569    // price inside a pruned <form> is gone from both clean and hard. Serve the first render that keeps
1570    // ≥ 70% of light's numbers: clean → hard → light.
1571    let light = render(tree, &tlen, final_url, Mode::Light, js);
1572    let (fl, priced) = (facts(&light.lines, false), facts(&light.lines, true));
1573    let lost = |lines: &[Line]| fl.difference(&facts(lines, false)).count();
1574    let loss_max: f64 = limit("loss_max");
1575    let keeps = |lines: &[Line]| lost(lines) as f64 <= loss_max * fl.len() as f64;
1576    let mut mode = "clean";
1577    let mut used = render(tree, &tlen, final_url, Mode::Clean, js);
1578    // the pictures the chrome prune keeps, whichever render is served
1579    let media = rank((cards, og), tree, &std::mem::take(&mut used.media), final_url, &info);
1580    if !keeps(&used.lines) {
1581        (mode, used) = ("hard", render(tree, &tlen, final_url, Mode::Hard, js));
1582    }
1583    let title = info.get("title").cloned().unwrap_or_default();
1584    let chars = |secs: &[Section]| secs.iter().flat_map(|s| s.lines.iter()).map(|l| l.chars().count()).sum();
1585    let mut pruned_chars = None;
1586    if !keeps(&used.lines) {
1587        pruned_chars = Some(chars(&sections_of(&used.lines).0));
1588        (mode, used) = ("light", light);
1589    }
1590    let (sections, top) = sections_of(&used.lines);
1591    let pruned_chars = pruned_chars.unwrap_or_else(|| chars(&sections));
1592    let visible_chars = tlen[0] + inert_chars(tree, &tlen);
1593    let (vs_light_lost, price_pruned) = (lost(&used.lines), priced.difference(&facts(&used.lines, false)).count());
1594    let loss = Loss { vs_light_lost, light_facts: fl.len(), pruned_chars, visible_chars, price_pruned };
1595    let title = if title.is_empty() { crate::lang::short(final_url, 60) } else { title };
1596    let islands = islands(tree, &mut used, final_url);
1597    // the post's own counts, else the size the page states for its thread (`outline::tally` prints `25 of 301`)
1598    let post = used.post();
1599    let stated = used.declared().filter(|_| !post.contains_key("comments"));
1600    info.extend(post);
1601    info.extend(stated.map(|n| ("comments".into(), n.to_string())));
1602    let mut doc = Doc {
1603        info,
1604        top,
1605        links: used.links.keys().cloned().collect(),
1606        anchors: used.links.into_values().collect(),
1607        cut: tree.cut,
1608        loss,
1609        islands: islands.len(),
1610        media,
1611        ..Doc::new(url, final_url, title, sections, mode)
1612    };
1613    doc.sections.extend(islands);
1614    doc
1615}
1616
1617/// A paragraph: a text of ≥ `paragraph_words` words (a thread's post, a description; never a name or a link).
1618pub fn paragraph(t: &str) -> bool {
1619    t.split_whitespace().count() >= limit("paragraph_words")
1620}
1621
1622#[cfg(test)]
1623mod tests {
1624    use super::*;
1625    use crate::html::parse;
1626
1627    /// The post's own counts come from the first element with a count attribute in no list item or chrome, its
1628    /// score and posted time from that element only: a custom element's plain attributes, a `data-num-comments`
1629    /// post, a `2.1k` count; never a count of what is not shown, a score with no count beside it (review bars), a
1630    /// ratio, a nav's or a list card's count, nor a later element's.
1631    #[test]
1632    fn the_post_counts_come_from_its_own_element() {
1633        let info = |h: &str| {
1634            let i = build_doc(&parse(h), "https://a.example/", "https://a.example/", false).info;
1635            post_keys().filter_map(|k| Some(format!("{k} {}", i.get(k)?))).collect::<Vec<_>>().join(" · ")
1636        };
1637        let post_el = r#"<x-post id=t3_1 comment-count="296" score="26" upvote-ratio="0.9265"
1638            created-timestamp="2025-12-11T09:49:02.123000+0000"><h1>What finally pushed you</h1></x-post>"#;
1639        let comments = r#"<template><x-comment score="40" created-timestamp="2025-12-12T01:00:00"
1640            comment-count="3"><p>A reply</p></x-comment></template>"#;
1641        let reddit = format!("<body>{post_el}{comments}</body>");
1642        assert_eq!(info(&reddit), "comments 296 · score 26 · posted 2025-12-11");
1643        // a nav's count and a list card's (a related post) are never the post's; the post after them is
1644        let text = "<p>The post itself, long enough to be the page's main text for the reader here.</p>";
1645        let nav = r#"<nav><a href="/hot" data-comment-count="812">Hot</a></nav>"#;
1646        let cards = r#"<ul><li data-comment-count="57"><a href="/r">Related</a></li></ul>"#;
1647        let post = format!(r#"<article data-comment-count="4" data-published-date="2024-05-01">{text}</article>"#);
1648        assert_eq!(info(&format!("<body>{nav}{cards}{post}</body>")), "comments 4 · posted 2024-05-01");
1649        assert_eq!(info(&format!("<body>{nav}{cards}{text}</body>")), "");
1650        // posted = a {created, published, posted} word with a {time, timestamp, date} word, or `datetime`
1651        let when = |a: &str| info(&format!(r#"<div data-comment-count="1" {a}="2024-03-01T10:00">x</div>"#));
1652        assert_eq!(when("data-posted-time"), "comments 1 · posted 2024-03-01");
1653        assert_eq!(when("created_date"), "comments 1 · posted 2024-03-01");
1654        assert_eq!(when("datetime"), "comments 1 · posted 2024-03-01");
1655        for other in ["data-created-by", "data-update-time", "data-date"] {
1656            assert_eq!(when(other), "comments 1", "{other}");
1657        }
1658        let linkedin =
1659            r#"<div class="feed"><article data-num-comments="3" data-num-likes="1,204"><p>Post</p></article>"#;
1660        assert_eq!(info(linkedin), "comments 3 · likes 1204");
1661        assert_eq!(
1662            info(r#"<div data-answer-count="2.1k" data-datetime="2024-03-01">Q</div>"#),
1663            "answers 2100 · posted 2024-03-01"
1664        );
1665        // a count of what is not shown, a score alone, a word that only holds a count word, no whole number
1666        let stack = r#"<div data-score="2"><span data-remaining-comments-count="6"></span></div>"#;
1667        assert_eq!(info(stack), "");
1668        assert_eq!(info(r#"<li data-score="92">Staff</li><li data-score="96">Comfort</li>"#), "");
1669        assert_eq!(info(r#"<a data-comment-id="99999" data-comment-count="many" data-commentcount="5">x</a>"#), "");
1670        assert_eq!(info(r#"<p data-like-count="2.5" data-unread-count="4" data-total-comments="-1">x</p>"#), "");
1671        // the first counted element is the post; a later one's score never joins it
1672        let later = r#"<p data-comment-count="40">40 comments</p><div data-score="7" data-comment-count="1"></div>"#;
1673        assert_eq!(info(later), "comments 40");
1674    }
1675
1676    /// A `<title>` that is only the site's name and tagline (Reddit's on every thread) yields to the first `h1`;
1677    /// a title of the page's own words, a bare word, an error's, one that holds the `h1` already and `og:title` stay.
1678    #[test]
1679    fn a_site_name_title_yields_to_the_h1() {
1680        let title = |head: &str| {
1681            let h = format!("<head>{head}</head><h1>Visiting <b>Portugal</b> for a week</h1><h1>Other</h1>");
1682            page_info(&parse(&h), "https://a.example/").0.get("title").cloned().unwrap_or_default()
1683        };
1684        assert_eq!(title("<title>Reddit - The heart of the internet</title>"), "Visiting Portugal for a week");
1685        assert_eq!(title("<title>Reddit</title>"), "Reddit");
1686        assert_eq!(title("<title>Rust traits explained | Blog</title>"), "Rust traits explained | Blog");
1687        let held = "<title>Lisboa - Visiting Portugal for a week</title>";
1688        assert_eq!(title(held), "Lisboa - Visiting Portugal for a week");
1689        assert_eq!(title("<title>Site Maintenance</title>"), "Site Maintenance");
1690        let og = "<title>Reddit</title><meta property='og:title' content='From og'>";
1691        assert_eq!(title(og), "From og");
1692        // An API docs page whose h1 holds the title's own word (and a button label) keeps its `<title>`
1693        let docs = |h1: &str| {
1694            let h = format!("<head><title>widget - Lang</title></head><h1>{h1}</h1>");
1695            page_info(&parse(&h), "https://a.example/").0.get("title").cloned().unwrap_or_default()
1696        };
1697        assert_eq!(docs("Crate widget <button>Copy item path</button>"), "widget - Lang");
1698        assert_eq!(docs("Module <span>Widget</span>"), "widget - Lang");
1699        assert_eq!(docs("<button>Copy item path</button>"), "widget - Lang");
1700        assert_eq!(docs("Gadget parts for sale"), "Gadget parts for sale");
1701    }
1702
1703    /// Two renders of one profile page: one caught before its script set the title (the site's name and tagline,
1704    /// no og:title), one after (`Name (@handle) | Site`). Both read the `h1`; a title that adds words of its own
1705    /// to the `h1`, or only a suffix, stays.
1706    #[test]
1707    fn a_page_reads_one_title_whatever_the_render_timing() {
1708        let title = |head: &str, h1: &str| {
1709            let h = format!("<head>{head}</head><h1>{h1}</h1><p>Posts and replies</p>");
1710            page_info(&parse(&h), "https://a.example/@nasa").0.get("title").cloned().unwrap_or_default()
1711        };
1712        let early = "<title>Clipsite - Make Your Day</title>";
1713        let late = "<title>NASA (@nasa) | Clipsite</title><meta property='og:title' content='NASA (@nasa) | Clipsite'>";
1714        assert_eq!((title(early, "NASA"), title(late, "NASA")), ("NASA".into(), "NASA".into()));
1715        assert_eq!(title("<title>Cleo Abram (@cleoabram) | Clipsite</title>", "Cleo Abram"), "Cleo Abram");
1716        assert_eq!(title("<title>vitiral (u/vitiral) - Forum</title>", "vitiral"), "vitiral");
1717        let stays = ["Rytas - Žalgiris - League", "History of Rome - Wiki", "Dune (2021) (film) - Db"];
1718        for t in stays {
1719            let h1 = t.split(' ').next().unwrap_or_default();
1720            assert_eq!(title(&format!("<title>{t}</title>"), h1), t, "{t}");
1721        }
1722    }
1723
1724    /// A TikTok rehydration island as saved (20 lines): Claude 5.5 count_tokens
1725    /// = 220; JSON's runs of marks (`": "`, `},`) read as letters land
1726    /// within ±25% (260; 277 before). The whole islands: IG #1 +32% → +22%, IG #2 +13% → +4%, TikTok +16% → +9%.
1727    #[test]
1728    fn json_marks_in_a_run_are_cheap() {
1729        let island = "l206      \"core_ux_fix\": {\nl207       \"vid\": \"v1\"\nl208      },\nl209      \"creator_center_connect\": {\nl210       \"vid\": \"v1\"\nl211      },\nl212      \"creator_center_connect_global\": {\nl213       \"vid\": \"v2\"\nl214      },\nl215      \"creator_center_global_comment_management\": {\nl216       \"vid\": \"v1\"\nl217      },\nl218      \"creator_center_global_post_management\": {\nl219       \"vid\": \"v1\"\nl220      },\nl221      \"creator_center_test\": {\nl222       \"vid\": \"v2\"\nl223      },\nl224      \"csp_merge_support\": {\nl225       \"vid\": \"v1\"";
1730        let t = tok(island);
1731        assert!((165..=275).contains(&t), "{t} vs 220 real");
1732        assert_eq!(tok_cut(island, t), island.len());
1733        assert!(tok(&island[..tok_cut(island, 40)]) <= 40);
1734    }
1735
1736    /// A thread's stated size = the count nearest the thread before it, shown, outside a list item; two there
1737    /// claim none: a related post's, a pruned sidebar's, a link's label, a count after the thread never name it.
1738    #[test]
1739    fn a_thread_states_its_size() {
1740        let text = "a reply that says one thing in a sentence long enough to be a paragraph here";
1741        let c = |i: usize, kids: &str| {
1742            format!("<li><article><b>user{i}</b> <time>Jan {i}</time><p>{text}</p></article>{kids}</li>")
1743        };
1744        let thread: String = (0..4).map(|i| c(i, &format!("<ol>{}</ol>", c(i + 10, "")))).collect();
1745        let at = |own: &str, between: &str, after: &str| {
1746            let html = format!(
1747                "<html><body><article><h1>A post</h1>{own}<p>{text}</p></article>{between}<div><h2>Discussion</h2>\
1748                 <ol>{thread}</ol>{after}</div></body></html>"
1749            );
1750            build_doc(&parse(&html), "https://a.example/p", "https://a.example/p", false).info.get("comments").cloned()
1751        };
1752        let related = "<section><h3>Related</h3><ul><li><a href=/o>Another post</a> <span>450 comments</span></li></ul></section>";
1753        assert_eq!(at("", related, ""), None, "a related post's count");
1754        assert_eq!(at("", "<aside><p><a href=/hot>99 comments</a></p></aside>", ""), None, "a pruned sidebar's");
1755        assert_eq!(
1756            at("", r#"<nav><a href=/prev aria-label="88 comments">Previous</a></nav>"#, ""),
1757            None,
1758            "a nav label"
1759        );
1760        assert_eq!(at("", "", " 77 comments"), None, "after the thread");
1761        assert_eq!(at("<a href=#c>12 comments</a>", related, "").as_deref(), Some("12"), "the post's own");
1762        assert_eq!(at("<p>12 comments</p><p>14 comments</p>", "", ""), None, "a tie claims none");
1763        assert_eq!(at("<p>1,204&nbsp;Comments</p>", "", "").as_deref(), Some("1204"));
1764        assert_eq!(at("", r#"<div data-comment-count="301"></div>"#, "").as_deref(), Some("301"), "a count attribute");
1765        assert_eq!(at(r#"<x data-comment-id="12345"></x><p>7 comment threads</p>"#, "", ""), None, "an id, a phrase");
1766    }
1767
1768    /// A card group before a thread in one parent keeps the thread's comments: their headings are untitled, and
1769    /// only the card members' emptied lines drop.
1770    #[test]
1771    fn cards_beside_a_thread_keep_its_comments() {
1772        let text = "a reply that says one thing in a sentence long enough to be a paragraph here";
1773        let c = |i: usize, kids: &str| {
1774            format!("<li><article><b>user{i}</b> <time>Jan {i}</time><p>{text}</p></article>{kids}</li>")
1775        };
1776        let thread: String = (0..4).map(|i| c(i, &format!("<ol>{}</ol>", c(i + 10, "")))).collect();
1777        let card =
1778            |i: usize| format!("<div class=c><h3><a href=/p{i}>A related post {i}</a></h3><p>{i}2 votes</p></div>");
1779        let html = format!("<main><h1>Post</h1>{}<ol>{thread}</ol></main>", (1..=4).map(card).collect::<String>());
1780        let d = build_doc(&parse(&html), "https://a.example/p", "https://a.example/p", false);
1781        let cards = d.sections.iter().flat_map(|s| &s.lines).filter(|l| l.starts_with(CARD)).count();
1782        assert_eq!((cards, d.sections.iter().filter(|s| s.level >= COMMENT).count()), (4, 8));
1783    }
1784
1785    /// A layout table (HN) is its cells' blocks; a thread table, ≥ 8 rows indented by a spacer, is a comment
1786    /// a row (HN's 373 comments were one 41k-token line); a data table with long cells stays rows.
1787    #[test]
1788    fn spacer_rows_are_comments() {
1789        let para = "this comment says one thing in a sentence long enough to be prose";
1790        // HN's shape: a row a comment, its indent a text-less 1 px spacer (`width` 0, 40, 80), a vote spacer after
1791        let post = |(i, w): (usize, usize)| {
1792            let spacer = format!("<img height=1 width={w}><img height=1 width=14>");
1793            format!(
1794                "<tr><td><table><tr><td>{spacer}</td><td>user{i} 2 hours ago</td><td>{para} {i}</td></tr></table></td></tr>"
1795            )
1796        };
1797        let page = |rows: String| {
1798            let html =
1799                format!("<html><body><table><tr><td><b>Story</b><table>{rows}</table></td></tr></table></body></html>");
1800            build_doc(&parse(&html), "https://a.example/item", "https://a.example/item", false).sections
1801        };
1802        let tree = [0, 40, 80, 40, 0, 40, 0, 0].into_iter().enumerate().map(post).collect::<String>();
1803        let levels: Vec<usize> = page(tree).iter().map(|s| s.level).collect();
1804        assert_eq!(levels, [0, 7, 8, 9, 8, 7, 8, 7, 7], "the story, then a comment a row at 7 + its depth");
1805        let flat = [0; 8].into_iter().enumerate().map(post).collect::<String>();
1806        assert_eq!(page(flat).len(), 1, "flat posts are a feed, no thread");
1807        let short = [0, 40, 80, 40, 0, 40, 0].into_iter().enumerate().map(post).collect::<String>();
1808        assert_eq!(page(short).len(), 1, "7 comments: one block");
1809        // a data table's rows hold no spacer: no comment
1810        let cell = |i: usize| format!("<tr><td>10.{i}</td><td>{para} {i}</td></tr>");
1811        let data = page((1..=8).map(cell).collect());
1812        assert_eq!((data.len(), data[0].lines.len()), (1, 9), "the story line, then a line a row: {:?}", data[0].lines);
1813        // a table-layout news page: a photo's `width`, a sized cell's, are no indent (a spacer is text-less, 1 high)
1814        let story = |(i, w): (usize, usize)| {
1815            let photo = format!("<img src=p{i}.jpg width={w} height=200>");
1816            format!("<tr><td><table><tr><td width={w}>{photo}</td><td>{para} {i}</td></tr></table></td></tr>")
1817        };
1818        let news = [120, 300, 600, 300, 120, 300, 120, 120].into_iter().enumerate().map(story).collect::<String>();
1819        assert!(page(news).iter().all(|s| s.level < COMMENT), "photos and cell widths are no thread");
1820        // other spacer tables: no step starts at 0, too few rows hold a paragraph, or each row heads its own story
1821        let rows = |cell: &dyn Fn(usize, usize) -> String, ws: &[usize]| {
1822            let row = |(i, &w): (usize, &usize)| format!("<tr><td><img height=1 width={w}></td>{}</tr>", cell(i, w));
1823            page(ws.iter().enumerate().map(row).collect()).into_iter().filter(|s| s.level >= COMMENT).count()
1824        };
1825        let stair = [0, 20, 20, 0, 20, 40, 40, 0, 20, 20];
1826        let toc = |i: usize, _| format!("<td><a href=#s{i}>{i} Part {i}</a></td><td>{i}</td>");
1827        let files = |i: usize, _| format!("<td><a href=/f{i}.c>f{i}.c</a></td><td>r{i}</td><td>2004-03-0{i}</td>");
1828        let gov = |i: usize, _| format!("<td><b>News {i}</b><br>{para} {i}</td>");
1829        let letter = |i: usize, _| format!("<td><h3>Story {i}</h3><p>{para} {i}</p></td>");
1830        let found = [
1831            rows(&toc, &stair),
1832            rows(&files, &stair),
1833            rows(&gov, &[10, 1, 1, 10, 1, 1, 10, 1, 1, 10]),
1834            rows(&letter, &stair),
1835        ];
1836        assert_eq!(found, [0; 4], "a contents list, a file tree, a layout, a newsletter");
1837        // a hostile chain (every row one spacer step deeper) is clamped at `thread_depth`, in linear time
1838        let t0 = std::time::Instant::now();
1839        let chain = (0..4_000usize).map(|i| (i, if i.is_multiple_of(2) { 0 } else { i })).map(post).collect::<String>();
1840        let deepest = page(chain).iter().map(|s| s.level).max();
1841        assert_eq!(deepest, Some(COMMENT + limit::<usize>("thread_depth")));
1842        assert!(t0.elapsed().as_secs() < 20, "{:?}", t0.elapsed());
1843    }
1844
1845    /// A thread in a block the clean render prunes (an `<aside>` widget) is never counted: comments are what a
1846    /// render serves, so a dropped block opens none, nor makes a live blog's dated updates (one post) a thread.
1847    #[test]
1848    fn a_pruned_thread_counts_nothing() {
1849        let para = "this comment says one thing in a sentence long enough to be prose";
1850        let li = |i: usize, kids: &str| format!("<li><time>{i}h ago</time><p>{para} {i}</p>{kids}</li>");
1851        let tree: String = (0..4).map(|i| li(i, &format!("<ol>{}</ol>", li(10 + i, "")))).collect();
1852        let body: String = (0..40).map(|i| format!("<p>{para} body {i}</p>")).collect();
1853        let html = format!("<html><body><main>{body}</main><aside><ol>{tree}</ol></aside></body></html>");
1854        let doc = build_doc(&parse(&html), "https://a.example/p", "https://a.example/p", false);
1855        assert_eq!(doc.mode, "clean");
1856        assert!(doc.sections.iter().all(|s| s.level < COMMENT), "{:?}", doc.sections.len());
1857        let post = |i: usize, w: &str| format!("<article><time>{w} {i}</time><p>{para} {w} {i}</p></article>");
1858        let (upd, side): (String, String) =
1859            ((0..9).map(|i| post(i, "update")).collect(), (0..2).map(|i| post(i, "side")).collect());
1860        let blog = format!(
1861            "<html><body><article><h1>Live</h1><time>now</time><p>{para}</p>{upd}</article><aside>{side}</aside></body></html>"
1862        );
1863        let doc = build_doc(&parse(&blog), "https://a.example/p", "https://a.example/p", false);
1864        assert!(doc.sections.iter().all(|s| s.level < COMMENT), "the sidebar's posts were its second top");
1865    }
1866
1867    /// BOM, then the header, then the page's `<meta>`, then UTF-8; a page cannot claim UTF-16 from ASCII.
1868    /// A server's Markdown is a page: headings are sections (a `#` inside a fence is code), `![alt](src)` a media
1869    /// row, `[text](url)` a link; no frontmatter title → the first `# ` heading.
1870    #[test]
1871    fn markdown_is_a_page() {
1872        let md = "# Camera modules?\n\nIntro with [a link](/a) and enough words to keep.\n\n## Wiring\n\n```\n# not a \
1873                  heading\n```\n\n![The board](/b.jpg)\n\n## Code\n\nMore words.\n\n```json\n\
1874                  {\"@context\":\"https://schema.org\",\"@type\":\"WebPage\",\"dateModified\":\"2026-10-08\"}\n```\n";
1875        let d = markdown(md.as_bytes(), "https://ex.com/t/1", "https://ex.com/t/1");
1876        let titles: Vec<&str> = d.sections.iter().map(|s| s.title.as_str()).collect();
1877        assert_eq!(
1878            (d.mode.as_str(), d.title.as_str(), titles),
1879            ("md", "Camera modules?", vec!["Camera modules?", "Wiring", "Code"])
1880        );
1881        assert_eq!(
1882            (d.media.len(), d.media[0].src.as_str(), d.media[0].alt.as_str()),
1883            (1, "https://ex.com/b.jpg", "The board")
1884        );
1885        assert_eq!(d.links.first().map(String::as_str), Some("https://ex.com/a"));
1886        let modified = d.info.get("modified").map(String::as_str);
1887        assert_eq!(modified, Some("2026-10-08"), "JSON-LD read as such: {:?}", d.info);
1888        assert!(!d.sections.iter().flat_map(|s| &s.lines).any(|l| l.contains("@context")), "never text");
1889    }
1890
1891    /// THE detection rule: magic, then a PDF/zip type, then an HTML page by type or start, then text documents.
1892    #[test]
1893    fn kind_of_bodies() {
1894        let cases: &[(&str, &[u8], &str)] = &[
1895            ("text/plain", b"%PDF-1.7", "pdf"),
1896            ("application/pdf", b"<html>", "pdf"),
1897            ("text/plain; charset=utf-8", b"local x = 1\n", "text"),
1898            ("text/csv", b"a,b\n1,2", "text"),
1899            ("text/markdown", b"# Title", "md"),
1900            ("text/plain", b"<!DOCTYPE html><title>x</title>", "html"),
1901            ("text/html", b"{\"a\":1}", "html"),
1902            ("application/json", b"not json", "json"),
1903            ("text/plain", b" [1, 2]", "json"),
1904            ("text/plain", b"[section]\nkey=1", "text"),
1905            ("", b"{\"a\": [1]}", "json"),
1906            ("", b"{ broken", "html"),
1907            ("application/rss+xml", b"<rss>", "xml"),
1908            ("", b"<?xml version=\"1.0\"?><urlset/>", "xml"),
1909            ("", b"<?xml version=\"1.0\"?><html xmlns=\"x\">", "html"),
1910            ("application/xhtml+xml", b"<?xml?><html>", "html"),
1911            ("", b"<p>local notes</p>", "html"),
1912            ("application/octet-stream", b"plain words", "html"),
1913        ];
1914        for (ct, body, want) in cases {
1915            assert_eq!(kind_of(ct, body), *want, "{ct} {}", String::from_utf8_lossy(body));
1916        }
1917    }
1918
1919    #[test]
1920    fn charset_order() {
1921        let cz = b"<meta charset=\"windows-1250\"><p>\x8Elu\x9D cena 120 \x80</p>".to_vec();
1922        let d = |b: &[u8], h| {
1923            let (t, n) = decode(b.to_vec(), h);
1924            (String::from_utf8(t).unwrap_or_default(), n)
1925        };
1926        assert!(d(&cz, None).0.contains("Žluť cena 120 €") && d(&cz, None).1 == "windows-1250");
1927        let eq = b"<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-2'><p>\xAE</p>";
1928        assert_eq!(
1929            d(eq, None),
1930            ("<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-2'><p>Ž</p>".into(), "ISO-8859-2")
1931        );
1932        assert_eq!(d(&cz, Some("utf-8")).1, "", "the header wins over the page");
1933        assert_eq!(
1934            d(b"\xEF\xBB\xBF<meta charset=windows-1250>\xC5\xBD", Some("iso-8859-1")).0,
1935            "<meta charset=windows-1250>Ž"
1936        );
1937        assert_eq!(d(b"<meta charset=utf-16><p>x</p>", None).1, "", "utf-16 from ASCII bytes = UTF-8");
1938        assert_eq!(d(b"<p>plain \xC5\xBD</p>", None), ("<p>plain Ž</p>".into(), ""));
1939        assert_eq!(d(b"<meta name=x><meta charset=bogus>", None).1, "", "an unknown label is ignored");
1940    }
1941
1942    #[test]
1943    fn facts_and_fold() {
1944        let line = [Line::T("Preis 1 299,99 € · 2026-10-11 · 7 · m² 45 · EUR 12 · $30 · 40 USD · 50% off".into())];
1945        let f = facts(&line, false);
1946        assert!(f.contains("299,99") && f.contains("2026-10-11") && f.contains("45") && !f.contains("7"));
1947        let priced: BTreeSet<String> = facts(&line, true).into_iter().collect();
1948        assert_eq!(priced.into_iter().collect::<Vec<_>>(), ["12", "299,99", "30", "40"], "next to € EUR $ USD");
1949        assert_eq!(fold("Žluťoučký ĚŠ Café"), "zlutoucky es cafe");
1950        assert_eq!(fold("Brand™ ½ Full fi"), "brandtm 1⁄2 full fi");
1951        assert_eq!(fold("한").chars().count(), 3);
1952        assert_eq!(collapse("  a \u{a0}\n b  "), "a b");
1953        let ours = [Line::T("Home [l10] · Shop [l11] · 12 items [l12]".into())];
1954        assert_eq!(facts(&ours, false).into_iter().collect::<Vec<_>>(), ["12"], "[lN] ids are ours");
1955    }
1956
1957    /// A page with no digits and 40 nav links: light counted 32 "numbers" (our ids l10..l40), so the guard's
1958    /// mode was set by link ids, not by the page.
1959    #[test]
1960    fn link_ids_are_not_page_numbers() {
1961        let nav: String = (0..40).map(|i| format!("<a href='/p{i}'>page</a> ")).collect();
1962        let h = format!("<nav>{nav}</nav><h1>Words</h1><p>Only words here, no digits at all.</p>");
1963        let d = build_doc(&parse(&h), "https://ex.com/", "https://ex.com/", false);
1964        assert_eq!((d.mode.as_str(), d.loss.light_facts, d.loss.vs_light_lost), ("clean", 0, 0));
1965    }
1966
1967    /// `<pre>` lines break where Python's `splitlines` breaks (`\r\n` once, form feed, U+2028); a combining mark
1968    /// at either end of a table range is dropped, its neighbours outside the range are kept.
1969    #[test]
1970    fn pre_lines_and_combining_edges() {
1971        let h = "<pre>a\r\nb\x0cc\u{2028}d\r\r\ne  \n\n</pre>";
1972        let d = build_doc(&parse(h), "https://x.io/", "https://x.io/", false);
1973        assert_eq!(d.sections[0].lines, ["a", "b", "c", "d", "e"]);
1974        let (lo, hi) = COMBINING[0];
1975        let (last_lo, last_hi) = COMBINING[COMBINING.len() - 1];
1976        let f = |cp: u32| fold(&format!("x{}", char::from_u32(cp).expect("a char")));
1977        assert_eq!((f(lo), f(hi), f(last_lo), f(last_hi)), ("x".into(), "x".into(), "x".into(), "x".into()));
1978        assert_eq!(f(lo - 1).chars().count(), 2);
1979        assert_eq!(f(0x2FF).chars().count(), 2, "just below U+0300");
1980    }
1981
1982    #[test]
1983    fn clean_prunes_chrome_and_keeps_links() {
1984        let h = "<html><head><title>T</title></head><body><nav><a href='/x'>menu</a></nav>\
1985             <h1>One</h1><p>Price <a href='/p'>12 EUR</a></p><h2>Two</h2><p>b 24 36 48</p>\
1986             <footer>foot 2026</footer></body></html>";
1987        let d = build_doc(&parse(h), "https://ex.com/", "https://ex.com/", false);
1988        assert_eq!(d.links, vec!["https://ex.com/p".to_string()]);
1989        assert_eq!(d.sections[0].lines, vec!["Price 12 EUR [l1]".to_string()]);
1990        assert_eq!((d.mode.as_str(), d.loss.vs_light_lost), ("clean", 1)); // "2026" sat in the footer: 1 of 5
1991    }
1992
1993    /// A link whose text holds no word reads its accessible name (W3C accname): a thumbnail's caption in its alt
1994    /// after the count it shows, an `aria-label`, a `title` only when it shows nothing; a card's overlay link puts
1995    /// its id on the headline that shows its name. Never an icon's short label, a decorative picture, a picture
1996    /// beside a text link to the same target, nor a link that names itself.
1997    #[test]
1998    fn a_picture_link_reads_its_accessible_name() {
1999        let h = "<h1>Videos</h1><div><a href='/v/1'><div><img alt='Crew-13 reaches the ISS this week'></div>\
2000             <div><strong>1.7M</strong></div></a></div>\
2001             <p>See <a href='/v/2' aria-label='The full launch video in HD'><img alt=''></a></p>\
2002             <div><a href='/p/3'><img alt='Red wool winter coat for women'></a><a href='/p/3'>Red coat</a></div>\
2003             <div><a href='/share'><img alt='Share this page'></a><a href='/v/5'><img role=presentation alt='a b c d'></a></div>\
2004             <p><a href='/docs'><img alt='a small book icon here'> Read the docs</a></p>\
2005             <p><a href='/x25' title='The X.25 protocol for packet networks'>X.25</a></p>\
2006             <div><a href='/n/7' aria-label='Storm closes the harbour for two days'></a><img alt='Waves'>\
2007             <h3>Weather</h3><p>Storm closes the harbour for two days</p></div>";
2008        let d = build_doc(&parse(h), "https://ex.com/", "https://ex.com/", false);
2009        let want = [
2010            "1.7M · Crew-13 reaches the ISS this week [l1]",
2011            "See The full launch video in HD [l2]",
2012            "Red coat [l3]",
2013            "Read the docs [l4]",
2014            "X.25 [l5]",
2015            "Storm closes the harbour for two days [l6]",
2016        ];
2017        assert_eq!(d.sections.iter().flat_map(|s| &s.lines).collect::<Vec<_>>(), want);
2018    }
2019
2020    /// A `<button>`'s text is on screen (trivago's hotel cards are buttons: 44 facts were dropped blind); a
2021    /// button in chrome (a search form) goes with its region.
2022    #[test]
2023    fn button_text_is_page_text() {
2024        let h = "<h1>Hotels in Seville</h1><p>Two hotels found for your dates in the old town.</p>\
2025                 <div><button><span>9.1</span> Excellent (17k ratings) Seville, 0.5 miles to City center</button></div>\
2026                 <form><input name=q><button>Search 2.0</button></form>";
2027        let d = build_doc(&parse(h), "https://ex.com/", "https://ex.com/", false);
2028        assert!(has(&d, "9.1 Excellent (17k ratings) Seville, 0.5 miles") && !has(&d, "Search 2.0"));
2029    }
2030
2031    /// aria-hidden text is on screen (Amazon's star line, Google's `4.7 (1.4K)`): kept in clean; an aria-hidden
2032    /// icon glyph is not.
2033    #[test]
2034    fn aria_hidden_text_is_on_screen() {
2035        let h = "<h1>Earbuds</h1><p>Wireless earbuds with a case and three tip sizes in the box.</p>\
2036                 <p><span aria-hidden=true>4.6 out of 5 stars</span> <span aria-hidden=true>16,544</span>\
2037                 <i aria-hidden=true>★</i> ratings</p>";
2038        let d = build_doc(&parse(h), "https://ex.com/", "https://ex.com/", false);
2039        assert_eq!(d.mode, "clean");
2040        assert!(has(&d, "4.6 out of 5 stars 16,544 ratings"));
2041    }
2042
2043    /// Two numbers in two elements never glue into a third (coinmarketcap `$109.720.24%`, SO `4,33633`); a
2044    /// superscript stays glued on purpose (`419⁰⁰ €`), digits inside one text node are untouched.
2045    #[test]
2046    fn digits_at_an_element_boundary_get_a_space() {
2047        let h = "<h1>Coins</h1><p>Prices of the day for the top coins on the market.</p>\
2048                 <p><span>$109.72</span><span>0.24%</span> · <span>4,336</span><span>3</span> gold · 419<sup>00</sup> €</p>";
2049        let d = build_doc(&parse(h), "https://ex.com/", "https://ex.com/", false);
2050        assert!(has(&d, "$109.72 0.24% · 4,336 3 gold · 419⁰⁰ €"));
2051    }
2052
2053    fn has(d: &Doc, needle: &str) -> bool {
2054        d.sections.iter().flat_map(|s| s.lines.iter()).any(|l| l.contains(needle))
2055    }
2056
2057    /// A `div` grid with ARIA table roles (`row`, `columnheader`, `cell` around a `<p>`) is a table: a row a line.
2058    #[test]
2059    fn aria_rows_are_table_rows() {
2060        let h = include_str!("../tests/fixtures/table-aria.html");
2061        let d = build_doc(&parse(h), "https://docs.example/limits", "https://docs.example/limits", false);
2062        let rows: Vec<&String> =
2063            d.sections.iter().flat_map(|s| s.lines.iter()).filter(|l| l.starts_with('|')).collect();
2064        assert_eq!(rows.len(), 9, "{rows:?}");
2065        assert_eq!(rows[0], "| Plan | Traffic, GB | Total req/s | Render req/s |");
2066        assert_eq!(rows[1], "| Free trial | 1 | 10 | 3 |");
2067        assert_eq!(rows[8], "| Custom + | Custom | Custom | Custom |");
2068    }
2069
2070    #[test]
2071    fn loss_guard_measures_against_light() {
2072        // the price sits in a <form>: clean and hard both prune it, so comparing them never fired
2073        let h = include_str!("../tests/fixtures/price-rows.html");
2074        let d = build_doc(&parse(h), "https://store.example/p/x", "https://store.example/p/x", false);
2075        assert_eq!((d.mode.as_str(), d.loss.vs_light_lost), ("light", 0));
2076        assert!(has(&d, "Regular price") && has(&d, "13,50 €"));
2077    }
2078
2079    /// JSON-LD values as Python reads them: keys in document order (the first object wins), a repeated key in its
2080    /// first place with its last value, an integer printed as written and a float with its point.
2081    #[test]
2082    fn ld_keeps_document_order_and_number_spelling() {
2083        let ld = |j: &str| {
2084            let v: Value = serde_json::from_str(j).expect("json");
2085            let mut objs = Vec::new();
2086            walk_ld(&v, 0, &mut objs);
2087            let mut info = IndexMap::new();
2088            objs.iter().for_each(|o| ld_info(o, &mut info));
2089            info.into_iter().collect::<Vec<_>>()
2090        };
2091        let i = ld(
2092            r#"{"offers":{"price":330,"priceCurrency":"EUR"},"aggregateRating":{"ratingValue":4.5,"ratingCount":12}}"#,
2093        );
2094        assert_eq!(i, [("price".into(), "330 EUR".into()), ("rating".into(), "4.5 (12 reviews)".into())]);
2095        assert_eq!(ld(r#"{"offers":{"price":12.0}}"#)[0].1, "12.0");
2096        let dup = ld(r#"{"offers":{"price":"1","priceCurrency":"EUR","price":"2"}}"#);
2097        assert_eq!(dup[0].1, "2 EUR", "last value, first place");
2098        let first = ld(r#"{"a":{"datePublished":"2026-01-01"},"b":{"datePublished":"2026-02-02"}}"#);
2099        assert_eq!(first[0], ("published".into(), "2026-01-01".into()), "document order, not sorted keys");
2100        let v: Value = serde_json::from_str(r#"{"b":1,"a":2}"#).expect("json");
2101        assert!(matches!(&v, Value::Object(kv) if kv.keys().eq(["b", "a"])));
2102        // an island prints the page's numbers as written (serde_json `float_roundtrip`; best-effort parsing printed
2103        // a Booking.com aspect ratio 1.4984391259105099 as 1.49843912591051)
2104        assert_eq!(one_space(r#"{"r":1.4984391259105099}"#), b"{\n \"r\": 1.4984391259105099\n}");
2105    }
2106
2107    /// MEDIA: the og card first with its alt (JSON escapes decoded: `\u2019`, a surrogate pair, `\n`), size and
2108    /// type; the `<picture>`'s largest candidate; data:, svg, a 1 px pixel and aria-hidden dropped; the
2109    /// avatar-sized image and the bare `@handle` alt last, demoted.
2110    #[test]
2111    fn og_card_and_body_media() {
2112        let h = include_str!("../tests/fixtures/og-card.html");
2113        let d = build_doc(&parse(h), "https://social.example/a/status/1", "https://social.example/a/status/1", false);
2114        let src: Vec<&str> = d.media.iter().map(|m| m.src.as_str()).collect();
2115        assert_eq!(
2116            src,
2117            [
2118                "https://img.example/media/galaxy?format=webp&name=large",
2119                "https://social.example/media/arm-1600.jpg",
2120                // demoted, in the order the rest holds them (alt length); `share.png` is the share card
2121                "https://social.example/profile/other.jpg",
2122                "https://social.example/profile/agency_normal.jpg",
2123                "https://social.example/static/share.png",
2124            ]
2125        );
2126        let og = &d.media[0];
2127        assert_eq!((og.w, og.h, og.ty.as_str(), og.video), (5955, 3969, "webp", false));
2128        assert!(og.alt.starts_with("A starfield filled with thousands of stars"), "{og:?}");
2129        assert!(og.alt.ends_with(" dust. The Milky Way’s bar, seen edge-on 🌌."), "{og:?}");
2130        assert_eq!(d.media[1].alt, "The bar of stars");
2131        assert_eq!(d.media.iter().map(|m| m.demoted).collect::<Vec<_>>(), [false, false, true, true, true]);
2132        assert_eq!(
2133            unjson(r"a\u00e9 \ud83c b\x \u12"),
2134            "aé \u{fffd} b\\x \\u12",
2135            "a lone half is U+FFFD; the rest is kept"
2136        );
2137    }
2138
2139    /// Honest media: one row per picture at its largest copy (the og card's 1287 px
2140    /// over the body's 393 px, alt from the copy that has one), the tag's hi-res or lazy source over its `src`,
2141    /// fillers dropped (a `pxl.gif`, a spacer, a placeholder), and listed but not counted: a JSON-LD logo, a logo or
2142    /// a badge by name or class, an avatar-sized square, cards linked to another page (around or laid over). A small
2143    /// non-square thumbnail and a picture linked to its own file page stay content; tracking parameters are cut.
2144    #[test]
2145    fn media_is_counted_honestly() {
2146        let h = include_str!("../tests/fixtures/media-honest.html");
2147        let d = build_doc(&parse(h), "https://news.example/a/river", "https://news.example/a/river", false);
2148        let base = |s: &str| s.trim_start_matches("https://news.example").to_string();
2149        let pick = |demoted: bool| d.media.iter().filter(|m| m.demoted == demoted).map(|m| base(&m.src)).collect();
2150        let counted: Vec<String> = pick(false);
2151        assert_eq!(
2152            counted,
2153            [
2154                "/img/2026/2511401-685193-1287x836.jpg?v=2",
2155                "/img/reply-box-3301.jpg",
2156                "/img/2026/crowd-5512-150x84.jpg",
2157                "/img/lantern-4410.jpg",
2158                "/img/hero-77001-1500.jpg",
2159                "/thumb/250px-Old_bridge_at_dusk.jpg",
2160            ]
2161        );
2162        assert_eq!(d.media[0].alt, "Boats on the river");
2163        let mut demoted: Vec<String> = pick(true);
2164        demoted.sort();
2165        let want = ["/b/build.png", "/brand/site_logo.jpg", "/img/2026/feed-8801-150x84.jpg"];
2166        let more = ["/img/2026/other-9901-393x221.jpg", "/people/editor.jpg", "/static/poster-1024x576.png"];
2167        assert_eq!(demoted, [want, more].concat());
2168        let size = |u: &str| key_of(&url::Url::parse(u).expect("url"));
2169        assert_eq!(size("https://x.io/a/1280px-Big_bridge.jpg").0, size("https://x.io/b/Big_bridge@2x.jpg").0);
2170        assert_eq!(size("https://x.io/p/AbC123=s1600").1, 1600);
2171        assert_eq!(size("https://x.io/p/photo_640x480.jpg?w=1200").1, 1200);
2172    }
2173
2174    /// One picture's key is its own file name without size words,
2175    /// never a folder or a query a CDN sizes or crops in (a proxied original in the query is kept), so different
2176    /// pictures never merge; a picture linked to its own page (a gallery) counts, a feed card does not; a strip
2177    /// (≥ 10:1 by its name's size) is dropped; a generated share card and a short alt naming the site or a map are
2178    /// listed, not counted.
2179    #[test]
2180    fn media_keys_galleries_and_cards() {
2181        let key = |u: &str| key_of(&url::Url::parse(u).expect("url")).0;
2182        let wiki = "https://up.wiki/c/thumb/a/ab/Gate_of_Dawn.jpg/250px-Gate_of_Dawn.jpg";
2183        assert_eq!(key(wiki), key("https://up.wiki/c/a/ab/Gate_of_Dawn.jpg"));
2184        let cdn = "https://cdn.io/fetch/w_1456,c_limit/https%3A%2F%2Fs3.io%2Fimages%2F";
2185        assert_ne!(key(&format!("{cdn}acafbb9a-17a6_389x557.png")), key(&format!("{cdn}46d227b9-ef48_943x796.png")));
2186        assert_eq!(
2187            key(&format!("{cdn}acafbb9a-17a6_389x557.png")),
2188            key("https://cdn.io/w_40/acafbb9a-17a6_389x557.png")
2189        );
2190        assert_ne!(
2191            key("https://x.io/_next/image?url=%2Fa%2Fp1.jpg&w=750"),
2192            key("https://x.io/_next/image?url=%2Fa%2Fp2.jpg")
2193        );
2194        assert_ne!(key("https://x.io/img/IMG_2026.10.11.jpg"), key("https://x.io/img/IMG_2026.10.12.jpg"));
2195        // a `._The_` inside a name is no CDN suffix: two pictures of one series stay two
2196        assert_ne!(key("https://up.wiki/c/History._The_warrior.jpg"), key("https://up.wiki/c/History._A_helmet.jpg"));
2197        assert_eq!(key("https://ae.io/kf/S5501ck.jpg_960x960q75.jpg_.avif"), key("https://ae.io/kf/S5501ck.jpg"));
2198        let thumbs: String = (1..=3)
2199            .map(|i| {
2200                format!("<div><a href='/photos/{i}'><img src='/img/p{i}-thumb.jpg' width=120 height=120></a></div>")
2201            })
2202            .collect();
2203        let h = format!(
2204            "<meta property='og:site_name' content='Jane Photo'><main><p>My portfolio</p>{thumbs}\
2205             <div><a href='/blog/next-post'><img src='/img/next.jpg' alt='Next post'></a></div>\
2206             <p><img src='/img/1500x40whitespace.jpg'><img src='/img/jane.png' alt='Jane Photo logo'>\
2207             <img src='https://opengraph.example/abc/jane/portfolio'><img src='/tile.png' alt='Map'></p></main>"
2208        );
2209        let d = build_doc(&parse(&h), "https://jane.example/portfolio", "https://jane.example/portfolio", false);
2210        let rows: Vec<(&str, bool)> =
2211            d.media.iter().map(|m| (m.src.rsplit('/').next().unwrap_or_default(), m.demoted)).collect();
2212        let (gallery, rest) = rows.split_at(3);
2213        assert!(gallery.iter().all(|r| !r.1) && rest.iter().all(|r| r.1), "{rows:?}");
2214        assert_eq!(rest.iter().map(|r| r.0).collect::<Vec<_>>(), ["jane.png", "next.jpg", "tile.png", "portfolio"]);
2215    }
2216
2217    /// A share card is named by whole generic words of its own file name or its host's first label: never a folder
2218    /// (`/product-card-image/1.jpg` is a product photo), never a brand word; a host only by an Open Graph label
2219    /// (`share_host`), never `social.` or `cards.` (a site's own pictures).
2220    #[test]
2221    fn share_cards_by_whole_words() {
2222        let card = |src: &str| {
2223            let h = format!(
2224                "<main><p>{}</p><img src='{src}' alt='a photo of the ridge at dawn'></main>",
2225                "Text. ".repeat(9)
2226            );
2227            build_doc(&parse(&h), "https://ex.io/p", "https://ex.io/p", false)
2228                .media
2229                .iter()
2230                .map(|m| m.demoted)
2231                .collect::<Vec<_>>()
2232        };
2233        let host = ["https://mastodon.social/a.png", "https://social.ex.io/m/a.png", "https://cards.ex.io/x/1.jpg"];
2234        for src in [&["/product-card-image/1.jpg", "/img/discard.jpg", "/i/blog.png"][..], &host].concat() {
2235            assert_eq!(card(src), [false], "{src}");
2236        }
2237        let proxied = "https://cdn.io/fetch/w_1200/https%3A%2F%2Fs3.io%2Fp%2Fog-image.png";
2238        let og = ["https://opengraph.gh.io/x/repo", "https://og-image.ex.app/a.png", proxied];
2239        for src in [&["/static/og-image.png", "/a/share_card.jpg", "/s/social-preview.jpg"][..], &og].concat() {
2240            assert_eq!(card(src), [true], "{src}");
2241        }
2242    }
2243
2244    /// A size in the file name filters (a strip, an icon) but is never stored as declared.
2245    #[test]
2246    fn size_in_name_is_not_declared() {
2247        let imgs = "<img src='/a/boats-1287x836.jpg' alt='Boats'><img src='/a/rule-1500x40.jpg' alt='a rule'>\
2248                    <img src='/a/dot-12x12.png' alt='a dot'><img src='/a/x.jpg' width=640 height=480 alt='X'>";
2249        let h = format!("<main><p>{}</p>{imgs}</main>", "Text. ".repeat(9));
2250        let d = build_doc(&parse(&h), "https://ex.io/p", "https://ex.io/p", false);
2251        let rows: Vec<(&str, u32, u32)> = d.media.iter().map(|m| (m.alt.as_str(), m.w, m.h)).collect();
2252        assert_eq!(rows, [("Boats", 0, 0), ("X", 640, 480)]);
2253    }
2254
2255    /// The site's name demotes a picture only as whole words: site "X" substring-matched every short alt with an x in
2256    /// it, so a fox photo on x.com printed `0 photos`.
2257    #[test]
2258    fn site_name_by_whole_words() {
2259        let demoted = |site: &str, alt: &str| {
2260            let h = format!(
2261                "<meta property='og:site_name' content='{site}'><main><p>Post</p>\
2262                 <img src='/a/p.jpg' alt='{alt}' width=800 height=600></main>"
2263            );
2264            let d = build_doc(&parse(&h), "https://s.example/p", "https://s.example/p", false);
2265            d.media.iter().map(|m| m.demoted).collect::<Vec<_>>()
2266        };
2267        assert_eq!(demoted("X", "Red fox"), [false]);
2268        assert_eq!(demoted("X", "X"), [true]);
2269        assert_eq!(demoted("Jane Photo", "Jane Photo logo"), [true]);
2270        assert_eq!(demoted("Jane Photo", "Jane Photo"), [true]);
2271        assert_eq!(demoted("Jane Photo", "Jane at the photo fair"), [false]);
2272    }
2273
2274    #[test]
2275    fn digit_sup_is_superscript() {
2276        // `419<sup>00</sup> €` glued into "41900 €" reads as a price a hundred times too high
2277        let h = include_str!("../tests/fixtures/price-sup-digits.html");
2278        let d = build_doc(&parse(h), "https://shop.example/p", "https://shop.example/p", false);
2279        assert!(
2280            has(&d, "Regular price 419⁰⁰ €") && has(&d, "17⁹⁹ €") && has(&d, "12 m², "),
2281            "{:?}",
2282            d.sections.iter().map(|s| &s.lines).collect::<Vec<_>>()
2283        );
2284        assert!(!has(&d, "41900"));
2285    }
2286
2287    /// Cards: a thread's comments hold their replies (their own shape inside) and stay lines, a flat list's open
2288    /// with a byline (a name, a `<time>`) and stay lines too; a menu's
2289    /// `name [lN] 33` is two texts, no card; a block holding code keeps its lines.
2290    #[test]
2291    fn cards_and_what_stays_lines() {
2292        let lines = |body: &str| {
2293            let d = build_doc(&parse(body), "https://ex.com/", "https://ex.com/", false);
2294            d.sections.into_iter().flat_map(|s| s.lines).collect::<Vec<_>>()
2295        };
2296        let reply = |n: usize, inner: &str| {
2297            format!("<div class=c><a href=/u{n}>user{n}</a><div>{n}h ago</div><div>Reply text {n}</div>{inner}</div>")
2298        };
2299        let thread: String = (1..=4).map(|n| reply(n, &reply(n + 10, ""))).collect();
2300        assert!(!lines(&thread).iter().any(|l| l.starts_with(CARD)), "{:?}", lines(&thread));
2301        // a flat comment list: a two-word name, then a `<time>` before the text; never cards
2302        let flat = (1..=5).map(|n| {
2303            format!("<div class=c><a href=/u{n}>John Smith{n}</a> <time>{n}h ago</time><p>I think option {n} wins.</p><p>Also see version 0.{n} notes.</p></div>")
2304        });
2305        let flat = lines(&flat.collect::<String>());
2306        assert!(!flat.iter().any(|l| l.starts_with(CARD)) && flat[0] == "John Smith1 [l1] 1h ago", "{flat:?}");
2307        // a date before a linked heading, a link around the whole card: cards, never a byline
2308        let dated = (1..=5)
2309            .map(|n| format!("<div class=d><time>May {n}</time><h3><a href=/p{n}>Post title {n} here</a></h3></div>"));
2310        let wrapped = (1..=5).map(|n| {
2311            format!("<div class=w><a href=/r{n}><div>Release notes {n}</div><div><time>May {n}</time></div></a></div>")
2312        });
2313        for page in [dated.collect::<String>(), wrapped.collect()] {
2314            assert_eq!(lines(&page).iter().filter(|l| l.starts_with(CARD)).count(), 5, "{:?}", lines(&page));
2315        }
2316        let menu: String = (1..=5).map(|n| format!("<li class=m><a href=/r{n}>Region {n}</a> 3{n}</li>")).collect();
2317        assert!(!lines(&format!("<ul>{menu}</ul>")).iter().any(|l| l.starts_with(CARD)));
2318        let code: String = (1..=4)
2319            .map(|n| format!("<div class=k><a href=/f{n}>fn f{n}</a><p>Since {n}.0</p><pre>f{n}()</pre></div>"))
2320            .collect();
2321        assert!(!lines(&code).iter().any(|l| l.starts_with(CARD)), "{:?}", lines(&code));
2322    }
2323
2324    /// A card group is decided whole: every member one row when four in five are one item linked by its title,
2325    /// else none. The main link: the one around the heading (inside it or around it), else the one around the
2326    /// most text (a job beside its company's profile link); a document's sections (a heading no link holds, its
2327    /// hatnote link aside; a type named inside a heading) and forum posts (a name links) stay lines.
2328    #[test]
2329    fn cards_are_whole_groups_of_titled_items() {
2330        let doc = |body: &str| build_doc(&parse(body), "https://ex.com/", "https://ex.com/", false);
2331        let rows = |d: &Doc| {
2332            d.sections.iter().flat_map(|s| s.lines.clone()).filter(|l| l.starts_with(CARD)).collect::<Vec<_>>()
2333        };
2334        let story = |n: usize| {
2335            format!(
2336                "<div class=t><a href=/a{n}><h3>Story number {n} today</h3><p>Teaser {n}</p><span>{n} hrs ago</span></a></div>"
2337            )
2338        };
2339        let d = doc(&format!("<h1>News</h1>{}", (1..=4).map(story).collect::<String>()));
2340        assert_eq!(
2341            rows(&d).get(1).map(String::as_str),
2342            Some("▸ Story number 2 today [l2] · Teaser 2 · 2 hrs ago"),
2343            "{:?}",
2344            d.sections.iter().map(|s| (&s.title, &s.lines)).collect::<Vec<_>>()
2345        );
2346        assert_eq!(d.links[1], "https://ex.com/a2");
2347        let job = |n: usize| {
2348            format!(
2349                "<li class=j><a href=/co{n}>View Company Profile</a><a href=/job{n}><div>New</div><div>Senior engineer {n}</div><div>Acme Ltd</div><div>$100,000 USD</div></a></li>"
2350            )
2351        };
2352        let d = doc(&format!("<ul>{}</ul>", (1..=4).map(job).collect::<String>()));
2353        assert_eq!(rows(&d)[0], "▸ Senior engineer 1 [l2] · View Company Profile [l1] · New · Acme Ltd · $100,000 USD");
2354        let wiki = |n: usize| {
2355            format!(
2356                "<section class=s><h2>Topic {n}</h2><div class=hat>Main article: <a href=/t{n}>Topic {n}</a></div><p>In 19{n}0 the <a href=/w{n}>thing {n}</a> grew.</p></section>"
2357            )
2358        };
2359        let d = doc(&format!("<h1>History</h1>{}", (1..=5).map(wiki).collect::<String>()));
2360        assert!(rows(&d).is_empty() && d.sections.len() == 6, "{:?}", rows(&d));
2361        let method = |n: usize| {
2362            format!(
2363                "<div class=m><h3 id=f{n}><a href=#f{n}>fn set_{n}(x: u{n}) -> Self</a></h3><a href=/src{n}>source</a><p>Sets {n}.</p></div>"
2364            )
2365        };
2366        assert!(rows(&doc(&(1..=5).map(method).collect::<String>())).is_empty());
2367        let auto = |n: usize| {
2368            format!("<section class=impl><a href=#i{n}>§</a><h3>impl !Send{n} for <a href=/T.html>T</a></h3></section>")
2369        };
2370        assert!(rows(&doc(&(1..=5).map(auto).collect::<String>())).is_empty());
2371        let post = |n: usize| {
2372            format!(
2373                "<div class=p><a href=/u/user{n}>user{n}</a><span>Oct {n}, 2025</span><p>My reply number {n}.</p></div>"
2374            )
2375        };
2376        assert!(rows(&doc(&(1..=5).map(post).collect::<String>())).is_empty());
2377        // four in five → all five rows, the odd one (an unlinked heading) too: no section between the cards
2378        let odd = "<div class=t><h3>Our sponsor of 2026</h3><p>Ad copy</p><a href=/ad>more</a></div>";
2379        let d = doc(&format!("<h1>News</h1>{}{odd}", (1..=4).map(story).collect::<String>()));
2380        assert!(rows(&d).len() == 5 && d.sections.len() == 1, "{:?}", rows(&d));
2381        let d = doc(&format!("<h1>News</h1>{}{odd}{odd}{odd}", (1..=2).map(story).collect::<String>()));
2382        assert!(rows(&d).is_empty(), "{:?}", rows(&d));
2383    }
2384
2385    /// A card row keeps the page's order, a repeated piece too (only the title's repeat, an alt, drops); a
2386    /// member holding a second heading is an article (a blog post), never one item: its sections stay; a link the
2387    /// members share is no title.
2388    #[test]
2389    fn card_pieces_keep_order_and_articles_stay_sections() {
2390        let doc = |body: &str| build_doc(&parse(body), "https://ex.com/", "https://ex.com/", false);
2391        let rows = |d: &Doc| {
2392            d.sections.iter().flat_map(|s| s.lines.clone()).filter(|l| l.starts_with(CARD)).collect::<Vec<_>>()
2393        };
2394        let note = |n: usize| {
2395            format!(
2396                "<div class=r><a href=/v{n}><h3>Release {n} notes</h3></a><img alt='Release {n} notes'><p>This release brings many small fixes to the parser and the cache layer.</p><li>Bump dependencies</li><li>Fix the docs</li><li>Bump dependencies</li></div>"
2397            )
2398        };
2399        let d = doc(&(1..=4).map(note).collect::<String>());
2400        let want = "▸ Release 1 notes [l1] · This release brings many small fixes to the parser and the cache layer. · Bump dependencies · Fix the docs · Bump dependencies";
2401        assert_eq!(rows(&d).first().map(String::as_str), Some(want), "{:?}", rows(&d));
2402        let post = |n: usize| {
2403            format!(
2404                "<article class=post><h2><a href=/p{n}>Post title number {n}</a></h2><time>Oct {n}</time><p>Intro {n}.</p><h3>Background {n}</h3><p>More {n}.</p></article>"
2405            )
2406        };
2407        let d = doc(&format!("<h1>Blog</h1>{}", (1..=4).map(post).collect::<String>()));
2408        assert!(rows(&d).is_empty() && d.sections.len() == 9, "{:?}", rows(&d));
2409        // a link every member shares (a store's "learn more") never titles one: the item's own link does
2410        let app = |n: usize| {
2411            format!(
2412                "<div class=a><div><a href=/help>Learn more about results and reviews.</a></div><div><a href=/app{n}>Markdown tool {n}</a></div><div>4.{n}</div></div>"
2413            )
2414        };
2415        let d = doc(&(1..=4).map(app).collect::<String>());
2416        let want = "▸ Markdown tool 2 [l3] · Learn more about results and reviews. [l1] · 4.2";
2417        assert_eq!(rows(&d).get(1).map(String::as_str), Some(want), "{:?}", rows(&d));
2418    }
2419
2420    /// Siblings are sorted into roles in one pass: ten times the list items take about ten times as long (a
2421    /// pass per kid over its siblings took 22 s on a 5 MB page).
2422    #[test]
2423    fn many_siblings_are_linear() {
2424        let run = |n: usize| {
2425            let body = format!("<ul>{}</ul>", (0..n).map(|k| format!("<li>{k}</li>")).collect::<String>());
2426            let t = std::time::Instant::now();
2427            let d = build_doc(&parse(&body), "https://ex.com/", "https://ex.com/", false);
2428            assert_eq!(d.sections.iter().map(|s| s.lines.len()).sum::<usize>(), n);
2429            t.elapsed().as_secs_f64()
2430        };
2431        let (small, big) = (run(4_000), run(40_000));
2432        assert!(big < 40.0 * small + 0.5, "{small:.3} s → {big:.3} s");
2433    }
2434}