1#![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 pub enum TextTransformCase {
31 None,
33 Uppercase,
35 Lowercase,
37 Capitalize,
39 }
40}
41
42impl Default for TextTransformCase {
43 fn default() -> TextTransformCase {
44 TextTransformCase::None
45 }
46}
47
48bitflags! {
49 #[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 const FullWidth = 0b00000001;
59 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 full_width: bool,
107 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#[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 pub case: TextTransformCase,
158 #[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 pub enum WhiteSpace {
216 "normal": Normal,
218 "pre": Pre,
220 "nowrap": NoWrap,
222 "pre-wrap": PreWrap,
224 "break-spaces": BreakSpaces,
226 "pre-line": PreLine,
228 }
229}
230
231enum_property! {
232 pub enum WordBreak {
234 Normal,
236 KeepAll,
238 BreakAll,
240 BreakWord,
242 }
243}
244
245enum_property! {
246 pub enum LineBreak {
248 Auto,
250 Loose,
252 Normal,
254 Strict,
256 Anywhere,
258 }
259}
260enum_property! {
261 pub enum Hyphens {
263 None,
265 Manual,
267 Auto,
269 }
270}
271
272enum_property! {
273 pub enum OverflowWrap {
275 Normal,
277 Anywhere,
279 BreakWord,
282 }
283}
284
285enum_property! {
286 pub enum TextAlign {
288 Start,
290 End,
292 Left,
294 Right,
296 Center,
298 Justify,
300 MatchParent,
302 JustifyAll,
304 }
305}
306
307enum_property! {
308 pub enum TextAlignLast {
310 Auto,
312 Start,
314 End,
316 Left,
318 Right,
320 Center,
322 Justify,
324 MatchParent,
326 }
327}
328
329enum_property! {
330 pub enum TextJustify {
332 Auto,
334 None,
336 InterWord,
338 InterCharacter,
340 }
341}
342
343#[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 Normal,
357 Length(Length),
359}
360
361#[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 pub value: LengthPercentage,
374 pub hanging: bool,
376 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#[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 Auto,
449 None,
451 Percentage(NonNegative<Percentage>),
453}
454
455bitflags! {
456 #[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 const Underline = 0b00000001;
466 const Overline = 0b00000010;
468 const LineThrough = 0b00000100;
470 const Blink = 0b00001000;
472 const SpellingError = 0b00010000;
474 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 pub enum TextDecorationStyle {
672 Solid,
674 Double,
676 Dotted,
678 Dashed,
680 Wavy,
682 }
683}
684
685impl Default for TextDecorationStyle {
686 fn default() -> TextDecorationStyle {
687 TextDecorationStyle::Solid
688 }
689}
690
691#[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 Auto,
704 FromFont,
706 LengthPercentage(LengthPercentage),
708}
709
710impl Default for TextDecorationThickness {
711 fn default() -> TextDecorationThickness {
712 TextDecorationThickness::Auto
713 }
714}
715
716define_shorthand! {
717 pub struct TextDecoration(VendorPrefix) {
719 line: TextDecorationLine(TextDecorationLine, VendorPrefix),
721 thickness: TextDecorationThickness(TextDecorationThickness),
723 style: TextDecorationStyle(TextDecorationStyle, VendorPrefix),
725 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 pub enum TextDecorationSkipInk {
812 Auto,
814 None,
816 All,
818 }
819}
820
821enum_property! {
822 pub enum TextEmphasisFillMode {
826 Filled,
828 Open,
830 }
831}
832
833enum_property! {
834 pub enum TextEmphasisShape {
838 Dot,
840 Circle,
842 DoubleCircle,
844 Triangle,
846 Sesame,
848 }
849}
850
851#[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 None,
864 Keyword {
866 fill: TextEmphasisFillMode,
868 shape: Option<TextEmphasisShape>,
870 },
871 #[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 pub struct TextEmphasis<'i>(VendorPrefix) {
940 #[cfg_attr(feature = "serde", serde(borrow))]
942 style: TextEmphasisStyle(TextEmphasisStyle<'i>, VendorPrefix),
943 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 pub enum TextEmphasisPositionVertical {
1007 Over,
1009 Under,
1011 }
1012}
1013
1014enum_property! {
1015 pub enum TextEmphasisPositionHorizontal {
1019 Left,
1021 Right,
1023 }
1024}
1025
1026#[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 pub vertical: TextEmphasisPositionVertical,
1035 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 pub enum BoxDecorationBreak {
1057 Slice,
1059 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 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 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 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 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 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 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 if pos.horizontal != TextEmphasisPositionHorizontal::Right {
1345 prefix = VendorPrefix::None;
1346 }
1347 dest.push(Property::TextEmphasisPosition(pos, prefix))
1348 }
1349 }
1350 }
1351}
1352
1353#[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 pub color: CssColor,
1366 pub x_offset: Length,
1368 pub y_offset: Length,
1370 pub blur: NonNegative<Length>,
1372 pub spread: NonNegative<Length>, }
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 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 pub enum Direction {
1524 Ltr,
1526 Rtl,
1528 }
1529}
1530
1531enum_property! {
1532 pub enum UnicodeBidi {
1534 Normal,
1536 Embed,
1538 Isolate,
1540 BidiOverride,
1542 IsolateOverride,
1544 Plaintext,
1546 }
1547}