Skip to main content

fleuron/
style.rs

1//! The style tree: resolved styling.
2//!
3//! Styling enters as CSS. A built-in user-agent stylesheet supplies
4//! the defaults; author CSS cascades over it. What comes out is one
5//! computed style per content node and one page master per situation
6//! a page can be in, and that is the whole of what layout is told.
7//!
8//! ```text
9//! content tree + CSS ─► style tree ─► box tree ─► …
10//! ```
11//!
12//! Font faces reach the registry here too: `@font-face` names a
13//! source, the host loader hands back bytes, and every node's face is
14//! an id by the time layout sees it.
15
16mod element;
17mod inspect;
18mod properties;
19mod sheet;
20pub mod subset;
21mod substitution;
22
23use std::collections::BTreeMap;
24
25use cssparser::ToCss;
26use selectors::context::{
27    MatchingForInvalidation, MatchingMode, NeedsSelectorFlags, QuirksMode, SelectorCaches,
28};
29use selectors::matching::{MatchingContext, matches_selector};
30use serde::Serialize;
31
32use crate::Warning;
33use crate::content::{
34    Alignment, Attributes, Block, Book, Inline, NodeId, PseudoElement, block_attributes,
35    block_position, inline_attributes, inline_position, origin, rows,
36};
37use crate::fonts::{FaceAttributes, FontError, FontRegistry, FontSource};
38use crate::lines::{FirstLine, InlineBox, InlineStyles, ParagraphStyle};
39use crate::pages::Side;
40
41pub(crate) use inspect::element_of;
42pub use inspect::{Ancestor, InspectedDeclaration, Inspection, MatchedRule};
43pub use properties::{
44    Align, AlignContent, Background, BackgroundPosition, BackgroundRepeat, BackgroundSize, Band,
45    BlendMode, Border, BorderCollapse, BorderRadius, BorderStyle, BoxDecorationBreak, Break, Clear,
46    Color, ColumnRule, ColumnSpan, Columns, ComputedStyle, Content, ContentPiece, Coord, Corner,
47    CornerRadius, CounterStyle, DecorationLine, DecorationStyle, Edge, Edges, Family, Figures,
48    Float, FontStyle, FontVariantAlternates, FontVariantCaps, FontVariantLigatures,
49    FontVariantNumeric, Fractions, Hyphens, Inset, Length, LineHeight, ListStyleType, MarginBox,
50    Marks, NumericSpacing, PageGeometry, Position, ShapeOutside, ShapePoint, ShapeSource,
51    SizeSource, StringPiece, StringSet, Target, TextAlign, TextDecoration, TextJustify,
52    TextTransform, Url, Width, WrapFlow,
53};
54pub use sheet::{FontFace, Origin, SheetPosition, Source, Src, Written};
55
56use element::{BLOCK_ELEMENTS, ElementTree, INLINE_ELEMENTS};
57use properties::{Custom, Declaration};
58use sheet::{Importance, MarginDeclaration, PageDeclaration, PageRule, Sheet};
59
60/// The defaults, as a stylesheet. There are no style constants in the
61/// engine; this file is where the trade paperback lives.
62pub const USER_AGENT_CSS: &str = include_str!("style/ua.css");
63
64/// Resolves `@font-face` sources to font bytes.
65///
66/// The engine reads no paths of its own. Whatever string the sheet
67/// writes in `url()` is handed over as it is: it never has to be a
68/// real URL, and a host that resolves nothing is a host with no
69/// author fonts.
70pub trait FontLoader {
71    /// The bytes behind one `src` url, or `None` when the host cannot
72    /// resolve it.
73    fn load(&self, url: &str) -> Option<Vec<u8>>;
74}
75
76/// A loader that resolves nothing.
77pub struct NoFonts;
78
79impl FontLoader for NoFonts {
80    fn load(&self, _url: &str) -> Option<Vec<u8>> {
81        None
82    }
83}
84
85/// One node's place in the tree: what it is, and which style it got.
86#[derive(Debug, Clone, PartialEq, Serialize)]
87pub struct NodeStyle {
88    /// The content node this style belongs to.
89    pub id: u32,
90    /// The element name selectors matched against.
91    pub element: &'static str,
92    /// Index into the tree's distinct styles.
93    pub style: u32,
94    /// Index of the style `::first-letter` computed for this node,
95    /// when a rule named one.
96    #[serde(skip_serializing_if = "Option::is_none")]
97    pub first_letter: Option<u32>,
98    /// Index of the style `::first-line` computed for this node, when
99    /// a rule named one.
100    #[serde(skip_serializing_if = "Option::is_none")]
101    pub first_line: Option<u32>,
102    /// Index of the style `::before` computed for this node, when it
103    /// generates text.
104    #[serde(skip_serializing_if = "Option::is_none")]
105    pub before: Option<u32>,
106    /// Index of the style `::after` computed for this node, when it
107    /// generates text.
108    #[serde(skip_serializing_if = "Option::is_none")]
109    pub after: Option<u32>,
110}
111
112/// The situation a page finds itself in, which is what `@page`
113/// selects on beyond the page's name.
114#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
115#[serde(rename_all = "snake_case")]
116pub enum Situation {
117    /// The page a page group opens on: `@page :first`.
118    First(Side),
119    /// Any later page of the group.
120    Body(Side),
121    /// A page inserted to square the sheet: `@page :blank`.
122    Blank,
123}
124
125impl Situation {
126    /// The side of the spread this situation falls on. Blanks are
127    /// versos: a book never opens a leaf to a blank right-hand page.
128    pub fn side(self) -> Side {
129        match self {
130            Situation::First(side) | Situation::Body(side) => side,
131            Situation::Blank => Side::Verso,
132        }
133    }
134}
135
136/// Which page a `@page` lookup is about.
137#[derive(Debug, Clone, Copy, PartialEq, Eq)]
138pub struct PageQuery<'a> {
139    /// The named page in force, from the `page` property.
140    pub name: Option<&'a str>,
141    /// Which page of the group, and which side.
142    pub situation: Situation,
143}
144
145/// One resolved page master: the page box, and what its margin boxes
146/// paint.
147#[derive(Debug, Clone, PartialEq, Serialize)]
148pub struct PageStyle {
149    /// Trim size and margins.
150    pub geometry: PageGeometry,
151    /// What is painted behind the whole page box, margins included.
152    #[serde(skip_serializing_if = "properties::no_background")]
153    pub background: Background,
154    /// The margin boxes the page's rules mentioned, in CSS order.
155    pub boxes: Vec<MarginBoxStyle>,
156}
157
158impl PageStyle {
159    /// The margin box `which`, when it paints anything.
160    pub fn margin_box(&self, which: MarginBox) -> Option<&MarginBoxStyle> {
161        self.boxes
162            .iter()
163            .find(|box_| box_.which == which && box_.content != Content::None)
164    }
165}
166
167/// One page margin box: what it paints and the style it paints with.
168#[derive(Debug, Clone, PartialEq, Serialize)]
169pub struct MarginBoxStyle {
170    /// Which of the sixteen boxes.
171    pub which: MarginBox,
172    /// What it paints.
173    pub content: Content,
174    /// The box's own text style, inherited from the book's root the
175    /// way a block's would be.
176    pub style: ComputedStyle,
177}
178
179/// One page master, named and situated.
180#[derive(Debug, Clone, PartialEq, Serialize)]
181pub struct PageMaster {
182    /// The named page, or `None` for the unnamed default.
183    pub page: Option<String>,
184    /// The situation this master answers.
185    pub situation: Situation,
186    /// The page box and its margin boxes.
187    pub style: PageStyle,
188}
189
190/// The compiled styling of one book.
191#[derive(Debug, Clone, Serialize)]
192pub struct StyleTree {
193    /// The distinct computed styles this book uses. Nodes index into
194    /// it: a book has thousands of nodes and a handful of styles.
195    styles: Vec<ComputedStyle>,
196    /// Every element, in document order.
197    nodes: Vec<NodeStyle>,
198    /// Every master a page of this book can take.
199    masters: Vec<PageMaster>,
200    /// Style index by raw node id. Index 0 is the root, which is also
201    /// what an unassigned node resolves to.
202    #[serde(skip)]
203    by_node: Vec<u32>,
204    /// `::first-letter` style index by raw node id, where there is one.
205    #[serde(skip)]
206    initial_by_node: Vec<Option<u32>>,
207    /// `::first-line` style index by raw node id, where there is one.
208    #[serde(skip)]
209    first_line_by_node: Vec<Option<u32>>,
210    /// `::before` style index by raw node id, where it generates text.
211    #[serde(skip)]
212    before_by_node: Vec<Option<u32>>,
213    /// `::after` style index by raw node id, where it generates text.
214    #[serde(skip)]
215    after_by_node: Vec<Option<u32>>,
216    /// Whether generated text prints the page an element lands on.
217    #[serde(skip)]
218    counts_pages: bool,
219    /// Whether generated text names another element at all.
220    #[serde(skip)]
221    refers: bool,
222    /// The footnote area, which no content node stands behind.
223    #[serde(skip)]
224    notes: NodeId,
225    warnings: Vec<Warning>,
226}
227
228impl StyleTree {
229    /// The computed style of one content node, or of one
230    /// pseudo-element. An id the tree does not know — an unassigned
231    /// one, or a node from another book — gets the root style, which
232    /// is the book's own defaults.
233    pub fn style(&self, id: NodeId) -> &ComputedStyle {
234        if let Some((element, which)) = id.pseudo_element() {
235            return self
236                .pseudo_style(element, which)
237                .unwrap_or_else(|| self.style(NodeId::UNASSIGNED));
238        }
239        let index = self
240            .by_node
241            .get(id.get() as usize)
242            .copied()
243            .unwrap_or_default();
244        &self.styles[index as usize]
245    }
246
247    /// The node the footnote area is styled by: the `notes` element,
248    /// which stands for the foot of every page.
249    pub fn notes_area(&self) -> NodeId {
250        self.notes
251    }
252
253    /// Everything line layout needs about one node.
254    pub fn paragraph(&self, id: NodeId) -> ParagraphStyle {
255        self.style(id).paragraph()
256    }
257
258    /// The style `::first-letter` computed for one node, when a rule
259    /// named one. This is where a drop cap's size and face come from.
260    pub fn first_letter(&self, id: NodeId) -> Option<&ComputedStyle> {
261        let index = (*self.initial_by_node.get(id.get() as usize)?)?;
262        Some(&self.styles[index as usize])
263    }
264
265    /// The style `::first-line` computed for one node, when a rule
266    /// named one. Line layout reads it as what the opening line
267    /// changes about the paragraph around it.
268    pub fn first_line(&self, id: NodeId) -> Option<&ComputedStyle> {
269        let index = (*self.first_line_by_node.get(id.get() as usize)?)?;
270        Some(&self.styles[index as usize])
271    }
272
273    /// What `::first-line` changes about one node's own style, which
274    /// is what line layout applies to the opening line.
275    pub fn opening_line(&self, id: NodeId) -> Option<FirstLine> {
276        Some(self.first_line(id)?.first_line_over(self.style(id)))
277    }
278
279    /// The style `::before` computed for one node, when its `content`
280    /// generates anything. On an inline that is text inside the line.
281    /// On a block it is a box, the first child of the block.
282    pub fn before(&self, id: NodeId) -> Option<&ComputedStyle> {
283        let index = (*self.before_by_node.get(id.get() as usize)?)?;
284        Some(&self.styles[index as usize])
285    }
286
287    /// The same for `::after`.
288    pub fn after(&self, id: NodeId) -> Option<&ComputedStyle> {
289        let index = (*self.after_by_node.get(id.get() as usize)?)?;
290        Some(&self.styles[index as usize])
291    }
292
293    /// The id of one pseudo-element of `element`, where a rule styles
294    /// it. On a block, `::before` and `::after` are boxes. On an
295    /// inline element, they are text inside the line. The id comes
296    /// from the element and the pseudo-element alone, so it is the
297    /// same in every layout of the same book and sheets, and no
298    /// content node has it. `style` answers for it.
299    pub fn pseudo_element(&self, element: NodeId, which: PseudoElement) -> Option<NodeId> {
300        self.pseudo_style(element, which)
301            .map(|_| element.pseudo(which))
302    }
303
304    fn pseudo_style(&self, element: NodeId, which: PseudoElement) -> Option<&ComputedStyle> {
305        match which {
306            PseudoElement::Before => self.before(element),
307            PseudoElement::After => self.after(element),
308            PseudoElement::FirstLetter => self.first_letter(element),
309            PseudoElement::FirstLine => self.first_line(element),
310        }
311    }
312
313    /// Whether any generated text prints the page another element
314    /// lands on. Such a book is laid out twice: once to find the
315    /// pages, and once to print them.
316    pub fn counts_pages(&self) -> bool {
317        self.counts_pages
318    }
319
320    /// Whether any generated text names another element, for its
321    /// page or for its text.
322    pub fn refers(&self) -> bool {
323        self.refers
324    }
325
326    /// The style of the book itself: the root of inheritance.
327    pub fn root(&self) -> &ComputedStyle {
328        &self.styles[0]
329    }
330
331    /// The distinct computed styles, in the order nodes index them.
332    pub fn styles(&self) -> &[ComputedStyle] {
333        &self.styles
334    }
335
336    /// Every element, in document order.
337    pub fn nodes(&self) -> &[NodeStyle] {
338        &self.nodes
339    }
340
341    /// What compilation had to complain about.
342    pub fn warnings(&self) -> &[Warning] {
343        &self.warnings
344    }
345
346    /// The page master one page resolves to. A named page with no
347    /// master of its own falls back to the unnamed one.
348    pub fn page(&self, query: PageQuery<'_>) -> &PageStyle {
349        self.master(query.name, query.situation)
350            .or_else(|| self.master(None, query.situation))
351            .expect("every situation has an unnamed master")
352    }
353
354    /// The default page: an unnamed body recto. The measure every
355    /// paragraph breaks to comes from here.
356    pub fn default_page(&self) -> &PageStyle {
357        self.page(PageQuery {
358            name: None,
359            situation: Situation::Body(Side::Recto),
360        })
361    }
362
363    /// Every master this book can put on a page: one per named page
364    /// and situation, in a stable order.
365    pub fn masters(&self) -> &[PageMaster] {
366        &self.masters
367    }
368
369    fn master(&self, name: Option<&str>, situation: Situation) -> Option<&PageStyle> {
370        self.masters
371            .iter()
372            .find(|master| master.page.as_deref() == name && master.situation == situation)
373            .map(|master| &master.style)
374    }
375}
376
377/// Resolves every master the book can use: the unnamed default, plus
378/// each named page, in each situation a page can be in.
379fn resolve_masters(
380    pages: &[(u8, PageRule)],
381    styles: &[ComputedStyle],
382    root: &ComputedStyle,
383    registry: &FontRegistry,
384    warnings: &mut Vec<Warning>,
385) -> Vec<PageMaster> {
386    let mut names: Vec<Option<String>> = vec![None];
387    for style in styles {
388        if let Some(name) = &style.page
389            && !names.iter().any(|known| known.as_deref() == Some(name))
390        {
391            names.push(Some(name.clone()));
392        }
393    }
394    let situations = [
395        Situation::First(Side::Recto),
396        Situation::First(Side::Verso),
397        Situation::Body(Side::Recto),
398        Situation::Body(Side::Verso),
399        Situation::Blank,
400    ];
401    let mut masters = Vec::new();
402    for name in names {
403        for situation in situations {
404            masters.push(PageMaster {
405                page: name.clone(),
406                situation,
407                style: resolve_page(
408                    pages,
409                    PageQuery {
410                        name: name.as_deref(),
411                        situation,
412                    },
413                    root,
414                    registry,
415                    warnings,
416                ),
417            });
418        }
419    }
420    masters
421}
422
423/// One page master: every `@page` rule that selects it, applied in
424/// specificity then source order.
425fn resolve_page(
426    pages: &[(u8, PageRule)],
427    query: PageQuery<'_>,
428    root: &ComputedStyle,
429    registry: &FontRegistry,
430    warnings: &mut Vec<Warning>,
431) -> PageStyle {
432    let mut matching: Vec<&(u8, PageRule)> = pages
433        .iter()
434        .filter(|(_, rule)| selects(rule, query))
435        .collect();
436    // `@page` cascades like any other rule: origin first, then
437    // specificity. The rules are already in source order, and a stable
438    // sort leaves the later of two equal rules on top.
439    matching.sort_by_key(|(level, rule)| (*level, rule.specificity()));
440
441    let root_size = root.font_size;
442    // `column-gap: normal` is one em of the book's own size, and the
443    // page box is not text, so the em it means is the root's.
444    let mut geometry = PageGeometry {
445        width: 612.0,
446        height: 792.0,
447        margin: Edges::all(0.0),
448        columns: Columns::undivided(root_size),
449        align_content: AlignContent::Start,
450        bleed: None,
451        marks: Marks::NONE,
452    };
453    let initial = geometry;
454    let mut background = Background::NONE;
455    let mut boxes: BTreeMap<MarginBox, MarginBoxStyle> = BTreeMap::new();
456    for (_, rule) in matching {
457        for declaration in &rule.declarations {
458            let PageDeclaration::Pending(pending) = declaration else {
459                apply_page(&mut geometry, &mut background, declaration, root_size);
460                continue;
461            };
462            let read = sheet::read_pending_page;
463            match substitution::substituted(pending, &root.custom, read, warnings) {
464                Some(declarations) => {
465                    for declaration in &declarations {
466                        apply_page(&mut geometry, &mut background, declaration, root_size);
467                    }
468                }
469                None => {
470                    for like in sheet::page_longhands(&pending.property) {
471                        reset_page(&mut geometry, &mut background, &like, &initial);
472                    }
473                }
474            }
475        }
476        for margin in &rule.boxes {
477            let entry = boxes.entry(margin.which).or_insert_with(|| MarginBoxStyle {
478                which: margin.which,
479                content: Content::None,
480                style: root.inherit(),
481            });
482            for declaration in &margin.declarations {
483                let MarginDeclaration::Pending(pending) = declaration else {
484                    apply_margin(entry, declaration, root_size);
485                    continue;
486                };
487                let read = sheet::read_pending_margin;
488                match substitution::substituted(pending, &root.custom, read, warnings) {
489                    Some(declarations) => {
490                        for declaration in &declarations {
491                            apply_margin(entry, declaration, root_size);
492                        }
493                    }
494                    None => {
495                        let base = root.inherit();
496                        for like in sheet::margin_longhands(&pending.property) {
497                            match like {
498                                MarginDeclaration::Style(like) => entry.style.reset(&like, &base),
499                                _ => entry.content = Content::None,
500                            }
501                        }
502                    }
503                }
504            }
505            let (font_id, warning) = resolve_face(&entry.style, registry);
506            entry.style.font_id = font_id;
507            report(warnings, warning);
508        }
509    }
510    PageStyle {
511        geometry,
512        background,
513        boxes: boxes.into_values().collect(),
514    }
515}
516
517/// Applies one declaration of a `@page` body.
518fn apply_page(
519    geometry: &mut PageGeometry,
520    background: &mut Background,
521    declaration: &PageDeclaration,
522    root_size: f32,
523) {
524    match declaration {
525        PageDeclaration::Size(width, height) => {
526            geometry.width = *width;
527            geometry.height = *height;
528        }
529        PageDeclaration::Margin(edge, length) => {
530            *geometry.margin.edge(*edge) = length.to_points(root_size, root_size)
531        }
532        PageDeclaration::BackgroundColor(color) => background.color = *color,
533        PageDeclaration::BackgroundImage(url) => background.image = url.clone(),
534        PageDeclaration::BackgroundRepeat(repeat) => background.repeat = *repeat,
535        PageDeclaration::BackgroundSize(size) => {
536            background.size = properties::computed_size(*size, root_size, root_size)
537        }
538        PageDeclaration::BackgroundPosition(x, y) => {
539            background.position = BackgroundPosition {
540                x: Coord::of(*x, root_size, root_size),
541                y: Coord::of(*y, root_size, root_size),
542            }
543        }
544        PageDeclaration::ColumnCount(count) => geometry.columns.count = *count,
545        PageDeclaration::ColumnWidth(width) => {
546            geometry.columns.width = width.map(|width| width.to_points(root_size, root_size))
547        }
548        PageDeclaration::ColumnGap(gap) => {
549            geometry.columns.gap = gap
550                .map(|gap| gap.to_points(root_size, root_size))
551                .unwrap_or(root_size)
552                .max(0.0)
553        }
554        PageDeclaration::ColumnRuleWidth(width) => {
555            geometry.columns.rule.width = width.to_points(root_size, root_size)
556        }
557        PageDeclaration::ColumnRuleStyle(style) => geometry.columns.rule.style = *style,
558        PageDeclaration::AlignContent(align) => geometry.align_content = *align,
559        PageDeclaration::Bleed(bleed) => {
560            geometry.bleed = bleed.map(|bleed| bleed.to_points(root_size, root_size))
561        }
562        PageDeclaration::Marks(marks) => geometry.marks = *marks,
563        PageDeclaration::Pending(_) => {}
564    }
565}
566
567/// Sets what `like` declares on a page back to its initial value.
568fn reset_page(
569    geometry: &mut PageGeometry,
570    background: &mut Background,
571    like: &PageDeclaration,
572    initial: &PageGeometry,
573) {
574    match like {
575        PageDeclaration::Size(..) => {
576            geometry.width = initial.width;
577            geometry.height = initial.height;
578        }
579        PageDeclaration::Margin(edge, _) => {
580            *geometry.margin.edge(*edge) = initial.margin.get(*edge)
581        }
582        PageDeclaration::BackgroundColor(_) => background.color = Background::NONE.color,
583        PageDeclaration::BackgroundImage(_) => background.image = None,
584        PageDeclaration::BackgroundRepeat(_) => background.repeat = Background::NONE.repeat,
585        PageDeclaration::BackgroundSize(_) => background.size = Background::NONE.size,
586        PageDeclaration::BackgroundPosition(..) => background.position = Background::NONE.position,
587        PageDeclaration::ColumnCount(_) => geometry.columns.count = initial.columns.count,
588        PageDeclaration::ColumnWidth(_) => geometry.columns.width = initial.columns.width,
589        PageDeclaration::ColumnGap(_) => geometry.columns.gap = initial.columns.gap,
590        PageDeclaration::ColumnRuleWidth(_) => {
591            geometry.columns.rule.width = initial.columns.rule.width
592        }
593        PageDeclaration::ColumnRuleStyle(_) => {
594            geometry.columns.rule.style = initial.columns.rule.style
595        }
596        PageDeclaration::AlignContent(_) => geometry.align_content = initial.align_content,
597        PageDeclaration::Bleed(_) => geometry.bleed = initial.bleed,
598        PageDeclaration::Marks(_) => geometry.marks = initial.marks,
599        PageDeclaration::Pending(_) => {}
600    }
601}
602
603/// Applies one declaration of a page margin box.
604fn apply_margin(entry: &mut MarginBoxStyle, declaration: &MarginDeclaration, root_size: f32) {
605    match declaration {
606        MarginDeclaration::Content(content) => entry.content = content.clone(),
607        MarginDeclaration::Style(style) => entry.style.apply(style, root_size, root_size),
608        MarginDeclaration::Pending(_) => {}
609    }
610}
611
612impl InlineStyles for StyleTree {
613    fn style(&self, id: NodeId, block: &ParagraphStyle) -> ParagraphStyle {
614        match self.by_node.get(id.get() as usize) {
615            Some(index) => self.styles[*index as usize].paragraph(),
616            None => block.clone(),
617        }
618    }
619
620    fn inline_box(&self, id: NodeId) -> Option<InlineBox> {
621        let index = self.by_node.get(id.get() as usize)?;
622        self.styles[*index as usize].inline_box()
623    }
624}
625
626/// Whether one `@page` rule selects the page a query describes.
627fn selects(rule: &PageRule, query: PageQuery<'_>) -> bool {
628    if rule.name.is_some() && rule.name.as_deref() != query.name {
629        return false;
630    }
631    if rule.first && !matches!(query.situation, Situation::First(_)) {
632        return false;
633    }
634    if rule.blank && query.situation != Situation::Blank {
635        return false;
636    }
637    match rule.side {
638        Some(side) => side == query.situation.side(),
639        None => true,
640    }
641}
642
643/// Parsed stylesheets: the built-in sheet, then whatever the host
644/// added, ready to compile against a book.
645///
646/// Parsing is separate from compiling because a run styles several
647/// books from one set of sheets, and separate from font loading
648/// because loading is the one step that reaches outside the engine.
649#[derive(Debug)]
650pub struct Stylesheets {
651    sheets: Vec<Sheet>,
652    /// What parsing said, then what font loading said.
653    warnings: Vec<Warning>,
654    /// How many of `warnings` parsing raised.
655    parsed: usize,
656}
657
658impl Stylesheets {
659    /// Parses the built-in sheet, then `sources` in the order given.
660    pub fn parse(sources: &[Source<'_>]) -> Stylesheets {
661        let built_in = Source::user_agent("user-agent.css", USER_AGENT_CSS);
662        let mut sheets = Vec::new();
663        let mut warnings = Vec::new();
664        for source in std::iter::once(&built_in).chain(sources) {
665            let (sheet, mut sheet_warnings) = sheet::parse(source);
666            warnings.append(&mut sheet_warnings);
667            sheets.push(sheet);
668        }
669        let parsed = warnings.len();
670        Stylesheets {
671            sheets,
672            warnings,
673            parsed,
674        }
675    }
676
677    /// Registers every `@font-face` the loader resolves, under the
678    /// family the sheet gave it rather than the one inside the file:
679    /// a stylesheet's name for a face is the one its selectors use.
680    ///
681    /// Run this before compiling — a face the registry does not have
682    /// is a face no computed style can resolve to. Running it again
683    /// replaces what the last run warned about.
684    pub fn load_fonts(&mut self, registry: &mut FontRegistry, loader: &dyn FontLoader) {
685        let warnings = self
686            .sheets
687            .iter()
688            .flat_map(|sheet| &sheet.faces)
689            .flat_map(|face| register_face(face, registry, loader))
690            .collect();
691        self.set_font_warnings(warnings);
692    }
693
694    /// What the last font loading warned about.
695    pub(crate) fn font_warnings(&self) -> &[Warning] {
696        &self.warnings[self.parsed..]
697    }
698
699    /// Replaces what font loading warned about, for sheets whose faces
700    /// a session already registered from an earlier copy of them.
701    pub(crate) fn set_font_warnings(&mut self, warnings: Vec<Warning>) {
702        self.warnings.truncate(self.parsed);
703        self.warnings.extend(warnings);
704    }
705
706    /// Hashes every `@font-face` the sheets declare, and what `file`
707    /// says about the bytes behind each url: two sheets that hash the
708    /// same register the same faces.
709    pub(crate) fn hash_faces(
710        &self,
711        h: &mut impl std::hash::Hasher,
712        file: impl Fn(&str) -> Option<u64>,
713    ) {
714        use std::hash::Hash;
715        for face in self.sheets.iter().flat_map(|sheet| &sheet.faces) {
716            face.family.hash(h);
717            face.style.hash(h);
718            face.weight.hash(h);
719            for src in &face.src {
720                match src {
721                    Src::Url(url) => (url, file(url)).hash(h),
722                    Src::Local(name) => name.hash(h),
723                }
724            }
725        }
726    }
727
728    /// What parsing and font loading had to complain about.
729    pub fn warnings(&self) -> &[Warning] {
730        &self.warnings
731    }
732
733    /// Every sheet as it was written, the built-in sheet first: what
734    /// a writer reads that hands the CSS to a renderer of its own
735    /// rather than laying it out.
736    ///
737    /// Only what the parser accepted is here. A rule or a declaration
738    /// outside the subset is in [`Stylesheets::warnings`] instead.
739    pub fn written(&self) -> Vec<WrittenSheet> {
740        self.sheets
741            .iter()
742            .map(|sheet| WrittenSheet {
743                origin: sheet.origin,
744                rules: sheet
745                    .rules
746                    .iter()
747                    .map(|rule| WrittenRule {
748                        selectors: rule
749                            .selectors
750                            .slice()
751                            .iter()
752                            .map(|selector| selector.to_css_string())
753                            .collect(),
754                        declarations: rule.written.clone(),
755                        position: rule.position.clone(),
756                    })
757                    .collect(),
758                pages: sheet
759                    .pages
760                    .iter()
761                    .map(|page| WrittenPage {
762                        selector: page.selector.clone(),
763                        position: page.position.clone(),
764                    })
765                    .collect(),
766                faces: sheet.faces.clone(),
767            })
768            .collect()
769    }
770
771    /// Compiles one book's styling against the faces in the registry.
772    pub fn compile(&self, book: &Book, registry: &FontRegistry) -> StyleTree {
773        cascade(book, &self.sheets, registry, self.warnings.clone())
774    }
775}
776
777/// One sheet as it was written. See [`Stylesheets::written`].
778#[derive(Debug, Clone, PartialEq)]
779pub struct WrittenSheet {
780    /// Which origin the sheet cascades at.
781    pub origin: Origin,
782    /// The style rules, in the order they were written.
783    pub rules: Vec<WrittenRule>,
784    /// The `@page` rules, in the order they were written.
785    pub pages: Vec<WrittenPage>,
786    /// The `@font-face` rules, in the order they were written.
787    pub faces: Vec<FontFace>,
788}
789
790/// One style rule as it was written.
791#[derive(Debug, Clone, PartialEq)]
792pub struct WrittenRule {
793    /// Each selector of the list, as CSS.
794    pub selectors: Vec<String>,
795    /// The declarations the parser accepted, in the order they were
796    /// written.
797    pub declarations: Vec<Written>,
798    /// Where the rule begins.
799    pub position: SheetPosition,
800}
801
802/// One `@page` rule as it was written.
803#[derive(Debug, Clone, PartialEq)]
804pub struct WrittenPage {
805    /// The prelude, `@page` included.
806    pub selector: String,
807    /// Where the rule begins.
808    pub position: SheetPosition,
809}
810
811/// One book's styling under the built-in sheet alone.
812pub fn defaults(book: &Book, registry: &FontRegistry) -> StyleTree {
813    Stylesheets::parse(&[]).compile(book, registry)
814}
815
816/// Registers one `@font-face`, or says why it could not be.
817fn register_face(
818    face: &FontFace,
819    registry: &mut FontRegistry,
820    loader: &dyn FontLoader,
821) -> Vec<Warning> {
822    let mut warnings = Vec::new();
823    for src in &face.src {
824        let Src::Url(url) = src else {
825            continue;
826        };
827        let Some(bytes) = loader.load(url) else {
828            continue;
829        };
830        match FontSource::from_bytes(bytes) {
831            Ok(mut source) => {
832                source.family = face.family.to_lowercase();
833                source.declared = declared(face);
834                return match registry.add(source) {
835                    Ok(_) => warnings,
836                    Err(error) => {
837                        warnings.push(Warning {
838                            message: face_failure(&face.family, &error),
839                            origin: Some(url.clone()),
840                        });
841                        warnings
842                    }
843                };
844            }
845            Err(error) => warnings.push(Warning {
846                message: face_failure(&face.family, &error),
847                origin: Some(url.clone()),
848            }),
849        }
850    }
851    warnings.push(Warning {
852        message: format!("No src url loaded for {}. {FALLBACK}", face.family),
853        origin: None,
854    });
855    warnings
856}
857
858/// What happens to text that asked for a face the registry has not
859/// got.
860const FALLBACK: &str = "Falling back to another registered font.";
861
862/// Why one `@font-face` file did not register. The two causes read
863/// apart, because the fix for each one is different.
864fn face_failure(family: &str, error: &FontError) -> String {
865    match error {
866        FontError::MissingName => {
867            format!("{family} has no family name and was not registered. {FALLBACK}")
868        }
869        FontError::Parse => format!("{family} could not be read as a font. {FALLBACK}"),
870    }
871}
872
873/// What a `@font-face` declared its source to be. A sheet that
874/// declares neither slope nor weight is naming a family, not a cut,
875/// and the file names the cuts.
876fn declared(face: &FontFace) -> Option<FaceAttributes> {
877    let (style, weight) = (face.style, face.weight);
878    (style.is_some() || weight.is_some()).then(|| FaceAttributes {
879        italic: style == Some(FontStyle::Italic),
880        weight: weight.unwrap_or(FaceAttributes::REGULAR.weight),
881    })
882}
883
884/// Matching and the cascade: every element gets the declarations that
885/// match it, in cascade order, applied over what it inherited.
886fn cascade(
887    book: &Book,
888    sheets: &[Sheet],
889    registry: &FontRegistry,
890    mut warnings: Vec<Warning>,
891) -> StyleTree {
892    let elements = ElementTree::build(book);
893    warnings.extend(repeated_ids(book));
894    let mut caches = SelectorCaches::default();
895
896    let mut styles: Vec<ComputedStyle> = Vec::new();
897    let mut nodes = Vec::new();
898    let mut computed: Vec<u32> = Vec::with_capacity(elements.nodes().len());
899    let mut first_letters: Vec<Option<u32>> = Vec::with_capacity(elements.nodes().len());
900    let mut first_lines: Vec<Option<u32>> = Vec::with_capacity(elements.nodes().len());
901    let mut befores: Vec<Option<u32>> = Vec::with_capacity(elements.nodes().len());
902    let mut afters: Vec<Option<u32>> = Vec::with_capacity(elements.nodes().len());
903    let mut max_id = 0u32;
904    // Most sheets name neither, and a pass that no rule can match is
905    // a pass over every rule for every element.
906    let named = |which: &PseudoElement| {
907        sheets.iter().any(|sheet| {
908            sheet.rules.iter().any(|rule| {
909                rule.selectors
910                    .slice()
911                    .iter()
912                    .any(|selector| selector.pseudo_element() == Some(which))
913            })
914        })
915    };
916    let (wants_before, wants_after) = (named(&PseudoElement::Before), named(&PseudoElement::After));
917
918    for (index, node) in elements.nodes().iter().enumerate() {
919        let parent = node
920            .parent
921            .map(|parent| styles[computed[parent] as usize].clone())
922            .unwrap_or_else(ComputedStyle::initial);
923        let mut style = parent.inherit();
924
925        let matched = applicable(sheets, &elements, index, &mut caches, None);
926        let root_size = styles.first().map(|style| style.font_size);
927        let parent_size = parent.font_size;
928        let hint = node.align.map(align_hint);
929        apply_all(
930            &mut style,
931            sheets,
932            &matched,
933            hint.as_ref(),
934            parent_size,
935            root_size,
936            &mut warnings,
937        );
938        let (font_id, warning) = resolve_face(&style, registry);
939        style.font_id = font_id;
940        report(&mut warnings, warning);
941        report(&mut warnings, synthesized_small_caps(&style, registry));
942        report_all(&mut warnings, missing_features(&style, registry));
943
944        // A pseudo-element cascades over the style of the element it
945        // belongs to, so each is a second matching pass rather than a
946        // second element.
947        let mut pseudo_style = |which, warnings: &mut Vec<Warning>| {
948            let matched = applicable(sheets, &elements, index, &mut caches, Some(which));
949            (!matched.is_empty()).then(|| {
950                let mut pseudo = style.inherit();
951                apply_all(
952                    &mut pseudo,
953                    sheets,
954                    &matched,
955                    None,
956                    style.font_size,
957                    root_size,
958                    warnings,
959                );
960                let (font_id, warning) = resolve_face(&pseudo, registry);
961                pseudo.font_id = font_id;
962                report(warnings, warning);
963                report(warnings, synthesized_small_caps(&pseudo, registry));
964                report_all(warnings, missing_features(&pseudo, registry));
965                pseudo
966            })
967        };
968        let first_letter = pseudo_style(&PseudoElement::FirstLetter, &mut warnings);
969        let first_line = pseudo_style(&PseudoElement::FirstLine, &mut warnings);
970        let before = wants_before
971            .then(|| pseudo_style(&PseudoElement::Before, &mut warnings))
972            .flatten();
973        let after = wants_after
974            .then(|| pseudo_style(&PseudoElement::After, &mut warnings))
975            .flatten();
976        // `content: none`, the initial value, generates nothing.
977        let [before, after] = [(before, "::before"), (after, "::after")].map(|(pseudo, name)| {
978            let pseudo = pseudo.filter(|pseudo| pseudo.content != Content::None)?;
979            if INLINE_ELEMENTS.contains(&node.name) || BLOCK_ELEMENTS.contains(&node.name) {
980                return Some(pseudo);
981            }
982            let message = format!(
983                "Unsupported pseudo-element `{name}` on `{}`. Nothing is generated.",
984                node.name
985            );
986            if !warnings.iter().any(|seen| seen.message == message) {
987                warnings.push(Warning {
988                    message,
989                    origin: None,
990                });
991            }
992            None
993        });
994
995        let index_of_style = intern(&mut styles, style);
996        let index_of_initial = first_letter.map(|initial| intern(&mut styles, initial));
997        let index_of_line = first_line.map(|line| intern(&mut styles, line));
998        let index_of_before = before.map(|before| intern(&mut styles, before));
999        let index_of_after = after.map(|after| intern(&mut styles, after));
1000        computed.push(index_of_style);
1001        first_letters.push(index_of_initial);
1002        first_lines.push(index_of_line);
1003        befores.push(index_of_before);
1004        afters.push(index_of_after);
1005        nodes.push(NodeStyle {
1006            id: node.id.get(),
1007            element: node.name,
1008            style: index_of_style,
1009            first_letter: index_of_initial,
1010            first_line: index_of_line,
1011            before: index_of_before,
1012            after: index_of_after,
1013        });
1014        max_id = max_id.max(node.id.get());
1015    }
1016
1017    // A paragraph with no element of its own takes the style of an
1018    // anonymous box inside its item: what the item passes on, and
1019    // nothing of its own.
1020    let mut anonymous = Vec::with_capacity(elements.anonymous().len());
1021    for (id, item) in elements.anonymous() {
1022        let inherited = styles[computed[*item] as usize].inherit();
1023        anonymous.push((id.get() as usize, intern(&mut styles, inherited)));
1024        max_id = max_id.max(id.get());
1025    }
1026
1027    let root = computed.first().copied().unwrap_or(0);
1028    let mut by_node = vec![root; max_id as usize + 1];
1029    let mut initial_by_node = vec![None; max_id as usize + 1];
1030    let mut first_line_by_node = vec![None; max_id as usize + 1];
1031    let mut before_by_node = vec![None; max_id as usize + 1];
1032    let mut after_by_node = vec![None; max_id as usize + 1];
1033    for (index, node) in elements.nodes().iter().enumerate() {
1034        let id = node.id.get() as usize;
1035        by_node[id] = computed[index];
1036        initial_by_node[id] = first_letters[index];
1037        first_line_by_node[id] = first_lines[index];
1038        before_by_node[id] = befores[index];
1039        after_by_node[id] = afters[index];
1040    }
1041    for (id, style) in anonymous {
1042        by_node[id] = style;
1043    }
1044    by_node[0] = root;
1045    let generated = || {
1046        befores
1047            .iter()
1048            .chain(&afters)
1049            .flatten()
1050            .map(|index| &styles[*index as usize].content)
1051    };
1052    let counts_pages = generated().any(Content::counts_pages);
1053    let refers = generated().any(|content| matches!(content, Content::Pieces(_)));
1054
1055    if styles.is_empty() {
1056        styles.push(ComputedStyle::initial());
1057    }
1058    let pages: Vec<(u8, PageRule)> = sheets
1059        .iter()
1060        .flat_map(|sheet| {
1061            let level = level(sheet.origin, Importance::Normal);
1062            sheet.pages.iter().cloned().map(move |rule| (level, rule))
1063        })
1064        .collect();
1065    let masters = resolve_masters(
1066        &pages,
1067        &styles,
1068        &styles[root as usize].clone(),
1069        registry,
1070        &mut warnings,
1071    );
1072
1073    StyleTree {
1074        styles,
1075        nodes,
1076        masters,
1077        by_node,
1078        initial_by_node,
1079        first_line_by_node,
1080        before_by_node,
1081        after_by_node,
1082        counts_pages,
1083        refers,
1084        notes: elements.notes(),
1085        warnings,
1086    }
1087}
1088
1089/// Reports every id a book gives to a second element.
1090///
1091/// An id names one element. Both still match.
1092fn repeated_ids(book: &Book) -> Vec<Warning> {
1093    let mut first: BTreeMap<&str, String> = BTreeMap::new();
1094    let mut warnings = Vec::new();
1095    for section in &book.sections {
1096        let source = section.source.as_deref();
1097        named_blocks(&section.blocks, source, &mut first, &mut warnings);
1098    }
1099    warnings
1100}
1101
1102/// The ids of these blocks and everything inside them, in document
1103/// order, warning on each id already taken.
1104fn named_blocks<'a>(
1105    blocks: &'a [Block],
1106    source: Option<&str>,
1107    first: &mut BTreeMap<&'a str, String>,
1108    warnings: &mut Vec<Warning>,
1109) {
1110    for block in blocks {
1111        claim(
1112            block_attributes(block),
1113            origin(source, block_position(block)),
1114            first,
1115            warnings,
1116        );
1117        match block {
1118            Block::Heading { inlines, .. } | Block::Paragraph { inlines, .. } => {
1119                named_inlines(inlines, source, first, warnings)
1120            }
1121            Block::Blockquote { blocks, .. } => named_blocks(blocks, source, first, warnings),
1122            Block::List { items, .. } => {
1123                for item in items {
1124                    claim(
1125                        &item.attributes,
1126                        origin(source, item.position),
1127                        first,
1128                        warnings,
1129                    );
1130                    named_blocks(&item.blocks, source, first, warnings);
1131                }
1132            }
1133            Block::Table { head, body, .. } => {
1134                for row in rows(head, body) {
1135                    claim(
1136                        &row.attributes,
1137                        origin(source, row.position),
1138                        first,
1139                        warnings,
1140                    );
1141                    for cell in &row.cells {
1142                        claim(
1143                            &cell.attributes,
1144                            origin(source, cell.position),
1145                            first,
1146                            warnings,
1147                        );
1148                        named_blocks(&cell.blocks, source, first, warnings);
1149                    }
1150                }
1151            }
1152            Block::CodeBlock { .. }
1153            | Block::ThematicBreak { .. }
1154            | Block::PageBreak { .. }
1155            | Block::ColumnBreak { .. }
1156            | Block::Image { .. } => {}
1157        }
1158    }
1159}
1160
1161/// The same, over the inlines of one block.
1162fn named_inlines<'a>(
1163    inlines: &'a [Inline],
1164    source: Option<&str>,
1165    first: &mut BTreeMap<&'a str, String>,
1166    warnings: &mut Vec<Warning>,
1167) {
1168    for inline in inlines {
1169        claim(
1170            inline_attributes(inline),
1171            origin(source, inline_position(inline)),
1172            first,
1173            warnings,
1174        );
1175        match inline {
1176            Inline::Text { .. } | Inline::Code { .. } | Inline::Break { .. } => {}
1177            Inline::Note { blocks, .. } => named_blocks(blocks, source, first, warnings),
1178            Inline::Emphasis { children, .. }
1179            | Inline::Strong { children, .. }
1180            | Inline::Link { children, .. }
1181            | Inline::Strikethrough { children, .. }
1182            | Inline::Highlight { children, .. }
1183            | Inline::Span { children, .. } => named_inlines(children, source, first, warnings),
1184        }
1185    }
1186}
1187
1188/// Takes one node's id, or reports the element that has it already.
1189fn claim<'a>(
1190    attributes: &'a Attributes,
1191    at: String,
1192    first: &mut BTreeMap<&'a str, String>,
1193    warnings: &mut Vec<Warning>,
1194) {
1195    let Some(id) = attributes.id.as_deref() else {
1196        return;
1197    };
1198    match first.get(id) {
1199        Some(taken) => warnings.push(Warning {
1200            message: format!("Id `{id}` is duplicated. Applied at {taken}."),
1201            origin: Some(at),
1202        }),
1203        None => {
1204            first.insert(id, at);
1205        }
1206    }
1207}
1208
1209/// Where one applicable declaration lives, sorted into cascade order:
1210/// origin and importance, then specificity, then source order.
1211type Applicable = (u8, u32, usize, usize, usize);
1212
1213/// Every declaration that matches one element, in cascade order.
1214/// `pseudo` selects the pass: `None` matches the element itself,
1215/// `Some(_)` matches only rules ending in that pseudo-element.
1216fn applicable(
1217    sheets: &[Sheet],
1218    elements: &ElementTree,
1219    index: usize,
1220    caches: &mut SelectorCaches,
1221    pseudo: Option<&PseudoElement>,
1222) -> Vec<Applicable> {
1223    let mode = match pseudo {
1224        Some(_) => MatchingMode::ForStatelessPseudoElement,
1225        None => MatchingMode::Normal,
1226    };
1227    let mut applicable = Vec::new();
1228    for (sheet_index, sheet) in sheets.iter().enumerate() {
1229        for (rule_index, rule) in sheet.rules.iter().enumerate() {
1230            let specificity = rule
1231                .selectors
1232                .slice()
1233                .iter()
1234                .filter(|selector| selector.pseudo_element() == pseudo)
1235                .filter(|selector| {
1236                    let mut context = MatchingContext::new(
1237                        mode,
1238                        None,
1239                        caches,
1240                        QuirksMode::NoQuirks,
1241                        NeedsSelectorFlags::No,
1242                        MatchingForInvalidation::No,
1243                    );
1244                    matches_selector(selector, 0, None, &elements.at(index), &mut context)
1245                })
1246                .map(|selector| selector.specificity())
1247                .max();
1248            let Some(specificity) = specificity else {
1249                continue;
1250            };
1251            for (order, (_, importance)) in rule.declarations.iter().enumerate() {
1252                applicable.push((
1253                    level(sheet.origin, *importance),
1254                    specificity,
1255                    sheet_index,
1256                    rule_index,
1257                    order,
1258                ));
1259            }
1260        }
1261    }
1262    applicable.sort_unstable();
1263    applicable
1264}
1265
1266/// Applies matched declarations in cascade order.
1267///
1268/// `hint` is what the source wrote on the element itself, as HTML's
1269/// `align` is written on a cell. It goes in after the built-in sheet
1270/// and before every rule of the author's, whatever its specificity.
1271fn apply_all(
1272    style: &mut ComputedStyle,
1273    sheets: &[Sheet],
1274    applicable: &[Applicable],
1275    hint: Option<&properties::Declaration>,
1276    parent_size: f32,
1277    root_size: Option<f32>,
1278    warnings: &mut Vec<Warning>,
1279) {
1280    let root_size = root_size.unwrap_or(parent_size);
1281    let declaration = |(_, _, sheet, rule, order): &Applicable| {
1282        &sheets[*sheet].rules[*rule].declarations[*order].0
1283    };
1284    // Custom properties resolve first, because a declaration anywhere
1285    // in the cascade can read one declared after it.
1286    let declared: Vec<&Custom> = applicable
1287        .iter()
1288        .filter_map(|at| match declaration(at) {
1289            Declaration::Custom(custom) => Some(custom),
1290            _ => None,
1291        })
1292        .collect();
1293    if !declared.is_empty() {
1294        style.custom = substitution::resolve(&style.custom, &declared, warnings);
1295    }
1296    let base = applicable
1297        .iter()
1298        .any(|at| matches!(declaration(at), Declaration::Pending(_)))
1299        .then(|| style.clone());
1300    let mut hint = hint;
1301    for at in applicable {
1302        if at.0 > 0
1303            && let Some(declaration) = hint.take()
1304        {
1305            style.apply(declaration, parent_size, root_size);
1306        }
1307        match (declaration(at), &base) {
1308            (Declaration::Pending(pending), Some(base)) => {
1309                substitution::apply(style, pending, base, parent_size, root_size, warnings)
1310            }
1311            (declaration, _) => style.apply(declaration, parent_size, root_size),
1312        }
1313    }
1314    if let Some(declaration) = hint {
1315        style.apply(declaration, parent_size, root_size);
1316    }
1317}
1318
1319/// The `text-align` a table's delimiter row wrote on a cell's column.
1320fn align_hint(align: Alignment) -> properties::Declaration {
1321    properties::Declaration::TextAlign(match align {
1322        Alignment::Left => TextAlign::Left,
1323        Alignment::Center => TextAlign::Center,
1324        Alignment::Right => TextAlign::Right,
1325    })
1326}
1327
1328/// Where one declaration sits in the cascade, before specificity is
1329/// consulted: author CSS beats the built-in sheet, and `!important`
1330/// turns that round for the origin that used it.
1331fn level(origin: Origin, importance: Importance) -> u8 {
1332    match (origin, importance) {
1333        (Origin::UserAgent, Importance::Normal) => 0,
1334        (Origin::Author, Importance::Normal) => 1,
1335        (Origin::Author, Importance::Important) => 2,
1336        (Origin::UserAgent, Importance::Important) => 3,
1337    }
1338}
1339
1340/// The index of a style in the table, adding it if it is new. Books
1341/// have thousands of nodes and a handful of styles.
1342fn intern(styles: &mut Vec<ComputedStyle>, style: ComputedStyle) -> u32 {
1343    match styles.iter().position(|known| *known == style) {
1344        Some(index) => index as u32,
1345        None => {
1346            styles.push(style);
1347            (styles.len() - 1) as u32
1348        }
1349    }
1350}
1351
1352/// Records a face diagnostic once. Thousands of nodes share a
1353/// handful of styles, and a font stack that cannot be honoured is a
1354/// fact about the stack, not about each node that used it.
1355fn report(warnings: &mut Vec<Warning>, warning: Option<Warning>) {
1356    let Some(warning) = warning else {
1357        return;
1358    };
1359    if !warnings.iter().any(|seen| seen.message == warning.message) {
1360        warnings.push(warning);
1361    }
1362}
1363
1364/// Records each of a list of diagnostics once.
1365fn report_all(warnings: &mut Vec<Warning>, found: Vec<Warning>) {
1366    for warning in found {
1367        report(warnings, Some(warning));
1368    }
1369}
1370
1371/// The face a computed style shapes with: the first family in the
1372/// registry, at the nearest slope and weight it has.
1373///
1374/// A family the registry does not have is skipped — that is what a
1375/// font stack is for — but a stack that resolves nothing, or a
1376/// family with no cut at the slope asked for, falls back to a face
1377/// that is visibly not the one requested. Both say so.
1378fn resolve_face(style: &ComputedStyle, registry: &FontRegistry) -> (u16, Option<Warning>) {
1379    let want = FaceAttributes {
1380        italic: style.font_style == FontStyle::Italic,
1381        weight: style.font_weight,
1382    };
1383    for family in &style.font_family {
1384        let name = match family {
1385            Family::Named(name) => Some(name.clone()),
1386            Family::Generic(generic) => registry
1387                .generic(*generic)
1388                .and_then(|id| registry.font_ref(id).map(|entry| entry.family.clone())),
1389        };
1390        let Some(found) = name.as_deref().and_then(|name| registry.select(name, want)) else {
1391            continue;
1392        };
1393        let warning = (found.attributes.italic != want.italic).then(|| Warning {
1394            message: format!(
1395                "{} has no {} face. {} text falls back to {}.",
1396                name.unwrap_or_default(),
1397                slope(want.italic),
1398                sentence(slope(want.italic)),
1399                slope(found.attributes.italic),
1400            ),
1401            origin: None,
1402        });
1403        return (found.id, warning);
1404    }
1405    (
1406        0,
1407        Some(Warning {
1408            message: format!(
1409                "No registered font matches {}. The first registered font is used instead.",
1410                stack(&style.font_family),
1411            ),
1412            origin: None,
1413        }),
1414    )
1415}
1416
1417/// The diagnostic for a face with no small capitals of its own, one
1418/// per style that asks for them: an author who picked the face can
1419/// pick another one.
1420fn synthesized_small_caps(style: &ComputedStyle, registry: &FontRegistry) -> Option<Warning> {
1421    let asked = style.font_variant_caps == FontVariantCaps::SmallCaps;
1422    (asked && !registry.has_small_caps(style.font_id)).then(|| Warning {
1423        message: format!(
1424            "{} has no small capitals. Falling back to reduced capitals.",
1425            registry
1426                .font_ref(style.font_id)
1427                .map(|entry| entry.family.clone())
1428                .unwrap_or_else(|| stack(&style.font_family)),
1429        ),
1430        origin: None,
1431    })
1432}
1433
1434/// The diagnostic for a face that carries none of a feature the
1435/// sheet asked for, one per style that asks for it. The run is set
1436/// without the feature; nothing is synthesized.
1437///
1438/// A setting of zero asks for a feature to be left off, which a face
1439/// that has nothing for it already does.
1440fn missing_features(style: &ComputedStyle, registry: &FontRegistry) -> Vec<Warning> {
1441    let family = || {
1442        registry
1443            .font_ref(style.font_id)
1444            .map(|entry| entry.family.clone())
1445            .unwrap_or_else(|| stack(&style.font_family))
1446    };
1447    style
1448        .features()
1449        .iter()
1450        .filter(|setting| setting.value != 0)
1451        .filter(|setting| !registry.has_feature(style.font_id, setting.tag))
1452        .map(|setting| Warning {
1453            message: format!(
1454                "{} has no `{}` feature. The text is set without it.",
1455                family(),
1456                String::from_utf8_lossy(&setting.tag),
1457            ),
1458            origin: None,
1459        })
1460        .collect()
1461}
1462
1463/// A slope as a stylesheet names it.
1464/// A slope at the head of a sentence.
1465fn sentence(slope: &str) -> String {
1466    let mut opens = slope.chars();
1467    match opens.next() {
1468        Some(first) => first.to_uppercase().collect::<String>() + opens.as_str(),
1469        None => String::new(),
1470    }
1471}
1472
1473fn slope(italic: bool) -> &'static str {
1474    if italic { "italic" } else { "upright" }
1475}
1476
1477/// A font stack as the sheet wrote it, for a diagnostic to quote.
1478fn stack(families: &[Family]) -> String {
1479    families
1480        .iter()
1481        .map(|family| match family {
1482            Family::Named(name) => name.clone(),
1483            Family::Generic(generic) => generic.keyword().to_string(),
1484        })
1485        .collect::<Vec<_>>()
1486        .join(", ")
1487}
1488
1489#[cfg(test)]
1490mod tests {
1491    use super::*;
1492    use crate::content::{Attributes, Block, HeadingLevel, Inline, Metadata, Section, SourcePos};
1493    use crate::fonts::{
1494        BUNDLED_FONT, FaceAttributes, FeatureSetting, GenericFamily, bundled_registry,
1495    };
1496    use crate::lines::{HangEnd, HangingPunctuation};
1497
1498    fn registry() -> &'static FontRegistry {
1499        static REGISTRY: std::sync::OnceLock<FontRegistry> = std::sync::OnceLock::new();
1500        REGISTRY.get_or_init(|| bundled_registry().expect("bundled font parses"))
1501    }
1502
1503    /// A sheet reads back as it was written: selectors as CSS, the
1504    /// declarations the parser kept with their positions, and the
1505    /// at-rules. What the parser refused is a warning and not here.
1506    #[test]
1507    fn a_sheet_reads_back_as_it_was_written() {
1508        let css = "@page :left { margin: 1in }\n\
1509                   h1 + p, NOTE::first-letter {\n  color: red;\n  display: flex;\n  --x: 1pt;\n}\n\
1510                   @font-face { font-family: Author; src: url(a.otf), local(\"B\") }";
1511        let sheets = Stylesheets::parse(&[Source::author("a.css", css)]);
1512        let written = sheets.written();
1513        assert_eq!(written.len(), 2);
1514        assert_eq!(written[0].origin, Origin::UserAgent);
1515
1516        let author = &written[1];
1517        assert_eq!(author.origin, Origin::Author);
1518        assert_eq!(author.pages[0].selector, "@page :left");
1519        assert_eq!(author.pages[0].position.to_string(), "a.css:1:1");
1520        let rule = &author.rules[0];
1521        assert_eq!(rule.selectors, ["h1 + p", "NOTE::first-letter"]);
1522        assert_eq!(rule.position.to_string(), "a.css:2:1");
1523        let kept: Vec<(&str, &str, String)> = rule
1524            .declarations
1525            .iter()
1526            .map(|d| (&*d.property, &*d.value, d.position.to_string()))
1527            .collect();
1528        assert_eq!(
1529            kept,
1530            [
1531                ("color", "red", "a.css:3:3".to_string()),
1532                ("--x", "1pt", "a.css:5:3".to_string()),
1533            ]
1534        );
1535        assert!(
1536            sheets
1537                .warnings()
1538                .iter()
1539                .any(|w| w.origin.as_deref() == Some("a.css:4:3")),
1540            "{:?}",
1541            sheets.warnings()
1542        );
1543        assert_eq!(author.faces[0].family, "Author");
1544        assert_eq!(
1545            author.faces[0].src,
1546            [Src::Url("a.otf".into()), Src::Local("B".into())]
1547        );
1548    }
1549
1550    fn text(value: &str) -> Inline {
1551        Inline::Text {
1552            id: NodeId::UNASSIGNED,
1553            value: value.into(),
1554            attributes: Attributes::default(),
1555            position: None,
1556            span: None,
1557        }
1558    }
1559
1560    /// A chapter: a heading, a paragraph opening with emphasis, a
1561    /// paragraph of plain prose, and a blockquote.
1562    fn sample() -> Book {
1563        let mut book = Book {
1564            metadata: Metadata::default(),
1565            sections: vec![Section {
1566                attributes: Default::default(),
1567                id: NodeId::UNASSIGNED,
1568                source: Some("chapter-01.md".into()),
1569                title: None,
1570                blocks: vec![
1571                    Block::Heading {
1572                        id: NodeId::UNASSIGNED,
1573                        level: HeadingLevel::H1,
1574                        inlines: vec![text("Chapter One")],
1575                        attributes: Attributes::default(),
1576                        position: None,
1577                        span: None,
1578                    },
1579                    Block::Paragraph {
1580                        id: NodeId::UNASSIGNED,
1581                        inlines: vec![
1582                            Inline::Emphasis {
1583                                id: NodeId::UNASSIGNED,
1584                                children: vec![text("In which")],
1585                                attributes: Attributes::default(),
1586                                position: None,
1587                                span: None,
1588                            },
1589                            text(" a drawer is opened."),
1590                        ],
1591                        attributes: Attributes::default(),
1592                        position: None,
1593                        span: None,
1594                    },
1595                    Block::Paragraph {
1596                        id: NodeId::UNASSIGNED,
1597                        inlines: vec![text("It was the kind of morning.")],
1598                        attributes: Attributes::default(),
1599                        position: None,
1600                        span: None,
1601                    },
1602                    Block::Blockquote {
1603                        id: NodeId::UNASSIGNED,
1604                        blocks: vec![Block::Paragraph {
1605                            id: NodeId::UNASSIGNED,
1606                            inlines: vec![text("\"Nobody's early here.\"")],
1607                            attributes: Attributes::default(),
1608                            position: None,
1609                            span: None,
1610                        }],
1611                        attributes: Attributes::default(),
1612                        position: None,
1613                        span: None,
1614                    },
1615                ],
1616                position: None,
1617                span: None,
1618            }],
1619        };
1620        book.assign_node_ids();
1621        book
1622    }
1623
1624    /// The tree, with `css` cascading over the built-in sheet.
1625    fn compile(book: &Book, css: &str) -> StyleTree {
1626        Stylesheets::parse(&[Source::author("author.css", css)]).compile(book, registry())
1627    }
1628
1629    /// The computed style of the nth element with a given name.
1630    fn nth(tree: &StyleTree, element: &str, index: usize) -> ComputedStyle {
1631        let node = tree
1632            .nodes()
1633            .iter()
1634            .filter(|node| node.element == element)
1635            .nth(index)
1636            .unwrap_or_else(|| panic!("no {element} #{index}"));
1637        tree.styles()[node.style as usize].clone()
1638    }
1639
1640    fn first(tree: &StyleTree, element: &str) -> ComputedStyle {
1641        nth(tree, element, 0)
1642    }
1643
1644    /// Two chapters of the sample, the first named `front` and
1645    /// `preface`, the second `body`.
1646    fn named_sections() -> Book {
1647        let mut book = sample();
1648        let mut body = book.sections[0].clone();
1649        body.source = Some("chapter-02.md".into());
1650        body.attributes.classes = vec!["body".into()];
1651        book.sections[0].attributes = Attributes {
1652            id: Some("preface".into()),
1653            classes: vec!["front".into()],
1654        };
1655        book.sections.push(body);
1656        book.assign_node_ids();
1657        book
1658    }
1659
1660    /// Acceptance: the page-name and page-counter examples on the
1661    /// subset page reach the sections they name, and no other.
1662    #[test]
1663    fn the_subset_page_section_examples_match() {
1664        let tree = compile(
1665            &named_sections(),
1666            "section.front { page: front }
1667             section.body { counter-reset: page 1 }",
1668        );
1669        let (front, body) = (nth(&tree, "section", 0), nth(&tree, "section", 1));
1670        assert_eq!(front.page.as_deref(), Some("front"));
1671        assert_ne!(body.page.as_deref(), Some("front"));
1672        assert_eq!(body.counter_reset, Some(1));
1673        assert_eq!(front.counter_reset, None);
1674    }
1675
1676    /// Acceptance: a section's class and id match in the cascade, and
1677    /// `:is()` and a descendant selector see them.
1678    #[test]
1679    fn a_section_class_and_id_match_in_every_selector_form() {
1680        let tree = compile(
1681            &named_sections(),
1682            "section#preface { page: by-id }
1683             :is(section.body) { page: by-is }
1684             section.front p { page: below-front }
1685             :is(section.body) > h1 { page: below-body }",
1686        );
1687        assert_eq!(nth(&tree, "section", 0).page.as_deref(), Some("by-id"));
1688        assert_eq!(nth(&tree, "section", 1).page.as_deref(), Some("by-is"));
1689        // Each chapter of the sample holds three paragraphs.
1690        assert_eq!(nth(&tree, "p", 2).page.as_deref(), Some("below-front"));
1691        assert_ne!(nth(&tree, "p", 3).page.as_deref(), Some("below-front"));
1692        assert_ne!(nth(&tree, "h1", 0).page.as_deref(), Some("below-body"));
1693        assert_eq!(nth(&tree, "h1", 1).page.as_deref(), Some("below-body"));
1694    }
1695
1696    /// A book of two images, the first of them named.
1697    fn images() -> Book {
1698        let image = |named: Attributes| Block::Image {
1699            id: NodeId::UNASSIGNED,
1700            url: "plate.jpg".into(),
1701            alt: "a map".into(),
1702            attributes: named,
1703            position: None,
1704            span: None,
1705        };
1706        let mut book = Book {
1707            metadata: Metadata::default(),
1708            sections: vec![Section {
1709                attributes: Default::default(),
1710                id: NodeId::UNASSIGNED,
1711                source: Some("chapter-01.md".into()),
1712                title: None,
1713                blocks: vec![
1714                    image(Attributes {
1715                        id: Some("frontispiece".into()),
1716                        classes: vec!["map".into()],
1717                    }),
1718                    image(Attributes::default()),
1719                ],
1720                position: None,
1721                span: None,
1722            }],
1723        };
1724        book.assign_node_ids();
1725        book
1726    }
1727
1728    /// A table of a header row and three body rows, its second column
1729    /// written centered.
1730    fn table() -> Book {
1731        use crate::content::{Alignment, Cell, Row};
1732        let cell = |value: &str, align: Option<Alignment>| Cell {
1733            blocks: vec![Block::Paragraph {
1734                id: NodeId::UNASSIGNED,
1735                inlines: vec![text(value)],
1736                attributes: Attributes::default(),
1737                position: None,
1738                span: None,
1739            }],
1740            align,
1741            ..Cell::default()
1742        };
1743        let row = |left: &str, right: &str| Row {
1744            cells: vec![cell(left, None), cell(right, Some(Alignment::Center))],
1745            ..Row::default()
1746        };
1747        let mut book = Book {
1748            metadata: Metadata::default(),
1749            sections: vec![Section {
1750                attributes: Default::default(),
1751                id: NodeId::UNASSIGNED,
1752                source: Some("chapter-01.md".into()),
1753                title: None,
1754                blocks: vec![Block::Table {
1755                    id: NodeId::UNASSIGNED,
1756                    head: vec![row("Pocket", "Found")],
1757                    body: vec![
1758                        row("Right", "A handkerchief"),
1759                        row("Left", "A snuff-box"),
1760                        row("Fob", "A watch"),
1761                    ],
1762                    attributes: Attributes::default(),
1763                    position: None,
1764                    span: None,
1765                }],
1766                position: None,
1767                span: None,
1768            }],
1769        };
1770        book.assign_node_ids();
1771        book
1772    }
1773
1774    /// Acceptance: `z-index` is the layer a block paints in. It is a
1775    /// block's own: a child of a raised block is not raised with it,
1776    /// and `auto` is layer 0.
1777    #[test]
1778    fn a_block_takes_the_layer_it_names_and_a_child_takes_none_of_it() {
1779        let tree = compile(
1780            &sample(),
1781            "blockquote { z-index: 10 }
1782             h1 { z-index: -1 }
1783             p { z-index: auto }",
1784        );
1785        assert_eq!(first(&tree, "blockquote").z_index, 10);
1786        assert_eq!(first(&tree, "h1").z_index, -1);
1787        // The paragraph inside the blockquote is the last of them.
1788        assert_eq!(nth(&tree, "p", 2).z_index, 0);
1789        assert_eq!(first(&tree, "section").z_index, 0);
1790    }
1791
1792    /// Part: `float` and `clear` are a block's own, and neither
1793    /// passes to the blocks inside it.
1794    #[test]
1795    fn float_and_clear_are_read_and_not_inherited() {
1796        let tree = compile(
1797            &sample(),
1798            "blockquote { float: right; clear: both }
1799             h1 { clear: left }
1800             p { float: left }
1801             p + p { float: none }",
1802        );
1803        assert_eq!(first(&tree, "blockquote").float, Float::Right);
1804        assert_eq!(first(&tree, "blockquote").clear, Clear::Both);
1805        assert_eq!(first(&tree, "h1").clear, Clear::Left);
1806        assert_eq!(first(&tree, "p").float, Float::Left);
1807        assert_eq!(nth(&tree, "p", 2).clear, Clear::None);
1808        assert_eq!(first(&tree, "section").float, Float::None);
1809        assert!(Clear::Both.clears(Float::Right));
1810        assert!(!Clear::Left.clears(Float::Right));
1811    }
1812
1813    /// Acceptance: `tbody tr:nth-child(odd)` counts the rows of the
1814    /// body, so it reaches the first and the third of them and not
1815    /// the header row.
1816    #[test]
1817    fn a_body_row_counts_among_the_rows_of_the_body() {
1818        let tint = Some(Color::rgb(0xe3, 0xe3, 0xe3));
1819        let tree = compile(
1820            &table(),
1821            "tbody tr:nth-child(odd) { background-color: #e3e3e3 }",
1822        );
1823        let rows: Vec<Option<Color>> = (0..4)
1824            .map(|index| nth(&tree, "tr", index).background.color)
1825            .collect();
1826        assert_eq!(rows, [None, tint, None, tint]);
1827        assert_eq!(first(&tree, "thead").background.color, None);
1828    }
1829
1830    /// Acceptance: the alignment the delimiter row wrote beats the
1831    /// built-in sheet and reaches the prose in the cell. Any rule of
1832    /// the author's beats it, even one with no specificity.
1833    #[test]
1834    fn the_alignment_a_table_wrote_sits_under_every_author_rule() {
1835        let book = table();
1836        let tree = defaults(&book, registry());
1837        assert_eq!(nth(&tree, "td", 0).text_align, TextAlign::Left);
1838        assert_eq!(nth(&tree, "td", 1).text_align, TextAlign::Center);
1839        assert_eq!(nth(&tree, "th", 1).text_align, TextAlign::Center);
1840        // The header row holds the first two paragraphs, so the first
1841        // body row's second cell holds the fourth.
1842        assert_eq!(nth(&tree, "p", 3).text_align, TextAlign::Center);
1843
1844        let tree = compile(&book, "td { text-align: right }");
1845        assert_eq!(nth(&tree, "td", 1).text_align, TextAlign::Right);
1846        assert_eq!(nth(&tree, "th", 1).text_align, TextAlign::Center);
1847
1848        let tree = compile(&book, "* { text-align: justify }");
1849        assert_eq!(nth(&tree, "td", 1).text_align, TextAlign::Justify);
1850    }
1851
1852    /// `width` computes to points, or stays a percentage of a table
1853    /// the cascade has not sized. `border-collapse` inherits, so the
1854    /// cells of a collapsed table are collapsed too.
1855    #[test]
1856    fn width_and_border_collapse_compute() {
1857        let book = table();
1858        let tree = compile(&book, "th:first-of-type { width: 8em }");
1859        let header = first(&tree, "th");
1860        assert_eq!(header.width, Width::Points(8.0 * header.font_size));
1861        assert_eq!(nth(&tree, "th", 1).width, Width::Auto);
1862        assert_eq!(
1863            first(&tree, "td").width,
1864            Width::Auto,
1865            "width does not inherit"
1866        );
1867
1868        let tree = compile(&book, "th { width: 25% }");
1869        assert_eq!(first(&tree, "th").width, Width::Percent(25.0));
1870
1871        let tree = defaults(&book, registry());
1872        assert_eq!(
1873            first(&tree, "table").border_collapse,
1874            BorderCollapse::Collapse
1875        );
1876        assert_eq!(first(&tree, "td").border_collapse, BorderCollapse::Collapse);
1877        let tree = compile(&book, "table { border-collapse: separate }");
1878        assert_eq!(first(&tree, "td").border_collapse, BorderCollapse::Separate);
1879    }
1880
1881    /// `column-span` is `none` until a sheet says otherwise, and it
1882    /// does not inherit: the cells of a spanning table are set in
1883    /// the table, not across the page a second time.
1884    #[test]
1885    fn column_span_computes_and_does_not_inherit() {
1886        let book = table();
1887        let tree = defaults(&book, registry());
1888        assert_eq!(first(&tree, "table").column_span, ColumnSpan::None);
1889
1890        let tree = compile(&book, "table { column-span: all }");
1891        assert_eq!(first(&tree, "table").column_span, ColumnSpan::All);
1892        assert_eq!(first(&tree, "td").column_span, ColumnSpan::None);
1893        assert!(tree.warnings().is_empty(), "{:?}", tree.warnings());
1894
1895        let tree = compile(
1896            &book,
1897            "table { column-span: all } table { column-span: none }",
1898        );
1899        assert_eq!(first(&tree, "table").column_span, ColumnSpan::None);
1900    }
1901
1902    /// A class names one element out of a kind of them: the image
1903    /// that carries it is set, and the image beside it is not.
1904    #[test]
1905    fn a_class_reaches_the_element_that_carries_it_and_no_other() {
1906        let book = images();
1907        let tree = compile(&book, ".map { text-align: right }");
1908        assert_eq!(nth(&tree, "img", 0).text_align, TextAlign::Right);
1909        assert_eq!(nth(&tree, "img", 1).text_align, TextAlign::Left);
1910    }
1911
1912    /// An id names one element and nothing else, and outranks the
1913    /// class on the same element.
1914    #[test]
1915    fn an_id_reaches_the_element_that_carries_it_and_outranks_a_class() {
1916        let book = images();
1917        let tree = compile(
1918            &book,
1919            ".map { break-before: page } #frontispiece { break-before: recto }",
1920        );
1921        assert_eq!(nth(&tree, "img", 0).break_before, Break::Side(Side::Recto));
1922        assert_eq!(nth(&tree, "img", 1).break_before, Break::Auto);
1923    }
1924
1925    /// An id names one element, so a second element under it is a
1926    /// mistake. Both still match: the sheet reaches two, the origin
1927    /// is the second, and the message names the first.
1928    #[test]
1929    fn an_id_written_twice_warns_naming_both_places() {
1930        let mut book = images();
1931        let Block::Image {
1932            attributes,
1933            position,
1934            ..
1935        } = &mut book.sections[0].blocks[1]
1936        else {
1937            panic!("expected an image");
1938        };
1939        attributes.id = Some("frontispiece".into());
1940        *position = Some(SourcePos {
1941            line: 12,
1942            column: 1,
1943        });
1944        let Block::Image { position, .. } = &mut book.sections[0].blocks[0] else {
1945            panic!("expected an image");
1946        };
1947        *position = Some(SourcePos { line: 3, column: 1 });
1948
1949        let tree = compile(&book, "#frontispiece { break-before: recto }");
1950        assert_eq!(nth(&tree, "img", 0).break_before, Break::Side(Side::Recto));
1951        assert_eq!(nth(&tree, "img", 1).break_before, Break::Side(Side::Recto));
1952        let repeated: Vec<&Warning> = tree
1953            .warnings()
1954            .iter()
1955            .filter(|warning| warning.message.contains("frontispiece"))
1956            .collect();
1957        assert_eq!(repeated.len(), 1, "{:?}", tree.warnings());
1958        assert_eq!(
1959            repeated[0].message,
1960            "Id `frontispiece` is duplicated. Applied at chapter-01.md:3:1.",
1961        );
1962        assert_eq!(repeated[0].origin.as_deref(), Some("chapter-01.md:12:1"));
1963    }
1964
1965    /// The built-in sheet sets the body, chapter and folio styles, and
1966    /// the trade-paperback page.
1967    #[test]
1968    fn the_built_in_sheet_sets_the_defaults() {
1969        let book = sample();
1970        let tree = defaults(&book, registry());
1971
1972        let body = first(&tree, "p");
1973        assert_eq!(body.font_size, 11.0);
1974        assert_eq!(body.line_height, 1.4);
1975        assert_eq!(body.font_id, 0);
1976        assert_eq!(body.hyphens, Hyphens::None);
1977        assert_eq!(first(&tree, "h1").font_size, 18.0);
1978
1979        let recto = tree.page(PageQuery {
1980            name: Some("chapter"),
1981            situation: Situation::Body(Side::Recto),
1982        });
1983        assert_eq!(recto.geometry.width, 432.0);
1984        assert_eq!(recto.geometry.height, 648.0);
1985        assert_eq!(recto.geometry.content_size(), (336.0, 540.0));
1986        let folio = recto
1987            .margin_box(MarginBox::BottomCenter)
1988            .expect("the folio is a margin box");
1989        assert_eq!(folio.content, Content::Counter(CounterStyle::Decimal));
1990        assert_eq!(folio.style.font_size, 9.0);
1991        assert_eq!(folio.style.line_height, 1.4);
1992    }
1993
1994    /// The four background properties compute on a block: a url the
1995    /// sheet wrote, and how it is drawn.
1996    #[test]
1997    fn the_background_properties_compute_on_a_block() {
1998        let tree = compile(
1999            &sample(),
2000            "p {\n  background-color: #f4f1ea;\n  background-image: url(\"scan.webp\");\n  \
2001             background-repeat: no-repeat;\n  background-size: cover;\n  \
2002             background-position: right bottom;\n}",
2003        );
2004        assert!(tree.warnings().is_empty(), "{:?}", tree.warnings());
2005        let background = first(&tree, "p").background;
2006        assert_eq!(background.color, Some(Color::rgb(0xf4, 0xf1, 0xea)));
2007        assert_eq!(
2008            background.image.as_ref().map(|url| url.value.as_str()),
2009            Some("scan.webp"),
2010        );
2011        assert_eq!(background.repeat, BackgroundRepeat::NoRepeat);
2012        assert_eq!(background.size, BackgroundSize::Cover);
2013        assert_eq!(background.position.x, Coord::Percent(100.0));
2014        assert_eq!(background.position.y, Coord::Percent(100.0));
2015        assert!(!first(&tree, "blockquote").background.paints());
2016    }
2017
2018    /// A url carries where it was written, so a warning about it can
2019    /// name the line and column long after the sheet was parsed.
2020    #[test]
2021    fn a_background_url_carries_where_the_sheet_wrote_it() {
2022        let tree = compile(&sample(), "p {\n  background-image: url(scan.webp);\n}");
2023        let url = first(&tree, "p")
2024            .background
2025            .image
2026            .expect("the url reached the style");
2027        assert_eq!(url.origin.as_deref(), Some("author.css:2:3"));
2028    }
2029
2030    /// `background-size` and `background-position` take their length
2031    /// forms, and the cascade resolves `em` against the font size in
2032    /// force while a percentage stays one.
2033    #[test]
2034    fn background_lengths_compute_and_percentages_stay() {
2035        let tree = compile(
2036            &sample(),
2037            "p {\n  font-size: 10pt;\n  background-size: 2em 50%;\n  \
2038             background-position: 1em 25%;\n}",
2039        );
2040        assert!(tree.warnings().is_empty(), "{:?}", tree.warnings());
2041        let background = first(&tree, "p").background;
2042        assert_eq!(
2043            background.size,
2044            BackgroundSize::Fixed {
2045                width: Some(Coord::Points(20.0)),
2046                height: Some(Coord::Percent(50.0)),
2047            },
2048        );
2049        assert_eq!(background.position.x, Coord::Points(10.0));
2050        assert_eq!(background.position.y, Coord::Percent(25.0));
2051    }
2052
2053    /// A background does not inherit: a rule on the quotation leaves
2054    /// the paragraph inside it painting nothing.
2055    #[test]
2056    fn a_background_does_not_reach_the_children_of_the_box() {
2057        let tree = compile(&sample(), "blockquote { background-image: url(scan.webp) }");
2058        assert!(first(&tree, "blockquote").background.paints());
2059        assert!(!first(&tree, "p").background.paints());
2060    }
2061
2062    /// Each side of the spread takes its own scan, and `@page` reads
2063    /// the same four properties a block does.
2064    #[test]
2065    fn each_side_of_the_spread_takes_its_own_background() {
2066        let tree = compile(
2067            &sample(),
2068            "@page :left { background-image: url(verso.webp); background-size: cover }\n\
2069             @page :right { background-image: url(recto.webp); background-size: contain }",
2070        );
2071        assert!(tree.warnings().is_empty(), "{:?}", tree.warnings());
2072        let named = |side| {
2073            tree.page(PageQuery {
2074                name: Some("chapter"),
2075                situation: Situation::Body(side),
2076            })
2077            .background
2078            .clone()
2079        };
2080        let verso = named(Side::Verso);
2081        assert_eq!(
2082            verso.image.as_ref().map(|url| url.value.as_str()),
2083            Some("verso.webp"),
2084        );
2085        assert_eq!(verso.size, BackgroundSize::Cover);
2086        let recto = named(Side::Recto);
2087        assert_eq!(
2088            recto.image.as_ref().map(|url| url.value.as_str()),
2089            Some("recto.webp"),
2090        );
2091        assert_eq!(recto.size, BackgroundSize::Contain);
2092    }
2093
2094    /// Part: `align-content` on `@page` reaches the page box of the
2095    /// pages the rule selects, and a page that names nothing keeps its
2096    /// content at the top.
2097    #[test]
2098    fn align_content_reaches_the_page_box() {
2099        use crate::style::AlignContent;
2100        let book = sample();
2101        let css = "@page chapter:first { align-content: center } \
2102                   @page :left { align-content: end }";
2103        let align = |css: &str, situation: Situation| {
2104            compile(&book, css)
2105                .page(PageQuery {
2106                    name: Some("chapter"),
2107                    situation,
2108                })
2109                .geometry
2110                .align_content
2111        };
2112        assert_eq!(align("", Situation::Body(Side::Recto)), AlignContent::Start);
2113        assert_eq!(
2114            align(css, Situation::First(Side::Recto)),
2115            AlignContent::Center
2116        );
2117        assert_eq!(align(css, Situation::Body(Side::Verso)), AlignContent::End);
2118        assert_eq!(
2119            align(css, Situation::Body(Side::Recto)),
2120            AlignContent::Start
2121        );
2122    }
2123
2124    /// Part: `bleed: auto | <length>` and `marks: none | crop | cross`
2125    /// reach the page box. `auto` is 6pt under crop marks and nothing
2126    /// otherwise, and the slug is there only where a mark is.
2127    #[test]
2128    fn bleed_and_marks_reach_the_page_box() {
2129        let book = sample();
2130        let geometry = |css: &str| {
2131            compile(&book, css)
2132                .page(PageQuery {
2133                    name: Some("chapter"),
2134                    situation: Situation::Body(Side::Recto),
2135                })
2136                .geometry
2137        };
2138        let plain = geometry("");
2139        assert_eq!((plain.bleed(), plain.slug()), (0.0, 0.0));
2140        assert!(plain.marks.is_none());
2141
2142        let marked = geometry("@page { bleed: 3mm; marks: crop }");
2143        assert!((marked.bleed() - 3.0 * 72.0 / 25.4).abs() < 1e-3);
2144        assert!(marked.marks.crop && !marked.marks.cross);
2145        assert!(marked.slug() > 0.0);
2146
2147        assert_eq!(geometry("@page { marks: crop }").bleed(), 6.0);
2148        assert_eq!(geometry("@page { marks: cross }").bleed(), 0.0);
2149        assert_eq!(geometry("@page { bleed: 9pt }").bleed(), 9.0);
2150        assert_eq!(geometry("@page { bleed: 9pt }").slug(), 0.0);
2151        let both = geometry("@page { marks: cross crop }").marks;
2152        assert!(both.crop && both.cross);
2153        assert!(
2154            geometry("@page { marks: crop; marks: none }")
2155                .marks
2156                .is_none()
2157        );
2158    }
2159
2160    /// A value `bleed` and `marks` cannot take warns and leaves the
2161    /// page as it was.
2162    #[test]
2163    fn bleed_and_marks_refuse_what_they_cannot_take() {
2164        let book = sample();
2165        for css in [
2166            "@page { bleed: -3mm }",
2167            "@page { bleed: 5% }",
2168            "@page { marks: crop crop }",
2169            "@page { marks: none crop }",
2170            "@page { marks: bleed }",
2171        ] {
2172            let tree = compile(&book, css);
2173            assert!(!tree.warnings().is_empty(), "{css} warned about nothing");
2174            let geometry = tree
2175                .page(PageQuery {
2176                    name: Some("chapter"),
2177                    situation: Situation::Body(Side::Recto),
2178                })
2179                .geometry;
2180            assert_eq!((geometry.bleed(), geometry.slug()), (0.0, 0.0), "{css}");
2181        }
2182    }
2183
2184    /// The column properties resolve to points against the page's
2185    /// content box: a count divides it, a width takes as many columns
2186    /// of that width as fit, the two together take the smaller
2187    /// answer, and `normal` is one em of the book's own size.
2188    #[test]
2189    fn columns_divide_the_content_box() {
2190        let book = sample();
2191        let page = |css: &str| {
2192            compile(&book, css)
2193                .page(PageQuery {
2194                    name: Some("chapter"),
2195                    situation: Situation::Body(Side::Recto),
2196                })
2197                .geometry
2198        };
2199
2200        let plain = page("");
2201        assert_eq!(plain.column_count(), 1);
2202        assert_eq!(plain.measure(), 336.0);
2203        assert_eq!(plain.columns.gap, compile(&book, "").root().font_size);
2204
2205        let two = page("@page { column-count: 2; column-gap: 16pt }");
2206        assert_eq!(two.column_count(), 2);
2207        assert_eq!(two.measure(), 160.0);
2208        assert_eq!(two.column_origin(0), (54.0, 54.0));
2209        assert_eq!(two.column_origin(1), (230.0, 54.0));
2210
2211        // 336 points of content box takes three 100pt columns with
2212        // 16pt gutters between them, and the columns widen to fill
2213        // what is left over.
2214        let by_width = page("@page { column-width: 100pt; column-gap: 16pt }");
2215        assert_eq!(by_width.column_count(), 3);
2216        assert_eq!(by_width.measure(), (336.0 - 32.0) / 3.0);
2217
2218        // A count declared beside a width is the ceiling on it.
2219        let both = page("@page { column-count: 2; column-width: 100pt; column-gap: 16pt }");
2220        assert_eq!(both.column_count(), 2);
2221
2222        // A width nothing fits still leaves one column.
2223        assert_eq!(page("@page { column-width: 900pt }").column_count(), 1);
2224
2225        let ruled = page("@page { column-count: 2; column-rule-style: solid }");
2226        assert_eq!(ruled.columns.rule.used(), crate::style::Border::NONE.width);
2227        assert_eq!(
2228            page("@page { column-rule-width: thin }")
2229                .columns
2230                .rule
2231                .used(),
2232            0.0,
2233            "a rule with no style is not drawn",
2234        );
2235    }
2236
2237    /// Selectors run against the content tree: type, descendant,
2238    /// child, `:first-child` and `:is()` all pick out the elements a
2239    /// reader of the markdown would expect.
2240    #[test]
2241    fn selectors_match_the_content_tree() {
2242        let book = sample();
2243        let tree = compile(
2244            &book,
2245            "section > p { text-indent: 12pt }
2246             blockquote p { text-indent: 3pt }
2247             :is(h1, h2):first-child { text-indent: 6pt }
2248             :is(em, strong) { font-weight: 700 }",
2249        );
2250        // The section's own paragraphs are indented; the one inside
2251        // the blockquote is not a child of the section, so only the
2252        // descendant rule reaches it.
2253        assert_eq!(nth(&tree, "p", 0).text_indent, 12.0);
2254        assert_eq!(nth(&tree, "p", 1).text_indent, 12.0);
2255        assert_eq!(nth(&tree, "p", 2).text_indent, 3.0);
2256        // The heading opens the section, so it is a first child.
2257        assert_eq!(first(&tree, "h1").text_indent, 6.0);
2258        assert_eq!(first(&tree, "em").font_weight, 700);
2259
2260        // Siblings, negation, counting and `:has()` all reach the
2261        // same tree.
2262        let tree = compile(
2263            &book,
2264            "h1 + p { text-indent: 1pt }
2265             h1 ~ p { widows: 3 }
2266             p:not(:first-child) { orphans: 4 }
2267             section:has(blockquote) > p:nth-child(3) { text-indent: 2pt }",
2268        );
2269        assert_eq!(nth(&tree, "p", 0).text_indent, 1.0);
2270        assert_eq!(nth(&tree, "p", 1).text_indent, 2.0);
2271        assert_eq!(nth(&tree, "p", 0).widows, 3);
2272        assert_eq!(nth(&tree, "p", 0).orphans, 4);
2273        assert_eq!(first(&tree, "h1").orphans, 2);
2274    }
2275
2276    /// Author CSS overrides the built-in sheet, and specificity and
2277    /// source order decide between author rules.
2278    #[test]
2279    fn author_css_overrides_the_built_in_sheet() {
2280        let book = sample();
2281        // The built-in sheet's `book { font-size: 11pt }` is more
2282        // specific than nothing, and still loses to the author.
2283        let tree = compile(&book, "* { font-size: 13pt } p { font-size: 12pt }");
2284        assert_eq!(first(&tree, "p").font_size, 12.0);
2285        // Equal specificity: the later rule wins.
2286        let tree = compile(&book, "p { font-size: 12pt } p { font-size: 14pt }");
2287        assert_eq!(first(&tree, "p").font_size, 14.0);
2288        // `!important` in the built-in sheet would outrank the
2289        // author, and nothing in it uses one.
2290        let tree = compile(
2291            &book,
2292            "p { font-size: 12pt !important } p { font-size: 14pt }",
2293        );
2294        assert_eq!(first(&tree, "p").font_size, 12.0);
2295    }
2296
2297    /// An unsupported property is a diagnostic naming its source
2298    /// position, and the rest of the rule still applies.
2299    #[test]
2300    fn unsupported_properties_warn_and_the_run_continues() {
2301        let book = sample();
2302        let tree = compile(
2303            &book,
2304            "p {\n  text-shadow: 0 0 2px black;\n  font-size: 13pt;\n}\n",
2305        );
2306        let warning = tree
2307            .warnings()
2308            .iter()
2309            .find(|warning| warning.message.contains("text-shadow"))
2310            .expect("text-shadow is outside the subset");
2311        assert_eq!(
2312            warning.message,
2313            "Unsupported property `text-shadow`. The declaration is ignored."
2314        );
2315        assert_eq!(warning.origin.as_deref(), Some("author.css:2:3"));
2316        assert_eq!(
2317            first(&tree, "p").font_size,
2318            13.0,
2319            "the declaration after the bad one was dropped"
2320        );
2321    }
2322
2323    /// A sheet that breaks the subset every way it can. Each warning
2324    /// is a sentence, and says what happened to the declaration or to
2325    /// the rule.
2326    #[test]
2327    fn every_css_warning_names_what_was_ignored() {
2328        let css = "p { text-shadow: 0 0 2px black }\n\
2329                   p { text-align: bananas }\n\
2330                   p::first-line { font-family: serif }\n\
2331                   @media print { p { color: red } }\n\
2332                   @page :nth(2) { size: a4 }\n\
2333                   p:hover { color: red }\n\
2334                   p { color: }\n";
2335        let sheets = Stylesheets::parse(&[Source::author("author.css", css)]);
2336        let warnings = sheets.warnings();
2337        assert!(warnings.len() >= 6, "{warnings:?}");
2338        for warning in warnings {
2339            let message = &warning.message;
2340            assert!(
2341                message.starts_with(|opens: char| opens.is_uppercase()),
2342                "{message}",
2343            );
2344            assert!(!message.contains(';'), "{message}");
2345            assert!(
2346                message.ends_with("The declaration is ignored.")
2347                    || message.ends_with("The rule is ignored."),
2348                "{message}",
2349            );
2350        }
2351    }
2352
2353    /// A font file that will not parse and a font with no family name
2354    /// are different mistakes, so they read apart.
2355    #[test]
2356    fn the_two_font_face_failures_read_apart() {
2357        assert_eq!(
2358            face_failure("Sabon", &FontError::Parse),
2359            "Sabon could not be read as a font. Falling back to another registered font.",
2360        );
2361        assert_eq!(
2362            face_failure("Sabon", &FontError::MissingName),
2363            "Sabon has no family name and was not registered. \
2364             Falling back to another registered font.",
2365        );
2366    }
2367
2368    /// The rest of the subset's edges: an at-rule, a selector and a
2369    /// value the engine does not know each warn where they were
2370    /// written, and the sheet keeps parsing.
2371    #[test]
2372    fn unsupported_at_rules_selectors_and_values_warn() {
2373        let book = sample();
2374        let tree = compile(
2375            &book,
2376            "@media print { p { font-size: 30pt } }\n\
2377             p:hover { font-size: 40pt }\n\
2378             p { text-align: sideways }\n\
2379             p { hanging-punctuation: sideways }\n\
2380             p { font-size: 15pt }\n",
2381        );
2382        let messages: Vec<&str> = tree
2383            .warnings()
2384            .iter()
2385            .map(|warning| warning.message.as_str())
2386            .collect();
2387        assert!(
2388            messages.contains(&"Unsupported at-rule `@media`. The rule is ignored."),
2389            "{messages:?}"
2390        );
2391        assert!(
2392            messages.contains(&"Unsupported selector `:hover`. The rule is ignored."),
2393            "{messages:?}"
2394        );
2395        assert!(
2396            messages.contains(&"Unsupported value for `text-align`. The declaration is ignored."),
2397            "{messages:?}"
2398        );
2399        assert!(
2400            messages.contains(
2401                &"Unsupported value for `hanging-punctuation`. The declaration is ignored."
2402            ),
2403            "{messages:?}"
2404        );
2405        assert!(
2406            tree.warnings()
2407                .iter()
2408                .all(|warning| warning.origin.is_some()),
2409            "a diagnostic with no position: {:?}",
2410            tree.warnings()
2411        );
2412        assert_eq!(first(&tree, "p").font_size, 15.0);
2413    }
2414
2415    /// `@page :first` and `:left`/`:right` select different masters
2416    /// for the same book: a chapter opening runs a blind folio, and
2417    /// the spread's margins mirror.
2418    #[test]
2419    fn page_pseudo_classes_select_different_masters() {
2420        let book = sample();
2421        let tree = defaults(&book, registry());
2422        let chapter = |situation| {
2423            tree.page(PageQuery {
2424                name: Some("chapter"),
2425                situation,
2426            })
2427        };
2428        let opening = chapter(Situation::First(Side::Recto));
2429        let body = chapter(Situation::Body(Side::Recto));
2430        let verso = chapter(Situation::Body(Side::Verso));
2431        let blank = chapter(Situation::Blank);
2432
2433        assert!(opening.margin_box(MarginBox::BottomCenter).is_none());
2434        // A blank's master is a master like any other; that nothing
2435        // paints on a blank is the flow's rule, not the sheet's.
2436        assert_eq!(blank.geometry, verso.geometry);
2437        assert_eq!(
2438            body.margin_box(MarginBox::BottomCenter)
2439                .map(|box_| &box_.content),
2440            Some(&Content::Counter(CounterStyle::Decimal))
2441        );
2442        assert_eq!(body.geometry.margin.left, 54.0);
2443        assert_eq!(body.geometry.margin.right, 42.0);
2444        assert_eq!(verso.geometry.margin.left, 42.0);
2445        assert_eq!(verso.geometry.margin.right, 54.0);
2446        // Every situation of every named page has a master.
2447        assert_eq!(tree.masters().len(), 10);
2448    }
2449
2450    /// Part: the `text-decoration` shorthand sets all four
2451    /// longhands, and puts back to its initial value every one it
2452    /// leaves out.
2453    #[test]
2454    fn the_text_decoration_shorthand_sets_every_longhand() {
2455        let book = sample();
2456        let tree = compile(
2457            &book,
2458            "p { text-decoration: underline double #808080 1.5pt }
2459             em { text-decoration: line-through }",
2460        );
2461        let paragraph = first(&tree, "p");
2462        assert_eq!(
2463            paragraph.text_decoration_line,
2464            DecorationLine {
2465                under: true,
2466                over: false,
2467                through: false,
2468            },
2469        );
2470        assert_eq!(paragraph.text_decoration_style, DecorationStyle::Double);
2471        assert_eq!(
2472            paragraph.text_decoration_color,
2473            Some(Color::rgb(128, 128, 128)),
2474        );
2475        assert_eq!(paragraph.text_decoration_thickness, Some(1.5));
2476
2477        // The emphasis is inside the paragraph, so it inherits all
2478        // four and then the shorthand puts back the three it does
2479        // not name.
2480        let emphasis = first(&tree, "em");
2481        assert_eq!(
2482            emphasis.text_decoration_line,
2483            DecorationLine {
2484                under: false,
2485                over: false,
2486                through: true,
2487            },
2488        );
2489        assert_eq!(emphasis.text_decoration_style, DecorationStyle::Solid);
2490        assert_eq!(emphasis.text_decoration_color, None);
2491        assert_eq!(emphasis.text_decoration_thickness, None);
2492
2493        // The longhands inherit on their own: an emphasis the
2494        // shorthand does not reach keeps what the paragraph drew.
2495        let inherited = compile(&book, "p { text-decoration: underline }");
2496        assert_eq!(
2497            first(&inherited, "em").text_decoration_line,
2498            first(&inherited, "p").text_decoration_line,
2499        );
2500    }
2501
2502    /// A highlight is the element `mark`. The built-in sheet puts a
2503    /// background behind it, and a sheet reaches it by that name.
2504    #[test]
2505    fn a_highlight_is_a_mark_with_a_background() {
2506        let mut book: Book = serde_json::from_str(
2507            r#"{"metadata": {}, "sections": [{"blocks": [{"type": "paragraph", "inlines": [
2508                {"type": "text", "value": "He was "},
2509                {"type": "highlight", "children": [{"type": "text", "value": "certain"}]}
2510            ]}]}]}"#,
2511        )
2512        .expect("the book reads");
2513        book.assign_node_ids();
2514
2515        let built_in = first(&compile(&book, ""), "mark");
2516        assert_eq!(built_in.background.color, Some(Color::rgb(255, 255, 0)));
2517
2518        let authored = first(
2519            &compile(&book, "mark { background-color: #c0c0c0 }"),
2520            "mark",
2521        );
2522        assert_eq!(authored.background.color, Some(Color::rgb(192, 192, 192)));
2523    }
2524
2525    /// The furniture grammar: what an element sets a running string
2526    /// to, where the folio restarts, and what a margin box resolves
2527    /// its content from.
2528    #[test]
2529    fn string_set_counter_reset_and_margin_box_content_compile() {
2530        let book = sample();
2531        let tree = compile(
2532            &book,
2533            "h1 { string-set: chapter \"— \" content() }
2534             section { counter-reset: page 7 }
2535             @page :left { @top-left { content: string(chapter) } }
2536             @page :right { @top-right { content: counter(page, upper-roman) } }",
2537        );
2538
2539        assert_eq!(
2540            first(&tree, "h1").string_set,
2541            vec![StringSet {
2542                name: "chapter".into(),
2543                value: vec![StringPiece::Text("— ".into()), StringPiece::Content],
2544            }],
2545        );
2546        // `content(text)` is the other spelling of the same thing,
2547        // and an argument the engine has no answer for is not.
2548        let spelled = compile(
2549            &book,
2550            "h1 { string-set: chapter content(text) }
2551             p { string-set: stanza content(before) }",
2552        );
2553        assert_eq!(
2554            first(&spelled, "h1").string_set,
2555            vec![StringSet {
2556                name: "chapter".into(),
2557                value: vec![StringPiece::Content],
2558            }],
2559        );
2560        assert!(first(&spelled, "p").string_set.is_empty());
2561        assert_eq!(spelled.warnings().len(), 1, "{:?}", spelled.warnings());
2562
2563        assert_eq!(first(&tree, "section").counter_reset, Some(7));
2564        // Not inherited: a paragraph inside the section restarts
2565        // nothing and sets nothing.
2566        assert_eq!(first(&tree, "p").counter_reset, None);
2567        assert!(first(&tree, "p").string_set.is_empty());
2568
2569        let box_content = |situation, which| {
2570            tree.page(PageQuery {
2571                name: Some("chapter"),
2572                situation,
2573            })
2574            .margin_box(which)
2575            .map(|box_| box_.content.clone())
2576        };
2577        assert_eq!(
2578            box_content(Situation::Body(Side::Verso), MarginBox::TopLeft),
2579            Some(Content::String("chapter".into())),
2580        );
2581        assert_eq!(
2582            box_content(Situation::Body(Side::Recto), MarginBox::TopRight),
2583            Some(Content::Counter(CounterStyle::UpperRoman)),
2584        );
2585    }
2586
2587    /// A counter style outside the subset is a diagnostic, not a
2588    /// silently decimal folio.
2589    #[test]
2590    fn an_unsupported_counter_style_warns() {
2591        let book = sample();
2592        let tree = compile(
2593            &book,
2594            "@page { @bottom-center { content: counter(page, georgian) } }",
2595        );
2596        assert!(
2597            tree.warnings().iter().any(|warning| warning.message
2598                == "Unsupported value for `content`. The declaration is ignored."),
2599            "{:?}",
2600            tree.warnings(),
2601        );
2602    }
2603
2604    /// The `@page` grammar: named pages, sheet sizes, margins, and a
2605    /// margin box set to a literal.
2606    #[test]
2607    fn page_grammar_sets_size_margins_and_margin_boxes() {
2608        let book = sample();
2609        let tree = compile(
2610            &book,
2611            "section { page: chapter }
2612             @page { size: a5; margin: 2cm }
2613             @page chapter { margin-left: 3cm }
2614             @page chapter:first { @top-center { content: \"❦\"; font-size: 14pt } }",
2615        );
2616        let a5 = (148.0 * 72.0 / 25.4, 210.0 * 72.0 / 25.4);
2617        let body = tree.page(PageQuery {
2618            name: Some("chapter"),
2619            situation: Situation::Body(Side::Recto),
2620        });
2621        assert!((body.geometry.width - a5.0).abs() < 1e-3);
2622        assert!((body.geometry.height - a5.1).abs() < 1e-3);
2623        assert!((body.geometry.margin.top - 2.0 * 72.0 / 2.54).abs() < 1e-3);
2624        assert!((body.geometry.margin.left - 3.0 * 72.0 / 2.54).abs() < 1e-3);
2625
2626        let opening = tree.page(PageQuery {
2627            name: Some("chapter"),
2628            situation: Situation::First(Side::Recto),
2629        });
2630        let ornament = opening
2631            .margin_box(MarginBox::TopCenter)
2632            .expect("the opening page has an ornament");
2633        assert_eq!(ornament.content, Content::Text("❦".into()));
2634        assert_eq!(ornament.style.font_size, 14.0);
2635        // An unnamed page never picked up the named rule's margin.
2636        let unnamed = tree.page(PageQuery {
2637            name: None,
2638            situation: Situation::Body(Side::Recto),
2639        });
2640        assert!((unnamed.geometry.margin.left - 2.0 * 72.0 / 2.54).abs() < 1e-3);
2641    }
2642
2643    /// `@font-face` resolves its `src` through the host loader, and
2644    /// the family the sheet declared is the one selectors use.
2645    #[test]
2646    fn font_face_src_resolves_through_the_host_loader() {
2647        struct OneFace;
2648        impl FontLoader for OneFace {
2649            fn load(&self, url: &str) -> Option<Vec<u8>> {
2650                (url == "faces/garamond.ttf").then(|| BUNDLED_FONT.to_vec())
2651            }
2652        }
2653
2654        let book = sample();
2655        let mut registry = bundled_registry().expect("bundled font parses");
2656        let css = "@font-face {
2657                     font-family: \"Author Serif\";
2658                     src: url(\"faces/garamond.ttf\") format(\"truetype\");
2659                   }
2660                   @font-face {
2661                     font-family: \"Missing\";
2662                     src: url(\"faces/nowhere.ttf\");
2663                   }
2664                   p { font-family: \"Author Serif\", serif }
2665                   h1 { font-family: \"Missing\", serif }";
2666        let mut sheets = Stylesheets::parse(&[Source::author("author.css", css)]);
2667        sheets.load_fonts(&mut registry, &OneFace);
2668        let tree = sheets.compile(&book, &registry);
2669
2670        let author = registry
2671            .by_family("author serif")
2672            .expect("the loaded face joined the registry");
2673        assert_eq!(registry.len(), bundled_registry().unwrap().len() + 5);
2674        assert_eq!(first(&tree, "p").font_id, author);
2675        // A face nothing resolved falls back to the next family.
2676        assert_eq!(first(&tree, "h1").font_id, 0);
2677        assert!(
2678            tree.warnings()
2679                .iter()
2680                .any(|warning| warning.message.contains("Missing")),
2681            "an unresolved face should say so: {:?}",
2682            tree.warnings()
2683        );
2684    }
2685
2686    /// The engine opens nothing itself: with a loader that resolves
2687    /// nothing, `@font-face` adds no face and says why.
2688    #[test]
2689    fn without_a_loader_no_font_face_resolves() {
2690        let book = sample();
2691        let mut registry = bundled_registry().expect("bundled font parses");
2692        let css = "@font-face { font-family: \"Author Serif\"; src: url(\"anywhere.ttf\") }";
2693        let mut sheets = Stylesheets::parse(&[Source::author("author.css", css)]);
2694        sheets.load_fonts(&mut registry, &NoFonts);
2695        let tree = sheets.compile(&book, &registry);
2696        assert_eq!(registry.len(), bundled_registry().unwrap().len());
2697        assert!(
2698            tree.warnings()
2699                .iter()
2700                .any(|w| w.message.contains("No src url loaded"))
2701        );
2702    }
2703
2704    /// Relative lengths compute against what CSS says they do:
2705    /// `em` in `font-size` against the parent, `rem` against the
2706    /// root, `em` elsewhere against the element's own size.
2707    #[test]
2708    fn relative_lengths_resolve_against_their_reference() {
2709        let book = sample();
2710        let tree = compile(
2711            &book,
2712            "book { font-size: 10pt }
2713             p { font-size: 1.2em; text-indent: 2em; margin-left: 1rem }
2714             em { font-size: 50% }",
2715        );
2716        let paragraph = first(&tree, "p");
2717        assert!((paragraph.font_size - 12.0).abs() < 1e-4);
2718        assert!((paragraph.text_indent - 24.0).abs() < 1e-4);
2719        assert!((paragraph.margin.left - 10.0).abs() < 1e-4);
2720        assert!((first(&tree, "em").font_size - 6.0).abs() < 1e-4);
2721    }
2722
2723    /// Line height computes to a multiple whatever it was written as.
2724    #[test]
2725    fn line_height_computes_to_a_multiple() {
2726        let book = sample();
2727        let tree = compile(
2728            &book,
2729            "p { font-size: 10pt; line-height: 15pt }
2730             h1 { line-height: 150% }
2731             em { line-height: normal }",
2732        );
2733        assert!((first(&tree, "p").line_height - 1.5).abs() < 1e-4);
2734        assert!((first(&tree, "h1").line_height - 1.5).abs() < 1e-4);
2735        assert!((first(&tree, "em").line_height - 1.2).abs() < 1e-4);
2736    }
2737
2738    /// Inheritance: text properties reach descendants, box properties
2739    /// do not.
2740    #[test]
2741    fn text_properties_inherit_and_box_properties_do_not() {
2742        let book = sample();
2743        let tree = compile(
2744            &book,
2745            "section { text-align: justify; margin-left: 20pt; hyphens: auto }",
2746        );
2747        let paragraph = first(&tree, "p");
2748        assert_eq!(paragraph.text_align, TextAlign::Justify);
2749        assert_eq!(paragraph.hyphens, Hyphens::Auto);
2750        assert_eq!(paragraph.margin.left, 0.0);
2751        assert_eq!(first(&tree, "section").margin.left, 20.0);
2752    }
2753
2754    /// The `inherited` flag on each row of the property table is what
2755    /// the cascade does: set on `section`, an inherited property
2756    /// reaches the paragraph under it and a box property does not.
2757    #[test]
2758    fn the_property_table_says_what_inherits() {
2759        let book = sample();
2760        // The mode the elements around a node draw in is kept beside
2761        // the node's own values, and is none of them.
2762        let own = |style: &ComputedStyle| ComputedStyle {
2763            blend_around: BlendMode::Normal,
2764            ..style.clone()
2765        };
2766        let baseline = own(&first(&compile(&book, ""), "p"));
2767        for spec in sheet::PROPERTIES {
2768            let reached = spec.examples.iter().any(|example| {
2769                let css = format!("section {{ {}: {example} }}", spec.name);
2770                own(&first(&compile(&book, &css), "p")) != baseline
2771            });
2772            assert_eq!(reached, spec.inherited, "{}", spec.name);
2773        }
2774    }
2775
2776    /// The border shorthands compute onto the four edges: `border`
2777    /// sets all of them, a per-edge longhand one, and the per-value
2778    /// longhands one component of each. What a shorthand leaves out
2779    /// goes back to its initial value, so `border: solid` after a
2780    /// colour drops the colour.
2781    #[test]
2782    fn the_border_shorthands_reach_the_four_edges() {
2783        let book = sample();
2784        let tree = compile(
2785            &book,
2786            "p { border: 2pt solid crimson; border-left: 6pt solid }\n             blockquote { border-style: solid none; border-width: 1pt; border-color: teal }",
2787        );
2788        assert!(tree.warnings().is_empty(), "{:?}", tree.warnings());
2789        let paragraph = first(&tree, "p");
2790        assert_eq!(paragraph.border.top.width, 2.0);
2791        assert_eq!(paragraph.border.top.style, BorderStyle::Solid);
2792        assert_eq!(paragraph.border.top.color, Some(Color::rgb(220, 20, 60)));
2793        assert_eq!(paragraph.border.left.width, 6.0);
2794        assert_eq!(paragraph.border.left.color, None);
2795        assert_eq!(paragraph.border.widths().inline(), 8.0);
2796
2797        let quote = first(&tree, "blockquote");
2798        assert_eq!(quote.border.widths().top, 1.0);
2799        assert_eq!(quote.border.widths().right, 0.0);
2800        assert_eq!(quote.border.left.color, Some(Color::rgb(0, 128, 128)));
2801    }
2802
2803    /// An edge `border-style` leaves at `none` takes no width in the
2804    /// flow, whatever `border-width` said, and one written with no
2805    /// width at all is `medium`.
2806    #[test]
2807    fn an_undrawn_edge_takes_no_width() {
2808        let book = sample();
2809        let tree = compile(
2810            &book,
2811            "p { border-width: 4pt }\nblockquote { border: solid }",
2812        );
2813        assert_eq!(first(&tree, "p").border.widths(), Edges::all(0.0));
2814        assert_eq!(first(&tree, "blockquote").border.widths(), Edges::all(2.25));
2815    }
2816
2817    /// `padding` reads the one-to-four value shorthand the way
2818    /// `margin` does, and its longhands overwrite what it set.
2819    #[test]
2820    fn padding_reads_the_shorthand_and_its_longhands() {
2821        let book = sample();
2822        let tree = compile(&book, "p { padding: 6pt 12pt; padding-bottom: 0 }");
2823        let padding = first(&tree, "p").padding;
2824        assert_eq!(padding.top, 6.0);
2825        assert_eq!(padding.right, 12.0);
2826        assert_eq!(padding.bottom, 0.0);
2827        assert_eq!(padding.left, 12.0);
2828    }
2829
2830    /// `text-justify` and `hanging-punctuation` read as CSS writes
2831    /// them: the first a keyword, the second a set of them in any
2832    /// order.
2833    #[test]
2834    fn justification_and_hanging_marks_read_as_css_writes_them() {
2835        let book = sample();
2836        let tree = compile(
2837            &book,
2838            "book { text-justify: inter-character;\
2839                    hanging-punctuation: last first allow-end }",
2840        );
2841        let paragraph = first(&tree, "p");
2842        assert_eq!(paragraph.text_justify, TextJustify::InterCharacter);
2843        assert_eq!(
2844            paragraph.hanging_punctuation,
2845            HangingPunctuation {
2846                first: true,
2847                end: HangEnd::Allow,
2848                last: true,
2849            },
2850        );
2851        let plain = compile(&book, "book { hanging-punctuation: none }");
2852        assert_eq!(
2853            first(&plain, "p").hanging_punctuation,
2854            HangingPunctuation::NONE,
2855        );
2856    }
2857
2858    /// Generic families resolve through the registry's bindings, and
2859    /// slope and weight pick the nearest face in a family.
2860    #[test]
2861    fn families_resolve_through_the_registry() {
2862        let book = sample();
2863        let tree = compile(&book, "p { font-family: \"Nowhere\", monospace }");
2864        let paragraph = first(&tree, "p");
2865        assert_eq!(
2866            paragraph.font_family,
2867            vec![
2868                Family::Named("Nowhere".into()),
2869                Family::Generic(GenericFamily::Monospace),
2870            ]
2871        );
2872        assert_eq!(
2873            paragraph.font_id,
2874            registry().generic(GenericFamily::Monospace).unwrap()
2875        );
2876    }
2877
2878    /// A book of one paragraph, a scene break and a quotation: the
2879    /// blocks whose defaults the built-in sheet has opinions about.
2880    fn furnished() -> Book {
2881        let mut book = Book {
2882            metadata: Metadata::default(),
2883            sections: vec![Section {
2884                attributes: Default::default(),
2885                blocks: vec![
2886                    Block::Paragraph {
2887                        id: NodeId::UNASSIGNED,
2888                        inlines: vec![text("Before the break.")],
2889                        attributes: Attributes::default(),
2890                        position: None,
2891                        span: None,
2892                    },
2893                    Block::ThematicBreak {
2894                        id: NodeId::UNASSIGNED,
2895                        attributes: Attributes::default(),
2896                        position: None,
2897                        span: None,
2898                    },
2899                    Block::Blockquote {
2900                        id: NodeId::UNASSIGNED,
2901                        blocks: vec![Block::Paragraph {
2902                            id: NodeId::UNASSIGNED,
2903                            inlines: vec![text("Quoted.")],
2904                            attributes: Attributes::default(),
2905                            position: None,
2906                            span: None,
2907                        }],
2908                        attributes: Attributes::default(),
2909                        position: None,
2910                        span: None,
2911                    },
2912                ],
2913                ..Default::default()
2914            }],
2915        };
2916        book.assign_node_ids();
2917        book
2918    }
2919
2920    /// The built-in sheet sets a scene break in an ornament, centred,
2921    /// and keeps it off both ends of a page. An author sets it in
2922    /// something else, or in space.
2923    #[test]
2924    fn a_thematic_break_takes_its_ornament_from_the_cascade() {
2925        let book = furnished();
2926        let tree = defaults(&book, registry());
2927        let rule = first(&tree, "hr");
2928        assert_eq!(rule.content, Content::Text("\u{2766}".into()));
2929        assert_eq!(rule.text_align, TextAlign::Center);
2930        assert_eq!(rule.break_before, Break::Avoid);
2931        assert_eq!(rule.break_after, Break::Avoid);
2932        assert_eq!(rule.margin.top, 11.0);
2933
2934        assert_eq!(
2935            first(&compile(&book, "hr { content: none }"), "hr").content,
2936            Content::None,
2937        );
2938        assert_eq!(
2939            first(&compile(&book, "hr { content: \"* * *\" }"), "hr").content,
2940            Content::Text("* * *".into()),
2941        );
2942    }
2943
2944    /// A quotation is indented on both sides and set off above and
2945    /// below, and the indent is a multiple of its own size.
2946    #[test]
2947    fn a_blockquote_is_indented_by_the_built_in_sheet() {
2948        let book = furnished();
2949        let tree = defaults(&book, registry());
2950        let quote = first(&tree, "blockquote");
2951        assert_eq!(quote.margin.left, 2.0 * quote.font_size);
2952        assert_eq!(quote.margin.right, 2.0 * quote.font_size);
2953        assert_eq!(quote.margin.top, quote.font_size);
2954        // The paragraph inside has no indent of its own: the
2955        // quotation's box is what moves it.
2956        assert_eq!(nth(&tree, "p", 1).margin.left, 0.0);
2957    }
2958
2959    /// `::first-letter` is a second pass over the element it belongs
2960    /// to: it starts from that element's own computed style, cascades
2961    /// the rules that named it over the top, and resolves a face of
2962    /// its own. Rules that name no pseudo-element never reach it, and
2963    /// it never reaches the element.
2964    #[test]
2965    fn first_letter_cascades_over_the_element_it_belongs_to() {
2966        let book = sample();
2967        let tree = compile(
2968            &book,
2969            "p { font-size: 12pt; line-height: 1.8 }
2970             p::first-letter { initial-letter: 3; font-family: monospace }",
2971        );
2972        let Block::Paragraph { id, .. } = &book.sections[0].blocks[1] else {
2973            panic!("the second block is a paragraph");
2974        };
2975        let initial = tree
2976            .first_letter(*id)
2977            .expect("a rule named the paragraph's first letter");
2978        assert_eq!(initial.initial_letter, 3);
2979        assert_eq!(initial.font_size, 12.0, "the element's size is inherited");
2980        assert_eq!(initial.line_height, 1.8);
2981        assert_eq!(
2982            initial.font_id,
2983            registry().generic(GenericFamily::Monospace).unwrap(),
2984            "the pseudo-element resolves its own face",
2985        );
2986
2987        // The element keeps its own style, and an element no rule
2988        // named has no first-letter style at all.
2989        assert_eq!(first(&tree, "p").initial_letter, 0);
2990        let Block::Heading { id, .. } = &book.sections[0].blocks[0] else {
2991            panic!("the first block is a heading");
2992        };
2993        assert!(tree.first_letter(*id).is_none());
2994        assert!(defaults(&book, registry()).first_letter(*id).is_none());
2995
2996        // Selectors in front of the pseudo-element still have to
2997        // match: only the paragraph after the heading is picked out.
2998        let tree = compile(&book, "h1 + p::first-letter { initial-letter: 2 }");
2999        assert!(tree.first_letter(*id).is_none());
3000        let Block::Paragraph { id: second, .. } = &book.sections[0].blocks[2] else {
3001            panic!("the third block is a paragraph");
3002        };
3003        assert!(tree.first_letter(*second).is_none());
3004    }
3005
3006    /// A pseudo-element outside the subset is a diagnostic, and the
3007    /// sheet keeps parsing.
3008    #[test]
3009    fn an_unsupported_pseudo_element_warns() {
3010        let book = sample();
3011        let tree = compile(
3012            &book,
3013            "p::marker { content: \"x\" }\np { font-size: 15pt }\n",
3014        );
3015        assert!(
3016            tree.warnings()
3017                .iter()
3018                .any(|warning| warning.message
3019                    == "Unsupported selector `:marker`. The rule is ignored."),
3020            "{:?}",
3021            tree.warnings(),
3022        );
3023        assert_eq!(first(&tree, "p").font_size, 15.0);
3024    }
3025
3026    /// A chapter heading named `the-hunter`, and a paragraph with a
3027    /// link to it.
3028    fn linked() -> Book {
3029        let mut book = sample();
3030        let blocks = &mut book.sections[0].blocks;
3031        if let Block::Heading { attributes, .. } = &mut blocks[0] {
3032            attributes.id = Some("the-hunter".into());
3033        }
3034        blocks.push(Block::Paragraph {
3035            id: NodeId::UNASSIGNED,
3036            inlines: vec![
3037                text("See "),
3038                Inline::Link {
3039                    id: NodeId::UNASSIGNED,
3040                    url: "#the-hunter".into(),
3041                    children: vec![text("the hunter")],
3042                    attributes: Attributes::default(),
3043                    position: None,
3044                    span: None,
3045                },
3046                text("."),
3047            ],
3048            attributes: Attributes::default(),
3049            position: None,
3050            span: None,
3051        });
3052        book.assign_node_ids();
3053        book
3054    }
3055
3056    /// The id of the first element of one name.
3057    fn id_of(tree: &StyleTree, element: &str) -> NodeId {
3058        let node = tree
3059            .nodes()
3060            .iter()
3061            .find(|node| node.element == element)
3062            .unwrap_or_else(|| panic!("no {element}"));
3063        NodeId::new(node.id)
3064    }
3065
3066    /// `content` on a pseudo-element reads literals and references in
3067    /// the order they are written. Literals side by side are one.
3068    #[test]
3069    fn content_reads_references_between_literals() {
3070        let book = linked();
3071        let after = |css: &str| {
3072            let tree = compile(&book, &format!("a::after {{ content: {css} }}"));
3073            assert!(tree.warnings().is_empty(), "{css}: {:?}", tree.warnings());
3074            tree.after(id_of(&tree, "a"))
3075                .map(|style| style.content.clone())
3076        };
3077        assert_eq!(
3078            after("\" (page \" target-counter(attr(href url), page) \")\""),
3079            Some(Content::Pieces(vec![
3080                ContentPiece::Text(" (page ".into()),
3081                ContentPiece::TargetCounter {
3082                    target: Target::Href,
3083                    style: CounterStyle::Decimal,
3084                },
3085                ContentPiece::Text(")".into()),
3086            ])),
3087        );
3088        assert_eq!(
3089            after("target-counter(\"#the-hunter\", page, upper-roman)"),
3090            Some(Content::Pieces(vec![ContentPiece::TargetCounter {
3091                target: Target::Url("#the-hunter".into()),
3092                style: CounterStyle::UpperRoman,
3093            }])),
3094        );
3095        assert_eq!(
3096            after("\"see \" target-text(attr(href))"),
3097            Some(Content::Pieces(vec![
3098                ContentPiece::Text("see ".into()),
3099                ContentPiece::TargetText {
3100                    target: Target::Href,
3101                },
3102            ])),
3103        );
3104        assert_eq!(after("\"a\" \"b\""), Some(Content::Text("ab".into())));
3105        assert_eq!(after("none"), None, "`none` generates nothing");
3106    }
3107
3108    /// `page` is the only counter a reference can print, and a
3109    /// function outside the subset is a diagnostic on `content`.
3110    #[test]
3111    fn a_reference_outside_the_subset_warns() {
3112        let book = linked();
3113        for css in [
3114            "a::after { content: target-counter(attr(href url), chapter) }",
3115            "a::after { content: target-counters(attr(href url), page, \".\") }",
3116            "a::after { content: target-counter(attr(title), page) }",
3117            "a::after { content: counter(page) }",
3118        ] {
3119            let tree = compile(&book, css);
3120            assert!(
3121                tree.warnings().iter().any(|warning| warning.message
3122                    == "Unsupported value for `content`. The declaration is ignored."),
3123                "{css}: {:?}",
3124                tree.warnings(),
3125            );
3126            assert!(tree.after(id_of(&tree, "a")).is_none(), "{css}");
3127        }
3128    }
3129
3130    /// A pseudo-element starts from the style of the element it
3131    /// belongs to, and a rule that names it outranks what it
3132    /// inherited.
3133    #[test]
3134    fn a_pseudo_element_inherits_from_its_element() {
3135        let book = linked();
3136        let tree = compile(
3137            &book,
3138            "a { font-size: 9pt; font-family: monospace; color: #336699 }
3139             a::before { content: \"[\" }
3140             a::after { content: \"]\"; color: #d6075e; font-size: 7pt }",
3141        );
3142        let link = id_of(&tree, "a");
3143        let before = tree.before(link).expect("`::before` generates text");
3144        assert_eq!(before.content, Content::Text("[".into()));
3145        assert_eq!(before.font_size, 9.0);
3146        assert_eq!(before.color, Color::rgb(0x33, 0x66, 0x99));
3147        assert_eq!(
3148            before.font_id,
3149            registry().generic(GenericFamily::Monospace).unwrap(),
3150        );
3151        let after = tree.after(link).expect("`::after` generates text");
3152        assert_eq!(after.font_size, 7.0);
3153        assert_eq!(after.color, Color::rgb(0xd6, 0x07, 0x5e));
3154
3155        // The element keeps its own style, and generates nothing
3156        // itself.
3157        assert_eq!(tree.style(link).content, Content::None);
3158        assert_eq!(tree.style(link).font_size, 9.0);
3159    }
3160
3161    /// `content: none` is the initial value, so a rule that names a
3162    /// pseudo-element and sets no `content` generates nothing.
3163    #[test]
3164    fn a_pseudo_element_with_no_content_generates_nothing() {
3165        let book = linked();
3166        let tree = compile(
3167            &book,
3168            "a::after { color: red } em::before { content: none } \
3169             p::after { height: 2pt } h1::before { content: none; height: 2pt }",
3170        );
3171        assert!(tree.after(id_of(&tree, "a")).is_none());
3172        assert!(tree.before(id_of(&tree, "em")).is_none());
3173        assert!(tree.after(id_of(&tree, "p")).is_none());
3174        assert!(tree.before(id_of(&tree, "h1")).is_none());
3175        assert!(tree.warnings().is_empty(), "{:?}", tree.warnings());
3176    }
3177
3178    /// Part: `::before` and `::after` parse and match on a block, and
3179    /// the cascade computes a style for each.
3180    #[test]
3181    fn a_pseudo_element_on_a_block_matches_and_computes_a_style() {
3182        let book = linked();
3183        let tree = compile(
3184            &book,
3185            "p::before { content: \"x\"; color: red }\np { font-size: 15pt }\n\
3186             h1::after { content: \"\"; height: 2pt }",
3187        );
3188        assert!(tree.warnings().is_empty(), "{:?}", tree.warnings());
3189        let before = tree
3190            .before(id_of(&tree, "p"))
3191            .expect("`p::before` generates");
3192        assert_eq!(before.content, Content::Text("x".into()));
3193        assert_eq!(before.color, Color::rgb(0xff, 0, 0));
3194        let after = tree
3195            .after(id_of(&tree, "h1"))
3196            .expect("`h1::after` generates");
3197        assert_eq!(after.content, Content::Text(String::new()));
3198        assert_eq!(after.height, Width::Points(2.0));
3199        assert!(tree.after(id_of(&tree, "p")).is_none());
3200        assert_eq!(first(&tree, "p").content, Content::None);
3201    }
3202
3203    /// Part: the style tree gives `::first-letter`, `::first-line`,
3204    /// `::before` and `::after` an id that no content node can have.
3205    /// The same book and stylesheet give the same ids.
3206    #[test]
3207    fn a_pseudo_element_has_an_id_no_content_node_has() {
3208        let book = linked();
3209        let css = "p::before { content: \"x\" } h1::after { content: \"\"; height: 2pt } \
3210                   p::first-letter { initial-letter: 3 } \
3211                   p::first-line { font-variant-caps: small-caps }";
3212        let tree = compile(&book, css);
3213        let p = id_of(&tree, "p");
3214        let before = tree
3215            .pseudo_element(p, PseudoElement::Before)
3216            .expect("`p::before` generates");
3217        assert_eq!(tree.pseudo_element(p, PseudoElement::After), None);
3218        assert_eq!(before.pseudo_element(), Some((p, PseudoElement::Before)));
3219        assert_eq!(before.element(), p);
3220        assert_eq!(p.pseudo_element(), None);
3221        assert_eq!(p.element(), p);
3222        assert_eq!(book.subtree(before), None, "the book holds no such node");
3223        assert!(tree.nodes().iter().all(|node| node.id != before.get()));
3224        assert_eq!(tree.style(before).content, Content::Text("x".into()));
3225
3226        let h1 = id_of(&tree, "h1");
3227        let after = tree
3228            .pseudo_element(h1, PseudoElement::After)
3229            .expect("`h1::after` generates");
3230        assert_ne!(after, before);
3231        assert_eq!(tree.style(after).height, Width::Points(2.0));
3232
3233        let letter = tree
3234            .pseudo_element(p, PseudoElement::FirstLetter)
3235            .expect("`p::first-letter` is styled");
3236        let line = tree
3237            .pseudo_element(p, PseudoElement::FirstLine)
3238            .expect("`p::first-line` is styled");
3239        assert_eq!(tree.pseudo_element(h1, PseudoElement::FirstLetter), None);
3240        let ids = [before, after, letter, line];
3241        for id in ids {
3242            assert_eq!(ids.iter().filter(|other| **other == id).count(), 1);
3243            assert_eq!(book.subtree(id), None, "the book holds no such node");
3244            assert!(tree.nodes().iter().all(|node| node.id != id.get()));
3245        }
3246        assert_eq!(letter.element(), p);
3247        assert_eq!(line.element(), p);
3248        assert!(std::ptr::eq(
3249            tree.style(letter),
3250            tree.first_letter(p).unwrap()
3251        ));
3252        assert!(std::ptr::eq(tree.style(line), tree.first_line(p).unwrap()));
3253
3254        let again = compile(&book, css);
3255        assert_eq!(again.pseudo_element(p, PseudoElement::Before), Some(before));
3256        assert_eq!(again.pseudo_element(h1, PseudoElement::After), Some(after));
3257        assert_eq!(
3258            again.pseudo_element(p, PseudoElement::FirstLetter),
3259            Some(letter)
3260        );
3261        assert_eq!(
3262            again.pseudo_element(p, PseudoElement::FirstLine),
3263            Some(line)
3264        );
3265    }
3266
3267    /// Part: `::before` and `::after` on an inline element have an id,
3268    /// the same as on a block.
3269    #[test]
3270    fn an_inline_pseudo_element_has_an_id_as_a_block_does() {
3271        let book = linked();
3272        let tree = compile(&book, "a::after { content: \" (link)\" }");
3273        let a = id_of(&tree, "a");
3274        let after = tree
3275            .pseudo_element(a, PseudoElement::After)
3276            .expect("`a::after` generates text");
3277        assert_eq!(after.pseudo_element(), Some((a, PseudoElement::After)));
3278        assert_eq!(after.element(), a);
3279        assert_eq!(tree.pseudo_element(a, PseudoElement::Before), None);
3280        assert_eq!(tree.style(after).content, Content::Text(" (link)".into()));
3281    }
3282
3283    /// An element with no box of its own takes no generated box. A
3284    /// sheet that asks for one is told so once, and the element is
3285    /// styled as though the rule were not there.
3286    #[test]
3287    fn a_pseudo_element_on_the_book_warns_and_generates_nothing() {
3288        let book = linked();
3289        let tree = compile(
3290            &book,
3291            "book::before { content: \"x\" }\nbook { font-size: 15pt }",
3292        );
3293        let told: Vec<&str> = tree
3294            .warnings()
3295            .iter()
3296            .map(|warning| warning.message.as_str())
3297            .collect();
3298        assert_eq!(
3299            told,
3300            ["Unsupported pseudo-element `::before` on `book`. Nothing is generated."],
3301        );
3302        assert!(tree.before(id_of(&tree, "book")).is_none());
3303        assert_eq!(first(&tree, "book").font_size, 15.0);
3304    }
3305
3306    /// Acceptance: a pseudo-element inherits the element's family and
3307    /// size, and a rule naming the pseudo-element beats it, however
3308    /// specific the rule on the element is.
3309    #[test]
3310    fn a_block_pseudo_element_inherits_and_its_own_rule_beats_the_element() {
3311        let book = linked();
3312        let tree = compile(
3313            &book,
3314            "section > h1#the-hunter { font-size: 20pt; font-family: monospace }\n\
3315             h1::before { content: \"x\" }\nh1::after { content: \"y\"; font-size: 8pt }",
3316        );
3317        let h1 = id_of(&tree, "h1");
3318        let mono = registry().generic(GenericFamily::Monospace).unwrap();
3319        let before = tree.before(h1).expect("`::before` generates");
3320        assert_eq!(before.font_size, 20.0);
3321        assert_eq!(before.font_id, mono);
3322        let after = tree.after(h1).expect("`::after` generates");
3323        assert_eq!(after.font_size, 8.0);
3324        assert_eq!(after.font_id, mono);
3325    }
3326
3327    /// Only a reference to a page asks for a second layout pass. The
3328    /// text of the target is in the book before anything is laid out.
3329    #[test]
3330    fn only_a_page_reference_counts_pages() {
3331        let book = linked();
3332        for (css, counts) in [
3333            ("", false),
3334            ("a::after { content: \" (see below)\" }", false),
3335            (
3336                "a::after { content: \" \" target-text(attr(href url)) }",
3337                false,
3338            ),
3339            (
3340                "a::after { content: \" \" target-counter(attr(href url), page) }",
3341                true,
3342            ),
3343            (
3344                "p::after { content: target-counter(\"#the-hunter\", page) }",
3345                true,
3346            ),
3347            ("p::after { content: target-text(\"#the-hunter\") }", false),
3348        ] {
3349            assert_eq!(compile(&book, css).counts_pages(), counts, "{css}");
3350        }
3351    }
3352
3353    /// `::first-line` cascades over the element the way
3354    /// `::first-letter` does, and what line layout reads back is what
3355    /// it changed rather than the whole computed style.
3356    #[test]
3357    fn first_line_cascades_over_the_element_it_belongs_to() {
3358        let book = sample();
3359        let tree = compile(
3360            &book,
3361            "p { font-size: 12pt; color: #112233 }
3362             h1 + p::first-line { font-variant-caps: small-caps; letter-spacing: 0.5pt }",
3363        );
3364        let Block::Paragraph { id, .. } = &book.sections[0].blocks[1] else {
3365            panic!("the second block is a paragraph");
3366        };
3367        let line = tree
3368            .first_line(*id)
3369            .expect("a rule named the paragraph's first line");
3370        assert_eq!(line.font_variant_caps, FontVariantCaps::SmallCaps);
3371        assert_eq!(line.font_size, 12.0, "the element's size is inherited");
3372        assert_eq!(line.color, first(&tree, "p").color);
3373
3374        let opening = tree.opening_line(*id).expect("the opening line's overlay");
3375        assert_eq!(opening.caps, Some(FontVariantCaps::SmallCaps));
3376        assert_eq!(opening.letter_spacing, Some(0.5));
3377        assert_eq!(opening.size, None, "nothing the rule left alone is set");
3378        assert_eq!(opening.color, None);
3379        assert_eq!(opening.transform, None);
3380
3381        // The element keeps its own style, and the sibling selector
3382        // in front of the pseudo-element still has to match.
3383        assert_eq!(first(&tree, "p").font_variant_caps, FontVariantCaps::Normal);
3384        let Block::Paragraph { id: second, .. } = &book.sections[0].blocks[2] else {
3385            panic!("the third block is a paragraph");
3386        };
3387        assert!(tree.first_line(*second).is_none());
3388        assert!(tree.opening_line(*second).is_none());
3389    }
3390
3391    /// `::first-line` takes the properties that change a run's width,
3392    /// its colour and the height of its line. Anything else warns
3393    /// naming the property, is dropped, and leaves the rest of the
3394    /// rule standing.
3395    #[test]
3396    fn a_property_outside_the_first_line_set_warns_and_is_dropped() {
3397        let book = sample();
3398        let tree = compile(
3399            &book,
3400            "p::first-line { margin-top: 2em; text-transform: uppercase }",
3401        );
3402        assert!(
3403            tree.warnings().iter().any(|warning| {
3404                warning.message
3405                    == "Unsupported property `margin-top` on `::first-line`. \
3406                        The declaration is ignored."
3407            }),
3408            "{:?}",
3409            tree.warnings(),
3410        );
3411        let Block::Paragraph { id, .. } = &book.sections[0].blocks[1] else {
3412            panic!("the second block is a paragraph");
3413        };
3414        let opening = tree.opening_line(*id).expect("the opening line's overlay");
3415        assert_eq!(opening.transform, Some(TextTransform::Uppercase));
3416        assert_eq!(
3417            tree.first_line(*id).unwrap().margin.top,
3418            0.0,
3419            "the margin the rule asked for was dropped",
3420        );
3421    }
3422
3423    /// Acceptance: `line-height` on `::first-line` does not warn, and
3424    /// reaches the overlay line layout reads. A rule that leaves it
3425    /// alone sets nothing.
3426    #[test]
3427    fn a_line_height_sets_on_a_first_line() {
3428        let book = sample();
3429        let tree = compile(
3430            &book,
3431            "p { line-height: 1.5 }
3432             h1 + p::first-line { line-height: 2 }
3433             p::first-line { color: #112233 }",
3434        );
3435        assert_eq!(
3436            tree.warnings()
3437                .iter()
3438                .filter(|warning| warning.message.contains("`::first-line`"))
3439                .collect::<Vec<_>>(),
3440            Vec::<&Warning>::new(),
3441        );
3442        let Block::Paragraph { id, .. } = &book.sections[0].blocks[1] else {
3443            panic!("the second block is a paragraph");
3444        };
3445        let opening = tree.opening_line(*id).expect("the opening line's overlay");
3446        assert_eq!(opening.line_height, Some(2.0));
3447        assert_eq!(
3448            first(&tree, "p").line_height,
3449            1.5,
3450            "the element keeps its own"
3451        );
3452
3453        let Block::Paragraph { id: second, .. } = &book.sections[0].blocks[2] else {
3454            panic!("the third block is a paragraph");
3455        };
3456        let untouched = tree.opening_line(*second).expect("the colour rule matched");
3457        assert_eq!(untouched.line_height, None);
3458    }
3459
3460    /// Acceptance: a length on `::first-line` is read against the
3461    /// first line's own `font-size`, not the paragraph's.
3462    #[test]
3463    fn a_first_line_length_is_read_against_its_own_size() {
3464        let book = sample();
3465        let tree = compile(
3466            &book,
3467            "p { font-size: 12pt }
3468             h1 + p::first-line { font-size: 8pt; line-height: 20pt }",
3469        );
3470        let Block::Paragraph { id, .. } = &book.sections[0].blocks[1] else {
3471            panic!("the second block is a paragraph");
3472        };
3473        let opening = tree.opening_line(*id).expect("the opening line's overlay");
3474        assert_eq!(opening.size, Some(8.0));
3475        assert_eq!(opening.line_height, Some(2.5));
3476    }
3477
3478    /// Acceptance: `font-family`, `font-style` and `font-weight` on
3479    /// `::first-line` warn about none of themselves, and each one
3480    /// reaches the overlay line layout reads.
3481    #[test]
3482    fn the_font_properties_set_on_a_first_line() {
3483        let book = sample();
3484        let mut registry = bundled_registry().expect("bundled font parses");
3485        let mut display =
3486            crate::fonts::FontSource::from_bytes(crate::fonts::BUNDLED_ITALIC.to_vec())
3487                .expect("the face parses");
3488        display.family = "display".into();
3489        registry.add(display).expect("the face registers");
3490        let css = "p { font-family: \"EB Garamond\" }
3491                   p::first-line { font-family: display; font-style: italic;
3492                                   font-weight: bold }";
3493        let tree =
3494            Stylesheets::parse(&[Source::author("author.css", css)]).compile(&book, &registry);
3495        assert_eq!(
3496            tree.warnings()
3497                .iter()
3498                .filter(|warning| warning.message.contains("`::first-line`"))
3499                .collect::<Vec<_>>(),
3500            Vec::<&Warning>::new(),
3501        );
3502
3503        let Block::Paragraph { id, .. } = &book.sections[0].blocks[1] else {
3504            panic!("the second block is a paragraph");
3505        };
3506        let face = tree
3507            .opening_line(*id)
3508            .expect("the opening line's overlay")
3509            .face
3510            .expect("the rule asked for another face");
3511        assert_eq!(face.italic, Some(true));
3512        assert_eq!(face.weight, Some(700));
3513        assert_eq!(
3514            registry
3515                .font_ref(face.family.expect("the rule named a family"))
3516                .map(|entry| entry.family.as_str()),
3517            Some("display"),
3518        );
3519    }
3520
3521    /// A book whose one paragraph nests `strong` inside `em`.
3522    fn nested() -> Book {
3523        let mut book = Book {
3524            metadata: Metadata::default(),
3525            sections: vec![Section {
3526                attributes: Default::default(),
3527                blocks: vec![Block::Paragraph {
3528                    id: NodeId::UNASSIGNED,
3529                    inlines: vec![
3530                        text("She said "),
3531                        Inline::Emphasis {
3532                            id: NodeId::UNASSIGNED,
3533                            children: vec![
3534                                text("never "),
3535                                Inline::Strong {
3536                                    id: NodeId::UNASSIGNED,
3537                                    children: vec![text("again")],
3538                                    attributes: Attributes::default(),
3539                                    position: None,
3540                                    span: None,
3541                                },
3542                            ],
3543                            attributes: Attributes::default(),
3544                            position: None,
3545                            span: None,
3546                        },
3547                        text("."),
3548                    ],
3549                    attributes: Attributes::default(),
3550                    position: None,
3551                    span: None,
3552                }],
3553                ..Default::default()
3554            }],
3555        };
3556        book.assign_node_ids();
3557        book
3558    }
3559
3560    /// Slope and weight reach the face through the cascade: `em` and
3561    /// `strong` set properties like any other rule, and `strong`
3562    /// inside `em` inherits the slope on its way to a bold italic
3563    /// face.
3564    #[test]
3565    fn emphasis_and_strong_resolve_to_their_own_faces() {
3566        let book = nested();
3567        let tree = defaults(&book, registry());
3568        let face = |italic, weight| {
3569            registry()
3570                .select("eb garamond", FaceAttributes { italic, weight })
3571                .unwrap()
3572                .id
3573        };
3574        assert_eq!(first(&tree, "p").font_id, face(false, 400));
3575        assert_eq!(first(&tree, "em").font_id, face(true, 400));
3576        assert_eq!(first(&tree, "strong").font_id, face(true, 700));
3577        // The cascade, not the element name: an author who unsets
3578        // the slope gets the upright bold cut under the same markup.
3579        let tree = compile(&book, "em { font-style: normal }");
3580        assert_eq!(first(&tree, "strong").font_id, face(false, 700));
3581    }
3582
3583    /// A face the registry cannot supply is a diagnostic and the
3584    /// nearest cut, once, however many nodes asked for it.
3585    #[test]
3586    fn a_face_the_registry_lacks_warns_and_lays_out_anyway() {
3587        let mut upright = FontRegistry::new();
3588        upright
3589            .add(crate::fonts::FontSource::from_bytes(BUNDLED_FONT.to_vec()).unwrap())
3590            .unwrap();
3591        upright
3592            .map_generic(GenericFamily::Serif, "eb garamond")
3593            .unwrap();
3594        let book = nested();
3595        let tree = Stylesheets::parse(&[]).compile(&book, &upright);
3596        assert_eq!(
3597            first(&tree, "em").font_id,
3598            first(&tree, "p").font_id,
3599            "there is no italic cut, so emphasis takes the upright one",
3600        );
3601        let complaints: Vec<&str> = tree
3602            .warnings()
3603            .iter()
3604            .map(|warning| warning.message.as_str())
3605            .filter(|message| message.contains("italic"))
3606            .collect();
3607        assert_eq!(
3608            complaints,
3609            vec!["eb garamond has no italic face. Italic text falls back to upright."],
3610        );
3611
3612        // A stack that resolves nothing at all says so, and the book
3613        // still lays out on the first registered face.
3614        let tree = compile(&book, "p { font-family: \"Nowhere\", \"Nor here\" }");
3615        assert_eq!(first(&tree, "p").font_id, 0);
3616        assert!(
3617            tree.warnings().iter().any(|warning| {
3618                warning.message
3619                    == "No registered font matches Nowhere, Nor here. \
3620                        The first registered font is used instead."
3621            }),
3622            "{:?}",
3623            tree.warnings(),
3624        );
3625    }
3626
3627    /// The display-typography properties parse, cascade and inherit:
3628    /// a rule on the book reaches the paragraph inside it, a rule on
3629    /// the paragraph overrides it, and `em` inside picks up what the
3630    /// paragraph set without being named.
3631    #[test]
3632    fn display_typography_parses_cascades_and_inherits() {
3633        let book = nested();
3634        let tree = compile(
3635            &book,
3636            "book { letter-spacing: 0.1em; font-variant-caps: small-caps;
3637                    text-transform: uppercase }
3638             p { letter-spacing: 2pt }",
3639        );
3640        let paragraph = first(&tree, "p");
3641        assert_eq!(paragraph.letter_spacing, 2.0, "the closer rule lost");
3642        assert_eq!(paragraph.font_variant_caps, FontVariantCaps::SmallCaps);
3643        assert_eq!(paragraph.text_transform, TextTransform::Uppercase);
3644        let emphasis = first(&tree, "em");
3645        assert_eq!(
3646            (
3647                emphasis.letter_spacing,
3648                emphasis.font_variant_caps,
3649                emphasis.text_transform,
3650            ),
3651            (2.0, FontVariantCaps::SmallCaps, TextTransform::Uppercase,),
3652            "emphasis did not inherit what the paragraph set",
3653        );
3654
3655        // `em` is a multiple of the element's own size, `normal` and
3656        // `none` are the initial values written out, and the defaults
3657        // are what a book gets when nothing says otherwise.
3658        let tree = compile(
3659            &book,
3660            "book { letter-spacing: 0.1em; text-transform: uppercase }
3661             p { font-size: 20pt; letter-spacing: 0.1em }
3662             em { letter-spacing: normal; text-transform: none;
3663                  font-variant-caps: normal }",
3664        );
3665        assert_eq!(first(&tree, "p").letter_spacing, 2.0);
3666        assert_eq!(first(&tree, "em").letter_spacing, 0.0);
3667        assert_eq!(first(&tree, "em").text_transform, TextTransform::None);
3668        let plain = first(&defaults(&book, registry()), "p");
3669        assert_eq!(plain.letter_spacing, 0.0);
3670        assert_eq!(plain.font_variant_caps, FontVariantCaps::Normal);
3671        assert_eq!(plain.text_transform, TextTransform::None);
3672
3673        // A value none of the three has is a diagnostic, not a rule.
3674        let tree = compile(&book, "p { text-transform: full-width }");
3675        assert!(
3676            tree.warnings().iter().any(|warning| {
3677                warning.message
3678                    == "Unsupported value for `text-transform`. The declaration is ignored."
3679            }),
3680            "{:?}",
3681            tree.warnings(),
3682        );
3683    }
3684
3685    /// Part: `font-feature-settings` reads a tag and a value, in
3686    /// each of the three ways a value is written, and it inherits.
3687    #[test]
3688    fn font_feature_settings_read_a_tag_and_a_value_and_inherit() {
3689        let book = nested();
3690        let tree = compile(
3691            &book,
3692            "book { font-feature-settings: \"ss01\" 1, \"liga\" off, \"onum\" }",
3693        );
3694        let asked = [
3695            FeatureSetting::new(*b"ss01", 1),
3696            FeatureSetting::new(*b"liga", 0),
3697            FeatureSetting::new(*b"onum", 1),
3698        ];
3699        assert_eq!(first(&tree, "p").font_feature_settings, asked);
3700        assert_eq!(
3701            first(&tree, "em").font_feature_settings,
3702            asked,
3703            "emphasis did not inherit what the book asked for",
3704        );
3705        assert!(
3706            first(&defaults(&book, registry()), "p")
3707                .font_feature_settings
3708                .is_empty(),
3709            "a book that asks for nothing asks for nothing",
3710        );
3711
3712        let tree = compile(&book, "p { font-feature-settings: normal }");
3713        assert!(first(&tree, "p").font_feature_settings.is_empty());
3714
3715        let tree = compile(&book, "p { font-feature-settings: ss01 }");
3716        assert!(
3717            tree.warnings().iter().any(|warning| warning.message
3718                == "Unsupported value for `font-feature-settings`. The declaration is ignored."),
3719            "{:?}",
3720            tree.warnings(),
3721        );
3722    }
3723
3724    /// Part: the `font-variant` longhands name a feature without
3725    /// spelling its tag, and the computed list merges over what the
3726    /// engine asks for, `font-feature-settings` last.
3727    #[test]
3728    fn the_font_variant_longhands_name_the_features_they_stand_for() {
3729        let book = nested();
3730        let tree = compile(
3731            &book,
3732            "p { font-variant-numeric: oldstyle-nums tabular-nums;
3733                 font-variant-ligatures: no-common-ligatures discretionary-ligatures;
3734                 font-variant-alternates: historical-forms;
3735                 font-feature-settings: \"onum\" 0, \"ss01\" 1 }",
3736        );
3737        let paragraph = first(&tree, "p");
3738        assert_eq!(
3739            paragraph.features(),
3740            [
3741                FeatureSetting::new(*b"liga", 0),
3742                FeatureSetting::new(*b"clig", 0),
3743                FeatureSetting::new(*b"dlig", 1),
3744                FeatureSetting::new(*b"onum", 1),
3745                FeatureSetting::new(*b"tnum", 1),
3746                FeatureSetting::new(*b"hist", 1),
3747                FeatureSetting::new(*b"onum", 0),
3748                FeatureSetting::new(*b"ss01", 1),
3749            ],
3750            "the sheet's own settings are read after the named forms",
3751        );
3752
3753        let plain = first(&defaults(&book, registry()), "p");
3754        assert!(plain.features().is_empty());
3755    }
3756
3757    /// Part: a face that carries none of a feature the sheet asked
3758    /// for is named once, and a feature turned off is not.
3759    #[test]
3760    fn a_face_without_a_requested_feature_is_named() {
3761        let book = nested();
3762        let tree = compile(
3763            &book,
3764            "book { font-feature-settings: \"zero\" 1 }
3765             p { font-feature-settings: \"zero\" 1, \"ss01\" 1 }",
3766        );
3767        let named: Vec<&str> = tree
3768            .warnings()
3769            .iter()
3770            .map(|warning| warning.message.as_str())
3771            .filter(|message| message.contains("feature"))
3772            .collect();
3773        assert_eq!(
3774            named,
3775            ["eb garamond has no `zero` feature. The text is set without it."],
3776            "{:?}",
3777            tree.warnings(),
3778        );
3779
3780        let quiet = compile(&book, "p { font-feature-settings: \"zero\" 0 }");
3781        assert!(
3782            !quiet
3783                .warnings()
3784                .iter()
3785                .any(|warning| warning.message.contains("feature")),
3786            "a feature asked to stay off is one the face need not carry: {:?}",
3787            quiet.warnings(),
3788        );
3789    }
3790
3791    /// `color` reads in each of the four forms the subset takes, and
3792    /// a form outside it is a diagnostic rather than a rule.
3793    #[test]
3794    fn colour_reads_in_every_form_the_subset_takes() {
3795        let book = sample();
3796        let tree = compile(
3797            &book,
3798            "h1 { color: darkred }
3799             p { color: #036 }
3800             blockquote { color: #b41e1e }
3801             em { color: rgb(0% 20% 100%) }",
3802        );
3803        assert_eq!(first(&tree, "h1").color, Color::rgb(139, 0, 0));
3804        assert_eq!(first(&tree, "p").color, Color::rgb(0, 51, 102));
3805        assert_eq!(first(&tree, "blockquote").color, Color::rgb(180, 30, 30));
3806        assert_eq!(first(&tree, "em").color, Color::rgb(0, 51, 255));
3807        assert_eq!(
3808            first(&defaults(&book, registry()), "p").color,
3809            Color::BLACK,
3810            "a book nothing coloured is set in black",
3811        );
3812
3813        // A name no colour has, and channels written half as
3814        // numbers and half as percentages, neither of which CSS
3815        // allows.
3816        for css in ["p { color: octarine }", "p { color: rgb(10, 20%, 30) }"] {
3817            let tree = compile(&book, css);
3818            assert!(
3819                tree.warnings().iter().any(|warning| warning.message
3820                    == "Unsupported value for `color`. The declaration is ignored."),
3821                "{css}: {:?}",
3822                tree.warnings(),
3823            );
3824        }
3825    }
3826
3827    /// Colour inherits: a rule on the section reaches the prose under
3828    /// it, and a rule on the heading beats what it inherited.
3829    #[test]
3830    fn a_colour_on_a_section_reaches_the_prose_under_it() {
3831        let book = sample();
3832        let tree = compile(
3833            &book,
3834            "section { color: #444444 }
3835             h1 { color: rgb(180 30 30) }",
3836        );
3837        assert_eq!(first(&tree, "p").color, Color::rgb(68, 68, 68));
3838        assert_eq!(first(&tree, "em").color, Color::rgb(68, 68, 68));
3839        assert_eq!(first(&tree, "h1").color, Color::rgb(180, 30, 30));
3840    }
3841
3842    /// `color` is the ink a box is set in and `background-color` is
3843    /// what is painted behind it. The text colour inherits and the
3844    /// background does not, so the emphasis inside a tinted paragraph
3845    /// takes the ink and leaves the tint.
3846    #[test]
3847    fn colour_inherits_where_a_background_does_not() {
3848        let book = nested();
3849        let tree = compile(
3850            &book,
3851            "p {\n  color: teal;\n  background-color: #f4f1ea;\n}\n",
3852        );
3853        assert!(tree.warnings().is_empty(), "{:?}", tree.warnings());
3854        assert_eq!(first(&tree, "p").color, Color::rgb(0, 128, 128));
3855        assert_eq!(
3856            first(&tree, "p").background.color,
3857            Some(Color::rgb(0xf4, 0xf1, 0xea))
3858        );
3859        assert_eq!(first(&tree, "em").color, Color::rgb(0, 128, 128));
3860        assert_eq!(first(&tree, "em").background.color, None);
3861    }
3862
3863    /// A face with no small capitals of its own is reported once,
3864    /// however many nodes asked for them, and the book is set anyway.
3865    /// A face that has them is not reported at all.
3866    #[test]
3867    fn a_face_without_small_capitals_says_so() {
3868        let book = nested();
3869        let bare = crate::fonts::registry_without_substitutions();
3870        let css = "p, em, strong { font-variant-caps: small-caps }";
3871        let tree = Stylesheets::parse(&[Source::author("author.css", css)]).compile(&book, &bare);
3872        let complaints: Vec<&str> = tree
3873            .warnings()
3874            .iter()
3875            .map(|warning| warning.message.as_str())
3876            .filter(|message| message.contains("small capitals"))
3877            .collect();
3878        assert_eq!(
3879            complaints,
3880            vec!["eb garamond has no small capitals. Falling back to reduced capitals."],
3881        );
3882
3883        let tree = compile(&book, css);
3884        assert!(
3885            !tree
3886                .warnings()
3887                .iter()
3888                .any(|warning| warning.message.contains("small capitals")),
3889            "the bundled face has small capitals: {:?}",
3890            tree.warnings(),
3891        );
3892    }
3893
3894    /// Styles are interned: a book of thousands of nodes computes a
3895    /// handful of distinct styles, and every node points at one.
3896    #[test]
3897    fn styles_are_shared_between_nodes() {
3898        let book = sample();
3899        let tree = defaults(&book, registry());
3900        assert!(
3901            tree.styles().len() < tree.nodes().len(),
3902            "{} styles for {} nodes",
3903            tree.styles().len(),
3904            tree.nodes().len()
3905        );
3906        for node in tree.nodes() {
3907            assert!((node.style as usize) < tree.styles().len());
3908        }
3909        // A real node id resolves to the style its element got: the
3910        // section is the second element, after the book itself.
3911        assert_eq!(
3912            tree.style(book.sections[0].id),
3913            &tree.styles()[tree.nodes()[1].style as usize]
3914        );
3915    }
3916}