Skip to main content

rspack_lightningcss/properties/
ui.rs

1//! CSS properties related to user interface.
2
3use crate::context::PropertyHandlerContext;
4use crate::declaration::{DeclarationBlock, DeclarationList};
5use crate::error::{ParserError, PrinterError};
6use crate::macros::{define_shorthand, enum_property, shorthand_property};
7use crate::properties::{Property, PropertyId};
8use crate::targets::{should_compile, Browsers, Targets};
9use crate::traits::{FallbackValues, IsCompatible, Parse, PropertyHandler, Shorthand, ToCss};
10use crate::values::color::CssColor;
11use crate::values::number::CSSNumber;
12use crate::values::string::CowArcStr;
13use crate::values::url::Url;
14#[cfg(feature = "visitor")]
15use crate::visitor::Visit;
16use bitflags::bitflags;
17use cssparser::*;
18use smallvec::SmallVec;
19
20use super::custom::Token;
21use super::{CustomProperty, CustomPropertyName, TokenList, TokenOrValue};
22
23enum_property! {
24  /// A value for the [resize](https://www.w3.org/TR/2021/WD-css-ui-4-20210316/#resize) property.
25  pub enum Resize {
26    /// The element does not allow resizing.
27    None,
28    /// The element is resizable in both the x and y directions.
29    Both,
30    /// The element is resizable in the x direction.
31    Horizontal,
32    /// The element is resizable in the y direction.
33    Vertical,
34    /// The element is resizable in the block direction, according to the writing mode.
35    Block,
36    /// The element is resizable in the inline direction, according to the writing mode.
37    Inline,
38  }
39}
40
41/// A [cursor image](https://www.w3.org/TR/2021/WD-css-ui-4-20210316/#cursor) value, used in the `cursor` property.
42///
43/// See [Cursor](Cursor).
44#[derive(Debug, Clone, PartialEq)]
45#[cfg_attr(feature = "visitor", derive(Visit))]
46#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
47#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
48#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
49pub struct CursorImage<'i> {
50  /// A url to the cursor image.
51  #[cfg_attr(feature = "serde", serde(borrow))]
52  pub url: Url<'i>,
53  /// The location in the image where the mouse pointer appears.
54  pub hotspot: Option<(CSSNumber, CSSNumber)>,
55}
56
57impl<'i> Parse<'i> for CursorImage<'i> {
58  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
59    let url = Url::parse(input)?;
60    let hotspot = if let Ok(x) = input.try_parse(CSSNumber::parse) {
61      let y = CSSNumber::parse(input)?;
62      Some((x, y))
63    } else {
64      None
65    };
66
67    Ok(CursorImage { url, hotspot })
68  }
69}
70
71impl<'i> ToCss for CursorImage<'i> {
72  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
73    self.url.to_css(dest)?;
74
75    if let Some((x, y)) = self.hotspot {
76      dest.write_char(' ')?;
77      x.to_css(dest)?;
78      dest.write_char(' ')?;
79      y.to_css(dest)?;
80    }
81    Ok(())
82  }
83}
84
85enum_property! {
86  /// A pre-defined [cursor](https://www.w3.org/TR/2021/WD-css-ui-4-20210316/#cursor) value,
87  /// used in the `cursor` property.
88  ///
89  /// See [Cursor](Cursor).
90  #[allow(missing_docs)]
91  pub enum CursorKeyword {
92    Auto,
93    Default,
94    None,
95    ContextMenu,
96    Help,
97    Pointer,
98    Progress,
99    Wait,
100    Cell,
101    Crosshair,
102    Text,
103    VerticalText,
104    Alias,
105    Copy,
106    Move,
107    NoDrop,
108    NotAllowed,
109    Grab,
110    Grabbing,
111    EResize,
112    NResize,
113    NeResize,
114    NwResize,
115    SResize,
116    SeResize,
117    SwResize,
118    WResize,
119    EwResize,
120    NsResize,
121    NeswResize,
122    NwseResize,
123    ColResize,
124    RowResize,
125    AllScroll,
126    ZoomIn,
127    ZoomOut,
128  }
129}
130
131/// A value for the [cursor](https://www.w3.org/TR/2021/WD-css-ui-4-20210316/#cursor) property.
132#[derive(Debug, Clone, PartialEq)]
133#[cfg_attr(feature = "visitor", derive(Visit))]
134#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
135#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
136#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
137pub struct Cursor<'i> {
138  /// A list of cursor images.
139  #[cfg_attr(feature = "serde", serde(borrow))]
140  pub images: SmallVec<[CursorImage<'i>; 1]>,
141  /// A pre-defined cursor.
142  pub keyword: CursorKeyword,
143}
144
145impl<'i> Parse<'i> for Cursor<'i> {
146  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
147    let mut images = SmallVec::new();
148    loop {
149      match input.try_parse(CursorImage::parse) {
150        Ok(image) => images.push(image),
151        Err(_) => break,
152      }
153      input.expect_comma()?;
154    }
155
156    Ok(Cursor {
157      images,
158      keyword: CursorKeyword::parse(input)?,
159    })
160  }
161}
162
163impl<'i> ToCss for Cursor<'i> {
164  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
165    for image in &self.images {
166      image.to_css(dest)?;
167      dest.delim(',', false)?;
168    }
169    self.keyword.to_css(dest)
170  }
171}
172
173/// A value for the [caret-color](https://www.w3.org/TR/2021/WD-css-ui-4-20210316/#caret-color) property.
174#[derive(Debug, Clone, PartialEq, Parse, ToCss)]
175#[cfg_attr(feature = "visitor", derive(Visit))]
176#[cfg_attr(
177  feature = "serde",
178  derive(serde::Serialize, serde::Deserialize),
179  serde(tag = "type", content = "value", rename_all = "kebab-case")
180)]
181#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
182#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
183pub enum ColorOrAuto {
184  /// The `currentColor`, adjusted by the UA to ensure contrast against the background.
185  Auto,
186  /// A color.
187  Color(CssColor),
188}
189
190impl Default for ColorOrAuto {
191  fn default() -> ColorOrAuto {
192    ColorOrAuto::Auto
193  }
194}
195
196impl FallbackValues for ColorOrAuto {
197  fn get_fallbacks(&mut self, targets: Targets) -> Vec<Self> {
198    match self {
199      ColorOrAuto::Color(color) => color
200        .get_fallbacks(targets)
201        .into_iter()
202        .map(|color| ColorOrAuto::Color(color))
203        .collect(),
204      ColorOrAuto::Auto => Vec::new(),
205    }
206  }
207}
208
209impl IsCompatible for ColorOrAuto {
210  fn is_compatible(&self, browsers: Browsers) -> bool {
211    match self {
212      ColorOrAuto::Color(color) => color.is_compatible(browsers),
213      ColorOrAuto::Auto => true,
214    }
215  }
216}
217
218enum_property! {
219  /// A value for the [caret-shape](https://www.w3.org/TR/2021/WD-css-ui-4-20210316/#caret-shape) property.
220  pub enum CaretShape {
221    /// The UA determines the caret shape.
222    Auto,
223    /// A thin bar caret.
224    Bar,
225    /// A rectangle caret.
226    Block,
227    /// An underscore caret.
228    Underscore,
229  }
230}
231
232impl Default for CaretShape {
233  fn default() -> CaretShape {
234    CaretShape::Auto
235  }
236}
237
238shorthand_property! {
239  /// A value for the [caret](https://www.w3.org/TR/2021/WD-css-ui-4-20210316/#caret) shorthand property.
240  pub struct Caret {
241    /// The caret color.
242    color: CaretColor(ColorOrAuto),
243    /// The caret shape.
244    shape: CaretShape(CaretShape),
245  }
246}
247
248impl FallbackValues for Caret {
249  fn get_fallbacks(&mut self, targets: Targets) -> Vec<Self> {
250    self
251      .color
252      .get_fallbacks(targets)
253      .into_iter()
254      .map(|color| Caret {
255        color,
256        shape: self.shape.clone(),
257      })
258      .collect()
259  }
260}
261
262impl IsCompatible for Caret {
263  fn is_compatible(&self, browsers: Browsers) -> bool {
264    self.color.is_compatible(browsers)
265  }
266}
267
268enum_property! {
269  /// A value for the [user-select](https://www.w3.org/TR/2021/WD-css-ui-4-20210316/#content-selection) property.
270  pub enum UserSelect {
271    /// The UA determines whether text is selectable.
272    Auto,
273    /// Text is selectable.
274    Text,
275    /// Text is not selectable.
276    None,
277    /// Text selection is contained to the element.
278    Contain,
279    /// Only the entire element is selectable.
280    All,
281  }
282}
283
284/// A value for the [appearance](https://www.w3.org/TR/2021/WD-css-ui-4-20210316/#appearance-switching) property.
285#[derive(Debug, Clone, PartialEq)]
286#[cfg_attr(feature = "visitor", derive(Visit))]
287#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
288#[allow(missing_docs)]
289pub enum Appearance<'i> {
290  None,
291  Auto,
292  Textfield,
293  MenulistButton,
294  Button,
295  Checkbox,
296  Listbox,
297  Menulist,
298  Meter,
299  ProgressBar,
300  PushButton,
301  Radio,
302  Searchfield,
303  SliderHorizontal,
304  SquareButton,
305  Textarea,
306  NonStandard(CowArcStr<'i>),
307}
308
309impl<'i> Appearance<'i> {
310  fn from_str(name: &str) -> Option<Self> {
311    Some(match_ignore_ascii_case! { &name,
312      "none" => Appearance::None,
313      "auto" => Appearance::Auto,
314      "textfield" => Appearance::Textfield,
315      "menulist-button" => Appearance::MenulistButton,
316      "button" => Appearance::Button,
317      "checkbox" => Appearance::Checkbox,
318      "listbox" => Appearance::Listbox,
319      "menulist" => Appearance::Menulist,
320      "meter" => Appearance::Meter,
321      "progress-bar" => Appearance::ProgressBar,
322      "push-button" => Appearance::PushButton,
323      "radio" => Appearance::Radio,
324      "searchfield" => Appearance::Searchfield,
325      "slider-horizontal" => Appearance::SliderHorizontal,
326      "square-button" => Appearance::SquareButton,
327      "textarea" => Appearance::Textarea,
328      _ => return None
329    })
330  }
331
332  fn to_str(&self) -> &str {
333    match self {
334      Appearance::None => "none",
335      Appearance::Auto => "auto",
336      Appearance::Textfield => "textfield",
337      Appearance::MenulistButton => "menulist-button",
338      Appearance::Button => "button",
339      Appearance::Checkbox => "checkbox",
340      Appearance::Listbox => "listbox",
341      Appearance::Menulist => "menulist",
342      Appearance::Meter => "meter",
343      Appearance::ProgressBar => "progress-bar",
344      Appearance::PushButton => "push-button",
345      Appearance::Radio => "radio",
346      Appearance::Searchfield => "searchfield",
347      Appearance::SliderHorizontal => "slider-horizontal",
348      Appearance::SquareButton => "square-button",
349      Appearance::Textarea => "textarea",
350      Appearance::NonStandard(s) => s.as_ref(),
351    }
352  }
353}
354
355impl<'i> Parse<'i> for Appearance<'i> {
356  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
357    let ident = input.expect_ident()?;
358    Ok(Self::from_str(ident.as_ref()).unwrap_or_else(|| Appearance::NonStandard(ident.into())))
359  }
360}
361
362impl<'i> ToCss for Appearance<'i> {
363  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
364    dest.write_str(self.to_str())?;
365    Ok(())
366  }
367}
368
369#[cfg(feature = "serde")]
370#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
371impl<'i> serde::Serialize for Appearance<'i> {
372  fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
373  where
374    S: serde::Serializer,
375  {
376    serializer.serialize_str(self.to_str())
377  }
378}
379
380#[cfg(feature = "serde")]
381#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
382impl<'i, 'de: 'i> serde::Deserialize<'de> for Appearance<'i> {
383  fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
384  where
385    D: serde::Deserializer<'de>,
386  {
387    let s = CowArcStr::deserialize(deserializer)?;
388    Ok(Self::from_str(s.as_ref()).unwrap_or_else(|| Appearance::NonStandard(s)))
389  }
390}
391
392#[cfg(feature = "jsonschema")]
393#[cfg_attr(docsrs, doc(cfg(feature = "jsonschema")))]
394impl<'a> schemars::JsonSchema for Appearance<'a> {
395  fn is_referenceable() -> bool {
396    true
397  }
398
399  fn json_schema(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {
400    str::json_schema(gen)
401  }
402
403  fn schema_name() -> String {
404    "Appearance".into()
405  }
406}
407
408bitflags! {
409  /// A value for the [color-scheme](https://drafts.csswg.org/css-color-adjust/#color-scheme-prop) property.
410  #[cfg_attr(feature = "visitor", derive(Visit))]
411  #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize), serde(from = "SerializedColorScheme", into = "SerializedColorScheme"))]
412  #[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
413  #[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Clone, Copy)]
414  pub struct ColorScheme: u8 {
415    /// Indicates that the element supports a light color scheme.
416    const Light    = 0b01;
417    /// Indicates that the element supports a dark color scheme.
418    const Dark     = 0b10;
419    /// Forbids the user agent from overriding the color scheme for the element.
420    const Only     = 0b100;
421  }
422}
423
424impl<'i> Parse<'i> for ColorScheme {
425  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
426    let mut res = ColorScheme::empty();
427    let mut has_any = false;
428
429    if input.try_parse(|input| input.expect_ident_matching("normal")).is_ok() {
430      return Ok(res);
431    }
432
433    if input.try_parse(|input| input.expect_ident_matching("only")).is_ok() {
434      res |= ColorScheme::Only;
435      has_any = true;
436    }
437
438    loop {
439      if input.try_parse(|input| input.expect_ident_matching("light")).is_ok() {
440        res |= ColorScheme::Light;
441        has_any = true;
442        continue;
443      }
444
445      if input.try_parse(|input| input.expect_ident_matching("dark")).is_ok() {
446        res |= ColorScheme::Dark;
447        has_any = true;
448        continue;
449      }
450
451      break;
452    }
453
454    // Only is allowed at the start or the end.
455    if !res.contains(ColorScheme::Only) && input.try_parse(|input| input.expect_ident_matching("only")).is_ok() {
456      res |= ColorScheme::Only;
457      has_any = true;
458    }
459
460    if has_any {
461      return Ok(res);
462    }
463
464    Err(input.new_custom_error(ParserError::InvalidValue))
465  }
466}
467
468impl ToCss for ColorScheme {
469  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
470    if self.is_empty() {
471      dest.write_str("normal")?;
472      return Ok(());
473    }
474
475    if self.contains(ColorScheme::Light) {
476      dest.write_str("light")?;
477      if self.contains(ColorScheme::Dark) {
478        dest.write_char(' ')?;
479      }
480    }
481
482    if self.contains(ColorScheme::Dark) {
483      dest.write_str("dark")?;
484    }
485
486    if self.contains(ColorScheme::Only) {
487      // Avoid parsing `color-scheme: only` as `color-scheme:  only`
488      if !self.intersects(ColorScheme::Light | ColorScheme::Dark) {
489        dest.write_str("only")?;
490        return Ok(());
491      }
492      dest.write_str(" only")?;
493    }
494
495    Ok(())
496  }
497}
498
499#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
500#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
501struct SerializedColorScheme {
502  light: bool,
503  dark: bool,
504  only: bool,
505}
506
507impl From<ColorScheme> for SerializedColorScheme {
508  fn from(color_scheme: ColorScheme) -> Self {
509    Self {
510      light: color_scheme.contains(ColorScheme::Light),
511      dark: color_scheme.contains(ColorScheme::Dark),
512      only: color_scheme.contains(ColorScheme::Only),
513    }
514  }
515}
516
517impl From<SerializedColorScheme> for ColorScheme {
518  fn from(s: SerializedColorScheme) -> ColorScheme {
519    let mut color_scheme = ColorScheme::empty();
520    color_scheme.set(ColorScheme::Light, s.light);
521    color_scheme.set(ColorScheme::Dark, s.dark);
522    color_scheme.set(ColorScheme::Only, s.only);
523    color_scheme
524  }
525}
526
527#[cfg(feature = "jsonschema")]
528#[cfg_attr(docsrs, doc(cfg(feature = "jsonschema")))]
529impl<'a> schemars::JsonSchema for ColorScheme {
530  fn is_referenceable() -> bool {
531    true
532  }
533
534  fn json_schema(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {
535    SerializedColorScheme::json_schema(gen)
536  }
537
538  fn schema_name() -> String {
539    "ColorScheme".into()
540  }
541}
542
543#[derive(Default)]
544pub(crate) struct ColorSchemeHandler;
545
546impl<'i> PropertyHandler<'i> for ColorSchemeHandler {
547  fn handle_property(
548    &mut self,
549    property: &Property<'i>,
550    dest: &mut DeclarationList<'i>,
551    context: &mut PropertyHandlerContext<'i, '_>,
552  ) -> bool {
553    match property {
554      Property::ColorScheme(color_scheme) => {
555        if should_compile!(context.targets, LightDark) {
556          if color_scheme.contains(ColorScheme::Light) {
557            dest.push(define_var("--lightningcss-light", Token::Ident("initial".into())));
558            dest.push(define_var("--lightningcss-dark", Token::WhiteSpace(" ".into())));
559
560            if color_scheme.contains(ColorScheme::Dark) {
561              context.add_dark_rule(define_var("--lightningcss-light", Token::WhiteSpace(" ".into())));
562              context.add_dark_rule(define_var("--lightningcss-dark", Token::Ident("initial".into())));
563            }
564          } else if color_scheme.contains(ColorScheme::Dark) {
565            dest.push(define_var("--lightningcss-light", Token::WhiteSpace(" ".into())));
566            dest.push(define_var("--lightningcss-dark", Token::Ident("initial".into())));
567          }
568        }
569        dest.push(property.clone());
570        true
571      }
572      _ => false,
573    }
574  }
575
576  fn finalize(&mut self, _: &mut DeclarationList<'i>, _: &mut PropertyHandlerContext<'i, '_>) {}
577}
578
579enum_property! {
580  /// A value for the [print-color-adjust](https://drafts.csswg.org/css-color-adjust/#propdef-print-color-adjust) property.
581  pub enum PrintColorAdjust {
582    /// The user agent is allowed to make adjustments to the element as it deems appropriate.
583    Economy,
584    /// The user agent is not allowed to make adjustments to the element.
585    Exact,
586  }
587}
588
589#[inline]
590fn define_var<'i>(name: &'static str, value: Token<'static>) -> Property<'i> {
591  Property::Custom(CustomProperty {
592    name: CustomPropertyName::Custom(name.into()),
593    value: TokenList(vec![TokenOrValue::Token(value)]),
594  })
595}