use std::{ collections::HashMap, fmt::{self, Write}, mem::take, ops::Deref, sync::{Arc, LazyLock}, }; use cssparser::*; use precomputed_hash::PrecomputedHash; use selectors::parser::{ NonTSPseudoClass, ParseRelative, PseudoElement as PseudoElementTrait, SelectorImpl as SelectorImplTrait, SelectorList, }; use crate::style::ContainerQuery; #[cfg(feature = "font-face")] use crate::style::font_face_rule::FontFaceRule; pub use crate::style::media_query::MediaQueryList; use crate::style::{ DeclarationOrigin, IgnoredDeclaration, IgnoredReason, PageName, PropertySyntax, page_rule::{PageContext, PageDescriptors, PageKind, PageRule, PageSelector, PageStyles}, }; use crate::viewport::Viewport; use crate::{ Xxh3HashSet, error::{StyleSheetParseError, StyleSheetParseErrorKind}, keyframes::parse_keyframe_prelude, matching::RuleIndex, style::{ BreakpointOverrides, FromCssStr, KeyframeRule, KeyframesRule, Length, RawDeclaration, RawDeclarationParser, StyleDeclaration, StyleDeclarationBlock, expand_apply, is_reserved_custom_ident, supports::parse_supports_condition, }, }; /// A registered custom property from an `@property` rule. #[derive(Debug, Clone, PartialEq)] pub struct PropertyRule { /// Custom property name, including the leading `--`. pub name: String, /// The values the property takes. pub syntax: PropertySyntax, /// Whether the property inherits. pub inherits: bool, /// Declared `initial-value`, if any. pub initial_value: Option, /// Media queries this rule is gated behind. pub media_queries: Vec, } /// A name in a cascade layer path. #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub(crate) enum LayerName { /// An explicitly named layer. Named(String), /// An anonymous layer. Anonymous, } pub(crate) type LayerPath = Vec; /// An ASCII-case-insensitive CSS identifier. #[derive(Debug, Clone, PartialEq, Eq, Default)] pub(crate) struct Ident(String); impl Deref for Ident { type Target = str; fn deref(&self) -> &Self::Target { &self.0 } } impl AsRef for Ident { fn as_ref(&self) -> &str { &self.0 } } impl PartialEq<&str> for Ident { fn eq(&self, other: &&str) -> bool { self.0 == *other } } impl PartialEq for &str { fn eq(&self, other: &Ident) -> bool { self == &other.0 } } impl From<&str> for Ident { fn from(s: &str) -> Self { Self(s.to_owned()) } } impl ToCss for Ident { fn to_css(&self, dest: &mut W) -> fmt::Result where W: Write, { serialize_identifier(&self.0, dest) } } impl PrecomputedHash for Ident { fn precomputed_hash(&self) -> u32 { let mut hash = 0x811c9dc5u32; for byte in self.0.as_bytes() { hash ^= u32::from(byte.to_ascii_lowercase()); hash = hash.wrapping_mul(0x0100_0193); } hash } } /// Selector type bindings for the `selectors` crate. #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) struct SelectorImpl; // Pseudo-classes parse so a selector list keeps its other selectors, and only the static ones, // such as `:lang()`, `:dir()`, and the form control states, match. #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) enum PseudoClass { /// `:lang(en, fr, ...)` — one or more comma-separated BCP-47 basic-filtering ranges. Lang(Vec>), /// `:dir(ltr)` or `:dir(rtl)`, by the keyword it names; any other keyword matches nothing. Dir(Ident), /// A form control state, such as `:disabled`. FormState(FormState), /// Any other pseudo-class, parsed but never matched. Other(Ident), } impl ToCss for PseudoClass { fn to_css(&self, dest: &mut W) -> fmt::Result where W: Write, { match self { Self::Lang(ranges) => { dest.write_str(":lang(")?; for (i, range) in ranges.iter().enumerate() { if i > 0 { dest.write_str(", ")?; } dest.write_str(range)?; } dest.write_char(')') } Self::Dir(direction) => { dest.write_str(":dir(")?; direction.to_css(dest)?; dest.write_char(')') } Self::FormState(state) => { dest.write_char(':')?; dest.write_str(state.name()) } Self::Other(name) => { dest.write_char(':')?; name.to_css(dest) } } } } /// A pseudo-class HTML defines on form control state. /// #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum FormState { Disabled, Enabled, Checked, Indeterminate, PlaceholderShown, ReadOnly, ReadWrite, Required, Optional, } impl FormState { const NAMES: [(&'static str, Self); 9] = [ ("disabled", Self::Disabled), ("enabled", Self::Enabled), ("checked", Self::Checked), ("indeterminate", Self::Indeterminate), ("placeholder-shown", Self::PlaceholderShown), ("read-only", Self::ReadOnly), ("read-write", Self::ReadWrite), ("required", Self::Required), ("optional", Self::Optional), ]; fn from_name(name: &str) -> Option { Self::NAMES .iter() .find(|(state_name, _)| state_name.eq_ignore_ascii_case(name)) .map(|&(_, state)| state) } fn name(self) -> &'static str { Self::NAMES .iter() .find(|&&(_, state)| state == self) .map_or("", |&(name, _)| name) } } impl NonTSPseudoClass for PseudoClass { fn is_active_or_hover(&self) -> bool { false } fn is_user_action_state(&self) -> bool { false } } /// A pseudo-element. #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) enum PseudoElement { /// `::before`. Before, /// `::after`. After, /// Any other pseudo-element, kept but never matched. Other(Ident), } impl PseudoElement { fn from_name(name: &str) -> Self { if name.eq_ignore_ascii_case("before") { Self::Before } else if name.eq_ignore_ascii_case("after") { Self::After } else { Self::Other(Ident::from(name)) } } fn as_str(&self) -> &str { match self { Self::Before => "before", Self::After => "after", Self::Other(name) => name, } } } impl ToCss for PseudoElement { fn to_css(&self, dest: &mut W) -> fmt::Result where W: Write, { dest.write_str("::")?; serialize_identifier(self.as_str(), dest) } } impl PseudoElementTrait for PseudoElement {} impl SelectorImplTrait for SelectorImpl { type ExtraMatchingData<'a> = (); type AttrValue = Ident; type Identifier = Ident; type LocalName = Ident; type NamespaceUrl = Ident; type NamespacePrefix = Ident; type BorrowedNamespaceUrl = Ident; type BorrowedLocalName = Ident; type NonTSPseudoClass = PseudoClass; type PseudoElement = PseudoElement; } pub(crate) struct TakumiSelectorParser; impl<'i> selectors::Parser<'i> for TakumiSelectorParser { type Impl = SelectorImpl; type Error = StyleSheetParseError; fn parse_parent_selector(&self) -> bool { true } fn parse_host(&self) -> bool { true } fn parse_is_and_where(&self) -> bool { true } fn parse_has(&self) -> bool { true } fn parse_non_ts_pseudo_class( &self, name: &str, ) -> Result<::NonTSPseudoClass, ParseError> { Ok(FormState::from_name(name).map_or_else( || PseudoClass::Other(Ident::from(name)), PseudoClass::FormState, )) } fn parse_non_ts_functional_pseudo_class( &self, name: &str, parser: &mut Parser<'i>, _after_part: bool, ) -> Result<::NonTSPseudoClass, ParseError> { if name.eq_ignore_ascii_case("lang") { let ranges = parser.parse_comma_separated(|input| { let token = input.next()?.clone(); match &token { Token::Ident(ident) => Ok(ident.as_ref().into()), Token::QuotedString(s) => Ok(s.as_ref().into()), _ => Err(ParseError::unexpected_token()), } })?; return Ok(PseudoClass::Lang(ranges)); } if name.eq_ignore_ascii_case("dir") { let direction = parser.expect_ident()?; return Ok(PseudoClass::Dir(Ident::from( &*direction.to_ascii_lowercase(), ))); } while parser.next_including_whitespace_and_comments().is_ok() {} Ok(PseudoClass::Other(Ident::from(name))) } fn parse_pseudo_element( &self, name: &str, ) -> Result<::PseudoElement, ParseError> { Ok(PseudoElement::from_name(name)) } fn parse_functional_pseudo_element( &self, name: &str, arguments: &mut Parser<'i>, ) -> Result<::PseudoElement, ParseError> { while arguments.next_including_whitespace_and_comments().is_ok() {} Ok(PseudoElement::Other(Ident::from(name))) } } #[derive(Debug, Clone, Default)] struct StyleSheetFragment { rules: Vec, keyframes: Vec, property_rules: Vec, #[cfg(feature = "font-face")] font_faces: Vec, page_rules: Vec, declared_layers: Vec, preflight: bool, /// The declarations and at-rules parsing dropped. ignored: Vec, } impl StyleSheetFragment { /// A fragment that holds only the at-rule parsing dropped. fn ignoring(at_rule: IgnoredDeclaration) -> Self { Self { ignored: vec![at_rule], ..Self::default() } } fn extend(&mut self, other: Self) { self.rules.extend(other.rules); self.keyframes.extend(other.keyframes); self.property_rules.extend(other.property_rules); #[cfg(feature = "font-face")] self.font_faces.extend(other.font_faces); self.page_rules.extend(other.page_rules); self.declared_layers.extend(other.declared_layers); self.preflight |= other.preflight; self.ignored.extend(other.ignored); } } #[derive(Debug)] enum StyleRuleBodyItem { Declarations(Box), Rules(StyleSheetFragment), } /// Declarations gathered for one rule, split at the importance boundary. #[derive(Default)] struct RuleDeclarations { normal: StyleDeclarationBlock, important: StyleDeclarationBlock, } impl RuleDeclarations { /// Adds one parsed declaration, whose block is important as a whole or not at all. fn push(&mut self, block: StyleDeclarationBlock) { if block.importance.is_empty() { self.normal.append(block); } else { self.important.append(block); } } fn is_empty(&self) -> bool { self.normal.declarations.is_empty() && self.important.declarations.is_empty() } /// Moves out the declarations parsing dropped from both blocks. fn take_ignored(&mut self) -> impl Iterator { take(&mut self.normal.ignored) .into_iter() .chain(take(&mut self.important.ignored)) } } /// What a nested rule inherits from the rules around it: the media queries, layer, scope, and /// container queries gating it, and whether invalid items are dropped. #[derive(Clone, Copy)] struct NestingContext<'a> { media_queries: &'a [MediaQueryList], layer: Option<&'a LayerPath>, /// The scope of an `@scope` rule nested in a style rule around it. scope: Option<&'a Arc>, /// The queries of `@container` rules nested in style rules around it. container_queries: &'a [Arc], lossy: bool, } /// The items a rule or declaration list yields, with the invalid ones dropped /// when `lossy`, each dropped declaration added to `ignored`, and their errors /// kept otherwise. fn recover<'i, T>( items: impl Iterator, &'i str, SourceLocation)>>, lossy: bool, ignored: &mut Vec, ) -> impl Iterator>> { items.filter_map(move |item| match item { Ok(item) => Some(Ok(item)), Err((_, source, location)) if lossy => { log_ignored(source, location); ignored.extend(IgnoredDeclaration::invalid_value( source, DeclarationOrigin::StyleSheet, )); None } Err((error, ..)) => Some(Err(error)), }) } /// Logs the CSS a lossy parse dropped, `source` cut to its first line. pub(crate) fn log_ignored(source: &str, location: SourceLocation) { log::debug!( target: "takumi::style", "ignored `{}` at line {}, column {} of its style sheet or `style` attribute", source.trim().lines().next().unwrap_or_default(), location.line + 1, location.column ); } macro_rules! impl_parser_traits { ($parser:ty, $item:ty) => { impl<'i> QualifiedRuleParser<'i> for $parser { type Prelude = (); type QualifiedRule = $item; type Error = StyleSheetParseError; } impl<'i> AtRuleParser<'i> for $parser { type Prelude = (); type AtRule = $item; type Error = StyleSheetParseError; } impl<'i> RuleBodyItemParser<'i, $item, StyleSheetParseError> for $parser { fn parse_qualified(&self) -> bool { false } fn parse_declarations(&self) -> bool { true } } }; } /// Parses one declaration, recording a property takumi does not support as written in `origin`. pub(crate) struct StyleDeclarationParser { pub(crate) origin: DeclarationOrigin, } impl<'i> DeclarationParser<'i> for StyleDeclarationParser { type Declaration = StyleDeclarationBlock; type Error = StyleSheetParseError; fn parse_value( &mut self, name: CowRcStr<'i>, input: &mut Parser<'i>, _state: &ParserState, ) -> Result> { let mut declarations = StyleDeclarationBlock::parse(&name, input, self.origin).map_err(ParseError::into)?; if input.try_parse(parse_important).is_ok() { declarations.mark_important(); } Ok(declarations) } } impl_parser_traits!(StyleDeclarationParser, StyleDeclarationBlock); struct NestedStyleRuleParser<'a> { parent_selectors: SelectorList, context: NestingContext<'a>, } impl<'i> DeclarationParser<'i> for NestedStyleRuleParser<'_> { type Declaration = StyleRuleBodyItem; type Error = StyleSheetParseError; fn parse_value( &mut self, name: CowRcStr<'i>, input: &mut Parser<'i>, state: &ParserState, ) -> Result> { let mut parser = StyleDeclarationParser { origin: DeclarationOrigin::StyleSheet, }; parser .parse_value(name, input, state) .map(Box::new) .map(StyleRuleBodyItem::Declarations) } } impl<'i> QualifiedRuleParser<'i> for NestedStyleRuleParser<'_> { type Prelude = SelectorList; type QualifiedRule = StyleRuleBodyItem; type Error = StyleSheetParseError; fn parse_prelude( &mut self, input: &mut Parser<'i>, ) -> Result> { SelectorList::parse(&TakumiSelectorParser, input, ParseRelative::ForNesting) } fn parse_block( &mut self, nested_selectors: Self::Prelude, _location: &ParserState, input: &mut Parser<'i>, ) -> Result> { let selectors = nested_selectors.replace_parent_selector(&self.parent_selectors); self .context .parse_style_rule_block(selectors, input) .map(StyleRuleBodyItem::Rules) } } impl<'i> AtRuleParser<'i> for NestedStyleRuleParser<'_> { type Prelude = AtRulePrelude; type AtRule = StyleRuleBodyItem; type Error = StyleSheetParseError; fn parse_prelude( &mut self, name: CowRcStr<'i>, input: &mut Parser<'i>, ) -> Result> { parse_at_rule_prelude(name, input) } fn parse_block( &mut self, prelude: Self::Prelude, _location: &ParserState, input: &mut Parser<'i>, ) -> Result> { self .context .parse_nested_at_rule_block(&self.parent_selectors, prelude, input) .map(StyleRuleBodyItem::Rules) } fn rule_without_block( &mut self, prelude: Self::Prelude, _start: &ParserState, ) -> Result { match prelude { // A rule on the parent's selectors, so declarations around `@apply` keep their order. AtRulePrelude::Apply(block) => { let (normal, important) = block.split_importance(); Ok(StyleRuleBodyItem::Rules(StyleSheetFragment { rules: vec![self.context.rule( self.parent_selectors.clone(), RuleDeclarations { normal, important }, )], ..StyleSheetFragment::default() })) } AtRulePrelude::Unknown(at_rule) => Ok(StyleRuleBodyItem::Rules( StyleSheetFragment::ignoring(*at_rule), )), _ => Err(()), } } } impl<'i> RuleBodyItemParser<'i, StyleRuleBodyItem, StyleSheetParseError> for NestedStyleRuleParser<'_> { fn parse_qualified(&self) -> bool { true } fn parse_declarations(&self) -> bool { true } } struct KeyframeDeclarationParser; impl<'i> DeclarationParser<'i> for KeyframeDeclarationParser { type Declaration = StyleDeclarationBlock; type Error = StyleSheetParseError; fn parse_value( &mut self, name: CowRcStr<'i>, input: &mut Parser<'i>, _state: &ParserState, ) -> Result> { let declarations = StyleDeclarationBlock::parse(&name, input, DeclarationOrigin::StyleSheet) .map_err(ParseError::into)?; // !important flag is ignored in keyframe declartion. // Ref: https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/At-rules/@keyframes#!important_in_a_keyframe input.try_parse(parse_important).ok(); Ok(declarations) } } impl_parser_traits!(KeyframeDeclarationParser, StyleDeclarationBlock); struct KeyframeRuleParser { lossy: bool, } impl<'i> QualifiedRuleParser<'i> for KeyframeRuleParser { type Prelude = Vec; type QualifiedRule = KeyframeRule; type Error = StyleSheetParseError; fn parse_prelude( &mut self, input: &mut Parser<'i>, ) -> Result> { parse_keyframe_prelude(input) } fn parse_block( &mut self, offsets: Self::Prelude, _location: &ParserState, input: &mut Parser<'i>, ) -> Result> { let mut declaration_parser = KeyframeDeclarationParser; let mut declarations = StyleDeclarationBlock::default(); let mut ignored = Vec::new(); for block in recover( RuleBodyParser::new(input, &mut declaration_parser), self.lossy, &mut ignored, ) { declarations.append(block?); } declarations.ignored.extend(ignored); Ok(KeyframeRule { offsets, declarations, }) } } impl<'i> AtRuleParser<'i> for KeyframeRuleParser { type Prelude = (); type AtRule = KeyframeRule; type Error = StyleSheetParseError; } struct RuleParser { current_layer: Option, lossy: bool, /// Inside `@scope`, where a selector without `:scope` or `&` is relative to the scope's root. scoped: bool, /// False inside `@media`, `@layer` and `@supports` blocks, where `@import` /// is invalid and its preflight flag must not escape the gate. top_level: bool, } impl RuleParser { /// The parser for a block gated by an at-rule, filling `current_layer`. fn nested(&self, current_layer: Option) -> Self { Self { current_layer, lossy: self.lossy, scoped: self.scoped, top_level: false, } } /// What a rule at this level hands the rules nested in it. fn context(&self) -> NestingContext<'_> { NestingContext { media_queries: &[], layer: self.current_layer.as_ref(), scope: None, container_queries: &[], lossy: self.lossy, } } /// The layers `layer_names` declare, as paths under the current layer. fn declared_layers(&self, layer_names: &[LayerPath]) -> Vec { layer_names .iter() .map(|layer_name| extend_layer_name(self.current_layer.as_ref(), layer_name)) .collect() } fn parse_fragment<'i>( &mut self, input: &mut Parser<'i>, ) -> Result> { let lossy = self.lossy; let mut fragment = StyleSheetFragment::default(); let mut ignored = Vec::new(); for nested in recover(StyleSheetParser::new(input, self), lossy, &mut ignored) { fragment.extend(nested?); } fragment.ignored.extend(ignored); Ok(fragment) } } #[derive(Debug, Clone)] enum AtRulePrelude { Keyframes(String), Layer(Vec), Media(MediaQueryList), Property(String), #[cfg(feature = "font-face")] FontFace, Page(PageSelector), Supports(bool), /// Tailwind's `@theme`, read as the `:root` rule it compiles to, whatever its modifiers. Theme, /// A Tailwind entry point such as `@import "tailwindcss"`, which only turns Preflight on. TailwindImport { preflight: bool, }, /// `@apply`, already expanded into the declarations its utilities stand for. Apply(Box), /// `@scope`, its root and limit selectors. Scope(Scope), /// `@container`, its query. Container(ContainerQuery), /// An at-rule takumi does not implement, such as `@counter-style`, dropped /// without failing the sheet: . Unknown(Box), } /// The scope an `@scope` rule gives the style rules in it: the elements its `start` selectors /// match, or the tree's root without them, down to but not into the elements its `end` selectors /// match. #[derive(Debug, Clone)] pub(crate) struct Scope { pub(crate) start: Option>, pub(crate) end: Option>, /// The scope of an `@scope` rule this one is in, which its roots must be in. pub(crate) parent: Option>, } impl Scope { /// This scope inside `outer`, at the end of its chain of enclosing scopes. fn within(&self, outer: &Arc) -> Arc { Arc::new(Self { parent: Some(match &self.parent { Some(parent) => parent.within(outer), None => Arc::clone(outer), }), ..self.clone() }) } } /// A style rule with its selectors and declaration blocks. Opaque: its /// `selectors` crate innards stay out of takumi's public API. #[derive(Debug, Clone)] pub(crate) struct CssRule { /// Selectors this rule applies to. pub(crate) selectors: SelectorList, /// Declarations without `!important`. pub(crate) normal_declarations: StyleDeclarationBlock, /// Declarations marked `!important`. pub(crate) important_declarations: StyleDeclarationBlock, /// Media queries gating this rule. pub(crate) media_queries: Vec, /// Cascade layer this rule belongs to. pub(crate) layer: Option, /// Resolved ordinal of the rule's layer. pub(crate) layer_order: Option, /// The scope of the `@scope` rule it is in. pub(crate) scope: Option>, /// The queries of the `@container` rules it is in, which must all hold. pub(crate) container_queries: Vec>, } fn parse_property_rule<'i>( property_name: String, input: &mut Parser<'i>, ) -> Result> { let mut parser = RawDeclarationParser; let mut syntax = None; let mut inherits = None; let mut initial_value = None; let mut invalid_inherits = false; for descriptor in RuleBodyParser::new(input, &mut parser) { let RawDeclaration { name, value, important, } = descriptor.map_err(|(error, ..)| error)?; // Blink parses descriptors without the `!important` annotation, so one that has it is invalid. if important { continue; } match_ignore_ascii_case! { &name, "syntax" => syntax = Some(value.to_owned()), "inherits" => match_ignore_ascii_case! { &value, "true" => inherits = Some(true), "false" => inherits = Some(false), _ => invalid_inherits = true, }, "initial-value" => initial_value = Some(value.to_owned()), _ => {}, } } if invalid_inherits { return Err(ParseError::custom( StyleSheetParseErrorKind::PropertyInheritsMustBeBoolean, )); } let Some(syntax) = syntax else { return Err(ParseError::custom( StyleSheetParseErrorKind::MissingPropertySyntax, )); }; let Some(inherits) = inherits else { return Err(ParseError::custom( StyleSheetParseErrorKind::MissingPropertyInherits, )); }; // The descriptor is one CSS string, which the syntax is read from once decoded. let mut syntax_input = Parser::new(&syntax); let decoded = syntax_input.expect_string().map(ToString::to_string).ok(); let syntax = decoded .filter(|_| syntax_input.is_exhausted()) .and_then(|decoded| decoded.parse::().ok()) .ok_or_else(|| ParseError::custom(StyleSheetParseErrorKind::InvalidPropertySyntax))?; // css-properties-values-api-1 2.1: only the universal syntax may leave the initial value out, // and any other must take it and compute it without an element. let initial_value = match (&syntax, initial_value) { (PropertySyntax::Universal, initial_value) => initial_value, (_, None) => { return Err(ParseError::custom( StyleSheetParseErrorKind::MissingPropertyInitialValue, )); } (_, Some(value)) if syntax.is_computationally_independent(&value) => { syntax.compute(&value, None) } _ => { return Err(ParseError::custom( StyleSheetParseErrorKind::InvalidPropertyInitialValue, )); } }; Ok(PropertyRule { name: property_name, syntax, inherits, initial_value, media_queries: Vec::new(), }) } /// Parses a `@theme` body into `:root` declarations and the `@keyframes` it carries. struct ThemeBlockParser<'a> { context: NestingContext<'a>, } enum ThemeBodyItem { Declarations(Box), Keyframes(StyleSheetFragment), } impl<'i> DeclarationParser<'i> for ThemeBlockParser<'_> { type Declaration = ThemeBodyItem; type Error = StyleSheetParseError; fn parse_value( &mut self, name: CowRcStr<'i>, input: &mut Parser<'i>, state: &ParserState, ) -> Result> { let mut parser = StyleDeclarationParser { origin: DeclarationOrigin::StyleSheet, }; parser .parse_value(name, input, state) .map(Box::new) .map(ThemeBodyItem::Declarations) } } impl<'i> AtRuleParser<'i> for ThemeBlockParser<'_> { type Prelude = AtRulePrelude; type AtRule = ThemeBodyItem; type Error = StyleSheetParseError; fn parse_prelude( &mut self, name: CowRcStr<'i>, input: &mut Parser<'i>, ) -> Result> { parse_at_rule_prelude(name, input) } fn parse_block( &mut self, prelude: Self::Prelude, _location: &ParserState, input: &mut Parser<'i>, ) -> Result> { match prelude { AtRulePrelude::Keyframes(name) => self .context .parse_keyframes_block(name, input) .map(ThemeBodyItem::Keyframes), _ => Err(ParseError::custom( StyleSheetParseErrorKind::UnsupportedNestedAtRule, )), } } } impl<'i> QualifiedRuleParser<'i> for ThemeBlockParser<'_> { type Prelude = (); type QualifiedRule = ThemeBodyItem; type Error = StyleSheetParseError; fn parse_prelude( &mut self, _input: &mut Parser<'i>, ) -> Result> { Err(ParseError::custom( StyleSheetParseErrorKind::UnsupportedNestedAtRule, )) } } impl<'i> RuleBodyItemParser<'i, ThemeBodyItem, StyleSheetParseError> for ThemeBlockParser<'_> { fn parse_qualified(&self) -> bool { false } fn parse_declarations(&self) -> bool { true } } impl NestingContext<'_> { /// A rule for `selectors` gated the way this context gates it. fn rule(self, selectors: SelectorList, declarations: RuleDeclarations) -> CssRule { CssRule { selectors, normal_declarations: declarations.normal, important_declarations: declarations.important, media_queries: self.media_queries.to_vec(), layer: self.layer.cloned(), layer_order: None, scope: self.scope.cloned(), container_queries: self.container_queries.to_vec(), } } fn parse_theme_block<'i>( self, input: &mut Parser<'i>, ) -> Result> { let selectors = SelectorList::parse( &TakumiSelectorParser, &mut Parser::new(":root"), ParseRelative::No, ) .map_err(|_| ParseError::custom(StyleSheetParseErrorKind::UnsupportedNestedAtRule))?; let mut declarations = RuleDeclarations::default(); let mut fragment = StyleSheetFragment::default(); let mut parser = ThemeBlockParser { context: self }; let mut ignored = Vec::new(); for item in recover( RuleBodyParser::new(input, &mut parser), self.lossy, &mut ignored, ) { match item? { ThemeBodyItem::Declarations(block) => declarations.push(*block), ThemeBodyItem::Keyframes(keyframes) => fragment.extend(keyframes), } } fragment.ignored.extend(declarations.take_ignored()); fragment.ignored.extend(ignored); if !declarations.is_empty() { fragment.rules.push(self.rule(selectors, declarations)); } Ok(fragment) } fn parse_keyframes_block<'i>( self, name: String, input: &mut Parser<'i>, ) -> Result> { let mut parser = KeyframeRuleParser { lossy: self.lossy }; let mut keyframes = Vec::new(); let mut ignored = Vec::new(); for keyframe in recover( StyleSheetParser::new(input, &mut parser), self.lossy, &mut ignored, ) { keyframes.push(keyframe?); } for keyframe in &mut keyframes { ignored.extend(take(&mut keyframe.declarations.ignored)); } let mut rule = KeyframesRule::builder() .name(name) .keyframes(keyframes) .build(); rule.media_queries = self.media_queries.to_vec(); Ok(StyleSheetFragment { keyframes: vec![rule], ignored, ..StyleSheetFragment::default() }) } fn parse_style_rule_block<'i>( self, selectors: SelectorList, input: &mut Parser<'i>, ) -> Result> { let mut declarations = RuleDeclarations::default(); let mut fragment = StyleSheetFragment::default(); let mut parser = NestedStyleRuleParser { parent_selectors: selectors.clone(), context: self, }; let mut ignored = Vec::new(); for item in recover( RuleBodyParser::new(input, &mut parser), self.lossy, &mut ignored, ) { match item? { StyleRuleBodyItem::Declarations(block) => declarations.push(*block), StyleRuleBodyItem::Rules(nested_rules) => { fragment.ignored.extend(declarations.take_ignored()); if !declarations.is_empty() { fragment .rules .push(self.rule(selectors.clone(), take(&mut declarations))); } fragment.extend(nested_rules); } } } fragment.ignored.extend(declarations.take_ignored()); fragment.ignored.extend(ignored); if !declarations.is_empty() { fragment.rules.push(self.rule(selectors, declarations)); } Ok(fragment) } fn parse_nested_at_rule_block<'i>( self, parent_selectors: &SelectorList, prelude: AtRulePrelude, input: &mut Parser<'i>, ) -> Result> { match prelude { AtRulePrelude::Layer(layer_names) => { ensure_single_layer_name(&layer_names)?; let Some(layer_name) = layer_names.first() else { return Ok(StyleSheetFragment::default()); }; let nested_layer = extend_layer_name(self.layer, layer_name); NestingContext { layer: Some(&nested_layer), ..self } .parse_style_rule_block(parent_selectors.clone(), input) } AtRulePrelude::Media(media_query) => { let mut media_queries = self.media_queries.to_vec(); media_queries.push(media_query); NestingContext { media_queries: &media_queries, ..self } .parse_style_rule_block(parent_selectors.clone(), input) } AtRulePrelude::Supports(true) => self.parse_style_rule_block(parent_selectors.clone(), input), AtRulePrelude::Supports(false) => Ok(skip_block(input)), AtRulePrelude::Container(query) => { let mut container_queries = self.container_queries.to_vec(); container_queries.push(Arc::new(query)); NestingContext { container_queries: &container_queries, ..self } .parse_style_rule_block(parent_selectors.clone(), input) } // A nested `@scope` roots at the elements the rule around it matches, or at the ones its // start selects with `&` for that rule, and its declarations apply to the root itself. // AtRulePrelude::Scope(scope) => { let scope = Arc::new(Scope { start: Some(match scope.start { Some(start) => start.replace_parent_selector(parent_selectors), None => parent_selectors.clone(), }), end: scope.end, parent: self.scope.cloned(), }); let root = SelectorList::parse( &TakumiSelectorParser, &mut Parser::new(":where(:scope)"), ParseRelative::No, )?; NestingContext { scope: Some(&scope), ..self } .parse_style_rule_block(root, input) } AtRulePrelude::Unknown(at_rule) => { skip_block(input); Ok(StyleSheetFragment::ignoring(*at_rule)) } AtRulePrelude::Theme => self.parse_theme_block(input), #[cfg(feature = "font-face")] AtRulePrelude::FontFace => Err(ParseError::custom( StyleSheetParseErrorKind::UnsupportedNestedAtRule, )), AtRulePrelude::Keyframes(_) | AtRulePrelude::Property(_) | AtRulePrelude::Page(_) | AtRulePrelude::TailwindImport { .. } | AtRulePrelude::Apply(_) => Err(ParseError::custom( StyleSheetParseErrorKind::UnsupportedNestedAtRule, )), } } } /// Whether the Tailwind v4 entry point `target` brings Preflight, or `None` when `target` is not one. /// fn tailwind_entry_preflight(target: &str) -> Option { match target.strip_prefix("tailwindcss")? { "" | "/index" | "/index.css" | "/preflight" | "/preflight.css" => Some(true), "/theme" | "/theme.css" | "/utilities" | "/utilities.css" => Some(false), _ => None, } } fn parse_at_rule_prelude<'i>( name: CowRcStr<'i>, input: &mut Parser<'i>, ) -> Result> { if name.eq_ignore_ascii_case("layer") { if input.is_exhausted() { return Ok(AtRulePrelude::Layer(vec![vec![LayerName::Anonymous]])); } return Ok(AtRulePrelude::Layer( input.parse_comma_separated(parse_layer_name)?, )); } if name.eq_ignore_ascii_case("keyframes") { return Ok(AtRulePrelude::Keyframes( input.expect_ident_or_string()?.to_string(), )); } if name.eq_ignore_ascii_case("media") { return MediaQueryList::parse(input).map(AtRulePrelude::Media); } if name.eq_ignore_ascii_case("container") { return ContainerQuery::parse(input).map(AtRulePrelude::Container); } if name.eq_ignore_ascii_case("scope") { let selectors = |input: &mut Parser<'i>, relative| { input.parse_nested_block(|input| SelectorList::parse(&TakumiSelectorParser, input, relative)) }; let start = input .try_parse(|input| { input.expect_parenthesis_block()?; selectors(input, ParseRelative::No) }) .ok(); let end = input .try_parse(|input| { input.expect_ident_matching("to")?; input.expect_parenthesis_block()?; selectors(input, ParseRelative::ForScope) }) .ok(); input.expect_exhausted()?; return Ok(AtRulePrelude::Scope(Scope { start, end, parent: None, })); } if name.eq_ignore_ascii_case("supports") { return parse_supports_condition(input).map(AtRulePrelude::Supports); } if name.eq_ignore_ascii_case("import") { let target = match input.next()? { Token::QuotedString(value) => value.clone(), _ => return Err(ParseError::unexpected_token()), }; let Some(preflight) = tailwind_entry_preflight(&target) else { return Err(ParseError::from_basic_kind( BasicParseErrorKind::AtRuleInvalid, )); }; // Modifiers such as `layer(base)`, `source(none)` and `important` change nothing here. while input.next().is_ok() {} return Ok(AtRulePrelude::TailwindImport { preflight }); } if name.eq_ignore_ascii_case("apply") { let mut source = String::new(); let mut start = input.position(); loop { let before = input.position(); match input.next_including_whitespace_and_comments() { Ok(Token::Comment(_)) => { source.push_str(input.slice(start..before)); source.push(' '); start = input.position(); } Ok(_) => {} Err(_) => break, } } source.push_str(input.slice_from(start)); let block = expand_apply(&source) .ok_or_else(|| ParseError::custom(StyleSheetParseErrorKind::InvalidApplyUtility))?; return Ok(AtRulePrelude::Apply(Box::new(block))); } if name.eq_ignore_ascii_case("theme") { while !input.is_exhausted() { let modifier = input.expect_ident()?.clone(); match_ignore_ascii_case! {&modifier, "reference" | "default" | "static" | "inline" => {}, _ => return Err(ParseError::unexpected_token()), } } return Ok(AtRulePrelude::Theme); } #[cfg(feature = "font-face")] if name.eq_ignore_ascii_case("font-face") { input.expect_exhausted()?; return Ok(AtRulePrelude::FontFace); } // Blink's `ConsumePageRule` drops a rule whose selector `ParsePageSelector` rejects. if name.eq_ignore_ascii_case("page") && let Ok(selector) = input.try_parse(|input| PageSelector::parse(input).ok_or(())) { return Ok(AtRulePrelude::Page(selector)); } if name.eq_ignore_ascii_case("property") { let property_name = input.expect_ident_or_string()?.to_string(); if !property_name.starts_with("--") { return Err(ParseError::custom( StyleSheetParseErrorKind::PropertyNameMustBeCustomProperty, )); } return Ok(AtRulePrelude::Property(property_name)); } let start = input.position(); while input.next().is_ok() {} Ok(AtRulePrelude::Unknown(Box::new(IgnoredDeclaration::new( format!("@{name}"), input.slice_from(start), IgnoredReason::UnknownAtRule, DeclarationOrigin::StyleSheet, )))) } pub(crate) fn parse_layer_name<'i>( input: &mut Parser<'i>, ) -> Result> { let mut segments = Vec::new(); loop { let segment = match input.next()? { Token::Ident(value) if !is_reserved_custom_ident(value) => value.to_string(), _ => return Err(ParseError::unexpected_token()), }; segments.push(LayerName::Named(segment)); if input.try_parse(|input| input.expect_delim('.')).is_err() { break; } } Ok(segments) } /// Reads a block whose rules do not apply to its end, which the parser needs /// before it accepts the block. fn skip_block(input: &mut Parser<'_>) -> StyleSheetFragment { while input.next_including_whitespace_and_comments().is_ok() {} StyleSheetFragment::default() } fn extend_layer_name(current_layer: Option<&LayerPath>, layer_name: &[LayerName]) -> LayerPath { let mut combined = current_layer.cloned().unwrap_or_default(); combined.extend(layer_name.iter().cloned()); combined } fn ensure_single_layer_name( layer_names: &[LayerPath], ) -> Result<(), ParseError> { if layer_names.len() <= 1 { return Ok(()); } Err(ParseError::custom( StyleSheetParseErrorKind::LayerBlockMultipleNames, )) } impl<'i> QualifiedRuleParser<'i> for RuleParser { type Prelude = SelectorList; type QualifiedRule = StyleSheetFragment; type Error = StyleSheetParseError; fn parse_prelude( &mut self, input: &mut Parser<'i>, ) -> Result> { let relative = if self.scoped { ParseRelative::ForScope } else { ParseRelative::No }; SelectorList::parse(&TakumiSelectorParser, input, relative) } fn parse_block( &mut self, selectors: Self::Prelude, _location: &ParserState, input: &mut Parser<'i>, ) -> Result> { self.context().parse_style_rule_block(selectors, input) } } impl<'i> AtRuleParser<'i> for RuleParser { type Prelude = AtRulePrelude; type AtRule = StyleSheetFragment; type Error = StyleSheetParseError; fn parse_prelude( &mut self, name: CowRcStr<'i>, input: &mut Parser<'i>, ) -> Result> { parse_at_rule_prelude(name, input) } fn parse_block( &mut self, prelude: Self::Prelude, _location: &ParserState, input: &mut Parser<'i>, ) -> Result> { match prelude { AtRulePrelude::Layer(layer_names) => { ensure_single_layer_name(&layer_names)?; let declared_layers = self.declared_layers(&layer_names); let Some(nested_layer) = declared_layers.first().cloned() else { return Ok(StyleSheetFragment { declared_layers, ..StyleSheetFragment::default() }); }; let mut fragment = self.nested(Some(nested_layer)).parse_fragment(input)?; fragment.declared_layers.splice(0..0, declared_layers); Ok(fragment) } AtRulePrelude::Keyframes(name) => self.context().parse_keyframes_block(name, input), AtRulePrelude::Theme => self.context().parse_theme_block(input), // `@import` and `@apply` end at their semicolon; a block after them is invalid. AtRulePrelude::TailwindImport { .. } | AtRulePrelude::Apply(_) => Err(ParseError::custom( StyleSheetParseErrorKind::UnsupportedNestedAtRule, )), AtRulePrelude::Media(media_query) => { let mut fragment = self .nested(self.current_layer.clone()) .parse_fragment(input)?; for rule in &mut fragment.rules { rule.media_queries.push(media_query.clone()); } for keyframes in &mut fragment.keyframes { keyframes.media_queries.push(media_query.clone()); } for property_rule in &mut fragment.property_rules { property_rule.media_queries.push(media_query.clone()); } #[cfg(feature = "font-face")] for font_face in &mut fragment.font_faces { font_face.media_queries.push(media_query.clone()); } for page_rule in &mut fragment.page_rules { page_rule.media_queries.push(media_query.clone()); } Ok(fragment) } AtRulePrelude::Container(query) => { let query = Arc::new(query); let mut fragment = self .nested(self.current_layer.clone()) .parse_fragment(input)?; for rule in &mut fragment.rules { rule.container_queries.push(Arc::clone(&query)); } Ok(fragment) } AtRulePrelude::Scope(scope) => { let scope = Arc::new(scope); let mut fragment = Self { scoped: true, ..self.nested(self.current_layer.clone()) } .parse_fragment(input)?; for rule in &mut fragment.rules { rule.scope = Some(match &rule.scope { Some(inner) => inner.within(&scope), None => Arc::clone(&scope), }); } Ok(fragment) } AtRulePrelude::Supports(true) => self .nested(self.current_layer.clone()) .parse_fragment(input), AtRulePrelude::Supports(false) => Ok(skip_block(input)), AtRulePrelude::Unknown(at_rule) => { skip_block(input); Ok(StyleSheetFragment::ignoring(*at_rule)) } AtRulePrelude::Property(name) => Ok(StyleSheetFragment { property_rules: vec![parse_property_rule(name, input)?], ..StyleSheetFragment::default() }), #[cfg(feature = "font-face")] AtRulePrelude::FontFace => Ok(StyleSheetFragment { font_faces: FontFaceRule::parse(input) .map(|rule| FontFaceRule { layer: self.current_layer.clone(), ..rule }) .into_iter() .collect(), ..StyleSheetFragment::default() }), AtRulePrelude::Page(selector) => Ok(StyleSheetFragment { page_rules: vec![PageRule { layer: self.current_layer.clone(), ..PageRule::parse(selector, input) }], ..StyleSheetFragment::default() }), } } fn rule_without_block( &mut self, prelude: Self::Prelude, _start: &ParserState, ) -> Result { match prelude { AtRulePrelude::Layer(layer_names) => Ok(StyleSheetFragment { declared_layers: self.declared_layers(&layer_names), ..StyleSheetFragment::default() }), AtRulePrelude::TailwindImport { preflight } => { if !self.top_level { return Err(()); } Ok(StyleSheetFragment { preflight, ..StyleSheetFragment::default() }) } AtRulePrelude::Unknown(at_rule) => Ok(StyleSheetFragment::ignoring(*at_rule)), _ => Err(()), } } } /// Defines a stylesheet with rules, keyframes, and property rules. #[derive(Debug, Clone, Default)] pub struct StyleSheet { /// Style rules in source order, shared by clones. rules: Arc<[CssRule]>, /// Index over `rules`, built with them; `rules` never changes afterwards. rule_index: Arc, /// `@keyframes` rules. pub(crate) keyframes: Vec, /// `@property` rules. pub(crate) property_rules: Vec, /// `@font-face` rules that make a face, in source order. #[cfg(feature = "font-face")] pub(crate) font_faces: Vec, /// `@page` rules, in source order. pub(crate) page_rules: Vec, /// Number of distinct cascade layers. pub(crate) layer_count: usize, /// Widths from unconditional `:root` `--breakpoint-*` declarations, which /// gate `tw` variants before the cascade runs and so resolve at parse time. pub(crate) breakpoints: BreakpointOverrides, /// The declarations and at-rules parsing dropped, each once. ignored: Box<[IgnoredDeclaration]>, } impl From> for StyleSheet { fn from(keyframes: Vec) -> Self { Self { keyframes, ..Default::default() } } } impl From> for StyleSheet { fn from(property_rules: Vec) -> Self { Self { property_rules, ..Default::default() } } } /// [Tailwind's Preflight](https://github.com/tailwindlabs/tailwindcss/blob/main/packages/tailwindcss/preflight.css), /// without the rules for form controls, pseudo-elements, `abbr[title]`, and `summary`. const PREFLIGHT_CSS: &str = r" @layer base { *, ::before, ::after { box-sizing: border-box; margin: 0; padding: 0; border: 0 solid; } :root { line-height: 1.5; tab-size: 4; } hr { height: 0; color: inherit; border-top-width: 1px; } h1, h2, h3, h4, h5, h6 { font-size: inherit; font-weight: inherit; } a { color: inherit; text-decoration: inherit; } b, strong { font-weight: bolder; } code, kbd, samp, pre { font-size: 1em; } small { font-size: 80%; } sub, sup { font-size: 75%; line-height: 0; position: relative; vertical-align: baseline; } sub { bottom: -0.25em; } sup { top: -0.5em; } table { text-indent: 0; border-color: inherit; border-collapse: collapse; } ol, ul, menu { list-style: none; } img, svg { display: block; vertical-align: middle; } img { max-width: 100%; height: auto; } [hidden]:where(:not([hidden='until-found'])) { display: none !important; } } "; impl StyleSheet { /// Style rules in source order. pub(crate) fn rules(&self) -> &[CssRule] { &self.rules } /// Whether a rule is in an `@container` rule. pub(crate) fn has_container_queries(&self) -> bool { self .rules .iter() .any(|rule| !rule.container_queries.is_empty()) } /// Collects unique resource URLs referenced by the declarations of its rules, keyframes, and /// page-margin rules. pub fn image_urls(&self) -> impl Iterator { let rules = self .rules .iter() .flat_map(|rule| [&rule.normal_declarations, &rule.important_declarations]); let keyframes = self .keyframes .iter() .flat_map(|rule| &rule.keyframes) .map(|keyframe| &keyframe.declarations); let urls: Xxh3HashSet<&str> = rules .chain(keyframes) .flat_map(StyleDeclarationBlock::image_urls) .chain(self.page_rules.iter().flat_map(PageRule::image_urls)) .collect(); urls.into_iter() } /// The index over [`Self::rules`]. pub(crate) fn rule_index(&self) -> &RuleIndex { &self.rule_index } /// The `@property` registrations declared by this stylesheet. pub(crate) fn property_rules(&self) -> &[PropertyRule] { &self.property_rules } /// The `@font-face` rules that make a face, in source order. #[cfg(feature = "font-face")] pub(crate) fn font_faces(&self) -> &[FontFaceRule] { &self.font_faces } /// The `@page` descriptors that win for a `kind` page named `name` in `context`, with `@media` /// read at `viewport`. pub fn page_descriptors( &self, viewport: Viewport, kind: PageKind, name: &PageName, context: &PageContext, ) -> PageDescriptors { PageRule::cascade( &self.page_rules, self.layer_count, viewport, kind, name, context, ) } /// The declarations that style the boxes of a `kind` page named `name` in `context`, with /// `@media` read at `viewport`. pub fn page_styles( &self, viewport: Viewport, kind: PageKind, name: &PageName, context: &PageContext, ) -> PageStyles { PageRule::styles( &self.page_rules, self.layer_count, viewport, kind, name, context, ) } /// Whether an `@page` rule nests a page-margin rule. pub fn has_page_margin_rules(&self) -> bool { self.page_rules.iter().any(|rule| !rule.margins.is_empty()) } /// Whether a page-margin rule's `content` reads `counter(pages)`, the document's page count. pub fn page_margins_count_pages(&self) -> bool { self.page_rules.iter().any(PageRule::counts_pages) } /// The page names the `@page` rules select, each once, in the order they first appear. pub fn page_names(&self) -> Vec { let mut names: Vec = Vec::new(); for name in self.page_rules.iter().map(|rule| rule.selector.name()) { if name.is_named() && !names.contains(name) { names.push(name.clone()); } } names } /// The declarations and at-rules parsing dropped, each once. pub fn ignored_declarations(&self) -> &[IgnoredDeclaration] { &self.ignored } /// Extends the stylesheet with keyframes. pub fn extend_keyframes(&mut self, keyframes: Vec) { self.keyframes.extend(keyframes); } /// Parses a list of stylesheets. pub fn parse_list(stylesheets: I) -> Result where I: IntoIterator, S: AsRef, { Self::parse(&concat_css(stylesheets)) } /// Parses a list of stylesheets while discarding invalid rules. pub fn parse_list_loosy(stylesheets: I) -> Self where I: IntoIterator, S: AsRef, { Self::parse_loosy(&concat_css(stylesheets)) } /// Parses a list of owned stylesheets while discarding invalid rules. pub fn parse_owned_list_loosy(stylesheets: Vec) -> Self { if stylesheets.is_empty() { return Self::default(); } if stylesheets.len() == 1 { return Self::parse_loosy(&stylesheets[0]); } let mut combined_css = String::with_capacity(stylesheets.iter().map(String::len).sum()); for css in stylesheets { combined_css.push_str(&css); } Self::parse_loosy(&combined_css) } /// Parses a stylesheet. pub fn parse(css: &str) -> Result { Self::parse_with_mode(css, false) } /// Parses a stylesheet while discarding invalid rules. pub fn parse_loosy(css: &str) -> Self { Self::parse_with_mode(css, true).unwrap_or_default() } fn parse_with_mode(css: &str, lossy: bool) -> Result { let mut parser = Parser::new(css); let mut rule_parser = RuleParser { current_layer: None, lossy, scoped: false, top_level: true, }; let mut fragment = StyleSheetFragment::default(); for parsed in StyleSheetParser::new(&mut parser, &mut rule_parser) { match parsed { Ok(parsed) => fragment.extend(parsed), Err((_, source, location)) if lossy => log_ignored(source, location), Err((error, context, _)) => { return Err(StyleSheetParseError::from_parse_error(context, error)); } } } let StyleSheetFragment { mut rules, keyframes, property_rules, #[cfg(feature = "font-face")] mut font_faces, mut page_rules, mut declared_layers, preflight, ignored, } = fragment; if preflight { static PREFLIGHT_RULES: LazyLock> = LazyLock::new(|| StyleSheet::parse_loosy(PREFLIGHT_CSS).rules); let mut preflight_rules = PREFLIGHT_RULES.to_vec(); declared_layers.splice( 0..0, preflight_rules.iter().filter_map(|rule| rule.layer.clone()), ); preflight_rules.append(&mut rules); rules = preflight_rules; } let mut layer_order = HashMap::::new(); let used_layers = rules.iter().filter_map(|rule| rule.layer.clone()); #[cfg(feature = "font-face")] let used_layers = used_layers.chain(font_faces.iter().filter_map(|rule| rule.layer.clone())); let used_layers = used_layers.chain(page_rules.iter().filter_map(|rule| rule.layer.clone())); for layer_name in declared_layers.into_iter().chain(used_layers) { let next_order = layer_order.len(); layer_order.entry(layer_name).or_insert(next_order); } for rule in &mut rules { rule.layer_order = rule .layer .as_ref() .and_then(|layer_name| layer_order.get(layer_name).copied()); } #[cfg(feature = "font-face")] for font_face in &mut font_faces { font_face.layer_order = font_face .layer .as_ref() .and_then(|layer_name| layer_order.get(layer_name).copied()); } for page_rule in &mut page_rules { page_rule.layer_order = page_rule .layer .as_ref() .and_then(|layer_name| layer_order.get(layer_name).copied()); } rules.retain(|rule| { !rule.normal_declarations.declarations.is_empty() || !rule.important_declarations.declarations.is_empty() }); Ok(Self { breakpoints: collect_breakpoints(&rules), rule_index: Arc::new(RuleIndex::build(&rules)), rules: rules.into(), keyframes, property_rules, #[cfg(feature = "font-face")] font_faces, page_rules, layer_count: layer_order.len(), ignored: IgnoredDeclaration::unique(&ignored).into(), }) } } /// `--breakpoint-*` widths from unconditional `:root` rules. Variants gate at /// parse time, so only statically-known declarations can re-size them. fn collect_breakpoints(rules: &[CssRule]) -> BreakpointOverrides { let mut breakpoints = BreakpointOverrides::default(); let mut winners = HashMap::::new(); for rule in rules { if !rule.media_queries.is_empty() || rule.selectors.to_css_string() != ":root" { continue; } // Unlayered declarations outrank every layer, so they sort above the // highest ordinal rather than below the lowest. let precedence = rule.layer_order.unwrap_or(usize::MAX); for declaration in rule.normal_declarations.declarations.iter() { if let StyleDeclaration::CustomProperty(name, value) = declaration && let Some(token) = name.strip_prefix("--breakpoint-") && let Ok(width) = Length::from_css_str(value) // Only units `Breakpoint::matches` resolves; anything else would // shadow the built-in width with a dead one. && matches!(width, Length::Rem(_) | Length::Px(_) | Length::Vw(_)) && winners.get(token).is_none_or(|winner| precedence >= *winner) { winners.insert(token.to_owned(), precedence); breakpoints.insert(token.to_owned(), width); } } } breakpoints } /// The stylesheets as one text, in order. fn concat_css>(stylesheets: impl IntoIterator) -> String { let mut combined_css = String::new(); for css in stylesheets { combined_css.push_str(css.as_ref()); } combined_css } #[cfg(test)] mod tests { use cssparser::ToCss; use super::*; use crate::{ style::{Color, ColorInput, ComputedStyle, Length, Style, StyleDeclaration}, viewport::{ColorScheme, MediaTarget, Viewport}, }; fn computed_style_from_declarations(declarations: &StyleDeclarationBlock) -> ComputedStyle { let mut style = Style::default(); for declaration in &declarations.declarations { style.push(declaration.clone(), false); } style.inherit(&ComputedStyle::default()) } fn selector_text(rule: &CssRule) -> String { rule.selectors.to_css_string() } fn parse_stylesheet(css: &str) -> StyleSheet { let result = StyleSheet::parse(css); assert!(result.is_ok(), "expected stylesheet to parse: {result:?}"); result.unwrap_or_default() } fn parse_stylesheet_loosy(css: &str) -> StyleSheet { StyleSheet::parse_loosy(css) } fn assert_lossy_parse_keeps_single_valid_rule(css: &str) { let sheet = parse_stylesheet_loosy(css); assert_eq!(sheet.rules.len(), 1); assert_eq!(selector_text(&sheet.rules[0]), ".card"); assert_eq!( computed_style_from_declarations(&sheet.rules[0].normal_declarations) .box_data .width, Length::Px(100.0).into() ); } #[test] fn image_urls_cover_rules_and_keyframes() { let sheet = parse_stylesheet_loosy( "a { background: url(a.png) } b { background-image: url(b.png) !important } \ @keyframes k { to { background-image: url(c.png) } } d { background: url(a.png) }", ); let mut urls: Vec<&str> = sheet.image_urls().collect(); urls.sort_unstable(); assert_eq!(urls, ["a.png", "b.png", "c.png"]); } #[test] fn test_parse_stylesheet() { let css = r#" .box { width: 100px; color: red; } "#; let sheet = parse_stylesheet(css); assert_eq!(sheet.rules.len(), 1); let rule = &sheet.rules[0]; assert_eq!(rule.selectors.slice().len(), 1); assert_eq!( computed_style_from_declarations(&rule.normal_declarations) .box_data .width, Length::Px(100.0).into() ); } #[test] fn test_parse_stylesheet_compound_selectors_specificity() { let sheet = parse_stylesheet( r#" div.box { width: 10px; } #hero .label { height: 20px; } "#, ); assert_eq!(sheet.rules.len(), 2); assert_eq!(sheet.rules[0].selectors.slice().len(), 1); assert_eq!(sheet.rules[1].selectors.slice().len(), 1); assert!(sheet.rules[0].selectors.slice()[0].specificity() > 0); assert!( sheet.rules[1].selectors.slice()[0].specificity() > sheet.rules[0].selectors.slice()[0].specificity() ); } #[test] fn test_parse_stylesheet_multiple_rules() { let sheet = parse_stylesheet( r#" .a { width: 10px; } .b { height: 20px; } "#, ); assert_eq!(sheet.rules.len(), 2); assert_eq!( computed_style_from_declarations(&sheet.rules[0].normal_declarations) .box_data .width, Length::Px(10.0).into() ); assert_eq!( computed_style_from_declarations(&sheet.rules[1].normal_declarations) .box_data .height, Length::Px(20.0).into() ); } #[test] fn test_parse_stylesheet_multiple_selectors_in_rule() { let sheet = parse_stylesheet( r#" .a, .b { width: 12px; } "#, ); assert_eq!(sheet.rules.len(), 1); assert_eq!(sheet.rules[0].selectors.slice().len(), 2); assert_eq!( computed_style_from_declarations(&sheet.rules[0].normal_declarations) .box_data .width, Length::Px(12.0).into() ); } #[test] fn test_parse_stylesheet_universal_selector() { let sheet = parse_stylesheet( r#" * { width: 100px; } "#, ); assert_eq!(sheet.rules.len(), 1); assert_eq!(selector_text(&sheet.rules[0]), "*"); assert_eq!(sheet.rules[0].selectors.slice().len(), 1); assert_eq!( computed_style_from_declarations(&sheet.rules[0].normal_declarations) .box_data .width, Length::Px(100.0).into() ); } #[test] fn test_parse_stylesheet_important_declaration() { let sheet = parse_stylesheet( r#" .a { width: 10px !important; height: 20px; } "#, ); let rule = &sheet.rules[0]; assert_eq!( computed_style_from_declarations(&rule.important_declarations) .box_data .width, Length::Px(10.0).into() ); assert_eq!( computed_style_from_declarations(&rule.normal_declarations) .box_data .height, Length::Px(20.0).into() ); } #[test] fn test_parse_stylesheet_shorthand_clears_prior_longhand() { let sheet = parse_stylesheet( r#" .a { padding-left: 4px; padding: 10px; } "#, ); let declarations = &sheet.rules[0].normal_declarations; assert_eq!(declarations.declarations.len(), 5); assert_eq!( declarations.declarations[0], StyleDeclaration::padding_left(Length::Px(4.0)) ); assert_eq!( declarations.declarations[1], StyleDeclaration::padding_top(Length::Px(10.0)) ); assert_eq!( declarations.declarations[2], StyleDeclaration::padding_right(Length::Px(10.0)) ); assert_eq!( declarations.declarations[3], StyleDeclaration::padding_bottom(Length::Px(10.0)) ); assert_eq!( declarations.declarations[4], StyleDeclaration::padding_left(Length::Px(10.0)) ); } #[test] fn test_parse_stylesheet_webkit_alias_property() { let sheet = parse_stylesheet( r#" .a { -webkit-text-fill-color: rgb(255, 0, 0); } "#, ); let style = computed_style_from_declarations(&sheet.rules[0].normal_declarations); assert_eq!( style.misc_inherited1_data.webkit_text_fill_color, Some(ColorInput::Value(Color([255, 0, 0, 255]))) ); } #[test] fn test_parse_stylesheet_unknown_property_does_not_drop_supported_declarations() { let sheet = parse_stylesheet( r#" .a { --local-token: 1; width: 14px; unsupported-prop: 2; height: 6px; } "#, ); let style = computed_style_from_declarations(&sheet.rules[0].normal_declarations); assert_eq!(style.box_data.width, Length::Px(14.0).into()); assert_eq!(style.box_data.height, Length::Px(6.0).into()); } #[test] fn test_attribute_selector_rule_is_preserved() { let sheet = parse_stylesheet_loosy( r#" [data-kind="hero"] { width: 10px; } "#, ); assert_eq!(sheet.rules.len(), 1); } #[test] fn test_parse_stylesheet_accepts_attribute_selector() { let result = StyleSheet::parse( r#" [data-kind="hero"] { width: 10px; } "#, ); assert!(result.is_ok()); } #[test] fn test_ignored_pseudo_selector_rule_is_kept_but_never_matches() { let sheet = parse_stylesheet_loosy( r#" .a:hover { width: 10px; } .a, .a:hover { height: 20px; } .a::before { color: red; } "#, ); assert_eq!(sheet.rules.len(), 3); assert_eq!(selector_text(&sheet.rules[0]), ".a:hover"); assert_eq!(selector_text(&sheet.rules[1]), ".a, .a:hover"); assert_eq!(selector_text(&sheet.rules[2]), ".a::before"); } #[test] fn test_lang_pseudo_class_round_trips_its_ranges() { let sheet = parse_stylesheet_loosy( r#" .a:lang(en) { color: blue; } .a:lang(zh-Hant, "ja") { color: red; } "#, ); assert_eq!(sheet.rules.len(), 2); assert_eq!(selector_text(&sheet.rules[0]), ".a:lang(en)"); assert_eq!(selector_text(&sheet.rules[1]), ".a:lang(zh-Hant, ja)"); } #[test] fn test_is_and_where_selectors_are_accepted() { let sheet = parse_stylesheet_loosy( r#" .a:where(.b) div { background: red; } .a:is(.b, .c) { color: blue; } "#, ); assert_eq!(sheet.rules.len(), 2); assert_eq!(selector_text(&sheet.rules[0]), ".a:where(.b) div"); assert_eq!(selector_text(&sheet.rules[1]), ".a:is(.b, .c)"); } #[test] fn test_parse_keyframes_rule() { let sheet = parse_stylesheet( r#" @keyframes fade { from { opacity: 0; } 50% { opacity: 0.5; } to { opacity: 1; } } "#, ); assert!(sheet.rules.is_empty()); assert_eq!(sheet.keyframes.len(), 1); assert_eq!(sheet.keyframes[0].name, "fade"); assert_eq!(sheet.keyframes[0].keyframes.len(), 3); assert_eq!(sheet.keyframes[0].keyframes[0].offsets, vec![0.0]); assert_eq!(sheet.keyframes[0].keyframes[1].offsets, vec![0.5]); assert_eq!(sheet.keyframes[0].keyframes[2].offsets, vec![1.0]); } #[test] fn lossy_parse_drops_only_the_invalid_keyframe_declaration() { let sheet = parse_stylesheet_loosy("@keyframes fade { to { opacity: 1; width: bogus; } }"); assert_eq!(sheet.keyframes.len(), 1); assert_eq!(sheet.keyframes[0].keyframes.len(), 1); assert_eq!(sheet.keyframes[0].keyframes[0].declarations.len(), 1); } #[test] fn prefers_color_scheme_matches_the_viewport_scheme() { let sheet = parse_stylesheet( r#" @media (prefers-color-scheme: dark) { .card { width: 100px; } } @media (prefers-color-scheme: light) { .card { width: 200px; } } @media (prefers-color-scheme) { .card { width: 300px; } } "#, ); let dark = Viewport::new((800, 600)).with_color_scheme(ColorScheme::Dark); let light = Viewport::new((800, 600)); let matches = |index: usize, viewport: Viewport| { sheet.rules[index] .media_queries .first() .is_some_and(|media| media.matches(viewport)) }; assert_eq!(sheet.rules.len(), 3); assert!(matches(0, dark) && !matches(0, light)); assert!(matches(1, light) && !matches(1, dark)); assert!(matches(2, light) && matches(2, dark)); } #[test] fn test_parse_media_rule_with_viewport_features() { let sheet = parse_stylesheet( r#" @media screen and (min-width: 600px) and (orientation: landscape) { .card { width: 100px; } } "#, ); assert_eq!(sheet.rules.len(), 1); assert!(sheet.keyframes.is_empty()); assert!( sheet.rules[0] .media_queries .first() .is_some_and(|media| media.matches(Viewport::new((800, 600)))) ); assert!( !sheet.rules[0] .media_queries .first() .is_some_and(|media| media.matches(Viewport::new((500, 800)))) ); } #[test] fn test_parse_media_rule_ignores_feature_name_case() { for query in [ "(MIN-WIDTH: 600px)", "(Min-Width: 600px)", "(WIDTH >= 600px)", ] { let sheet = parse_stylesheet(&format!("@media {query} {{ .card {{ width: 100px; }} }}")); let Some(media) = sheet.rules[0].media_queries.first() else { unreachable!("expected media queries on parsed rule: {query}"); }; assert!(media.matches(Viewport::new((800, 600))), "{query}"); assert!(!media.matches(Viewport::new((400, 600))), "{query}"); } } #[test] fn test_parse_media_rule_with_comma_list() { let sheet = parse_stylesheet( r#" @media (max-width: 480px), (min-width: 1024px) { .card { width: 100px; } } "#, ); let Some(media) = sheet.rules[0].media_queries.first() else { unreachable!("expected media queries on parsed rule"); }; assert!(media.matches(Viewport::new((400, 800)))); assert!(media.matches(Viewport::new((1280, 800)))); assert!(!media.matches(Viewport::new((800, 800)))); } #[test] fn test_parse_media_rule_with_range_syntax() { for (query, matching, non_matching) in [ ("(width >= 600px)", (600, 400), (599, 400)), ("(width > 600px)", (601, 400), (600, 400)), ("(width <= 600px)", (600, 400), (601, 400)), ("(width < 600px)", (599, 400), (600, 400)), ("(width = 600px)", (600, 400), (601, 400)), ("(600px <= width)", (600, 400), (599, 400)), ("(600px > width)", (599, 400), (600, 400)), ("(height >= 400px)", (600, 400), (600, 399)), ("(400px < height)", (600, 401), (600, 400)), ("(width >= 40em)", (640, 400), (639, 400)), ("(400px < width <= 700px)", (700, 400), (400, 400)), ("(700px >= width > 400px)", (401, 400), (701, 400)), ("(width>=600px)", (600, 400), (599, 400)), ("(width >= calc(500px + 100px))", (600, 400), (599, 400)), ("(width)", (1, 400), (0, 400)), ] { let sheet = parse_stylesheet(&format!("@media {query} {{ .card {{ width: 100px; }} }}")); let Some(media) = sheet.rules[0].media_queries.first() else { unreachable!("expected media queries on parsed rule: {query}"); }; assert!( media.matches(Viewport::new(matching)), "{query} at {matching:?}" ); assert!( !media.matches(Viewport::new(non_matching)), "{query} at {non_matching:?}" ); } } #[test] fn test_parse_media_rule_with_resolution_and_aspect_ratio() { let dpr = |dpr: f32| Viewport::new((800, 400)).with_device_pixel_ratio(dpr); for (query, matching, non_matching) in [ ("(resolution: 2dppx)", dpr(2.0), dpr(1.0)), ("(resolution >= 2x)", dpr(3.0), dpr(1.5)), ("(min-resolution: 192dpi)", dpr(3.0), dpr(1.0)), ("(resolution <= 96dpi)", dpr(1.0), dpr(2.0)), ("(2dppx <= resolution)", dpr(2.0), dpr(1.0)), ("(resolution: 37.7952756dpcm)", dpr(1.0), dpr(2.0)), ("(resolution: 1dppx)", dpr(1.0), dpr(1.01)), ] { let sheet = parse_stylesheet(&format!("@media {query} {{ .card {{ width: 100px; }} }}")); let Some(media) = sheet.rules[0].media_queries.first() else { unreachable!("expected media queries on parsed rule: {query}"); }; assert!(media.matches(matching), "{query} should match"); assert!(!media.matches(non_matching), "{query} should not match"); } let negative = parse_stylesheet("@media (min-resolution: -1dppx) { .card { width: 1px; } }"); assert!( negative.rules[0].media_queries[0].matches(dpr(1.0)), "a negative lower bound is always true" ); let max_ratio = parse_stylesheet("@media (max-aspect-ratio: 2/1) { .card { width: 1px; } }"); assert!(max_ratio.rules[0].media_queries[0].matches(Viewport::new((800, 400)))); assert!(!max_ratio.rules[0].media_queries[0].matches(Viewport::new((900, 400)))); let degenerate = parse_stylesheet("@media (aspect-ratio <= 1/0) { .card { width: 100px; } }"); assert!( !degenerate.rules[0].media_queries[0].matches(Viewport::new((800, 400))), "a zero divisor is not a ratio" ); let boolean = parse_stylesheet("@media (resolution) { .card { width: 100px; } }"); assert!( boolean.rules[0].media_queries[0].matches(dpr(1.0)), "a render always has a resolution" ); for (query, matching, non_matching) in [ ("(aspect-ratio: 2/1)", (800, 400), (900, 400)), ("(aspect-ratio >= 16/9)", (1600, 900), (800, 600)), ("(aspect-ratio < 1)", (400, 800), (800, 400)), ("(1/1 < aspect-ratio <= 2/1)", (800, 400), (900, 400)), ("(aspect-ratio)", (800, 400), (0, 400)), ] { let sheet = parse_stylesheet(&format!("@media {query} {{ .card {{ width: 100px; }} }}")); let Some(media) = sheet.rules[0].media_queries.first() else { unreachable!("expected media queries on parsed rule: {query}"); }; assert!( media.matches(Viewport::new(matching)), "{query} at {matching:?}" ); assert!( !media.matches(Viewport::new(non_matching)), "{query} at {non_matching:?}" ); } } #[test] fn test_parse_media_rule_with_boolean_logic() { for (query, matching, non_matching) in [ ( "(min-width: 600px) or (min-height: 900px)", (400, 1000), (400, 400), ), ( "((min-width: 600px) or (min-height: 900px))", (800, 400), (400, 400), ), ("not (min-width: 600px)", (400, 400), (800, 400)), ( "(not (min-width: 600px)) or (orientation: portrait)", (400, 800), (800, 400), ), ( "(width > 100px) and ((height < 500px) or (orientation: portrait))", (800, 400), (800, 600), ), ( "screen and ((min-width: 600px) or (min-height: 900px))", (800, 400), (400, 400), ), ] { let sheet = parse_stylesheet(&format!("@media {query} {{ .card {{ width: 100px; }} }}")); let Some(media) = sheet.rules[0].media_queries.first() else { unreachable!("expected media queries on parsed rule: {query}"); }; assert!( media.matches(Viewport::new(matching)), "{query} at {matching:?}" ); assert!( !media.matches(Viewport::new(non_matching)), "{query} at {non_matching:?}" ); } } #[test] fn test_parse_media_rule_rejects_a_bare_or_after_a_media_type() { let sheet = parse_stylesheet( "@media screen and (min-width: 600px) or (min-width: 1px) { .card { width: 100px; } }", ); let Some(media) = sheet.rules[0].media_queries.first() else { unreachable!("expected media queries on parsed rule"); }; assert!(!media.matches(Viewport::new((800, 400)))); } #[test] fn test_parse_media_rule_with_media_types() { let screen = Viewport::new((800, 600)); let print = screen.with_media_target(MediaTarget::Print); for (prelude, matches_screen, matches_print) in [ ("screen", true, false), ("print", false, true), ("all", true, true), ("print and (min-width: 600px)", false, true), ("not print", true, false), ("only screen", true, false), ] { let sheet = parse_stylesheet(&format!("@media {prelude} {{ .card {{ width: 100px; }} }}")); let Some(media) = sheet.rules[0].media_queries.first() else { unreachable!("expected media queries on parsed rule: {prelude}"); }; assert_eq!(media.matches(screen), matches_screen, "{prelude} on screen"); assert_eq!(media.matches(print), matches_print, "{prelude} on print"); } } #[test] fn test_parse_media_rule_replaces_malformed_queries_with_not_all() { for prelude in [ "(400px < width > 700px)", "(unsupported-feature: 10px)", "not (unsupported-feature: 10px)", "(min-width: 600px) trailing-junk", "braille", ] { let sheet = parse_stylesheet(&format!("@media {prelude} {{ .card {{ width: 100px; }} }}")); let Some(media) = sheet.rules[0].media_queries.first() else { unreachable!("expected media queries on parsed rule: {prelude}"); }; assert!(!media.matches(Viewport::new((800, 600))), "{prelude}"); } } #[test] fn test_parse_media_rule_keeps_valid_queries_beside_malformed_ones() { let sheet = parse_stylesheet( r#" @media (unsupported-feature: 10px), (min-width: 600px) { .card { width: 100px; } } "#, ); let Some(media) = sheet.rules[0].media_queries.first() else { unreachable!("expected media queries on parsed rule"); }; assert!(media.matches(Viewport::new((800, 600)))); assert!(!media.matches(Viewport::new((400, 600)))); } #[test] fn test_parse_media_rule_applies_to_keyframes_and_property_rules() { let sheet = parse_stylesheet( r#" @media (min-width: 600px) { @keyframes fade { from { opacity: 0; } to { opacity: 1; } } @property --box-size { syntax: ""; inherits: false; initial-value: 10px; } } "#, ); assert_eq!(sheet.keyframes.len(), 1); assert_eq!(sheet.property_rules.len(), 1); assert!( sheet.keyframes[0] .media_queries .first() .is_some_and(|media| media.matches(Viewport::new((800, 600)))) ); assert!( sheet.property_rules[0] .media_queries .first() .is_some_and(|media| media.matches(Viewport::new((800, 600)))) ); } #[test] fn test_parse_nested_rule_is_flattened() { let sheet = parse_stylesheet( r#" .card { width: 100px; .title { height: 20px; } & > .icon { width: 12px; } } "#, ); assert_eq!(sheet.rules.len(), 3); assert_eq!(selector_text(&sheet.rules[0]), ".card"); assert_eq!(selector_text(&sheet.rules[1]), ":is(.card) .title"); assert_eq!(selector_text(&sheet.rules[2]), ":is(.card) > .icon"); } #[test] fn test_parse_nested_rule_cross_product_for_selector_lists() { let sheet = parse_stylesheet( r#" .card, .panel { & .title, & .subtitle { width: 12px; } } "#, ); assert_eq!(sheet.rules.len(), 1); assert_eq!( selector_text(&sheet.rules[0]), ":is(.card, .panel) .title, :is(.card, .panel) .subtitle" ); } #[test] fn test_parse_nested_rule_uses_is_wrapper_for_multi_parent_lists() { let sheet = parse_stylesheet( r#" .card, .panel { & + .item { width: 12px; } } "#, ); assert_eq!(sheet.rules.len(), 1); assert_eq!(selector_text(&sheet.rules[0]), ":is(.card, .panel) + .item"); } #[test] fn test_parse_nested_media_and_supports_rules() { let sheet = parse_stylesheet( r#" .card { @media (min-width: 600px) { @supports (display: grid) { width: 100px; } } } "#, ); assert_eq!(sheet.rules.len(), 1); assert_eq!(selector_text(&sheet.rules[0]), ".card"); assert_eq!(sheet.rules[0].media_queries.len(), 1); assert!( sheet.rules[0] .media_queries .first() .is_some_and(|media| media.matches(Viewport::new((800, 600)))) ); } #[test] fn test_parse_multiple_nested_media_queries_accumulate() { let sheet = parse_stylesheet( r#" .card { @media (min-width: 600px) { @media (orientation: landscape) { width: 100px; } } } "#, ); assert_eq!(sheet.rules.len(), 1); assert_eq!(sheet.rules[0].media_queries.len(), 2); assert!(sheet.rules[0].media_queries[0].matches(Viewport::new((800, 600)))); assert!(sheet.rules[0].media_queries[1].matches(Viewport::new((800, 600)))); assert!(!sheet.rules[0].media_queries[1].matches(Viewport::new((500, 800)))); } #[test] fn test_parse_supports_rule_filters_unsupported_declarations() { let sheet = parse_stylesheet( r#" @supports (display: grid) { .card { width: 100px; } } @supports (unknown-prop: nope) { .card { height: 20px; } } "#, ); assert_eq!(sheet.rules.len(), 1); assert_eq!(selector_text(&sheet.rules[0]), ".card"); assert_eq!( computed_style_from_declarations(&sheet.rules[0].normal_declarations) .box_data .width, Length::Px(100.0).into() ); } #[test] fn test_parse_supports_not_and_or_conditions() { let sheet = parse_stylesheet( r#" @supports (display: grid) and (not (unknown-prop: nope)) { .grid { width: 10px; } } @supports (unknown-prop: nope) or (display: flex) { .flex { height: 20px; } } "#, ); assert_eq!(sheet.rules.len(), 2); assert_eq!(selector_text(&sheet.rules[0]), ".grid"); assert_eq!(selector_text(&sheet.rules[1]), ".flex"); } #[test] fn test_parse_supports_mixed_and_or_requires_parentheses() { let sheet = parse_stylesheet_loosy( r#" @supports (display: grid) and (color: red) or (display: flex) { .invalid { width: 10px; } } .valid { height: 20px; } "#, ); assert_eq!(sheet.rules.len(), 1); assert_eq!(selector_text(&sheet.rules[0]), ".valid"); assert_eq!( computed_style_from_declarations(&sheet.rules[0].normal_declarations) .box_data .height, Length::Px(20.0).into() ); } #[test] fn test_parse_property_rule() { let sheet = parse_stylesheet( r#" @property --box-size { syntax: ""; inherits: false; initial-value: 10px; } "#, ); assert_eq!(sheet.property_rules.len(), 1); assert_eq!(sheet.property_rules[0].name, "--box-size"); assert_eq!(sheet.property_rules[0].syntax.to_string(), ""); assert!(!sheet.property_rules[0].inherits); assert_eq!( sheet.property_rules[0].initial_value, Some("10px".to_owned()) ); } #[test] fn test_parse_property_rule_drops_important_descriptors() { let sheet = parse_stylesheet( r#" @property --box-size { syntax: ""; inherits: false; initial-value: 10px; initial-value: 20px !important; } "#, ); assert_eq!( sheet.property_rules[0].initial_value, Some("10px".to_owned()) ); let sheet = parse_stylesheet_loosy( r#" @property --box-size { syntax: ""; inherits: false !important; initial-value: 10px; } "#, ); assert!(sheet.property_rules.is_empty()); } #[test] fn test_parse_property_rule_descriptors_case_insensitively() { let sheet = parse_stylesheet( r#" @property --box-size { SYNTAX: ""; InHeRiTs: false; INITIAL-VALUE: 10px; } "#, ); assert_eq!(sheet.property_rules.len(), 1); assert_eq!(sheet.property_rules[0].name, "--box-size"); assert_eq!(sheet.property_rules[0].syntax.to_string(), ""); assert!(!sheet.property_rules[0].inherits); assert_eq!( sheet.property_rules[0].initial_value, Some("10px".to_owned()) ); } #[test] fn test_parse_property_rule_needs_an_initial_value_unless_universal() { let sheet = parse_stylesheet( r#" @property --tw-rotate-x { syntax: "*"; inherits: false; } "#, ); assert_eq!(sheet.property_rules.len(), 1); assert_eq!(sheet.property_rules[0].name, "--tw-rotate-x"); assert_eq!(sheet.property_rules[0].syntax.to_string(), "*"); assert!(!sheet.property_rules[0].inherits); assert_eq!(sheet.property_rules[0].initial_value, None); // A typed syntax has nothing to fall back to without one, so the rule goes. let sheet = parse_stylesheet_loosy( r#" @property --box-size { syntax: ""; inherits: false; } .card { width: 100px; } "#, ); assert!(sheet.property_rules.is_empty()); assert_eq!(sheet.rules.len(), 1); } #[test] fn test_parse_property_rule_supports_extended_syntaxes() { let sheet = parse_stylesheet( r#" @property --accent { syntax: " | "; inherits: false; initial-value: red; } @property --display-state { syntax: "none | auto"; inherits: false; initial-value: none; } @property --fade-duration { syntax: "