Skip to main content

deepdoc_core/extract/
html.rs

1//! HTML extractor — a real HTML5 parse (html5ever), then a walk into the model.
2//!
3//! Going through the `Document` model rather than straight to Markdown is what
4//! keeps `--format json` and `--chunk` working on web pages, and what lets the
5//! same table/list rendering serve every format.
6
7use std::path::Path;
8
9use html5ever::tendril::TendrilSink;
10use html5ever::{local_name, parse_document};
11use markup5ever_rcdom::{Handle, NodeData, RcDom};
12
13use crate::detect::{Format, Sniff};
14use crate::error::{Error, Result};
15use crate::extract::{ExtractOpts, Extractor};
16use crate::model::{Block, Document, Inline, Metadata, Row, Span};
17
18pub struct HtmlExtractor;
19
20impl Extractor for HtmlExtractor {
21    fn name(&self) -> &'static str {
22        "html"
23    }
24
25    fn supports(&self, _path: &Path, sniff: &Sniff) -> bool {
26        crate::detect::detect(sniff) == Some(Format::Html)
27    }
28
29    fn extract(&self, path: &Path, _opts: &ExtractOpts) -> Result<Document> {
30        let raw = std::fs::read(path).map_err(|e| Error::io(path, e))?;
31        let parsed = parse(&String::from_utf8_lossy(&raw));
32
33        Ok(Document {
34            meta: Metadata {
35                title: parsed.title,
36                author: parsed.author,
37                language: parsed.language,
38                source_format: Some(Format::Html),
39                source_path: Some(path.display().to_string()),
40                ..Metadata::default()
41            },
42            blocks: parsed.blocks,
43        })
44    }
45}
46
47/// What a parsed page yields.
48#[derive(Debug, Default, PartialEq)]
49pub struct Parsed {
50    pub title: Option<String>,
51    pub author: Option<String>,
52    /// The `lang` attribute of `<html>`, when the page declares one.
53    pub language: Option<String>,
54    pub blocks: Vec<Block>,
55}
56
57/// Parse an HTML document. Pure.
58pub fn parse(html: &str) -> Parsed {
59    let dom = parse_document(RcDom::default(), Default::default()).one(html);
60
61    let mut parsed = Parsed::default();
62    let mut builder = Builder::default();
63    walk(&dom.document, &mut builder, &mut parsed);
64    parsed.blocks = builder.finish();
65    parsed
66}
67
68/// Collects blocks, buffering loose inline content into implicit paragraphs.
69#[derive(Default)]
70struct Builder {
71    blocks: Vec<Block>,
72    inline: Vec<Span>,
73}
74
75impl Builder {
76    /// Close the paragraph being accumulated, if it holds anything.
77    fn flush(&mut self) {
78        let spans = trim_spans(std::mem::take(&mut self.inline));
79        if !spans.is_empty() {
80            self.blocks.push(Block::Paragraph {
81                text: Inline::new(spans),
82            });
83        }
84    }
85
86    fn push_block(&mut self, block: Block) {
87        self.flush();
88        self.blocks.push(block);
89    }
90
91    fn push_spans(&mut self, spans: Vec<Span>) {
92        self.inline.extend(spans);
93    }
94
95    fn finish(mut self) -> Vec<Block> {
96        self.flush();
97        self.blocks
98    }
99}
100
101/// Elements whose content is never document text.
102fn is_dropped(tag: &str) -> bool {
103    matches!(
104        tag,
105        "script"
106            | "style"
107            | "noscript"
108            | "template"
109            | "svg"
110            | "canvas"
111            | "iframe"
112            | "object"
113            | "embed"
114            | "audio"
115            | "video"
116            | "form"
117            | "button"
118            | "select"
119            | "textarea"
120            | "input"
121            // Page furniture, not content — the usual reason HTML → Markdown
122            // output is full of menus.
123            | "nav"
124            | "footer"
125            | "aside"
126    )
127}
128
129fn is_inline(tag: &str) -> bool {
130    matches!(
131        tag,
132        "a" | "abbr"
133            | "b"
134            | "cite"
135            | "code"
136            | "del"
137            | "em"
138            | "i"
139            | "ins"
140            | "kbd"
141            | "mark"
142            | "q"
143            | "s"
144            | "samp"
145            | "small"
146            | "span"
147            | "strong"
148            | "sub"
149            | "sup"
150            | "time"
151            | "tt"
152            | "u"
153            | "var"
154    )
155}
156
157fn walk(node: &Handle, builder: &mut Builder, parsed: &mut Parsed) {
158    for child in node.children.borrow().iter() {
159        match &child.data {
160            NodeData::Text { contents } => {
161                let text = normalize_whitespace(&contents.borrow());
162                if !text.is_empty() {
163                    builder.push_spans(vec![Span::Text(text)]);
164                }
165            }
166            NodeData::Element { name, attrs, .. } => {
167                let tag = name.local.as_ref();
168                if is_dropped(tag) {
169                    continue;
170                }
171
172                match tag {
173                    "title" => {
174                        let title = text_content(child).trim().to_string();
175                        if parsed.title.is_none() && !title.is_empty() {
176                            parsed.title = Some(title);
177                        }
178                    }
179                    "html" => {
180                        parsed.language = attr(child, "lang")
181                            .map(|lang| lang.trim().to_string())
182                            .filter(|lang| !lang.is_empty());
183                        builder.flush();
184                        walk(child, builder, parsed);
185                        builder.flush();
186                    }
187                    "meta" => {
188                        let attrs = attrs.borrow();
189                        let name = attrs
190                            .iter()
191                            .find(|a| a.name.local == local_name!("name"))
192                            .map(|a| a.value.to_ascii_lowercase());
193                        if name.as_deref() == Some("author") {
194                            let author = attrs
195                                .iter()
196                                .find(|a| a.name.local == local_name!("content"))
197                                .map(|a| a.value.trim().to_string());
198                            parsed.author = author.filter(|a| !a.is_empty());
199                        }
200                    }
201                    "h1" | "h2" | "h3" | "h4" | "h5" | "h6" => {
202                        let level = tag[1..].parse().unwrap_or(1);
203                        let spans = trim_spans(collect_inline(child));
204                        if !spans.is_empty() {
205                            builder.push_block(Block::Heading {
206                                level,
207                                text: Inline::new(spans),
208                            });
209                        }
210                    }
211                    "p" => {
212                        builder.flush();
213                        let spans = trim_spans(collect_inline(child));
214                        if !spans.is_empty() {
215                            builder.blocks.push(Block::Paragraph {
216                                text: Inline::new(spans),
217                            });
218                        }
219                    }
220                    "br" => builder.push_spans(vec![Span::LineBreak]),
221                    "hr" => builder.flush(),
222                    "pre" => {
223                        let text = text_content(child);
224                        if !text.trim().is_empty() {
225                            builder.push_block(Block::Code {
226                                lang: code_language(child),
227                                text: text.trim_matches('\n').to_string(),
228                            });
229                        }
230                    }
231                    "ul" | "ol" => {
232                        let items = list_items(child, parsed);
233                        if !items.is_empty() {
234                            builder.push_block(Block::List {
235                                ordered: tag == "ol",
236                                items,
237                            });
238                        }
239                    }
240                    "table" => {
241                        if let Some(table) = table_block(child) {
242                            builder.push_block(table);
243                        }
244                    }
245                    "img" => {
246                        if let Some(alt) = attr(child, "alt").filter(|alt| !alt.trim().is_empty()) {
247                            builder.push_block(Block::Image {
248                                alt: Some(alt.trim().to_string()),
249                            });
250                        }
251                    }
252                    tag if is_inline(tag) => {
253                        let spans = collect_inline(child);
254                        builder.push_spans(spans);
255                    }
256                    // Everything else (div, section, article, blockquote, …) is
257                    // a transparent container: recurse and keep the content.
258                    _ => {
259                        builder.flush();
260                        walk(child, builder, parsed);
261                        builder.flush();
262                    }
263                }
264            }
265            _ => {}
266        }
267    }
268}
269
270/// Build one item per `<li>`, recursing so nested lists survive.
271fn list_items(list: &Handle, parsed: &mut Parsed) -> Vec<Vec<Block>> {
272    let mut items = Vec::new();
273    for child in list.children.borrow().iter() {
274        let NodeData::Element { name, .. } = &child.data else {
275            continue;
276        };
277        if name.local.as_ref() != "li" {
278            continue;
279        }
280
281        let mut builder = Builder::default();
282        walk(child, &mut builder, parsed);
283        let blocks = builder.finish();
284        if !blocks.is_empty() {
285            items.push(blocks);
286        }
287    }
288    items
289}
290
291fn table_block(table: &Handle) -> Option<Block> {
292    let mut header: Option<Row> = None;
293    let mut rows = Vec::new();
294
295    for row in table_rows(table) {
296        let mut cells = Vec::new();
297        let mut all_header_cells = true;
298
299        for cell in row.children.borrow().iter() {
300            let NodeData::Element { name, .. } = &cell.data else {
301                continue;
302            };
303            match name.local.as_ref() {
304                "th" => cells.push(Inline::new(trim_spans(collect_inline(cell)))),
305                "td" => {
306                    all_header_cells = false;
307                    cells.push(Inline::new(trim_spans(collect_inline(cell))));
308                }
309                _ => {}
310            }
311        }
312
313        if cells.is_empty() {
314            continue;
315        }
316        if header.is_none() && all_header_cells {
317            header = Some(Row::new(cells));
318        } else {
319            rows.push(Row::new(cells));
320        }
321    }
322
323    (header.is_some() || !rows.is_empty()).then_some(Block::Table { header, rows })
324}
325
326/// Every `<tr>` under a table, whatever section it sits in.
327fn table_rows(node: &Handle) -> Vec<Handle> {
328    let mut rows = Vec::new();
329    for child in node.children.borrow().iter() {
330        if let NodeData::Element { name, .. } = &child.data {
331            match name.local.as_ref() {
332                "tr" => rows.push(child.clone()),
333                "thead" | "tbody" | "tfoot" => rows.extend(table_rows(child)),
334                _ => {}
335            }
336        }
337    }
338    rows
339}
340
341/// Collect the inline content of an element, flattening what the model cannot hold.
342fn collect_inline(node: &Handle) -> Vec<Span> {
343    let mut spans = Vec::new();
344
345    for child in node.children.borrow().iter() {
346        match &child.data {
347            NodeData::Text { contents } => {
348                let text = normalize_whitespace(&contents.borrow());
349                if !text.is_empty() {
350                    spans.push(Span::Text(text));
351                }
352            }
353            NodeData::Element { name, .. } => {
354                let tag = name.local.as_ref();
355                if is_dropped(tag) {
356                    continue;
357                }
358                match tag {
359                    "strong" | "b" => push_styled(&mut spans, child, Span::Bold),
360                    "em" | "i" => push_styled(&mut spans, child, Span::Italic),
361                    "code" | "kbd" | "samp" | "tt" | "var" => {
362                        let text = text_content(child);
363                        if !text.trim().is_empty() {
364                            spans.push(Span::Code(text.trim().to_string()));
365                        }
366                    }
367                    "a" => {
368                        let inner = collect_inline(child);
369                        match attr(child, "href") {
370                            Some(href) if !href.trim().is_empty() && !inner.is_empty() => {
371                                spans.push(Span::Link {
372                                    href: href.trim().to_string(),
373                                    text: inner,
374                                });
375                            }
376                            _ => spans.extend(inner),
377                        }
378                    }
379                    "br" => spans.push(Span::LineBreak),
380                    "img" => {
381                        if let Some(alt) = attr(child, "alt").filter(|alt| !alt.trim().is_empty()) {
382                            spans.push(Span::Text(alt.trim().to_string()));
383                        }
384                    }
385                    _ => spans.extend(collect_inline(child)),
386                }
387            }
388            _ => {}
389        }
390    }
391
392    spans
393}
394
395fn push_styled(spans: &mut Vec<Span>, node: &Handle, wrap: fn(Vec<Span>) -> Span) {
396    let inner = trim_spans(collect_inline(node));
397    if !inner.is_empty() {
398        spans.push(wrap(inner));
399    }
400}
401
402/// `<pre><code class="language-rust">` → `Some("rust")`.
403fn code_language(pre: &Handle) -> Option<String> {
404    let class = attr(pre, "class").or_else(|| {
405        pre.children
406            .borrow()
407            .iter()
408            .find(|child| matches!(&child.data, NodeData::Element { name, .. } if name.local.as_ref() == "code"))
409            .and_then(|code| attr(code, "class"))
410    })?;
411
412    class.split_whitespace().find_map(|token| {
413        token
414            .strip_prefix("language-")
415            .or_else(|| token.strip_prefix("lang-"))
416            .map(str::to_string)
417    })
418}
419
420fn attr(node: &Handle, wanted: &str) -> Option<String> {
421    let NodeData::Element { attrs, .. } = &node.data else {
422        return None;
423    };
424    attrs
425        .borrow()
426        .iter()
427        .find(|attr| attr.name.local.as_ref() == wanted)
428        .map(|attr| attr.value.to_string())
429}
430
431/// All text under a node, with no whitespace normalisation (`<pre>`, `<title>`).
432fn text_content(node: &Handle) -> String {
433    let mut out = String::new();
434    for child in node.children.borrow().iter() {
435        match &child.data {
436            NodeData::Text { contents } => out.push_str(&contents.borrow()),
437            NodeData::Element { name, .. } if !is_dropped(name.local.as_ref()) => {
438                out.push_str(&text_content(child));
439            }
440            _ => {}
441        }
442    }
443    out
444}
445
446/// HTML collapses every run of whitespace into a single space.
447///
448/// Leading and trailing spaces are kept: a text node that is nothing but
449/// whitespace is what separates `</strong>` from the next word. The block's
450/// outer edges are trimmed later, by [`trim_spans`].
451fn normalize_whitespace(text: &str) -> String {
452    let mut out = String::with_capacity(text.len());
453    let mut in_space = false;
454    for ch in text.chars() {
455        if ch.is_whitespace() {
456            in_space = true;
457        } else {
458            if in_space {
459                out.push(' ');
460            }
461            in_space = false;
462            out.push(ch);
463        }
464    }
465    if in_space {
466        out.push(' ');
467    }
468    out
469}
470
471/// Drop the leading and trailing whitespace of a span run.
472fn trim_spans(spans: Vec<Span>) -> Vec<Span> {
473    let mut spans = spans;
474
475    while let Some(first) = spans.first_mut() {
476        if let Span::Text(text) = first {
477            let trimmed = text.trim_start();
478            if trimmed.is_empty() {
479                spans.remove(0);
480                continue;
481            }
482            *text = trimmed.to_string();
483        }
484        break;
485    }
486
487    while let Some(last) = spans.last_mut() {
488        match last {
489            Span::Text(text) => {
490                let trimmed = text.trim_end();
491                if trimmed.is_empty() {
492                    spans.pop();
493                    continue;
494                }
495                *text = trimmed.to_string();
496            }
497            Span::LineBreak => {
498                spans.pop();
499                continue;
500            }
501            _ => {}
502        }
503        break;
504    }
505
506    spans
507}
508
509#[cfg(test)]
510mod tests {
511    use super::*;
512    use crate::render::{RenderOpts, to_markdown};
513
514    fn blocks(html: &str) -> Vec<Block> {
515        parse(html).blocks
516    }
517
518    fn markdown(html: &str) -> String {
519        let doc = Document {
520            meta: Metadata::default(),
521            blocks: blocks(html),
522        };
523        to_markdown(&doc, &RenderOpts::default())
524    }
525
526    #[test]
527    fn reads_title_author_and_language() {
528        let parsed = parse(
529            "<html lang=\"en-GB\"><head><title>A page</title><meta name=\"author\" content=\"Ada\"></head>\
530             <body><p>hi</p></body></html>",
531        );
532        assert_eq!(parsed.title.as_deref(), Some("A page"));
533        assert_eq!(parsed.author.as_deref(), Some("Ada"));
534        assert_eq!(parsed.language.as_deref(), Some("en-GB"));
535    }
536
537    #[test]
538    fn headings_and_paragraphs() {
539        assert_eq!(
540            blocks("<h2>Summary</h2><p>Revenue grew.</p>"),
541            vec![
542                Block::Heading {
543                    level: 2,
544                    text: Inline::text("Summary")
545                },
546                Block::paragraph("Revenue grew."),
547            ]
548        );
549    }
550
551    #[test]
552    fn collapses_whitespace_like_a_browser() {
553        assert_eq!(
554            blocks("<p>one   two\n\n   three</p>"),
555            vec![Block::paragraph("one two three")]
556        );
557    }
558
559    #[test]
560    fn inline_markup_becomes_spans() {
561        let Block::Paragraph { text } = &blocks(
562            "<p>a <strong>bold</strong> <em>it</em> <code>x</code> <a href=\"/l\">link</a></p>",
563        )[0] else {
564            panic!("expected a paragraph");
565        };
566        assert_eq!(
567            text.spans,
568            vec![
569                Span::Text("a ".into()),
570                Span::Bold(vec![Span::Text("bold".into())]),
571                Span::Text(" ".into()),
572                Span::Italic(vec![Span::Text("it".into())]),
573                Span::Text(" ".into()),
574                Span::Code("x".into()),
575                Span::Text(" ".into()),
576                Span::Link {
577                    href: "/l".into(),
578                    text: vec![Span::Text("link".into())],
579                },
580            ]
581        );
582    }
583
584    #[test]
585    fn script_style_and_page_furniture_are_dropped() {
586        assert_eq!(
587            blocks(
588                "<nav><a href=\"/\">menu</a></nav>\
589                 <script>alert(1)</script><style>p{}</style>\
590                 <p>content</p><footer>copyright</footer>"
591            ),
592            vec![Block::paragraph("content")]
593        );
594    }
595
596    #[test]
597    fn nested_lists_survive() {
598        assert_eq!(
599            blocks("<ul><li>one<ol><li>inner</li></ol></li><li>two</li></ul>"),
600            vec![Block::List {
601                ordered: false,
602                items: vec![
603                    vec![
604                        Block::paragraph("one"),
605                        Block::List {
606                            ordered: true,
607                            items: vec![vec![Block::paragraph("inner")]],
608                        },
609                    ],
610                    vec![Block::paragraph("two")],
611                ],
612            }]
613        );
614    }
615
616    #[test]
617    fn tables_use_th_rows_as_the_header() {
618        assert_eq!(
619            blocks(
620                "<table><thead><tr><th>a</th><th>b</th></tr></thead>\
621                 <tbody><tr><td>1</td><td>2</td></tr></tbody></table>"
622            ),
623            vec![Block::Table {
624                header: Some(Row::from_texts(["a", "b"])),
625                rows: vec![Row::from_texts(["1", "2"])],
626            }]
627        );
628    }
629
630    #[test]
631    fn headerless_tables_keep_every_row() {
632        assert_eq!(
633            blocks("<table><tr><td>1</td></tr><tr><td>2</td></tr></table>"),
634            vec![Block::Table {
635                header: None,
636                rows: vec![Row::from_texts(["1"]), Row::from_texts(["2"])],
637            }]
638        );
639    }
640
641    #[test]
642    fn pre_becomes_a_code_block_with_its_language() {
643        assert_eq!(
644            blocks("<pre><code class=\"language-rust\">fn main() {}\n</code></pre>"),
645            vec![Block::Code {
646                lang: Some("rust".into()),
647                text: "fn main() {}".into(),
648            }]
649        );
650    }
651
652    #[test]
653    fn images_keep_their_alt_text() {
654        assert_eq!(
655            blocks("<img src=\"a.png\" alt=\"a diagram\">"),
656            vec![Block::Image {
657                alt: Some("a diagram".into())
658            }]
659        );
660        // Decorative images carry no text and are dropped.
661        assert!(blocks("<img src=\"a.png\" alt=\"\">").is_empty());
662    }
663
664    #[test]
665    fn loose_text_in_a_div_still_becomes_a_paragraph() {
666        assert_eq!(
667            blocks("<div>loose text<br>second line</div>"),
668            vec![Block::Paragraph {
669                text: Inline::new(vec![
670                    Span::Text("loose text".into()),
671                    Span::LineBreak,
672                    Span::Text("second line".into()),
673                ])
674            }]
675        );
676    }
677
678    #[test]
679    fn renders_a_small_page_to_markdown() {
680        let rendered = markdown(
681            "<h1>Report</h1><p>Revenue grew <strong>12%</strong>.</p>\
682             <table><tr><th>Segment</th><th>Q1</th></tr><tr><td>Cloud</td><td>4.1</td></tr></table>",
683        );
684        assert_eq!(
685            rendered,
686            "# Report\n\n\
687             Revenue grew **12%**.\n\n\
688             | Segment | Q1  |\n\
689             | ------- | --- |\n\
690             | Cloud   | 4.1 |\n"
691        );
692    }
693}