Skip to main content

rspack_lightningcss/properties/
position.rs

1//! CSS properties related to positioning.
2
3use super::Property;
4use crate::context::PropertyHandlerContext;
5use crate::declaration::DeclarationList;
6use crate::error::{ParserError, PrinterError};
7use crate::prefixes::Feature;
8use crate::traits::{Parse, PropertyHandler, ToCss};
9use crate::values::number::CSSInteger;
10use crate::vendor_prefix::VendorPrefix;
11#[cfg(feature = "visitor")]
12use crate::visitor::Visit;
13use cssparser::*;
14
15/// A value for the [position](https://www.w3.org/TR/css-position-3/#position-property) property.
16#[derive(Debug, Clone, PartialEq)]
17#[cfg_attr(feature = "visitor", derive(Visit))]
18#[cfg_attr(
19  feature = "serde",
20  derive(serde::Serialize, serde::Deserialize),
21  serde(tag = "type", content = "value", rename_all = "kebab-case")
22)]
23#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
24#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
25pub enum Position {
26  /// The box is laid in the document flow.
27  Static,
28  /// The box is laid out in the document flow and offset from the resulting position.
29  Relative,
30  /// The box is taken out of document flow and positioned in reference to its relative ancestor.
31  Absolute,
32  /// Similar to relative but adjusted according to the ancestor scrollable element.
33  Sticky(VendorPrefix),
34  /// The box is taken out of the document flow and positioned in reference to the page viewport.
35  Fixed,
36}
37
38impl<'i> Parse<'i> for Position {
39  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
40    let location = input.current_source_location();
41    let ident = input.expect_ident()?;
42    match_ignore_ascii_case! { &*ident,
43      "static" => Ok(Position::Static),
44      "relative" => Ok(Position::Relative),
45      "absolute" => Ok(Position::Absolute),
46      "fixed" => Ok(Position::Fixed),
47      "sticky" => Ok(Position::Sticky(VendorPrefix::None)),
48      "-webkit-sticky" => Ok(Position::Sticky(VendorPrefix::WebKit)),
49      _ => Err(location.new_unexpected_token_error(
50        cssparser::Token::Ident(ident.clone())
51      ))
52    }
53  }
54}
55
56impl ToCss for Position {
57  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
58    match self {
59      Position::Static => {
60        dest.write_str("static")?;
61        Ok(())
62      }
63      Position::Relative => {
64        dest.write_str("relative")?;
65        Ok(())
66      }
67      Position::Absolute => {
68        dest.write_str("absolute")?;
69        Ok(())
70      }
71      Position::Fixed => {
72        dest.write_str("fixed")?;
73        Ok(())
74      }
75      Position::Sticky(prefix) => {
76        prefix.to_css(dest)?;
77        dest.write_str("sticky")?;
78        Ok(())
79      }
80    }
81  }
82}
83
84/// A value for the [z-index](https://drafts.csswg.org/css2/#z-index) property.
85#[derive(Debug, Clone, PartialEq, Parse, ToCss)]
86#[cfg_attr(feature = "visitor", derive(Visit))]
87#[cfg_attr(
88  feature = "serde",
89  derive(serde::Serialize, serde::Deserialize),
90  serde(tag = "type", content = "value", rename_all = "kebab-case")
91)]
92#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
93#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
94pub enum ZIndex {
95  /// The `auto` keyword.
96  Auto,
97  /// An integer value.
98  Integer(CSSInteger),
99}
100
101#[derive(Default)]
102pub(crate) struct PositionHandler {
103  position: Option<Position>,
104}
105
106impl<'i> PropertyHandler<'i> for PositionHandler {
107  fn handle_property(
108    &mut self,
109    property: &Property<'i>,
110    _: &mut DeclarationList<'i>,
111    _: &mut PropertyHandlerContext<'i, '_>,
112  ) -> bool {
113    if let Property::Position(position) = property {
114      if let (Some(Position::Sticky(cur)), Position::Sticky(new)) = (&mut self.position, position) {
115        *cur |= *new;
116      } else {
117        self.position = Some(position.clone());
118      }
119
120      return true;
121    }
122
123    false
124  }
125
126  fn finalize(&mut self, dest: &mut DeclarationList, context: &mut PropertyHandlerContext<'i, '_>) {
127    if self.position.is_none() {
128      return;
129    }
130
131    if let Some(position) = std::mem::take(&mut self.position) {
132      match position {
133        Position::Sticky(mut prefix) => {
134          prefix = context.targets.prefixes(prefix, Feature::Sticky);
135          if prefix.contains(VendorPrefix::WebKit) {
136            dest.push(Property::Position(Position::Sticky(VendorPrefix::WebKit)))
137          }
138
139          if prefix.contains(VendorPrefix::None) {
140            dest.push(Property::Position(Position::Sticky(VendorPrefix::None)))
141          }
142        }
143        _ => dest.push(Property::Position(position)),
144      }
145    }
146  }
147}