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