1use super::*;
4
5#[derive(Debug, Clone, PartialEq)]
6pub struct StyleSheet {
7 pub rules: Vec<Rule>,
8 pub keyframes: Vec<Keyframes>,
10 pub counter_styles: Vec<CounterStyleDef>,
12 pub font_faces: Vec<FontFaceDef>,
14}
15
16#[derive(Debug, Clone, PartialEq, Eq)]
23pub struct FontFaceDef {
24 pub family: String,
25 pub src_url: Option<String>,
26 pub weight: u16,
34 pub unicode_ranges: Vec<(u32, u32)>,
37}
38
39impl FontFaceDef {
40 pub fn matches_codepoint(&self, cp: u32) -> bool {
42 if self.unicode_ranges.is_empty() {
43 return true;
44 }
45 self.unicode_ranges
46 .iter()
47 .any(|&(lo, hi)| cp >= lo && cp <= hi)
48 }
49
50 pub fn matches_any_codepoint<'a>(&self, codepoints: impl IntoIterator<Item = &'a u32>) -> bool {
53 if self.unicode_ranges.is_empty() {
54 return true;
55 }
56 for &cp in codepoints {
57 if self.matches_codepoint(cp) {
58 return true;
59 }
60 }
61 false
62 }
63}
64
65#[derive(Debug, Clone, PartialEq, Eq)]
71pub struct CounterStyleDef {
72 pub name: String,
73 pub system: String,
74 pub symbols: Vec<String>,
75 pub suffix: String,
76}
77
78pub fn format_with_counter_style(def: &CounterStyleDef, value: i64) -> String {
83 if def.symbols.is_empty() {
84 return alloc::format!("{}", value);
85 }
86 if def.system.trim() == "numeric" {
87 if value <= 0 {
88 return alloc::format!("{}", value);
89 }
90 let base = def.symbols.len() as i64;
91 let mut n = value;
92 let mut digits: alloc::vec::Vec<&str> = alloc::vec::Vec::new();
93 while n > 0 {
94 let d = (n % base) as usize;
95 digits.push(def.symbols[d].as_str());
96 n /= base;
97 }
98 digits.iter().rev().copied().collect::<Vec<&str>>().concat()
99 } else {
100 let len = def.symbols.len() as i64;
101 let idx = (value - 1).rem_euclid(len) as usize;
102 def.symbols[idx].clone()
103 }
104}
105
106#[derive(Debug, Clone, PartialEq)]
108pub struct Keyframes {
109 pub name: String,
110 pub frames: Vec<(f32, Vec<Declaration>)>,
112}
113
114#[derive(Debug, Clone, PartialEq)]
115pub struct Rule {
116 pub selectors: Vec<Selector>,
117 pub declarations: Vec<Declaration>,
118 pub layer: Option<usize>,
123 pub media_query: Option<String>,
133 pub container_query: Option<String>,
142}
143
144#[derive(Debug, Clone, PartialEq)]
145pub enum Selector {
146 Simple(SimpleSelector),
147 Chain(Vec<SelectorStep>),
148}
149
150#[derive(Debug, Clone, PartialEq)]
152pub enum AttrOp {
153 Exists, Eq, Prefix, Suffix, Contains, Word, Dash, }
161
162#[derive(Debug, Clone, PartialEq)]
163pub struct AttrSelector {
164 pub name: String,
165 pub op: AttrOp,
166 pub value: String,
167 pub case_insensitive: bool,
169}
170
171#[derive(Debug, Clone, PartialEq)]
172pub enum PseudoClass {
173 FirstChild,
174 LastChild,
175 NthChild(i64, i64, Option<alloc::boxed::Box<SimpleSelector>>),
179 NthLastChild(i64, i64, Option<alloc::boxed::Box<SimpleSelector>>),
181 Not(alloc::boxed::Box<SimpleSelector>),
183 Checked,
185 Disabled,
187 FirstOfType,
190 LastOfType,
191 NthOfType(i64, i64),
193 NthLastOfType(i64, i64),
195 OnlyOfType,
197 Empty,
199 OnlyChild,
201 Target,
203 Is(Vec<SimpleSelector>),
206 Where(Vec<SimpleSelector>),
208 Lang(String),
212 Dir(String),
217 Has(Vec<(HasCombinator, SimpleSelector)>),
225 Unmatchable(String),
229 Heading(Vec<i64>),
232 Other(String),
233}
234
235#[derive(Debug, Clone, Copy, PartialEq, Eq)]
238pub enum PseudoElement {
239 Before,
240 After,
241 Marker,
242 FirstLine,
243 FirstLetter,
244 Placeholder,
245 Selection,
246 Backdrop,
247}
248
249#[derive(Debug, Clone, PartialEq)]
250pub struct SelectorStep {
251 pub simple: SimpleSelector,
252 pub combinator: Option<Combinator>,
253}
254
255#[derive(Debug, Clone, Copy, PartialEq, Eq)]
256pub enum Combinator {
257 Descendant,
258 Child,
259 NextSibling,
261 SubsequentSibling,
263}
264
265#[derive(Debug, Clone, Copy, PartialEq, Eq)]
268pub enum HasCombinator {
269 Descendant,
271 Child,
273 NextSibling,
275 SubsequentSibling,
277}
278
279#[derive(Debug, Clone, PartialEq, Default)]
280pub struct SimpleSelector {
281 pub tag_name: Option<String>,
282 pub id: Option<String>,
283 pub class: Vec<String>,
284 pub pseudo_classes: Vec<PseudoClass>,
285 pub attrs: Vec<AttrSelector>,
286 pub universal: bool,
288 pub pseudo_element: Option<PseudoElement>,
290}
291
292#[derive(Debug, Clone, PartialEq, Eq)]
293pub struct Declaration {
294 pub name: String,
295 pub value: String,
296 pub important: bool,
298}
299
300pub trait VarLookup {
302 fn var(&self, name: &str) -> Option<&str>;
303}
304
305impl VarLookup for BTreeMap<String, String> {
306 fn var(&self, name: &str) -> Option<&str> {
307 self.get(name).map(String::as_str)
308 }
309}
310
311#[derive(Debug, Default, Clone)]
317pub struct CssVars {
318 own: BTreeMap<String, String>,
319 parent: Option<alloc::rc::Rc<CssVars>>,
320 depth: u16,
321 hash: (u64, u64),
323}
324
325impl CssVars {
326 const MAX_DEPTH: u16 = 8;
327
328 pub fn layered(parent: &alloc::rc::Rc<CssVars>, own: BTreeMap<String, String>) -> Self {
330 let mut h = super::style_memo::KeyHasher::new();
331 h.key(parent.hash);
332 for (k, v) in &own {
333 h.bytes(k.as_bytes());
334 h.bytes(v.as_bytes());
335 }
336 let hash = h.finish();
337 if parent.is_empty() {
338 return CssVars { own, parent: None, depth: 0, hash };
339 }
340 if parent.depth + 1 >= Self::MAX_DEPTH {
341 let mut flat = parent.to_map();
342 flat.extend(own);
343 return CssVars { own: flat, parent: None, depth: 0, hash };
344 }
345 CssVars { own, parent: Some(parent.clone()), depth: parent.depth + 1, hash }
346 }
347
348 pub(crate) fn content_hash(&self) -> (u64, u64) {
350 self.hash
351 }
352
353 pub fn get(&self, name: &str) -> Option<&String> {
354 let mut cur = self;
355 loop {
356 if let Some(v) = cur.own.get(name) {
357 return Some(v);
358 }
359 match &cur.parent {
360 Some(p) => cur = p,
361 None => return None,
362 }
363 }
364 }
365
366 pub fn is_empty(&self) -> bool {
367 self.own.is_empty() && self.parent.as_ref().is_none_or(|p| p.is_empty())
368 }
369
370 pub fn to_map(&self) -> BTreeMap<String, String> {
372 let mut out = match &self.parent {
373 Some(p) => p.to_map(),
374 None => BTreeMap::new(),
375 };
376 out.extend(self.own.iter().map(|(k, v)| (k.clone(), v.clone())));
377 out
378 }
379}
380
381impl PartialEq for CssVars {
382 fn eq(&self, o: &Self) -> bool {
383 self.to_map() == o.to_map()
384 }
385}
386
387impl VarLookup for CssVars {
388 fn var(&self, name: &str) -> Option<&str> {
389 self.get(name).map(String::as_str)
390 }
391}
392
393pub(crate) struct VarsView<'v> {
395 pub own: &'v BTreeMap<String, String>,
396 pub parent: &'v CssVars,
397}
398
399impl VarsView<'_> {
400 pub fn get(&self, name: &str) -> Option<&String> {
401 self.own.get(name).or_else(|| self.parent.get(name))
402 }
403}
404
405impl VarLookup for VarsView<'_> {
406 fn var(&self, name: &str) -> Option<&str> {
407 self.get(name).map(String::as_str)
408 }
409}
410
411#[derive(Debug, Clone)]
413pub struct StyledNode<'a> {
414 pub node: &'a Node,
415 pub specified_values: alloc::rc::Rc<BTreeMap<String, String>>,
417 pub hover_values: Option<BTreeMap<String, String>>,
418 pub focus_values: Option<BTreeMap<String, String>>,
424 pub active_values: Option<BTreeMap<String, String>>,
427 pub css_vars: alloc::rc::Rc<CssVars>,
432 pub children: Vec<StyledNode<'a>>,
433 pub edges_cache: core::cell::RefCell<Vec<(i32, [i32; 12], [i32; 12])>>,
438 pub intrinsic_size_cache: core::cell::RefCell<Option<(i32, bool, bool, i32, i32)>>,
441 pub block_intrinsic_cache: core::cell::RefCell<Option<(u8, i32, i32, i32)>>,
445 pub layout_subtree_cache: core::cell::Cell<Option<(u64, u64, bool)>>,
448}
449
450pub static CUR_WORLD: core::sync::atomic::AtomicU8 = core::sync::atomic::AtomicU8::new(0);
455pub static WM_SEEN: core::sync::atomic::AtomicBool = core::sync::atomic::AtomicBool::new(false);
458
459pub(crate) fn world_phys_side(w: u8, s: usize) -> usize {
462 if w == 0 {
463 return s;
464 }
465 let fb = w & 2 != 0;
466 let fi = w & 4 != 0;
467 match s {
468 0 => if fb { 1 } else { 3 },
469 2 => if fb { 3 } else { 1 },
470 3 => if fi { 2 } else { 0 },
471 _ => if fi { 0 } else { 2 },
472 }
473}
474
475fn world_phys_name(name: &str, w: u8) -> Option<&'static str> {
477 match name {
478 "width" => return Some("height"),
479 "height" => return Some("width"),
480 "min-width" => return Some("min-height"),
481 "min-height" => return Some("min-width"),
482 "max-width" => return Some("max-height"),
483 "max-height" => return Some("max-width"),
484 "overflow-x" => return Some("overflow-y"),
485 "overflow-y" => return Some("overflow-x"),
486 _ => {}
487 }
488 const SIDES: [[&str; 4]; 7] = [
490 ["margin-top", "margin-right", "margin-bottom", "margin-left"],
491 ["padding-top", "padding-right", "padding-bottom", "padding-left"],
492 ["border-top-width", "border-right-width", "border-bottom-width", "border-left-width"],
493 ["border-top-style", "border-right-style", "border-bottom-style", "border-left-style"],
494 ["border-top-color", "border-right-color", "border-bottom-color", "border-left-color"],
495 ["top", "right", "bottom", "left"],
496 ["border-top", "border-right", "border-bottom", "border-left"],
497 ];
498 for fam in SIDES.iter() {
499 for (i, n) in fam.iter().enumerate() {
500 if *n == name {
501 return Some(fam[world_phys_side(w, i)]);
502 }
503 }
504 }
505 None
506}
507
508impl<'a> StyledNode<'a> {
509 pub fn value(&self, name: &str) -> Option<String> {
510 self.value_ref(name).map(String::from)
511 }
512
513 pub fn value_ref(&self, name: &str) -> Option<&str> {
514 let w = CUR_WORLD.load(core::sync::atomic::Ordering::Relaxed);
515 if w != 0 {
516 return self.value_ref_world(name, w);
517 }
518 self.specified_values.get(name).map(|s| s.as_str())
519 }
520
521 #[cold]
523 fn value_ref_world(&self, name: &str, w: u8) -> Option<&str> {
524 if name == "direction" {
525 return Some("ltr");
526 }
527 let phys = world_phys_name(name, w).unwrap_or(name);
528 self.specified_values.get(phys).map(|s| s.as_str())
529 }
530
531 pub fn value_raw(&self, name: &str) -> Option<&str> {
533 self.specified_values.get(name).map(|s| s.as_str())
534 }
535}
536