//! From an element tree to positioned boxes: cascade, box tree, taffy layout. //! //! * Block containers with inline content become wrapping flex lines of word //! boxes (so text, links and inline-blocks wrap like a browser's line //! boxes); inline elements own their words for painting and hit testing. //! * Flex and grid containers get text runs as measured, wrapping leaves. //! * Tables map onto flex rows and columns, lists paint their markers. //! //! Everything lives in flat arenas owned by the window and reused every //! frame: boxes and element data in [`Frame`], computed styles in //! [`StyleStore`] (shared between identical elements), the taffy tree, text //! widths and images. Boxes refer to each other by index; nothing is //! reference-counted. use std::collections::{HashMap, HashSet}; use std::hash::{Hash, Hasher}; use std::sync::Arc; use taffy::prelude::*; use taffy::style::Overflow; use crate::css::{Decl, Prop, Rule, Stylesheet, Subject}; use crate::element::{AnyElement, Div, Listeners, PaintFn, ParentElement, ReplacedSource, SharedString}; use crate::geometry::{rect, Bounds, Units}; use crate::html::{tag_kind, ua_styled_stylesheet, ua_stylesheet, TagKind}; use crate::paint::{Image, ImageCache, ImageFile}; use crate::prof::{span, Phase}; use crate::style::ContentPart; use crate::style::{apply, key_hasher, Computed, DisplayKind, KeyMap, TextAlign, TextTransform, VAlign, WhiteSpace}; use crate::text::{self, TextCache}; use crate::widgets::{WidgetAsk, WidgetSpec}; // ========================================================================== // Keys /// An element's identity across frames: a hash of its `.id()`, or of its /// parent's key, tag and position. pub(crate) type Key = u64; fn hash_parts(parts: &[&[u8]]) -> u64 { let mut h = key_hasher(); for p in parts { h.write(p); h.write(&[0xff]); } h.finish() } /// The key of the element with `.id(id)`. pub(crate) fn id_key(id: &str) -> Key { hash_parts(&[b"#", id.as_bytes()]) } fn child_key(parent: Key, tag: &str, n: usize) -> Key { hash_parts(&[&parent.to_le_bytes(), tag.as_bytes(), &(n as u64).to_le_bytes()]) } /// The key of the `` element. pub(crate) const ROOT_KEY: Key = 0x68746d6c; // "html" /// Interaction state the cascade reads (`:hover`, `:active`, `:focus`, `details[open]`). #[derive(Default)] pub(crate) struct UiState { pub hovered: HashSet, pub active: HashSet, pub focused: Option, /// The focused element and its ancestors (`:focus-within`). pub focus_path: HashSet, /// The `.id()` of the focused element. pub focused_id: Option, pub details_open: HashMap, pub scroll: HashMap, pub checked: HashMap, } // ========================================================================== // Styles /// A computed style in a [`StyleStore`]. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub(crate) struct StyleId(u32); /// The style everything inherits from at the root. pub(crate) const ROOT_STYLE: StyleId = StyleId(0); /// What a computed style depends on (style sharing). struct StyleKey { parent: StyleId, viewport: (u32, u32), author: u64, rules: Vec, decls: Vec, fixup: u8, } /// Computed styles, shared by every element with the same inputs and kept /// across frames (browsers call this style sharing). Elements refer to them /// by [`StyleId`]. pub(crate) struct StyleStore { styles: Vec, cache: KeyMap>, /// Custom property maps the styles point into (`Computed::vars`). vars: crate::vars::Vars, /// The author sheet whose `@property` initial values seed the root /// style's variables. seeded: u64, } impl Default for StyleStore { fn default() -> Self { StyleStore { styles: vec![Computed::default()], cache: Default::default(), vars: Default::default(), seeded: 0 } } } impl std::ops::Index for StyleStore { type Output = Computed; fn index(&self, id: StyleId) -> &Computed { &self.styles[id.0 as usize] } } impl StyleStore { /// A style one element owns (an animated one's private copy, never in /// the cache), to change in place. pub(crate) fn private_mut(&mut self, id: StyleId) -> &mut Computed { &mut self.styles[id.0 as usize] } /// Before building a frame: drop everything when the store has grown /// large (ids from the previous frame are not used after this). fn begin_frame(&mut self) { if self.styles.len() > 20_000 { self.styles.truncate(1); self.cache.clear(); self.vars.clear(); self.seeded = 0; } } /// `@property --x { initial-value: .. }`: registered properties hold /// their initial value until something sets them (`var(--x)` finds it /// without a fallback). Seeded into the root style once per sheet. fn seed_properties(&mut self, sheet: &Stylesheet, hash: u64) { if self.seeded == hash { return; } self.seeded = hash; let mut map: Vec<(Prop, Box<[crate::css::Tok]>)> = sheet.properties.iter() .filter(|p| p.name.starts_with("--")) .filter_map(|p| Some((Prop::custom(&p.name), crate::css::tokenize(p.initial.as_deref()?).into_boxed_slice()))) .collect(); map.sort_by_key(|e| e.0); map.dedup_by_key(|e| e.0); // styles computed against the old root variables are stale self.styles.truncate(1); self.cache.clear(); self.vars.clear(); self.styles[0].vars = if map.is_empty() { 0 } else { self.vars.add(map.into_boxed_slice()) }; } fn add(&mut self, c: Computed) -> StyleId { self.styles.push(c); StyleId((self.styles.len() - 1) as u32) } } /// The author stylesheet (all `