Skip to main content

rspack_lightningcss/rules/
scope.rs

1//! The `@scope` rule.
2
3use super::{detach_style_context, style_context_ptr, Location, StyleContext};
4use super::{CssRuleList, MinifyContext};
5use crate::error::{MinifyError, PrinterError};
6use crate::parser::DefaultAtRule;
7use crate::selector::{is_pure_css_modules_selector, SelectorList};
8use crate::traits::ToCss;
9#[cfg(feature = "visitor")]
10use crate::visitor::Visit;
11
12/// A [@scope](https://drafts.csswg.org/css-cascade-6/#scope-atrule) rule.
13///
14/// @scope (<scope-start>) [to (<scope-end>)]? {
15///  <stylesheet>
16/// }
17#[derive(Debug, PartialEq, Clone)]
18#[cfg_attr(feature = "visitor", derive(Visit))]
19#[cfg_attr(
20  feature = "serde",
21  derive(serde::Serialize, serde::Deserialize),
22  serde(rename_all = "camelCase")
23)]
24#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
25#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
26pub struct ScopeRule<'i, R = DefaultAtRule> {
27  /// A selector list used to identify the scoping root(s).
28  pub scope_start: Option<SelectorList<'i>>,
29  /// A selector list used to identify any scoping limits.
30  pub scope_end: Option<SelectorList<'i>>,
31  /// Nested rules within the `@scope` rule.
32  #[cfg_attr(feature = "serde", serde(borrow))]
33  pub rules: CssRuleList<'i, R>,
34  /// The location of the rule in the source file.
35  #[cfg_attr(feature = "visitor", skip_visit)]
36  pub loc: Location,
37}
38
39impl<'i, T: Clone> ScopeRule<'i, T> {
40  pub(crate) fn minify(&mut self, context: &mut MinifyContext<'_, 'i>) -> Result<(), MinifyError> {
41    if context.pure_css_modules {
42      if let Some(scope_start) = &self.scope_start {
43        if !scope_start.0.iter().all(is_pure_css_modules_selector) {
44          return Err(MinifyError {
45            kind: crate::error::MinifyErrorKind::ImpureCSSModuleSelector,
46            loc: self.loc,
47          });
48        }
49      }
50
51      if let Some(scope_end) = &self.scope_end {
52        if !scope_end.0.iter().all(is_pure_css_modules_selector) {
53          return Err(MinifyError {
54            kind: crate::error::MinifyErrorKind::ImpureCSSModuleSelector,
55            loc: self.loc,
56          });
57        }
58      }
59    }
60
61    self.rules.minify(context, false)
62  }
63}
64
65impl<'i, T: ToCss> ToCss for ScopeRule<'i, T> {
66  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
67    dest.add_mapping(self.loc);
68    dest.write_str("@scope")?;
69    dest.whitespace()?;
70    if let Some(scope_start) = &self.scope_start {
71      dest.write_char('(')?;
72      scope_start.to_css(dest)?;
73      dest.write_char(')')?;
74      dest.whitespace()?;
75    }
76    if let Some(scope_end) = &self.scope_end {
77      if dest.options().minify {
78        dest.write_char(' ')?;
79      }
80      dest.write_str("to (")?;
81      // <scope-start> is treated as an ancestor of scope end.
82      // https://drafts.csswg.org/css-nesting/#nesting-at-scope
83      if let Some(scope_start) = &self.scope_start {
84        let parent = dest.state().context;
85        dest.state_mut().context = None;
86        let ctx = StyleContext {
87          selectors: unsafe { std::mem::transmute(scope_start) },
88          parent: detach_style_context(parent),
89        };
90        dest.state_mut().context = Some(style_context_ptr(&ctx));
91        let res = scope_end.to_css(dest);
92        dest.state_mut().context = parent;
93        res?;
94      } else {
95        scope_end.to_css(dest)?;
96      }
97      dest.write_char(')')?;
98      dest.whitespace()?;
99    }
100    dest.write_char('{')?;
101    dest.indent();
102    dest.newline()?;
103    // Nested style rules within @scope are implicitly relative to the <scope-start>
104    // so clear our style context while printing them to avoid replacing & ourselves.
105    // https://drafts.csswg.org/css-cascade-6/#scoped-rules
106    let parent = dest.state().context;
107    dest.state_mut().context = None;
108    let res = self.rules.to_css(dest);
109    dest.state_mut().context = parent;
110    res?;
111    dest.dedent();
112    dest.newline()?;
113    dest.write_char('}')?;
114    Ok(())
115  }
116}