takumi 0.73.0

Render your React components to images.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
//! Style properties and related types for the takumi styling system.
//!
//! This module contains CSS-like properties including layout properties,
//! typography settings, positioning, and visual effects.

mod animation;
mod aspect_ratio;
mod background;
mod background_image;
mod background_position;
mod background_repeat;
mod background_size;
mod blend_mode;
mod border;
mod box_shadow;
mod clip_path;
mod color;
mod conic_gradient;
mod filter;
mod flex;
mod flex_grow;
mod font_family;
mod font_feature_settings;
mod font_size;
mod font_stretch;
mod font_style;
mod font_synthesis;
mod font_variation_settings;
mod font_weight;
mod gradient_utils;
mod grid;
mod length;
mod line_clamp;
mod line_height;
mod linear_gradient;
mod noise_v1;
mod overflow;
mod overflow_wrap;
mod percentage_number;
mod radial_gradient;
mod sides;
mod space_pair;
mod text_decoration;
mod text_overflow;
mod text_shadow;
mod text_stroke;
mod text_wrap;
mod transform;
mod vertical_align;
mod white_space;
mod word_break;

pub use animation::*;
pub use aspect_ratio::*;
pub use background::*;
pub use background_image::*;
pub use background_position::*;
pub use background_repeat::*;
pub use background_size::*;
pub use blend_mode::*;
pub use border::*;
pub use box_shadow::*;
pub use clip_path::*;
pub use color::*;
pub use conic_gradient::*;
pub use filter::*;
pub use flex::*;
pub use flex_grow::*;
pub use font_family::*;
pub use font_feature_settings::*;
pub use font_size::*;
pub use font_stretch::*;
pub use font_style::*;
pub use font_synthesis::*;
pub use font_variation_settings::*;
pub use font_weight::*;
pub(crate) use gradient_utils::{
  GradientOverlayTile, compute_overlay_bounds, overlay_gradient_tile_fast_normal_unconstrained,
};
pub use grid::*;
pub use length::*;
pub use line_clamp::*;
pub use line_height::*;
pub use linear_gradient::*;
pub use noise_v1::*;
pub use overflow::*;
pub use overflow_wrap::*;
pub use percentage_number::*;
pub use radial_gradient::*;
pub use sides::*;
pub use space_pair::*;
pub use text_decoration::*;
pub use text_overflow::*;
pub use text_shadow::*;
pub use text_stroke::*;
pub use text_wrap::*;
pub use transform::*;
pub use vertical_align::*;
pub use white_space::*;
pub use word_break::*;

use cssparser::{
  ParseError, ParseErrorKind, Parser, ParserInput, SourceLocation, ToCss, Token,
  match_ignore_ascii_case,
};
use fast_image_resize::ResizeAlg;
use image::imageops::FilterType;
use parley::Alignment;
use std::borrow::Cow;
use zeno::Join;

use crate::layout::style::tw::TailwindPropertyParser;
use crate::rendering::Sizing;

/// Parser result type alias for CSS property parsers.
pub type ParseResult<'i, T> = Result<T, ParseError<'i, Cow<'i, str>>>;

/// Enum representing CSS tokens.
pub enum CssToken {
  /// A CSS keyword.
  Keyword(&'static str),
  /// A CSS token without the < and > wrappers.
  Token(&'static str),
}

impl std::fmt::Display for CssToken {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    match self {
      CssToken::Keyword(keyword) => write!(f, "'{}'", keyword),
      CssToken::Token(token) => write!(f, "<{}>", token),
    }
  }
}

/// Trait for types that can be parsed from CSS.
pub trait FromCss<'i> {
  /// Parses the type from a [`Parser`] instance.
  fn from_css(input: &mut Parser<'i, '_>) -> ParseResult<'i, Self>
  where
    Self: Sized;

  /// Helper function to parse the type from a string.
  fn from_str(source: &'i str) -> ParseResult<'i, Self>
  where
    Self: Sized,
  {
    let mut input = ParserInput::new(source);
    let mut parser = Parser::new(&mut input);

    Self::from_css(&mut parser)
  }

  /// Returns the list of valid CSS tokens for this type.
  fn valid_tokens() -> &'static [CssToken];

  /// Returns a message to be used in error messages.
  fn expect_message() -> Cow<'static, str> {
    Cow::Owned(format!(
      "a value of {}",
      merge_enum_values(Self::valid_tokens())
    ))
  }

  /// Creates a parse error for an unexpected token.
  fn unexpected_token_error(
    location: SourceLocation,
    token: &Token,
  ) -> ParseError<'i, Cow<'i, str>> {
    #[cfg(feature = "detailed_css_error")]
    {
      create_unexpected_token_error(location, token, Self::expect_message())
    }
    #[cfg(not(feature = "detailed_css_error"))]
    {
      create_unexpected_token_error(location, token)
    }
  }
}

impl<'i, T: FromCss<'i>> FromCss<'i> for Option<T> {
  fn valid_tokens() -> &'static [CssToken] {
    // 'none' is intentionally omitted and applied in `expect_message`
    T::valid_tokens()
  }

  fn expect_message() -> Cow<'static, str> {
    Cow::Owned(format!("{} or 'none'", T::expect_message()))
  }

  fn from_css(input: &mut Parser<'i, '_>) -> ParseResult<'i, Self> {
    if input.try_parse(|i| i.expect_ident_matching("none")).is_ok() {
      return Ok(None);
    }

    T::from_css(input).map(Some)
  }
}

/// Converts a parsed/inherited value into a computed value for the current node context.
pub(crate) trait MakeComputed {
  /// Default no-op for types that do not need computed-value normalization.
  fn make_computed(&mut self, _sizing: &Sizing) {}
}

pub(crate) trait Animatable: Sized + Clone {
  fn interpolate(
    &mut self,
    from: &Self,
    to: &Self,
    progress: f32,
    _sizing: &Sizing,
    _current_color: Color,
  ) {
    *self = if progress >= 1.0 {
      to.clone()
    } else {
      from.clone()
    };
  }

  fn list_interpolation_strategy() -> ListInterpolationStrategy {
    ListInterpolationStrategy::Discrete
  }

  fn neutral_value_like(_other: &Self) -> Option<Self> {
    None
  }

  fn missing_value() -> Option<Self> {
    None
  }
}

pub(crate) fn lerp(lhs: f32, rhs: f32, progress: f32) -> f32 {
  lhs + (rhs - lhs) * progress
}

pub(crate) enum ListInterpolationStrategy {
  Discrete,
  RepeatToLcm,
  PadToLongestWithNeutral,
}

impl<T: MakeComputed> MakeComputed for Option<T> {
  fn make_computed(&mut self, sizing: &Sizing) {
    if let Some(value) = self.as_mut() {
      value.make_computed(sizing);
    }
  }
}

impl<T: MakeComputed> MakeComputed for Box<[T]> {
  fn make_computed(&mut self, sizing: &Sizing) {
    for value in self.iter_mut() {
      value.make_computed(sizing);
    }
  }
}

impl<T: MakeComputed> MakeComputed for Vec<T> {
  fn make_computed(&mut self, sizing: &Sizing) {
    for value in self.iter_mut() {
      value.make_computed(sizing);
    }
  }
}

pub(crate) fn next_is_comma<'i>(input: &mut Parser<'i, '_>) -> bool {
  let state = input.state();
  let is_comma = input.expect_comma().is_ok();
  input.reset(&state);
  is_comma
}

impl<T: Animatable + Clone> Animatable for Option<T> {
  fn interpolate(
    &mut self,
    from: &Self,
    to: &Self,
    progress: f32,
    sizing: &Sizing,
    current_color: Color,
  ) {
    *self = match (from, to) {
      (Some(from), Some(to)) => {
        let mut value = from.clone();
        value.interpolate(from, to, progress, sizing, current_color);
        Some(value)
      }
      (Some(from), None) => T::missing_value().map_or_else(
        || {
          if progress >= 0.5 {
            None
          } else {
            Some(from.clone())
          }
        },
        |missing| {
          let mut value = from.clone();
          value.interpolate(from, &missing, progress, sizing, current_color);
          Some(value)
        },
      ),
      (None, Some(to)) => T::missing_value().map_or_else(
        || {
          if progress >= 0.5 {
            Some(to.clone())
          } else {
            None
          }
        },
        |missing| {
          let mut value = missing.clone();
          value.interpolate(&missing, to, progress, sizing, current_color);
          Some(value)
        },
      ),
      (None, None) => None,
    };
  }
}

impl<T: Animatable + Clone> Animatable for Box<[T]> {
  fn missing_value() -> Option<Self> {
    match T::list_interpolation_strategy() {
      ListInterpolationStrategy::Discrete => None,
      ListInterpolationStrategy::RepeatToLcm
      | ListInterpolationStrategy::PadToLongestWithNeutral => Some(Box::default()),
    }
  }

  fn interpolate(
    &mut self,
    from: &Self,
    to: &Self,
    progress: f32,
    sizing: &Sizing,
    current_color: Color,
  ) {
    *self = interpolate_list(
      from,
      to,
      progress,
      sizing,
      current_color,
      Vec::into_boxed_slice,
    )
    .unwrap_or_else(|| {
      if progress >= 1.0 {
        to.clone()
      } else {
        from.clone()
      }
    });
  }
}

impl<T: Animatable + Clone> Animatable for Vec<T> {
  fn missing_value() -> Option<Self> {
    match T::list_interpolation_strategy() {
      ListInterpolationStrategy::Discrete => None,
      ListInterpolationStrategy::RepeatToLcm
      | ListInterpolationStrategy::PadToLongestWithNeutral => Some(Vec::new()),
    }
  }

  fn interpolate(
    &mut self,
    from: &Self,
    to: &Self,
    progress: f32,
    sizing: &Sizing,
    current_color: Color,
  ) {
    *self = interpolate_list(from, to, progress, sizing, current_color, |values| values)
      .unwrap_or_else(|| {
        if progress >= 1.0 {
          to.clone()
        } else {
          from.clone()
        }
      });
  }
}

fn interpolate_list<T: Animatable + Clone, C: AsRef<[T]>, O>(
  from: &C,
  to: &C,
  progress: f32,
  sizing: &Sizing,
  current_color: Color,
  build: impl FnOnce(Vec<T>) -> O,
) -> Option<O> {
  let from = from.as_ref();
  let to = to.as_ref();

  let values = match T::list_interpolation_strategy() {
    ListInterpolationStrategy::Discrete => {
      if from.len() != to.len() {
        return None;
      }
      interpolate_pairwise_list(from, to, from.len(), progress, sizing, current_color)
    }
    ListInterpolationStrategy::RepeatToLcm => {
      if from.is_empty() || to.is_empty() {
        return None;
      }
      interpolate_pairwise_list(
        from,
        to,
        lcm(from.len(), to.len()),
        progress,
        sizing,
        current_color,
      )
    }
    ListInterpolationStrategy::PadToLongestWithNeutral => {
      interpolate_neutral_padded_list(from, to, progress, sizing, current_color)?
    }
  };

  Some(build(values))
}

fn interpolate_pairwise_list<T: Animatable + Clone>(
  from: &[T],
  to: &[T],
  output_len: usize,
  progress: f32,
  sizing: &Sizing,
  current_color: Color,
) -> Vec<T> {
  (0..output_len)
    .map(|index| {
      let from_value = &from[index % from.len()];
      let to_value = &to[index % to.len()];
      let mut value = from_value.clone();
      value.interpolate(from_value, to_value, progress, sizing, current_color);
      value
    })
    .collect()
}

fn interpolate_neutral_padded_list<T: Animatable + Clone>(
  from: &[T],
  to: &[T],
  progress: f32,
  sizing: &Sizing,
  current_color: Color,
) -> Option<Vec<T>> {
  let output_len = from.len().max(to.len());

  (0..output_len)
    .map(|index| {
      let from_value = if index < from.len() {
        from.get(index).cloned()
      } else {
        to.get(index).and_then(T::neutral_value_like)
      }?;
      let to_value = if index < to.len() {
        to.get(index).cloned()
      } else {
        from.get(index).and_then(T::neutral_value_like)
      }?;

      let mut value = from_value.clone();
      value.interpolate(&from_value, &to_value, progress, sizing, current_color);
      Some(value)
    })
    .collect()
}

fn gcd(lhs: usize, rhs: usize) -> usize {
  let mut lhs = lhs;
  let mut rhs = rhs;
  while rhs != 0 {
    let remainder = lhs % rhs;
    lhs = rhs;
    rhs = remainder;
  }
  lhs
}

fn lcm(lhs: usize, rhs: usize) -> usize {
  lhs / gcd(lhs, rhs) * rhs
}

impl<T: Animatable + Copy> Animatable for SpacePair<T> {
  fn interpolate(
    &mut self,
    from: &Self,
    to: &Self,
    progress: f32,
    sizing: &Sizing,
    current_color: Color,
  ) {
    self
      .x
      .interpolate(&from.x, &to.x, progress, sizing, current_color);
    self
      .y
      .interpolate(&from.y, &to.y, progress, sizing, current_color);
  }
}

impl<T: Animatable + Copy> Animatable for Sides<T> {
  fn interpolate(
    &mut self,
    from: &Self,
    to: &Self,
    progress: f32,
    sizing: &Sizing,
    current_color: Color,
  ) {
    for (index, value) in self.0.iter_mut().enumerate() {
      value.interpolate(
        &from.0[index],
        &to.0[index],
        progress,
        sizing,
        current_color,
      );
    }
  }
}

fn create_unexpected_token_error<'i>(
  location: SourceLocation,
  token: &Token,
  #[cfg(feature = "detailed_css_error")] expect_message: Cow<'static, str>,
) -> ParseError<'i, Cow<'i, str>> {
  #[cfg(feature = "detailed_css_error")]
  let message = format!(
    "unexpected token: {}, {}.",
    token.to_css_string(),
    expect_message
  );
  #[cfg(not(feature = "detailed_css_error"))]
  let message = format!("unexpected token: {}.", token.to_css_string());

  ParseError {
    location,
    kind: ParseErrorKind::Custom(Cow::Owned(message)),
  }
}

/// Helper function to merge enum values into a human-readable format.
/// - `["fill"]` → `"'fill'"`
/// - `["fill", "contain"]` → `"'fill' or 'contain'"`
/// - `["fill", "contain", "cover"]` → `"'fill', 'contain' or 'cover'"`
pub(crate) fn merge_enum_values(values: &[CssToken]) -> String {
  match values.len() {
    0 => String::new(),
    1 => values[0].to_string(),
    2 => format!("{} or {}", values[0], values[1]),
    _ => {
      let all_but_last = values[..values.len() - 1]
        .iter()
        .map(ToString::to_string)
        .collect::<Vec<_>>()
        .join(", ");
      format!("{} or {}", all_but_last, values[values.len() - 1])
    }
  }
}

/// Macro to implement From trait for Taffy enum conversions.
macro_rules! impl_from_taffy_enum {
  ($from_ty:ty, $to_ty:ty, $($variant:ident),*) => {
    impl From<$from_ty> for $to_ty {
      fn from(value: $from_ty) -> Self {
        match value {
          $(<$from_ty>::$variant => <$to_ty>::$variant,)*
        }
      }
    }
  };
}

/// Declares a CSS enum parser with automatic value list generation.
macro_rules! declare_enum_from_css_impl {
  (
    $enum_type:ty,
    $($css_value:expr => $variant:expr),* $(,)?
  ) => {
    impl crate::layout::style::MakeComputed for $enum_type {}

    impl<'i> crate::layout::style::FromCss<'i> for $enum_type {
      fn valid_tokens() -> &'static [crate::layout::style::CssToken] {
        &[$(crate::layout::style::CssToken::Keyword($css_value)),*]
      }

      fn from_css(input: &mut cssparser::Parser<'i, '_>) -> crate::layout::style::ParseResult<'i, Self> {
        let location = input.current_source_location();
        let token = input.next()?;

        let cssparser::Token::Ident(ident) = token else {
          return Err(Self::unexpected_token_error(location, &token));
        };

        cssparser::match_ignore_ascii_case! {&ident,
          $(
            $css_value => Ok($variant),
          )*
          _ => Err(Self::unexpected_token_error(location, &token)),
        }
      }
    }
  };
}

pub(crate) use declare_enum_from_css_impl;

/// Defines how an image should be resized to fit its container.
///
/// Similar to CSS object-fit property.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum ObjectFit {
  /// The replaced content is sized to fill the element's content box exactly, without maintaining aspect ratio
  #[default]
  Fill,
  /// The replaced content is scaled to maintain its aspect ratio while fitting within the element's content box
  Contain,
  /// The replaced content is sized to maintain its aspect ratio while filling the element's entire content box
  Cover,
  /// The content is sized as if none or contain were specified, whichever would result in a smaller concrete object size
  ScaleDown,
  /// The replaced content is not resized and maintains its intrinsic dimensions
  None,
}

declare_enum_from_css_impl!(
  ObjectFit,
  "fill" => ObjectFit::Fill,
  "contain" => ObjectFit::Contain,
  "cover" => ObjectFit::Cover,
  "scale-down" => ObjectFit::ScaleDown,
  "none" => ObjectFit::None
);

impl TailwindPropertyParser for ObjectFit {
  fn parse_tw(token: &str) -> Option<Self> {
    Self::from_str(token).ok()
  }
}

/// Defines how the background is clipped.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum BackgroundClip {
  /// The background extends to the outside edge of the border
  #[default]
  BorderBox,
  /// The background extends to the outside edge of the padding
  PaddingBox,
  /// The background extends to the inside edge of the content box
  ContentBox,
  /// The background extends to the outside edge of the text
  Text,
  /// The background extends to the outside edge of the border area
  BorderArea,
}

declare_enum_from_css_impl!(
  BackgroundClip,
  "border-box" => BackgroundClip::BorderBox,
  "padding-box" => BackgroundClip::PaddingBox,
  "content-box" => BackgroundClip::ContentBox,
  "text" => BackgroundClip::Text,
  "border-area" => BackgroundClip::BorderArea
);

impl TailwindPropertyParser for BackgroundClip {
  fn parse_tw(token: &str) -> Option<Self> {
    match_ignore_ascii_case! {token,
      "border" => Some(BackgroundClip::BorderBox),
      "padding" => Some(BackgroundClip::PaddingBox),
      "content" => Some(BackgroundClip::ContentBox),
      "text" => Some(BackgroundClip::Text),
      _ => None,
    }
  }
}

/// Represents the CSS `border-radius` property, supporting elliptical corners.
///
/// Each corner has independent horizontal and vertical radii, allowing for both circular and elliptical shapes.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct BorderRadius(pub Sides<SpacePair<LengthDefaultsToZero>>);

impl From<f32> for BorderRadius {
  fn from(value: f32) -> Self {
    Self(Sides(
      [SpacePair::from_pair(Length::Px(value), Length::Px(value)); 4],
    ))
  }
}

impl MakeComputed for BorderRadius {
  fn make_computed(&mut self, sizing: &Sizing) {
    self.0.make_computed(sizing);
  }
}

impl Animatable for BorderRadius {
  fn interpolate(
    &mut self,
    from: &Self,
    to: &Self,
    progress: f32,
    sizing: &Sizing,
    current_color: Color,
  ) {
    self
      .0
      .interpolate(&from.0, &to.0, progress, sizing, current_color);
  }
}

impl Animatable for Box<BorderRadius> {
  fn interpolate(
    &mut self,
    from: &Self,
    to: &Self,
    progress: f32,
    sizing: &Sizing,
    current_color: Color,
  ) {
    let mut value = **from;
    value.interpolate(&**from, to.as_ref(), progress, sizing, current_color);
    **self = value;
  }
}

impl<'i> FromCss<'i> for Box<BorderRadius> {
  fn from_css(input: &mut Parser<'i, '_>) -> ParseResult<'i, Self> {
    let value = BorderRadius::from_css(input)?;
    Ok(Box::new(value))
  }

  fn expect_message() -> Cow<'static, str> {
    BorderRadius::expect_message()
  }

  fn valid_tokens() -> &'static [CssToken] {
    BorderRadius::valid_tokens()
  }
}

impl<'i> FromCss<'i> for BorderRadius {
  fn from_css(input: &mut Parser<'i, '_>) -> ParseResult<'i, Self> {
    let widths: Sides<LengthDefaultsToZero> = Sides::from_css(input)?;

    let heights = if input.try_parse(|input| input.expect_delim('/')).is_ok() {
      Sides::from_css(input)?
    } else {
      widths
    };

    Ok(BorderRadius(Sides([
      SpacePair::from_pair(widths.0[0], heights.0[0]),
      SpacePair::from_pair(widths.0[1], heights.0[1]),
      SpacePair::from_pair(widths.0[2], heights.0[2]),
      SpacePair::from_pair(widths.0[3], heights.0[3]),
    ])))
  }

  fn expect_message() -> Cow<'static, str> {
    "1 to 4 length values for width, optionally followed by '/' and 1 to 4 length values for height"
      .into()
  }

  fn valid_tokens() -> &'static [CssToken] {
    &[CssToken::Token("length")]
  }
}

/// Defines how the width and height of an element are calculated.
///
/// This enum determines whether the width and height properties include padding and border, or just the content area.
#[derive(Default, Debug, Clone, Copy, PartialEq)]
pub enum BoxSizing {
  /// The width and height properties include padding and border, but not the content area
  ContentBox,
  /// The width and height properties include the content area, but not padding and border
  #[default]
  BorderBox,
}

declare_enum_from_css_impl!(
  BoxSizing,
  "content-box" => BoxSizing::ContentBox,
  "border-box" => BoxSizing::BorderBox
);

impl_from_taffy_enum!(BoxSizing, taffy::BoxSizing, ContentBox, BorderBox);

/// Text alignment options for text rendering.
///
/// Corresponds to CSS text-align property values.
#[derive(Default, Debug, Clone, Copy, PartialEq)]
pub enum TextAlign {
  /// Aligns inline content to the left edge of the line box
  Left,
  /// Aligns inline content to the right edge of the line box
  Right,
  /// Centers inline content within the line box
  Center,
  /// Expands inline content to fill the entire line box
  Justify,
  /// Aligns inline content to the start edge of the line box (language-dependent)
  #[default]
  Start,
  /// Aligns inline content to the end edge of the line box (language-dependent)
  End,
}

declare_enum_from_css_impl!(
  TextAlign,
  "left" => TextAlign::Left,
  "right" => TextAlign::Right,
  "center" => TextAlign::Center,
  "justify" => TextAlign::Justify,
  "start" => TextAlign::Start,
  "end" => TextAlign::End
);

impl TailwindPropertyParser for TextAlign {
  fn parse_tw(token: &str) -> Option<Self> {
    Self::from_str(token).ok()
  }
}

impl_from_taffy_enum!(
  TextAlign, Alignment, Left, Right, Center, Justify, Start, End
);

/// Defines whether an element creates a new stacking context.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum Isolation {
  /// The element creates a new stacking context.
  Isolate,
  /// Determine by other properties.
  #[default]
  Auto,
}

declare_enum_from_css_impl!(
  Isolation,
  "isolate" => Isolation::Isolate,
  "auto" => Isolation::Auto
);

/// Defines whether an element is visible.
///
/// This controls whether an element is rendered, but unlike `display: none`,
/// it still takes up space in the layout.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum Visibility {
  /// The element is visible.
  #[default]
  Visible,
  /// The element is invisible (not rendered) but still takes up space.
  Hidden,
}

declare_enum_from_css_impl!(
  Visibility,
  "visible" => Visibility::Visible,
  "hidden" => Visibility::Hidden
);

/// Defines how the corners of text strokes are rendered.
#[derive(Default, Debug, Clone, Copy, PartialEq)]
pub enum LineJoin {
  /// The corners are sharp and pointed.
  #[default]
  Miter,
  /// The corners are rounded.
  Round,
  /// The corners are cut off at a 45-degree angle.
  Bevel,
}

declare_enum_from_css_impl!(
  LineJoin,
  "miter" => LineJoin::Miter,
  "round" => LineJoin::Round,
  "bevel" => LineJoin::Bevel
);

impl From<LineJoin> for Join {
  fn from(value: LineJoin) -> Self {
    match value {
      LineJoin::Miter => Join::Miter,
      LineJoin::Round => Join::Round,
      LineJoin::Bevel => Join::Bevel,
    }
  }
}

impl TailwindPropertyParser for LineJoin {
  fn parse_tw(token: &str) -> Option<Self> {
    Self::from_str(token).ok()
  }
}

/// Defines the positioning method for an element.
///
/// This enum determines how an element is positioned within its containing element.
#[derive(Default, Debug, Clone, Copy, PartialEq)]
pub enum Position {
  /// The element is positioned according to the normal flow of the document.
  /// Offsets (top, right, bottom, left) have no effect.
  #[default]
  Relative,
  /// The element is removed from the normal document flow and positioned relative to its nearest positioned ancestor.
  /// Offsets (top, right, bottom, left) specify the distance from the ancestor.
  Absolute,
}

declare_enum_from_css_impl!(
  Position,
  "relative" => Position::Relative,
  "absolute" => Position::Absolute
);

impl_from_taffy_enum!(Position, taffy::Position, Relative, Absolute);

/// Defines the direction of flex items within a flex container.
///
/// This enum determines how flex items are laid out along the main axis.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum FlexDirection {
  /// Items are laid out in the same direction as the text direction (left-to-right for English)
  #[default]
  Row,
  /// Items are laid out perpendicular to the text direction (top-to-bottom)
  Column,
  /// Items are laid out in the opposite direction to the text direction (right-to-left for English)
  RowReverse,
  /// Items are laid out opposite to the column direction (bottom-to-top)
  ColumnReverse,
}

declare_enum_from_css_impl!(
  FlexDirection,
  "row" => FlexDirection::Row,
  "column" => FlexDirection::Column,
  "row-reverse" => FlexDirection::RowReverse,
  "column-reverse" => FlexDirection::ColumnReverse
);

impl_from_taffy_enum!(
  FlexDirection,
  taffy::FlexDirection,
  Row,
  Column,
  RowReverse,
  ColumnReverse
);

/// Defines how flex items are aligned along the main axis.
///
/// This enum determines how space is distributed between and around flex items
/// along the main axis of the flex container.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum JustifyContent {
  /// The items are distributed using the normal flow of the flex container.
  #[default]
  Normal,
  /// Items are packed toward the start of the line.
  Start,
  /// Items are packed toward the end of the line.
  End,
  /// Items are packed toward the flex container's main-start side.
  /// For flex containers with flex_direction RowReverse or ColumnReverse, this is equivalent
  /// to End. In all other cases it is equivalent to Start.
  FlexStart,
  /// Items are packed toward the flex container's main-end side.
  /// For flex containers with flex_direction RowReverse or ColumnReverse, this is equivalent
  /// to Start. In all other cases it is equivalent to End.
  FlexEnd,
  /// Items are packed toward the center of the line.
  Center,
  /// Items are stretched to fill the container (only applies to flex containers)
  Stretch,
  /// Items are evenly distributed in the line; first item is on the start line,
  /// last item on the end line.
  SpaceBetween,
  /// Items are evenly distributed in the line with equal space around them.
  SpaceEvenly,
  /// Items are evenly distributed in the line; first item is on the start line,
  /// last item on the end line, and the space between items is twice the space
  /// between the start/end items and the container edges.
  SpaceAround,
}

declare_enum_from_css_impl!(
  JustifyContent,
  "normal" => JustifyContent::Normal,
  "start" => JustifyContent::Start,
  "end" => JustifyContent::End,
  "flex-start" => JustifyContent::FlexStart,
  "flex-end" => JustifyContent::FlexEnd,
  "center" => JustifyContent::Center,
  "stretch" => JustifyContent::Stretch,
  "space-between" => JustifyContent::SpaceBetween,
  "space-around" => JustifyContent::SpaceAround,
  "space-evenly" => JustifyContent::SpaceEvenly
);

impl TailwindPropertyParser for JustifyContent {
  fn parse_tw(token: &str) -> Option<Self> {
    match token {
      "between" => Some(JustifyContent::SpaceBetween),
      "around" => Some(JustifyContent::SpaceAround),
      "evenly" => Some(JustifyContent::SpaceEvenly),
      _ => Self::from_str(token).ok(),
    }
  }
}

impl From<JustifyContent> for Option<taffy::JustifyContent> {
  fn from(value: JustifyContent) -> Self {
    match value {
      JustifyContent::Normal => None,
      JustifyContent::Start => Some(taffy::JustifyContent::Start),
      JustifyContent::End => Some(taffy::JustifyContent::End),
      JustifyContent::FlexStart => Some(taffy::JustifyContent::FlexStart),
      JustifyContent::FlexEnd => Some(taffy::JustifyContent::FlexEnd),
      JustifyContent::Center => Some(taffy::JustifyContent::Center),
      JustifyContent::Stretch => Some(taffy::JustifyContent::Stretch),
      JustifyContent::SpaceBetween => Some(taffy::JustifyContent::SpaceBetween),
      JustifyContent::SpaceAround => Some(taffy::JustifyContent::SpaceAround),
      JustifyContent::SpaceEvenly => Some(taffy::JustifyContent::SpaceEvenly),
    }
  }
}

/// This enum determines the layout algorithm used for the children of a node.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum Display {
  /// The element is not displayed
  None,
  /// The element generates a flex container and its children follow the flexbox layout algorithm
  #[default]
  Flex,
  /// The element generates an inline-level flex container
  InlineFlex,
  /// The element generates a grid container and its children follow the CSS Grid layout algorithm
  Grid,
  /// The element generates an inline-level grid container
  InlineGrid,
  /// The element generates an inline container and its children follow the inline layout algorithm
  Inline,
  /// The element creates a block container and its children follow the block layout algorithm
  Block,
  /// The element generates an inline-level block container
  InlineBlock,
}

declare_enum_from_css_impl!(
  Display,
  "none" => Display::None,
  "flex" => Display::Flex,
  "inline-flex" => Display::InlineFlex,
  "grid" => Display::Grid,
  "inline-grid" => Display::InlineGrid,
  "inline" => Display::Inline,
  "block" => Display::Block,
  "inline-block" => Display::InlineBlock
);

impl Display {
  /// Returns true if the display creates an inline formatting context.
  pub fn is_inline(&self) -> bool {
    *self == Display::Inline
  }

  /// Returns true if the display participates in the inline flow as an atomic box.
  pub fn is_inline_level(&self) -> bool {
    matches!(
      self,
      Display::Inline | Display::InlineBlock | Display::InlineFlex | Display::InlineGrid
    )
  }

  /// Returns true if the display makes the children blockified (e.g., flex or grid).
  pub fn should_blockify_children(&self) -> bool {
    matches!(
      self,
      Display::Flex | Display::InlineFlex | Display::Grid | Display::InlineGrid
    )
  }

  /// Cast the display to block level.
  pub fn as_blockified(self) -> Self {
    match self {
      Display::Inline => Display::Block,
      Display::InlineBlock => Display::Block,
      Display::InlineFlex => Display::Flex,
      Display::InlineGrid => Display::Grid,
      _ => self,
    }
  }

  /// Mutate the display to be block level.
  pub fn blockify(&mut self) {
    *self = self.as_blockified();
  }
}

impl From<Display> for taffy::Display {
  fn from(value: Display) -> Self {
    match value {
      Display::Flex => taffy::Display::Flex,
      Display::InlineFlex => taffy::Display::Flex,
      Display::Grid => taffy::Display::Grid,
      Display::InlineGrid => taffy::Display::Grid,
      Display::Block => taffy::Display::Block,
      Display::InlineBlock => taffy::Display::Block,
      Display::None => taffy::Display::None,
      Display::Inline => unreachable!("Inline node should not be inserted into taffy context"),
    }
  }
}

/// Defines how flex items are aligned along the cross axis.
///
/// This enum determines how items are aligned within the flex container
/// along the cross axis (perpendicular to the main axis).
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum AlignItems {
  /// The items are distributed using the normal flow of the flex container.
  #[default]
  Normal,
  /// Items are aligned to the start of the line in the cross axis
  Start,
  /// Items are aligned to the end of the line in the cross axis
  End,
  /// Items are aligned to the flex container's cross-start side
  FlexStart,
  /// Items are aligned to the flex container's cross-end side
  FlexEnd,
  /// Items are centered in the cross axis
  Center,
  /// Items are aligned so that their baselines align
  Baseline,
  /// Items are stretched to fill the container in the cross axis
  Stretch,
}

declare_enum_from_css_impl!(
  AlignItems,
  "normal" => AlignItems::Normal,
  "start" => AlignItems::Start,
  "end" => AlignItems::End,
  "flex-start" => AlignItems::FlexStart,
  "flex-end" => AlignItems::FlexEnd,
  "center" => AlignItems::Center,
  "baseline" => AlignItems::Baseline,
  "stretch" => AlignItems::Stretch
);

impl TailwindPropertyParser for AlignItems {
  fn parse_tw(token: &str) -> Option<Self> {
    Self::from_str(token).ok()
  }
}

impl From<AlignItems> for Option<taffy::AlignItems> {
  fn from(value: AlignItems) -> Self {
    match value {
      AlignItems::Normal => None,
      AlignItems::Start => Some(taffy::AlignItems::Start),
      AlignItems::End => Some(taffy::AlignItems::End),
      AlignItems::FlexStart => Some(taffy::AlignItems::FlexStart),
      AlignItems::FlexEnd => Some(taffy::AlignItems::FlexEnd),
      AlignItems::Center => Some(taffy::AlignItems::Center),
      AlignItems::Baseline => Some(taffy::AlignItems::Baseline),
      AlignItems::Stretch => Some(taffy::AlignItems::Stretch),
    }
  }
}

/// Defines how flex items should wrap.
///
/// This enum determines how flex items should wrap within the flex container.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum FlexWrap {
  /// Flex items will all be displayed in a single line, shrinking as needed
  #[default]
  NoWrap,
  /// Flex items will wrap onto multiple lines, with new lines stacking in the flex direction
  Wrap,
  /// Flex items will wrap onto multiple lines, with new lines stacking in the reverse flex direction
  WrapReverse,
}

declare_enum_from_css_impl!(
  FlexWrap,
  "nowrap" => FlexWrap::NoWrap,
  "wrap" => FlexWrap::Wrap,
  "wrap-reverse" => FlexWrap::WrapReverse
);

impl_from_taffy_enum!(FlexWrap, taffy::FlexWrap, NoWrap, Wrap, WrapReverse);

/// Controls text case transformation when rendering.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum TextTransform {
  /// Do not transform text
  #[default]
  None,
  /// Transform all characters to uppercase
  Uppercase,
  /// Transform all characters to lowercase
  Lowercase,
  /// Uppercase the first letter of each word
  Capitalize,
}

declare_enum_from_css_impl!(
  TextTransform,
  "none" => TextTransform::None,
  "uppercase" => TextTransform::Uppercase,
  "lowercase" => TextTransform::Lowercase,
  "capitalize" => TextTransform::Capitalize
);

/// Controls whether text decoration should skip descenders.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum TextDecorationSkipInk {
  /// Skip descenders and glyph interiors when painting decorations.
  #[default]
  Auto,
  /// Do not skip ink; paint decoration continuously.
  None,
}

declare_enum_from_css_impl!(
  TextDecorationSkipInk,
  "auto" => TextDecorationSkipInk::Auto,
  "none" => TextDecorationSkipInk::None
);

/// Controls how whitespace should be collapsed.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum WhiteSpaceCollapse {
  /// Preserve whitespace as is—spaces and tabs are not collapsed.
  Preserve,
  /// Collapse whitespace—spaces and tabs are collapsed.
  #[default]
  Collapse,
  /// Preserve spaces and remove breaks.
  PreserveSpaces,
  /// Preserve breaks and collapse spaces.
  PreserveBreaks,
}

declare_enum_from_css_impl!(
  WhiteSpaceCollapse,
  "preserve" => WhiteSpaceCollapse::Preserve,
  "collapse" => WhiteSpaceCollapse::Collapse,
  "preserve-spaces" => WhiteSpaceCollapse::PreserveSpaces,
  "preserve-breaks" => WhiteSpaceCollapse::PreserveBreaks,
);

/// Defines how images should be scaled when rendered.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum ImageScalingAlgorithm {
  /// The image is scaled using Catmull-Rom interpolation.
  /// This is balanced for speed and quality.
  #[default]
  Auto,
  /// The image is scaled using Lanczos3 resampling.
  /// This provides high-quality scaling but may be slower.
  Smooth,
  /// The image is scaled using nearest neighbor interpolation,
  /// which is suitable for pixel art or images where sharp edges are desired.
  Pixelated,
}

declare_enum_from_css_impl!(
  ImageScalingAlgorithm,
  "auto" => ImageScalingAlgorithm::Auto,
  "smooth" => ImageScalingAlgorithm::Smooth,
  "pixelated" => ImageScalingAlgorithm::Pixelated
);

#[cfg(feature = "svg")]
impl From<ImageScalingAlgorithm> for resvg::usvg::ImageRendering {
  fn from(algorithm: ImageScalingAlgorithm) -> Self {
    match algorithm {
      ImageScalingAlgorithm::Auto => resvg::usvg::ImageRendering::default(),
      ImageScalingAlgorithm::Smooth => resvg::usvg::ImageRendering::Smooth,
      ImageScalingAlgorithm::Pixelated => resvg::usvg::ImageRendering::Pixelated,
    }
  }
}

/// Represents border style options.
#[derive(Debug, Default, Clone, Copy, PartialEq)]
pub enum BorderStyle {
  /// No border will be rendered.
  #[default]
  None,
  /// Solid border style.
  Solid,
}

declare_enum_from_css_impl!(
  BorderStyle,
  "none" => BorderStyle::None,
  "solid" => BorderStyle::Solid,
);

impl TailwindPropertyParser for BorderStyle {
  fn parse_tw(token: &str) -> Option<Self> {
    Self::from_str(token).ok()
  }
}

impl From<ImageScalingAlgorithm> for FilterType {
  fn from(algorithm: ImageScalingAlgorithm) -> Self {
    match algorithm {
      ImageScalingAlgorithm::Auto => FilterType::CatmullRom,
      ImageScalingAlgorithm::Smooth => FilterType::Lanczos3,
      ImageScalingAlgorithm::Pixelated => FilterType::Nearest,
    }
  }
}

impl From<ImageScalingAlgorithm> for ResizeAlg {
  fn from(algorithm: ImageScalingAlgorithm) -> Self {
    match algorithm {
      ImageScalingAlgorithm::Auto => {
        ResizeAlg::Convolution(fast_image_resize::FilterType::CatmullRom)
      }
      ImageScalingAlgorithm::Smooth => {
        ResizeAlg::Convolution(fast_image_resize::FilterType::Lanczos3)
      }
      ImageScalingAlgorithm::Pixelated => ResizeAlg::Nearest,
    }
  }
}