Skip to main content

rspack_lightningcss/values/
percentage.rs

1//! CSS percentage values.
2
3use super::angle::{impl_try_from_angle, Angle};
4use super::calc::{Calc, MathFunction};
5use super::number::{CSSNumber, NumericRange};
6use crate::error::{ParserError, PrinterError};
7use crate::traits::private::AddInternal;
8use crate::traits::{
9  impl_op, private::TryAdd, Op, Parse, ParseNumeric, Sign, ToCss, TryMap, TryOp, TrySign, Zero,
10};
11#[cfg(feature = "visitor")]
12use crate::visitor::Visit;
13use cssparser::*;
14
15/// A CSS [`<percentage>`](https://www.w3.org/TR/css-values-4/#percentages) value.
16///
17/// Percentages may be explicit or computed by `calc()`, but are always stored and serialized
18/// as their computed value.
19#[derive(Debug, Clone, PartialEq)]
20#[cfg_attr(feature = "visitor", derive(Visit))]
21#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize), serde(transparent))]
22#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
23#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
24pub struct Percentage(pub CSSNumber);
25
26impl<'i> Parse<'i> for Percentage {
27  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
28    Self::parse_with_range(input, NumericRange::All)
29  }
30}
31
32impl<'i> ParseNumeric<'i> for Percentage {
33  fn parse_with_range<'t>(
34    input: &mut Parser<'i, 't>,
35    range: NumericRange,
36  ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
37    match input.try_parse(Calc::<Self>::parse) {
38      Ok(Calc::Value(v)) => return Ok(Percentage(range.clamp(v.0))),
39      // A percentage calculation must resolve to a percentage, not a number.
40      Ok(_) => return Err(input.new_custom_error(ParserError::InvalidValue)),
41      _ => {}
42    }
43
44    let location = input.current_source_location();
45    let percent = input.expect_percentage()?;
46    Ok(Percentage(range.check(percent, location)?))
47  }
48}
49
50impl ToCss for Percentage {
51  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
52    use cssparser::ToCss;
53    let v = self.0 * 100.0;
54    let int_value = if (v).fract() == 0.0 { Some(v as i32) } else { None };
55    let percent = Token::Percentage {
56      has_sign: self.0 < 0.0,
57      unit_value: self.0,
58      int_value,
59    };
60    if self.0 != 0.0 && self.0.abs() < 0.01 {
61      let mut s = String::new();
62      percent.to_css(&mut s)?;
63      if self.0 < 0.0 {
64        dest.write_char('-')?;
65        dest.write_str(s.trim_start_matches("-0"))?;
66        Ok(())
67      } else {
68        dest.write_str(s.trim_start_matches('0'))?;
69        Ok(())
70      }
71    } else {
72      percent.to_css(dest)?;
73      Ok(())
74    }
75  }
76}
77
78impl std::convert::Into<Calc<Percentage>> for Percentage {
79  fn into(self) -> Calc<Percentage> {
80    Calc::Value(Box::new(self))
81  }
82}
83
84impl std::convert::TryFrom<Calc<Percentage>> for Percentage {
85  type Error = ();
86
87  fn try_from(calc: Calc<Percentage>) -> Result<Percentage, Self::Error> {
88    match calc {
89      Calc::Value(v) => Ok(*v),
90      _ => Err(()),
91    }
92  }
93}
94
95impl std::ops::Mul<CSSNumber> for Percentage {
96  type Output = Self;
97
98  fn mul(self, other: CSSNumber) -> Percentage {
99    Percentage(self.0 * other)
100  }
101}
102
103impl AddInternal for Percentage {
104  fn add(self, other: Self) -> Self {
105    self + other
106  }
107}
108
109impl std::cmp::PartialOrd<Percentage> for Percentage {
110  fn partial_cmp(&self, other: &Percentage) -> Option<std::cmp::Ordering> {
111    self.0.partial_cmp(&other.0)
112  }
113}
114
115impl Op for Percentage {
116  fn op<F: FnOnce(f32, f32) -> f32>(&self, to: &Self, op: F) -> Self {
117    Percentage(op(self.0, to.0))
118  }
119
120  fn op_to<T, F: FnOnce(f32, f32) -> T>(&self, rhs: &Self, op: F) -> T {
121    op(self.0, rhs.0)
122  }
123}
124
125impl TryMap for Percentage {
126  fn try_map<F: FnOnce(f32) -> f32>(&self, _: F) -> Option<Self> {
127    // Percentages cannot be mapped because we don't know what they will resolve to.
128    // For example, they might be positive or negative depending on what they are a
129    // percentage of, which we don't know.
130    None
131  }
132}
133
134impl Zero for Percentage {
135  fn zero() -> Self {
136    Percentage(0.0)
137  }
138
139  fn is_zero(&self) -> bool {
140    self.0.is_zero()
141  }
142}
143
144impl Sign for Percentage {
145  fn sign(&self) -> f32 {
146    self.0.sign()
147  }
148}
149
150impl_op!(Percentage, std::ops::Rem, rem);
151impl_op!(Percentage, std::ops::Add, add);
152
153impl_try_from_angle!(Percentage);
154
155/// Either a `<number>` or `<percentage>`.
156#[derive(Debug, Clone, PartialEq, ToCss)]
157#[cfg_attr(feature = "visitor", derive(Visit))]
158#[cfg_attr(
159  feature = "serde",
160  derive(serde::Serialize, serde::Deserialize),
161  serde(tag = "type", content = "value", rename_all = "kebab-case")
162)]
163#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
164#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
165pub enum NumberOrPercentage {
166  /// A number.
167  Number(CSSNumber),
168  /// A percentage.
169  Percentage(Percentage),
170}
171
172impl<'i> Parse<'i> for NumberOrPercentage {
173  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
174    Self::parse_with_range(input, NumericRange::All)
175  }
176}
177
178impl<'i> ParseNumeric<'i> for NumberOrPercentage {
179  fn parse_with_range<'t>(
180    input: &mut Parser<'i, 't>,
181    range: NumericRange,
182  ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
183    if let Ok(value) = input.try_parse(|input| CSSNumber::parse_with_range(input, range)) {
184      return Ok(Self::Number(value));
185    }
186    Ok(Self::Percentage(Percentage::parse_with_range(input, range)?))
187  }
188}
189
190impl std::convert::Into<CSSNumber> for &NumberOrPercentage {
191  fn into(self) -> CSSNumber {
192    match self {
193      NumberOrPercentage::Number(a) => *a,
194      NumberOrPercentage::Percentage(a) => a.0,
195    }
196  }
197}
198
199/// A generic type that allows any kind of dimension and percentage to be
200/// used standalone or mixed within a `calc()` expression.
201///
202/// <https://drafts.csswg.org/css-values-4/#mixed-percentages>
203#[derive(Debug, Clone, PartialEq)]
204#[cfg_attr(feature = "visitor", derive(Visit))]
205#[cfg_attr(
206  feature = "serde",
207  derive(serde::Serialize, serde::Deserialize),
208  serde(tag = "type", content = "value", rename_all = "kebab-case")
209)]
210#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
211#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
212pub enum DimensionPercentage<D> {
213  /// An explicit dimension value.
214  Dimension(D),
215  /// A percentage.
216  Percentage(Percentage),
217  /// A `calc()` expression.
218  #[cfg_attr(feature = "visitor", skip_type)]
219  Calc(Box<Calc<DimensionPercentage<D>>>),
220}
221
222impl<
223    'i,
224    D: ParseNumeric<'i>
225      + std::ops::Mul<CSSNumber, Output = D>
226      + TryAdd<D>
227      + Clone
228      + TryOp
229      + TryMap
230      + Zero
231      + TrySign
232      + TryFrom<Angle>
233      + TryInto<Angle>
234      + PartialOrd<D>
235      + std::fmt::Debug,
236  > Parse<'i> for DimensionPercentage<D>
237{
238  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
239    Self::parse_with_range(input, NumericRange::All)
240  }
241}
242
243impl<
244    'i,
245    D: ParseNumeric<'i>
246      + std::ops::Mul<CSSNumber, Output = D>
247      + TryAdd<D>
248      + Clone
249      + TryOp
250      + TryMap
251      + Zero
252      + TrySign
253      + TryFrom<Angle>
254      + TryInto<Angle>
255      + PartialOrd<D>
256      + std::fmt::Debug,
257  > ParseNumeric<'i> for DimensionPercentage<D>
258{
259  fn parse_with_range<'t>(
260    input: &mut Parser<'i, 't>,
261    range: NumericRange,
262  ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
263    match input.try_parse(Calc::parse) {
264      Ok(Calc::Value(v)) => {
265        if range == NumericRange::All {
266          return Ok(*v);
267        }
268        if let Some(value) = v.try_map(|value| range.clamp(value)) {
269          return Ok(value);
270        }
271        if matches!(&*v, DimensionPercentage::Percentage(Percentage(value)) if *value >= 0.0) {
272          return Ok(*v);
273        }
274        // A negative percentage cannot be emitted as a literal in this range.
275        // Preserve the math boundary rather than clamp it before its basis is known.
276        return Ok(DimensionPercentage::Calc(Box::new(Calc::Function(Box::new(
277          MathFunction::Calc(Calc::Value(v)),
278        )))));
279      }
280      Ok(Calc::Number(_)) => return Err(input.new_custom_error(ParserError::InvalidValue)),
281      Ok(calc) => return Ok(DimensionPercentage::Calc(Box::new(calc))),
282      _ => {}
283    }
284
285    if let Ok(length) = input.try_parse(|input| D::parse_with_range(input, range)) {
286      return Ok(DimensionPercentage::Dimension(length));
287    }
288
289    if let Ok(percent) = input.try_parse(|input| Percentage::parse_with_range(input, range)) {
290      return Ok(DimensionPercentage::Percentage(percent));
291    }
292
293    Err(input.new_error_for_next_token())
294  }
295}
296
297impl<D: std::ops::Mul<CSSNumber, Output = D>> std::ops::Mul<CSSNumber> for DimensionPercentage<D> {
298  type Output = Self;
299
300  fn mul(self, other: CSSNumber) -> DimensionPercentage<D> {
301    match self {
302      DimensionPercentage::Dimension(l) => DimensionPercentage::Dimension(l * other),
303      DimensionPercentage::Percentage(p) => DimensionPercentage::Percentage(Percentage(p.0 * other)),
304      DimensionPercentage::Calc(c) => DimensionPercentage::Calc(Box::new(*c * other)),
305    }
306  }
307}
308
309impl<D: TryAdd<D> + Clone + Zero + TrySign + std::fmt::Debug> std::ops::Add<DimensionPercentage<D>>
310  for DimensionPercentage<D>
311{
312  type Output = DimensionPercentage<D>;
313
314  fn add(self, other: DimensionPercentage<D>) -> DimensionPercentage<D> {
315    // Unwrap calc(...) functions so we can add inside.
316    // Then wrap the result in a calc(...) again if necessary.
317    let a = unwrap_calc(self);
318    let b = unwrap_calc(other);
319    let res = AddInternal::add(a, b);
320    match res {
321      DimensionPercentage::Calc(c) => match *c {
322        Calc::Value(l) => *l,
323        Calc::Function(f) if !matches!(*f, MathFunction::Calc(_)) => {
324          DimensionPercentage::Calc(Box::new(Calc::Function(f)))
325        }
326        c => DimensionPercentage::Calc(Box::new(Calc::Function(Box::new(MathFunction::Calc(c))))),
327      },
328      _ => res,
329    }
330  }
331}
332
333fn unwrap_calc<D>(v: DimensionPercentage<D>) -> DimensionPercentage<D> {
334  match v {
335    DimensionPercentage::Calc(c) => match *c {
336      Calc::Function(f) => match *f {
337        MathFunction::Calc(c) => DimensionPercentage::Calc(Box::new(c)),
338        c => DimensionPercentage::Calc(Box::new(Calc::Function(Box::new(c)))),
339      },
340      _ => DimensionPercentage::Calc(c),
341    },
342    _ => v,
343  }
344}
345
346impl<D: TryAdd<D> + Clone + Zero + TrySign + std::fmt::Debug> AddInternal for DimensionPercentage<D> {
347  fn add(self, other: Self) -> Self {
348    match self.add_recursive(&other) {
349      Some(r) => r,
350      None => self.add(other),
351    }
352  }
353}
354
355impl<D: TryAdd<D> + Clone + Zero + TrySign + std::fmt::Debug> DimensionPercentage<D> {
356  fn add_recursive(&self, other: &DimensionPercentage<D>) -> Option<DimensionPercentage<D>> {
357    match (self, other) {
358      (DimensionPercentage::Dimension(a), DimensionPercentage::Dimension(b)) => {
359        if let Some(res) = a.try_add(b) {
360          Some(DimensionPercentage::Dimension(res))
361        } else {
362          None
363        }
364      }
365      (DimensionPercentage::Percentage(a), DimensionPercentage::Percentage(b)) => {
366        Some(DimensionPercentage::Percentage(Percentage(a.0 + b.0)))
367      }
368      (DimensionPercentage::Calc(a), other) => match &**a {
369        Calc::Value(v) => v.add_recursive(other),
370        Calc::Sum(a, b) => {
371          if let Some(res) = DimensionPercentage::Calc(Box::new(*a.clone())).add_recursive(other) {
372            return Some(res.add(DimensionPercentage::from(*b.clone())));
373          }
374
375          if let Some(res) = DimensionPercentage::Calc(Box::new(*b.clone())).add_recursive(other) {
376            return Some(DimensionPercentage::from(*a.clone()).add(res));
377          }
378
379          None
380        }
381        _ => None,
382      },
383      (other, DimensionPercentage::Calc(b)) => match &**b {
384        Calc::Value(v) => other.add_recursive(&*v),
385        Calc::Sum(a, b) => {
386          if let Some(res) = other.add_recursive(&DimensionPercentage::Calc(Box::new(*a.clone()))) {
387            return Some(res.add(DimensionPercentage::from(*b.clone())));
388          }
389
390          if let Some(res) = other.add_recursive(&DimensionPercentage::Calc(Box::new(*b.clone()))) {
391            return Some(DimensionPercentage::from(*a.clone()).add(res));
392          }
393
394          None
395        }
396        _ => None,
397      },
398      _ => None,
399    }
400  }
401
402  fn add(self, other: DimensionPercentage<D>) -> DimensionPercentage<D> {
403    let mut a = self;
404    let mut b = other;
405
406    if a.is_zero() {
407      return b;
408    }
409
410    if b.is_zero() {
411      return a;
412    }
413
414    if a.is_sign_negative() && b.is_sign_positive() {
415      std::mem::swap(&mut a, &mut b);
416    }
417
418    match (a, b) {
419      (DimensionPercentage::Calc(a), DimensionPercentage::Calc(b)) => {
420        DimensionPercentage::Calc(Box::new(a.add(*b).unwrap()))
421      }
422      (DimensionPercentage::Calc(calc), b) => {
423        if let Calc::Value(a) = *calc {
424          a.add(b)
425        } else {
426          DimensionPercentage::Calc(Box::new(Calc::Sum(Box::new((*calc).into()), Box::new(b.into()))))
427        }
428      }
429      (a, DimensionPercentage::Calc(calc)) => {
430        if let Calc::Value(b) = *calc {
431          a.add(*b)
432        } else {
433          DimensionPercentage::Calc(Box::new(Calc::Sum(Box::new(a.into()), Box::new((*calc).into()))))
434        }
435      }
436      (a, b) => DimensionPercentage::Calc(Box::new(Calc::Sum(Box::new(a.into()), Box::new(b.into())))),
437    }
438  }
439}
440
441impl<D> std::convert::Into<Calc<DimensionPercentage<D>>> for DimensionPercentage<D> {
442  fn into(self) -> Calc<DimensionPercentage<D>> {
443    match self {
444      DimensionPercentage::Calc(c) => *c,
445      b => Calc::Value(Box::new(b)),
446    }
447  }
448}
449
450impl<D> std::convert::From<Calc<DimensionPercentage<D>>> for DimensionPercentage<D> {
451  fn from(calc: Calc<DimensionPercentage<D>>) -> DimensionPercentage<D> {
452    DimensionPercentage::Calc(Box::new(calc))
453  }
454}
455
456impl<D: std::cmp::PartialOrd<D>> std::cmp::PartialOrd<DimensionPercentage<D>> for DimensionPercentage<D> {
457  fn partial_cmp(&self, other: &DimensionPercentage<D>) -> Option<std::cmp::Ordering> {
458    match (self, other) {
459      (DimensionPercentage::Dimension(a), DimensionPercentage::Dimension(b)) => a.partial_cmp(b),
460      (DimensionPercentage::Percentage(a), DimensionPercentage::Percentage(b)) => a.partial_cmp(b),
461      _ => None,
462    }
463  }
464}
465
466impl<D: TryOp> TryOp for DimensionPercentage<D> {
467  fn try_op<F: FnOnce(f32, f32) -> f32>(&self, rhs: &Self, op: F) -> Option<Self> {
468    match (self, rhs) {
469      (DimensionPercentage::Dimension(a), DimensionPercentage::Dimension(b)) => {
470        a.try_op(b, op).map(DimensionPercentage::Dimension)
471      }
472      (DimensionPercentage::Percentage(a), DimensionPercentage::Percentage(b)) => {
473        Some(DimensionPercentage::Percentage(Percentage(op(a.0, b.0))))
474      }
475      _ => None,
476    }
477  }
478
479  fn try_op_to<T, F: FnOnce(f32, f32) -> T>(&self, rhs: &Self, op: F) -> Option<T> {
480    match (self, rhs) {
481      (DimensionPercentage::Dimension(a), DimensionPercentage::Dimension(b)) => a.try_op_to(b, op),
482      (DimensionPercentage::Percentage(a), DimensionPercentage::Percentage(b)) => Some(op(a.0, b.0)),
483      _ => None,
484    }
485  }
486}
487
488impl<D: TryMap> TryMap for DimensionPercentage<D> {
489  fn try_map<F: FnOnce(f32) -> f32>(&self, op: F) -> Option<Self> {
490    match self {
491      DimensionPercentage::Dimension(v) => v.try_map(op).map(DimensionPercentage::Dimension),
492      _ => None,
493    }
494  }
495}
496
497impl<E, D: TryFrom<Angle, Error = E>> TryFrom<Angle> for DimensionPercentage<D> {
498  type Error = E;
499
500  fn try_from(value: Angle) -> Result<Self, Self::Error> {
501    Ok(DimensionPercentage::Dimension(D::try_from(value)?))
502  }
503}
504
505impl<E, D: TryInto<Angle, Error = E>> TryInto<Angle> for DimensionPercentage<D> {
506  type Error = ();
507
508  fn try_into(self) -> Result<Angle, Self::Error> {
509    match self {
510      DimensionPercentage::Dimension(d) => d.try_into().map_err(|_| ()),
511      _ => Err(()),
512    }
513  }
514}
515
516impl<D: Zero> Zero for DimensionPercentage<D> {
517  fn zero() -> Self {
518    DimensionPercentage::Dimension(D::zero())
519  }
520
521  fn is_zero(&self) -> bool {
522    match self {
523      DimensionPercentage::Dimension(d) => d.is_zero(),
524      DimensionPercentage::Percentage(p) => p.is_zero(),
525      _ => false,
526    }
527  }
528}
529
530impl<D: TrySign> TrySign for DimensionPercentage<D> {
531  fn try_sign(&self) -> Option<f32> {
532    match self {
533      DimensionPercentage::Dimension(d) => d.try_sign(),
534      DimensionPercentage::Percentage(p) => p.try_sign(),
535      DimensionPercentage::Calc(c) => c.try_sign(),
536    }
537  }
538}
539
540impl<D: ToCss + std::ops::Mul<CSSNumber, Output = D> + TrySign + Clone + std::fmt::Debug> ToCss
541  for DimensionPercentage<D>
542{
543  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
544    match self {
545      DimensionPercentage::Dimension(length) => length.to_css(dest),
546      DimensionPercentage::Percentage(percent) => percent.to_css(dest),
547      DimensionPercentage::Calc(calc) => calc.to_css(dest),
548    }
549  }
550}