Skip to main content

rspack_lightningcss/properties/
text.rs

1//! CSS properties related to text.
2
3#![allow(non_upper_case_globals)]
4
5use super::{Property, PropertyId};
6use crate::compat;
7use crate::context::PropertyHandlerContext;
8use crate::declaration::{DeclarationBlock, DeclarationList};
9use crate::error::{ParserError, PrinterError};
10use crate::macros::{define_shorthand, enum_property};
11use crate::prefixes::Feature;
12use crate::targets::{should_compile, Browsers, Targets};
13use crate::traits::{FallbackValues, IsCompatible, Parse, PropertyHandler, Shorthand, ToCss, Zero};
14use crate::values::calc::{Calc, MathFunction};
15use crate::values::color::{ColorFallbackKind, CssColor};
16use crate::values::length::{Length, LengthPercentage, LengthValue};
17use crate::values::number::NonNegative;
18use crate::values::percentage::Percentage;
19use crate::values::string::CSSString;
20use crate::vendor_prefix::VendorPrefix;
21#[cfg(feature = "visitor")]
22use crate::visitor::Visit;
23use bitflags::bitflags;
24use cssparser::*;
25use smallvec::SmallVec;
26
27enum_property! {
28  /// Defines how text case should be transformed in the
29  /// [text-transform](https://www.w3.org/TR/2021/CRD-css-text-3-20210422/#text-transform-property) property.
30  pub enum TextTransformCase {
31    /// Text should not be transformed.
32    None,
33    /// Text should be uppercased.
34    Uppercase,
35    /// Text should be lowercased.
36    Lowercase,
37    /// Each word should be capitalized.
38    Capitalize,
39  }
40}
41
42impl Default for TextTransformCase {
43  fn default() -> TextTransformCase {
44    TextTransformCase::None
45  }
46}
47
48bitflags! {
49  /// Defines how ideographic characters should be transformed in the
50  /// [text-transform](https://www.w3.org/TR/2021/CRD-css-text-3-20210422/#text-transform-property) property.
51  ///
52  /// All combinations of flags is supported.
53  #[cfg_attr(feature = "visitor", derive(Visit))]
54  #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize), serde(from = "SerializedTextTransformOther", into = "SerializedTextTransformOther"))]
55  #[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Clone, Copy)]
56  pub struct TextTransformOther: u8 {
57    /// Puts all typographic character units in full-width form.
58    const FullWidth    = 0b00000001;
59    /// Converts all small Kana characters to the equivalent full-size Kana.
60    const FullSizeKana = 0b00000010;
61  }
62}
63
64impl<'i> Parse<'i> for TextTransformOther {
65  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
66    let location = input.current_source_location();
67    let ident = input.expect_ident()?;
68    match_ignore_ascii_case! { &ident,
69      "full-width" => Ok(TextTransformOther::FullWidth),
70      "full-size-kana" => Ok(TextTransformOther::FullSizeKana),
71      _ => Err(location.new_unexpected_token_error(
72        cssparser::Token::Ident(ident.clone())
73      ))
74    }
75  }
76}
77
78impl ToCss for TextTransformOther {
79  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
80    let mut needs_space = false;
81    if self.contains(TextTransformOther::FullWidth) {
82      dest.write_str("full-width")?;
83      needs_space = true;
84    }
85
86    if self.contains(TextTransformOther::FullSizeKana) {
87      if needs_space {
88        dest.write_char(' ')?;
89      }
90      dest.write_str("full-size-kana")?;
91    }
92
93    Ok(())
94  }
95}
96
97#[cfg_attr(
98  feature = "serde",
99  derive(serde::Serialize, serde::Deserialize),
100  serde(rename_all = "camelCase")
101)]
102#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
103#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
104struct SerializedTextTransformOther {
105  /// Puts all typographic character units in full-width form.
106  full_width: bool,
107  /// Converts all small Kana characters to the equivalent full-size Kana.
108  full_size_kana: bool,
109}
110
111impl From<TextTransformOther> for SerializedTextTransformOther {
112  fn from(t: TextTransformOther) -> Self {
113    Self {
114      full_width: t.contains(TextTransformOther::FullWidth),
115      full_size_kana: t.contains(TextTransformOther::FullSizeKana),
116    }
117  }
118}
119
120impl From<SerializedTextTransformOther> for TextTransformOther {
121  fn from(t: SerializedTextTransformOther) -> Self {
122    let mut res = TextTransformOther::empty();
123    if t.full_width {
124      res |= TextTransformOther::FullWidth;
125    }
126    if t.full_size_kana {
127      res |= TextTransformOther::FullSizeKana;
128    }
129    res
130  }
131}
132
133#[cfg(feature = "jsonschema")]
134#[cfg_attr(docsrs, doc(cfg(feature = "jsonschema")))]
135impl<'a> schemars::JsonSchema for TextTransformOther {
136  fn is_referenceable() -> bool {
137    true
138  }
139
140  fn json_schema(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {
141    SerializedTextTransformOther::json_schema(gen)
142  }
143
144  fn schema_name() -> String {
145    "TextTransformOther".into()
146  }
147}
148
149/// A value for the [text-transform](https://www.w3.org/TR/2021/CRD-css-text-3-20210422/#text-transform-property) property.
150#[derive(Debug, Clone, PartialEq)]
151#[cfg_attr(feature = "visitor", derive(Visit))]
152#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
153#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
154#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
155pub struct TextTransform {
156  /// How case should be transformed.
157  pub case: TextTransformCase,
158  /// How ideographic characters should be transformed.
159  #[cfg_attr(feature = "serde", serde(flatten))]
160  pub other: TextTransformOther,
161}
162
163impl<'i> Parse<'i> for TextTransform {
164  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
165    let mut case = None;
166    let mut other = TextTransformOther::empty();
167
168    loop {
169      if case.is_none() {
170        if let Ok(c) = input.try_parse(TextTransformCase::parse) {
171          case = Some(c);
172          if c == TextTransformCase::None {
173            other = TextTransformOther::empty();
174            break;
175          }
176          continue;
177        }
178      }
179
180      if let Ok(o) = input.try_parse(TextTransformOther::parse) {
181        other |= o;
182        continue;
183      }
184
185      break;
186    }
187
188    Ok(TextTransform {
189      case: case.unwrap_or_default(),
190      other,
191    })
192  }
193}
194
195impl ToCss for TextTransform {
196  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
197    let mut needs_space = false;
198    if self.case != TextTransformCase::None || self.other.is_empty() {
199      self.case.to_css(dest)?;
200      needs_space = true;
201    }
202
203    if !self.other.is_empty() {
204      if needs_space {
205        dest.write_char(' ')?;
206      }
207      self.other.to_css(dest)?;
208    }
209    Ok(())
210  }
211}
212
213enum_property! {
214  /// A value for the [white-space](https://www.w3.org/TR/2021/CRD-css-text-3-20210422/#white-space-property) property.
215  pub enum WhiteSpace {
216    /// Sequences of white space are collapsed into a single character.
217    "normal": Normal,
218    /// White space is not collapsed.
219    "pre": Pre,
220    /// White space is collapsed, but no line wrapping occurs.
221    "nowrap": NoWrap,
222    /// White space is preserved, but line wrapping occurs.
223    "pre-wrap": PreWrap,
224    /// Like pre-wrap, but with different line breaking rules.
225    "break-spaces": BreakSpaces,
226    /// White space is collapsed, but with different line breaking rules.
227    "pre-line": PreLine,
228  }
229}
230
231enum_property! {
232  /// A value for the [word-break](https://www.w3.org/TR/2021/CRD-css-text-3-20210422/#word-break-property) property.
233  pub enum WordBreak {
234    /// Words break according to their customary rules.
235    Normal,
236    /// Breaking is forbidden within “words”.
237    KeepAll,
238    /// Breaking is allowed within “words”.
239    BreakAll,
240    /// Breaking is allowed if there is no otherwise acceptable break points in a line.
241    BreakWord,
242  }
243}
244
245enum_property! {
246  /// A value for the [line-break](https://www.w3.org/TR/2021/CRD-css-text-3-20210422/#line-break-property) property.
247  pub enum LineBreak {
248    /// The UA determines the set of line-breaking restrictions to use.
249    Auto,
250    /// Breaks text using the least restrictive set of line-breaking rules.
251    Loose,
252    /// Breaks text using the most common set of line-breaking rules.
253    Normal,
254    /// Breaks text using the most stringent set of line-breaking rules.
255    Strict,
256    /// There is a soft wrap opportunity around every typographic character unit.
257    Anywhere,
258  }
259}
260enum_property! {
261  /// A value for the [hyphens](https://www.w3.org/TR/2021/CRD-css-text-3-20210422/#hyphenation) property.
262  pub enum Hyphens {
263    /// Words are not hyphenated.
264    None,
265    /// Words are only hyphenated where there are characters inside the word that explicitly suggest hyphenation opportunities.
266    Manual,
267    /// Words may be broken at hyphenation opportunities determined automatically by the UA.
268    Auto,
269  }
270}
271
272enum_property! {
273  /// A value for the [overflow-wrap](https://www.w3.org/TR/2021/CRD-css-text-3-20210422/#overflow-wrap-property) property.
274  pub enum OverflowWrap {
275    /// Lines may break only at allowed break points.
276    Normal,
277    /// Breaking is allowed if there is no otherwise acceptable break points in a line.
278    Anywhere,
279    /// As for anywhere except that soft wrap opportunities introduced by break-word are
280    /// not considered when calculating min-content intrinsic sizes.
281    BreakWord,
282  }
283}
284
285enum_property! {
286  /// A value for the [text-align](https://www.w3.org/TR/2021/CRD-css-text-3-20210422/#text-align-property) property.
287  pub enum TextAlign {
288    /// Inline-level content is aligned to the start edge of the line box.
289    Start,
290    /// Inline-level content is aligned to the end edge of the line box.
291    End,
292    /// Inline-level content is aligned to the line-left edge of the line box.
293    Left,
294    /// Inline-level content is aligned to the line-right edge of the line box.
295    Right,
296    /// Inline-level content is centered within the line box.
297    Center,
298    /// Text is justified according to the method specified by the text-justify property.
299    Justify,
300    /// Matches the parent element.
301    MatchParent,
302    /// Same as justify, but also justifies the last line.
303    JustifyAll,
304  }
305}
306
307enum_property! {
308  /// A value for the [text-align-last](https://www.w3.org/TR/2021/CRD-css-text-3-20210422/#text-align-last-property) property.
309  pub enum TextAlignLast {
310    /// Content on the affected line is aligned per `text-align-all` unless set to `justify`, in which case it is start-aligned.
311    Auto,
312    /// Inline-level content is aligned to the start edge of the line box.
313    Start,
314    /// Inline-level content is aligned to the end edge of the line box.
315    End,
316    /// Inline-level content is aligned to the line-left edge of the line box.
317    Left,
318    /// Inline-level content is aligned to the line-right edge of the line box.
319    Right,
320    /// Inline-level content is centered within the line box.
321    Center,
322    /// Text is justified according to the method specified by the text-justify property.
323    Justify,
324    /// Matches the parent element.
325    MatchParent,
326  }
327}
328
329enum_property! {
330  /// A value for the [text-justify](https://www.w3.org/TR/2021/CRD-css-text-3-20210422/#text-justify-property) property.
331  pub enum TextJustify {
332    /// The UA determines the justification algorithm to follow.
333    Auto,
334    /// Justification is disabled.
335    None,
336    /// Justification adjusts spacing at word separators only.
337    InterWord,
338    /// Justification adjusts spacing between each character.
339    InterCharacter,
340  }
341}
342
343/// A value for the [word-spacing](https://www.w3.org/TR/2021/CRD-css-text-3-20210422/#word-spacing-property)
344/// and [letter-spacing](https://www.w3.org/TR/2021/CRD-css-text-3-20210422/#letter-spacing-property) properties.
345#[derive(Debug, Clone, PartialEq, Parse, ToCss)]
346#[cfg_attr(feature = "visitor", derive(Visit))]
347#[cfg_attr(
348  feature = "serde",
349  derive(serde::Serialize, serde::Deserialize),
350  serde(tag = "type", content = "value", rename_all = "kebab-case")
351)]
352#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
353#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
354pub enum Spacing {
355  /// No additional spacing is applied.
356  Normal,
357  /// Additional spacing between each word or letter.
358  Length(Length),
359}
360
361/// A value for the [text-indent](https://www.w3.org/TR/2021/CRD-css-text-3-20210422/#text-indent-property) property.
362#[derive(Debug, Clone, PartialEq)]
363#[cfg_attr(feature = "visitor", derive(Visit))]
364#[cfg_attr(
365  feature = "serde",
366  derive(serde::Serialize, serde::Deserialize),
367  serde(rename_all = "camelCase")
368)]
369#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
370#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
371pub struct TextIndent {
372  /// The amount to indent.
373  pub value: LengthPercentage,
374  /// Inverts which lines are affected.
375  pub hanging: bool,
376  /// Affects the first line after each hard break.
377  pub each_line: bool,
378}
379
380impl<'i> Parse<'i> for TextIndent {
381  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
382    let mut value = None;
383    let mut hanging = false;
384    let mut each_line = false;
385
386    loop {
387      if value.is_none() {
388        if let Ok(val) = input.try_parse(LengthPercentage::parse) {
389          value = Some(val);
390          continue;
391        }
392      }
393
394      if !hanging {
395        if input.try_parse(|input| input.expect_ident_matching("hanging")).is_ok() {
396          hanging = true;
397          continue;
398        }
399      }
400
401      if !each_line {
402        if input.try_parse(|input| input.expect_ident_matching("each-line")).is_ok() {
403          each_line = true;
404          continue;
405        }
406      }
407
408      break;
409    }
410
411    if let Some(value) = value {
412      Ok(TextIndent {
413        value,
414        hanging,
415        each_line,
416      })
417    } else {
418      Err(input.new_custom_error(ParserError::InvalidDeclaration))
419    }
420  }
421}
422
423impl ToCss for TextIndent {
424  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
425    self.value.to_css(dest)?;
426    if self.hanging {
427      dest.write_str(" hanging")?;
428    }
429    if self.each_line {
430      dest.write_str(" each-line")?;
431    }
432    Ok(())
433  }
434}
435
436/// A value for the [text-size-adjust](https://w3c.github.io/csswg-drafts/css-size-adjust/#adjustment-control) property.
437#[derive(Debug, Clone, PartialEq, Parse, ToCss)]
438#[cfg_attr(feature = "visitor", derive(Visit))]
439#[cfg_attr(
440  feature = "serde",
441  derive(serde::Serialize, serde::Deserialize),
442  serde(tag = "type", content = "value", rename_all = "kebab-case")
443)]
444#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
445#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
446pub enum TextSizeAdjust {
447  /// Use the default size adjustment when displaying on a small device.
448  Auto,
449  /// No size adjustment when displaying on a small device.
450  None,
451  /// When displaying on a small device, the font size is multiplied by this percentage.
452  Percentage(NonNegative<Percentage>),
453}
454
455bitflags! {
456  /// A value for the [text-decoration-line](https://www.w3.org/TR/2020/WD-css-text-decor-4-20200506/#text-decoration-line-property) property.
457  ///
458  /// Multiple lines may be specified by combining the flags.
459  #[cfg_attr(feature = "visitor", derive(Visit))]
460  #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize), serde(from = "SerializedTextDecorationLine", into = "SerializedTextDecorationLine"))]
461  #[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
462  #[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Clone, Copy)]
463  pub struct TextDecorationLine: u8 {
464    /// Each line of text is underlined.
465    const Underline     = 0b00000001;
466    /// Each line of text has a line over it.
467    const Overline      = 0b00000010;
468    /// Each line of text has a line through the middle.
469    const LineThrough   = 0b00000100;
470    /// The text blinks.
471    const Blink         = 0b00001000;
472    /// The text is decorated as a spelling error.
473    const SpellingError = 0b00010000;
474    /// The text is decorated as a grammar error.
475    const GrammarError  = 0b00100000;
476  }
477}
478
479impl Default for TextDecorationLine {
480  fn default() -> TextDecorationLine {
481    TextDecorationLine::empty()
482  }
483}
484
485impl<'i> Parse<'i> for TextDecorationLine {
486  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
487    let mut value = TextDecorationLine::empty();
488    let mut any = false;
489
490    loop {
491      let flag: Result<_, ParseError<'i, ParserError<'i>>> = input.try_parse(|input| {
492        let location = input.current_source_location();
493        let ident = input.expect_ident()?;
494        Ok(match_ignore_ascii_case! { &ident,
495          "none" if value.is_empty() => TextDecorationLine::empty(),
496          "underline" => TextDecorationLine::Underline,
497          "overline" => TextDecorationLine::Overline,
498          "line-through" => TextDecorationLine::LineThrough,
499          "blink" =>TextDecorationLine::Blink,
500          "spelling-error" if value.is_empty() => TextDecorationLine::SpellingError,
501          "grammar-error" if value.is_empty() => TextDecorationLine::GrammarError,
502          _ => return Err(location.new_unexpected_token_error(
503            cssparser::Token::Ident(ident.clone())
504          ))
505        })
506      });
507
508      if let Ok(flag) = flag {
509        value |= flag;
510        any = true;
511      } else {
512        break;
513      }
514    }
515
516    if !any {
517      return Err(input.new_custom_error(ParserError::InvalidDeclaration));
518    }
519
520    Ok(value)
521  }
522}
523
524impl ToCss for TextDecorationLine {
525  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
526    if self.is_empty() {
527      dest.write_str("none")?;
528      return Ok(());
529    }
530
531    if self.contains(TextDecorationLine::SpellingError) {
532      dest.write_str("spelling-error")?;
533      return Ok(());
534    }
535
536    if self.contains(TextDecorationLine::GrammarError) {
537      dest.write_str("grammar-error")?;
538      return Ok(());
539    }
540
541    let mut needs_space = false;
542    macro_rules! val {
543      ($val: ident, $str: expr) => {
544        #[allow(unused_assignments)]
545        if self.contains(TextDecorationLine::$val) {
546          if needs_space {
547            dest.write_char(' ')?;
548          }
549          dest.write_str($str)?;
550          needs_space = true;
551        }
552      };
553    }
554
555    val!(Underline, "underline");
556    val!(Overline, "overline");
557    val!(LineThrough, "line-through");
558    val!(Blink, "blink");
559    Ok(())
560  }
561}
562
563#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize), serde(untagged))]
564#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
565enum SerializedTextDecorationLine {
566  Exclusive(ExclusiveTextDecorationLine),
567  Other(Vec<OtherTextDecorationLine>),
568}
569
570#[cfg_attr(
571  feature = "serde",
572  derive(serde::Serialize, serde::Deserialize),
573  serde(rename_all = "kebab-case")
574)]
575#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
576enum ExclusiveTextDecorationLine {
577  None,
578  SpellingError,
579  GrammarError,
580}
581
582#[cfg_attr(
583  feature = "serde",
584  derive(serde::Serialize, serde::Deserialize),
585  serde(rename_all = "kebab-case")
586)]
587#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
588enum OtherTextDecorationLine {
589  Underline,
590  Overline,
591  LineThrough,
592  Blink,
593}
594
595impl From<TextDecorationLine> for SerializedTextDecorationLine {
596  fn from(l: TextDecorationLine) -> Self {
597    if l.is_empty() {
598      return Self::Exclusive(ExclusiveTextDecorationLine::None);
599    }
600
601    macro_rules! exclusive {
602      ($t: ident) => {
603        if l.contains(TextDecorationLine::$t) {
604          return Self::Exclusive(ExclusiveTextDecorationLine::$t);
605        }
606      };
607    }
608
609    exclusive!(SpellingError);
610    exclusive!(GrammarError);
611
612    let mut v = Vec::new();
613    macro_rules! other {
614      ($t: ident) => {
615        if l.contains(TextDecorationLine::$t) {
616          v.push(OtherTextDecorationLine::$t)
617        }
618      };
619    }
620
621    other!(Underline);
622    other!(Overline);
623    other!(LineThrough);
624    other!(Blink);
625    Self::Other(v)
626  }
627}
628
629impl From<SerializedTextDecorationLine> for TextDecorationLine {
630  fn from(l: SerializedTextDecorationLine) -> Self {
631    match l {
632      SerializedTextDecorationLine::Exclusive(v) => match v {
633        ExclusiveTextDecorationLine::None => TextDecorationLine::empty(),
634        ExclusiveTextDecorationLine::SpellingError => TextDecorationLine::SpellingError,
635        ExclusiveTextDecorationLine::GrammarError => TextDecorationLine::GrammarError,
636      },
637      SerializedTextDecorationLine::Other(v) => {
638        let mut res = TextDecorationLine::empty();
639        for val in v {
640          res |= match val {
641            OtherTextDecorationLine::Underline => TextDecorationLine::Underline,
642            OtherTextDecorationLine::Overline => TextDecorationLine::Overline,
643            OtherTextDecorationLine::LineThrough => TextDecorationLine::LineThrough,
644            OtherTextDecorationLine::Blink => TextDecorationLine::Blink,
645          }
646        }
647        res
648      }
649    }
650  }
651}
652
653#[cfg(feature = "jsonschema")]
654#[cfg_attr(docsrs, doc(cfg(feature = "jsonschema")))]
655impl<'a> schemars::JsonSchema for TextDecorationLine {
656  fn is_referenceable() -> bool {
657    true
658  }
659
660  fn json_schema(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {
661    SerializedTextDecorationLine::json_schema(gen)
662  }
663
664  fn schema_name() -> String {
665    "TextDecorationLine".into()
666  }
667}
668
669enum_property! {
670  /// A value for the [text-decoration-style](https://www.w3.org/TR/2020/WD-css-text-decor-4-20200506/#text-decoration-style-property) property.
671  pub enum TextDecorationStyle {
672    /// A single line segment.
673    Solid,
674    /// Two parallel solid lines with some space between them.
675    Double,
676    /// A series of round dots.
677    Dotted,
678    /// A series of square-ended dashes.
679    Dashed,
680    /// A wavy line.
681    Wavy,
682  }
683}
684
685impl Default for TextDecorationStyle {
686  fn default() -> TextDecorationStyle {
687    TextDecorationStyle::Solid
688  }
689}
690
691/// A value for the [text-decoration-thickness](https://www.w3.org/TR/2020/WD-css-text-decor-4-20200506/#text-decoration-width-property) property.
692#[derive(Debug, Clone, PartialEq, Parse, ToCss)]
693#[cfg_attr(feature = "visitor", derive(Visit))]
694#[cfg_attr(
695  feature = "serde",
696  derive(serde::Serialize, serde::Deserialize),
697  serde(tag = "type", content = "value", rename_all = "kebab-case")
698)]
699#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
700#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
701pub enum TextDecorationThickness {
702  /// The UA chooses an appropriate thickness for text decoration lines.
703  Auto,
704  /// Use the thickness defined in the current font.
705  FromFont,
706  /// An explicit length.
707  LengthPercentage(LengthPercentage),
708}
709
710impl Default for TextDecorationThickness {
711  fn default() -> TextDecorationThickness {
712    TextDecorationThickness::Auto
713  }
714}
715
716define_shorthand! {
717  /// A value for the [text-decoration](https://www.w3.org/TR/2020/WD-css-text-decor-4-20200506/#text-decoration-property) shorthand property.
718  pub struct TextDecoration(VendorPrefix) {
719    /// The lines to display.
720    line: TextDecorationLine(TextDecorationLine, VendorPrefix),
721    /// The thickness of the lines.
722    thickness: TextDecorationThickness(TextDecorationThickness),
723    /// The style of the lines.
724    style: TextDecorationStyle(TextDecorationStyle, VendorPrefix),
725    /// The color of the lines.
726    color: TextDecorationColor(CssColor, VendorPrefix),
727  }
728}
729
730impl<'i> Parse<'i> for TextDecoration {
731  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
732    let mut line = None;
733    let mut thickness = None;
734    let mut style = None;
735    let mut color = None;
736
737    loop {
738      macro_rules! prop {
739        ($key: ident, $type: ident) => {
740          if $key.is_none() {
741            if let Ok(val) = input.try_parse($type::parse) {
742              $key = Some(val);
743              continue;
744            }
745          }
746        };
747      }
748
749      prop!(line, TextDecorationLine);
750      prop!(thickness, TextDecorationThickness);
751      prop!(style, TextDecorationStyle);
752      prop!(color, CssColor);
753      break;
754    }
755
756    Ok(TextDecoration {
757      line: line.unwrap_or_default(),
758      thickness: thickness.unwrap_or_default(),
759      style: style.unwrap_or_default(),
760      color: color.unwrap_or(CssColor::current_color()),
761    })
762  }
763}
764
765impl ToCss for TextDecoration {
766  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
767    self.line.to_css(dest)?;
768    if self.line.is_empty() {
769      return Ok(());
770    }
771
772    let mut needs_space = true;
773    if self.thickness != TextDecorationThickness::default() {
774      dest.write_char(' ')?;
775      self.thickness.to_css(dest)?;
776      needs_space = true;
777    }
778
779    if self.style != TextDecorationStyle::default() {
780      if needs_space {
781        dest.write_char(' ')?;
782      }
783      self.style.to_css(dest)?;
784      needs_space = true;
785    }
786
787    if self.color != CssColor::current_color() {
788      if needs_space {
789        dest.write_char(' ')?;
790      }
791      self.color.to_css(dest)?;
792    }
793
794    Ok(())
795  }
796}
797
798impl FallbackValues for TextDecoration {
799  fn get_fallbacks(&mut self, targets: Targets) -> Vec<Self> {
800    self
801      .color
802      .get_fallbacks(targets)
803      .into_iter()
804      .map(|color| TextDecoration { color, ..self.clone() })
805      .collect()
806  }
807}
808
809enum_property! {
810  /// A value for the [text-decoration-skip-ink](https://www.w3.org/TR/2020/WD-css-text-decor-4-20200506/#text-decoration-skip-ink-property) property.
811  pub enum TextDecorationSkipInk {
812    /// UAs may interrupt underlines and overlines.
813    Auto,
814    /// UAs must interrupt underlines and overlines.
815    None,
816    /// UA must draw continuous underlines and overlines.
817    All,
818  }
819}
820
821enum_property! {
822  /// A keyword for the [text-emphasis-style](https://www.w3.org/TR/2020/WD-css-text-decor-4-20200506/#text-emphasis-style-property) property.
823  ///
824  /// See [TextEmphasisStyle](TextEmphasisStyle).
825  pub enum TextEmphasisFillMode {
826    /// The shape is filled with solid color.
827    Filled,
828    /// The shape is hollow.
829    Open,
830  }
831}
832
833enum_property! {
834  /// A text emphasis shape for the [text-emphasis-style](https://www.w3.org/TR/2020/WD-css-text-decor-4-20200506/#text-emphasis-style-property) property.
835  ///
836  /// See [TextEmphasisStyle](TextEmphasisStyle).
837  pub enum TextEmphasisShape {
838    /// Display small circles as marks.
839    Dot,
840    /// Display large circles as marks.
841    Circle,
842    /// Display double circles as marks.
843    DoubleCircle,
844    /// Display triangles as marks.
845    Triangle,
846    /// Display sesames as marks.
847    Sesame,
848  }
849}
850
851/// A value for the [text-emphasis-style](https://www.w3.org/TR/2020/WD-css-text-decor-4-20200506/#text-emphasis-style-property) property.
852#[derive(Debug, Clone, PartialEq)]
853#[cfg_attr(feature = "visitor", derive(Visit))]
854#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
855#[cfg_attr(
856  feature = "serde",
857  derive(serde::Serialize, serde::Deserialize),
858  serde(tag = "type", rename_all = "kebab-case")
859)]
860#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
861pub enum TextEmphasisStyle<'i> {
862  /// No emphasis.
863  None,
864  /// Defines the fill and shape of the marks.
865  Keyword {
866    /// The fill mode for the marks.
867    fill: TextEmphasisFillMode,
868    /// The shape of the marks.
869    shape: Option<TextEmphasisShape>,
870  },
871  /// Display the given string as marks.
872  #[cfg_attr(
873    feature = "serde",
874    serde(borrow, with = "crate::serialization::ValueWrapper::<CSSString>")
875  )]
876  String(CSSString<'i>),
877}
878
879impl<'i> Default for TextEmphasisStyle<'i> {
880  fn default() -> TextEmphasisStyle<'i> {
881    TextEmphasisStyle::None
882  }
883}
884
885impl<'i> Parse<'i> for TextEmphasisStyle<'i> {
886  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
887    if input.try_parse(|input| input.expect_ident_matching("none")).is_ok() {
888      return Ok(TextEmphasisStyle::None);
889    }
890
891    if let Ok(s) = input.try_parse(CSSString::parse) {
892      return Ok(TextEmphasisStyle::String(s));
893    }
894
895    let mut shape = input.try_parse(TextEmphasisShape::parse).ok();
896    let fill = input.try_parse(TextEmphasisFillMode::parse).ok();
897    if shape.is_none() {
898      shape = input.try_parse(TextEmphasisShape::parse).ok();
899    }
900
901    if shape.is_none() && fill.is_none() {
902      return Err(input.new_custom_error(ParserError::InvalidDeclaration));
903    }
904
905    let fill = fill.unwrap_or(TextEmphasisFillMode::Filled);
906    Ok(TextEmphasisStyle::Keyword { fill, shape })
907  }
908}
909
910impl<'i> ToCss for TextEmphasisStyle<'i> {
911  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
912    match self {
913      TextEmphasisStyle::None => {
914        dest.write_str("none")?;
915        Ok(())
916      }
917      TextEmphasisStyle::String(s) => s.to_css(dest),
918      TextEmphasisStyle::Keyword { fill, shape } => {
919        let mut needs_space = false;
920        if *fill != TextEmphasisFillMode::Filled || shape.is_none() {
921          fill.to_css(dest)?;
922          needs_space = true;
923        }
924
925        if let Some(shape) = shape {
926          if needs_space {
927            dest.write_char(' ')?;
928          }
929          shape.to_css(dest)?;
930        }
931        Ok(())
932      }
933    }
934  }
935}
936
937define_shorthand! {
938  /// A value for the [text-emphasis](https://www.w3.org/TR/2020/WD-css-text-decor-4-20200506/#text-emphasis-property) shorthand property.
939  pub struct TextEmphasis<'i>(VendorPrefix) {
940    /// The text emphasis style.
941    #[cfg_attr(feature = "serde", serde(borrow))]
942    style: TextEmphasisStyle(TextEmphasisStyle<'i>, VendorPrefix),
943    /// The text emphasis color.
944    color: TextEmphasisColor(CssColor, VendorPrefix),
945  }
946}
947
948impl<'i> Parse<'i> for TextEmphasis<'i> {
949  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
950    let mut style = None;
951    let mut color = None;
952
953    loop {
954      if style.is_none() {
955        if let Ok(s) = input.try_parse(TextEmphasisStyle::parse) {
956          style = Some(s);
957          continue;
958        }
959      }
960
961      if color.is_none() {
962        if let Ok(c) = input.try_parse(CssColor::parse) {
963          color = Some(c);
964          continue;
965        }
966      }
967
968      break;
969    }
970
971    Ok(TextEmphasis {
972      style: style.unwrap_or_default(),
973      color: color.unwrap_or(CssColor::current_color()),
974    })
975  }
976}
977
978impl<'i> ToCss for TextEmphasis<'i> {
979  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
980    self.style.to_css(dest)?;
981
982    if self.style != TextEmphasisStyle::None && self.color != CssColor::current_color() {
983      dest.write_char(' ')?;
984      self.color.to_css(dest)?;
985    }
986
987    Ok(())
988  }
989}
990
991impl<'i> FallbackValues for TextEmphasis<'i> {
992  fn get_fallbacks(&mut self, targets: Targets) -> Vec<Self> {
993    self
994      .color
995      .get_fallbacks(targets)
996      .into_iter()
997      .map(|color| TextEmphasis { color, ..self.clone() })
998      .collect()
999  }
1000}
1001
1002enum_property! {
1003  /// A vertical position keyword for the [text-emphasis-position](https://www.w3.org/TR/2020/WD-css-text-decor-4-20200506/#text-emphasis-position-property) property.
1004  ///
1005  /// See [TextEmphasisPosition](TextEmphasisPosition).
1006  pub enum TextEmphasisPositionVertical {
1007    /// Draw marks over the text in horizontal typographic modes.
1008    Over,
1009    /// Draw marks under the text in horizontal typographic modes.
1010    Under,
1011  }
1012}
1013
1014enum_property! {
1015  /// A horizontal position keyword for the [text-emphasis-position](https://www.w3.org/TR/2020/WD-css-text-decor-4-20200506/#text-emphasis-position-property) property.
1016  ///
1017  /// See [TextEmphasisPosition](TextEmphasisPosition).
1018  pub enum TextEmphasisPositionHorizontal {
1019    /// Draw marks to the right of the text in vertical typographic modes.
1020    Left,
1021    /// Draw marks to the left of the text in vertical typographic modes.
1022    Right,
1023  }
1024}
1025
1026/// A value for the [text-emphasis-position](https://www.w3.org/TR/2020/WD-css-text-decor-4-20200506/#text-emphasis-position-property) property.
1027#[derive(Debug, Clone, PartialEq)]
1028#[cfg_attr(feature = "visitor", derive(Visit))]
1029#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1030#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
1031#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
1032pub struct TextEmphasisPosition {
1033  /// The vertical position.
1034  pub vertical: TextEmphasisPositionVertical,
1035  /// The horizontal position.
1036  pub horizontal: TextEmphasisPositionHorizontal,
1037}
1038
1039impl<'i> Parse<'i> for TextEmphasisPosition {
1040  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
1041    if let Ok(horizontal) = input.try_parse(TextEmphasisPositionHorizontal::parse) {
1042      let vertical = TextEmphasisPositionVertical::parse(input)?;
1043      Ok(TextEmphasisPosition { horizontal, vertical })
1044    } else {
1045      let vertical = TextEmphasisPositionVertical::parse(input)?;
1046      let horizontal = input
1047        .try_parse(TextEmphasisPositionHorizontal::parse)
1048        .unwrap_or(TextEmphasisPositionHorizontal::Right);
1049      Ok(TextEmphasisPosition { horizontal, vertical })
1050    }
1051  }
1052}
1053
1054enum_property! {
1055  /// A value for the [box-decoration-break](https://www.w3.org/TR/css-break-3/#break-decoration) property.
1056  pub enum BoxDecorationBreak {
1057    /// The element is rendered with no breaks present, and then sliced by the breaks afterward.
1058    Slice,
1059    /// Each box fragment is independently wrapped with the border, padding, and margin.
1060    Clone,
1061  }
1062}
1063
1064impl Default for BoxDecorationBreak {
1065  fn default() -> Self {
1066    BoxDecorationBreak::Slice
1067  }
1068}
1069
1070impl ToCss for TextEmphasisPosition {
1071  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
1072    self.vertical.to_css(dest)?;
1073    if self.horizontal != TextEmphasisPositionHorizontal::Right {
1074      dest.write_char(' ')?;
1075      self.horizontal.to_css(dest)?;
1076    }
1077    Ok(())
1078  }
1079}
1080
1081#[derive(Default)]
1082pub(crate) struct TextDecorationHandler<'i> {
1083  line: Option<(TextDecorationLine, VendorPrefix)>,
1084  thickness: Option<TextDecorationThickness>,
1085  style: Option<(TextDecorationStyle, VendorPrefix)>,
1086  color: Option<(CssColor, VendorPrefix)>,
1087  emphasis_style: Option<(TextEmphasisStyle<'i>, VendorPrefix)>,
1088  emphasis_color: Option<(CssColor, VendorPrefix)>,
1089  emphasis_position: Option<(TextEmphasisPosition, VendorPrefix)>,
1090  has_any: bool,
1091}
1092
1093impl<'i> PropertyHandler<'i> for TextDecorationHandler<'i> {
1094  fn handle_property(
1095    &mut self,
1096    property: &Property<'i>,
1097    dest: &mut DeclarationList<'i>,
1098    context: &mut PropertyHandlerContext<'i, '_>,
1099  ) -> bool {
1100    use Property::*;
1101
1102    macro_rules! maybe_flush {
1103      ($prop: ident, $val: expr, $vp: expr) => {{
1104        // If two vendor prefixes for the same property have different
1105        // values, we need to flush what we have immediately to preserve order.
1106        if let Some((val, prefixes)) = &self.$prop {
1107          if val != $val && !prefixes.contains(*$vp) {
1108            self.finalize(dest, context);
1109          }
1110        }
1111      }};
1112    }
1113
1114    macro_rules! property {
1115      ($prop: ident, $val: expr, $vp: expr) => {{
1116        maybe_flush!($prop, $val, $vp);
1117
1118        // Otherwise, update the value and add the prefix.
1119        if let Some((val, prefixes)) = &mut self.$prop {
1120          *val = $val.clone();
1121          *prefixes |= *$vp;
1122        } else {
1123          self.$prop = Some(($val.clone(), *$vp));
1124          self.has_any = true;
1125        }
1126      }};
1127    }
1128
1129    match property {
1130      TextDecorationLine(val, vp) => property!(line, val, vp),
1131      TextDecorationThickness(val) => {
1132        self.thickness = Some(val.clone());
1133        self.has_any = true;
1134      }
1135      TextDecorationStyle(val, vp) => property!(style, val, vp),
1136      TextDecorationColor(val, vp) => property!(color, val, vp),
1137      TextDecoration(val, vp) => {
1138        maybe_flush!(line, &val.line, vp);
1139        maybe_flush!(style, &val.style, vp);
1140        maybe_flush!(color, &val.color, vp);
1141        property!(line, &val.line, vp);
1142        self.thickness = Some(val.thickness.clone());
1143        property!(style, &val.style, vp);
1144        property!(color, &val.color, vp);
1145      }
1146      TextEmphasisStyle(val, vp) => property!(emphasis_style, val, vp),
1147      TextEmphasisColor(val, vp) => property!(emphasis_color, val, vp),
1148      TextEmphasis(val, vp) => {
1149        maybe_flush!(emphasis_style, &val.style, vp);
1150        maybe_flush!(emphasis_color, &val.color, vp);
1151        property!(emphasis_style, &val.style, vp);
1152        property!(emphasis_color, &val.color, vp);
1153      }
1154      TextEmphasisPosition(val, vp) => property!(emphasis_position, val, vp),
1155      TextAlign(align) => {
1156        use super::text::*;
1157        macro_rules! logical {
1158          ($ltr: ident, $rtl: ident) => {{
1159            let logical_supported = !context.should_compile_logical(compat::Feature::LogicalTextAlign);
1160            if logical_supported {
1161              dest.push(property.clone());
1162            } else {
1163              context.add_logical_rule(
1164                Property::TextAlign(TextAlign::$ltr),
1165                Property::TextAlign(TextAlign::$rtl),
1166              );
1167            }
1168          }};
1169        }
1170
1171        match align {
1172          TextAlign::Start => logical!(Left, Right),
1173          TextAlign::End => logical!(Right, Left),
1174          _ => dest.push(property.clone()),
1175        }
1176      }
1177      Unparsed(val) => {
1178        let feature = if is_text_decoration_property(&val.property_id) {
1179          Feature::TextDecoration
1180        } else if is_text_emphasis_property(&val.property_id) {
1181          Feature::TextEmphasis
1182        } else {
1183          return false;
1184        };
1185
1186        self.finalize(dest, context);
1187        let mut unparsed = val.get_prefixed(context.targets, feature);
1188        context.add_unparsed_fallbacks(&mut unparsed);
1189
1190        // Combine adjacent identical values after adding prefixes and fallbacks.
1191        // Only inspect the last declaration so intervening longhands retain their order.
1192        if let Some(Property::Unparsed(previous)) = dest.last_mut() {
1193          let prefix = unparsed.property_id.prefix();
1194          if previous.property_id.with_prefix(prefix) == unparsed.property_id && previous.value == unparsed.value {
1195            previous.property_id.add_prefix(prefix);
1196            return true;
1197          }
1198        }
1199
1200        dest.push(Property::Unparsed(unparsed))
1201      }
1202      _ => return false,
1203    }
1204
1205    true
1206  }
1207
1208  fn finalize(&mut self, dest: &mut DeclarationList<'i>, context: &mut PropertyHandlerContext<'i, '_>) {
1209    if !self.has_any {
1210      return;
1211    }
1212
1213    self.has_any = false;
1214
1215    let mut line = std::mem::take(&mut self.line);
1216    let mut thickness = std::mem::take(&mut self.thickness);
1217    let mut style = std::mem::take(&mut self.style);
1218    let mut color = std::mem::take(&mut self.color);
1219    let mut emphasis_style = std::mem::take(&mut self.emphasis_style);
1220    let mut emphasis_color = std::mem::take(&mut self.emphasis_color);
1221    let emphasis_position = std::mem::take(&mut self.emphasis_position);
1222
1223    if let (Some((line, line_vp)), Some(thickness_val), Some((style, style_vp)), Some((color, color_vp))) =
1224      (&mut line, &mut thickness, &mut style, &mut color)
1225    {
1226      let intersection = *line_vp | *style_vp | *color_vp;
1227      if !intersection.is_empty() {
1228        let mut prefix = intersection;
1229
1230        // Some browsers don't support thickness in the shorthand property yet.
1231        let supports_thickness = context.targets.is_compatible(compat::Feature::TextDecorationThicknessShorthand);
1232        let mut decoration = TextDecoration {
1233          line: line.clone(),
1234          thickness: if supports_thickness {
1235            thickness_val.clone()
1236          } else {
1237            TextDecorationThickness::default()
1238          },
1239          style: style.clone(),
1240          color: color.clone(),
1241        };
1242
1243        // Only add prefixes if one of the new sub-properties was used
1244        if prefix.contains(VendorPrefix::None)
1245          && (*style != TextDecorationStyle::default() || *color != CssColor::current_color())
1246        {
1247          prefix = context.targets.prefixes(VendorPrefix::None, Feature::TextDecoration);
1248
1249          let fallbacks = decoration.get_fallbacks(context.targets);
1250          for fallback in fallbacks {
1251            dest.push(Property::TextDecoration(fallback, prefix))
1252          }
1253        }
1254
1255        dest.push(Property::TextDecoration(decoration, prefix));
1256        line_vp.remove(intersection);
1257        style_vp.remove(intersection);
1258        color_vp.remove(intersection);
1259        if supports_thickness || *thickness_val == TextDecorationThickness::default() {
1260          thickness = None;
1261        }
1262      }
1263    }
1264
1265    macro_rules! color {
1266      ($key: ident, $prop: ident) => {
1267        if let Some((mut val, vp)) = $key {
1268          if !vp.is_empty() {
1269            let prefix = context.targets.prefixes(vp, Feature::$prop);
1270            if prefix.contains(VendorPrefix::None) {
1271              let fallbacks = val.get_fallbacks(context.targets);
1272              for fallback in fallbacks {
1273                dest.push(Property::$prop(fallback, prefix))
1274              }
1275            }
1276            dest.push(Property::$prop(val, prefix))
1277          }
1278        }
1279      };
1280    }
1281
1282    macro_rules! single_property {
1283      ($key: ident, $prop: ident) => {
1284        if let Some((val, vp)) = $key {
1285          if !vp.is_empty() {
1286            let prefix = context.targets.prefixes(vp, Feature::$prop);
1287            dest.push(Property::$prop(val, prefix))
1288          }
1289        }
1290      };
1291    }
1292
1293    single_property!(line, TextDecorationLine);
1294    single_property!(style, TextDecorationStyle);
1295    color!(color, TextDecorationColor);
1296
1297    if let Some(thickness) = thickness {
1298      // Percentages in the text-decoration-thickness property are based on 1em.
1299      // If unsupported, compile this to a calc() instead.
1300      match thickness {
1301        TextDecorationThickness::LengthPercentage(LengthPercentage::Percentage(p))
1302          if should_compile!(context.targets, TextDecorationThicknessPercent) =>
1303        {
1304          let calc = Calc::Function(Box::new(MathFunction::Calc(Calc::Product(
1305            p.0,
1306            Box::new(Calc::Value(Box::new(LengthPercentage::Dimension(LengthValue::Em(1.0))))),
1307          ))));
1308          let thickness = TextDecorationThickness::LengthPercentage(LengthPercentage::Calc(Box::new(calc)));
1309          dest.push(Property::TextDecorationThickness(thickness));
1310        }
1311        thickness => dest.push(Property::TextDecorationThickness(thickness)),
1312      }
1313    }
1314
1315    if let (Some((style, style_vp)), Some((color, color_vp))) = (&mut emphasis_style, &mut emphasis_color) {
1316      let intersection = *style_vp | *color_vp;
1317      if !intersection.is_empty() {
1318        let prefix = context.targets.prefixes(intersection, Feature::TextEmphasis);
1319        let mut emphasis = TextEmphasis {
1320          style: style.clone(),
1321          color: color.clone(),
1322        };
1323
1324        if prefix.contains(VendorPrefix::None) {
1325          let fallbacks = emphasis.get_fallbacks(context.targets);
1326          for fallback in fallbacks {
1327            dest.push(Property::TextEmphasis(fallback, prefix))
1328          }
1329        }
1330
1331        dest.push(Property::TextEmphasis(emphasis, prefix));
1332        style_vp.remove(intersection);
1333        color_vp.remove(intersection);
1334      }
1335    }
1336
1337    single_property!(emphasis_style, TextEmphasisStyle);
1338    color!(emphasis_color, TextEmphasisColor);
1339
1340    if let Some((pos, vp)) = emphasis_position {
1341      if !vp.is_empty() {
1342        let mut prefix = context.targets.prefixes(vp, Feature::TextEmphasisPosition);
1343        // Prefixed version does not support horizontal keyword.
1344        if pos.horizontal != TextEmphasisPositionHorizontal::Right {
1345          prefix = VendorPrefix::None;
1346        }
1347        dest.push(Property::TextEmphasisPosition(pos, prefix))
1348      }
1349    }
1350  }
1351}
1352
1353/// A value for the [text-shadow](https://www.w3.org/TR/2020/WD-css-text-decor-4-20200506/#text-shadow-property) property.
1354#[derive(Debug, Clone, PartialEq)]
1355#[cfg_attr(feature = "visitor", derive(Visit))]
1356#[cfg_attr(
1357  feature = "serde",
1358  derive(serde::Serialize, serde::Deserialize),
1359  serde(rename_all = "camelCase")
1360)]
1361#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
1362#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
1363pub struct TextShadow {
1364  /// The color of the text shadow.
1365  pub color: CssColor,
1366  /// The x offset of the text shadow.
1367  pub x_offset: Length,
1368  /// The y offset of the text shadow.
1369  pub y_offset: Length,
1370  /// The blur radius of the text shadow.
1371  pub blur: NonNegative<Length>,
1372  /// The spread distance of the text shadow.
1373  pub spread: NonNegative<Length>, // added in Level 4 spec
1374}
1375
1376impl<'i> Parse<'i> for TextShadow {
1377  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
1378    let mut color = None;
1379    let mut lengths = None;
1380
1381    loop {
1382      if lengths.is_none() {
1383        let value = input.try_parse::<_, _, ParseError<ParserError<'i>>>(|input| {
1384          let horizontal = Length::parse(input)?;
1385          let vertical = Length::parse(input)?;
1386          let blur = input.try_parse(NonNegative::<Length>::parse).ok();
1387          // A rejected blur radius must not be reinterpreted as a spread.
1388          let spread = if blur.is_some() {
1389            input.try_parse(NonNegative::<Length>::parse).unwrap_or(NonNegative::zero())
1390          } else {
1391            NonNegative::zero()
1392          };
1393          Ok((horizontal, vertical, blur.unwrap_or(NonNegative::zero()), spread))
1394        });
1395
1396        if let Ok(value) = value {
1397          lengths = Some(value);
1398          continue;
1399        }
1400      }
1401
1402      if color.is_none() {
1403        if let Ok(value) = input.try_parse(CssColor::parse) {
1404          color = Some(value);
1405          continue;
1406        }
1407      }
1408
1409      break;
1410    }
1411
1412    let lengths = lengths.ok_or(input.new_error(BasicParseErrorKind::QualifiedRuleInvalid))?;
1413    Ok(TextShadow {
1414      color: color.unwrap_or(CssColor::current_color()),
1415      x_offset: lengths.0,
1416      y_offset: lengths.1,
1417      blur: lengths.2,
1418      spread: lengths.3,
1419    })
1420  }
1421}
1422
1423impl ToCss for TextShadow {
1424  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
1425    self.x_offset.to_css(dest)?;
1426    dest.write_char(' ')?;
1427    self.y_offset.to_css(dest)?;
1428
1429    if self.blur != NonNegative::zero() || self.spread != NonNegative::zero() {
1430      dest.write_char(' ')?;
1431      self.blur.to_css(dest)?;
1432
1433      if self.spread != NonNegative::zero() {
1434        dest.write_char(' ')?;
1435        self.spread.to_css(dest)?;
1436      }
1437    }
1438
1439    if self.color != CssColor::current_color() {
1440      dest.write_char(' ')?;
1441      self.color.to_css(dest)?;
1442    }
1443
1444    Ok(())
1445  }
1446}
1447
1448impl IsCompatible for TextShadow {
1449  fn is_compatible(&self, browsers: Browsers) -> bool {
1450    self.color.is_compatible(browsers)
1451      && self.x_offset.is_compatible(browsers)
1452      && self.y_offset.is_compatible(browsers)
1453      && self.blur.is_compatible(browsers)
1454      && self.spread.is_compatible(browsers)
1455  }
1456}
1457
1458#[inline]
1459fn is_text_decoration_property(property_id: &PropertyId) -> bool {
1460  match property_id {
1461    PropertyId::TextDecorationLine(_)
1462    | PropertyId::TextDecorationThickness
1463    | PropertyId::TextDecorationStyle(_)
1464    | PropertyId::TextDecorationColor(_)
1465    | PropertyId::TextDecoration(_) => true,
1466    _ => false,
1467  }
1468}
1469
1470#[inline]
1471fn is_text_emphasis_property(property_id: &PropertyId) -> bool {
1472  match property_id {
1473    PropertyId::TextEmphasisStyle(_)
1474    | PropertyId::TextEmphasisColor(_)
1475    | PropertyId::TextEmphasis(_)
1476    | PropertyId::TextEmphasisPosition(_) => true,
1477    _ => false,
1478  }
1479}
1480
1481impl FallbackValues for SmallVec<[TextShadow; 1]> {
1482  fn get_fallbacks(&mut self, targets: Targets) -> Vec<Self> {
1483    let mut fallbacks = ColorFallbackKind::empty();
1484    for shadow in self.iter() {
1485      fallbacks |= shadow.color.get_necessary_fallbacks(targets);
1486    }
1487
1488    let mut res = Vec::new();
1489    if fallbacks.contains(ColorFallbackKind::RGB) {
1490      let rgb = self
1491        .iter()
1492        .map(|shadow| TextShadow {
1493          color: shadow.color.to_rgb().unwrap(),
1494          ..shadow.clone()
1495        })
1496        .collect();
1497      res.push(rgb);
1498    }
1499
1500    if fallbacks.contains(ColorFallbackKind::P3) {
1501      let p3 = self
1502        .iter()
1503        .map(|shadow| TextShadow {
1504          color: shadow.color.to_p3().unwrap(),
1505          ..shadow.clone()
1506        })
1507        .collect();
1508      res.push(p3);
1509    }
1510
1511    if fallbacks.contains(ColorFallbackKind::LAB) {
1512      for shadow in self.iter_mut() {
1513        shadow.color = shadow.color.to_lab().unwrap();
1514      }
1515    }
1516
1517    res
1518  }
1519}
1520
1521enum_property! {
1522  /// A value for the [direction](https://drafts.csswg.org/css-writing-modes-3/#direction) property.
1523  pub enum Direction {
1524    /// This value sets inline base direction (bidi directionality) to line-left-to-line-right.
1525    Ltr,
1526    /// This value sets inline base direction (bidi directionality) to line-right-to-line-left.
1527    Rtl,
1528  }
1529}
1530
1531enum_property! {
1532  /// A value for the [unicode-bidi](https://drafts.csswg.org/css-writing-modes-3/#unicode-bidi) property.
1533  pub enum UnicodeBidi {
1534    /// The box does not open an additional level of embedding.
1535    Normal,
1536    /// If the box is inline, this value creates a directional embedding by opening an additional level of embedding.
1537    Embed,
1538    /// On an inline box, this bidi-isolates its contents.
1539    Isolate,
1540    /// This value puts the box’s immediate inline content in a directional override.
1541    BidiOverride,
1542    /// This combines the isolation behavior of isolate with the directional override behavior of bidi-override.
1543    IsolateOverride,
1544    /// This value behaves as isolate except that the base directionality is determined using a heuristic rather than the direction property.
1545    Plaintext,
1546  }
1547}