Skip to main content

rspack_lightningcss/values/
length.rs

1//! CSS length values.
2
3use super::angle::impl_try_from_angle;
4use super::calc::{Calc, MathFunction};
5use super::number::{CSSNumber, NumericRange};
6use super::percentage::DimensionPercentage;
7use crate::error::{ParserError, PrinterError};
8use crate::targets::Browsers;
9use crate::traits::{
10  private::{AddInternal, TryAdd},
11  Map, Parse, ParseNumeric, Sign, ToCss, TryMap, TryOp, Zero,
12};
13use crate::traits::{IsCompatible, TrySign};
14#[cfg(feature = "visitor")]
15use crate::visitor::Visit;
16use const_str;
17use cssparser::*;
18
19/// A CSS [`<length-percentage>`](https://www.w3.org/TR/css-values-4/#typedef-length-percentage) value.
20/// May be specified as either a length or a percentage that resolves to an length.
21pub type LengthPercentage = DimensionPercentage<LengthValue>;
22
23impl LengthPercentage {
24  /// Constructs a `LengthPercentage` with the given pixel value.
25  pub fn px(val: CSSNumber) -> LengthPercentage {
26    LengthPercentage::Dimension(LengthValue::Px(val))
27  }
28
29  pub(crate) fn to_css_unitless<PrinterT: crate::printer::PrinterTrait>(
30    &self,
31    dest: &mut PrinterT,
32  ) -> Result<(), PrinterError> {
33    match self {
34      DimensionPercentage::Dimension(d) => d.to_css_unitless(dest),
35      _ => self.to_css(dest),
36    }
37  }
38}
39
40impl IsCompatible for LengthPercentage {
41  fn is_compatible(&self, browsers: Browsers) -> bool {
42    match self {
43      LengthPercentage::Dimension(d) => d.is_compatible(browsers),
44      LengthPercentage::Calc(c) => c.is_compatible(browsers),
45      LengthPercentage::Percentage(..) => true,
46    }
47  }
48}
49
50/// Either a [`<length-percentage>`](https://www.w3.org/TR/css-values-4/#typedef-length-percentage), or the `auto` keyword.
51#[derive(Debug, Clone, PartialEq, ToCss)]
52#[cfg_attr(feature = "visitor", derive(Visit))]
53#[cfg_attr(
54  feature = "serde",
55  derive(serde::Serialize, serde::Deserialize),
56  serde(tag = "type", content = "value", rename_all = "kebab-case")
57)]
58#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
59#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
60pub enum LengthPercentageOrAuto {
61  /// The `auto` keyword.
62  Auto,
63  /// A [`<length-percentage>`](https://www.w3.org/TR/css-values-4/#typedef-length-percentage).
64  LengthPercentage(LengthPercentage),
65}
66
67impl<'i> Parse<'i> for LengthPercentageOrAuto {
68  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
69    Self::parse_with_range(input, NumericRange::All)
70  }
71}
72
73impl<'i> ParseNumeric<'i> for LengthPercentageOrAuto {
74  fn parse_with_range<'t>(
75    input: &mut Parser<'i, 't>,
76    range: NumericRange,
77  ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
78    if input.try_parse(|input| input.expect_ident_matching("auto")).is_ok() {
79      return Ok(Self::Auto);
80    }
81    Ok(Self::LengthPercentage(LengthPercentage::parse_with_range(
82      input, range,
83    )?))
84  }
85}
86
87impl IsCompatible for LengthPercentageOrAuto {
88  fn is_compatible(&self, browsers: Browsers) -> bool {
89    match self {
90      LengthPercentageOrAuto::LengthPercentage(p) => p.is_compatible(browsers),
91      _ => true,
92    }
93  }
94}
95
96const PX_PER_IN: f32 = 96.0;
97const PX_PER_CM: f32 = PX_PER_IN / 2.54;
98const PX_PER_MM: f32 = PX_PER_CM / 10.0;
99const PX_PER_Q: f32 = PX_PER_CM / 40.0;
100const PX_PER_PT: f32 = PX_PER_IN / 72.0;
101const PX_PER_PC: f32 = PX_PER_IN / 6.0;
102
103macro_rules! define_length_units {
104  (
105    $(
106      $(#[$meta: meta])*
107      $name: ident $(/ $feature: ident)?,
108    )+
109  ) => {
110    /// A CSS [`<length>`](https://www.w3.org/TR/css-values-4/#lengths) value,
111    /// without support for `calc()`. See also: [Length](Length).
112    #[derive(Debug, Clone, PartialEq)]
113    #[cfg_attr(feature = "visitor", derive(Visit))]
114    #[cfg_attr(feature = "visitor", visit(visit_length, LENGTHS))]
115    #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize), serde(tag = "unit", content = "value", rename_all = "kebab-case"))]
116    #[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
117    pub enum LengthValue {
118      $(
119        $(#[$meta])*
120        $name(CSSNumber),
121      )+
122    }
123
124    impl<'i> Parse<'i> for LengthValue {
125      fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
126        Self::parse_with_range(input, NumericRange::All)
127      }
128    }
129
130    impl<'i> ParseNumeric<'i> for LengthValue {
131      fn parse_with_range<'t>(input: &mut Parser<'i, 't>, range: NumericRange) -> Result<Self, ParseError<'i, ParserError<'i>>> {
132        let location = input.current_source_location();
133        let token = input.next()?;
134        match *token {
135          Token::Dimension { value, ref unit, .. } => {
136            let value = range.check(value, location)?;
137            Ok(match unit {
138              $(
139                s if s.eq_ignore_ascii_case(stringify!($name)) => LengthValue::$name(value),
140              )+
141              _ => return Err(location.new_unexpected_token_error(token.clone())),
142            })
143          },
144          Token::Number { value, .. } => {
145            // TODO: quirks mode only?
146            Ok(LengthValue::Px(range.check(value, location)?))
147          }
148          ref token => return Err(location.new_unexpected_token_error(token.clone())),
149        }
150      }
151    }
152
153    impl<'i> TryFrom<&Token<'i>> for LengthValue {
154      type Error = ();
155
156      fn try_from(token: &Token) -> Result<Self, Self::Error> {
157        match token {
158          Token::Dimension { value, ref unit, .. } => {
159            Ok(match unit {
160              $(
161                s if s.eq_ignore_ascii_case(stringify!($name)) => LengthValue::$name(*value),
162              )+
163              _ => return Err(()),
164            })
165          },
166          _ => Err(())
167        }
168      }
169    }
170
171    impl LengthValue {
172      /// Returns the numeric value and unit string for the length value.
173      pub fn to_unit_value(&self) -> (CSSNumber, &str) {
174        match self {
175          $(
176            LengthValue::$name(value) => (*value, const_str::convert_ascii_case!(lower, stringify!($name))),
177          )+
178        }
179      }
180    }
181
182    impl IsCompatible for LengthValue {
183      fn is_compatible(&self, browsers: Browsers) -> bool {
184        macro_rules! is_compatible {
185          ($f: ident) => {
186            crate::compat::Feature::$f.is_compatible(browsers)
187          };
188          () => {
189            true
190          };
191        }
192
193        match self {
194          $(
195            LengthValue::$name(_) => {
196              is_compatible!($($feature)?)
197            }
198          )+
199        }
200      }
201    }
202
203    impl TryAdd<LengthValue> for LengthValue {
204      fn try_add(&self, other: &LengthValue) -> Option<LengthValue> {
205        use LengthValue::*;
206        match (self, other) {
207          $(
208            ($name(a), $name(b)) => Some($name(a + b)),
209          )+
210          (a, b) => {
211            if let (Some(a), Some(b)) = (a.to_px(), b.to_px()) {
212              Some(Px(a + b))
213            } else {
214              None
215            }
216          }
217        }
218      }
219    }
220
221    impl std::ops::Mul<CSSNumber> for LengthValue {
222      type Output = Self;
223
224      fn mul(self, other: CSSNumber) -> LengthValue {
225        use LengthValue::*;
226        match self {
227          $(
228            $name(value) => $name(value * other),
229          )+
230        }
231      }
232    }
233
234    impl std::cmp::PartialOrd<LengthValue> for LengthValue {
235      fn partial_cmp(&self, other: &LengthValue) -> Option<std::cmp::Ordering> {
236        use LengthValue::*;
237        match (self, other) {
238          $(
239            ($name(a), $name(b)) => a.partial_cmp(b),
240          )+
241          (a, b) => {
242            if let (Some(a), Some(b)) = (a.to_px(), b.to_px()) {
243              a.partial_cmp(&b)
244            } else {
245              None
246            }
247          }
248        }
249      }
250    }
251
252    impl TryOp for LengthValue {
253      fn try_op<F: FnOnce(f32, f32) -> f32>(&self, rhs: &Self, op: F) -> Option<Self> {
254        use LengthValue::*;
255        match (self, rhs) {
256          $(
257            ($name(a), $name(b)) => Some($name(op(*a, *b))),
258          )+
259          (a, b) => {
260            if let (Some(a), Some(b)) = (a.to_px(), b.to_px()) {
261              Some(Px(op(a, b)))
262            } else {
263              None
264            }
265          }
266        }
267      }
268
269      fn try_op_to<T, F: FnOnce(f32, f32) -> T>(&self, rhs: &Self, op: F) -> Option<T> {
270        use LengthValue::*;
271        match (self, rhs) {
272          $(
273            ($name(a), $name(b)) => Some(op(*a, *b)),
274          )+
275          (a, b) => {
276            if let (Some(a), Some(b)) = (a.to_px(), b.to_px()) {
277              Some(op(a, b))
278            } else {
279              None
280            }
281          }
282        }
283      }
284    }
285
286    impl Map for LengthValue {
287      fn map<F: FnOnce(f32) -> f32>(&self, op: F) -> Self {
288        use LengthValue::*;
289        match self {
290          $(
291            $name(value) => $name(op(*value)),
292          )+
293        }
294      }
295    }
296
297    impl Sign for LengthValue {
298      fn sign(&self) -> f32 {
299        use LengthValue::*;
300        match self {
301          $(
302            $name(value) => value.sign(),
303          )+
304        }
305      }
306    }
307
308    impl Zero for LengthValue {
309      fn zero() -> Self {
310        LengthValue::Px(0.0)
311      }
312
313      fn is_zero(&self) -> bool {
314        use LengthValue::*;
315        match self {
316          $(
317            $name(value) => value.is_zero(),
318          )+
319        }
320      }
321    }
322
323    impl_try_from_angle!(LengthValue);
324
325    #[cfg(feature = "jsonschema")]
326    #[cfg_attr(docsrs, doc(cfg(feature = "jsonschema")))]
327    impl schemars::JsonSchema for LengthValue {
328      fn is_referenceable() -> bool {
329        true
330      }
331
332      fn json_schema(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {
333        #[derive(schemars::JsonSchema)]
334        #[schemars(rename_all = "lowercase")]
335        #[allow(dead_code)]
336        enum LengthUnit {
337          $(
338            $(#[$meta])*
339            $name,
340          )+
341        }
342
343        #[derive(schemars::JsonSchema)]
344        #[allow(dead_code)]
345        struct LengthValue {
346          /// The length unit.
347          unit: LengthUnit,
348          /// The length value.
349          value: CSSNumber
350        }
351
352        LengthValue::json_schema(gen)
353      }
354
355      fn schema_name() -> String {
356        "LengthValue".into()
357      }
358    }
359  };
360}
361
362define_length_units! {
363  // https://www.w3.org/TR/css-values-4/#absolute-lengths
364  /// A length in pixels.
365  Px,
366  /// A length in inches. 1in = 96px.
367  In,
368  /// A length in centimeters. 1cm = 96px / 2.54.
369  Cm,
370  /// A length in millimeters. 1mm = 1/10th of 1cm.
371  Mm,
372  /// A length in quarter-millimeters. 1Q = 1/40th of 1cm.
373  Q / QUnit,
374  /// A length in points. 1pt = 1/72nd of 1in.
375  Pt,
376  /// A length in picas. 1pc = 1/6th of 1in.
377  Pc,
378
379  // https://www.w3.org/TR/css-values-4/#font-relative-lengths
380  /// A length in the `em` unit. An `em` is equal to the computed value of the
381  /// font-size property of the element on which it is used.
382  Em,
383  /// A length in the `rem` unit. A `rem` is equal to the computed value of the
384  /// `em` unit on the root element.
385  Rem / RemUnit,
386  /// A length in `ex` unit. An `ex` is equal to the x-height of the font.
387  Ex / ExUnit,
388  /// A length in the `rex` unit. A `rex` is equal to the value of the `ex` unit on the root element.
389  Rex,
390  /// A length in the `ch` unit. A `ch` is equal to the width of the zero ("0") character in the current font.
391  Ch / ChUnit,
392  /// A length in the `rch` unit. An `rch` is equal to the value of the `ch` unit on the root element.
393  Rch,
394  /// A length in the `cap` unit. A `cap` is equal to the cap-height of the font.
395  Cap / CapUnit,
396  /// A length in the `rcap` unit. An `rcap` is equal to the value of the `cap` unit on the root element.
397  Rcap,
398  /// A length in the `ic` unit. An `ic` is equal to the width of the “水” (CJK water ideograph) character in the current font.
399  Ic / IcUnit,
400  /// A length in the `ric` unit. An `ric` is equal to the value of the `ic` unit on the root element.
401  Ric,
402  /// A length in the `lh` unit. An `lh` is equal to the computed value of the `line-height` property.
403  Lh / LhUnit,
404  /// A length in the `rlh` unit. An `rlh` is equal to the value of the `lh` unit on the root element.
405  Rlh / RlhUnit,
406
407  // https://www.w3.org/TR/css-values-4/#viewport-relative-units
408  /// A length in the `vw` unit. A `vw` is equal to 1% of the [viewport width](https://www.w3.org/TR/css-values-4/#ua-default-viewport-size).
409  Vw / VwUnit,
410  /// A length in the `lvw` unit. An `lvw` is equal to 1% of the [large viewport width](https://www.w3.org/TR/css-values-4/#large-viewport-size).
411  Lvw / ViewportPercentageUnitsLarge,
412  /// A length in the `svw` unit. An `svw` is equal to 1% of the [small viewport width](https://www.w3.org/TR/css-values-4/#small-viewport-size).
413  Svw / ViewportPercentageUnitsSmall,
414  /// A length in the `dvw` unit. An `dvw` is equal to 1% of the [dynamic viewport width](https://www.w3.org/TR/css-values-4/#dynamic-viewport-size).
415  Dvw / ViewportPercentageUnitsDynamic,
416  /// A length in the `cqw` unit. An `cqw` is equal to 1% of the [query container](https://drafts.csswg.org/css-contain-3/#query-container) width.
417  Cqw / ContainerQueryLengthUnits,
418
419  /// A length in the `vh` unit. A `vh` is equal to 1% of the [viewport height](https://www.w3.org/TR/css-values-4/#ua-default-viewport-size).
420  Vh / VhUnit,
421  /// A length in the `lvh` unit. An `lvh` is equal to 1% of the [large viewport height](https://www.w3.org/TR/css-values-4/#large-viewport-size).
422  Lvh / ViewportPercentageUnitsLarge,
423  /// A length in the `svh` unit. An `svh` is equal to 1% of the [small viewport height](https://www.w3.org/TR/css-values-4/#small-viewport-size).
424  Svh / ViewportPercentageUnitsSmall,
425  /// A length in the `dvh` unit. An `dvh` is equal to 1% of the [dynamic viewport height](https://www.w3.org/TR/css-values-4/#dynamic-viewport-size).
426  Dvh / ViewportPercentageUnitsDynamic,
427  /// A length in the `cqh` unit. An `cqh` is equal to 1% of the [query container](https://drafts.csswg.org/css-contain-3/#query-container) height.
428  Cqh / ContainerQueryLengthUnits,
429
430  /// A length in the `vi` unit. A `vi` is equal to 1% of the [viewport size](https://www.w3.org/TR/css-values-4/#ua-default-viewport-size)
431  /// in the box's [inline axis](https://www.w3.org/TR/css-writing-modes-4/#inline-axis).
432  Vi / ViUnit,
433  /// A length in the `svi` unit. A `svi` is equal to 1% of the [small viewport size](https://www.w3.org/TR/css-values-4/#small-viewport-size)
434  /// in the box's [inline axis](https://www.w3.org/TR/css-writing-modes-4/#inline-axis).
435  Svi / ViewportPercentageUnitsSmall,
436  /// A length in the `lvi` unit. A `lvi` is equal to 1% of the [large viewport size](https://www.w3.org/TR/css-values-4/#large-viewport-size)
437  /// in the box's [inline axis](https://www.w3.org/TR/css-writing-modes-4/#inline-axis).
438  Lvi / ViewportPercentageUnitsLarge,
439  /// A length in the `dvi` unit. A `dvi` is equal to 1% of the [dynamic viewport size](https://www.w3.org/TR/css-values-4/#dynamic-viewport-size)
440  /// in the box's [inline axis](https://www.w3.org/TR/css-writing-modes-4/#inline-axis).
441  Dvi / ViewportPercentageUnitsDynamic,
442  /// A length in the `cqi` unit. An `cqi` is equal to 1% of the [query container](https://drafts.csswg.org/css-contain-3/#query-container) inline size.
443  Cqi / ContainerQueryLengthUnits,
444
445  /// A length in the `vb` unit. A `vb` is equal to 1% of the [viewport size](https://www.w3.org/TR/css-values-4/#ua-default-viewport-size)
446  /// in the box's [block axis](https://www.w3.org/TR/css-writing-modes-4/#block-axis).
447  Vb / VbUnit,
448  /// A length in the `svb` unit. A `svb` is equal to 1% of the [small viewport size](https://www.w3.org/TR/css-values-4/#small-viewport-size)
449  /// in the box's [block axis](https://www.w3.org/TR/css-writing-modes-4/#block-axis).
450  Svb / ViewportPercentageUnitsSmall,
451  /// A length in the `lvb` unit. A `lvb` is equal to 1% of the [large viewport size](https://www.w3.org/TR/css-values-4/#large-viewport-size)
452  /// in the box's [block axis](https://www.w3.org/TR/css-writing-modes-4/#block-axis).
453  Lvb / ViewportPercentageUnitsLarge,
454  /// A length in the `dvb` unit. A `dvb` is equal to 1% of the [dynamic viewport size](https://www.w3.org/TR/css-values-4/#dynamic-viewport-size)
455  /// in the box's [block axis](https://www.w3.org/TR/css-writing-modes-4/#block-axis).
456  Dvb / ViewportPercentageUnitsDynamic,
457  /// A length in the `cqb` unit. An `cqb` is equal to 1% of the [query container](https://drafts.csswg.org/css-contain-3/#query-container) block size.
458  Cqb / ContainerQueryLengthUnits,
459
460  /// A length in the `vmin` unit. A `vmin` is equal to the smaller of `vw` and `vh`.
461  Vmin / VminUnit,
462  /// A length in the `svmin` unit. An `svmin` is equal to the smaller of `svw` and `svh`.
463  Svmin / ViewportPercentageUnitsSmall,
464  /// A length in the `lvmin` unit. An `lvmin` is equal to the smaller of `lvw` and `lvh`.
465  Lvmin / ViewportPercentageUnitsLarge,
466  /// A length in the `dvmin` unit. A `dvmin` is equal to the smaller of `dvw` and `dvh`.
467  Dvmin / ViewportPercentageUnitsDynamic,
468  /// A length in the `cqmin` unit. An `cqmin` is equal to the smaller of `cqi` and `cqb`.
469  Cqmin / ContainerQueryLengthUnits,
470
471  /// A length in the `vmax` unit. A `vmax` is equal to the larger of `vw` and `vh`.
472  Vmax / VmaxUnit,
473  /// A length in the `svmax` unit. An `svmax` is equal to the larger of `svw` and `svh`.
474  Svmax / ViewportPercentageUnitsSmall,
475  /// A length in the `lvmax` unit. An `lvmax` is equal to the larger of `lvw` and `lvh`.
476  Lvmax / ViewportPercentageUnitsLarge,
477  /// A length in the `dvmax` unit. An `dvmax` is equal to the larger of `dvw` and `dvh`.
478  Dvmax / ViewportPercentageUnitsDynamic,
479  /// A length in the `cqmax` unit. An `cqmin` is equal to the larger of `cqi` and `cqb`.
480  Cqmax / ContainerQueryLengthUnits,
481}
482
483impl ToCss for LengthValue {
484  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
485    let (value, unit) = self.to_unit_value();
486
487    // The unit can be omitted if the value is zero, except inside calc()
488    // expressions, where unitless numbers won't be parsed as dimensions.
489    if !dest.in_calc() && value == 0.0 {
490      dest.write_char('0')?;
491      return Ok(());
492    }
493
494    serialize_dimension(value, unit, dest)
495  }
496}
497
498impl LengthValue {
499  pub(crate) fn to_css_unitless<PrinterT: crate::printer::PrinterTrait>(
500    &self,
501    dest: &mut PrinterT,
502  ) -> Result<(), PrinterError> {
503    match self {
504      LengthValue::Px(value) => value.to_css(dest),
505      _ => self.to_css(dest),
506    }
507  }
508}
509
510pub(crate) fn serialize_dimension<PrinterT: crate::printer::PrinterTrait>(
511  value: f32,
512  unit: &str,
513  dest: &mut PrinterT,
514) -> Result<(), PrinterError> {
515  use cssparser::ToCss;
516  let int_value = if value.fract() == 0.0 { Some(value as i32) } else { None };
517  let token = Token::Dimension {
518    has_sign: value < 0.0,
519    value,
520    int_value,
521    unit: CowRcStr::from(unit),
522  };
523  if value != 0.0 && value.abs() < 1.0 {
524    let mut s = String::new();
525    token.to_css(&mut s)?;
526    if value < 0.0 {
527      if let Some(stripped) = s.strip_prefix("-0") {
528        dest.write_char('-')?;
529        dest.write_str(stripped)?;
530        Ok(())
531      } else {
532        dest.write_str(&s)?;
533        Ok(())
534      }
535    } else {
536      dest.write_str(s.trim_start_matches('0'))?;
537      Ok(())
538    }
539  } else {
540    token.to_css(dest)?;
541    Ok(())
542  }
543}
544
545impl LengthValue {
546  /// Attempts to convert the value to pixels.
547  /// Returns `None` if the conversion is not possible.
548  pub fn to_px(&self) -> Option<CSSNumber> {
549    use LengthValue::*;
550    match self {
551      Px(value) => Some(*value),
552      In(value) => Some(value * PX_PER_IN),
553      Cm(value) => Some(value * PX_PER_CM),
554      Mm(value) => Some(value * PX_PER_MM),
555      Q(value) => Some(value * PX_PER_Q),
556      Pt(value) => Some(value * PX_PER_PT),
557      Pc(value) => Some(value * PX_PER_PC),
558      _ => None,
559    }
560  }
561}
562
563/// A CSS [`<length>`](https://www.w3.org/TR/css-values-4/#lengths) value, with support for `calc()`.
564#[derive(Debug, Clone, PartialEq)]
565#[cfg_attr(feature = "visitor", derive(Visit))]
566#[cfg_attr(
567  feature = "serde",
568  derive(serde::Serialize, serde::Deserialize),
569  serde(tag = "type", content = "value", rename_all = "kebab-case")
570)]
571#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
572#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
573pub enum Length {
574  /// An explicitly specified length value.
575  Value(LengthValue),
576  /// A computed length value using `calc()`.
577  #[cfg_attr(feature = "visitor", skip_type)]
578  Calc(Box<Calc<Length>>),
579}
580
581impl<'i> Parse<'i> for Length {
582  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
583    Self::parse_with_range(input, NumericRange::All)
584  }
585}
586
587impl<'i> ParseNumeric<'i> for Length {
588  fn parse_with_range<'t>(
589    input: &mut Parser<'i, 't>,
590    range: NumericRange,
591  ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
592    match input.try_parse(Calc::parse) {
593      Ok(Calc::Value(v)) => {
594        if range == NumericRange::All {
595          return Ok(*v);
596        }
597        if let Some(value) = v.try_map(|value| range.clamp(value)) {
598          return Ok(value);
599        }
600        return Ok(Length::Calc(Box::new(Calc::Function(Box::new(MathFunction::Calc(
601          Calc::Value(v),
602        ))))));
603      }
604      Ok(Calc::Number(_)) => return Err(input.new_custom_error(ParserError::InvalidValue)),
605      Ok(calc) => return Ok(Length::Calc(Box::new(calc))),
606      _ => {}
607    }
608
609    let len = LengthValue::parse_with_range(input, range)?;
610    Ok(Length::Value(len))
611  }
612}
613
614impl ToCss for Length {
615  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
616    match self {
617      Length::Value(a) => a.to_css(dest),
618      Length::Calc(c) => c.to_css(dest),
619    }
620  }
621}
622
623impl std::ops::Mul<CSSNumber> for Length {
624  type Output = Self;
625
626  fn mul(self, other: CSSNumber) -> Length {
627    match self {
628      Length::Value(a) => Length::Value(a * other),
629      Length::Calc(a) => Length::Calc(Box::new(*a * other)),
630    }
631  }
632}
633
634impl std::ops::Add<Length> for Length {
635  type Output = Self;
636
637  fn add(self, other: Length) -> Length {
638    // Unwrap calc(...) functions so we can add inside.
639    // Then wrap the result in a calc(...) again if necessary.
640    let a = unwrap_calc(self);
641    let b = unwrap_calc(other);
642    let res = AddInternal::add(a, b);
643    match res {
644      Length::Calc(c) => match *c {
645        Calc::Value(l) => *l,
646        Calc::Function(f) if !matches!(*f, MathFunction::Calc(_)) => Length::Calc(Box::new(Calc::Function(f))),
647        c => Length::Calc(Box::new(Calc::Function(Box::new(MathFunction::Calc(c))))),
648      },
649      _ => res,
650    }
651  }
652}
653
654fn unwrap_calc(length: Length) -> Length {
655  match length {
656    Length::Calc(c) => match *c {
657      Calc::Function(f) => match *f {
658        MathFunction::Calc(c) => Length::Calc(Box::new(c)),
659        c => Length::Calc(Box::new(Calc::Function(Box::new(c)))),
660      },
661      _ => Length::Calc(c),
662    },
663    _ => length,
664  }
665}
666
667impl AddInternal for Length {
668  fn add(self, other: Self) -> Self {
669    match self.try_add(&other) {
670      Some(r) => r,
671      None => self.add(other),
672    }
673  }
674}
675
676impl Length {
677  /// Constructs a length with the given pixel value.
678  pub fn px(px: CSSNumber) -> Length {
679    Length::Value(LengthValue::Px(px))
680  }
681
682  /// Attempts to convert the length to pixels.
683  /// Returns `None` if the conversion is not possible.
684  pub fn to_px(&self) -> Option<CSSNumber> {
685    match self {
686      Length::Value(a) => a.to_px(),
687      _ => None,
688    }
689  }
690
691  fn add(self, other: Length) -> Length {
692    let mut a = self;
693    let mut b = other;
694
695    if a.is_zero() {
696      return b;
697    }
698
699    if b.is_zero() {
700      return a;
701    }
702
703    if a.is_sign_negative() && b.is_sign_positive() {
704      std::mem::swap(&mut a, &mut b);
705    }
706
707    match (a, b) {
708      (Length::Calc(a), Length::Calc(b)) => return Length::Calc(Box::new(a.add(*b).unwrap())),
709      (Length::Calc(calc), b) => {
710        if let Calc::Value(a) = *calc {
711          a.add(b)
712        } else {
713          Length::Calc(Box::new(Calc::Sum(Box::new((*calc).into()), Box::new(b.into()))))
714        }
715      }
716      (a, Length::Calc(calc)) => {
717        if let Calc::Value(b) = *calc {
718          a.add(*b)
719        } else {
720          Length::Calc(Box::new(Calc::Sum(Box::new(a.into()), Box::new((*calc).into()))))
721        }
722      }
723      (a, b) => Length::Calc(Box::new(Calc::Sum(Box::new(a.into()), Box::new(b.into())))),
724    }
725  }
726}
727
728impl IsCompatible for Length {
729  fn is_compatible(&self, browsers: Browsers) -> bool {
730    match self {
731      Length::Value(v) => v.is_compatible(browsers),
732      Length::Calc(calc) => calc.is_compatible(browsers),
733    }
734  }
735}
736
737impl Zero for Length {
738  fn zero() -> Length {
739    Length::Value(LengthValue::Px(0.0))
740  }
741
742  fn is_zero(&self) -> bool {
743    match self {
744      Length::Value(v) => v.is_zero(),
745      _ => false,
746    }
747  }
748}
749
750impl TryAdd<Length> for Length {
751  fn try_add(&self, other: &Length) -> Option<Length> {
752    match (self, other) {
753      (Length::Value(a), Length::Value(b)) => {
754        if let Some(res) = a.try_add(b) {
755          Some(Length::Value(res))
756        } else {
757          None
758        }
759      }
760      (Length::Calc(a), other) => match &**a {
761        Calc::Value(v) => v.try_add(other),
762        Calc::Sum(a, b) => {
763          if let Some(res) = Length::Calc(Box::new(*a.clone())).try_add(other) {
764            return Some(res.add(Length::from(*b.clone())));
765          }
766
767          if let Some(res) = Length::Calc(Box::new(*b.clone())).try_add(other) {
768            return Some(Length::from(*a.clone()).add(res));
769          }
770
771          None
772        }
773        _ => None,
774      },
775      (other, Length::Calc(b)) => match &**b {
776        Calc::Value(v) => other.try_add(&*v),
777        Calc::Sum(a, b) => {
778          if let Some(res) = other.try_add(&Length::Calc(Box::new(*a.clone()))) {
779            return Some(res.add(Length::from(*b.clone())));
780          }
781
782          if let Some(res) = other.try_add(&Length::Calc(Box::new(*b.clone()))) {
783            return Some(Length::from(*a.clone()).add(res));
784          }
785
786          None
787        }
788        _ => None,
789      },
790    }
791  }
792}
793
794impl std::convert::Into<Calc<Length>> for Length {
795  fn into(self) -> Calc<Length> {
796    match self {
797      Length::Calc(c) => *c,
798      b => Calc::Value(Box::new(b)),
799    }
800  }
801}
802
803impl std::convert::From<Calc<Length>> for Length {
804  fn from(calc: Calc<Length>) -> Length {
805    Length::Calc(Box::new(calc))
806  }
807}
808
809impl std::cmp::PartialOrd<Length> for Length {
810  fn partial_cmp(&self, other: &Length) -> Option<std::cmp::Ordering> {
811    match (self, other) {
812      (Length::Value(a), Length::Value(b)) => a.partial_cmp(b),
813      _ => None,
814    }
815  }
816}
817
818impl TryOp for Length {
819  fn try_op<F: FnOnce(f32, f32) -> f32>(&self, rhs: &Self, op: F) -> Option<Self> {
820    match (self, rhs) {
821      (Length::Value(a), Length::Value(b)) => a.try_op(b, op).map(Length::Value),
822      _ => None,
823    }
824  }
825
826  fn try_op_to<T, F: FnOnce(f32, f32) -> T>(&self, rhs: &Self, op: F) -> Option<T> {
827    match (self, rhs) {
828      (Length::Value(a), Length::Value(b)) => a.try_op_to(b, op),
829      _ => None,
830    }
831  }
832}
833
834impl TryMap for Length {
835  fn try_map<F: FnOnce(f32) -> f32>(&self, op: F) -> Option<Self> {
836    match self {
837      Length::Value(v) => v.try_map(op).map(Length::Value),
838      _ => None,
839    }
840  }
841}
842
843impl TrySign for Length {
844  fn try_sign(&self) -> Option<f32> {
845    match self {
846      Length::Value(v) => Some(v.sign()),
847      Length::Calc(c) => c.try_sign(),
848    }
849  }
850}
851
852impl_try_from_angle!(Length);
853
854/// Either a [`<length>`](https://www.w3.org/TR/css-values-4/#lengths) or a [`<number>`](https://www.w3.org/TR/css-values-4/#numbers).
855#[derive(Debug, Clone, PartialEq, ToCss)]
856#[cfg_attr(feature = "visitor", derive(Visit))]
857#[cfg_attr(
858  feature = "serde",
859  derive(serde::Serialize, serde::Deserialize),
860  serde(tag = "type", content = "value", rename_all = "kebab-case")
861)]
862#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
863#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
864pub enum LengthOrNumber {
865  /// A number.
866  Number(CSSNumber),
867  /// A length.
868  Length(Length),
869}
870
871impl<'i> Parse<'i> for LengthOrNumber {
872  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
873    Self::parse_with_range(input, NumericRange::All)
874  }
875}
876
877impl<'i> ParseNumeric<'i> for LengthOrNumber {
878  fn parse_with_range<'t>(
879    input: &mut Parser<'i, 't>,
880    range: NumericRange,
881  ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
882    if let Ok(value) = input.try_parse(|input| CSSNumber::parse_with_range(input, range)) {
883      return Ok(Self::Number(value));
884    }
885    Ok(Self::Length(Length::parse_with_range(input, range)?))
886  }
887}
888
889impl Default for LengthOrNumber {
890  fn default() -> LengthOrNumber {
891    LengthOrNumber::Number(0.0)
892  }
893}
894
895impl Zero for LengthOrNumber {
896  fn zero() -> Self {
897    LengthOrNumber::Number(0.0)
898  }
899
900  fn is_zero(&self) -> bool {
901    match self {
902      LengthOrNumber::Length(l) => l.is_zero(),
903      LengthOrNumber::Number(v) => v.is_zero(),
904    }
905  }
906}
907
908impl IsCompatible for LengthOrNumber {
909  fn is_compatible(&self, browsers: Browsers) -> bool {
910    match self {
911      LengthOrNumber::Length(l) => l.is_compatible(browsers),
912      LengthOrNumber::Number(..) => true,
913    }
914  }
915}