ferri-pdf 0.2.0

HTML and CSS to PDF renderer for print, in pure Rust
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
use super::common;
use crate::render_html;
use common::{PROFILE, local_options};

fn render(css: &str, body: &str) -> crate::RenderOutput {
    render_html(
        &format!(
            "<style>{PROFILE}@page{{size:360pt 240pt;margin:24pt}}p,h2{{margin:0;font:12pt/18pt Spike}}h2{{break-after:auto}}.next{{break-before:page}}{css}</style>{body}"
        ),
        &local_options(),
    )
    .expect("target expressions must resolve before final shaping and PDF output")
}

#[test]
fn forward_targets_capture_heading_counter_text_and_committed_page() {
    let output = render(
        "body{counter-reset:chapter 4}h2{counter-increment:chapter 2}a::after{content:' ' target-counter(attr(href),chapter,upper-roman) ': ' target-text(attr(href)) ' (page ' target-counter(attr(href),page) ')'}",
        "<p><a href='#launch'>See</a></p><h2 id=launch class=next>Launch</h2><h2 class=next>Later</h2>",
    );
    let trace = output.layout.unwrap();
    assert_eq!(
        trace.pages.len(),
        3,
        "both authored breaks must survive target resolution"
    );
    let text: Vec<_> = trace.pages[0]
        .iter()
        .map(|line| line.text.as_str())
        .collect();
    assert_eq!(
        text,
        ["See VI: Launch (page 2)"],
        "the target's counter must be captured before the later heading increments it"
    );
    let heading = output
        .headings
        .iter()
        .find(|heading| heading.id.as_deref() == Some("launch"))
        .unwrap();
    assert_eq!(
        heading.page, 2,
        "generated page references must agree with heading destinations"
    );
}

#[test]
fn target_text_uses_shared_pseudo_content_and_whitespace_extraction() {
    let output = render(
        "h2::before{content:'  Before  '}h2::after{content:'  After  '}a::after{content:'[' target-text('#launch',before) '|' target-text('#launch') '|' target-text('#launch',after) '|' target-text('#launch',first-letter) ']'}",
        "<p><a href='#launch'>See</a></p><h2 id=launch class=next>  Launch   window </h2>",
    );
    let trace = output.layout.unwrap();
    let text: Vec<_> = trace.pages[0]
        .iter()
        .map(|line| line.text.as_str())
        .collect();
    assert_eq!(
        text,
        ["See[Before|Launch window|After|B]"],
        "target extraction must share content() whitespace and first-letter semantics"
    );
}

#[test]
fn target_counters_preserve_nested_instances_and_counter_styles() {
    let output = render(
        "body{counter-reset:section 2}section{counter-reset:section 4}a::after{content:'[' target-counters('#target',section,'.',upper-roman) ']'}",
        "<p><a href='#target'>See</a></p><section class=next><h2 id=target>Nested</h2></section>",
    );
    let trace = output.layout.unwrap();
    let text: Vec<_> = trace.pages[0]
        .iter()
        .map(|line| line.text.as_str())
        .collect();
    assert_eq!(
        text,
        ["See[II.IV]"],
        "nested target counters must come from the shared counter scope engine"
    );
}

#[test]
fn borrowed_layout_resolves_literal_targets_without_mutating_the_source_document() {
    let options = local_options();
    let resolver = common::fixture_resolver();
    let html = format!(
        "<style>{PROFILE}.next{{break-before:page}}.reference::after{{content:target-counter('#target',page)}}</style><p class=reference>Page </p><p id=target class=next>Destination</p>"
    );
    let document =
        crate::document::StyledDocument::parse(&html, &options.base, &[], &resolver).unwrap();
    for iteration in 0..2 {
        let trace = crate::layout::layout(&document, &resolver).unwrap();
        assert_eq!(trace.pages.len(), 2, "borrowed layout pass {iteration}");
        assert_eq!(
            trace.pages[0][0].text, "Page 2",
            "literal targets must reserve destinations even without an HTML link"
        );
    }
}

#[test]
fn forward_reference_reflows_before_resolving_its_final_target_page() {
    let body = "<p class=reference>See</p><h2 id=target class=next>The deliberately long destination heading changes how many lines precede this target</h2>";
    let css = "@page{size:180pt 140pt;margin:20pt}.reference{width:70pt}";
    let control = render(&format!("{css}.reference::after{{content:' short'}}"), body);
    let output = render(
        &format!(
            "{css}.reference::after{{content:' ' target-text('#target') ' (page ' target-counter('#target',page) ')'}}"
        ),
        body,
    );
    let page = output
        .headings
        .iter()
        .find(|heading| heading.id.as_deref() == Some("target"))
        .unwrap()
        .page;
    assert!(
        page > control.headings[0].page,
        "expanded target text must change pagination before the reference is finalized"
    );
    let trace = output.layout.unwrap();
    let preceding = trace.pages[..page - 1]
        .iter()
        .flatten()
        .map(|line| line.text.as_str())
        .collect::<Vec<_>>()
        .join(" ");
    assert!(
        preceding.contains(&format!("(page {page})")),
        "reference must use final destination page {page}, got {preceding:?}"
    );
}

#[test]
fn repeated_target_layout_reuses_loaded_images() {
    use crate::{FileResolver, Resource, ResourceBase, ResourceError, ResourceResolver};
    use std::cell::Cell;
    struct CountingResolver {
        images: Cell<usize>,
        files: FileResolver,
    }
    impl ResourceResolver for CountingResolver {
        fn resolve(&self, reference: &str, base: &ResourceBase) -> Result<Resource, ResourceError> {
            if reference.ends_with("image-pattern.png") {
                self.images.set(self.images.get() + 1);
            }
            self.files.resolve(reference, base)
        }
    }
    let resolver = CountingResolver {
        images: Cell::new(0),
        files: common::fixture_resolver(),
    };
    let html = format!(
        "<style>{PROFILE}img{{width:20pt;height:20pt}}h2{{break-before:page}}p::after{{content:target-counter('#target',page)}}</style><img src='../assets/image-pattern.png'><p>Page </p><h2 id=target>Destination</h2>"
    );
    let output = crate::render_with_resolver(&html, &local_options(), &resolver).unwrap();
    assert!(
        output.layout.unwrap().pages[0]
            .iter()
            .any(|line| line.text == "Page 2")
    );
    assert_eq!(
        resolver.images.get(),
        1,
        "layout stabilization must not reload the same image on each formatting pass"
    );
}

#[test]
fn late_named_page_margins_resolve_targets_not_seen_on_the_first_page() {
    let output = render(
        "@page chapter{@top-left{content:'Target ' target-counter('#target',page) ': ' target-text('#target')}}.next{page:chapter}",
        "<p>Opening</p><h2 id=target class=next>Destination</h2>",
    );
    let trace = output.layout.unwrap();
    assert_eq!(trace.pages.len(), 2);
    assert!(
        !trace.pages[0]
            .iter()
            .any(|line| line.text.starts_with("Target "))
    );
    assert!(
        trace.pages[1]
            .iter()
            .any(|line| line.text == "Target 2: Destination"),
        "page-only target expressions must join the same resolution pass as document content"
    );
}

#[test]
fn borrowed_layout_resolves_late_margin_targets_on_repeated_calls() {
    let resolver = common::fixture_resolver();
    let html = format!(
        "<style>{PROFILE}@page chapter{{@top-left{{content:target-text('#target') ' ' target-counter('#target',page)}}}}h2{{page:chapter;break-before:page}}</style><p>Opening</p><h2 id=target>Destination</h2>"
    );
    let document =
        crate::document::StyledDocument::parse(&html, &local_options().base, &[], &resolver)
            .unwrap();
    for iteration in 0..2 {
        let trace = crate::layout::layout(&document, &resolver).unwrap();
        assert_eq!(trace.pages.len(), 2);
        assert!(
            trace.pages[1]
                .iter()
                .any(|line| line.text == "Destination 2"),
            "late margin reference was lost in borrowed layout {iteration}"
        );
    }
}

#[test]
fn cyclic_target_text_keeps_the_last_layout_with_a_diagnostic() {
    let output = render(
        "#a::before{content:target-text('#b',first-letter)}#b::before{content:target-text('#a',first-letter)}",
        "<p id=a>A</p><p id=b>B</p>",
    );
    assert!(
        output.diagnostics.iter().any(|diagnostic| matches!(
            diagnostic,
            crate::RenderDiagnostic::Layout(crate::LayoutDiagnostic::Unsettled(
                crate::Convergence::GeneratedContent
            ))
        )),
        "mutually swapping first letters must be reported, got {:?}",
        output.diagnostics
    );
    let text: Vec<_> = output.layout.unwrap().pages[0]
        .iter()
        .map(|line| line.text.clone())
        .collect();
    assert_eq!(
        text.len(),
        2,
        "the kept pass lays out both paragraphs, got {text:?}"
    );
    for (line, own) in text.iter().zip(["A", "B"]) {
        assert!(
            line.ends_with(own) && line.len() == 2,
            "each paragraph shows one swapped first letter before its own text, got {text:?}"
        );
    }
}

#[test]
fn hidden_target_text_and_counters_use_the_shared_document_state() {
    let output = render(
        "body{counter-reset:chapter 4}#target{display:none;counter-increment:chapter}p::after{content:target-text('#target') ' ' target-counter('#target',chapter)}",
        "<p>See </p><h2 id=target>Hidden title</h2>",
    );
    assert_eq!(
        output.layout.unwrap().pages[0][0].text,
        "See Hidden title 4"
    );
}

#[test]
fn target_references_in_string_assignments_reach_page_margins() {
    let output = render(
        "p{string-set:reference content(before)}p::before{content:target-text('#target')}@page{@top-left{content:string(reference)}}",
        "<p>Opening</p><h2 id=target class=next>Destination</h2>",
    );
    assert!(
        output.layout.unwrap().pages[0]
            .iter()
            .any(|line| line.text == "Destination")
    );
}

#[test]
fn target_reference_in_an_explicit_bookmark_label_resolves() {
    let resolver = common::fixture_resolver();
    let html = format!(
        "<style>{PROFILE}h2{{bookmark-label:target-text('#target') ' page ' target-counter('#target',page)}}.next{{break-before:page}}</style><h2>Opening</h2><p id=target class=next>Destination</p>"
    );
    let document =
        crate::document::StyledDocument::parse(&html, &local_options().base, &[], &resolver)
            .unwrap();
    let (document, trace) = crate::layout::layout_document(document, &resolver).unwrap();
    assert_eq!(trace.pages.len(), 2);
    assert_eq!(
        document.navigation().bookmarks[0].label,
        "Destination page 2"
    );
}

#[test]
fn unresolved_target_references_render_empty_and_retain_the_reason_without_loading_external_documents()
 {
    use crate::style::{Degradation, TargetReferenceError};
    for (reference, expected) in [
        ("#absent", TargetReferenceError::MissingId),
        ("#", TargetReferenceError::MissingFragment),
        (
            "https://example.invalid/external#target",
            TargetReferenceError::ExternalDocument,
        ),
    ] {
        let html = format!(
            "<style>p::after{{content:'[' target-text('{reference}') ']'}}</style><p>Reference</p>"
        );
        let output = render_html(&html, &local_options()).unwrap_or_else(|error| {
            panic!("an unresolved target {reference} must render: {error}")
        });
        assert!(
            output.diagnostics.iter().any(|diagnostic| matches!(
                diagnostic,
                crate::RenderDiagnostic::Degraded(Degradation::UnresolvedTarget {
                    reference: found,
                    reason,
                }) if found == reference && *reason == expected.to_string()
            )),
            "wrong classification for {reference}: {:?}",
            output.diagnostics
        );
        assert_eq!(
            output.layout.unwrap().pages[0][0].text,
            "Reference[]",
            "the unresolved target {reference} renders as empty text"
        );
    }
}

#[test]
fn values_of_targets_without_a_box_render_empty_and_retain_the_reason() {
    use crate::style::{Degradation, TargetReferenceError};
    for (content, target, expected) in [
        (
            "target-counter('#t',page)",
            "<div id=t style=display:none>Hidden</div>",
            "See[]",
        ),
        (
            "target-counters('#t',page,'.')",
            "<div style=display:none><span id=t>Hidden</span></div>",
            "See[]",
        ),
        (
            "target-counter('#t',c) target-text('#t') target-counter('#t',page)",
            "<div id=t style=display:none>Hidden</div>",
            "See[5Hidden]",
        ),
        (
            "target-counter('#t',c) target-text('#t')",
            "<svg><text id=t>Inside SVG</text></svg>",
            "See[]",
        ),
        (
            "target-counters('#t',c,'.') target-text('#t')",
            "<select><option id=t>Option</option></select>",
            "See[]",
        ),
    ] {
        let html = format!(
            "<style>body{{counter-reset:c 5}}p::after{{content:'[' {content} ']'}}</style><p>See</p>{target}"
        );
        let output = render_html(&html, &local_options()).unwrap_or_else(|error| {
            panic!("{content} to the boxless target {target} must render: {error}")
        });
        assert!(
            output.diagnostics.iter().any(|diagnostic| matches!(
                diagnostic,
                crate::RenderDiagnostic::Degraded(Degradation::UnresolvedTarget {
                    reference,
                    reason,
                }) if reference == "#t" && *reason == TargetReferenceError::NoBox.to_string()
            )),
            "{content} to {target} must report the page it lacks: {:?}",
            output.diagnostics
        );
        assert_eq!(
            output.layout.unwrap().pages[0][0].text,
            expected,
            "{content} to {target}: only the values the target lacks render as empty text"
        );
    }
}

#[test]
fn page_targets_use_multi_digit_values_and_final_page_totals() {
    const TARGET_PAGE: usize = 10;
    let mut body = String::from("<p class=reference>See </p>");
    for _ in 1..TARGET_PAGE - 1 {
        body.push_str("<p class=next>Intervening page</p>");
    }
    body.push_str("<h2 id=target class=next>Destination</h2><p class=next>Last page</p>");
    let output = render(
        ".reference::after{content:target-counter('#target',page) '/' target-counter('#target',pages)}",
        &body,
    );
    assert_eq!(output.page_count, TARGET_PAGE + 1);
    assert_eq!(output.headings[0].page, TARGET_PAGE);
    assert_eq!(output.layout.unwrap().pages[0][0].text, "See 10/11");
}

#[test]
fn layouts_for_page_numbers_reuse_every_style_the_first_formatting_computed() {
    use crate::work::{self, Work};
    const SECTIONS: usize = 6;
    let contents: String = (1..=SECTIONS)
        .map(|section| format!("<p><a href='#s{section}'>Section {section}</a></p>"))
        .collect();
    let sections: String = (1..=SECTIONS)
        .map(|section| format!("<h2 id=s{section} class=next>Section {section}</h2>"))
        .collect();
    let html = format!(
        "<style>{PROFILE}@page{{size:360pt 240pt;margin:24pt}}p,h2{{margin:0;font:12pt/18pt Spike}}.next{{break-before:page}}a::after{{content:' ' target-counter(attr(href),page)}}.total::after{{content:' of ' counter(pages)}}</style>{contents}<p class=total>Pages</p>{sections}"
    );
    let resolver = common::fixture_resolver();
    let (document, formatting) = work::measured(Work::ComputedStyle, || {
        crate::document::StyledDocument::parse(&html, &local_options().base, &[], &resolver)
            .expect("the document formats")
    });
    let ((_, trace), relayout) = work::measured(Work::ComputedStyle, || {
        crate::layout::layout_document(document, &resolver).expect("the document lays out")
    });
    let text: Vec<_> = trace.pages[0]
        .iter()
        .map(|line| line.text.as_str())
        .collect();
    let expected: Vec<_> = (1..=SECTIONS)
        .map(|section| format!("Section {section} {}", section + 1))
        .chain([format!("Pages of {}", SECTIONS + 1)])
        .collect();
    assert_eq!(
        text, expected,
        "the contents must show the pages that the layout after the first one found"
    );
    assert!(
        formatting > SECTIONS * 2,
        "the first formatting must compute the styles of every element and pseudo-element, \
         not {formatting}"
    );
    assert_eq!(
        relayout, 0,
        "only page numbers changed after the first layout, so formatting again must reuse the \
         {formatting} styles the first formatting computed rather than compute {relayout}"
    );
}