Skip to main content

rspack_lightningcss/values/
position.rs

1//! CSS position values.
2
3use super::length::LengthPercentage;
4use super::percentage::Percentage;
5use crate::error::{ParserError, PrinterError};
6use crate::macros::enum_property;
7use crate::targets::Browsers;
8use crate::traits::{IsCompatible, Parse, ToCss, Zero};
9#[cfg(feature = "visitor")]
10use crate::visitor::Visit;
11use cssparser::*;
12
13#[cfg(feature = "serde")]
14use crate::serialization::ValueWrapper;
15
16/// A CSS [`<position>`](https://www.w3.org/TR/css3-values/#position) value,
17/// as used in the `background-position` property, gradients, masks, etc.
18#[derive(Debug, Clone, PartialEq)]
19#[cfg_attr(feature = "visitor", derive(Visit))]
20#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
21#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
22#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
23pub struct Position {
24  /// The x-position.
25  pub x: HorizontalPosition,
26  /// The y-position.
27  pub y: VerticalPosition,
28}
29
30impl Position {
31  /// Returns a `Position` with both the x and y set to `center`.
32  pub fn center() -> Position {
33    Position {
34      x: HorizontalPosition::Center,
35      y: VerticalPosition::Center,
36    }
37  }
38
39  /// Returns whether both the x and y positions are centered.
40  pub fn is_center(&self) -> bool {
41    self.x.is_center() && self.y.is_center()
42  }
43
44  /// Returns whether both the x and y positions are zero.
45  pub fn is_zero(&self) -> bool {
46    self.x.is_zero() && self.y.is_zero()
47  }
48}
49
50impl Default for Position {
51  fn default() -> Position {
52    Position {
53      x: HorizontalPosition::Length(LengthPercentage::Percentage(Percentage(0.0))),
54      y: VerticalPosition::Length(LengthPercentage::Percentage(Percentage(0.0))),
55    }
56  }
57}
58
59impl<'i> Parse<'i> for Position {
60  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
61    match input.try_parse(HorizontalPosition::parse) {
62      Ok(HorizontalPosition::Center) => {
63        // Try parsing a vertical position next.
64        if let Ok(y) = input.try_parse(VerticalPosition::parse) {
65          return Ok(Position {
66            x: HorizontalPosition::Center,
67            y,
68          });
69        }
70
71        // If it didn't work, assume the first actually represents a y position,
72        // and the next is an x position. e.g. `center left` rather than `left center`.
73        let x = input.try_parse(HorizontalPosition::parse).unwrap_or(HorizontalPosition::Center);
74        let y = VerticalPosition::Center;
75        return Ok(Position { x, y });
76      }
77      Ok(x @ HorizontalPosition::Length(_)) => {
78        // If we got a length as the first component, then the second must
79        // be a keyword or length (not a side offset).
80        if let Ok(y_keyword) = input.try_parse(VerticalPositionKeyword::parse) {
81          let y = VerticalPosition::Side {
82            side: y_keyword,
83            offset: None,
84          };
85          return Ok(Position { x, y });
86        }
87        if let Ok(y_lp) = input.try_parse(LengthPercentage::parse) {
88          let y = VerticalPosition::Length(y_lp);
89          return Ok(Position { x, y });
90        }
91        let y = VerticalPosition::Center;
92        let _ = input.try_parse(|i| i.expect_ident_matching("center"));
93        return Ok(Position { x, y });
94      }
95      Ok(HorizontalPosition::Side {
96        side: x_keyword,
97        offset: lp,
98      }) => {
99        // If we got a horizontal side keyword (and optional offset), expect another for the vertical side.
100        // e.g. `left center` or `left 20px center`
101        if input.try_parse(|i| i.expect_ident_matching("center")).is_ok() {
102          let x = HorizontalPosition::Side {
103            side: x_keyword,
104            offset: lp,
105          };
106          let y = VerticalPosition::Center;
107          return Ok(Position { x, y });
108        }
109
110        // e.g. `left top`, `left top 20px`, `left 20px top`, or `left 20px top 20px`
111        if let Ok(y_keyword) = input.try_parse(VerticalPositionKeyword::parse) {
112          let y_lp = input.try_parse(LengthPercentage::parse).ok();
113          let x = HorizontalPosition::Side {
114            side: x_keyword,
115            offset: lp,
116          };
117          let y = VerticalPosition::Side {
118            side: y_keyword,
119            offset: y_lp,
120          };
121          return Ok(Position { x, y });
122        }
123
124        // If we didn't get a vertical side keyword (e.g. `left 20px`), then apply the offset to the vertical side.
125        let x = HorizontalPosition::Side {
126          side: x_keyword,
127          offset: None,
128        };
129        let y = lp.map_or(VerticalPosition::Center, VerticalPosition::Length);
130        return Ok(Position { x, y });
131      }
132      _ => {}
133    }
134
135    // If the horizontal position didn't parse, then it must be out of order. Try vertical position keyword.
136    let y_keyword = VerticalPositionKeyword::parse(input)?;
137    let lp_and_x_pos: Result<_, ParseError<()>> = input.try_parse(|i| {
138      let y_lp = i.try_parse(LengthPercentage::parse).ok();
139      if let Ok(x_keyword) = i.try_parse(HorizontalPositionKeyword::parse) {
140        let x_lp = i.try_parse(LengthPercentage::parse).ok();
141        let x_pos = HorizontalPosition::Side {
142          side: x_keyword,
143          offset: x_lp,
144        };
145        return Ok((y_lp, x_pos));
146      }
147      i.expect_ident_matching("center")?;
148      let x_pos = HorizontalPosition::Center;
149      Ok((y_lp, x_pos))
150    });
151
152    if let Ok((y_lp, x)) = lp_and_x_pos {
153      let y = VerticalPosition::Side {
154        side: y_keyword,
155        offset: y_lp,
156      };
157      return Ok(Position { x, y });
158    }
159
160    let x = HorizontalPosition::Center;
161    let y = VerticalPosition::Side {
162      side: y_keyword,
163      offset: None,
164    };
165    Ok(Position { x, y })
166  }
167}
168
169impl ToCss for Position {
170  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
171    match (&self.x, &self.y) {
172      (x_pos @ &HorizontalPosition::Side { side, offset: Some(_) }, &VerticalPosition::Length(ref y_lp))
173        if side != HorizontalPositionKeyword::Left =>
174      {
175        x_pos.to_css(dest)?;
176        dest.write_str(" top ")?;
177        y_lp.to_css(dest)
178      }
179      (x_pos @ &HorizontalPosition::Side { side, offset: Some(_) }, y)
180        if side != HorizontalPositionKeyword::Left && y.is_center() =>
181      {
182        // If there is a side keyword with an offset, "center" must be a keyword not a percentage.
183        x_pos.to_css(dest)?;
184        dest.write_str(" center")?;
185        Ok(())
186      }
187      (&HorizontalPosition::Length(ref x_lp), y_pos @ &VerticalPosition::Side { side, offset: Some(_) })
188        if side != VerticalPositionKeyword::Top =>
189      {
190        dest.write_str("left ")?;
191        x_lp.to_css(dest)?;
192        dest.write_str(" ")?;
193        y_pos.to_css(dest)
194      }
195      (x, y) if x.is_center() && y.is_center() => {
196        // `center center` => 50%
197        x.to_css(dest)
198      }
199      (&HorizontalPosition::Length(ref x_lp), y) if y.is_center() => {
200        // `center` is assumed if omitted.
201        x_lp.to_css(dest)
202      }
203      (
204        &HorizontalPosition::Side {
205          side: HorizontalPositionKeyword::Left,
206          offset: Some(ref x_lp),
207        },
208        y,
209      ) if y.is_center() => {
210        // `left 10px center` => `10px` (omit Y when center)
211        x_lp.to_css(dest)
212      }
213      (&HorizontalPosition::Side { side, offset: None }, y) if y.is_center() => {
214        let p: LengthPercentage = side.into();
215        p.to_css(dest)
216      }
217      (x, y_pos @ &VerticalPosition::Side { offset: None, .. }) if x.is_center() => y_pos.to_css(dest),
218      (
219        &HorizontalPosition::Center,
220        y_pos @ &VerticalPosition::Side {
221          side: VerticalPositionKeyword::Bottom,
222          offset: Some(_),
223        },
224      ) => {
225        // `center bottom 10px` must keep the keyword form
226        dest.write_str("center ")?;
227        y_pos.to_css(dest)
228      }
229      (&HorizontalPosition::Side { side: x, offset: None }, &VerticalPosition::Side { side: y, offset: None }) => {
230        let x: LengthPercentage = x.into();
231        let y: LengthPercentage = y.into();
232        x.to_css(dest)?;
233        dest.write_str(" ")?;
234        y.to_css(dest)
235      }
236      (x_pos, y_pos) => {
237        let zero = LengthPercentage::zero();
238        let fifty = LengthPercentage::Percentage(Percentage(0.5));
239        let x_len = match &x_pos {
240          HorizontalPosition::Side {
241            side: HorizontalPositionKeyword::Left,
242            offset,
243          } => {
244            if let Some(len) = offset {
245              if len.is_zero() {
246                Some(&zero)
247              } else {
248                Some(len)
249              }
250            } else {
251              Some(&zero)
252            }
253          }
254          HorizontalPosition::Length(len) if len.is_zero() => Some(&zero),
255          HorizontalPosition::Length(len) => Some(len),
256          HorizontalPosition::Center => Some(&fifty),
257          _ => None,
258        };
259
260        let y_len = match &y_pos {
261          VerticalPosition::Side {
262            side: VerticalPositionKeyword::Top,
263            offset,
264          } => {
265            if let Some(len) = offset {
266              if len.is_zero() {
267                Some(&zero)
268              } else {
269                Some(len)
270              }
271            } else {
272              Some(&zero)
273            }
274          }
275          VerticalPosition::Length(len) if len.is_zero() => Some(&zero),
276          VerticalPosition::Length(len) => Some(len),
277          VerticalPosition::Center => Some(&fifty),
278          _ => None,
279        };
280
281        if let (Some(x), Some(y)) = (x_len, y_len) {
282          x.to_css(dest)?;
283          dest.write_str(" ")?;
284          y.to_css(dest)
285        } else {
286          x_pos.to_css(dest)?;
287          dest.write_str(" ")?;
288          y_pos.to_css(dest)
289        }
290      }
291    }
292  }
293}
294
295impl IsCompatible for Position {
296  fn is_compatible(&self, _browsers: Browsers) -> bool {
297    true
298  }
299}
300
301/// A component within a [Position](Position) value, representing a position
302/// along either the horizontal or vertical axis of a box.
303///
304/// This type is generic over side keywords.
305#[derive(Debug, Clone, PartialEq)]
306#[cfg_attr(feature = "visitor", derive(Visit))]
307#[cfg_attr(
308  feature = "serde",
309  derive(serde::Serialize, serde::Deserialize),
310  serde(tag = "type", rename_all = "kebab-case")
311)]
312#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
313#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
314pub enum PositionComponent<S> {
315  /// The `center` keyword.
316  Center,
317  /// A length or percentage from the top-left corner of the box.
318  #[cfg_attr(feature = "serde", serde(with = "ValueWrapper::<LengthPercentage>"))]
319  Length(LengthPercentage),
320  /// A side keyword with an optional offset.
321  Side {
322    /// A side keyword.
323    side: S,
324    /// Offset from the side.
325    offset: Option<LengthPercentage>,
326  },
327}
328
329impl<S> PositionComponent<S> {
330  fn is_center(&self) -> bool {
331    match self {
332      PositionComponent::Center => true,
333      PositionComponent::Length(LengthPercentage::Percentage(Percentage(p))) => *p == 0.5,
334      _ => false,
335    }
336  }
337
338  fn is_zero(&self) -> bool {
339    matches!(self, PositionComponent::Length(len) if len.is_zero())
340  }
341}
342
343impl<'i, S: Parse<'i>> Parse<'i> for PositionComponent<S> {
344  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
345    if input.try_parse(|i| i.expect_ident_matching("center")).is_ok() {
346      return Ok(PositionComponent::Center);
347    }
348
349    if let Ok(lp) = input.try_parse(|input| LengthPercentage::parse(input)) {
350      return Ok(PositionComponent::Length(lp));
351    }
352
353    let side = S::parse(input)?;
354    let offset = input.try_parse(|input| LengthPercentage::parse(input)).ok();
355    Ok(PositionComponent::Side { side, offset })
356  }
357}
358
359impl<S: ToCss> ToCss for PositionComponent<S> {
360  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
361    use PositionComponent::*;
362    match &self {
363      Center => {
364        if dest.options().minify {
365          dest.write_str("50%")?;
366          Ok(())
367        } else {
368          dest.write_str("center")?;
369          Ok(())
370        }
371      }
372      Length(lp) => lp.to_css(dest),
373      Side { side, offset } => {
374        side.to_css(dest)?;
375        if let Some(lp) = offset {
376          dest.write_str(" ")?;
377          lp.to_css(dest)?;
378        }
379        Ok(())
380      }
381    }
382  }
383}
384
385enum_property! {
386  /// A horizontal position keyword.
387  pub enum HorizontalPositionKeyword {
388    /// The `left` keyword.
389    Left,
390    /// The `right` keyword.
391    Right,
392  }
393}
394
395impl Into<LengthPercentage> for HorizontalPositionKeyword {
396  fn into(self) -> LengthPercentage {
397    match self {
398      HorizontalPositionKeyword::Left => LengthPercentage::zero(),
399      HorizontalPositionKeyword::Right => LengthPercentage::Percentage(Percentage(1.0)),
400    }
401  }
402}
403
404enum_property! {
405  /// A vertical position keyword.
406  pub enum VerticalPositionKeyword {
407    /// The `top` keyword.
408    Top,
409    /// The `bottom` keyword.
410    Bottom,
411  }
412}
413
414impl Into<LengthPercentage> for VerticalPositionKeyword {
415  fn into(self) -> LengthPercentage {
416    match self {
417      VerticalPositionKeyword::Top => LengthPercentage::zero(),
418      VerticalPositionKeyword::Bottom => LengthPercentage::Percentage(Percentage(1.0)),
419    }
420  }
421}
422
423/// A horizontal position component.
424pub type HorizontalPosition = PositionComponent<HorizontalPositionKeyword>;
425
426/// A vertical position component.
427pub type VerticalPosition = PositionComponent<VerticalPositionKeyword>;