//! Computed style and the one table that applies every CSS property. //! //! Layout properties land directly in a `taffy::Style`; paint and text //! properties in [`Computed`]. Shorthands call the longhand handlers, so //! each property has exactly one implementation. use std::collections::{HashMap, HashSet}; use std::hash::{BuildHasher, Hasher}; use std::sync::OnceLock; use foldhash::quality::FixedState; use taffy::geometry::MinMax; use taffy::prelude::*; use taffy::style::Overflow; use crate::color::{parse_color, Rgba}; use crate::css::{Decl, Prop, Tok}; use crate::geometry::{Length, Units}; // ========================================================================== // Computed style #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum DisplayKind { None, Block, Inline, InlineBlock, Flex, InlineFlex, Grid, InlineGrid, Contents, ListItem, Table, TableRowGroup, TableRow, TableCell, TableCaption, } impl DisplayKind { pub fn is_inline_level(self) -> bool { matches!(self, DisplayKind::Inline | DisplayKind::InlineBlock | DisplayKind::InlineFlex | DisplayKind::InlineGrid) } } /// `user-select`: whether, and how, the text of an element can be selected. /// `contain` is read as `text`; `auto` is resolved against the parent (see /// [`Computed::inherit`]) and is `text` for ordinary content. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum UserSelect { #[default] Auto, None, Text, /// One click selects the whole element. All, } /// `app-region`: what an element is to a window whose title bar the app draws (not inherited: /// an element is part of the nearest area around it). #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum AppRegion { #[default] Auto, /// The app's own, inside a drag area (Chromium's `no-drag`). NoDrag, Area(crate::window_kind::WindowControlArea), } #[derive(Clone, Copy, Debug, PartialEq)] pub enum TextAlign { Left, Center, Right, Justify, /// The line's start (left in `ltr`, right in `rtl`): the initial value. Start, End, } impl TextAlign { /// Left, right, center or justify, in direction `rtl` or not. pub(crate) const fn physical(self, rtl: bool) -> TextAlign { match self { TextAlign::Start if rtl => TextAlign::Right, TextAlign::Start => TextAlign::Left, TextAlign::End if rtl => TextAlign::Left, TextAlign::End => TextAlign::Right, a => a, } } } #[derive(Clone, Copy, Debug, PartialEq)] pub enum WhiteSpace { Normal, NoWrap, Pre, PreWrap, PreLine, /// `break-spaces`: as `pre-wrap`, but lines may break after every preserved space. BreakSpaces, } #[derive(Clone, Copy, Debug, PartialEq)] pub enum TextTransform { None, Upper, Lower, Capitalize, } #[derive(Clone, Copy, Debug, PartialEq)] pub enum LineHeight { Normal, Factor(f32), Px(f32), } #[derive(Clone, Copy, Debug, PartialEq)] pub enum ListStyle { None, Disc, Circle, Square, Decimal, LowerAlpha, UpperAlpha, LowerRoman, UpperRoman, } #[derive(Clone, Copy, Debug, PartialEq)] pub enum VAlign { Baseline, Sub, Super, /// `top`: the top of the line box (`text-top` / `-bottom`, by the parent's text, are baseline). Top, /// `middle`: the middle of the line box. Middle, /// `bottom`: its bottom. Bottom, } /// `border-style` / `outline-style` (`none` and `hidden` clear the width instead). #[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] pub enum BorderStyle { #[default] Solid, Dashed, Dotted, Double, Groove, Ridge, Inset, Outset, } impl BorderStyle { fn parse(s: &str) -> Option { Some(match s { "solid" | "none" | "hidden" | "auto" => BorderStyle::Solid, "dashed" => BorderStyle::Dashed, "dotted" => BorderStyle::Dotted, "double" => BorderStyle::Double, "groove" => BorderStyle::Groove, "ridge" => BorderStyle::Ridge, "inset" => BorderStyle::Inset, "outset" => BorderStyle::Outset, _ => return None, }) } } /// `text-decoration-style`. #[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] pub enum DecoStyle { #[default] Solid, Double, Dotted, Dashed, Wavy, } /// A box edge for `background-clip` / `background-origin`. #[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] pub enum BoxEdge { #[default] Border, Padding, Content, } impl BoxEdge { fn parse(s: &str) -> Option { Some(match s { "border-box" => BoxEdge::Border, "padding-box" => BoxEdge::Padding, "content-box" => BoxEdge::Content, _ => return None, }) } } /// `counter-reset` / `counter-set` / `counter-increment` of one element. #[derive(Clone, Debug, PartialEq, Default)] pub struct CounterOps { pub reset: Vec<(Box, i32)>, pub set: Vec<(Box, i32)>, pub increment: Vec<(Box, i32)>, } #[derive(Clone, Debug, PartialEq)] pub struct Gradient { pub shape: GradientShape, /// Colour stops, with their positions on the gradient line when given (`50%`, `75px`, /// `calc(100% - 10px)`). pub stops: Vec<(Rgba, Option)>, } /// Which way a gradient runs (CSS Images 3 §3.1, §3.2). #[derive(Clone, Copy, Debug, PartialEq)] pub enum GradientShape { /// Along a line at `angle_deg` (0 = to top, 90 = to right). Linear { angle_deg: f32 }, /// Out from a centre: a circle or an ellipse. Radial(Radial), } /// A `radial-gradient()`'s ending shape: a circle (one radius) or an ellipse, its size and its /// centre (`at `, against the box). #[derive(Clone, Copy, Debug, PartialEq)] pub struct Radial { pub circle: bool, pub size: RadialSize, pub at: [Pos; 2], } /// How big a radial gradient's ending shape is. #[derive(Clone, Copy, Debug, PartialEq)] pub enum RadialSize { /// `closest-side`, `farthest-side`, `closest-corner`, `farthest-corner` (the default). Extent { corner: bool, farthest: bool }, /// The radii, x and y (a circle's are the same length); a percentage is of the box's /// width / height. Radii(Pos, Pos), } impl Gradient { /// The stops at fractions of a gradient line `len` px long (CSS Images 3 §3.5.3: a first or /// last stop without a position is at the start or end, a position before an earlier one is /// moved up to it, and stops without one are spaced evenly between the ones around them). pub fn resolved(&self, len: f32) -> Vec<(Rgba, f32)> { let n = self.stops.len(); let len = len.max(1e-3); let mut at: Vec> = self.stops.iter() // to 1/64 px: `calc(20%)` and `20px` on a 100px line are the same stop .map(|(_, p)| p.map(|p| (taffy::ResolveOrZero::resolve_or_zero(p, Some(len), crate::tree::resolve_calc) * 64.0).round() / 64.0 / len)) .collect(); if let Some(f) = at.first_mut() { f.get_or_insert(0.0); } if let Some(l) = at.last_mut() { l.get_or_insert(1.0); } let mut high = f32::NEG_INFINITY; for p in at.iter_mut().flatten() { high = high.max(*p); *p = high; } let mut out: Vec<(Rgba, f32)> = Vec::with_capacity(n); let mut k = 0; while k < n { if let Some(p) = at[k] { out.push((self.stops[k].0, p)); k += 1; continue; } // a run of stops without positions, between the ones before and after let start = out.last().map_or(0.0, |s| s.1); let end = (k..n).find_map(|j| at[j].map(|p| (j, p))).unwrap_or((n, 1.0)); let steps = (end.0 - k + 1) as f32; for j in k..end.0 { out.push((self.stops[j].0, start + (end.1 - start) * (j - k + 1) as f32 / steps)); } k = end.0; } out } } #[derive(Clone, Copy, Debug, PartialEq)] pub struct Shadow { pub x: f32, pub y: f32, pub blur: f32, pub spread: f32, pub color: Rgba, pub inset: bool, } /// A position along one axis: `frac` of the free space plus `px` /// (`left` = 0, `center` = 0.5, `75%`, `10px`, `right 10px` ...). #[derive(Clone, Copy, Debug, PartialEq)] pub struct Pos { pub frac: f32, pub px: f32, } impl Pos { pub const START: Pos = Pos { frac: 0.0, px: 0.0 }; pub const CENTER: Pos = Pos { frac: 0.5, px: 0.0 }; /// Offset into `free` pixels of room. pub fn at(self, free: f32) -> f32 { free * self.frac + self.px } } /// `object-fit`. #[derive(Clone, Copy, Debug, PartialEq, Default)] pub enum ObjectFit { #[default] Fill, Contain, Cover, None, ScaleDown, } impl ObjectFit { /// The kit's `BK_FIT_*`; a video's default (fill) letterboxes, as browsers do. pub(crate) const fn kit_video(self) -> i32 { match self { Self::Fill | Self::Contain => blenderui_sys::BK_FIT_CONTAIN, Self::Cover => blenderui_sys::BK_FIT_COVER, Self::None => blenderui_sys::BK_FIT_NONE, Self::ScaleDown => blenderui_sys::BK_FIT_SCALE_DOWN, } } } /// `background-size`: a size is a fraction of the box plus pixels; `None` = auto. #[derive(Clone, Copy, Debug, PartialEq, Default)] pub enum BgSize { #[default] Auto, Cover, Contain, Size(Option, Option), } /// Image placement: `object-*` for replaced content, `background-*` images. /// Boxed in [`Computed::images`]: most elements have neither. #[derive(Clone, Debug, PartialEq)] pub struct ImageStyle { pub object_fit: ObjectFit, pub object_position: [Pos; 2], pub bg_url: Option>, pub bg_size: BgSize, pub bg_position: [Pos; 2], /// repeat along x, y pub bg_repeat: (bool, bool), /// How each repeating axis repeats: `REPEAT_*` (`space`, `round`, or plain). pub bg_spacing: [u8; 2], /// `background-attachment: fixed`: positioned against the viewport. pub bg_fixed: bool, /// `background-attachment: local`: it scrolls with a scroll container's content. pub bg_local: bool, } impl Default for ImageStyle { fn default() -> Self { ImageStyle { object_fit: ObjectFit::Fill, object_position: [Pos::CENTER; 2], bg_url: None, bg_size: BgSize::Auto, bg_position: [Pos::START; 2], bg_repeat: (true, true), bg_spacing: [REPEAT_PLAIN; 2], bg_fixed: false, bg_local: false, } } } impl ImageStyle { /// Where an image of `natural` size goes in `area` with `object-fit` / /// `object-position` (it may overflow `area`; clip to it). pub fn object_rect(&self, area: (f32, f32, f32, f32), natural: (f32, f32)) -> (f32, f32, f32, f32) { let (x, y, w, h) = area; let (nw, nh) = (natural.0.max(1.0), natural.1.max(1.0)); let (dw, dh) = match self.object_fit { ObjectFit::Fill => (w, h), ObjectFit::None => (nw, nh), ObjectFit::Contain | ObjectFit::Cover | ObjectFit::ScaleDown => { let s = if self.object_fit == ObjectFit::Cover { (w / nw).max(h / nh) } else { (w / nw).min(h / nh) }; let s = if self.object_fit == ObjectFit::ScaleDown { s.min(1.0) } else { s }; (nw * s, nh * s) } }; (x + self.object_position[0].at(w - dw), y + self.object_position[1].at(h - dh), dw, dh) } /// One background tile's size for an image of `natural` size in `area` (CSS Backgrounds 3 /// §3.9, with CSS Images 3 §5.3's default sizing for what `background-size` leaves `auto`). pub fn tile(&self, area: (f32, f32), natural: Natural) -> (f32, f32) { let (w, h) = area; // the largest (`contain`) or smallest (`cover`) size of ratio `r` that fits the area let fit = |r: f32, cover: bool| if (w / h > r) == cover { (w, w / r) } else { (h * r, h) }; let Natural { width: nw, height: nh, ratio } = natural; let auto = || match (nw, nh, ratio) { (Some(a), Some(b), _) => (a, b), (Some(a), None, r) => (a, r.map_or(h, |r| a / r)), (None, Some(b), r) => (r.map_or(w, |r| b * r), b), (None, None, Some(r)) => fit(r, false), (None, None, None) => (w, h), }; match self.bg_size { BgSize::Cover => ratio.map_or((w, h), |r| fit(r, true)), BgSize::Contain => ratio.map_or((w, h), |r| fit(r, false)), BgSize::Auto => auto(), BgSize::Size(sx, sy) => match (sx.map(|p| p.at(w)), sy.map(|p| p.at(h))) { (Some(a), Some(b)) => (a, b), (Some(a), None) => (a, ratio.map_or(nh.unwrap_or(h), |r| a / r)), (None, Some(b)) => (ratio.map_or(nw.unwrap_or(w), |r| b * r), b), (None, None) => auto(), }, } } } /// `background-repeat` per axis (`ImageStyle::bg_spacing`): tiles side by side, as many whole tiles as /// fit spaced out over the area, or tiles resized so a whole number of them fills it. pub(crate) const REPEAT_PLAIN: u8 = 0; pub(crate) const REPEAT_SPACE: u8 = 1; pub(crate) const REPEAT_ROUND: u8 = 2; /// An image's natural size (CSS Images 3 §5.1): an SVG may lack a width, a height, or its ratio. #[derive(Clone, Copy, Debug, PartialEq, Default)] pub struct Natural { pub width: Option, pub height: Option, pub ratio: Option, } impl Natural { /// A raster image's: `width` x `height` (at least a pixel each). pub fn of(width: f32, height: f32) -> Self { let (w, h) = (width.max(1.0), height.max(1.0)); Self { width: Some(w), height: Some(h), ratio: Some(w / h) } } } /// The style of one element after the cascade. #[derive(Clone, Debug)] pub struct Computed { pub display: DisplayKind, pub layout: Style, pub order: i32, /// `grid-template-columns`/`-rows: subgrid`: the axes (`tree::SUBGRID_COLUMNS`, `SUBGRID_ROWS`) /// whose tracks are the parent grid's. pub subgrid: u8, /// `display: grid-lanes` ([`LANES_ON`]) and `grid-lanes-direction` (`tree::LANES_*` flags). pub grid_lanes: u8, /// `fit-tolerance` (`None`: `normal`, 1em). pub fit_tolerance: Option, /// `aspect-ratio: auto `: a replaced element's natural ratio wins over the one given. pub aspect_auto: bool, /// Sizing keywords on `min-width`, `min-height`, `max-width`, `max-height` (4 bits each, in that /// order: `crate::tree::SIZING_*`), which taffy has no room for there: the tree resolves them. pub size_kw: u16, /// Size containment (`contain: size` both bits, `inline-size` the width's: `crate::tree::CONTAIN_*`) /// and the content size it sizes the box as (`contain-intrinsic-width` / `-height`, 0 for `none`). pub contain: (u8, [f32; 2]), /// Which of `justify-content`, `align-content`, `justify-items`, `align-items` (`tree::FLOW_*`) /// are `flow-start` / `flow-end`: start / end, swapped where grid lanes reverse that axis. pub flow_align: u8, /// Which `justify-*` properties are `left` / `right` (`PHYS_*`): physical, swapped right to left. pub phys_align: u8, /// `margin-trim` (`TRIM_*`): the edges whose children's margins this container drops. pub margin_trim: u8, /// `display: run-in` (a block box, which the block after it takes in as its first inline box). pub run_in: bool, /// `wrap-inside: avoid`: lines break inside this inline box only when they must. pub wrap_avoid: bool, /// `white-space-trim` (`TRIM_WS_*`): white space this box discards around and inside it. pub ws_trim: u8, /// `visibility: collapse` (inherited with `visible`): a collapsed flex item takes no room in /// the main axis, only its cross size (a strut). pub collapsed: bool, /// `background-color` when it uses `currentcolor`: its value, resolved by [`resolve_current`]. pub background_current: Option>, /// `word-space-transform` (inherited): what word separators U+200B and `` become: none /// (0), U+0020 (1) or U+3000 (2). pub word_space: u8, /// An absolutely positioned box blockified from an inline display: its static position is /// an inline box's, where it would be in its line (CSS 2 10.3.7). pub inline_static: bool, /// `width` / `height: stretch()`: the size the margin box fills, made the /// box's size once its margins are known ([`resolve_stretch`]). pub stretch_fn: [Option; 2], /// Anchor positioning (`anchor-name`, `anchor()` ...: `crate::anchor`), when the box uses it. pub anchor: Option>, /// `view-transition-name` / `-class`, when the box has a name (`crate::transition`). pub view_transition: Option>, // paint (not inherited) pub background: Rgba, pub gradient: Option, /// `object-*` / `background-image: url()` placement (None: defaults). pub images: Option>, /// `container-type`: 0 normal, 1 inline-size, 2 size. pub container_type: u8, /// `container-name` (space-separated names). pub container_name: Option>, pub border_color: [Rgba; 4], pub border_drawn: [bool; 4], pub border_style: [BorderStyle; 4], pub radius: [Length; 4], pub shadows: Vec, pub outline: (f32, Rgba, f32), pub outline_style: BorderStyle, /// `background-clip` and `background-origin`. pub bg_clip: BoxEdge, pub bg_origin: BoxEdge, /// `clip: rect(top, right, bottom, left)` (absolutely positioned boxes; /// `auto` edges are None). pub clip_rect: Option<[Option; 4]>, /// `counter-*` operations (None: none). pub counters: Option>, /// Filters, blending, clip-path, masks, transforms beyond translate and /// border-image (None: none). pub effects: Option>, pub opacity: f32, pub z_index: Option, pub app_region: AppRegion, pub translate: (Length, Length), pub scale: f32, // inherited pub visible: bool, pub cursor: Option, pub pointer_events: bool, /// `user-select` (not inherited; `auto` takes `none` / `all` from the parent, see `inherit`). pub user_select: UserSelect, pub color: Rgba, pub accent: Option, pub font_size: f32, /// The root element's font size (`rem`): inherited by every element from the root. pub root_font_size: f32, pub weight: u16, pub italic: bool, pub underline: bool, pub line_through: bool, pub overline: bool, pub text_align: TextAlign, /// `text-transform: full-width` / `full-size-kana` (`linebreak::TRANSFORM_*`, inherited), /// with or without a case in `text_transform`. pub text_transform_extra: u8, /// `text-align-last` (`auto`: none, which follows `text-align`). pub text_align_last: Option, pub line_height: LineHeight, pub white_space: WhiteSpace, pub text_transform: TextTransform, pub letter_spacing: f32, pub word_spacing: f32, pub text_indent: Length, pub list_style: ListStyle, pub ellipsis: bool, pub small_caps: bool, pub vertical_align: VAlign, pub font_family: String, /// The font family's engine id (see `text::font_id`); 0 = the UI font. pub font_id: u16, // tables, lists, quotes and text effects (inherited) pub border_spacing: (f32, f32), pub border_collapse: bool, pub caption_bottom: bool, /// `table-layout: fixed` (not inherited). pub table_fixed: bool, /// `unicode-bidi: bidi-override | isolate-override`: characters are laid /// out in `direction` order, ignoring their own directionality. pub bidi_override: bool, /// `scroll-snap-type`: axes (1 = x, 2 = y) and strictness. pub snap_axes: u8, pub snap_mandatory: bool, /// `scroll-snap-align` per axis (x, y): 0 none, 1 start, 2 center, 3 end. pub snap_align: (u8, u8), pub marker_inside: bool, /// `quotes`: None = the default curly quotes. pub quotes: Option<(String, String)>, /// `text-shadow`: the first on top. pub text_shadow: Vec, pub decoration_color: Option, pub decoration_style: DecoStyle, /// `text-decoration-thickness` in px (None: auto / from-font). pub decoration_thickness: Option, /// `text-underline-offset` in px (None: auto). pub underline_offset: Option, /// `empty-cells: hide` (inherited). pub empty_cells_hide: bool, /// `field-sizing: content` (not inherited): a textarea is as tall as its text, wrapped at its width. pub field_sizing_content: bool, /// `list-style-image: url()` (inherited). pub list_image: Option>, /// `word-break: break-all` (inherited). pub break_all: bool, /// `overflow-wrap: anywhere | break-word` (inherited). pub wrap_anywhere: bool, /// `word-break: keep-all`, `line-break: anywhere`, `hyphens: none`, `overflow-wrap: break-word` /// (`linebreak::WRAP_*`, inherited). pub text_wrap: u8, /// `tab-size` in spaces (inherited). pub tab_size: u8, /// Custom properties in scope (inherited), in the style store's var arena. pub vars: u32, /// `content` (for `::before` / `::after`): None = `normal` / `none`. pub content: Option>, /// `animation-*` / `transition-*` (None: none). Not inherited. pub anim: Option>, } /// One piece of generated content. #[derive(Clone, Debug, PartialEq)] pub enum ContentPart { Text(String), /// `attr(name)`: the originating element's attribute. Attr(String), OpenQuote, CloseQuote, /// `counter(name, style)`. Counter(Box, ListStyle), /// `counters(name, separator, style)`. Counters(Box, Box, ListStyle), } impl Default for Computed { fn default() -> Self { Computed { display: DisplayKind::Inline, layout: Style { display: Display::Block, ..Default::default() }, order: 0, subgrid: 0, grid_lanes: 0, fit_tolerance: None, flow_align: 0, phys_align: 0, margin_trim: 0, run_in: false, wrap_avoid: false, ws_trim: 0, collapsed: false, background_current: None, word_space: 0, inline_static: false, stretch_fn: [None; 2], aspect_auto: false, size_kw: 0, contain: (0, [0.0; 2]), anchor: None, view_transition: None, background: Rgba::TRANSPARENT, gradient: None, images: None, container_type: 0, container_name: None, border_color: [Rgba::TRANSPARENT; 4], border_drawn: [true; 4], border_style: [BorderStyle::Solid; 4], radius: [Length::Px(0.0); 4], shadows: Vec::new(), outline: (0.0, Rgba::TRANSPARENT, 0.0), outline_style: BorderStyle::Solid, bg_clip: BoxEdge::Border, bg_origin: BoxEdge::Padding, clip_rect: None, counters: None, effects: None, opacity: 1.0, z_index: None, app_region: AppRegion::Auto, translate: (Length::Px(0.0), Length::Px(0.0)), scale: 1.0, visible: true, cursor: None, pointer_events: true, user_select: UserSelect::Auto, color: crate::color::rgb(0x000000), // initial: CanvasText accent: None, font_size: 13.0, root_font_size: crate::geometry::ROOT_FONT_SIZE, weight: 400, italic: false, underline: false, line_through: false, overline: false, text_align: TextAlign::Start, text_align_last: None, text_transform_extra: 0, line_height: LineHeight::Normal, white_space: WhiteSpace::Normal, text_transform: TextTransform::None, letter_spacing: 0.0, word_spacing: 0.0, text_indent: Length::Px(0.0), list_style: ListStyle::Disc, ellipsis: false, small_caps: false, vertical_align: VAlign::Baseline, font_family: String::new(), font_id: 0, border_spacing: (0.0, 0.0), border_collapse: false, caption_bottom: false, table_fixed: false, bidi_override: false, snap_axes: 0, snap_mandatory: false, snap_align: (0, 0), marker_inside: false, quotes: None, text_shadow: Vec::new(), decoration_color: None, decoration_style: DecoStyle::Solid, decoration_thickness: None, underline_offset: None, empty_cells_hide: false, field_sizing_content: false, list_image: None, break_all: false, wrap_anywhere: false, text_wrap: 0, tab_size: 8, vars: 0, content: None, anim: None, } } } impl Computed { /// A child's starting style: inherited properties from `parent`, the rest initial. /// What this element's lengths resolve against in `viewport`. pub(crate) fn units(&self, viewport: (f32, f32)) -> Units { Units { font_size: self.font_size, ch: crate::text::ch(self.font_id, self.font_size), lh: self.line_px(), root_font_size: self.root_font_size, viewport } } pub fn inherit(parent: &Computed) -> Computed { Computed { visible: parent.visible, cursor: parent.cursor, pointer_events: parent.pointer_events, // CSS UI 4: `auto` computes to the parent's `none` / `all`, else `text` user_select: match parent.user_select { UserSelect::None => UserSelect::None, UserSelect::All => UserSelect::All, _ => UserSelect::Auto, }, color: parent.color, accent: parent.accent, font_size: parent.font_size, root_font_size: parent.root_font_size, weight: parent.weight, italic: parent.italic, text_align: parent.text_align, text_align_last: parent.text_align_last, text_transform_extra: parent.text_transform_extra, word_space: parent.word_space, collapsed: parent.collapsed, line_height: parent.line_height, white_space: parent.white_space, text_transform: parent.text_transform, letter_spacing: parent.letter_spacing, word_spacing: parent.word_spacing, text_indent: parent.text_indent, list_style: parent.list_style, small_caps: parent.small_caps, font_family: parent.font_family.clone(), font_id: parent.font_id, // text-decoration propagates to inline descendants in CSS underline: parent.underline, line_through: parent.line_through, overline: parent.overline, decoration_color: parent.decoration_color, decoration_style: parent.decoration_style, decoration_thickness: parent.decoration_thickness, underline_offset: parent.underline_offset, empty_cells_hide: parent.empty_cells_hide, list_image: parent.list_image.clone(), break_all: parent.break_all, wrap_anywhere: parent.wrap_anywhere, text_wrap: parent.text_wrap, tab_size: parent.tab_size, border_spacing: parent.border_spacing, border_collapse: parent.border_collapse, caption_bottom: parent.caption_bottom, marker_inside: parent.marker_inside, quotes: parent.quotes.clone(), text_shadow: parent.text_shadow.clone(), vars: parent.vars, layout: Style { display: Display::Block, direction: parent.layout.direction, ..Default::default() }, ..Computed::default() } } pub(crate) fn effects_mut(&mut self) -> &mut crate::effects::Effects { self.effects.get_or_insert_with(Default::default) } fn images_mut(&mut self) -> &mut ImageStyle { self.images.get_or_insert_with(Default::default) } /// The grid-lanes settings of a `display: grid-lanes` box. pub(crate) fn lanes(&self) -> Option { (self.grid_lanes & LANES_ON != 0).then(|| crate::tree::Lanes { flags: self.grid_lanes & !LANES_ON, flow: self.flow_align, tolerance: self.fit_tolerance.unwrap_or_else(|| LengthPercentage::length(self.font_size)), }) } /// Line box height in pixels. pub fn line_px(&self) -> f32 { match self.line_height { LineHeight::Normal => crate::text::normal_line(self.font_id, self.font_size), LineHeight::Factor(f) => (self.font_size * f).round(), LineHeight::Px(p) => p, } } /// `text-overflow: ellipsis` takes effect: it only applies to a block /// container that clips its overflow horizontally (CSS Overflow 3). pub fn ellipsizes(&self) -> bool { self.ellipsis && self.layout.overflow.x != taffy::Overflow::Visible } pub fn bold(&self) -> bool { self.weight >= 600 } } // ========================================================================== // Applying declarations /// What a handler sees: the style being computed, its parent, units. pub struct Ctx<'a> { pub c: &'a mut Computed, pub parent: &'a Computed, pub u: Units, } type Handler = fn(&mut Ctx, &[Tok]) -> bool; /// Apply one declaration; false when the property or value isn't understood. pub fn apply(c: &mut Computed, parent: &Computed, u: Units, d: &Decl) -> bool { let mut ctx = Ctx { c, parent, u }; if d.prop.is_custom() { return true; // custom properties are collected by the cascade (`vars`) } if d.prop == Prop::UNKNOWN { return false; } if let [Tok::Ident(k)] = &*d.value { if d.prop.name() == "all" { let keep = (ctx.c.layout.direction, ctx.c.vars); *ctx.c = match k.as_ref() { "inherit" => ctx.parent.clone(), "initial" => Computed::default(), "unset" | "revert" | "revert-layer" => Computed::inherit(ctx.parent), _ => return false, }; (ctx.c.layout.direction, ctx.c.vars) = keep; return true; } if matches!(k.as_ref(), "inherit" | "initial" | "unset" | "revert" | "revert-layer") { return global_keyword(&mut ctx, d.prop.name(), k); } } match HANDLERS.get(d.prop.0 as usize) { Some((_, h)) => h(&mut ctx, &d.value), None => true, // accepted, no effect } } /// `@supports (prop: value)`: whether this engine understands the declaration. pub(crate) fn supports_decl(prop: &str, value: &str) -> bool { let d = Decl::new(prop.to_ascii_lowercase(), value); if d.prop.is_custom() { return true; } if d.prop == Prop::UNKNOWN { return false; } let parent = Computed::default(); let mut c = Computed::default(); apply(&mut c, &parent, Units::initial(16.0, (1000.0, 800.0)), &d) } /// The property index of `name` (run-time lookup for parsed CSS). pub(crate) fn prop_index(name: &str) -> Prop { static MAP: OnceLock> = OnceLock::new(); let map = MAP.get_or_init(|| { HANDLERS.iter().map(|(n, _)| *n).chain(ACCEPTED.iter().copied()).enumerate() .map(|(i, n)| (n, i as u16)).collect() }); match map.get(name) { Some(&i) => Prop(i), None if name.starts_with("--") => Prop::custom(name), None => Prop::UNKNOWN, } } /// Standard properties that parse and are accepted but have no effect in this /// renderer (floats, bidi, generated content, background images, animation ...). pub const ACCEPTED: &[&str] = &[ "writing-mode", "will-change", "resize", "appearance", "caret-color", "scroll-behavior", "overscroll-behavior", "touch-action", "font-feature-settings", "font-kerning", "font-stretch", "text-rendering", "-webkit-font-smoothing", "-moz-osx-font-smoothing", "orphans", "widows", "page-break-before", "page-break-after", "page-break-inside", "break-before", "break-after", "break-inside", "columns", "column-count", "column-width", "column-rule", "perspective", "backface-visibility", "box-decoration-break", "image-rendering", "shape-outside", "text-justify", "all", // scrolling "scroll-margin", "scroll-margin-top", "scroll-margin-right", "scroll-margin-bottom", "scroll-margin-left", "scroll-margin-block", "scroll-margin-block-start", "scroll-margin-block-end", "scroll-margin-inline", "scroll-margin-inline-start", "scroll-margin-inline-end", "scroll-padding", "scroll-padding-top", "scroll-padding-right", "scroll-padding-bottom", "scroll-padding-left", "scroll-padding-block", "scroll-padding-block-start", "scroll-padding-block-end", "scroll-padding-inline", "scroll-padding-inline-start", "scroll-padding-inline-end", "scroll-snap-stop", "overscroll-behavior-x", "overscroll-behavior-y", "overscroll-behavior-block", "overscroll-behavior-inline", "overflow-anchor", "scrollbar-color", "scrollbar-gutter", "overflow-clip-margin", // fonts: OpenType features and synthesis "font-variant-ligatures", "font-variant-numeric", "font-variant-east-asian", "font-variant-alternates", "font-variant-position", "font-variant-emoji", "font-synthesis", "font-synthesis-weight", "font-synthesis-style", "font-synthesis-small-caps", "font-synthesis-position", "font-optical-sizing", "font-size-adjust", "font-variation-settings", "font-palette", "font-language-override", "font-width", // text details "text-underline-position", "text-decoration-skip-ink", "text-emphasis", "text-emphasis-color", "text-emphasis-style", "text-emphasis-position", "text-orientation", "text-combine-upright", "hanging-punctuation", "hyphenate-character", "line-clamp", "-webkit-line-clamp", "text-size-adjust", "-webkit-text-size-adjust", // sizing / containment / rendering hints "content-visibility", "interpolate-size", "color-scheme", "forced-color-adjust", "print-color-adjust", "color-adjust", "image-orientation", "image-resolution", "transform-box", "transform-style", "perspective-origin", "zoom", "caret", "caret-shape", "background-blend-mode", "column-span", "column-fill", "column-rule-color", "column-rule-style", "column-rule-width", // masking "mask-clip", "mask-origin", "mask-composite", "mask-type", "mask-border", "mask-border-source", "mask-border-slice", "mask-border-width", "mask-border-outset", "mask-border-repeat", "mask-border-mode", ]; /// Implemented or accepted. pub fn is_supported(name: &str) -> bool { is_implemented(name) || ACCEPTED.contains(&name) || name.starts_with("--") } fn global_keyword(ctx: &mut Ctx, name: &str, keyword: &str) -> bool { if name == "font-family" { global_keyword(ctx, "-bui-font-id", keyword); } if name == "background-color" { ctx.c.background_current = if keyword == "inherit" { ctx.parent.background_current.clone() } else { None }; } let src = if keyword == "inherit" || (keyword == "unset" && is_inherited(name)) { ctx.parent.clone() } else { Computed::default() }; macro_rules! copy { ($($prop:literal => $($field:ident).+),* $(,)?) => { match name { $($prop => { ctx.c.$($field).+ = src.$($field).+.clone(); true })* _ => handlers().contains_key(name), } }; } copy! { "color" => color, "font-size" => font_size, "font-weight" => weight, "font-style" => italic, "text-align" => text_align, "line-height" => line_height, "white-space" => white_space, "text-transform" => text_transform, "letter-spacing" => letter_spacing, "word-spacing" => word_spacing, "visibility" => visible, "cursor" => cursor, "list-style-type" => list_style, "background-color" => background, "opacity" => opacity, "display" => display, "width" => layout.size.width, "height" => layout.size.height, "font-family" => font_family, "accent-color" => accent, "-bui-font-id" => font_id, "user-select" => user_select, "align-items" => layout.align_items, "align-self" => layout.align_self, "align-content" => layout.align_content, "justify-items" => layout.justify_items, "justify-self" => layout.justify_self, "justify-content" => layout.justify_content, "flex-grow" => layout.flex_grow, "flex-shrink" => layout.flex_shrink, "flex-basis" => layout.flex_basis, "flex-direction" => layout.flex_direction, "flex-wrap" => layout.flex_wrap, "min-width" => layout.min_size.width, "min-height" => layout.min_size.height, "max-width" => layout.max_size.width, "max-height" => layout.max_size.height, "box-sizing" => layout.box_sizing, "aspect-ratio" => layout.aspect_ratio, "row-gap" => layout.gap.height, "column-gap" => layout.gap.width, "margin-top" => layout.margin.top, "margin-right" => layout.margin.right, "margin-bottom" => layout.margin.bottom, "margin-left" => layout.margin.left, "padding-top" => layout.padding.top, "padding-right" => layout.padding.right, "padding-bottom" => layout.padding.bottom, "padding-left" => layout.padding.left, "top" => layout.inset.top, "right" => layout.inset.right, "bottom" => layout.inset.bottom, "left" => layout.inset.left, } } fn is_inherited(name: &str) -> bool { INHERITED.contains(&name) } const INHERITED: &[&str] = &[ "border-spacing", "border-collapse", "caption-side", "list-style-position", "quotes", "text-shadow", "empty-cells", "color", "cursor", "font", "font-family", "font-size", "font-style", "font-variant", "font-weight", "letter-spacing", "line-height", "list-style", "list-style-type", "text-align", "text-align-last", "text-indent", "text-transform", "visibility", "white-space", "word-spacing", "accent-color", "caret-color", "pointer-events", "list-style-image", "word-break", "overflow-wrap", "word-wrap", "tab-size", "text-underline-offset", "line-break", "hyphens", "text-autospace", ]; /// The one hasher for keys, caches and maps: foldhash, a word at a time (FNV took a byte at a /// time). The fixed seed keeps keys the same for the whole run; the quality variant keeps /// element keys, which are identities with no equality check, collision-free in practice. pub(crate) type KeyState = FixedState; /// A new hasher with the crate's fixed seed. pub(crate) fn key_hasher() -> impl Hasher { KeyState::default().build_hasher() } pub(crate) type KeyMap = HashMap; /// A set with the same hasher as [`KeyMap`]. pub(crate) type KeySet = HashSet; fn handlers() -> &'static KeyMap<&'static str, Handler> { static MAP: OnceLock> = OnceLock::new(); MAP.get_or_init(|| HANDLERS.iter().copied().collect()) } /// Names of every property that changes layout or rendering. pub fn implemented_properties() -> impl Iterator { HANDLERS.iter().map(|(n, _)| *n) } pub fn is_implemented(name: &str) -> bool { handlers().contains_key(name) } // -- value helpers ----------------------------------------------------------------- pub(crate) fn length(t: &Tok) -> Option { use crate::calc::{is_math_fn, leaf, Calc}; Some(match t { Tok::Num(v) if *v == 0.0 => Length::Px(0.0), Tok::Pct(p) => Length::Percent(*p), Tok::Ident(s) if s == "auto" => Length::Auto, Tok::Dim(v, unit) => match leaf(*v, unit)? { Calc::Px(x) => Length::Px(x), Calc::Em(x) => Length::Em(x), // the font's own: resolved with the element's units ch @ (Calc::Ch(_) | Calc::Lh(_)) => Length::Calc(crate::calc::intern(ch)), Calc::Rem(x) => Length::Rem(x), Calc::Vw(x) => Length::Vw(x), Calc::Vh(x) => Length::Vh(x), Calc::Vmin(x) => Length::Vmin(x), Calc::Vmax(x) => Length::Vmax(x), _ => return None, // angles, times }, Tok::Calc(c) => Length::Calc(c), Tok::Func(fx) if is_math_fn(&fx.name) => Length::Calc(Calc::parse_fn(&fx.name, &fx.args)?), _ => return None, }) } pub(crate) fn tok_text(t: &Tok) -> String { match t { Tok::Num(v) => format!("{v}"), Tok::Dim(v, u) => format!("{v}{u}"), Tok::Pct(v) => format!("{v}%"), Tok::Ident(s) => s.to_string(), Tok::Hash(h) => format!("#{h}"), Tok::Str(s) => s.to_string(), Tok::Color(c) => c.to_css(), Tok::Func(fx) => format!( "{}({})", fx.name, fx.args.iter() .map(|a| a.iter().map(tok_text).collect::>().join(" ")) .collect::>() .join(",") ), Tok::Comma => ",".into(), Tok::Slash => "/".into(), Tok::Delim(c) => c.to_string(), Tok::Calc(c) => format!("{c:?}"), } } pub(crate) fn color(t: &Tok, current: Rgba) -> Option { match t { Tok::Color(c) => Some(*c), Tok::Ident(s) if s == "currentcolor" => Some(current), Tok::Ident(s) => crate::color4::system(s).or_else(|| parse_color(s)), Tok::Hash(_) => parse_color(&tok_text(t)), Tok::Func(fx) => crate::color4::color_fn(fx, current), _ => None, } } fn number(t: &Tok) -> Option { match t { Tok::Num(v) => Some(*v), Tok::Pct(p) => Some(*p / 100.0), _ => None, } } fn kw(v: &[Tok]) -> Option<&str> { v.first().and_then(Tok::ident) } fn px(ctx: &Ctx, l: Length) -> f32 { l.to_px(&ctx.u).unwrap_or(0.0) } fn lp(ctx: &Ctx, l: Length) -> LengthPercentage { match l { Length::Percent(p) => LengthPercentage::percent(p / 100.0), Length::Auto => LengthPercentage::length(0.0), Length::Calc(c) if c.has_pct() => LengthPercentage::calc(c.resolve(&ctx.u).as_ptr()), other => LengthPercentage::length(px(ctx, other)), } } fn lpa(ctx: &Ctx, l: Length) -> LengthPercentageAuto { match l { Length::Percent(p) => LengthPercentageAuto::percent(p / 100.0), Length::Auto => LengthPercentageAuto::auto(), Length::Calc(c) if c.has_pct() => LengthPercentageAuto::calc(c.resolve(&ctx.u).as_ptr()), other => LengthPercentageAuto::length(px(ctx, other)), } } fn dim(ctx: &Ctx, l: Length) -> Dimension { match l { Length::Percent(p) => Dimension::percent(p / 100.0), Length::Auto => Dimension::auto(), Length::Calc(c) if c.has_pct() => Dimension::calc(c.resolve(&ctx.u).as_ptr()), other => Dimension::length(px(ctx, other)), } } /// `width`-like values: lengths plus the sizing keywords. fn dim_kw(ctx: &Ctx, v: &[Tok]) -> Option { match kw(v) { Some("none") => Some(Dimension::auto()), Some("min-content") => Some(Dimension::min_content()), Some("max-content") => Some(Dimension::max_content()), Some("fit-content") => Some(Dimension::fit_content()), Some("stretch" | "-webkit-fill-available" | "-moz-available" | "fill-available") => { Some(Dimension::stretch()) } _ => match v.first()? { Tok::Func(fx) if fx.name == "fit-content" => { Some(match length(fx.args.first()?.first()?)? { Length::Percent(p) => Dimension::fit_content_percent(p / 100.0), Length::Calc(c) if c.has_pct() => Dimension::fit_content_calc(c.resolve(&ctx.u).as_ptr()), l => Dimension::fit_content_px(px(ctx, l)), }) } t => length(t).map(|l| dim(ctx, l)), }, } } /// Whether colour value `t` depends on `currentcolor` (itself, or inside a function). fn uses_currentcolor(t: &Tok) -> bool { match t { Tok::Ident(s) => s.eq_ignore_ascii_case("currentcolor"), Tok::Func(fx) => fx.args.iter().flatten().any(uses_currentcolor), _ => false, } } /// A `currentcolor` background ([`Computed::background_current`]) with the element's `color`. pub(crate) fn resolve_current(c: &mut Computed) { if let Some(col) = c.background_current.as_deref().and_then(|t| color(t, c.color)) { c.background = col; } } /// `stretch(L)` sizes (css-sizing-4 6.1) made the box's: L less its margins (auto ones 0), and /// less its padding and border for a `content-box` size, as a `calc()` when percentages are in it. pub(crate) fn resolve_stretch(c: &mut Computed, u: &Units) { use taffy::CompactLength; let term = |v: CompactLength| match v.tag() { CompactLength::LENGTH_TAG => Some(format!("{}px", v.value())), CompactLength::PERCENT_TAG => Some(format!("{}%", v.value() * 100.0)), _ => None, }; for k in 0..2 { let Some(l) = c.stretch_fn[k] else { continue }; let s = &c.layout; let (m, p, b) = if k == 0 { ([s.margin.left, s.margin.right], [s.padding.left, s.padding.right], [s.border.left, s.border.right]) } else { ([s.margin.top, s.margin.bottom], [s.padding.top, s.padding.bottom], [s.border.top, s.border.bottom]) }; let mut expr = term(l.into_raw()).unwrap_or_else(|| "0px".into()); let mut less = m.iter().filter_map(|v| term(v.into_raw())).collect::>(); if s.box_sizing == BoxSizing::ContentBox { less.extend(p.iter().chain(&b).filter_map(|v| term(v.into_raw()))); } for t in less { expr.push_str(" - "); expr.push_str(&t); } let toks = crate::css::tokenize(&format!("max(0px, {expr})")); let d = match toks.first().and_then(length) { Some(Length::Calc(c)) if c.has_pct() => Dimension::calc(c.resolve(u).as_ptr()), Some(l) => l.to_px(u).map_or(Dimension::auto(), Dimension::length), None => Dimension::auto(), }; if k == 0 { c.layout.size.width = d } else { c.layout.size.height = d } } } /// `contain-intrinsic-*` values: each `none` (0), a length, or `auto` before either. fn intrinsic_sizes(ctx: &Ctx, v: &[Tok]) -> Option> { v.iter().filter(|t| t.ident() != Some("auto")).map(|t| match t { t if t.ident() == Some("none") => Some(0.0), t => length(t).filter(|l| !matches!(l, Length::Percent(_))).map(|l| px(ctx, l).max(0.0)), }).collect::>>().filter(|s| (1..=2).contains(&s.len())) } /// A `min-width`-like value in slot `slot` of `Computed::size_kw`: a sizing keyword is recorded there /// (for the tree to resolve) and is `auto` to taffy. fn min_max(ctx: &mut Ctx, slot: u16, v: &[Tok]) -> Option { // `fit-content()`: the keyword, its limit kept as the value if let [Tok::Func(fx)] = v && fx.name == "fit-content" && let [arg] = fx.args.as_slice() && let [t] = arg.as_slice() && let Some(l) = length(t).filter(|l| *l != Length::Auto && !matches!(l, Length::Percent(p) if *p < 0.0)) { let shift = slot * 4; ctx.c.size_kw = (ctx.c.size_kw & !(0xf << shift)) | (crate::tree::SIZING_FIT_CONTENT << shift); return Some(lpa(ctx, l)); } let code = match kw(v) { Some("min-content") => crate::tree::SIZING_MIN_CONTENT, Some("max-content") => crate::tree::SIZING_MAX_CONTENT, Some("fit-content") => crate::tree::SIZING_FIT_CONTENT, Some("stretch" | "-webkit-fill-available" | "-moz-available" | "fill-available") => crate::tree::SIZING_STRETCH, _ => 0, }; let out = if code == 0 { lpa_kw(ctx, v) } else { Some(LengthPercentageAuto::auto()) }; if out.is_some() { let shift = slot * 4; ctx.c.size_kw = (ctx.c.size_kw & !(0xf << shift)) | (code << shift); } out } /// `min-width`-like values (taffy has no sizing keywords there yet: they act as auto). fn lpa_kw(ctx: &Ctx, v: &[Tok]) -> Option { match kw(v) { Some("none" | "min-content" | "max-content" | "fit-content" | "stretch") => { Some(LengthPercentageAuto::auto()) } _ => v.first().and_then(length).map(|l| lpa(ctx, l)), } } /// The 1–4 value box shorthand: top right bottom left. fn four(v: &[T]) -> Option<[T; 4]> { Some(match v.len() { 1 => [v[0]; 4], 2 => [v[0], v[1], v[0], v[1]], 3 => [v[0], v[1], v[2], v[1]], 4 => [v[0], v[1], v[2], v[3]], _ => return None, }) } fn lengths(v: &[Tok]) -> Option> { v.iter().filter(|t| !matches!(t, Tok::Slash)).map(length).collect() } // side index: 0 top, 1 right, 2 bottom, 3 left fn set_margin(ctx: &mut Ctx, side: usize, l: Length) { let v = lpa(ctx, l); let m = &mut ctx.c.layout.margin; match side { 0 => m.top = v, 1 => m.right = v, 2 => m.bottom = v, _ => m.left = v, } } fn set_padding(ctx: &mut Ctx, side: usize, l: Length) { let v = lp(ctx, l); let p = &mut ctx.c.layout.padding; match side { 0 => p.top = v, 1 => p.right = v, 2 => p.bottom = v, _ => p.left = v, } } /// The box's anchor positioning style, made when a property first needs it. fn anchoring<'c>(ctx: &'c mut Ctx) -> &'c mut crate::anchor::AnchorStyle { ctx.c.anchor.get_or_insert_with(Default::default) } /// `top`, `right`, `bottom`, `left`: a length, or `anchor()` (`auto` until resolved after layout). fn inset_side(ctx: &mut Ctx, side: usize, v: &[Tok]) -> bool { if let Some(e) = crate::anchor::Edge::parse(v, ctx.parent.font_size) { anchoring(ctx).insets[side] = Some(e); set_inset(ctx, side, Length::Auto); return true; } let Some(l) = v.first().and_then(length) else { return false }; if let Some(a) = ctx.c.anchor.as_deref_mut() { a.insets[side] = None; } set_inset(ctx, side, l); true } /// A size property (`width` .. `max-height`, in `AnchorStyle::sizes` order): `anchor-size()`, or what /// `rest` parses. fn size_prop(ctx: &mut Ctx, k: usize, v: &[Tok], rest: fn(&mut Ctx, &[Tok]) -> bool) -> bool { if k < 2 { // `stretch()`: auto until the cascade ends let arg = match v { [Tok::Func(fx)] if fx.name == "stretch" && fx.args.len() == 1 => match fx.args[0].as_slice() { [t] => Some(length(t).filter(|l| *l != Length::Auto).map(|l| lp(ctx, l))), _ => Some(None), }, _ => None, }; ctx.c.stretch_fn[k] = None; if let Some(arg) = arg { let Some(l) = arg else { return false }; ctx.c.stretch_fn[k] = Some(l); if k == 0 { ctx.c.layout.size.width = Dimension::auto() } else { ctx.c.layout.size.height = Dimension::auto() } return true; } } if let Some(x) = crate::anchor::Extent::parse(v, ctx.parent.font_size) { anchoring(ctx).sizes[k] = Some(x); return true; } if !rest(ctx, v) { return false; } if let Some(a) = ctx.c.anchor.as_deref_mut() { a.sizes[k] = None; } true } /// `justify-self` (bit 1) / `align-self` (bit 2): records `anchor-center`. fn anchor_center(ctx: &mut Ctx, v: &[Tok], bit: u8) { if kw(v) == Some("anchor-center") { anchoring(ctx).center |= bit; } else if let Some(a) = ctx.c.anchor.as_deref_mut() { a.center &= !bit; } } fn set_inset(ctx: &mut Ctx, side: usize, l: Length) { let v = lpa(ctx, l); let i = &mut ctx.c.layout.inset; match side { 0 => i.top = v, 1 => i.right = v, 2 => i.bottom = v, _ => i.left = v, } } fn set_border_width(ctx: &mut Ctx, side: usize, w: f32) { let v = LengthPercentage::length(w); let b = &mut ctx.c.layout.border; match side { 0 => b.top = v, 1 => b.right = v, 2 => b.bottom = v, _ => b.left = v, } } fn border_width_tok(ctx: &Ctx, t: &Tok) -> Option { match t.ident() { Some("thin") => Some(1.0), Some("medium") => Some(3.0), Some("thick") => Some(5.0), _ => length(t).map(|l| px(ctx, l)), } } const BORDER_STYLES: &[&str] = &["none", "hidden", "solid", "dashed", "dotted", "double", "groove", "ridge", "inset", "outset"]; /// `border[-side]: ||