1use 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
14pub const DOC_V: u32 = 16;
16pub const COMMENT: usize = 7;
18
19#[derive(Deserialize)]
21#[serde(deny_unknown_fields, bound(deserialize = "'de: 'static"))]
22pub struct Lists {
23 block: Vec<&'static str>,
25 drop_always: Vec<&'static str>,
27 sectioning: Vec<&'static str>,
29 sectioning_roles: Vec<&'static str>,
30 cookie: Vec<&'static str>,
32 skip_link: Vec<&'static str>,
34 magic: Vec<(String, &'static str)>,
36 pub text: Vec<&'static str>,
39 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 ad_slot: Vec<&'static str>,
54 said: [Vec<&'static str>; 2],
57 info: Vec<(&'static str, Vec<&'static str>)>,
59 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#[derive(Serialize, Deserialize, Default)]
74pub struct Loss {
75 pub vs_light_lost: usize,
76 pub light_facts: usize,
77 pub pruned_chars: usize,
80 pub visible_chars: usize,
83 pub price_pruned: usize,
86}
87
88#[derive(Serialize, Deserialize, Clone, Default, PartialEq, Debug)]
90pub struct Media {
91 pub src: String,
92 pub alt: String,
93 pub video: bool,
95 pub w: u32,
98 pub h: u32,
99 pub ty: String,
101 pub demoted: bool,
104 #[serde(skip)]
106 key: (String, u32),
107 #[serde(skip)]
109 linked: bool,
110}
111
112pub type Info = IndexMap<String, String>;
114
115#[derive(Serialize, Deserialize, Default)]
116pub struct Tokens {
117 pub clean: usize,
118}
119
120#[derive(Serialize, Deserialize, Default)]
122pub struct Doc {
123 pub v: u32,
124 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 pub anchors: Vec<String>,
135 pub mode: String,
136 pub loss: Loss,
137 pub tokens: Tokens,
138 pub cut: usize,
140 pub islands: usize,
142 pub media: Vec<Media>,
144}
145
146impl Doc {
147 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 pub fn served(&self) -> usize {
167 self.sections.len().saturating_sub(self.islands)
168 }
169}
170
171pub fn tok(s: &str) -> usize {
176 weights(s).sum::<usize>().div_ceil(216)
177}
178
179pub 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
185fn 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
195pub fn collapse(s: &str) -> String {
197 s.split(py_space).filter(|w| !w.is_empty()).collect::<Vec<_>>().join(" ")
198}
199
200fn 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
206pub 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 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
227pub 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 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
248fn 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
270pub 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
297pub 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
302pub 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
308pub fn is_word(c: char) -> bool {
310 c.is_alphanumeric() || c == '_'
311}
312
313pub const CARD: &str = "▸ ";
315pub const PIECE: &str = " · ";
317pub 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 base_url: Option<url::Url>,
346 mode: Mode,
347 js: bool,
348 lines: Vec<Line>,
349 buf: String,
351 marks: Vec<usize>,
352 links: IndexMap<String, String>,
355 inline: usize,
356 media: Vec<usize>,
358 thread: HashMap<usize, usize>,
360 by: Option<(usize, usize)>,
362}
363
364fn 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
380fn 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", "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 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 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 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 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 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 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 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 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; }
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 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 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 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 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 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 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 let key = |i: &&(usize, usize)| (anchor(i.1).len(), lines[i.0].text().len()); 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 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 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); 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 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 let quoted = || up(tree, id).any(|a| self.thread.contains_key(&a));
651 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 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 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 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 "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
770fn 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
777fn 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
790fn shape(n: &Node) -> (&str, &str) {
792 (n.tag.as_str(), n.attr("class").and_then(|c| c.split_whitespace().next()).unwrap_or(""))
793}
794
795fn 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
800fn 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
809const 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
823pub 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
829pub 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 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
857pub 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
864pub fn esc(v: &str) -> String {
866 v.replace('&', "&").replace('"', """).replace('<', "<").replace('>', ">")
867}
868
869pub 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 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 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
897fn 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
905fn 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
917fn 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
930fn 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
942fn 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
964fn 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
994fn px(v: &str) -> u32 {
996 v.trim().trim_end_matches("px").parse().unwrap_or(0)
997}
998
999fn 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
1018fn 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
1044fn 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
1063fn 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
1078fn 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
1086fn has_word(text: &str, list: &[&str]) -> bool {
1089 words(text).iter().any(|w| list.contains(&w.strip_suffix('s').unwrap_or(w)))
1090}
1091
1092fn 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
1097static 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
1103static 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
1109fn 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
1128fn 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 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: ®ex::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 let (w, h) = if m.w == 0 && m.h == 0 { named.unwrap_or_default() } else { (m.w, m.h) };
1151 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
1170fn 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
1187fn 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 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 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 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
1221fn 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 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
1248fn 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
1303fn one_space(text: &str) -> Vec<u8> {
1305 let mut out = serde_json::Serializer::with_formatter(Vec::new(), PrettyFormatter::with_indent(b" "));
1306 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
1315fn 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 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
1346fn 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
1352fn up(t: &Tree, i: usize) -> impl Iterator<Item = usize> + '_ {
1354 std::iter::successors(Some(i), |&p| t.nodes[p].parent)
1355}
1356
1357pub 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 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 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(§ions_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(§ions));
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 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
1409pub 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 #[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 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 #[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 #[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 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 #[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 #[test]
1510 fn spacer_rows_are_comments() {
1511 let para = "this comment says one thing in a sentence long enough to be prose";
1512 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 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 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 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 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 #[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 #[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\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 #[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 #[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 #[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)); }
1714
1715 #[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 #[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 #[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 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 #[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 assert_eq!(one_space(r#"{"r":1.4984391259105099}"#), b"{\n \"r\": 1.4984391259105099\n}");
1787 }
1788
1789 #[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 "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 #[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 #[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 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 #[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 #[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 #[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 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 #[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 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 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 #[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 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 #[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 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 #[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}