//! Cascade e computed style. Ambito M0: origine, specificità, ordine, inline style, //! ereditarietà. Niente `@layer`, niente pseudo-classi (arrivano in M1). use std::collections::HashMap; use std::sync::{Arc, OnceLock}; use crate::css::{parse_declarations, parse_stylesheet, Rule, Selector}; use crate::dom::{Document, NodeId, NodeKind}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Color { pub r: u8, pub g: u8, pub b: u8, pub a: u8, } impl Color { pub const BLACK: Color = Color { r: 0, g: 0, b: 0, a: 255, }; pub const WHITE: Color = Color { r: 255, g: 255, b: 255, a: 255, }; pub const TRANSPARENT: Color = Color { r: 0, g: 0, b: 0, a: 0, }; pub fn rgb(r: u8, g: u8, b: u8) -> Self { Color { r, g, b, a: 255 } } pub fn hex(&self) -> String { format!("#{:02x}{:02x}{:02x}", self.r, self.g, self.b) } } #[derive(Clone, Copy, Debug)] pub enum Len { Px(f32), Percent(f32), } impl Len { pub fn resolve(self, base: f32) -> f32 { match self { Len::Px(v) => v, Len::Percent(p) => base * p / 100.0, } } pub const ZERO: Len = Len::Px(0.0); } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Display { Block, /// contenitore flex: i figli si dispongono lungo l'asse principale Flex, /// tabella, riga e cella: modello a griglia (M2.3) Table, TableRow, TableCell, Inline, ListItem, None, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum FlexDirection { Row, RowReverse, Column, ColumnReverse, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum JustifyContent { FlexStart, Center, FlexEnd, SpaceBetween, SpaceAround, SpaceEvenly, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum AlignItems { Stretch, FlexStart, Center, FlexEnd, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum FlexWrap { NoWrap, Wrap, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum TextAlign { Left, Center, Right, } /// `position`. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Position { Static, Relative, Absolute, Fixed, } /// `float`. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum FloatSide { None, Left, Right, } /// `white-space`: spazi conservati o collassati, e se la riga può andare a capo. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum WhiteSpace { Normal, Nowrap, Pre, PreWrap, PreLine, } /// Direzione di scrittura del contenuto (`direction` / attributo `dir`). #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Direction { Ltr, Rtl, } impl Direction { /// Livello di base per l'algoritmo bidi (0 = LTR, 1 = RTL). pub fn base_level(self) -> u8 { match self { Direction::Ltr => 0, Direction::Rtl => 1, } } } #[derive(Clone, Debug)] pub struct ComputedStyle { pub display: Display, /// top, right, bottom, left pub margin: [Len; 4], pub padding: [Len; 4], pub border_width: [f32; 4], pub border_color: [Color; 4], pub width: Option, pub height: Option, /// `max-width`: una pagina che si limita la larghezza senza questo si /// stende su tutto lo schermo (era il caso di example.com) pub max_width: Option, /// `margin-left`/`margin-right`: `auto` → il blocco si centra pub margin_auto_x: bool, pub background: Color, pub color: Color, pub font_size: f32, pub font_weight: u16, pub line_height: f32, /// vero se `line-height` è stato dichiarato: altrimenti segue `1.2 * font-size`. pub line_height_explicit: bool, pub text_align: TextAlign, /// direzione di scrittura, ereditata pub direction: Direction, // --- proprietà del contenitore flex (non ereditate) --- pub flex_direction: FlexDirection, pub justify_content: JustifyContent, pub align_items: AlignItems, pub flex_wrap: FlexWrap, /// da `gap`: riga e colonna pub row_gap: f32, pub column_gap: f32, // --- proprietà del singolo elemento flex --- pub flex_grow: f32, pub flex_shrink: f32, /// `flex-basis`; `None` = auto pub flex_basis: Option, pub white_space: WhiteSpace, /// prima famiglia dichiarata (`@font-face` la può fornire) pub font_family: Option, pub position: Position, pub float: FloatSide, pub top: Option, pub left: Option, pub right: Option, pub bottom: Option, /// proprietà personalizzate (`--nome`), ereditate: servono a `var()` pub custom: Arc>, } impl Default for ComputedStyle { fn default() -> Self { ComputedStyle { display: Display::Inline, margin: [Len::ZERO; 4], padding: [Len::ZERO; 4], border_width: [0.0; 4], border_color: [Color::BLACK; 4], width: None, height: None, max_width: None, margin_auto_x: false, background: Color::TRANSPARENT, color: Color::BLACK, font_size: 16.0, font_weight: 400, line_height: 19.2, line_height_explicit: false, text_align: TextAlign::Left, direction: Direction::Ltr, flex_direction: FlexDirection::Row, justify_content: JustifyContent::FlexStart, align_items: AlignItems::Stretch, flex_wrap: FlexWrap::NoWrap, row_gap: 0.0, column_gap: 0.0, flex_grow: 0.0, flex_shrink: 1.0, flex_basis: None, white_space: WhiteSpace::Normal, font_family: None, position: Position::Static, float: FloatSide::None, top: None, left: None, right: None, bottom: None, custom: Arc::new(HashMap::new()), } } } impl ComputedStyle { fn inherit(parent: &ComputedStyle) -> Self { let mut st = ComputedStyle::default(); st.color = parent.color; st.font_size = parent.font_size; st.font_weight = parent.font_weight; st.text_align = parent.text_align; st.direction = parent.direction; st.white_space = parent.white_space; st.font_family = parent.font_family.clone(); st.custom = parent.custom.clone(); st.line_height_explicit = parent.line_height_explicit; st.line_height = if parent.line_height_explicit { parent.line_height } else { parent.font_size * 1.2 }; st } } const UA_SHEET: &str = r#" html, body, div, p, h1, h2, h3, h4, h5, h6, ul, ol, li, blockquote, pre, section, article, header, footer, main, nav, form, figure, figcaption, address, dl, dt, dd, fieldset, hr { display: block } li { display: list-item } body { margin: 8px } p { margin: 16px 0 } h1 { font-size: 32px; font-weight: bold; margin: 21px 0 } h2 { font-size: 24px; font-weight: bold; margin: 19px 0 } h3 { font-size: 18.72px; font-weight: bold; margin: 18px 0 } h4 { font-size: 16px; font-weight: bold; margin: 21px 0 } h5 { font-size: 13.28px; font-weight: bold; margin: 22px 0 } h6 { font-size: 10.72px; font-weight: bold; margin: 24px 0 } ul, ol { margin: 16px 0; padding-left: 40px } ol { display: block } pre { margin: 16px 0 } code, pre { font-size: 13px } hr { border-width: 1px 0 0 0; border-color: gray } table { display: table } tr { display: table-row } td, th { display: table-cell; padding: 1px } th { font-weight: bold; text-align: center } thead, tbody, tfoot { display: block } span, a, b, i, em, strong, small, code, sub, sup, label, br, img, u, s, cite, q, time, abbr, mark, var, kbd, samp { display: inline } "#; pub fn ua_rules() -> &'static Vec { static RULES: OnceLock> = OnceLock::new(); RULES.get_or_init(|| parse_stylesheet(UA_SHEET, 0, 1024.0)) } /// Specificità + ordine, con l'origine codificata: vedi `cascade_rank`. #[derive(PartialEq, Eq, PartialOrd, Ord)] struct CascadeKey { important: u8, rank: u8, spec: (u16, u16, u16), order: u32, decl: u16, } #[derive(Clone, Copy, PartialEq, Eq)] enum Origin { Ua = 0, Author = 1, Inline = 2, } fn cascade_rank(important: bool, origin: Origin) -> u8 { if important { match origin { Origin::Ua => 3, Origin::Author => 1, Origin::Inline => 2, } } else { origin as u8 } } /// Stili computati indicizzati per NodeId. Nodi non-elemento ricevono il default. pub fn compute_document(doc: &Document, rules: &[Rule]) -> Vec> { let mut out: Vec> = vec![Arc::new(ComputedStyle::default()); doc.node_count()]; let root_style = Arc::new(ComputedStyle::default()); compute_rec(doc, rules, doc.root(), &root_style, &mut out); out } fn compute_rec( doc: &Document, rules: &[Rule], node: NodeId, parent: &Arc, out: &mut Vec>, ) { for &child in &doc.node(node).children { let style = match &doc.node(child).kind { NodeKind::Element(_) => Arc::new(compute_element(doc, rules, child, parent)), _ => parent.clone(), }; out[child] = style.clone(); compute_rec(doc, rules, child, &style, out); } } pub fn compute_element( doc: &Document, rules: &[Rule], node: NodeId, parent: &ComputedStyle, ) -> ComputedStyle { let mut decls: Vec<(CascadeKey, &str, &str)> = Vec::new(); for rule in rules { if !selector_matches(doc, node, &rule.selector) { continue; } let spec = rule.selector.specificity(); for (idx, d) in rule.decls.iter().enumerate() { let origin = if rule.order < 1000 { Origin::Ua } else { Origin::Author }; decls.push(( CascadeKey { important: d.important as u8, rank: cascade_rank(d.important, origin), spec, order: rule.order, decl: idx as u16, }, d.name.as_str(), d.value.as_str(), )); } } // style attribute: specificità massima, ordine massimo let inline_parsed; if let Some(inline) = doc.attr(node, "style") { inline_parsed = parse_declarations(inline); for (idx, d) in inline_parsed.iter().enumerate() { decls.push(( CascadeKey { important: d.important as u8, rank: cascade_rank(d.important, Origin::Inline), spec: (u16::MAX, 0, 0), order: u32::MAX - 1, decl: idx as u16, }, d.name.as_str(), d.value.as_str(), )); } } decls.sort_by(|a, b| a.0.cmp(&b.0)); let mut st = ComputedStyle::inherit(parent); // Proprietà personalizzate: prima si raccolgono tutte (anche quelle che // arrivano dopo nell'ordine), poi si espandono i `var()` dei valori. let mut custom: HashMap = (*parent.custom).clone(); for (_, name, value) in &decls { if name.starts_with("--") { custom.insert(name.to_string(), value.trim().to_string()); } } let custom = Arc::new(custom); st.custom = custom.clone(); // Prima le proprietà che cambiano la base di `em` e `line-height`. for (_, name, value) in &decls { if name.starts_with("--") { continue; } let Some(expanded) = expand_vars(value, &custom) else { continue; }; if *name == "font-size" { apply_font_size(&mut st, &expanded, parent.font_size); } else if *name == "font-weight" { apply_font_weight(&mut st, &expanded); } } if !st.line_height_explicit { st.line_height = st.font_size * 1.2; } for (_, name, value) in &decls { if name.starts_with("--") || *name == "font-size" || *name == "font-weight" { continue; } let Some(expanded) = expand_vars(value, &custom) else { continue; }; apply_declaration(&mut st, name, &expanded, parent.font_size); } if !st.line_height_explicit { st.line_height = st.font_size * 1.2; } // Attributo `dir`: presentazionale, quindi ha la precedenza minima — vale // solo se `direction` non è dichiarato nel foglio né in linea. let direction_dichiarata = decls.iter().any(|(_, name, _)| *name == "direction"); if !direction_dichiarata { if let Some(d) = doc.attr(node, "dir") { st.direction = match d.trim().to_ascii_lowercase().as_str() { "rtl" => Direction::Rtl, _ => Direction::Ltr, }; } } // In un blocco RTL il valore iniziale di `text-align` è `right`. if st.direction == Direction::Rtl && !decls.iter().any(|(_, name, _)| *name == "text-align") { st.text_align = TextAlign::Right; } st } /// Sostituisce `var(--nome)` e `var(--nome, fallback)`. Restituisce `None` se una /// variabile resta irrisolta: la dichiarazione viene scartata, come da specifica. fn expand_vars(value: &str, custom: &HashMap) -> Option { if !value.contains("var(") { return Some(value.to_string()); } let mut out = String::with_capacity(value.len()); let chars: Vec = value.chars().collect(); let mut i = 0usize; while i < chars.len() { if chars[i] == 'v' && chars.get(i + 1) == Some(&'a') && chars.get(i + 2) == Some(&'r') && chars.get(i + 3) == Some(&'(') { let start = i + 4; let mut depth = 1i32; let mut j = start; while j < chars.len() && depth > 0 { match chars[j] { '(' => depth += 1, ')' => depth -= 1, _ => {} } if depth == 0 { break; } j += 1; } if depth != 0 { return None; } let inner: String = chars[start..j].iter().collect(); let (name, fallback) = match inner.split_once(',') { Some((n, f)) => (n.trim().to_string(), Some(f.trim().to_string())), None => (inner.trim().to_string(), None), }; let replacement = match custom.get(&name) { Some(v) => v.clone(), None => match fallback { // il fallback può contenere a sua volta una var() Some(f) => expand_vars(&f, custom)?, None => return None, }, }; out.push_str(&replacement); i = j + 1; } else { out.push(chars[i]); i += 1; } } Some(out) } fn apply_font_size(st: &mut ComputedStyle, value: &str, parent_font: f32) { let v = value.trim(); let px = match v { "xx-small" => 9.0, "x-small" => 10.0, "small" => 13.0, "medium" => 16.0, "large" => 18.0, "x-large" => 24.0, "xx-large" => 32.0, "smaller" => parent_font * 0.83, "larger" => parent_font * 1.2, _ => { if let Some(px) = v .strip_suffix("px") .and_then(|s| s.trim().parse::().ok()) { px } else if let Some(em) = v .strip_suffix("em") .and_then(|s| s.trim().parse::().ok()) { parent_font * em } else if let Some(p) = v .strip_suffix('%') .and_then(|s| s.trim().parse::().ok()) { parent_font * p / 100.0 } else if let Some(rem) = v .strip_suffix("rem") .and_then(|s| s.trim().parse::().ok()) { 16.0 * rem } else { return; } } }; st.font_size = px.max(0.0); if !st.line_height_explicit { st.line_height = st.font_size * 1.2; } } fn apply_font_weight(st: &mut ComputedStyle, value: &str) { let v = value.trim(); st.font_weight = match v { "normal" => 400, "bold" => 700, "bolder" => (st.font_weight + 300).min(900), "lighter" => st.font_weight.saturating_sub(300).max(100), other => other.parse::().unwrap_or(st.font_weight), }; } fn apply_declaration(st: &mut ComputedStyle, name: &str, value: &str, parent_font: f32) { let v = value.trim(); match name { "display" => { st.display = match v { "flex" | "inline-flex" => Display::Flex, "table" | "inline-table" => Display::Table, "table-row" => Display::TableRow, "table-cell" => Display::TableCell, "block" | "grid" => Display::Block, "list-item" => Display::ListItem, "none" => Display::None, _ => Display::Inline, } } "margin" => { // `auto` vale solo per il centraggio orizzontale: è il modo in cui le // pagine limitano la larghezza e la centrano (`margin: 0 auto`) let parti: Vec<&str> = v.split_whitespace().collect(); if let Some((vals, auto_x)) = four_sides_con_auto(&parti, st.font_size) { st.margin = vals; st.margin_auto_x = auto_x; } } "margin-top" => set_side(&mut st.margin, 0, v, st.font_size), "margin-right" => set_side(&mut st.margin, 1, v, st.font_size), "margin-bottom" => set_side(&mut st.margin, 2, v, st.font_size), "margin-left" => set_side(&mut st.margin, 3, v, st.font_size), "padding" => { if let Some(vals) = four_sides(v, st.font_size) { st.padding = vals; } } "padding-top" => set_side(&mut st.padding, 0, v, st.font_size), "padding-right" => set_side(&mut st.padding, 1, v, st.font_size), "padding-bottom" => set_side(&mut st.padding, 2, v, st.font_size), "padding-left" => set_side(&mut st.padding, 3, v, st.font_size), "border" => { apply_border_shorthand(st, v, [0, 1, 2, 3].as_slice()); } "border-top" => apply_border_shorthand(st, v, &[0]), "border-right" => apply_border_shorthand(st, v, &[1]), "border-bottom" => apply_border_shorthand(st, v, &[2]), "border-left" => apply_border_shorthand(st, v, &[3]), "border-width" => { if let Some(vals) = four_sides_f(v, st.font_size) { st.border_width = vals; } } "border-color" => { let parts: Vec<&str> = v.split_whitespace().collect(); let cols: Vec = parts.iter().filter_map(|p| parse_color(p)).collect(); match cols.len() { 1 => st.border_color = [cols[0]; 4], 2 => st.border_color = [cols[0], cols[1], cols[0], cols[1]], 3 => st.border_color = [cols[0], cols[1], cols[2], cols[1]], 4 => st.border_color = [cols[0], cols[1], cols[2], cols[3]], _ => {} } } "border-style" => { // M0: nessun bordo visibile se lo stile è none/hidden if v == "none" || v == "hidden" { st.border_width = [0.0; 4]; } } "width" => { if v == "auto" { st.width = None; } else if let Some(l) = parse_len(v, st.font_size) { st.width = Some(l); } } "height" => { if v == "auto" { st.height = None; } else if let Some(l) = parse_len(v, st.font_size) { st.height = Some(l); } } "background" | "background-color" => { if let Some(c) = parse_color(v) { st.background = c; } } "color" => { if let Some(c) = parse_color(v) { st.color = c; } } "line-height" => { if v == "normal" { st.line_height_explicit = false; st.line_height = st.font_size * 1.2; } else if let Some(n) = v.parse::().ok() { st.line_height_explicit = true; st.line_height = st.font_size * n; } else if let Some(l) = parse_len(v, st.font_size) { st.line_height_explicit = true; st.line_height = l.resolve(st.font_size); } } "flex-direction" => { st.flex_direction = match v { "row-reverse" => FlexDirection::RowReverse, "column" => FlexDirection::Column, "column-reverse" => FlexDirection::ColumnReverse, _ => FlexDirection::Row, } } "justify-content" => { st.justify_content = match v { "center" => JustifyContent::Center, "flex-end" | "end" | "right" => JustifyContent::FlexEnd, "space-between" => JustifyContent::SpaceBetween, "space-around" => JustifyContent::SpaceAround, "space-evenly" => JustifyContent::SpaceEvenly, _ => JustifyContent::FlexStart, } } "align-items" => { st.align_items = match v { "flex-start" | "start" => AlignItems::FlexStart, "center" => AlignItems::Center, "flex-end" | "end" => AlignItems::FlexEnd, _ => AlignItems::Stretch, } } "flex-wrap" => { st.flex_wrap = match v { "wrap" | "wrap-reverse" => FlexWrap::Wrap, _ => FlexWrap::NoWrap, } } "gap" | "grid-gap" => { let parti: Vec = v .split_whitespace() .filter_map(|p| parse_len(p, st.font_size).map(|l| l.resolve(st.font_size))) .collect(); match parti.len() { 1 => { st.row_gap = parti[0]; st.column_gap = parti[0]; } 2 => { st.row_gap = parti[0]; st.column_gap = parti[1]; } _ => {} } } "row-gap" => { if let Some(l) = parse_len(v, st.font_size) { st.row_gap = l.resolve(st.font_size); } } "column-gap" => { if let Some(l) = parse_len(v, st.font_size) { st.column_gap = l.resolve(st.font_size); } } "flex-grow" => st.flex_grow = v.parse::().unwrap_or(0.0).max(0.0), "flex-shrink" => st.flex_shrink = v.parse::().unwrap_or(1.0).max(0.0), "flex-basis" => { st.flex_basis = if v == "auto" || v == "content" { None } else { parse_len(v, st.font_size) } } "flex" => { // flex: [] [] | auto | none match v { "auto" => { st.flex_grow = 1.0; st.flex_shrink = 1.0; st.flex_basis = None; } "none" => { st.flex_grow = 0.0; st.flex_shrink = 0.0; st.flex_basis = None; } _ => { let parti: Vec<&str> = v.split_whitespace().collect(); let mut grow = None; let mut shrink = None; let mut basis = None; for p in parti { if p == "auto" { basis = None; } else if let Some(l) = parse_len(p, st.font_size) { basis = Some(l); } else if let Ok(n) = p.parse::() { if grow.is_none() { grow = Some(n); } else if shrink.is_none() { shrink = Some(n); } } } st.flex_grow = grow.unwrap_or(0.0).max(0.0); st.flex_shrink = shrink.unwrap_or(1.0).max(0.0); st.flex_basis = basis; } } } "direction" => { st.direction = match v { "rtl" => Direction::Rtl, _ => Direction::Ltr, } } "text-align" => { st.text_align = match v { "center" => TextAlign::Center, "right" => TextAlign::Right, _ => TextAlign::Left, } } "position" => { st.position = match v { "relative" => Position::Relative, "absolute" => Position::Absolute, "fixed" => Position::Fixed, _ => Position::Static, } } "float" => { st.float = match v { "left" => FloatSide::Left, "right" => FloatSide::Right, _ => FloatSide::None, } } "top" => { st.top = if v == "auto" { None } else { parse_len(v, st.font_size) } } "left" => { st.left = if v == "auto" { None } else { parse_len(v, st.font_size) } } "right" => { st.right = if v == "auto" { None } else { parse_len(v, st.font_size) } } "bottom" => { st.bottom = if v == "auto" { None } else { parse_len(v, st.font_size) } } "max-width" => st.max_width = parse_len(v, st.font_size), "font" => { apply_font_shorthand(st, v, parent_font); } "font-family" => { st.font_family = prima_famiglia_utile(v); } "white-space" => { st.white_space = match v { "nowrap" => WhiteSpace::Nowrap, "pre" => WhiteSpace::Pre, "pre-wrap" => WhiteSpace::PreWrap, "pre-line" => WhiteSpace::PreLine, _ => WhiteSpace::Normal, } } _ => {} } } fn apply_border_shorthand(st: &mut ComputedStyle, value: &str, sides: &[usize]) { let mut width: Option = None; let mut color: Option = None; let mut style_none = false; for part in value.split_whitespace() { if part == "none" || part == "hidden" { style_none = true; } else if let Some(l) = parse_len(part, st.font_size) { width = Some(l.resolve(st.font_size)); } else if let Some(c) = parse_color(part) { color = Some(c); } else if matches!( part, "solid" | "dashed" | "dotted" | "double" | "groove" | "ridge" | "inset" | "outset" ) { // stile grafico: M0 tratta tutto come solid } } for &s in sides { if style_none { st.border_width[s] = 0.0; } else if let Some(w) = width { st.border_width[s] = w; } if let Some(c) = color { st.border_color[s] = c; } } } fn set_side(slot: &mut [Len; 4], idx: usize, value: &str, em: f32) { match value.trim() { "auto" => slot[idx] = Len::ZERO, v => { if let Some(l) = parse_len(v, em) { slot[idx] = l; } } } } fn four_sides(value: &str, em: f32) -> Option<[Len; 4]> { let parts: Vec = value .split_whitespace() .map(|p| parse_len(p, em)) .collect::>>()?; match parts.len() { 1 => Some([parts[0]; 4]), 2 => Some([parts[0], parts[1], parts[0], parts[1]]), 3 => Some([parts[0], parts[1], parts[2], parts[1]]), 4 => Some([parts[0], parts[1], parts[2], parts[3]]), _ => None, } } /// Come `four_sides`, ma accetta `auto` sui lati orizzontali e lo riporta. fn four_sides_con_auto(parti: &[&str], em: f32) -> Option<([Len; 4], bool)> { let mut lati: Vec = Vec::new(); for p in parti { if p.eq_ignore_ascii_case("auto") { lati.push(Len::Px(0.0)); } else { lati.push(parse_len(p, em)?); } } let auto = |i: usize| { parti .get(i) .map(|p| p.eq_ignore_ascii_case("auto")) .unwrap_or(false) }; let (lati, auto_x) = match lati.len() { 1 => ([lati[0]; 4], auto(0)), 2 => ([lati[0], lati[1], lati[0], lati[1]], auto(1)), 3 => ([lati[0], lati[1], lati[2], lati[1]], auto(1)), 4 => ([lati[0], lati[1], lati[2], lati[3]], auto(1) || auto(3)), _ => return None, }; Some((lati, auto_x)) } fn four_sides_f(value: &str, em: f32) -> Option<[f32; 4]> { let parts: Vec = value .split_whitespace() .map(|p| parse_len(p, em).map(|l| l.resolve(em))) .collect::>>()?; match parts.len() { 1 => Some([parts[0]; 4]), 2 => Some([parts[0], parts[1], parts[0], parts[1]]), 3 => Some([parts[0], parts[1], parts[2], parts[1]]), 4 => Some([parts[0], parts[1], parts[2], parts[3]]), _ => None, } } // Dimensioni del viewport in px CSS, per `vh`/`vw`. Sono quelle della vista al // momento del calcolo degli stili: un ridimensionamento rifà la cascata. thread_local! { static VIEWPORT: std::cell::Cell<(f32, f32)> = const { std::cell::Cell::new((0.0, 0.0)) }; } pub fn set_viewport(larghezza: f32, altezza: f32) { VIEWPORT.with(|v| v.set((larghezza, altezza))); } pub fn parse_len(value: &str, em: f32) -> Option { let v = value.trim(); if let Some(px) = v.strip_suffix("px") { return px.trim().parse::().ok().map(Len::Px); } // l'ordine conta: "1rem" finisce con "em" if let Some(r) = v.strip_suffix("rem") { return r.trim().parse::().ok().map(|n| Len::Px(n * 16.0)); } if let Some(e) = v.strip_suffix("em") { return e.trim().parse::().ok().map(|n| Len::Px(n * em)); } if let Some(p) = v.strip_suffix('%') { return p.trim().parse::().ok().map(Len::Percent); } // vh/vw: riferite al viewport, quindi si risolvono subito in px if let Some(h) = v.strip_suffix("vh") { let (_, altezza) = VIEWPORT.with(|v| v.get()); return h .trim() .parse::() .ok() .map(|n| Len::Px(n * altezza / 100.0)); } if let Some(w) = v.strip_suffix("vw") { let (larghezza, _) = VIEWPORT.with(|v| v.get()); return w .trim() .parse::() .ok() .map(|n| Len::Px(n * larghezza / 100.0)); } if v == "0" { return Some(Len::Px(0.0)); } None } pub fn parse_color(value: &str) -> Option { let v = value.trim().to_ascii_lowercase(); let named = match v.as_str() { "black" => Some(Color::rgb(0, 0, 0)), "white" => Some(Color::rgb(255, 255, 255)), "red" => Some(Color::rgb(255, 0, 0)), "green" => Some(Color::rgb(0, 128, 0)), "lime" => Some(Color::rgb(0, 255, 0)), "blue" => Some(Color::rgb(0, 0, 255)), "yellow" => Some(Color::rgb(255, 255, 0)), "gray" | "grey" => Some(Color::rgb(128, 128, 128)), "silver" => Some(Color::rgb(192, 192, 192)), "maroon" => Some(Color::rgb(128, 0, 0)), "navy" => Some(Color::rgb(0, 0, 128)), "purple" => Some(Color::rgb(128, 0, 128)), "teal" => Some(Color::rgb(0, 128, 128)), "olive" => Some(Color::rgb(128, 128, 0)), "orange" => Some(Color::rgb(255, 165, 0)), "fuchsia" | "magenta" => Some(Color::rgb(255, 0, 255)), "aqua" | "cyan" => Some(Color::rgb(0, 255, 255)), "transparent" => Some(Color::TRANSPARENT), _ => None, }; if named.is_some() { return named; } if let Some(hex) = v.strip_prefix('#') { let h: Vec = hex.chars().collect(); let parse = |s: &[char]| -> Option { let s: String = s.iter().collect(); u8::from_str_radix(&s, 16).ok() }; return match h.len() { 3 => { let r = parse(&h[0..1])?; let g = parse(&h[1..2])?; let b = parse(&h[2..3])?; Some(Color::rgb(r * 17, g * 17, b * 17)) } 6 => { let r = parse(&h[0..2])?; let g = parse(&h[2..4])?; let b = parse(&h[4..6])?; Some(Color::rgb(r, g, b)) } 8 => { let r = parse(&h[0..2])?; let g = parse(&h[2..4])?; let b = parse(&h[4..6])?; let a = parse(&h[6..8])?; Some(Color { r, g, b, a }) } _ => None, }; } if let Some(inner) = v.strip_prefix("rgb(").and_then(|s| s.strip_suffix(')')) { let parts: Vec = inner .split(',') .filter_map(|p| p.trim().parse::().ok()) .map(|f| f.clamp(0.0, 255.0) as u8) .collect(); if parts.len() >= 3 { return Some(Color::rgb(parts[0], parts[1], parts[2])); } } None } /// Matching: ultimo composto sul soggetto, gli altri su antenati in ordine. pub fn selector_matches(doc: &Document, node: NodeId, sel: &Selector) -> bool { if sel.compounds.is_empty() { return false; } let subject = sel.compounds.last().unwrap(); if !compound_matches(doc, node, subject) { return false; } let mut ancestor = doc.node(node).parent; for comp in sel.compounds.iter().rev().skip(1) { let mut found = false; while let Some(a) = ancestor { if compound_matches(doc, a, comp) { ancestor = doc.node(a).parent; found = true; break; } ancestor = doc.node(a).parent; } if !found { return false; } } true } fn compound_matches(doc: &Document, node: NodeId, comp: &crate::css::Compound) -> bool { let Some(name) = doc.element_name(node) else { return false; }; if let Some(tag) = &comp.tag { if !name.eq_ignore_ascii_case(tag) { return false; } } if let Some(id) = &comp.id { if doc.attr(node, "id") != Some(id.as_str()) { return false; } } if !comp.classes.is_empty() { let classes = doc.classes(node); for c in &comp.classes { if !classes.iter().any(|x| x == c) { return false; } } } true } /// Parole chiave di famiglia: non sono font installati, sono categorie. Il /// motore ha una faccia sola per famiglia logica: se ne resta una generica, /// si usa il font di base invece di cercare un file che si chiama "system-ui". const FAMIGLIE_GENERICHE: &[&str] = &[ "serif", "sans-serif", "monospace", "cursive", "fantasy", "system-ui", "ui-serif", "ui-sans-serif", "ui-monospace", "ui-rounded", "-apple-system", "blinkmacsystemfont", "emoji", "math", "fangsong", "inherit", "initial", ]; /// Prima famiglia della lista che sia un nome vero; `None` se sono tutte generiche. fn prima_famiglia_utile(valore: &str) -> Option { for pezzo in valore.split(',') { let nome = pezzo.trim().trim_matches('"').trim_matches('\'').trim(); if nome.is_empty() { continue; } if FAMIGLIE_GENERICHE.contains(&nome.to_ascii_lowercase().as_str()) { continue; } return Some(nome.to_string()); } None } /// `font` è una scorciatoia che mescola stile, spessore, dimensione, interlinea /// e famiglia in una sola dichiarazione: `font: 16px/1.6 system-ui,sans-serif`. /// Senza, le pagine che la usano (molte) finiscono con dimensione e famiglia /// sbagliate, come è successo con example.com. fn apply_font_shorthand(st: &mut ComputedStyle, valore: &str, parent_font: f32) { let mut parti: Vec<&str> = valore.split_whitespace().collect(); if parti.is_empty() { return; } // la dimensione è il primo pezzo che ha un'unità o è una parola chiave nota let indice = parti.iter().position(|p| { let p = p.split('/').next().unwrap_or(p); p.parse::().is_ok() || p.ends_with("px") || p.ends_with("em") || p.ends_with("rem") || p.ends_with('%') || p.ends_with("pt") || matches!( p.to_ascii_lowercase().as_str(), "xx-small" | "x-small" | "small" | "medium" | "large" | "x-large" | "xx-large" | "smaller" | "larger" ) }); let Some(indice) = indice else { return }; for prima in &parti[..indice] { match prima.to_ascii_lowercase().as_str() { // il corsivo non è rappresentato: il motore ha una faccia per famiglia "italic" | "oblique" | "small-caps" | "normal" => {} "bold" | "bolder" => st.font_weight = 700, "lighter" => st.font_weight = 300, altro => { if let Ok(n) = altro.parse::() { st.font_weight = n; } } } } let dimensione = parti[indice]; let (dim, interlinea) = match dimensione.split_once('/') { Some((d, l)) => (d, Some(l)), None => (dimensione, None), }; apply_font_size(st, dim, parent_font); if let Some(l) = interlinea { if let Ok(px) = lunghezza_in_px(l, st.font_size) { st.line_height = px; st.line_height_explicit = true; } } // il resto è la famiglia, che può contenere spazi: si ricompone if indice + 1 <= parti.len() { let famiglia = parti.split_off(indice + 1).join(" "); if !famiglia.is_empty() { st.font_family = prima_famiglia_utile(&famiglia); } } } /// Lunghezza in px CSS per l'interlinea: un numero puro è un **fattore** della /// dimensione del font (`16px/1.6` = 25,6 px), non una lunghezza in px. fn lunghezza_in_px(valore: &str, em: f32) -> Result { let v = valore.trim(); if let Ok(fattore) = v.parse::() { return Ok(fattore * em); } if let Some(n) = v.strip_suffix("em") { return n.parse::().map(|x| x * em).map_err(|_| ()); } if let Some(n) = v.strip_suffix('%') { return n.parse::().map(|x| x * em / 100.0).map_err(|_| ()); } v.trim_end_matches("px").parse::().map_err(|_| ()) }