Skip to main content

fleuron/style/properties/
computed.rs

1//! What one node computes to: every property resolved, ready for
2//! the box tree to ask.
3
4use std::collections::BTreeMap;
5
6use serde::Serialize;
7
8use crate::fonts::{FeatureSetting, GenericFamily};
9use crate::lines::HangingPunctuation;
10
11use super::Declaration;
12use super::background::{
13    Background, BackgroundPosition, BackgroundSize, SizeSource, no_background,
14};
15use super::counter::{Content, ListStyleType, StringSet};
16use super::edges::{Border, BorderRadius, CornerRadius, Edges};
17use super::exclusion::{
18    Clear, Coord, Float, Inset, Position, ShapeOutside, ShapePoint, ShapeSource, WrapFlow,
19};
20use super::value::{
21    BlendMode, BorderCollapse, BoxDecorationBreak, Break, Color, ColumnSpan, DecorationLine,
22    DecorationStyle, Family, FontStyle, FontVariantAlternates, FontVariantCaps,
23    FontVariantLigatures, FontVariantNumeric, Hyphens, Length, NORMAL_LINE_HEIGHT, TextAlign,
24    TextDecoration, TextJustify, TextTransform, Width,
25};
26
27/// One node's resolved style: what every downstream pass reads.
28#[derive(Debug, Clone, PartialEq, Serialize)]
29pub struct ComputedStyle {
30    /// The face this style shapes with, resolved against the
31    /// registry. Family, slope and weight chose it; layout only needs
32    /// the answer.
33    pub font_id: u16,
34    /// The families asked for, in order, kept for diagnostics and for
35    /// the snapshot the style tree is reviewed through.
36    pub font_family: Vec<Family>,
37    /// Font size in points.
38    pub font_size: f32,
39    /// Upright or italic.
40    pub font_style: FontStyle,
41    /// Weight on the CSS 1–1000 scale.
42    pub font_weight: u16,
43    /// What text and rules are painted in.
44    pub color: Color,
45    /// Line height as a unitless multiple of the font size.
46    pub line_height: f32,
47    /// Extra advance after every glyph, in points, from
48    /// `letter-spacing`.
49    pub letter_spacing: f32,
50    /// Which capitals the run is drawn with.
51    pub font_variant_caps: FontVariantCaps,
52    /// The features the sheet asked the face for, from
53    /// `font-feature-settings`. They are asked for after the ones the
54    /// `font-variant` longhands name, so a tag in both is set here.
55    #[serde(skip_serializing_if = "Vec::is_empty")]
56    pub font_feature_settings: Vec<FeatureSetting>,
57    /// Which ligatures the run is set with.
58    #[serde(skip_serializing_if = "default_ligatures")]
59    pub font_variant_ligatures: FontVariantLigatures,
60    /// Which figures the run is set with.
61    #[serde(skip_serializing_if = "default_numeric")]
62    pub font_variant_numeric: FontVariantNumeric,
63    /// Which alternate glyphs the run is set with.
64    #[serde(skip_serializing_if = "default_alternates")]
65    pub font_variant_alternates: FontVariantAlternates,
66    /// What the run's letters are transformed to before shaping.
67    pub text_transform: TextTransform,
68    /// Which rules are drawn across the run, from
69    /// `text-decoration-line`.
70    #[serde(skip_serializing_if = "undecorated")]
71    pub text_decoration_line: DecorationLine,
72    /// What those rules are painted in, from
73    /// `text-decoration-color`. `None` is the colour of the text.
74    #[serde(skip_serializing_if = "Option::is_none")]
75    pub text_decoration_color: Option<Color>,
76    /// How each rule is drawn, from `text-decoration-style`.
77    #[serde(skip_serializing_if = "solid")]
78    pub text_decoration_style: DecorationStyle,
79    /// How thick each rule is, in points, from
80    /// `text-decoration-thickness`. `None` is the thickness the face
81    /// declares.
82    #[serde(skip_serializing_if = "Option::is_none")]
83    pub text_decoration_thickness: Option<f32>,
84    /// How lines fill the measure.
85    pub text_align: TextAlign,
86    /// What justification opens up to fill it.
87    pub text_justify: TextJustify,
88    /// Which marks may hang past the measure.
89    pub hanging_punctuation: HangingPunctuation,
90    /// First-line indent in points.
91    pub text_indent: f32,
92    /// Whether words may break at syllable boundaries.
93    pub hyphens: Hyphens,
94    /// Lines that must be left at the bottom of a fragment.
95    pub orphans: u16,
96    /// Lines that must be moved to the top of the next one.
97    pub widows: u16,
98    /// The named page this element's pages take, from `page`.
99    pub page: Option<String>,
100    /// What the element paints in place of children it has none of:
101    /// the ornament a thematic break is set with.
102    pub content: Content,
103    /// The named strings this element sets when the flow reaches it,
104    /// from `string-set`. This is where a running head's text comes
105    /// from.
106    #[serde(skip_serializing_if = "Vec::is_empty")]
107    pub string_set: Vec<StringSet>,
108    /// The folio the page this element opens takes, from
109    /// `counter-reset: page`.
110    #[serde(skip_serializing_if = "Option::is_none")]
111    pub counter_reset: Option<u32>,
112    /// The number the first note under this element takes, from
113    /// `counter-reset: note`. On the footnote area it restarts the
114    /// numbering on every page.
115    #[serde(skip_serializing_if = "Option::is_none")]
116    pub note_reset: Option<u32>,
117    /// Lines an initial letter is sunk over, from `initial-letter`.
118    /// Fewer than two is no drop cap.
119    pub initial_letter: u16,
120    /// Whether the element sits in the flow or against the page.
121    #[serde(skip_serializing_if = "in_flow")]
122    pub position: Position,
123    /// What the insets say, for an element that is against the page.
124    #[serde(skip_serializing_if = "unplaced")]
125    pub inset: Edges<Inset>,
126    /// Which layer the block paints in, from `z-index`. Higher paints
127    /// later, and `auto` is layer 0.
128    #[serde(skip_serializing_if = "ground_layer")]
129    pub z_index: i32,
130    /// How much of what the block paints shows, from `opacity`: 1 is
131    /// all of it and 0 is none. The blocks inside it show that much
132    /// of their own.
133    #[serde(skip_serializing_if = "opaque")]
134    pub opacity: f32,
135    /// How what the element draws is mixed with what is under it,
136    /// from `mix-blend-mode`.
137    #[serde(skip_serializing_if = "BlendMode::is_normal")]
138    pub mix_blend_mode: BlendMode,
139    /// The mode of the nearest element around this one that names
140    /// one. An element is part of what the elements around it draw.
141    #[serde(skip)]
142    pub blend_around: BlendMode,
143    /// Which side of this element the prose sets on, from `wrap-flow`.
144    #[serde(skip_serializing_if = "wraps_nothing")]
145    pub wrap_flow: WrapFlow,
146    /// Which side of its column an image in the flow moves to, from
147    /// `float`.
148    #[serde(skip_serializing_if = "floats_nowhere")]
149    pub float: Float,
150    /// Which floats the block starts below, from `clear`.
151    #[serde(skip_serializing_if = "clears_nothing")]
152    pub clear: Clear,
153    /// The contour the prose sets around, from `shape-outside`.
154    #[serde(skip_serializing_if = "wraps_its_box")]
155    pub shape_outside: ShapeOutside,
156    /// How far the prose keeps off that contour, in points, from
157    /// `shape-margin`.
158    #[serde(skip_serializing_if = "no_shape_margin")]
159    pub shape_margin: f32,
160    /// Margins in points.
161    pub margin: Edges,
162    /// Padding in points, between the border and the content.
163    #[serde(skip_serializing_if = "no_padding")]
164    pub padding: Edges,
165    /// The four border edges.
166    #[serde(skip_serializing_if = "no_border")]
167    pub border: Edges<Border>,
168    /// How far each corner of the border box is rounded, from
169    /// `border-radius`. The background and the border follow the
170    /// corners.
171    #[serde(skip_serializing_if = "square")]
172    pub border_radius: BorderRadius,
173    /// What is painted behind the block: a tint, and an image over
174    /// it.
175    #[serde(skip_serializing_if = "no_background")]
176    pub background: Background,
177    /// What the decoration does where a page break splits the block.
178    #[serde(skip_serializing_if = "sliced")]
179    pub box_decoration_break: BoxDecorationBreak,
180    /// The width the box is asked to take, from `width`. A table reads
181    /// it off the cells of its first row to size its columns.
182    #[serde(skip_serializing_if = "auto_width")]
183    pub width: Width,
184    /// The height the content box is asked to take, from `height`.
185    #[serde(skip_serializing_if = "auto_width")]
186    pub height: Width,
187    /// The least height the content box takes, from `min-height`.
188    #[serde(skip_serializing_if = "auto_width")]
189    pub min_height: Width,
190    /// The most width an image takes, from `max-width`. `Auto` is
191    /// `none`.
192    #[serde(skip_serializing_if = "auto_width")]
193    pub max_width: Width,
194    /// The most height an image takes, from `max-height`. `Auto` is
195    /// `none`.
196    #[serde(skip_serializing_if = "auto_width")]
197    pub max_height: Width,
198    /// Whether a table's cells share their borders, from
199    /// `border-collapse`.
200    #[serde(skip_serializing_if = "separate")]
201    pub border_collapse: BorderCollapse,
202    /// The marker a list item is set with, from `list-style-type`.
203    #[serde(skip_serializing_if = "disc")]
204    pub list_style_type: ListStyleType,
205    /// Where a page break falls before this element.
206    pub break_before: Break,
207    /// Where one falls after it.
208    pub break_after: Break,
209    /// Whether this element may be split across pages.
210    pub break_inside: Break,
211    /// Whether this element is set across every column of a divided
212    /// page, from `column-span`.
213    #[serde(skip_serializing_if = "one_column")]
214    pub column_span: ColumnSpan,
215    /// The custom properties in force, by name, each with every
216    /// `var()` in its value already replaced. A child inherits them.
217    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
218    pub custom: BTreeMap<String, String>,
219}
220
221impl ComputedStyle {
222    /// The initial value of every property: what the root computes to
223    /// before any rule matches it.
224    pub fn initial() -> ComputedStyle {
225        ComputedStyle {
226            font_id: 0,
227            font_family: vec![Family::Generic(GenericFamily::Serif)],
228            font_size: 12.0,
229            font_style: FontStyle::Normal,
230            font_weight: 400,
231            color: Color::BLACK,
232            line_height: NORMAL_LINE_HEIGHT,
233            letter_spacing: 0.0,
234            font_variant_caps: FontVariantCaps::Normal,
235            font_feature_settings: Vec::new(),
236            font_variant_ligatures: FontVariantLigatures::NORMAL,
237            font_variant_numeric: FontVariantNumeric::NORMAL,
238            font_variant_alternates: FontVariantAlternates::Normal,
239            text_transform: TextTransform::None,
240            text_decoration_line: DecorationLine::NONE,
241            text_decoration_color: None,
242            text_decoration_style: DecorationStyle::Solid,
243            text_decoration_thickness: None,
244            text_align: TextAlign::Left,
245            text_justify: TextJustify::InterWord,
246            hanging_punctuation: HangingPunctuation::NONE,
247            text_indent: 0.0,
248            hyphens: Hyphens::None,
249            orphans: 2,
250            widows: 2,
251            page: None,
252            content: Content::None,
253            string_set: Vec::new(),
254            counter_reset: None,
255            note_reset: None,
256            initial_letter: 0,
257            position: Position::Static,
258            inset: Edges::all(Inset::Auto),
259            z_index: 0,
260            opacity: 1.0,
261            mix_blend_mode: BlendMode::Normal,
262            blend_around: BlendMode::Normal,
263            wrap_flow: WrapFlow::Auto,
264            float: Float::None,
265            clear: Clear::None,
266            shape_outside: ShapeOutside::None,
267            shape_margin: 0.0,
268            margin: Edges::all(0.0),
269            padding: Edges::all(0.0),
270            border: Edges::all(Border::NONE),
271            border_radius: BorderRadius::SQUARE,
272            background: Background::NONE,
273            box_decoration_break: BoxDecorationBreak::Slice,
274            width: Width::Auto,
275            height: Width::Auto,
276            min_height: Width::Auto,
277            max_width: Width::Auto,
278            max_height: Width::Auto,
279            border_collapse: BorderCollapse::Separate,
280            list_style_type: ListStyleType::Disc,
281            break_before: Break::Auto,
282            break_after: Break::Auto,
283            break_inside: Break::Auto,
284            column_span: ColumnSpan::None,
285            custom: BTreeMap::new(),
286        }
287    }
288
289    /// A child's starting point: inherited properties as they stand,
290    /// the rest back at their initial values.
291    pub fn inherit(&self) -> ComputedStyle {
292        ComputedStyle {
293            margin: Edges::all(0.0),
294            padding: Edges::all(0.0),
295            border: Edges::all(Border::NONE),
296            border_radius: BorderRadius::SQUARE,
297            background: Background::NONE,
298            box_decoration_break: BoxDecorationBreak::Slice,
299            width: Width::Auto,
300            height: Width::Auto,
301            min_height: Width::Auto,
302            max_width: Width::Auto,
303            max_height: Width::Auto,
304            content: Content::None,
305            string_set: Vec::new(),
306            counter_reset: None,
307            note_reset: None,
308            initial_letter: 0,
309            position: Position::Static,
310            inset: Edges::all(Inset::Auto),
311            z_index: 0,
312            opacity: 1.0,
313            mix_blend_mode: BlendMode::Normal,
314            blend_around: self.blend(),
315            wrap_flow: WrapFlow::Auto,
316            float: Float::None,
317            clear: Clear::None,
318            shape_outside: ShapeOutside::None,
319            shape_margin: 0.0,
320            break_before: Break::Auto,
321            break_after: Break::Auto,
322            break_inside: Break::Auto,
323            column_span: ColumnSpan::None,
324            ..self.clone()
325        }
326    }
327
328    /// Applies one declaration. `parent_size` is what `em` and
329    /// percentages in `font-size` measure against; `root_size` is
330    /// what `rem` does.
331    pub fn apply(&mut self, declaration: &Declaration, parent_size: f32, root_size: f32) {
332        match declaration {
333            Declaration::FontFamily(families) => self.font_family = families.clone(),
334            Declaration::FontSize(length) => {
335                self.font_size = length.to_points(parent_size, root_size).max(0.0)
336            }
337            Declaration::FontStyle(style) => self.font_style = *style,
338            Declaration::FontWeight(weight) => self.font_weight = *weight,
339            Declaration::Color(color) => self.color = *color,
340            Declaration::LineHeight(line_height) => {
341                self.line_height = line_height.to_multiple(self.font_size, root_size)
342            }
343            Declaration::LetterSpacing(length) => {
344                self.letter_spacing = length.to_points(self.font_size, root_size)
345            }
346            Declaration::FontVariantCaps(caps) => self.font_variant_caps = *caps,
347            Declaration::FontFeatureSettings(settings) => {
348                self.font_feature_settings = settings.clone()
349            }
350            Declaration::FontVariantLigatures(ligatures) => {
351                self.font_variant_ligatures = *ligatures
352            }
353            Declaration::FontVariantNumeric(numeric) => self.font_variant_numeric = *numeric,
354            Declaration::FontVariantAlternates(alternates) => {
355                self.font_variant_alternates = *alternates
356            }
357            Declaration::TextTransform(transform) => self.text_transform = *transform,
358            Declaration::TextDecorationLine(line) => self.text_decoration_line = *line,
359            Declaration::TextDecorationColor(color) => self.text_decoration_color = *color,
360            Declaration::TextDecorationStyle(style) => self.text_decoration_style = *style,
361            Declaration::TextDecorationThickness(length) => {
362                self.text_decoration_thickness =
363                    length.map(|length| length.to_points(self.font_size, root_size).max(0.0))
364            }
365            Declaration::TextAlign(align) => self.text_align = *align,
366            Declaration::TextJustify(justify) => self.text_justify = *justify,
367            Declaration::HangingPunctuation(hanging) => self.hanging_punctuation = *hanging,
368            Declaration::TextIndent(length) => {
369                self.text_indent = length.to_points(self.font_size, root_size)
370            }
371            Declaration::Hyphens(hyphens) => self.hyphens = *hyphens,
372            Declaration::Orphans(lines) => self.orphans = *lines,
373            Declaration::Widows(lines) => self.widows = *lines,
374            Declaration::Page(name) => self.page = name.clone(),
375            Declaration::Content(content) => self.content = content.clone(),
376            Declaration::StringSet(sets) => self.string_set = sets.clone(),
377            Declaration::CounterReset(counters) => {
378                self.counter_reset = counters.page;
379                self.note_reset = counters.note;
380            }
381            Declaration::InitialLetter(lines) => self.initial_letter = *lines,
382            Declaration::Position(position) => self.position = *position,
383            Declaration::Inset(edge, length) => {
384                *self.inset.edge(*edge) = match length {
385                    None => Inset::Auto,
386                    Some(Length::Percent(percent)) => Inset::Percent(*percent),
387                    Some(length) => Inset::Points(length.to_points(self.font_size, root_size)),
388                }
389            }
390            Declaration::ZIndex(layer) => self.z_index = *layer,
391            Declaration::Opacity(opacity) => self.opacity = *opacity,
392            Declaration::MixBlendMode(mode) => self.mix_blend_mode = *mode,
393            Declaration::WrapFlow(wrap) => self.wrap_flow = *wrap,
394            Declaration::Float(float) => self.float = *float,
395            Declaration::Clear(clear) => self.clear = *clear,
396            Declaration::ShapeOutside(shape) => {
397                self.shape_outside = match shape {
398                    ShapeSource::None => ShapeOutside::None,
399                    ShapeSource::Auto => ShapeOutside::Auto,
400                    ShapeSource::Polygon(points) => ShapeOutside::Polygon(
401                        points
402                            .iter()
403                            .map(|(x, y)| ShapePoint {
404                                x: Coord::of(*x, self.font_size, root_size),
405                                y: Coord::of(*y, self.font_size, root_size),
406                            })
407                            .collect(),
408                    ),
409                }
410            }
411            Declaration::ShapeMargin(length) => {
412                self.shape_margin = length.to_points(self.font_size, root_size).max(0.0)
413            }
414            Declaration::Margin(edge, length) => {
415                *self.margin.edge(*edge) = length.to_points(self.font_size, root_size)
416            }
417            Declaration::Padding(edge, length) => {
418                *self.padding.edge(*edge) = length.to_points(self.font_size, root_size).max(0.0)
419            }
420            Declaration::BorderStyle(edge, style) => self.border.edge(*edge).style = *style,
421            Declaration::BorderWidth(edge, length) => {
422                self.border.edge(*edge).width = length.to_points(self.font_size, root_size).max(0.0)
423            }
424            Declaration::BorderColor(edge, color) => self.border.edge(*edge).color = *color,
425            Declaration::BorderRadius(corner, x, y) => {
426                *self.border_radius.corner(*corner) = CornerRadius {
427                    x: Coord::of(*x, self.font_size, root_size),
428                    y: Coord::of(*y, self.font_size, root_size),
429                }
430            }
431            Declaration::BackgroundColor(color) => self.background.color = *color,
432            Declaration::BackgroundImage(url) => self.background.image = url.clone(),
433            Declaration::BackgroundRepeat(repeat) => self.background.repeat = *repeat,
434            Declaration::BackgroundSize(size) => {
435                self.background.size = computed_size(*size, self.font_size, root_size)
436            }
437            Declaration::BackgroundPosition(x, y) => {
438                self.background.position = BackgroundPosition {
439                    x: Coord::of(*x, self.font_size, root_size),
440                    y: Coord::of(*y, self.font_size, root_size),
441                }
442            }
443            Declaration::BoxDecorationBreak(value) => self.box_decoration_break = *value,
444            Declaration::Width(width) => self.width = self.size(*width, root_size),
445            Declaration::Height(height) => self.height = self.size(*height, root_size),
446            Declaration::MinHeight(height) => self.min_height = self.size(*height, root_size),
447            Declaration::MaxWidth(width) => self.max_width = self.size(*width, root_size),
448            Declaration::MaxHeight(height) => self.max_height = self.size(*height, root_size),
449            Declaration::BorderCollapse(value) => self.border_collapse = *value,
450            Declaration::ListStyleType(value) => self.list_style_type = *value,
451            Declaration::BreakBefore(value) => self.break_before = *value,
452            Declaration::BreakAfter(value) => self.break_after = *value,
453            Declaration::BreakInside(value) => self.break_inside = *value,
454            Declaration::ColumnSpan(value) => self.column_span = *value,
455            // The cascade resolves both before anything is applied.
456            Declaration::Custom(_) | Declaration::Pending(_) => {}
457        }
458    }
459
460    /// Sets the longhand `like` names back to what `base` holds for
461    /// it. `base` is the style before any declaration applied, so a
462    /// property that inherits takes its parent's value and one that
463    /// does not takes its initial value.
464    pub(crate) fn reset(&mut self, like: &Declaration, base: &ComputedStyle) {
465        match like {
466            Declaration::FontFamily(_) => self.font_family = base.font_family.clone(),
467            Declaration::FontSize(_) => self.font_size = base.font_size,
468            Declaration::FontStyle(_) => self.font_style = base.font_style,
469            Declaration::FontWeight(_) => self.font_weight = base.font_weight,
470            Declaration::Color(_) => self.color = base.color,
471            Declaration::LineHeight(_) => self.line_height = base.line_height,
472            Declaration::LetterSpacing(_) => self.letter_spacing = base.letter_spacing,
473            Declaration::FontVariantCaps(_) => self.font_variant_caps = base.font_variant_caps,
474            Declaration::FontFeatureSettings(_) => {
475                self.font_feature_settings = base.font_feature_settings.clone()
476            }
477            Declaration::FontVariantLigatures(_) => {
478                self.font_variant_ligatures = base.font_variant_ligatures
479            }
480            Declaration::FontVariantNumeric(_) => {
481                self.font_variant_numeric = base.font_variant_numeric
482            }
483            Declaration::FontVariantAlternates(_) => {
484                self.font_variant_alternates = base.font_variant_alternates
485            }
486            Declaration::TextTransform(_) => self.text_transform = base.text_transform,
487            Declaration::TextDecorationLine(_) => {
488                self.text_decoration_line = base.text_decoration_line
489            }
490            Declaration::TextDecorationColor(_) => {
491                self.text_decoration_color = base.text_decoration_color
492            }
493            Declaration::TextDecorationStyle(_) => {
494                self.text_decoration_style = base.text_decoration_style
495            }
496            Declaration::TextDecorationThickness(_) => {
497                self.text_decoration_thickness = base.text_decoration_thickness
498            }
499            Declaration::TextAlign(_) => self.text_align = base.text_align,
500            Declaration::TextJustify(_) => self.text_justify = base.text_justify,
501            Declaration::HangingPunctuation(_) => {
502                self.hanging_punctuation = base.hanging_punctuation
503            }
504            Declaration::TextIndent(_) => self.text_indent = base.text_indent,
505            Declaration::Hyphens(_) => self.hyphens = base.hyphens,
506            Declaration::Orphans(_) => self.orphans = base.orphans,
507            Declaration::Widows(_) => self.widows = base.widows,
508            Declaration::Page(_) => self.page = base.page.clone(),
509            Declaration::Content(_) => self.content = base.content.clone(),
510            Declaration::StringSet(_) => self.string_set = base.string_set.clone(),
511            Declaration::CounterReset(_) => {
512                self.counter_reset = base.counter_reset;
513                self.note_reset = base.note_reset;
514            }
515            Declaration::InitialLetter(_) => self.initial_letter = base.initial_letter,
516            Declaration::Position(_) => self.position = base.position,
517            Declaration::Inset(edge, _) => *self.inset.edge(*edge) = base.inset.get(*edge),
518            Declaration::ZIndex(_) => self.z_index = base.z_index,
519            Declaration::Opacity(_) => self.opacity = base.opacity,
520            Declaration::MixBlendMode(_) => self.mix_blend_mode = base.mix_blend_mode,
521            Declaration::WrapFlow(_) => self.wrap_flow = base.wrap_flow,
522            Declaration::Float(_) => self.float = base.float,
523            Declaration::Clear(_) => self.clear = base.clear,
524            Declaration::ShapeOutside(_) => self.shape_outside = base.shape_outside.clone(),
525            Declaration::ShapeMargin(_) => self.shape_margin = base.shape_margin,
526            Declaration::Margin(edge, _) => *self.margin.edge(*edge) = base.margin.get(*edge),
527            Declaration::Padding(edge, _) => *self.padding.edge(*edge) = base.padding.get(*edge),
528            Declaration::BorderStyle(edge, _) => {
529                self.border.edge(*edge).style = base.border.get(*edge).style
530            }
531            Declaration::BorderWidth(edge, _) => {
532                self.border.edge(*edge).width = base.border.get(*edge).width
533            }
534            Declaration::BorderColor(edge, _) => {
535                self.border.edge(*edge).color = base.border.get(*edge).color
536            }
537            Declaration::BorderRadius(corner, ..) => {
538                *self.border_radius.corner(*corner) = base.border_radius.get(*corner)
539            }
540            Declaration::BackgroundColor(_) => self.background.color = base.background.color,
541            Declaration::BackgroundImage(_) => {
542                self.background.image = base.background.image.clone()
543            }
544            Declaration::BackgroundRepeat(_) => self.background.repeat = base.background.repeat,
545            Declaration::BackgroundSize(_) => self.background.size = base.background.size,
546            Declaration::BackgroundPosition(..) => {
547                self.background.position = base.background.position
548            }
549            Declaration::BoxDecorationBreak(_) => {
550                self.box_decoration_break = base.box_decoration_break
551            }
552            Declaration::Width(_) => self.width = base.width,
553            Declaration::Height(_) => self.height = base.height,
554            Declaration::MinHeight(_) => self.min_height = base.min_height,
555            Declaration::MaxWidth(_) => self.max_width = base.max_width,
556            Declaration::MaxHeight(_) => self.max_height = base.max_height,
557            Declaration::BorderCollapse(_) => self.border_collapse = base.border_collapse,
558            Declaration::ListStyleType(_) => self.list_style_type = base.list_style_type,
559            Declaration::BreakBefore(_) => self.break_before = base.break_before,
560            Declaration::BreakAfter(_) => self.break_after = base.break_after,
561            Declaration::BreakInside(_) => self.break_inside = base.break_inside,
562            Declaration::ColumnSpan(_) => self.column_span = base.column_span,
563            Declaration::Custom(_) | Declaration::Pending(_) => {}
564        }
565    }
566
567    /// What a written size computes to. A percentage stays one,
568    /// because the box it measures against is sized in the layout
569    /// pass.
570    fn size(&self, written: Option<Length>, root_size: f32) -> Width {
571        match written {
572            None => Width::Auto,
573            Some(Length::Percent(percent)) => Width::Percent(percent.max(0.0)),
574            Some(length) => Width::Points(length.to_points(self.font_size, root_size).max(0.0)),
575        }
576    }
577
578    /// Whether the block asks for a height of its own content box.
579    pub fn sized(&self) -> bool {
580        self.height != Width::Auto || self.min_height != Width::Auto
581    }
582
583    /// What this style, computed for `::first-line`, changes about
584    /// the element it was computed beside.
585    pub fn first_line_over(&self, element: &ComputedStyle) -> crate::lines::FirstLine {
586        fn set<T>(differs: bool, value: T) -> Option<T> {
587            differs.then_some(value)
588        }
589        let face = crate::lines::Face {
590            family: set(self.font_family != element.font_family, self.font_id),
591            italic: set(
592                self.font_style != element.font_style,
593                self.font_style == FontStyle::Italic,
594            ),
595            weight: set(self.font_weight != element.font_weight, self.font_weight),
596        };
597        crate::lines::FirstLine {
598            face: (face != crate::lines::Face::default()).then_some(face),
599            size: set(self.font_size != element.font_size, self.font_size),
600            line_height: set(self.line_height != element.line_height, self.line_height),
601            letter_spacing: set(
602                self.letter_spacing != element.letter_spacing,
603                self.letter_spacing,
604            ),
605            caps: set(
606                self.font_variant_caps != element.font_variant_caps,
607                self.font_variant_caps,
608            ),
609            transform: set(
610                self.text_transform != element.text_transform,
611                self.text_transform,
612            ),
613            color: set(self.color != element.color, self.color),
614            decoration: set(self.decoration() != element.decoration(), self.decoration()),
615        }
616    }
617
618    /// This block's border box inside `measure`, laid out at `x` from
619    /// the enclosing content box's leading edge: `(leading edge,
620    /// width)`, with only the margins taken off.
621    pub fn border_box(&self, x: f32, measure: f32) -> (f32, f32) {
622        (
623            x + self.margin.left,
624            (measure - self.margin.inline()).max(0.0),
625        )
626    }
627
628    /// Whether prose is set around this element rather than over it:
629    /// the sheet has taken it out of the flow, and it excludes a side.
630    ///
631    /// This is the one place a contour is read, so it is also what
632    /// decides whether one is traced. An element still in the flow
633    /// takes a band of its own and nothing sets beside it, so a
634    /// contour on it would answer a question nobody asks.
635    pub fn excludes(&self) -> bool {
636        self.position == Position::Absolute && self.wrap_flow != WrapFlow::Auto
637    }
638
639    /// This block's content box inside `measure`: `(leading edge, the
640    /// measure its lines break to)`. Margin, border and padding come
641    /// off both edges, and the leading edge moves in by what they
642    /// take on the left.
643    pub fn content_box(&self, x: f32, measure: f32) -> (f32, f32) {
644        let border = self.border.widths();
645        let leading = self.margin.left + border.left + self.padding.left;
646        let trailing = self.margin.right + border.right + self.padding.right;
647        (x + leading, (measure - leading - trailing).max(0.0))
648    }
649
650    /// The box this style paints around the runs of an inline
651    /// element, and `None` where it paints none and takes no width.
652    ///
653    /// Padding counts even where nothing is painted over it: it is
654    /// width, and the line breaks against it.
655    pub fn inline_box(&self) -> Option<crate::lines::InlineBox> {
656        let padding = self.padding;
657        let border = self.border.widths();
658        let paints = self.background.paints() || self.border.paints();
659        let spaced = padding != Edges::all(0.0);
660        (paints || spaced).then_some(crate::lines::InlineBox {
661            padding,
662            border,
663            cloned: self.box_decoration_break == BoxDecorationBreak::Clone,
664        })
665    }
666
667    /// The mode what this element draws is mixed in: its own, and
668    /// otherwise the one the elements around it draw in.
669    pub fn blend(&self) -> BlendMode {
670        match self.mix_blend_mode {
671            BlendMode::Normal => self.blend_around,
672            mode => mode,
673        }
674    }
675
676    /// Everything line layout needs from a style.
677    pub fn paragraph(&self) -> crate::lines::ParagraphStyle {
678        crate::lines::ParagraphStyle {
679            font_id: self.font_id,
680            size: self.font_size,
681            color: self.color,
682            line_height: self.line_height,
683            letter_spacing: self.letter_spacing,
684            caps: self.font_variant_caps,
685            features: self.features(),
686            transform: self.text_transform,
687            decoration: self.decoration(),
688            blend: self.blend(),
689        }
690    }
691
692    /// Every feature this style asks the face for, in the order the
693    /// shaper reads them: what the `font-variant` longhands name,
694    /// then what `font-feature-settings` spells out. A tag in both
695    /// takes the value written last, which is the one the sheet
696    /// spelled.
697    pub fn features(&self) -> Vec<FeatureSetting> {
698        let mut settings = self.font_variant_ligatures.settings();
699        settings.extend(self.font_variant_numeric.settings());
700        settings.extend(self.font_variant_alternates.settings());
701        settings.extend(self.font_feature_settings.iter().copied());
702        settings
703    }
704
705    /// What is drawn across this style's runs, the four longhands
706    /// gathered into one value.
707    pub fn decoration(&self) -> TextDecoration {
708        TextDecoration {
709            line: self.text_decoration_line,
710            color: self.text_decoration_color,
711            style: self.text_decoration_style,
712            thickness: self.text_decoration_thickness,
713        }
714    }
715}
716
717/// What the cascade makes of a written `background-size`: `em` and
718/// `rem` against the font size in force, a percentage kept as one,
719/// because the box it measures against is sized in the layout pass.
720pub(crate) fn computed_size(size: SizeSource, font_size: f32, root_size: f32) -> BackgroundSize {
721    let axis =
722        |length: Option<Length>| length.map(|length| Coord::of(length, font_size, root_size));
723    match size {
724        SizeSource::Auto => BackgroundSize::Auto,
725        SizeSource::Cover => BackgroundSize::Cover,
726        SizeSource::Contain => BackgroundSize::Contain,
727        SizeSource::Fixed(width, height) => BackgroundSize::Fixed {
728            width: axis(width),
729            height: axis(height),
730        },
731    }
732}
733
734fn default_ligatures(ligatures: &FontVariantLigatures) -> bool {
735    *ligatures == FontVariantLigatures::NORMAL
736}
737
738fn default_numeric(numeric: &FontVariantNumeric) -> bool {
739    *numeric == FontVariantNumeric::NORMAL
740}
741
742fn default_alternates(alternates: &FontVariantAlternates) -> bool {
743    *alternates == FontVariantAlternates::Normal
744}
745
746fn in_flow(position: &Position) -> bool {
747    *position == Position::Static
748}
749
750fn unplaced(inset: &Edges<Inset>) -> bool {
751    *inset == Edges::all(Inset::Auto)
752}
753
754fn ground_layer(layer: &i32) -> bool {
755    *layer == 0
756}
757
758fn opaque(opacity: &f32) -> bool {
759    *opacity == 1.0
760}
761
762fn wraps_nothing(wrap: &WrapFlow) -> bool {
763    *wrap == WrapFlow::Auto
764}
765
766fn floats_nowhere(float: &Float) -> bool {
767    *float == Float::None
768}
769
770fn clears_nothing(clear: &Clear) -> bool {
771    *clear == Clear::None
772}
773
774fn no_padding(padding: &Edges) -> bool {
775    *padding == Edges::all(0.0)
776}
777
778fn no_border(border: &Edges<Border>) -> bool {
779    *border == Edges::all(Border::NONE)
780}
781
782fn square(radius: &BorderRadius) -> bool {
783    *radius == BorderRadius::SQUARE
784}
785
786fn sliced(value: &BoxDecorationBreak) -> bool {
787    *value == BoxDecorationBreak::Slice
788}
789
790fn undecorated(line: &DecorationLine) -> bool {
791    !line.draws()
792}
793
794fn solid(style: &DecorationStyle) -> bool {
795    *style == DecorationStyle::Solid
796}
797
798fn auto_width(width: &Width) -> bool {
799    *width == Width::Auto
800}
801
802fn separate(collapse: &BorderCollapse) -> bool {
803    *collapse == BorderCollapse::Separate
804}
805
806fn disc(marker: &ListStyleType) -> bool {
807    *marker == ListStyleType::Disc
808}
809
810fn one_column(span: &ColumnSpan) -> bool {
811    *span == ColumnSpan::None
812}
813
814fn no_shape_margin(margin: &f32) -> bool {
815    *margin == 0.0
816}
817
818fn wraps_its_box(shape: &ShapeOutside) -> bool {
819    *shape == ShapeOutside::None
820}
821
822#[cfg(test)]
823#[cfg(test)]
824mod tests {
825    use super::*;
826    use crate::style::properties::{
827        Coord, CounterStyle, Declaration, Length, ShapeOutside, ShapeSource,
828    };
829
830    /// Part: `ComputedStyle` carries the custom properties in force,
831    /// and a child inherits them.
832    #[test]
833    fn a_child_inherits_the_custom_properties() {
834        assert!(ComputedStyle::initial().custom.is_empty());
835        let mut style = ComputedStyle::initial();
836        style.custom.insert("--accent".into(), "#d6075e".into());
837        assert_eq!(style.inherit().custom, style.custom);
838    }
839
840    /// Part: `ComputedStyle` carries the properties of an inline
841    /// box. A style that paints nothing and takes no width has none,
842    /// and padding alone is enough for one, because padding is width.
843    #[test]
844    fn an_inline_box_is_the_padding_border_and_background_of_a_style() {
845        let initial = ComputedStyle::initial();
846        assert_eq!(initial.inline_box(), None);
847
848        let mut padded = initial.clone();
849        padded.padding = Edges::all(4.0);
850        let box_ = padded.inline_box().expect("padding alone makes a box");
851        assert_eq!((box_.leading(), box_.above()), (4.0, 4.0));
852        assert!(!box_.cloned);
853
854        let mut tinted = initial.clone();
855        tinted.background.color = Some(Color::BLACK);
856        assert!(tinted.inline_box().is_some());
857
858        let mut ruled = initial.clone();
859        ruled.border = Edges::all(Border {
860            style: super::super::edges::BorderStyle::Solid,
861            width: 1.0,
862            color: None,
863        });
864        ruled.box_decoration_break = BoxDecorationBreak::Clone;
865        let box_ = ruled.inline_box().expect("a border makes a box");
866        assert_eq!(box_.border, Edges::all(1.0));
867        assert!(box_.cloned);
868    }
869
870    /// Folios spell out in every style the subset supports, and a
871    /// value a style has no spelling for falls back to decimal.
872    #[test]
873    fn counter_styles_spell_their_values() {
874        let spell = |style: CounterStyle, values: [u32; 4]| {
875            values.map(|value| style.format(value)).join(" ")
876        };
877        assert_eq!(spell(CounterStyle::Decimal, [1, 4, 9, 40]), "1 4 9 40");
878        assert_eq!(spell(CounterStyle::LowerRoman, [1, 4, 9, 40]), "i iv ix xl");
879        assert_eq!(spell(CounterStyle::UpperRoman, [1, 4, 9, 40]), "I IV IX XL");
880        assert_eq!(spell(CounterStyle::LowerAlpha, [1, 4, 26, 27]), "a d z aa");
881        assert_eq!(spell(CounterStyle::UpperAlpha, [1, 4, 26, 27]), "A D Z AA");
882        assert_eq!(CounterStyle::LowerRoman.format(0), "0");
883        assert_eq!(CounterStyle::LowerRoman.format(4000), "4000");
884        assert_eq!(CounterStyle::LowerAlpha.format(0), "0");
885    }
886
887    /// A polygon point written as a length computes to points against
888    /// the font size in force. One written as a percentage stays a
889    /// percentage, because the box it measures against is the image's
890    /// and the image is sized in the layout pass.
891    #[test]
892    fn a_polygon_keeps_its_percentages_and_computes_its_lengths() {
893        let mut style = ComputedStyle::initial();
894        style.font_size = 10.0;
895        style.apply(
896            &Declaration::ShapeOutside(ShapeSource::Polygon(vec![
897                (Length::Em(2.0), Length::Percent(50.0)),
898                (Length::Points(3.0), Length::Rem(1.0)),
899                (Length::Percent(100.0), Length::Percent(100.0)),
900            ])),
901            10.0,
902            16.0,
903        );
904        let ShapeOutside::Polygon(points) = &style.shape_outside else {
905            panic!(
906                "the polygon did not reach the style: {:?}",
907                style.shape_outside
908            );
909        };
910        assert_eq!(points[0].x, Coord::Points(20.0));
911        assert_eq!(points[0].y, Coord::Percent(50.0));
912        assert_eq!(points[1].x, Coord::Points(3.0));
913        assert_eq!(points[1].y, Coord::Points(16.0));
914        assert_eq!(points[2].x.to_points(80.0), 80.0);
915        assert_eq!(points[2].y.to_points(40.0), 40.0);
916
917        style.apply(&Declaration::ShapeMargin(Length::Em(1.5)), 10.0, 16.0);
918        assert_eq!(style.shape_margin, 15.0);
919    }
920
921    /// Part: `height` and `min-height` compute as lengths and
922    /// percentages. A length in `em` resolves against the font size in
923    /// force, and a percentage stays a percentage until layout
924    /// resolves it against the content box.
925    #[test]
926    fn height_and_min_height_compute_as_lengths_and_percentages() {
927        let mut style = ComputedStyle::initial();
928        style.font_size = 10.0;
929        assert!(!style.sized());
930        style.apply(&Declaration::Height(Some(Length::Em(3.0))), 10.0, 16.0);
931        style.apply(
932            &Declaration::MinHeight(Some(Length::Percent(25.0))),
933            10.0,
934            16.0,
935        );
936        assert_eq!(style.height, Width::Points(30.0));
937        assert_eq!(style.min_height, Width::Percent(25.0));
938        assert_eq!(style.min_height.resolve(540.0), Some(135.0));
939        assert!(style.sized());
940        assert_eq!(style.inherit().height, Width::Auto);
941        assert_eq!(style.inherit().min_height, Width::Auto);
942        style.apply(&Declaration::Height(None), 10.0, 16.0);
943        assert_eq!(style.height, Width::Auto);
944    }
945
946    /// Part: `width`, `height`, `max-width` and `max-height` compute
947    /// as lengths and percentages, and a child does not inherit them.
948    #[test]
949    fn image_sizes_compute_as_lengths_and_percentages_and_do_not_inherit() {
950        let mut style = ComputedStyle::initial();
951        style.font_size = 10.0;
952        style.apply(&Declaration::Width(Some(Length::Points(200.0))), 10.0, 16.0);
953        style.apply(
954            &Declaration::Height(Some(Length::Percent(50.0))),
955            10.0,
956            16.0,
957        );
958        style.apply(&Declaration::MaxWidth(Some(Length::Em(12.0))), 10.0, 16.0);
959        style.apply(
960            &Declaration::MaxHeight(Some(Length::Percent(40.0))),
961            10.0,
962            16.0,
963        );
964        assert_eq!(style.width, Width::Points(200.0));
965        assert_eq!(style.height, Width::Percent(50.0));
966        assert_eq!(style.max_width, Width::Points(120.0));
967        assert_eq!(style.max_height, Width::Percent(40.0));
968
969        let child = style.inherit();
970        assert_eq!(
971            [child.width, child.height, child.max_width, child.max_height],
972            [Width::Auto; 4]
973        );
974
975        style.apply(&Declaration::MaxWidth(None), 10.0, 16.0);
976        assert_eq!(style.max_width, Width::Auto);
977    }
978
979    /// Part: `position: relative` computes, and an inset written as a
980    /// percentage stays a percentage until layout resolves it against
981    /// the page area.
982    /// `left` outranks `right` and `top` outranks `bottom`.
983    #[test]
984    fn insets_keep_their_percentages_and_offset_a_relative_box() {
985        use crate::style::properties::{Edge, Inset, Position};
986        let mut style = ComputedStyle::initial();
987        style.font_size = 10.0;
988        style.apply(&Declaration::Position(Position::Relative), 10.0, 16.0);
989        style.apply(
990            &Declaration::Inset(Edge::Top, Some(Length::Em(-1.2))),
991            10.0,
992            16.0,
993        );
994        style.apply(
995            &Declaration::Inset(Edge::Bottom, Some(Length::Points(40.0))),
996            10.0,
997            16.0,
998        );
999        style.apply(
1000            &Declaration::Inset(Edge::Right, Some(Length::Percent(10.0))),
1001            10.0,
1002            16.0,
1003        );
1004        assert_eq!(style.position, Position::Relative);
1005        assert_eq!(style.inset.top, Inset::Points(-12.0));
1006        assert_eq!(style.inset.right, Inset::Percent(10.0));
1007        assert_eq!(style.inset.right.resolve(300.0), Some(30.0));
1008        assert_eq!(style.inset.left.resolve(300.0), None);
1009        assert_eq!(style.inset.offset((300.0, 500.0)), (-30.0, -12.0));
1010    }
1011}