1use cssparser::*;
4
5use super::Location;
6use super::{CssRuleList, MinifyContext};
7use crate::error::{MinifyError, ParserError, PrinterError};
8use crate::media_query::{
9 define_query_features, operation_to_css, parse_query_condition, to_css_with_parens_if_needed, FeatureToCss,
10 MediaFeatureType, Operator, QueryCondition, QueryConditionFlags, QueryFeature, ValueType,
11};
12use crate::parser::{DefaultAtRule, ParserOptions};
13use crate::printer::Printer;
14use crate::properties::{Property, PropertyId};
15#[cfg(feature = "serde")]
16use crate::serialization::ValueWrapper;
17use crate::targets::{Features, Targets};
18use crate::traits::{Parse, ParseWithOptions, ToCss};
19use crate::values::ident::CustomIdent;
20#[cfg(feature = "visitor")]
21use crate::visitor::Visit;
22
23#[derive(Debug, PartialEq, Clone)]
25#[cfg_attr(feature = "visitor", derive(Visit))]
26#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
27#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
28#[cfg_attr(feature = "into_owned", derive(static_self::IntoOwned))]
29pub struct ContainerRule<'i, R = DefaultAtRule> {
30 #[cfg_attr(feature = "serde", serde(borrow))]
32 pub name: Option<ContainerName<'i>>,
33 pub condition: ContainerCondition<'i>,
35 pub rules: CssRuleList<'i, R>,
37 #[cfg_attr(feature = "visitor", skip_visit)]
39 pub loc: Location,
40}
41
42#[derive(Clone, Debug, PartialEq)]
44#[cfg_attr(feature = "visitor", derive(Visit))]
45#[cfg_attr(feature = "into_owned", derive(static_self::IntoOwned))]
46#[cfg_attr(
47 feature = "serde",
48 derive(serde::Serialize, serde::Deserialize),
49 serde(tag = "type", rename_all = "kebab-case")
50)]
51#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
52pub enum ContainerCondition<'i> {
53 #[cfg_attr(feature = "serde", serde(borrow, with = "ValueWrapper::<ContainerSizeFeature>"))]
55 Feature(ContainerSizeFeature<'i>),
56 #[cfg_attr(feature = "visitor", skip_type)]
58 #[cfg_attr(feature = "serde", serde(with = "ValueWrapper::<Box<ContainerCondition>>"))]
59 Not(Box<ContainerCondition<'i>>),
60 #[cfg_attr(feature = "visitor", skip_type)]
62 Operation {
63 operator: Operator,
65 conditions: Vec<ContainerCondition<'i>>,
67 },
68 #[cfg_attr(feature = "serde", serde(borrow, with = "ValueWrapper::<StyleQuery>"))]
70 Style(StyleQuery<'i>),
71}
72
73pub type ContainerSizeFeature<'i> = QueryFeature<'i, ContainerSizeFeatureId>;
75
76define_query_features! {
77 pub enum ContainerSizeFeatureId {
79 "width": Width = Length,
81 "height": Height = Length,
83 "inline-size": InlineSize = Length,
85 "block-size": BlockSize = Length,
87 "aspect-ratio": AspectRatio = Ratio,
89 "orientation": Orientation = Ident,
91 }
92}
93
94impl FeatureToCss for ContainerSizeFeatureId {
95 fn to_css_with_prefix<W>(&self, prefix: &str, dest: &mut Printer<W>) -> Result<(), PrinterError>
96 where
97 W: std::fmt::Write,
98 {
99 dest.write_str(prefix)?;
100 self.to_css(dest)
101 }
102}
103
104#[derive(Clone, Debug, PartialEq)]
106#[cfg_attr(feature = "visitor", derive(Visit))]
107#[cfg_attr(feature = "into_owned", derive(static_self::IntoOwned))]
108#[cfg_attr(
109 feature = "serde",
110 derive(serde::Serialize, serde::Deserialize),
111 serde(tag = "type", rename_all = "kebab-case")
112)]
113#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
114pub enum StyleQuery<'i> {
115 #[cfg_attr(feature = "serde", serde(borrow, with = "ValueWrapper::<Property>"))]
117 Declaration(Property<'i>),
118 #[cfg_attr(feature = "serde", serde(with = "ValueWrapper::<PropertyId>"))]
121 Property(PropertyId<'i>),
122 #[cfg_attr(feature = "visitor", skip_type)]
124 #[cfg_attr(feature = "serde", serde(with = "ValueWrapper::<Box<StyleQuery>>"))]
125 Not(Box<StyleQuery<'i>>),
126 #[cfg_attr(feature = "visitor", skip_type)]
128 Operation {
129 operator: Operator,
131 conditions: Vec<StyleQuery<'i>>,
133 },
134}
135
136impl<'i> QueryCondition<'i> for ContainerCondition<'i> {
137 #[inline]
138 fn parse_feature<'t>(
139 input: &mut Parser<'i, 't>,
140 options: &ParserOptions<'_, 'i>,
141 ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
142 let feature = QueryFeature::parse_with_options(input, options)?;
143 Ok(Self::Feature(feature))
144 }
145
146 #[inline]
147 fn create_negation(condition: Box<ContainerCondition<'i>>) -> Self {
148 Self::Not(condition)
149 }
150
151 #[inline]
152 fn create_operation(operator: Operator, conditions: Vec<Self>) -> Self {
153 Self::Operation { operator, conditions }
154 }
155
156 fn parse_style_query<'t>(
157 input: &mut Parser<'i, 't>,
158 options: &ParserOptions<'_, 'i>,
159 ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
160 input.parse_nested_block(|input| {
161 if let Ok(res) =
162 input.try_parse(|input| parse_query_condition(input, QueryConditionFlags::ALLOW_OR, options))
163 {
164 return Ok(Self::Style(res));
165 }
166
167 Ok(Self::Style(StyleQuery::parse_feature(input, options)?))
168 })
169 }
170
171 fn needs_parens(&self, parent_operator: Option<Operator>, targets: &Targets) -> bool {
172 match self {
173 ContainerCondition::Not(_) => true,
174 ContainerCondition::Operation { operator, .. } => Some(*operator) != parent_operator,
175 ContainerCondition::Feature(f) => f.needs_parens(parent_operator, targets),
176 ContainerCondition::Style(_) => false,
177 }
178 }
179}
180
181impl<'i> QueryCondition<'i> for StyleQuery<'i> {
182 #[inline]
183 fn parse_feature<'t>(
184 input: &mut Parser<'i, 't>,
185 options: &ParserOptions<'_, 'i>,
186 ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
187 let property_id = PropertyId::parse(input)?;
188 if input.try_parse(|input| input.expect_colon()).is_ok() {
189 input.skip_whitespace();
190 let feature = Self::Declaration(Property::parse(property_id, input, options)?);
191 let _ = input.try_parse(|input| parse_important(input));
192 Ok(feature)
193 } else {
194 Ok(Self::Property(property_id))
195 }
196 }
197
198 #[inline]
199 fn create_negation(condition: Box<Self>) -> Self {
200 Self::Not(condition)
201 }
202
203 #[inline]
204 fn create_operation(operator: Operator, conditions: Vec<Self>) -> Self {
205 Self::Operation { operator, conditions }
206 }
207
208 fn needs_parens(&self, parent_operator: Option<Operator>, _targets: &Targets) -> bool {
209 match self {
210 StyleQuery::Not(_) => true,
211 StyleQuery::Operation { operator, .. } => Some(*operator) != parent_operator,
212 StyleQuery::Declaration(_) | StyleQuery::Property(_) => true,
213 }
214 }
215}
216
217impl<'i> ParseWithOptions<'i> for ContainerCondition<'i> {
218 fn parse_with_options<'t>(
219 input: &mut Parser<'i, 't>,
220 options: &ParserOptions<'_, 'i>,
221 ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
222 parse_query_condition(
223 input,
224 QueryConditionFlags::ALLOW_OR | QueryConditionFlags::ALLOW_STYLE,
225 options,
226 )
227 }
228}
229
230impl<'i> ToCss for ContainerCondition<'i> {
231 fn to_css<W>(&self, dest: &mut Printer<W>) -> Result<(), PrinterError>
232 where
233 W: std::fmt::Write,
234 {
235 match *self {
236 ContainerCondition::Feature(ref f) => f.to_css(dest),
237 ContainerCondition::Not(ref c) => {
238 dest.write_str("not ")?;
239 to_css_with_parens_if_needed(&**c, dest, c.needs_parens(None, &dest.targets.current))
240 }
241 ContainerCondition::Operation {
242 ref conditions,
243 operator,
244 } => operation_to_css(operator, conditions, dest),
245 ContainerCondition::Style(ref query) => {
246 dest.write_str("style(")?;
247 query.to_css(dest)?;
248 dest.write_char(')')
249 }
250 }
251 }
252}
253
254impl<'i> ToCss for StyleQuery<'i> {
255 fn to_css<W>(&self, dest: &mut Printer<W>) -> Result<(), PrinterError>
256 where
257 W: std::fmt::Write,
258 {
259 match *self {
260 StyleQuery::Declaration(ref f) => f.to_css(dest, false),
261 StyleQuery::Property(ref f) => f.to_css(dest),
262 StyleQuery::Not(ref c) => {
263 dest.write_str("not ")?;
264 to_css_with_parens_if_needed(&**c, dest, c.needs_parens(None, &dest.targets.current))
265 }
266 StyleQuery::Operation {
267 ref conditions,
268 operator,
269 } => operation_to_css(operator, conditions, dest),
270 }
271 }
272}
273
274#[derive(Debug, Clone, PartialEq)]
276#[cfg_attr(feature = "visitor", derive(Visit))]
277#[cfg_attr(feature = "into_owned", derive(static_self::IntoOwned))]
278#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize), serde(transparent))]
279#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
280pub struct ContainerName<'i>(#[cfg_attr(feature = "serde", serde(borrow))] pub CustomIdent<'i>);
281
282impl<'i> Parse<'i> for ContainerName<'i> {
283 fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
284 let ident = CustomIdent::parse(input)?;
285 match_ignore_ascii_case! { &*ident.0,
286 "none" | "and" | "not" | "or" => Err(input.new_unexpected_token_error(Token::Ident(ident.0.as_ref().to_owned().into()))),
287 _ => Ok(ContainerName(ident))
288 }
289 }
290}
291
292impl<'i> ToCss for ContainerName<'i> {
293 fn to_css<W>(&self, dest: &mut Printer<W>) -> Result<(), PrinterError>
294 where
295 W: std::fmt::Write,
296 {
297 self.0.to_css_with_options(
300 dest,
301 match &dest.css_module {
302 Some(css_module) => css_module.config.container,
303 None => false,
304 },
305 )
306 }
307}
308
309impl<'i, T: Clone> ContainerRule<'i, T> {
310 pub(crate) fn minify(
311 &mut self,
312 context: &mut MinifyContext<'_, 'i>,
313 parent_is_unused: bool,
314 ) -> Result<bool, MinifyError> {
315 self.rules.minify(context, parent_is_unused)?;
316 Ok(self.rules.0.is_empty())
317 }
318}
319
320impl<'a, 'i, T: ToCss> ToCss for ContainerRule<'i, T> {
321 fn to_css<W>(&self, dest: &mut Printer<W>) -> Result<(), PrinterError>
322 where
323 W: std::fmt::Write,
324 {
325 #[cfg(feature = "sourcemap")]
326 dest.add_mapping(self.loc);
327 dest.write_str("@container ")?;
328 if let Some(name) = &self.name {
329 name.to_css(dest)?;
330 dest.write_char(' ')?;
331 }
332
333 let exclude = dest.targets.current.exclude;
335 dest.targets.current.exclude.insert(Features::MediaQueries);
336 self.condition.to_css(dest)?;
337 dest.targets.current.exclude = exclude;
338
339 dest.whitespace()?;
340 dest.write_char('{')?;
341 dest.indent();
342 dest.newline()?;
343 self.rules.to_css(dest)?;
344 dest.dedent();
345 dest.newline()?;
346 dest.write_char('}')
347 }
348}