1use crate::compat::Feature;
4use crate::context::PropertyHandlerContext;
5use crate::declaration::DeclarationList;
6use crate::error::{ParserError, PrinterError};
7use crate::logical::PropertyCategory;
8use crate::macros::{enum_property, property_bitflags};
9use crate::properties::{Property, PropertyId};
10use crate::targets::Targets;
11use crate::traits::{IsCompatible, Parse, PropertyHandler, ToCss};
12use crate::values::length::LengthPercentage;
13use crate::values::number::NonNegative;
14use crate::values::ratio::Ratio;
15use crate::vendor_prefix::VendorPrefix;
16#[cfg(feature = "visitor")]
17use crate::visitor::Visit;
18use cssparser::*;
19
20#[cfg(feature = "serde")]
21use crate::serialization::*;
22
23#[derive(Debug, Clone, PartialEq)]
29#[cfg_attr(feature = "visitor", derive(Visit))]
30#[cfg_attr(
31 feature = "serde",
32 derive(serde::Serialize, serde::Deserialize),
33 serde(tag = "type", rename_all = "kebab-case")
34)]
35#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
36#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
37pub enum Size {
38 Auto,
40 #[cfg_attr(feature = "serde", serde(with = "ValueWrapper::<NonNegative<LengthPercentage>>"))]
42 LengthPercentage(NonNegative<LengthPercentage>),
43 #[cfg_attr(feature = "serde", serde(with = "PrefixWrapper"))]
45 MinContent(VendorPrefix),
46 #[cfg_attr(feature = "serde", serde(with = "PrefixWrapper"))]
48 MaxContent(VendorPrefix),
49 #[cfg_attr(feature = "serde", serde(with = "PrefixWrapper"))]
51 FitContent(VendorPrefix),
52 #[cfg_attr(feature = "serde", serde(with = "ValueWrapper::<NonNegative<LengthPercentage>>"))]
54 FitContentFunction(NonNegative<LengthPercentage>),
55 #[cfg_attr(feature = "serde", serde(with = "PrefixWrapper"))]
57 Stretch(VendorPrefix),
58 Contain,
60}
61
62impl<'i> Parse<'i> for Size {
63 fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
64 let res = input.try_parse(|input| {
65 let ident = input.expect_ident()?;
66 Ok(match_ignore_ascii_case! { &*ident,
67 "auto" => Size::Auto,
68 "min-content" => Size::MinContent(VendorPrefix::None),
69 "-webkit-min-content" => Size::MinContent(VendorPrefix::WebKit),
70 "-moz-min-content" => Size::MinContent(VendorPrefix::Moz),
71 "max-content" => Size::MaxContent(VendorPrefix::None),
72 "-webkit-max-content" => Size::MaxContent(VendorPrefix::WebKit),
73 "-moz-max-content" => Size::MaxContent(VendorPrefix::Moz),
74 "stretch" => Size::Stretch(VendorPrefix::None),
75 "-webkit-fill-available" => Size::Stretch(VendorPrefix::WebKit),
76 "-moz-available" => Size::Stretch(VendorPrefix::Moz),
77 "fit-content" => Size::FitContent(VendorPrefix::None),
78 "-webkit-fit-content" => Size::FitContent(VendorPrefix::WebKit),
79 "-moz-fit-content" => Size::FitContent(VendorPrefix::Moz),
80 "contain" => Size::Contain,
81 _ => return Err(input.new_custom_error(ParserError::InvalidValue))
82 })
83 });
84
85 if res.is_ok() {
86 return res;
87 }
88
89 if let Ok(res) = input.try_parse(parse_fit_content) {
90 return Ok(Size::FitContentFunction(res));
91 }
92
93 let lp = input.try_parse(NonNegative::<LengthPercentage>::parse)?;
94 Ok(Size::LengthPercentage(lp))
95 }
96}
97
98impl ToCss for Size {
99 fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
100 use Size::*;
101 match self {
102 Auto => {
103 dest.write_str("auto")?;
104 Ok(())
105 }
106 Contain => {
107 dest.write_str("contain")?;
108 Ok(())
109 }
110 MinContent(vp) => {
111 vp.to_css(dest)?;
112 dest.write_str("min-content")?;
113 Ok(())
114 }
115 MaxContent(vp) => {
116 vp.to_css(dest)?;
117 dest.write_str("max-content")?;
118 Ok(())
119 }
120 FitContent(vp) => {
121 vp.to_css(dest)?;
122 dest.write_str("fit-content")?;
123 Ok(())
124 }
125 Stretch(vp) => match *vp {
126 VendorPrefix::None => {
127 dest.write_str("stretch")?;
128 Ok(())
129 }
130 VendorPrefix::WebKit => {
131 dest.write_str("-webkit-fill-available")?;
132 Ok(())
133 }
134 VendorPrefix::Moz => {
135 dest.write_str("-moz-available")?;
136 Ok(())
137 }
138 _ => unreachable!(),
139 },
140 FitContentFunction(l) => {
141 dest.write_str("fit-content(")?;
142 l.to_css(dest)?;
143 dest.write_str(")")?;
144 Ok(())
145 }
146 LengthPercentage(l) => l.to_css(dest),
147 }
148 }
149}
150
151impl IsCompatible for Size {
152 fn is_compatible(&self, browsers: crate::targets::Browsers) -> bool {
153 use Size::*;
154 match self {
155 LengthPercentage(l) => l.is_compatible(browsers),
156 MinContent(..) => Feature::MinContentSize.is_compatible(browsers),
157 MaxContent(..) => Feature::MaxContentSize.is_compatible(browsers),
158 FitContent(..) => Feature::FitContentSize.is_compatible(browsers),
159 FitContentFunction(l) => {
160 Feature::FitContentFunctionSize.is_compatible(browsers) && l.is_compatible(browsers)
161 }
162 Stretch(vp) => match *vp {
163 VendorPrefix::None => Feature::StretchSize,
164 VendorPrefix::WebKit | VendorPrefix::Moz => Feature::WebkitFillAvailableSize,
165 _ => return false,
166 }
167 .is_compatible(browsers),
168 Contain => false, Auto => true,
170 }
171 }
172}
173
174#[derive(Debug, Clone, PartialEq)]
178#[cfg_attr(feature = "visitor", derive(Visit))]
179#[cfg_attr(
180 feature = "serde",
181 derive(serde::Serialize, serde::Deserialize),
182 serde(tag = "type", rename_all = "kebab-case")
183)]
184#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
185#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
186pub enum MaxSize {
187 None,
189 #[cfg_attr(feature = "serde", serde(with = "ValueWrapper::<NonNegative<LengthPercentage>>"))]
191 LengthPercentage(NonNegative<LengthPercentage>),
192 #[cfg_attr(feature = "serde", serde(with = "PrefixWrapper"))]
194 MinContent(VendorPrefix),
195 #[cfg_attr(feature = "serde", serde(with = "PrefixWrapper"))]
197 MaxContent(VendorPrefix),
198 #[cfg_attr(feature = "serde", serde(with = "PrefixWrapper"))]
200 FitContent(VendorPrefix),
201 #[cfg_attr(feature = "serde", serde(with = "ValueWrapper::<NonNegative<LengthPercentage>>"))]
203 FitContentFunction(NonNegative<LengthPercentage>),
204 #[cfg_attr(feature = "serde", serde(with = "PrefixWrapper"))]
206 Stretch(VendorPrefix),
207 Contain,
209}
210
211impl<'i> Parse<'i> for MaxSize {
212 fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
213 let res = input.try_parse(|input| {
214 let ident = input.expect_ident()?;
215 Ok(match_ignore_ascii_case! { &*ident,
216 "none" => MaxSize::None,
217 "min-content" => MaxSize::MinContent(VendorPrefix::None),
218 "-webkit-min-content" => MaxSize::MinContent(VendorPrefix::WebKit),
219 "-moz-min-content" => MaxSize::MinContent(VendorPrefix::Moz),
220 "max-content" => MaxSize::MaxContent(VendorPrefix::None),
221 "-webkit-max-content" => MaxSize::MaxContent(VendorPrefix::WebKit),
222 "-moz-max-content" => MaxSize::MaxContent(VendorPrefix::Moz),
223 "stretch" => MaxSize::Stretch(VendorPrefix::None),
224 "-webkit-fill-available" => MaxSize::Stretch(VendorPrefix::WebKit),
225 "-moz-available" => MaxSize::Stretch(VendorPrefix::Moz),
226 "fit-content" => MaxSize::FitContent(VendorPrefix::None),
227 "-webkit-fit-content" => MaxSize::FitContent(VendorPrefix::WebKit),
228 "-moz-fit-content" => MaxSize::FitContent(VendorPrefix::Moz),
229 "contain" => MaxSize::Contain,
230 _ => return Err(input.new_custom_error(ParserError::InvalidValue))
231 })
232 });
233
234 if res.is_ok() {
235 return res;
236 }
237
238 if let Ok(res) = input.try_parse(parse_fit_content) {
239 return Ok(MaxSize::FitContentFunction(res));
240 }
241
242 let lp = input.try_parse(NonNegative::<LengthPercentage>::parse)?;
243 Ok(MaxSize::LengthPercentage(lp))
244 }
245}
246
247impl ToCss for MaxSize {
248 fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
249 use MaxSize::*;
250 match self {
251 None => {
252 dest.write_str("none")?;
253 Ok(())
254 }
255 Contain => {
256 dest.write_str("contain")?;
257 Ok(())
258 }
259 MinContent(vp) => {
260 vp.to_css(dest)?;
261 dest.write_str("min-content")?;
262 Ok(())
263 }
264 MaxContent(vp) => {
265 vp.to_css(dest)?;
266 dest.write_str("max-content")?;
267 Ok(())
268 }
269 FitContent(vp) => {
270 vp.to_css(dest)?;
271 dest.write_str("fit-content")?;
272 Ok(())
273 }
274 Stretch(vp) => match *vp {
275 VendorPrefix::None => {
276 dest.write_str("stretch")?;
277 Ok(())
278 }
279 VendorPrefix::WebKit => {
280 dest.write_str("-webkit-fill-available")?;
281 Ok(())
282 }
283 VendorPrefix::Moz => {
284 dest.write_str("-moz-available")?;
285 Ok(())
286 }
287 _ => unreachable!(),
288 },
289 FitContentFunction(l) => {
290 dest.write_str("fit-content(")?;
291 l.to_css(dest)?;
292 dest.write_str(")")?;
293 Ok(())
294 }
295 LengthPercentage(l) => l.to_css(dest),
296 }
297 }
298}
299
300impl IsCompatible for MaxSize {
301 fn is_compatible(&self, browsers: crate::targets::Browsers) -> bool {
302 use MaxSize::*;
303 match self {
304 LengthPercentage(l) => l.is_compatible(browsers),
305 MinContent(..) => Feature::MinContentSize.is_compatible(browsers),
306 MaxContent(..) => Feature::MaxContentSize.is_compatible(browsers),
307 FitContent(..) => Feature::FitContentSize.is_compatible(browsers),
308 FitContentFunction(l) => {
309 Feature::FitContentFunctionSize.is_compatible(browsers) && l.is_compatible(browsers)
310 }
311 Stretch(vp) => match *vp {
312 VendorPrefix::None => Feature::StretchSize,
313 VendorPrefix::WebKit | VendorPrefix::Moz => Feature::WebkitFillAvailableSize,
314 _ => return false,
315 }
316 .is_compatible(browsers),
317 Contain => false, None => true,
319 }
320 }
321}
322
323#[derive(Clone, Copy)]
325enum SizeFallback {
326 Stretch,
327 MinContent,
328 MaxContent,
329 FitContent,
330}
331
332impl SizeFallback {
333 #[inline(never)]
334 fn prefixes(self, targets: Targets) -> VendorPrefix {
335 let feature = match self {
336 SizeFallback::Stretch => crate::prefixes::Feature::Stretch,
337 SizeFallback::MinContent => crate::prefixes::Feature::MinContent,
338 SizeFallback::MaxContent => crate::prefixes::Feature::MaxContent,
339 SizeFallback::FitContent => crate::prefixes::Feature::FitContent,
340 };
341 targets.prefixes(VendorPrefix::None, feature) - VendorPrefix::None
342 }
343
344 #[inline(never)]
345 fn size(self, prefix: VendorPrefix) -> Size {
346 match self {
347 SizeFallback::Stretch => Size::Stretch(prefix),
348 SizeFallback::MinContent => Size::MinContent(prefix),
349 SizeFallback::MaxContent => Size::MaxContent(prefix),
350 SizeFallback::FitContent => Size::FitContent(prefix),
351 }
352 }
353
354 #[inline(never)]
355 fn max_size(self, prefix: VendorPrefix) -> MaxSize {
356 match self {
357 SizeFallback::Stretch => MaxSize::Stretch(prefix),
358 SizeFallback::MinContent => MaxSize::MinContent(prefix),
359 SizeFallback::MaxContent => MaxSize::MaxContent(prefix),
360 SizeFallback::FitContent => MaxSize::FitContent(prefix),
361 }
362 }
363}
364
365#[inline(never)]
366fn size_fallback(value: &Size) -> Option<SizeFallback> {
367 match value {
368 Size::Stretch(VendorPrefix::None) => Some(SizeFallback::Stretch),
369 Size::MinContent(VendorPrefix::None) => Some(SizeFallback::MinContent),
370 Size::MaxContent(VendorPrefix::None) => Some(SizeFallback::MaxContent),
371 Size::FitContent(VendorPrefix::None) => Some(SizeFallback::FitContent),
372 _ => None,
373 }
374}
375
376#[inline(never)]
377fn max_size_fallback(value: &MaxSize) -> Option<SizeFallback> {
378 match value {
379 MaxSize::Stretch(VendorPrefix::None) => Some(SizeFallback::Stretch),
380 MaxSize::MinContent(VendorPrefix::None) => Some(SizeFallback::MinContent),
381 MaxSize::MaxContent(VendorPrefix::None) => Some(SizeFallback::MaxContent),
382 MaxSize::FitContent(VendorPrefix::None) => Some(SizeFallback::FitContent),
383 _ => None,
384 }
385}
386
387fn parse_fit_content<'i, 't>(
388 input: &mut Parser<'i, 't>,
389) -> Result<NonNegative<LengthPercentage>, ParseError<'i, ParserError<'i>>> {
390 input.expect_function_matching("fit-content")?;
391 input.parse_nested_block(|input| NonNegative::<LengthPercentage>::parse(input))
392}
393
394enum_property! {
395 pub enum BoxSizing {
397 ContentBox,
399 BorderBox,
401 }
402}
403
404#[derive(Debug, Clone, PartialEq)]
406#[cfg_attr(feature = "visitor", derive(Visit))]
407#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
408#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
409#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
410pub struct AspectRatio {
411 pub auto: bool,
413 pub ratio: Option<Ratio>,
415}
416
417impl<'i> Parse<'i> for AspectRatio {
418 fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
419 let location = input.current_source_location();
420 let mut auto = input.try_parse(|i| i.expect_ident_matching("auto"));
421 let ratio = input.try_parse(Ratio::parse);
422 if auto.is_err() {
423 auto = input.try_parse(|i| i.expect_ident_matching("auto"));
424 }
425 if auto.is_err() && ratio.is_err() {
426 return Err(location.new_custom_error(ParserError::InvalidValue));
427 }
428
429 Ok(AspectRatio {
430 auto: auto.is_ok(),
431 ratio: ratio.ok(),
432 })
433 }
434}
435
436impl ToCss for AspectRatio {
437 fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
438 if self.auto {
439 dest.write_str("auto")?;
440 }
441
442 if let Some(ratio) = &self.ratio {
443 if self.auto {
444 dest.write_char(' ')?;
445 }
446 ratio.to_css(dest)?;
447 }
448
449 Ok(())
450 }
451}
452
453property_bitflags! {
454 #[derive(Default)]
455 struct SizeProperty: u16 {
456 const Width = 1 << 0;
457 const Height = 1 << 1;
458 const MinWidth = 1 << 2;
459 const MinHeight = 1 << 3;
460 const MaxWidth = 1 << 4;
461 const MaxHeight = 1 << 5;
462 const BlockSize = 1 << 6;
463 const InlineSize = 1 << 7;
464 const MinBlockSize = 1 << 8;
465 const MinInlineSize = 1 << 9;
466 const MaxBlockSize = 1 << 10;
467 const MaxInlineSize = 1 << 11;
468 }
469}
470
471#[derive(Default)]
472pub(crate) struct SizeHandler {
473 width: Option<Size>,
474 height: Option<Size>,
475 min_width: Option<Size>,
476 min_height: Option<Size>,
477 max_width: Option<MaxSize>,
478 max_height: Option<MaxSize>,
479 block_size: Option<Size>,
480 inline_size: Option<Size>,
481 min_block_size: Option<Size>,
482 min_inline_size: Option<Size>,
483 max_block_size: Option<MaxSize>,
484 max_inline_size: Option<MaxSize>,
485 has_any: bool,
486 flushed_properties: SizeProperty,
487 category: PropertyCategory,
488}
489
490impl<'i> PropertyHandler<'i> for SizeHandler {
491 fn handle_property(
492 &mut self,
493 property: &Property<'i>,
494 dest: &mut DeclarationList<'i>,
495 context: &mut PropertyHandlerContext<'i, '_>,
496 ) -> bool {
497 let logical_supported = !context.should_compile_logical(Feature::LogicalSize);
498
499 macro_rules! property {
500 ($prop: ident, $val: ident, $category: ident) => {{
501 if PropertyCategory::$category != self.category || (self.$prop.is_some() && matches!(context.targets.browsers, Some(targets) if !$val.is_compatible(targets))) {
505 self.flush(dest, context);
506 }
507
508 self.$prop = Some($val.clone());
509 self.category = PropertyCategory::$category;
510 self.has_any = true;
511 }};
512 }
513
514 match property {
515 Property::Width(v) => property!(width, v, Physical),
516 Property::Height(v) => property!(height, v, Physical),
517 Property::MinWidth(v) => property!(min_width, v, Physical),
518 Property::MinHeight(v) => property!(min_height, v, Physical),
519 Property::MaxWidth(v) => property!(max_width, v, Physical),
520 Property::MaxHeight(v) => property!(max_height, v, Physical),
521 Property::BlockSize(size) => property!(block_size, size, Logical),
522 Property::MinBlockSize(size) => property!(min_block_size, size, Logical),
523 Property::MaxBlockSize(size) => property!(max_block_size, size, Logical),
524 Property::InlineSize(size) => property!(inline_size, size, Logical),
525 Property::MinInlineSize(size) => property!(min_inline_size, size, Logical),
526 Property::MaxInlineSize(size) => property!(max_inline_size, size, Logical),
527 Property::Unparsed(unparsed) => {
528 self.flush(dest, context);
529 macro_rules! logical_unparsed {
530 ($physical: ident) => {
531 if logical_supported {
532 self
533 .flushed_properties
534 .insert(SizeProperty::try_from(&unparsed.property_id).unwrap());
535 dest.push(property.clone());
536 } else {
537 dest.push(Property::Unparsed(
538 unparsed.with_property_id(PropertyId::$physical),
539 ));
540 self.flushed_properties.insert(SizeProperty::$physical);
541 }
542 };
543 }
544
545 match &unparsed.property_id {
546 PropertyId::Width
547 | PropertyId::Height
548 | PropertyId::MinWidth
549 | PropertyId::MaxWidth
550 | PropertyId::MinHeight
551 | PropertyId::MaxHeight => {
552 self
553 .flushed_properties
554 .insert(SizeProperty::try_from(&unparsed.property_id).unwrap());
555 dest.push(property.clone());
556 }
557 PropertyId::BlockSize => logical_unparsed!(Height),
558 PropertyId::MinBlockSize => logical_unparsed!(MinHeight),
559 PropertyId::MaxBlockSize => logical_unparsed!(MaxHeight),
560 PropertyId::InlineSize => logical_unparsed!(Width),
561 PropertyId::MinInlineSize => logical_unparsed!(MinWidth),
562 PropertyId::MaxInlineSize => logical_unparsed!(MaxWidth),
563 _ => return false,
564 }
565 }
566 _ => return false,
567 }
568
569 true
570 }
571
572 fn finalize(&mut self, dest: &mut DeclarationList, context: &mut PropertyHandlerContext<'i, '_>) {
573 self.flush(dest, context);
574 self.flushed_properties = SizeProperty::empty();
575 }
576}
577
578impl SizeHandler {
579 fn flush<'i>(&mut self, dest: &mut DeclarationList, context: &mut PropertyHandlerContext<'i, '_>) {
580 if !self.has_any {
581 return;
582 }
583
584 self.has_any = false;
585 let logical_supported = !context.should_compile_logical(Feature::LogicalSize);
586
587 macro_rules! property {
588 ($prop: ident, $val: ident, $fallback: ident, $constructor: ident) => {{
589 if let Some(val) = std::mem::take(&mut self.$val) {
590 if !self.flushed_properties.contains(SizeProperty::$prop) {
591 if let Some(fallback) = $fallback(&val) {
592 for prefix in fallback.prefixes(context.targets) {
593 dest.push(Property::$prop(fallback.$constructor(prefix)));
594 }
595 }
596 }
597 dest.push(Property::$prop(val));
598 self.flushed_properties.insert(SizeProperty::$prop);
599 }
600 }};
601 }
602
603 macro_rules! logical {
604 ($prop: ident, $val: ident, $physical: ident, $fallback: ident, $constructor: ident) => {
605 if logical_supported {
606 property!($prop, $val, $fallback, $constructor);
607 } else {
608 property!($physical, $val, $fallback, $constructor);
609 }
610 };
611 }
612
613 property!(Width, width, size_fallback, size);
614 property!(MinWidth, min_width, size_fallback, size);
615 property!(MaxWidth, max_width, max_size_fallback, max_size);
616 property!(Height, height, size_fallback, size);
617 property!(MinHeight, min_height, size_fallback, size);
618 property!(MaxHeight, max_height, max_size_fallback, max_size);
619 logical!(BlockSize, block_size, Height, size_fallback, size);
620 logical!(MinBlockSize, min_block_size, MinHeight, size_fallback, size);
621 logical!(MaxBlockSize, max_block_size, MaxHeight, max_size_fallback, max_size);
622 logical!(InlineSize, inline_size, Width, size_fallback, size);
623 logical!(MinInlineSize, min_inline_size, MinWidth, size_fallback, size);
624 logical!(MaxInlineSize, max_inline_size, MaxWidth, max_size_fallback, max_size);
625 }
626}