1use std::{borrow::Cow, error::Error, fmt, sync::Arc};
2
3use cssparser::{
4 BasicParseErrorKind, ParseError as CssParseError, ParseErrorKind, Parser,
5 ToCss as CssParserToCss, Token,
6};
7
8use crate::style::{Color, SizingContext, build_unexpected_token, math::lcm, merge_enum_values};
9
10pub(crate) type ParseResult<'i, T> = Result<T, CssParseError<ValueError<'i>>>;
12
13#[derive(Debug, Clone, PartialEq)]
16pub(crate) enum ValueError<'i> {
17 Message(Cow<'i, str>),
18 UnexpectedToken {
20 token: Token<'i>,
21 expect: CssExpectedMessage,
22 valid_tokens: &'static [&'static str],
23 },
24}
25
26impl<'i> ValueError<'i> {
27 pub(crate) fn invalid(message: &'static str) -> CssParseError<Self> {
29 CssParseError::custom(Self::Message(Cow::Borrowed(message)))
30 }
31}
32
33impl fmt::Display for ValueError<'_> {
34 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35 match self {
36 Self::Message(message) => f.write_str(message),
37 Self::UnexpectedToken {
38 token,
39 expect,
40 valid_tokens,
41 } => f.write_str(&expect.build_message(
42 &CssParserToCss::to_css_string(token),
43 merge_enum_values(valid_tokens),
44 )),
45 }
46 }
47}
48
49impl<'i> From<Cow<'i, str>> for ValueError<'i> {
50 fn from(message: Cow<'i, str>) -> Self {
51 Self::Message(message)
52 }
53}
54
55#[derive(Debug, Clone, PartialEq, Eq)]
57pub struct ParseError {
58 message: String,
59}
60
61impl fmt::Display for ParseError {
62 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63 f.write_str(&self.message)
64 }
65}
66
67impl Error for ParseError {}
68
69impl ParseError {
70 pub(crate) fn from_css_error(error: &CssParseError<ValueError<'_>>) -> Self {
72 let message = match &error.kind {
73 ParseErrorKind::Custom(message) => message.to_string(),
74 basic => format!("{basic:?}"),
75 };
76
77 Self { message }
78 }
79}
80
81pub(crate) fn parse_css_str<T>(source: &str) -> Result<T, ParseError>
84where
85 T: for<'i> FromCss<'i>,
86{
87 let mut parser = Parser::new(source);
88
89 T::from_css(&mut parser).map_err(|error| ParseError::from_css_error(&error))
90}
91
92pub trait FromCssStr: Sized {
94 fn from_css_str(source: &str) -> Result<Self, ParseError>;
96}
97
98impl<T> FromCssStr for T
99where
100 T: for<'i> FromCss<'i>,
101{
102 fn from_css_str(source: &str) -> Result<Self, ParseError> {
103 parse_css_str::<Self>(source)
104 }
105}
106
107pub(crate) const fn merged_token_len(lists: &[&[&'static str]]) -> usize {
110 let (mut len, mut list) = (0, 0);
111 while list < lists.len() {
112 len += lists[list].len();
113 list += 1;
114 }
115 len
116}
117
118pub(crate) const fn merge_token_lists<const N: usize>(
121 lists: &[&[&'static str]],
122) -> [&'static str; N] {
123 let mut merged = [""; N];
124 let (mut index, mut list) = (0, 0);
125 while list < lists.len() {
126 let tokens = lists[list];
127 let mut token = 0;
128 while token < tokens.len() {
129 merged[index] = tokens[token];
130 index += 1;
131 token += 1;
132 }
133 list += 1;
134 }
135 merged
136}
137
138#[inline(never)]
141pub(crate) fn keyword_index(ident: &str, tokens: &[&'static str]) -> Option<usize> {
142 tokens
143 .iter()
144 .position(|token| !token.starts_with('<') && ident.eq_ignore_ascii_case(token))
145}
146
147#[inline(never)]
148pub(crate) fn parse_enum_keyword<'i>(
149 input: &mut Parser<'i>,
150 valid_tokens: &'static [&'static str],
151 expect: CssExpectedMessage,
152) -> ParseResult<'i, usize> {
153 let token = input.next()?;
154
155 let Token::Ident(ident) = token else {
156 return Err(build_unexpected_token(token, expect, valid_tokens));
157 };
158
159 keyword_index(ident, valid_tokens)
160 .ok_or_else(|| build_unexpected_token(token, expect, valid_tokens))
161}
162
163#[inline(never)]
164pub(crate) fn parse_ident_enum_keyword<'i>(
165 input: &mut Parser<'i>,
166 valid_tokens: &'static [&'static str],
167 expect: CssExpectedMessage,
168) -> ParseResult<'i, usize> {
169 let ident = input.expect_ident()?;
170
171 keyword_index(ident, valid_tokens)
172 .ok_or_else(|| build_unexpected_token(&Token::Ident(ident.to_owned()), expect, valid_tokens))
173}
174
175#[derive(Debug, Clone, Copy, PartialEq)]
177#[non_exhaustive]
178pub(crate) enum CssExpectedMessage {
179 ValueOrNone,
181 OneValue,
183 OneOrTwoValues,
185 OneToFourValues,
187 BorderRadius,
189}
190
191impl CssExpectedMessage {
192 pub(crate) fn build_message(&self, token: &str, valid_tokens: String) -> String {
194 match self {
195 Self::ValueOrNone => {
196 format!("Unexpected token: {token}, expected a value of {valid_tokens} or 'none'")
197 }
198 Self::OneValue => format!("Unexpected token: {token}, expected a value of {valid_tokens}"),
199 Self::OneOrTwoValues => {
200 format!("Unexpected token: {token}, expected 1 ~ 2 values of {valid_tokens}")
201 }
202 Self::OneToFourValues => {
203 format!("Unexpected token: {token}, expected 1 ~ 4 values of {valid_tokens}")
204 }
205 Self::BorderRadius => format!(
206 "Unexpected token: {token}, expected 1 to 4 length values for width, optionally followed by '/' and 1 to 4 length values for height"
207 ),
208 }
209 }
210}
211
212pub(crate) trait FromCss<'i> {
214 fn from_css(input: &mut Parser<'i>) -> ParseResult<'i, Self>
216 where
217 Self: Sized;
218
219 const VALID_TOKENS: &'static [&'static str];
222
223 const EXPECT_MESSAGE: CssExpectedMessage = CssExpectedMessage::OneValue;
225}
226
227impl<'i, T: FromCss<'i>> FromCss<'i> for Option<T> {
228 const VALID_TOKENS: &'static [&'static str] = T::VALID_TOKENS;
230
231 const EXPECT_MESSAGE: CssExpectedMessage = CssExpectedMessage::ValueOrNone;
232
233 fn from_css(input: &mut Parser<'i>) -> ParseResult<'i, Self> {
234 let start = input.state();
235
236 if input.try_parse(|i| i.expect_ident_matching("none")).is_ok() {
237 let after_none = input.state();
238
239 if input.try_parse(Parser::expect_comma).is_err() {
240 return Ok(None);
241 }
242
243 input.reset(&start);
245
246 if let Ok(value) = input.try_parse(T::from_css) {
247 return Ok(Some(value));
248 }
249
250 input.reset(&after_none);
251
252 return Ok(None);
253 }
254
255 T::from_css(input).map(Some)
256 }
257}
258
259impl<'i> FromCss<'i> for String {
260 const VALID_TOKENS: &'static [&'static str] = &["<string>", "<custom-ident>"];
261
262 fn from_css(input: &mut Parser<'i>) -> ParseResult<'i, Self> {
263 Ok(input.expect_ident_or_string()?.to_string())
264 }
265}
266
267pub(crate) trait MakeComputed {
269 fn make_computed(&mut self, _sizing: &SizingContext) {}
271}
272
273pub(crate) trait Animatable: Sized + Clone {
274 fn interpolate(
275 &mut self,
276 from: &Self,
277 to: &Self,
278 progress: f32,
279 _sizing: &SizingContext,
280 _current_color: Color,
281 ) {
282 *self = discrete(from, to, progress);
283 }
284
285 fn interpolated(
287 from: &Self,
288 to: &Self,
289 progress: f32,
290 sizing: &SizingContext,
291 current_color: Color,
292 ) -> Self {
293 let mut value = from.clone();
294
295 value.interpolate(from, to, progress, sizing, current_color);
296 value
297 }
298
299 fn list_interpolation_strategy() -> ListInterpolationStrategy {
300 ListInterpolationStrategy::Discrete
301 }
302
303 fn neutral_value_like(_other: &Self) -> Option<Self> {
304 None
305 }
306
307 fn missing_value() -> Option<Self> {
308 None
309 }
310}
311
312pub(crate) fn discrete<T: Clone>(from: &T, to: &T, progress: f32) -> T {
314 if progress >= 0.5 {
315 to.clone()
316 } else {
317 from.clone()
318 }
319}
320
321pub(crate) enum ListInterpolationStrategy {
322 Discrete,
323 RepeatToLcm,
324 PadToLongestWithNeutral,
325}
326
327impl<T: MakeComputed> MakeComputed for Option<T> {
328 fn make_computed(&mut self, sizing: &SizingContext) {
329 if let Some(value) = self.as_mut() {
330 value.make_computed(sizing);
331 }
332 }
333}
334
335impl<T: MakeComputed> MakeComputed for Box<[T]> {
336 fn make_computed(&mut self, sizing: &SizingContext) {
337 for value in self.iter_mut() {
338 value.make_computed(sizing);
339 }
340 }
341}
342
343impl<T: MakeComputed> MakeComputed for Vec<T> {
344 fn make_computed(&mut self, sizing: &SizingContext) {
345 for value in self.iter_mut() {
346 value.make_computed(sizing);
347 }
348 }
349}
350
351impl<T: Animatable + Clone> Animatable for Option<T> {
352 fn interpolate(
353 &mut self,
354 from: &Self,
355 to: &Self,
356 progress: f32,
357 sizing: &SizingContext,
358 current_color: Color,
359 ) {
360 *self = match (from, to) {
361 (Some(start), Some(end)) => {
362 Some(T::interpolated(start, end, progress, sizing, current_color))
363 }
364 (Some(start), None) => T::missing_value().map_or_else(
365 || discrete(from, to, progress),
366 |missing| {
367 Some(T::interpolated(
368 start,
369 &missing,
370 progress,
371 sizing,
372 current_color,
373 ))
374 },
375 ),
376 (None, Some(end)) => T::missing_value().map_or_else(
377 || discrete(from, to, progress),
378 |missing| {
379 Some(T::interpolated(
380 &missing,
381 end,
382 progress,
383 sizing,
384 current_color,
385 ))
386 },
387 ),
388 (None, None) => None,
389 };
390 }
391}
392
393macro_rules! impl_list_animatable {
394 ($($list:ty),+) => {$(
395 impl<T: Animatable + Clone> Animatable for $list {
396 fn missing_value() -> Option<Self> {
397 match T::list_interpolation_strategy() {
398 ListInterpolationStrategy::Discrete => None,
399 ListInterpolationStrategy::RepeatToLcm
400 | ListInterpolationStrategy::PadToLongestWithNeutral => Some(Self::default()),
401 }
402 }
403
404 fn interpolate(
405 &mut self,
406 from: &Self,
407 to: &Self,
408 progress: f32,
409 sizing: &SizingContext,
410 current_color: Color,
411 ) {
412 *self = interpolate_list(from, to, progress, sizing, current_color)
413 .map_or_else(|| discrete(from, to, progress), Into::into);
414 }
415 }
416 )+};
417}
418
419impl_list_animatable!(Box<[T]>, Arc<[T]>, Vec<T>);
420
421const MAX_INTERPOLATED_LIST_LEN: usize = 1000;
423
424fn interpolate_list<T: Animatable + Clone, C: AsRef<[T]>>(
425 from: &C,
426 to: &C,
427 progress: f32,
428 sizing: &SizingContext,
429 current_color: Color,
430) -> Option<Vec<T>> {
431 let from = from.as_ref();
432 let to = to.as_ref();
433
434 match T::list_interpolation_strategy() {
435 ListInterpolationStrategy::Discrete => {
436 if from.len() != to.len() {
437 return None;
438 }
439
440 Some(interpolate_pairwise_list(
441 from,
442 to,
443 from.len(),
444 progress,
445 sizing,
446 current_color,
447 ))
448 }
449 ListInterpolationStrategy::RepeatToLcm => {
450 interpolate_repeated_list(from, to, progress, sizing, current_color)
451 }
452 ListInterpolationStrategy::PadToLongestWithNeutral => {
453 interpolate_neutral_padded_list(from, to, progress, sizing, current_color)
454 }
455 }
456}
457
458pub(crate) fn interpolate_repeated_list<T: Animatable + Clone>(
461 from: &[T],
462 to: &[T],
463 progress: f32,
464 sizing: &SizingContext,
465 current_color: Color,
466) -> Option<Vec<T>> {
467 if from.is_empty() || to.is_empty() {
468 return None;
469 }
470
471 let output_len = lcm(from.len(), to.len()).min(MAX_INTERPOLATED_LIST_LEN);
472
473 Some(interpolate_pairwise_list(
474 from,
475 to,
476 output_len,
477 progress,
478 sizing,
479 current_color,
480 ))
481}
482
483fn interpolate_pairwise_list<T: Animatable + Clone>(
484 from: &[T],
485 to: &[T],
486 output_len: usize,
487 progress: f32,
488 sizing: &SizingContext,
489 current_color: Color,
490) -> Vec<T> {
491 (0..output_len)
492 .map(|index| {
493 T::interpolated(
494 &from[index % from.len()],
495 &to[index % to.len()],
496 progress,
497 sizing,
498 current_color,
499 )
500 })
501 .collect()
502}
503
504fn interpolate_neutral_padded_list<T: Animatable + Clone>(
505 from: &[T],
506 to: &[T],
507 progress: f32,
508 sizing: &SizingContext,
509 current_color: Color,
510) -> Option<Vec<T>> {
511 let output_len = from.len().max(to.len());
512
513 (0..output_len)
514 .map(|index| {
515 let from_value = if index < from.len() {
516 from.get(index).cloned()
517 } else {
518 to.get(index).and_then(T::neutral_value_like)
519 }?;
520 let to_value = if index < to.len() {
521 to.get(index).cloned()
522 } else {
523 from.get(index).and_then(T::neutral_value_like)
524 }?;
525
526 Some(T::interpolated(
527 &from_value,
528 &to_value,
529 progress,
530 sizing,
531 current_color,
532 ))
533 })
534 .collect()
535}
536
537pub trait ToCss {
539 const LIST_SEPARATOR: &'static str = ", ";
541
542 const EMPTY_LIST_KEYWORD: Option<&'static str> = None;
544
545 fn to_css<W: fmt::Write>(&self, dest: &mut W) -> fmt::Result;
547
548 fn to_css_string(&self) -> String {
550 let mut css = String::new();
551 let _ = self.to_css(&mut css);
552 css
553 }
554}
555
556impl<T: ToCss + ?Sized> ToCss for &T {
557 fn to_css<W: fmt::Write>(&self, dest: &mut W) -> fmt::Result {
558 (*self).to_css(dest)
559 }
560}
561
562impl<T: ToCss> ToCss for Option<T> {
563 fn to_css<W: fmt::Write>(&self, dest: &mut W) -> fmt::Result {
564 match self {
565 Some(v) => v.to_css(dest),
566 None => dest.write_str("none"),
567 }
568 }
569}
570
571pub(crate) fn write_keywords<'k, W: fmt::Write>(
573 dest: &mut W,
574 keywords: impl IntoIterator<Item = &'k str>,
575 empty: &str,
576) -> fmt::Result {
577 let mut keywords = keywords.into_iter().peekable();
578
579 if keywords.peek().is_none() {
580 return dest.write_str(empty);
581 }
582
583 for (index, keyword) in keywords.enumerate() {
584 if index > 0 {
585 dest.write_char(' ')?;
586 }
587
588 dest.write_str(keyword)?;
589 }
590
591 Ok(())
592}
593
594fn write_css_list<W: fmt::Write, T: ToCss>(items: &[T], dest: &mut W) -> fmt::Result {
595 if items.is_empty() {
596 return match T::EMPTY_LIST_KEYWORD {
597 Some(keyword) => dest.write_str(keyword),
598 None => Ok(()),
599 };
600 }
601
602 for (i, item) in items.iter().enumerate() {
603 if i > 0 {
604 dest.write_str(T::LIST_SEPARATOR)?;
605 }
606 item.to_css(dest)?;
607 }
608 Ok(())
609}
610
611impl<T: ToCss> ToCss for Box<[T]> {
612 fn to_css<W: fmt::Write>(&self, dest: &mut W) -> fmt::Result {
613 write_css_list(self, dest)
614 }
615}
616
617impl<T: ToCss> ToCss for Arc<[T]> {
618 fn to_css<W: fmt::Write>(&self, dest: &mut W) -> fmt::Result {
619 write_css_list(self, dest)
620 }
621}
622
623impl<T: ToCss> ToCss for Vec<T> {
624 fn to_css<W: fmt::Write>(&self, dest: &mut W) -> fmt::Result {
625 write_css_list(self, dest)
626 }
627}
628
629impl ToCss for f32 {
630 fn to_css<W: fmt::Write>(&self, dest: &mut W) -> fmt::Result {
631 write!(dest, "{self}")
632 }
633}
634
635impl ToCss for u32 {
636 fn to_css<W: fmt::Write>(&self, dest: &mut W) -> fmt::Result {
637 write!(dest, "{self}")
638 }
639}
640
641impl MakeComputed for u32 {}
642impl Animatable for u32 {}
643
644impl<'i> FromCss<'i> for u32 {
645 const VALID_TOKENS: &'static [&'static str] = &["<integer>"];
646
647 fn from_css(input: &mut Parser<'i>) -> ParseResult<'i, Self> {
648 let value = input.expect_integer()?;
649 if value < 0 {
650 return Err(CssParseError::from_basic_kind(
651 BasicParseErrorKind::QualifiedRuleInvalid,
652 ));
653 }
654 Ok(value as u32)
655 }
656}
657
658impl ToCss for i32 {
659 fn to_css<W: fmt::Write>(&self, dest: &mut W) -> fmt::Result {
660 write!(dest, "{self}")
661 }
662}
663
664impl ToCss for String {
665 fn to_css<W: fmt::Write>(&self, dest: &mut W) -> fmt::Result {
666 dest.write_str(self)
667 }
668}
669
670impl ToCss for Arc<str> {
671 fn to_css<W: fmt::Write>(&self, dest: &mut W) -> fmt::Result {
672 dest.write_str(self)
673 }
674}
675
676macro_rules! impl_comma_list_from_css {
678 ($list:ty, $elem:ty) => {
679 $crate::style::properties::impl_comma_list_from_css!($list, $elem, <$elem>::VALID_TOKENS);
680 };
681 ($list:ty, $elem:ty, $valid:expr) => {
682 impl<'i> $crate::style::FromCss<'i> for $list {
683 fn from_css(input: &mut cssparser::Parser<'i>) -> $crate::style::ParseResult<'i, Self> {
684 input
685 .parse_comma_separated(<$elem as $crate::style::FromCss>::from_css)
686 .map(Vec::into_boxed_slice)
687 }
688
689 const VALID_TOKENS: &'static [&'static str] = $valid;
690 }
691 };
692}
693
694pub(crate) use impl_comma_list_from_css;
695
696macro_rules! impl_css_enum {
698 (
699 $enum_type:ty,
700 $($canonical:literal $(| $alias:literal)* => $variant:path),* $(,)?
701 ) => {
702 $crate::style::properties::impl_css_enum!(@impl
703 $crate::style::properties::parse_enum_keyword,
704 default,
705 $enum_type,
706 $($canonical $(| $alias)* => $variant),*
707 );
708 };
709
710 (
711 custom_animatable $enum_type:ty,
712 $($canonical:literal $(| $alias:literal)* => $variant:path),* $(,)?
713 ) => {
714 $crate::style::properties::impl_css_enum!(@impl
715 $crate::style::properties::parse_enum_keyword,
716 custom,
717 $enum_type,
718 $($canonical $(| $alias)* => $variant),*
719 );
720 };
721
722 (ident $enum_type:ty, $($canonical:literal $(| $alias:literal)* => $variant:path),* $(,)?) => {
723 $crate::style::properties::impl_css_enum!(@impl
724 $crate::style::properties::parse_ident_enum_keyword,
725 default,
726 $enum_type,
727 $($canonical $(| $alias)* => $variant),*
728 );
729 };
730
731 (ident keyword $enum_type:ty, $($canonical:literal $(| $alias:literal)* => $variant:path),* $(,)?) => {
732 $crate::style::properties::impl_css_enum!(
733 ident $enum_type,
734 $($canonical $(| $alias)* => $variant),*
735 );
736
737 impl $enum_type {
738 fn from_keyword(ident: &str) -> Option<Self> {
739 $crate::style::keyword_index(
740 ident,
741 <Self as $crate::style::properties::FromCss>::VALID_TOKENS,
742 )
743 .map(|index| Self::KEYWORD_VALUES[index])
744 }
745 }
746 };
747
748 (@impl $parser:path, $animatable:ident, $enum_type:ty, $($canonical:literal $(| $alias:literal)* => $variant:path),* $(,)?) => {
749 impl $enum_type {
750 const KEYWORD_VALUES: &'static [Self] = &[
751 $($variant $(, $crate::style::properties::impl_css_enum!(@value $variant, $alias))*),*
752 ];
753 }
754
755 impl crate::style::MakeComputed for $enum_type {}
756
757 $crate::style::properties::impl_css_enum!(@animatable $animatable $enum_type);
758
759 impl<'i> crate::style::FromCss<'i> for $enum_type {
760 const VALID_TOKENS: &'static [&'static str] = &[
761 $(
762 $canonical
763 $(, $alias)*
764 ),*
765 ];
766
767 fn from_css(input: &mut cssparser::Parser<'i>) -> crate::style::ParseResult<'i, Self> {
768 let index = $parser(
769 input,
770 Self::VALID_TOKENS,
771 <Self as crate::style::FromCss>::EXPECT_MESSAGE,
772 )?;
773
774 Ok(Self::KEYWORD_VALUES[index])
775 }
776 }
777
778 impl crate::style::properties::ToCss for $enum_type {
779 fn to_css<W: std::fmt::Write>(&self, dest: &mut W) -> std::fmt::Result {
780 match self {
781 $(
782 $variant => dest.write_str($canonical),
783 )*
784 }
785 }
786 }
787
788 };
789
790 (@animatable default $enum_type:ty) => {
791 impl $crate::style::Animatable for $enum_type {}
792 };
793
794 (@animatable custom $enum_type:ty) => {};
795
796 (@value $variant:path, $alias:literal) => {
797 $variant
798 };
799}
800
801pub(crate) use impl_css_enum;
802
803macro_rules! declare_box_alignment_enum_impl {
806 (
807 $enum_type:ty,
808 safe { $($safe_css:literal => $base_variant:ident / $safe_variant:ident $(/ $unsafe_variant:ident)?),+ $(,)? },
809 plain { $($plain_css:literal => $plain_variant:ident),* $(,)? }
810 ) => {
811 impl crate::style::MakeComputed for $enum_type {}
812
813 impl<'i> crate::style::FromCss<'i> for $enum_type {
814 const VALID_TOKENS: &'static [&'static str] = &[
815 $($plain_css,)*
816 $($safe_css,)*
817 "safe",
818 "unsafe",
819 ];
820
821 fn from_css(input: &mut cssparser::Parser<'i>) -> crate::style::ParseResult<'i, Self> {
822 let mut overflow_position = None;
823
824 loop {
825 let token = input.next()?;
826
827 let cssparser::Token::Ident(ident) = token else {
828 return Err($crate::style::unexpected_token!(token));
829 };
830
831 cssparser::match_ignore_ascii_case! {&ident,
832 "safe" | "unsafe" => {
833 if overflow_position.replace(ident.eq_ignore_ascii_case("safe")).is_some() {
834 return Err($crate::style::unexpected_token!(token));
835 }
836 },
837 $($safe_css => return Ok(match overflow_position {
838 Some(true) => Self::$safe_variant,
839 $(Some(false) => Self::$unsafe_variant,)?
840 _ => Self::$base_variant,
841 }),)*
842 $($plain_css => return if overflow_position.unwrap_or(false) {
843 Err($crate::style::unexpected_token!(token))
844 } else {
845 Ok(Self::$plain_variant)
846 },)*
847 _ => return Err($crate::style::unexpected_token!(token)),
848 }
849 }
850 }
851 }
852
853 impl crate::style::properties::ToCss for $enum_type {
854 fn to_css<W: std::fmt::Write>(&self, dest: &mut W) -> std::fmt::Result {
855 match self {
856 $(Self::$plain_variant => dest.write_str($plain_css),)*
857 $(Self::$base_variant => dest.write_str($safe_css),)*
858 $(Self::$safe_variant => {
859 dest.write_str("safe ")?;
860 dest.write_str($safe_css)
861 })*
862 $($(Self::$unsafe_variant => {
863 dest.write_str("unsafe ")?;
864 dest.write_str($safe_css)
865 })?)*
866 }
867 }
868 }
869
870 };
871}
872
873pub(crate) use declare_box_alignment_enum_impl;
874
875#[cfg(test)]
876mod tests {
877 use super::*;
878 use crate::{
879 style::{BackgroundRepeat, BackgroundRepeatStyle},
880 viewport::Viewport,
881 };
882
883 fn repeats(len: usize, style: BackgroundRepeatStyle) -> Vec<BackgroundRepeat> {
884 vec![BackgroundRepeat(style, style); len]
885 }
886
887 fn interpolated(from_len: usize, to_len: usize) -> Option<Vec<BackgroundRepeat>> {
888 let sizing = SizingContext::builder()
889 .viewport(Viewport::default())
890 .build();
891
892 interpolate_list(
893 &repeats(from_len, BackgroundRepeatStyle::Repeat),
894 &repeats(to_len, BackgroundRepeatStyle::NoRepeat),
895 0.75,
896 &sizing,
897 Color([0, 0, 0, 255]),
898 )
899 }
900
901 #[test]
902 fn repeat_to_lcm_interpolates_under_the_cap() {
903 assert_eq!(interpolated(2, 3).map(|values| values.len()), Some(6));
904 }
905
906 #[test]
907 fn repeat_to_lcm_clamps_past_the_cap() {
908 assert_eq!(
909 interpolated(61, 67).map(|values| values.len()),
910 Some(MAX_INTERPOLATED_LIST_LEN)
911 );
912 }
913}