1mod 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
60pub const USER_AGENT_CSS: &str = include_str!("style/ua.css");
63
64pub trait FontLoader {
71 fn load(&self, url: &str) -> Option<Vec<u8>>;
74}
75
76pub struct NoFonts;
78
79impl FontLoader for NoFonts {
80 fn load(&self, _url: &str) -> Option<Vec<u8>> {
81 None
82 }
83}
84
85#[derive(Debug, Clone, PartialEq, Serialize)]
87pub struct NodeStyle {
88 pub id: u32,
90 pub element: &'static str,
92 pub style: u32,
94 #[serde(skip_serializing_if = "Option::is_none")]
97 pub first_letter: Option<u32>,
98 #[serde(skip_serializing_if = "Option::is_none")]
101 pub first_line: Option<u32>,
102 #[serde(skip_serializing_if = "Option::is_none")]
105 pub before: Option<u32>,
106 #[serde(skip_serializing_if = "Option::is_none")]
109 pub after: Option<u32>,
110}
111
112#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
115#[serde(rename_all = "snake_case")]
116pub enum Situation {
117 First(Side),
119 Body(Side),
121 Blank,
123}
124
125impl Situation {
126 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
138pub struct PageQuery<'a> {
139 pub name: Option<&'a str>,
141 pub situation: Situation,
143}
144
145#[derive(Debug, Clone, PartialEq, Serialize)]
148pub struct PageStyle {
149 pub geometry: PageGeometry,
151 #[serde(skip_serializing_if = "properties::no_background")]
153 pub background: Background,
154 pub boxes: Vec<MarginBoxStyle>,
156}
157
158impl PageStyle {
159 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#[derive(Debug, Clone, PartialEq, Serialize)]
169pub struct MarginBoxStyle {
170 pub which: MarginBox,
172 pub content: Content,
174 pub style: ComputedStyle,
177}
178
179#[derive(Debug, Clone, PartialEq, Serialize)]
181pub struct PageMaster {
182 pub page: Option<String>,
184 pub situation: Situation,
186 pub style: PageStyle,
188}
189
190#[derive(Debug, Clone, Serialize)]
192pub struct StyleTree {
193 styles: Vec<ComputedStyle>,
196 nodes: Vec<NodeStyle>,
198 masters: Vec<PageMaster>,
200 #[serde(skip)]
203 by_node: Vec<u32>,
204 #[serde(skip)]
206 initial_by_node: Vec<Option<u32>>,
207 #[serde(skip)]
209 first_line_by_node: Vec<Option<u32>>,
210 #[serde(skip)]
212 before_by_node: Vec<Option<u32>>,
213 #[serde(skip)]
215 after_by_node: Vec<Option<u32>>,
216 #[serde(skip)]
218 counts_pages: bool,
219 #[serde(skip)]
221 refers: bool,
222 #[serde(skip)]
224 notes: NodeId,
225 warnings: Vec<Warning>,
226}
227
228impl StyleTree {
229 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 pub fn notes_area(&self) -> NodeId {
250 self.notes
251 }
252
253 pub fn paragraph(&self, id: NodeId) -> ParagraphStyle {
255 self.style(id).paragraph()
256 }
257
258 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 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 pub fn opening_line(&self, id: NodeId) -> Option<FirstLine> {
276 Some(self.first_line(id)?.first_line_over(self.style(id)))
277 }
278
279 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 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 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 pub fn counts_pages(&self) -> bool {
317 self.counts_pages
318 }
319
320 pub fn refers(&self) -> bool {
323 self.refers
324 }
325
326 pub fn root(&self) -> &ComputedStyle {
328 &self.styles[0]
329 }
330
331 pub fn styles(&self) -> &[ComputedStyle] {
333 &self.styles
334 }
335
336 pub fn nodes(&self) -> &[NodeStyle] {
338 &self.nodes
339 }
340
341 pub fn warnings(&self) -> &[Warning] {
343 &self.warnings
344 }
345
346 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 pub fn default_page(&self) -> &PageStyle {
357 self.page(PageQuery {
358 name: None,
359 situation: Situation::Body(Side::Recto),
360 })
361 }
362
363 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
377fn 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
423fn 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 matching.sort_by_key(|(level, rule)| (*level, rule.specificity()));
440
441 let root_size = root.font_size;
442 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
517fn 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
567fn 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
603fn 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
626fn 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#[derive(Debug)]
650pub struct Stylesheets {
651 sheets: Vec<Sheet>,
652 warnings: Vec<Warning>,
654 parsed: usize,
656}
657
658impl Stylesheets {
659 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 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 pub(crate) fn font_warnings(&self) -> &[Warning] {
696 &self.warnings[self.parsed..]
697 }
698
699 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 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 pub fn warnings(&self) -> &[Warning] {
730 &self.warnings
731 }
732
733 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 pub fn compile(&self, book: &Book, registry: &FontRegistry) -> StyleTree {
773 cascade(book, &self.sheets, registry, self.warnings.clone())
774 }
775}
776
777#[derive(Debug, Clone, PartialEq)]
779pub struct WrittenSheet {
780 pub origin: Origin,
782 pub rules: Vec<WrittenRule>,
784 pub pages: Vec<WrittenPage>,
786 pub faces: Vec<FontFace>,
788}
789
790#[derive(Debug, Clone, PartialEq)]
792pub struct WrittenRule {
793 pub selectors: Vec<String>,
795 pub declarations: Vec<Written>,
798 pub position: SheetPosition,
800}
801
802#[derive(Debug, Clone, PartialEq)]
804pub struct WrittenPage {
805 pub selector: String,
807 pub position: SheetPosition,
809}
810
811pub fn defaults(book: &Book, registry: &FontRegistry) -> StyleTree {
813 Stylesheets::parse(&[]).compile(book, registry)
814}
815
816fn 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
858const FALLBACK: &str = "Falling back to another registered font.";
861
862fn 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
873fn 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
884fn 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 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 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 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 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
1089fn 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(§ion.blocks, source, &mut first, &mut warnings);
1098 }
1099 warnings
1100}
1101
1102fn 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
1161fn 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
1188fn 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
1209type Applicable = (u8, u32, usize, usize, usize);
1212
1213fn 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
1266fn 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 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
1319fn 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
1328fn 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
1340fn 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
1352fn 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
1364fn report_all(warnings: &mut Vec<Warning>, found: Vec<Warning>) {
1366 for warning in found {
1367 report(warnings, Some(warning));
1368 }
1369}
1370
1371fn 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
1417fn 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
1434fn 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
1463fn 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
1477fn 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 #[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 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 fn compile(book: &Book, css: &str) -> StyleTree {
1626 Stylesheets::parse(&[Source::author("author.css", css)]).compile(book, registry())
1627 }
1628
1629 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 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 #[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 #[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 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 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 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 #[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 assert_eq!(nth(&tree, "p", 2).z_index, 0);
1789 assert_eq!(first(&tree, "section").z_index, 0);
1790 }
1791
1792 #[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 #[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 #[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 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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 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 let both = page("@page { column-count: 2; column-width: 100pt; column-gap: 16pt }");
2220 assert_eq!(both.column_count(), 2);
2221
2222 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 #[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 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 assert_eq!(first(&tree, "h1").text_indent, 6.0);
2258 assert_eq!(first(&tree, "em").font_weight, 700);
2259
2260 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 #[test]
2279 fn author_css_overrides_the_built_in_sheet() {
2280 let book = sample();
2281 let tree = compile(&book, "* { font-size: 13pt } p { font-size: 12pt }");
2284 assert_eq!(first(&tree, "p").font_size, 12.0);
2285 let tree = compile(&book, "p { font-size: 12pt } p { font-size: 14pt }");
2287 assert_eq!(first(&tree, "p").font_size, 14.0);
2288 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 #[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 #[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 #[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 #[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 #[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 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 assert_eq!(tree.masters().len(), 10);
2448 }
2449
2450 #[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 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 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 #[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 #[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 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 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 #[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 #[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 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 #[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, ®istry);
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 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 #[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, ®istry);
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 #[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 #[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 #[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 #[test]
2758 fn the_property_table_says_what_inherits() {
2759 let book = sample();
2760 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 #[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 #[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 #[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 #[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 #[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 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 #[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 #[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 assert_eq!(nth(&tree, "p", 1).margin.left, 0.0);
2957 }
2958
2959 #[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 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 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 #[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 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 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 #[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 #[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 #[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 assert_eq!(tree.style(link).content, Content::None);
3158 assert_eq!(tree.style(link).font_size, 9.0);
3159 }
3160
3161 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 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 #[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 #[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 #[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 #[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, ®istry);
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 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 #[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 let tree = compile(&book, "em { font-style: normal }");
3580 assert_eq!(first(&tree, "strong").font_id, face(false, 700));
3581 }
3582
3583 #[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 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 #[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 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 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 #[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 #[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 #[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 #[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 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 #[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 #[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 #[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 #[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 assert_eq!(
3912 tree.style(book.sections[0].id),
3913 &tree.styles()[tree.nodes()[1].style as usize]
3914 );
3915 }
3916}