diff --git a/src/interpreter/mod.rs b/src/interpreter/mod.rs index 3bb2ed3..1232186 100644 --- a/src/interpreter/mod.rs +++ b/src/interpreter/mod.rs @@ -48,6 +48,8 @@ impl Interpreter { //let rhei_ctx = RheiContext::new(&rhei_scripts); //rhei_ctx.initialize(&mut variables); + stylesheet.build_index(); + Ok(Document { roots, components, variables, rhei_scripts, stylesheet, interner: Interner::new(), tracker }) } diff --git a/src/interpreter/style.rs b/src/interpreter/style.rs index f8a41c5..9ce1369 100644 --- a/src/interpreter/style.rs +++ b/src/interpreter/style.rs @@ -457,9 +457,19 @@ impl StyleRule { } -#[derive(Debug, Clone, Default)] +#[derive(Debug, Clone)] pub struct StyleSheet { rules: Vec, + index: StyleIndex, +} + +impl Default for StyleSheet { + fn default() -> Self { + Self { + rules: Vec::new(), + index: StyleIndex::new(Vec::new()), + } + } } impl StyleSheet { @@ -473,6 +483,11 @@ impl StyleSheet { } } + /// Rebuild the style index (call after all rules are added). + pub fn build_index(&mut self) { + self.index = StyleIndex::new(std::mem::take(&mut self.rules)); + } + pub fn matching_rules<'a>( &'a self, type_name: &str, @@ -484,24 +499,10 @@ impl StyleSheet { preceding_siblings: &[AncestorInfo], el_attributes: &HashMap, ) -> Vec<&'a HashMap> { - let mut matched: Vec<(usize, &StyleRule)> = self - .rules - .iter() - .enumerate() - .filter(|(_, rule)| { - rule.selector - .matches(type_name, el_id, el_classes, active_pseudo, structural, ancestors, preceding_siblings, el_attributes) - }) - .collect(); - - matched.sort_by(|(i, a), (j, b)| { - a.selector - .specificity() - .cmp(&b.selector.specificity()) - .then_with(|| i.cmp(j)) - }); - - matched.into_iter().map(|(_, rule)| &rule.properties).collect() + self.index.query( + type_name, el_id, el_classes, active_pseudo, + structural, ancestors, preceding_siblings, el_attributes, + ) } pub fn matching_pseudo_rules( @@ -516,14 +517,12 @@ impl StyleSheet { el_attributes: &HashMap, ) -> HashMap { let mut props = HashMap::new(); - for rule in &self.rules { - if !rule.selector.has_pseudo_class(pseudo) { - continue; - } - if !rule.selector.matches(type_name, el_id, el_classes, &[pseudo], structural, ancestors, preceding_siblings, el_attributes) { - continue; - } - for (k, v) in &rule.properties { + let all_sheets = self.matching_rules( + type_name, el_id, el_classes, &[pseudo], + structural, ancestors, preceding_siblings, el_attributes, + ); + for sheet in &all_sheets { + for (k, v) in sheet.iter() { props.insert(k.clone(), v.clone()); } } @@ -531,7 +530,212 @@ impl StyleSheet { } pub fn is_empty(&self) -> bool { - self.rules.is_empty() + self.index.rules.is_empty() + } +} + +type RuleId = usize; + +/// Pre-built index for O(1) rule candidate lookup instead of O(N) scan. +#[derive(Debug, Clone)] +pub struct StyleIndex { + /// Rules keyed by tag name (e.g. "Button", "Panel") + by_tag: HashMap>, + /// Rules keyed by class name + by_class: HashMap>, + /// Rules keyed by id + by_id: HashMap>, + /// Rules keyed by (tag, class) pair + by_tag_class: HashMap<(String, String), Vec>, + /// Rules keyed by (tag, id) pair + by_tag_id: HashMap<(String, String), Vec>, + /// Complex selectors that can't be indexed (combinators, pseudo-classes, etc.) + complex_rules: Vec<(ComplexSelector, RuleId)>, + /// All rules, sorted by specificity once at build time + rules: Vec, + /// Epoch counter: incremented on rebuild, used for cache invalidation + epoch: u64, +} + +impl StyleIndex { + pub fn new(rules: Vec) -> Self { + let mut idx = Self { + by_tag: HashMap::new(), + by_class: HashMap::new(), + by_id: HashMap::new(), + by_tag_class: HashMap::new(), + by_tag_id: HashMap::new(), + complex_rules: Vec::new(), + rules: Vec::new(), + epoch: 0, + }; + + // Sort rules by specificity once + let mut sorted_rules: Vec<(usize, StyleRule)> = rules.into_iter().enumerate().collect(); + sorted_rules.sort_by(|(i, a), (j, b)| { + a.selector + .specificity() + .cmp(&b.selector.specificity()) + .then_with(|| i.cmp(j)) + }); + + for (new_id, (_, rule)) in sorted_rules.into_iter().enumerate() { + let rid = idx.rules.len(); + idx.rules.push(rule); + + let simple = idx.rules[rid].selector.as_simple().cloned(); + + if let Some(compound) = simple { + let has_pseudo = !compound.pseudo_classes.is_empty(); + let has_complex_combinator = false; // simple selector = no combinators + + if has_pseudo || has_complex_combinator { + idx.complex_rules.push((idx.rules[rid].selector.clone(), rid)); + } else { + // Index by tag + if let Some(ref tag) = compound.tag { + idx.by_tag.entry(tag.clone()).or_default().push(rid); + if let Some(ref id) = compound.id { + idx.by_tag_id.entry((tag.clone(), id.clone())).or_default().push(rid); + } + for cls in &compound.classes { + idx.by_tag_class.entry((tag.clone(), cls.clone())).or_default().push(rid); + } + } + // Index by class + for cls in &compound.classes { + idx.by_class.entry(cls.clone()).or_default().push(rid); + } + // Index by id + if let Some(ref id) = compound.id { + idx.by_id.entry(id.clone()).or_default().push(rid); + } + } + } else { + // Complex selector (combinators, multiple compounds) + idx.complex_rules.push((idx.rules[rid].selector.clone(), rid)); + } + } + + idx + } + + pub fn epoch(&self) -> u64 { + self.epoch + } + + pub fn query<'a>( + &'a self, + type_name: &str, + el_id: Option<&str>, + el_classes: &[&str], + active_pseudo: &[&str], + structural: &StructuralContext, + ancestors: &[AncestorInfo], + preceding_siblings: &[AncestorInfo], + el_attributes: &HashMap, + ) -> Vec<&'a HashMap> { + // Collect candidates from indexes + let mut candidates: Vec = Vec::new(); + + // Start with tag index + if let Some(tag_rules) = self.by_tag.get(type_name) { + // If we have tag+id, prefer that for more precise filtering + if let Some(id) = el_id { + if let Some(tag_id_rules) = self.by_tag_id.get(&(type_name.to_string(), id.to_string())) { + candidates = tag_id_rules.clone(); + } else { + candidates = tag_rules.clone(); + } + } else { + candidates = tag_rules.clone(); + } + + // Intersect with class if applicable + if !el_classes.is_empty() { + let first_class = el_classes[0]; + if let Some(tag_class_rules) = self.by_tag_class.get(&(type_name.to_string(), first_class.to_string())) { + candidates.retain(|r| tag_class_rules.contains(r)); + } else { + // No rules for tag+class, clear non-matching + candidates.retain(|r| { + el_classes.iter().any(|cls| { + self.by_class.get(*cls).map_or(false, |cr| cr.contains(r)) + }) + }); + } + } + + // Also check additional class-only rules + for cls in el_classes.iter().skip(if el_id.is_some() { 0 } else { 1 }) { + if let Some(cls_rules) = self.by_class.get(*cls) { + for &r in cls_rules { + if !candidates.contains(&r) { + candidates.push(r); + } + } + } + } + + // Also check id-only rules + if let Some(id) = el_id { + if let Some(id_rules) = self.by_id.get(id) { + for &r in id_rules { + if !candidates.contains(&r) { + candidates.push(r); + } + } + } + } + } else { + // No tag match — check class and id indexes + for cls in el_classes { + if let Some(cls_rules) = self.by_class.get(*cls) { + candidates.extend(cls_rules); + } + } + if let Some(id) = el_id { + if let Some(id_rules) = self.by_id.get(id) { + candidates.extend(id_rules); + } + } + } + + // De-duplicate while preserving order + let mut seen = std::collections::HashSet::new(); + candidates.retain(|r| seen.insert(*r)); + + // Test candidates against full selector + let mut matched: Vec<&StyleRule> = Vec::new(); + for &rid in &candidates { + let rule = &self.rules[rid]; + if rule.selector.matches( + type_name, el_id, el_classes, active_pseudo, + structural, ancestors, preceding_siblings, el_attributes, + ) { + matched.push(rule); + } + } + + // Test complex rules + for (sel, rid) in &self.complex_rules { + if sel.matches( + type_name, el_id, el_classes, active_pseudo, + structural, ancestors, preceding_siblings, el_attributes, + ) { + matched.push(&self.rules[*rid]); + } + } + + // Re-sort matched by specificity (candidates are already sorted) + // but we only need to sort the matched subset + matched.sort_by(|a, b| { + a.selector + .specificity() + .cmp(&b.selector.specificity()) + }); + + matched.into_iter().map(|r| &r.properties).collect() } }