oxipdf-html 0.1.0

HTML+CSS → StyledTree adapter for the oxipdf PDF engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
//! Main HTML → StyledTree conversion logic.
//!
//! Walks the parsed DOM tree, resolves CSS styles from `<style>` blocks
//! and inline `style=""` attributes, and builds a `StyledTree`.

use std::path::PathBuf;

use scraper::{Html, Node, Selector};

use oxipdf_ir::node::{ContentVariant, ImageContent, LinkContent, LinkTarget};
use oxipdf_ir::semantic::SemanticRole;
use oxipdf_ir::style::{Display, ResolvedStyle};
use oxipdf_ir::tree::StyledTreeBuilder;
use oxipdf_ir::units::Pt;
use oxipdf_ir::{IrVersion, TextContent};

use crate::css::{self, apply_declarations, parse_declarations};
use crate::elements::{self, heading_font_size};
use crate::error::HtmlError;

use super::cascade::{
    apply_important_stylesheet_rules, apply_matching_rules, apply_normal_stylesheet_rules,
};
use super::stylesheets::{collect_link_stylesheets, collect_style_rules};

/// Options for HTML → StyledTree conversion.
#[derive(Debug, Clone, Default)]
pub struct ConvertOptions {
    /// Additional CSS text applied after `<style>` blocks.
    pub extra_css: String,
    /// Base directory for resolving relative `<link rel="stylesheet" href="...">` paths.
    /// When `None`, `<link>` elements with relative paths are skipped.
    pub base_dir: Option<PathBuf>,
}

/// Convert an HTML string to a `StyledTree`.
///
/// Parses the HTML, extracts `<style>` blocks, resolves the CSS cascade,
/// and maps HTML elements to oxipdf IR nodes.
pub fn html_to_tree(html: &str) -> Result<oxipdf_ir::tree::StyledTree, HtmlError> {
    html_to_tree_with_options(html, &ConvertOptions::default())
}

/// Convert an HTML string to a `StyledTree` with additional CSS.
///
/// The `extra_css` is applied after any `<style>` blocks in the HTML,
/// with the same specificity rules.
pub fn html_to_tree_with_css(
    html: &str,
    extra_css: &str,
) -> Result<oxipdf_ir::tree::StyledTree, HtmlError> {
    html_to_tree_with_options(
        html,
        &ConvertOptions {
            extra_css: extra_css.to_string(),
            ..Default::default()
        },
    )
}

/// Convert an HTML string to a `StyledTree` with full options.
///
/// Supports `<style>` blocks, `<link rel="stylesheet">` (when `base_dir` set),
/// extra CSS, `!important` cascade, and all element types.
pub fn html_to_tree_with_options(
    html: &str,
    options: &ConvertOptions,
) -> Result<oxipdf_ir::tree::StyledTree, HtmlError> {
    let document = Html::parse_document(html);

    // Collect CSS rules: <link> stylesheets + <style> blocks + extra CSS.
    let mut rules = collect_link_stylesheets(&document, options.base_dir.as_deref());
    rules.extend(collect_style_rules(&document));
    if !options.extra_css.is_empty() {
        rules.extend(css::parse_stylesheet(&options.extra_css));
    }

    let mut builder = StyledTreeBuilder::new(IrVersion::new(1, 0));

    // Find the <body> element, or fall back to the document root.
    let body_sel = Selector::parse("body").expect("'body' is a valid CSS selector");
    let body_node = document
        .select(&body_sel)
        .next()
        .map(|el| el.id())
        .unwrap_or(document.root_element().id());

    // Create root container.
    let mut root_style = ResolvedStyle::default();
    root_style.layout.display = Display::Block;
    let root_id = builder.add_node(
        ContentVariant::Container,
        root_style,
        Some(SemanticRole::Document),
        None,
    );

    // Walk body children.
    let body_ref = document
        .tree
        .get(body_node)
        .ok_or(HtmlError::EmptyDocument)?;
    convert_children(&document, body_ref, root_id, &rules, &mut builder)?;

    if builder.len() < 2 {
        return Err(HtmlError::EmptyDocument);
    }

    Ok(builder.build()?)
}

/// Convert child nodes of a DOM node to StyledTree nodes.
fn convert_children(
    document: &Html,
    parent_node: ego_tree::NodeRef<'_, Node>,
    parent_id: oxipdf_ir::node::NodeId,
    rules: &[crate::css::CssRule],
    builder: &mut StyledTreeBuilder,
) -> Result<(), HtmlError> {
    for child in parent_node.children() {
        match child.value() {
            Node::Text(text) => {
                let t = text.text.to_string();
                if !t.trim().is_empty() {
                    let mut style = ResolvedStyle::default();
                    style.layout.display = Display::Inline;
                    builder.add_child(
                        parent_id,
                        ContentVariant::Text(TextContent::new(&t)),
                        style,
                        None,
                        None,
                    );
                }
            }
            Node::Element(el) => {
                convert_element(document, child, el, parent_id, rules, builder)?;
            }
            _ => {} // Comments, processing instructions — skip.
        }
    }
    Ok(())
}

/// Convert a single HTML element to a StyledTree node.
fn convert_element(
    document: &Html,
    node_ref: ego_tree::NodeRef<'_, Node>,
    el: &scraper::node::Element,
    parent_id: oxipdf_ir::node::NodeId,
    rules: &[crate::css::CssRule],
    builder: &mut StyledTreeBuilder,
) -> Result<(), HtmlError> {
    let tag = el.name().to_lowercase();

    // Skip non-renderable elements.
    if matches!(
        tag.as_str(),
        "script" | "style" | "meta" | "link" | "head" | "title"
    ) {
        return Ok(());
    }

    // Skip table sub-elements when encountered outside a <table> context
    // (they are handled by convert_table when encountered inside <table>).
    if matches!(
        tag.as_str(),
        "thead" | "tbody" | "tfoot" | "tr" | "td" | "th" | "caption" | "colgroup" | "col"
    ) {
        return Ok(());
    }

    // Handle <br> as newline text.
    if tag == "br" {
        let mut style = ResolvedStyle::default();
        style.layout.display = Display::Inline;
        builder.add_child(
            parent_id,
            ContentVariant::Text(TextContent::new("\n")),
            style,
            None,
            None,
        );
        return Ok(());
    }

    let info = elements::element_info(&tag);
    let element_id = el.attr("id").map(|s| s.to_string());

    // Build resolved style: base defaults → CSS rules → element overrides → inline style.
    let mut style = ResolvedStyle::default();
    style.layout.display = info.default_display;

    // Apply heading font size.
    if let Some(SemanticRole::Heading { level }) = info.role {
        style.typography.font_size = Pt::new(heading_font_size(level));
    }

    // Apply the CSS cascade.
    //
    // When the element has an inline `style=""` attribute we must interleave
    // the two phases of the stylesheet cascade with the inline declarations:
    //   1. Normal stylesheet declarations
    //   2. Element-implied overrides (bold for <strong>, italic for <em>, etc.)
    //   3. Normal inline declarations
    //   4. !important stylesheet declarations
    //   5. !important inline declarations  (beats everything)
    //
    // When there is no inline style the two stylesheet phases are applied
    // together via apply_matching_rules, followed by element overrides.
    let inline_css = el.attr("style");

    if inline_css.is_some() {
        apply_normal_stylesheet_rules(document, node_ref.id(), &mut style, rules);
    } else {
        apply_matching_rules(document, node_ref.id(), &mut style, rules);
    }

    // Element-implied styles run after normal stylesheet rules.
    info.style_overrides.apply(&mut style);

    // Apply monospace font hint.
    if info.style_overrides.is_monospace && style.typography.font_families.is_empty() {
        style.typography.font_families = vec!["monospace".to_string()];
    }

    if let Some(inline_css) = inline_css {
        let decls = parse_declarations(inline_css);

        // Normal inline declarations.
        let normal: Vec<_> = decls.iter().filter(|d| !d.important).cloned().collect();
        if !normal.is_empty() {
            apply_declarations(&mut style, &normal);
        }

        // Stylesheet !important declarations (override normal inline).
        apply_important_stylesheet_rules(document, node_ref.id(), &mut style, rules);

        // Inline !important declarations (beats everything).
        let important: Vec<_> = decls.iter().filter(|d| d.important).cloned().collect();
        if !important.is_empty() {
            apply_declarations(&mut style, &important);
        }
    }

    // Handle special elements.
    match tag.as_str() {
        "table" => {
            return super::table::convert_table(
                document, node_ref, parent_id, style, rules, element_id, builder,
            );
        }
        "img" => {
            return convert_img(el, parent_id, style, info.role, element_id, builder);
        }
        "a" => {
            return convert_link(
                document, node_ref, el, parent_id, style, rules, element_id, builder,
            );
        }
        "hr" => {
            style.visual.border_top = oxipdf_ir::style::visual::BorderSide {
                width: Pt::new(1.0),
                style: oxipdf_ir::style::visual::BorderStyle::Solid,
                color: oxipdf_ir::color::Color::rgb(0.8, 0.8, 0.8),
            };
            style.layout.margin_top = oxipdf_ir::Dimension::Length(Pt::new(6.0));
            style.layout.margin_bottom = oxipdf_ir::Dimension::Length(Pt::new(6.0));
            builder.add_child(
                parent_id,
                ContentVariant::Container,
                style,
                None,
                element_id,
            );
            return Ok(());
        }
        _ => {}
    }

    // Create the node and recurse into children.
    let node_id = builder.add_child(parent_id, info.content, style, info.role, element_id);
    convert_children(document, node_ref, node_id, rules, builder)?;

    Ok(())
}

/// Convert an `<img>` element to an Image node.
fn convert_img(
    el: &scraper::node::Element,
    parent_id: oxipdf_ir::node::NodeId,
    style: ResolvedStyle,
    role: Option<SemanticRole>,
    element_id: Option<String>,
    builder: &mut StyledTreeBuilder,
) -> Result<(), HtmlError> {
    let src = el.attr("src").unwrap_or_default();
    let alt = el.attr("alt").map(|s| s.to_string());
    let width = el
        .attr("width")
        .and_then(|w| w.parse::<f64>().ok())
        .unwrap_or(100.0);
    let height = el
        .attr("height")
        .and_then(|h| h.parse::<f64>().ok())
        .unwrap_or(100.0);

    // Only support data: URIs for now (no network I/O).
    if let Some((data, format)) = super::uri::parse_data_uri(src) {
        let mut img = ImageContent::with_dimensions(
            data,
            format,
            Pt::new(width * 0.75),
            Pt::new(height * 0.75),
        );
        if let Some(alt_text) = alt {
            img = img.with_alt_text(alt_text);
        }
        builder.add_child(
            parent_id,
            ContentVariant::Image(img),
            style,
            role.or(Some(SemanticRole::Figure)),
            element_id,
        );
    }
    // Non-data URIs silently skipped (no network I/O in the engine).

    Ok(())
}

/// Convert an `<a>` element to a Link node wrapping its children.
#[allow(clippy::too_many_arguments)]
fn convert_link(
    document: &Html,
    node_ref: ego_tree::NodeRef<'_, Node>,
    el: &scraper::node::Element,
    parent_id: oxipdf_ir::node::NodeId,
    mut style: ResolvedStyle,
    rules: &[crate::css::CssRule],
    element_id: Option<String>,
    builder: &mut StyledTreeBuilder,
) -> Result<(), HtmlError> {
    let href = el.attr("href").unwrap_or_default().to_string();
    let target = if let Some(fragment) = href.strip_prefix('#') {
        LinkTarget::Internal(fragment.to_string())
    } else {
        LinkTarget::External(href)
    };

    // Default link styling: blue + underline.
    if style.typography.color == oxipdf_ir::color::Color::BLACK {
        style.typography.color = oxipdf_ir::color::Color::rgb(0.0, 0.0, 0.8);
    }
    if style.typography.text_decoration == oxipdf_ir::style::typography::TextDecoration::None {
        style.typography.text_decoration = oxipdf_ir::style::typography::TextDecoration::Underline;
    }
    style.layout.display = Display::Inline;

    let link_id = builder.add_child(
        parent_id,
        ContentVariant::Link(LinkContent { target }),
        style,
        None,
        element_id,
    );

    convert_children(document, node_ref, link_id, rules, builder)?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use oxipdf_ir::node::LinkTarget;
    use oxipdf_ir::style::typography::FontStyle;

    #[test]
    fn simple_paragraph() {
        let tree = html_to_tree("<p>Hello world</p>").unwrap();
        assert!(tree.node_count() >= 3); // root + p + text
    }

    #[test]
    fn headings_create_semantic_roles() {
        let tree = html_to_tree("<h1>Title</h1><h2>Sub</h2>").unwrap();
        let mut found_h1 = false;
        let mut found_h2 = false;
        for node in tree.iter_nodes() {
            if node.semantic_role == Some(SemanticRole::Heading { level: 1 }) {
                found_h1 = true;
            }
            if node.semantic_role == Some(SemanticRole::Heading { level: 2 }) {
                found_h2 = true;
            }
        }
        assert!(found_h1, "should have H1");
        assert!(found_h2, "should have H2");
    }

    #[test]
    fn inline_elements_styled() {
        let tree = html_to_tree("<p><strong>bold</strong> and <em>italic</em></p>").unwrap();
        let mut found_bold = false;
        let mut found_italic = false;
        for node in tree.iter_nodes() {
            if node.style.typography.font_weight == 700 {
                found_bold = true;
            }
            if node.style.typography.font_style == FontStyle::Italic {
                found_italic = true;
            }
        }
        assert!(found_bold, "should have bold");
        assert!(found_italic, "should have italic");
    }

    #[test]
    fn style_block_applied() {
        let html = r##"
            <style>p { color: #ff0000; font-size: 14pt; }</style>
            <p>Red text</p>
        "##;
        let tree = html_to_tree(html).unwrap();
        let mut found = false;
        for node in tree.iter_nodes() {
            if node.semantic_role == Some(SemanticRole::Paragraph) {
                found = true;
                assert!(
                    (node.style.typography.font_size.get() - 14.0).abs() < 0.01,
                    "font size should be 14pt"
                );
            }
        }
        assert!(found, "should find paragraph");
    }

    #[test]
    fn inline_style_overrides_stylesheet() {
        let html = r##"
            <style>p { font-size: 10pt; }</style>
            <p style="font-size: 20pt">Big text</p>
        "##;
        let tree = html_to_tree(html).unwrap();
        for node in tree.iter_nodes() {
            if node.semantic_role == Some(SemanticRole::Paragraph) {
                assert!(
                    (node.style.typography.font_size.get() - 20.0).abs() < 0.01,
                    "inline style should override stylesheet"
                );
            }
        }
    }

    #[test]
    fn extra_css_applied() {
        let html = "<p>Styled</p>";
        let css = "p { font-size: 18pt; }";
        let tree = html_to_tree_with_css(html, css).unwrap();
        for node in tree.iter_nodes() {
            if node.semantic_role == Some(SemanticRole::Paragraph) {
                assert!((node.style.typography.font_size.get() - 18.0).abs() < 0.01);
            }
        }
    }

    #[test]
    fn empty_body_returns_error() {
        assert!(matches!(
            html_to_tree("<html><body></body></html>"),
            Err(HtmlError::EmptyDocument)
        ));
    }

    #[test]
    fn br_creates_newline_text() {
        let tree = html_to_tree("<p>Line 1<br>Line 2</p>").unwrap();
        let mut found_newline = false;
        for node in tree.iter_nodes() {
            if let ContentVariant::Text(ref t) = node.content {
                if t.text.contains('\n') {
                    found_newline = true;
                }
            }
        }
        assert!(found_newline, "should have newline from <br>");
    }

    #[test]
    fn link_creates_link_node() {
        let tree = html_to_tree(r#"<a href="https://example.com">Click</a>"#).unwrap();
        let mut found_link = false;
        for node in tree.iter_nodes() {
            if let ContentVariant::Link(ref l) = node.content {
                if let LinkTarget::External(ref url) = l.target {
                    if url == "https://example.com" {
                        found_link = true;
                    }
                }
            }
        }
        assert!(found_link, "should have external link");
    }

    // -----------------------------------------------------------------------
    // !important tests
    // -----------------------------------------------------------------------

    #[test]
    fn important_overrides_higher_specificity() {
        let html = r##"
            <style>
                #specific { font-size: 30pt; }
                p { font-size: 14pt !important; }
            </style>
            <p id="specific">Text</p>
        "##;
        let tree = html_to_tree(html).unwrap();
        for node in tree.iter_nodes() {
            if node.semantic_role == Some(SemanticRole::Paragraph) {
                assert!(
                    (node.style.typography.font_size.get() - 14.0).abs() < 0.01,
                    "!important should override #id specificity, got {}",
                    node.style.typography.font_size.get()
                );
            }
        }
    }

    #[test]
    fn important_overrides_inline_style() {
        let html = r##"
            <style>p { color: #ff0000 !important; }</style>
            <p style="color: #0000ff">Text</p>
        "##;
        let tree = html_to_tree(html).unwrap();
        for node in tree.iter_nodes() {
            if node.semantic_role == Some(SemanticRole::Paragraph) {
                match node.style.typography.color {
                    oxipdf_ir::color::Color::Srgb { r, b, .. } => {
                        assert!(
                            r > 0.9 && b < 0.1,
                            "!important red should override inline blue"
                        );
                    }
                    _ => panic!("expected Srgb color"),
                }
            }
        }
    }

    #[test]
    fn link_stylesheet_loaded() {
        // Write a temp CSS file.
        let dir = std::env::temp_dir().join("oxipdf_html_test");
        let _ = std::fs::create_dir_all(&dir);
        let css_path = dir.join("test_style.css");
        std::fs::write(&css_path, "p { font-size: 22pt; }").unwrap();

        let html = r#"
            <link rel="stylesheet" href="test_style.css">
            <p>Styled from file</p>
        "#;
        let options = ConvertOptions {
            base_dir: Some(dir.clone()),
            ..Default::default()
        };
        let tree = html_to_tree_with_options(html, &options).unwrap();
        for node in tree.iter_nodes() {
            if node.semantic_role == Some(SemanticRole::Paragraph) {
                assert!(
                    (node.style.typography.font_size.get() - 22.0).abs() < 0.01,
                    "should apply CSS from linked file, got {}",
                    node.style.typography.font_size.get()
                );
            }
        }

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn link_stylesheet_missing_file_skipped() {
        let html = r#"
            <link rel="stylesheet" href="nonexistent.css">
            <p>Still works</p>
        "#;
        let options = ConvertOptions {
            base_dir: Some(std::env::temp_dir()),
            ..Default::default()
        };
        // Should not error — missing CSS files are silently skipped.
        let tree = html_to_tree_with_options(html, &options).unwrap();
        assert!(tree.node_count() >= 3);
    }

    #[test]
    fn link_stylesheet_no_base_dir_skipped() {
        let html = r#"
            <link rel="stylesheet" href="style.css">
            <p>No base dir</p>
        "#;
        // No base_dir → relative links skipped.
        let tree = html_to_tree(html).unwrap();
        assert!(tree.node_count() >= 3);
    }

    #[test]
    fn link_stylesheet_http_skipped() {
        let html = r#"
            <link rel="stylesheet" href="https://example.com/style.css">
            <p>No network</p>
        "#;
        let options = ConvertOptions {
            base_dir: Some(std::env::temp_dir()),
            ..Default::default()
        };
        // HTTP URLs silently skipped — no network I/O.
        let tree = html_to_tree_with_options(html, &options).unwrap();
        assert!(tree.node_count() >= 3);
    }

    #[test]
    fn inline_important_beats_stylesheet_important() {
        let html = r##"
            <style>p { font-size: 10pt !important; }</style>
            <p style="font-size: 20pt !important">Text</p>
        "##;
        let tree = html_to_tree(html).unwrap();
        for node in tree.iter_nodes() {
            if node.semantic_role == Some(SemanticRole::Paragraph) {
                assert!(
                    (node.style.typography.font_size.get() - 20.0).abs() < 0.01,
                    "inline !important should beat stylesheet !important, got {}",
                    node.style.typography.font_size.get()
                );
            }
        }
    }
}