bevy_extended_ui 1.7.0

Create simply ui's with css and html for bevy.
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
pub mod components;
pub mod paint;
pub mod parser;

use crate::io::CssAsset;
use crate::styles::components::UiStyle;
use bevy::prelude::*;
use bevy::text::{FontSize, LineHeight};
use bevy::window::SystemCursorIcon;
use std::cmp::PartialEq;
use std::collections::{HashMap, HashSet};

// ==================================================
//                     Css Styling
// ==================================================

/// Resource that tracks existing CSS IDs to ensure uniqueness.
#[derive(Resource, Default)]
pub struct ExistingCssIDs(pub HashSet<String>);

/// Component representing the tag name of an element (e.g., "div", "span").
#[derive(Component, Reflect, Debug, Clone, Deref, DerefMut)]
#[reflect(Component)]
pub struct TagName(pub String);

/// Component representing one or more CSS classes applied to an element.
#[derive(Component, Reflect, Debug, Clone, PartialEq, Eq)]
#[reflect(Component)]
pub struct CssClass(pub Vec<String>);

/// Component representing the CSS ID of an element.
#[derive(Component, Reflect, Debug, Clone, PartialEq, Eq)]
#[reflect(Component)]
pub struct CssID(pub String);

/// Component that stores one or more CSS asset handles for an entity.
#[derive(Component, Reflect, Debug, Clone, Default, PartialEq)]
#[reflect(Component)]
pub struct CssSource(pub Vec<Handle<CssAsset>>);

impl CssSource {
    /// Creates a CSS source from a single asset path.
    pub fn from_path(asset_server: &AssetServer, path: &str) -> Self {
        Self(vec![asset_server.load::<CssAsset>(path.to_string())])
    }

    /// Appends another CSS asset path to the source list.
    pub fn push_path(&mut self, asset_server: &AssetServer, path: &str) {
        self.0.push(asset_server.load::<CssAsset>(path.to_string()));
    }

    /// Creates a CSS source from multiple asset paths.
    pub fn from_paths(
        asset_server: &AssetServer,
        paths: impl IntoIterator<Item = impl Into<String>>,
    ) -> Self {
        Self(
            paths
                .into_iter()
                .map(|p| asset_server.load::<CssAsset>(p.into()))
                .collect(),
        )
    }
}

/// Represents the border-radius of a rectangle with individual corner values.
#[derive(Reflect, Default, Clone, PartialEq, Debug)]
pub struct Radius {
    pub top_left: Val,
    pub top_right: Val,
    pub bottom_left: Val,
    pub bottom_right: Val,
}

impl Radius {
    /// Creates a `Radius` where all corners have the same radius value.
    pub fn all(val: Val) -> Self {
        Self {
            top_left: val,
            top_right: val,
            bottom_left: val,
            bottom_right: val,
        }
    }
}

/// Defines the background style including color, optional image, and optional gradient.
#[derive(Reflect, Debug, Clone, PartialEq)]
pub struct Background {
    pub color: Color,
    pub image: Option<String>,
    pub gradient: Option<LinearGradient>,
}

impl Default for Background {
    /// Creates a default `Background` with transparent color and no image.
    fn default() -> Self {
        Self {
            color: Color::NONE,
            image: None,
            gradient: None,
        }
    }
}

/// Defines how a background image is positioned.
#[derive(Reflect, Debug, Clone, PartialEq)]
pub struct BackgroundPosition {
    pub x: BackgroundPositionValue,
    pub y: BackgroundPositionValue,
}

impl Default for BackgroundPosition {
    /// Handles `default` in the extended UI workflow.
    fn default() -> Self {
        Self {
            x: BackgroundPositionValue::Percent(0.0),
            y: BackgroundPositionValue::Percent(0.0),
        }
    }
}

/// Represents a single background position axis value.
#[derive(Reflect, Debug, Clone, PartialEq)]
pub enum BackgroundPositionValue {
    /// Variant `Percent`.
    Percent(f32),
    /// Variant `Px`.
    Px(f32),
}

/// Defines how a background image is sized.
#[derive(Reflect, Debug, Clone, PartialEq)]
pub enum BackgroundSize {
    /// Variant `Auto`.
    Auto,
    /// Variant `Cover`.
    Cover,
    /// Variant `Contain`.
    Contain,
    /// Variant `Explicit`.
    Explicit(BackgroundSizeValue, BackgroundSizeValue),
}

impl Default for BackgroundSize {
    /// Handles `default` in the extended UI workflow.
    fn default() -> Self {
        Self::Auto
    }
}

/// Represents a single background size axis value.
#[derive(Reflect, Debug, Clone, PartialEq)]
pub enum BackgroundSizeValue {
    /// Variant `Auto`.
    Auto,
    /// Variant `Percent`.
    Percent(f32),
    /// Variant `Px`.
    Px(f32),
}

/// Defines how the background image is attached.
#[derive(Reflect, Debug, Clone, PartialEq)]
pub enum BackgroundAttachment {
    /// Variant `Scroll`.
    Scroll,
    /// Variant `Fixed`.
    Fixed,
    /// Variant `Local`.
    Local,
}

impl Default for BackgroundAttachment {
    /// Handles `default` in the extended UI workflow.
    fn default() -> Self {
        Self::Scroll
    }
}

/// Defines supported backdrop-filter effects.
#[derive(Reflect, Debug, Clone, PartialEq)]
pub enum BackdropFilter {
    /// Variant `Blur`.
    Blur(f32),
}

/// Represents a parsed CSS `linear-gradient(...)` definition.
#[derive(Reflect, Debug, Clone, PartialEq)]
pub struct LinearGradient {
    pub angle: f32,
    pub stops: Vec<GradientStop>,
}

/// Represents a single color stop in a linear gradient.
#[derive(Reflect, Debug, Clone, PartialEq)]
pub struct GradientStop {
    pub color: Color,
    pub position: Option<GradientStopPosition>,
}

/// Represents a gradient stop position.
#[derive(Reflect, Debug, Clone, PartialEq)]
pub enum GradientStopPosition {
    /// Variant `Percent`.
    Percent(f32),
    /// Variant `Px`.
    Px(f32),
}

/// Constants for common font weight values.
#[derive(Reflect, Debug, Clone, PartialEq, Copy)]
pub enum FontWeight {
    /// Variant `Thin`.
    Thin = 100,
    /// Variant `ExtraLight`.
    ExtraLight = 200,
    /// Variant `Light`.
    Light = 300,
    /// Variant `Normal`.
    Normal = 400,
    /// Variant `Medium`.
    Medium = 500,
    /// Variant `SemiBold`.
    SemiBold = 600,
    /// Variant `Bold`.
    Bold = 700,
    /// Variant `ExtraBold`.
    ExtraBold = 800,
    /// Variant `Black`.
    Black = 900,
}

impl FontWeight {
    /// Parses CSS-like font-weight names (case-insensitive)
    ///
    /// Examples:
    /// - "bold" -> Bold
    /// - "normal" -> Normal
    /// - "semibold" / "semi-bold" -> SemiBold
    pub fn from_name(name: &str) -> Option<Self> {
        let n = name.trim().to_ascii_lowercase();

        match n.as_str() {
            "thin" => Some(Self::Thin),
            "extralight" | "extra-light" => Some(Self::ExtraLight),
            "light" => Some(Self::Light),
            "normal" | "regular" => Some(Self::Normal),
            "medium" => Some(Self::Medium),
            "semibold" | "semi-bold" => Some(Self::SemiBold),
            "bold" => Some(Self::Bold),
            "extrabold" | "extra-bold" => Some(Self::ExtraBold),
            "black" | "heavy" => Some(Self::Black),
            _ => None,
        }
    }

    /// Parses numeric CSS font-weight values
    ///
    /// Examples:
    /// - 700 -> Bold
    /// - 650 -> SemiBold (nearest lower)
    /// - 999 -> Black
    pub fn from_number(value: u16) -> Option<Self> {
        Some(match value {
            100 => Self::Thin,
            200 => Self::ExtraLight,
            300 => Self::Light,
            400 => Self::Normal,
            500 => Self::Medium,
            600 => Self::SemiBold,
            700 => Self::Bold,
            800 => Self::ExtraBold,
            900 => Self::Black,
            _ => Self::Normal,
        })
    }

    /// Returns the numeric weight (100–900)
    pub fn as_number(self) -> u16 {
        self as u16
    }
}

/// Placement of an icon relative to text.
#[derive(Reflect, Debug, Clone, Copy, PartialEq, Eq)]
pub enum IconPlace {
    /// Variant `Left`.
    Left,
    /// Variant `Right`.
    Right,
}

impl Default for IconPlace {
    /// Returns the default icon placement (`Right`).
    fn default() -> Self {
        IconPlace::Right
    }
}

/// Resolves a Bevy [`FontSize`] to logical pixels for layout estimates.
pub fn font_size_to_px(font_size: FontSize, rem_size: Option<f32>) -> f32 {
    font_size.eval(Vec2::ZERO, rem_size.unwrap_or(1.0))
}

/// Defines the available `CalcUnit` variants for this part of the UI runtime.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CalcUnit {
    /// Variant `None`.
    None,
    /// Variant `Px`.
    Px,
    /// Variant `Percent`.
    Percent,
    /// Variant `Rem`.
    Rem,
    /// Variant `Vw`.
    Vw,
    /// Variant `Vh`.
    Vh,
    /// Variant `VMin`.
    VMin,
    /// Variant `VMax`.
    VMax,
    /// Variant `Deg`.
    Deg,
    /// Variant `Rad`.
    Rad,
    /// Variant `Turn`.
    Turn,
    /// Variant `Fr`.
    Fr,
}

/// Represents the `CalcValue` data structure used by the extended UI system.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct CalcValue {
    pub value: f32,
    pub unit: CalcUnit,
}

impl CalcValue {
    /// Handles `new` in the extended UI workflow.
    ///
    /// # Examples
    ///
    /// ```rust
    /// // Call `new` with values from your app state and world context.
    /// ```
    pub fn new(value: f32, unit: CalcUnit) -> Self {
        Self { value, unit }
    }

    /// Handles `to_length_px` in the extended UI workflow.
    fn to_length_px(self, ctx: CalcContext) -> Option<f32> {
        match self.unit {
            CalcUnit::Px => Some(self.value),
            CalcUnit::Percent => Some(ctx.base * self.value / 100.0),
            CalcUnit::Vw => Some(ctx.viewport.x * self.value / 100.0),
            CalcUnit::Vh => Some(ctx.viewport.y * self.value / 100.0),
            CalcUnit::VMin => Some(ctx.viewport.x.min(ctx.viewport.y) * self.value / 100.0),
            CalcUnit::VMax => Some(ctx.viewport.x.max(ctx.viewport.y) * self.value / 100.0),
            CalcUnit::None if self.value == 0.0 => Some(0.0),
            _ => None,
        }
    }

    /// Handles `to_angle_radians` in the extended UI workflow.
    fn to_angle_radians(self) -> Option<f32> {
        match self.unit {
            CalcUnit::None => Some(self.value),
            CalcUnit::Deg => Some(self.value.to_radians()),
            CalcUnit::Rad => Some(self.value),
            CalcUnit::Turn => Some(self.value * std::f32::consts::TAU),
            _ => None,
        }
    }
}

/// Defines the available `CalcExpr` variants for this part of the UI runtime.
#[derive(Debug, Clone, PartialEq)]
pub enum CalcExpr {
    /// Variant `Value`.
    Value(CalcValue),
    /// Variant `Add`.
    Add(Box<CalcExpr>, Box<CalcExpr>),
    /// Variant `Sub`.
    Sub(Box<CalcExpr>, Box<CalcExpr>),
    /// Variant `Mul`.
    Mul(Box<CalcExpr>, Box<CalcExpr>),
    /// Variant `Div`.
    Div(Box<CalcExpr>, Box<CalcExpr>),
    /// Variant `Min`.
    Min(Vec<CalcExpr>),
    /// Variant `Max`.
    Max(Vec<CalcExpr>),
    /// Variant `Sin`.
    Sin(Box<CalcExpr>),
}

/// Represents the `CalcContext` data structure used by the extended UI system.
#[derive(Debug, Clone, Copy)]
pub struct CalcContext {
    pub base: f32,
    pub viewport: Vec2,
}

impl CalcExpr {
    /// Handles `eval_length` in the extended UI workflow.
    ///
    /// # Examples
    ///
    /// ```rust
    /// // Call `eval_length` with values from your app state and world context.
    /// ```
    pub fn eval_length(&self, ctx: CalcContext) -> Option<f32> {
        match self {
            CalcExpr::Value(value) => value.to_length_px(ctx),
            CalcExpr::Add(a, b) => Some(a.eval_length(ctx)? + b.eval_length(ctx)?),
            CalcExpr::Sub(a, b) => Some(a.eval_length(ctx)? - b.eval_length(ctx)?),
            CalcExpr::Mul(a, b) => {
                let left_len = a.eval_length(ctx);
                let right_len = b.eval_length(ctx);
                let left_num = a.eval_unitless();
                let right_num = b.eval_unitless();

                if let (Some(len), Some(num)) = (left_len, right_num) {
                    return Some(len * num);
                }
                if let (Some(num), Some(len)) = (left_num, right_len) {
                    return Some(len * num);
                }
                None
            }
            CalcExpr::Div(a, b) => {
                let denom = b.eval_unitless()?;
                if denom == 0.0 {
                    return None;
                }
                Some(a.eval_length(ctx)? / denom)
            }
            CalcExpr::Min(values) => {
                let mut best: Option<f32> = None;
                for value in values {
                    let resolved = value.eval_length(ctx)?;
                    best = Some(match best {
                        Some(current) => current.min(resolved),
                        None => resolved,
                    });
                }
                best
            }
            CalcExpr::Max(values) => {
                let mut best: Option<f32> = None;
                for value in values {
                    let resolved = value.eval_length(ctx)?;
                    best = Some(match best {
                        Some(current) => current.max(resolved),
                        None => resolved,
                    });
                }
                best
            }
            CalcExpr::Sin(inner) => {
                let angle = inner.eval_angle_radians()?;
                Some(angle.sin())
            }
        }
    }

    /// Handles `eval_unitless` in the extended UI workflow.
    ///
    /// # Examples
    ///
    /// ```rust
    /// // Call `eval_unitless` with values from your app state and world context.
    /// ```
    pub fn eval_unitless(&self) -> Option<f32> {
        match self {
            CalcExpr::Value(value) if value.unit == CalcUnit::None => Some(value.value),
            CalcExpr::Add(a, b) => Some(a.eval_unitless()? + b.eval_unitless()?),
            CalcExpr::Sub(a, b) => Some(a.eval_unitless()? - b.eval_unitless()?),
            CalcExpr::Mul(a, b) => Some(a.eval_unitless()? * b.eval_unitless()?),
            CalcExpr::Div(a, b) => {
                let denom = b.eval_unitless()?;
                if denom == 0.0 {
                    return None;
                }
                Some(a.eval_unitless()? / denom)
            }
            CalcExpr::Min(values) => {
                let mut best: Option<f32> = None;
                for value in values {
                    let resolved = value.eval_unitless()?;
                    best = Some(match best {
                        Some(current) => current.min(resolved),
                        None => resolved,
                    });
                }
                best
            }
            CalcExpr::Max(values) => {
                let mut best: Option<f32> = None;
                for value in values {
                    let resolved = value.eval_unitless()?;
                    best = Some(match best {
                        Some(current) => current.max(resolved),
                        None => resolved,
                    });
                }
                best
            }
            CalcExpr::Sin(inner) => {
                let angle = inner.eval_angle_radians()?;
                Some(angle.sin())
            }
            _ => None,
        }
    }

    /// Handles `eval_angle_radians` in the extended UI workflow.
    fn eval_angle_radians(&self) -> Option<f32> {
        match self {
            CalcExpr::Value(value) => value.to_angle_radians(),
            CalcExpr::Add(a, b) => Some(a.eval_angle_radians()? + b.eval_angle_radians()?),
            CalcExpr::Sub(a, b) => Some(a.eval_angle_radians()? - b.eval_angle_radians()?),
            CalcExpr::Mul(a, b) => {
                let left = a.eval_angle_radians();
                let right = b.eval_angle_radians();
                let left_num = a.eval_unitless();
                let right_num = b.eval_unitless();

                if let (Some(angle), Some(num)) = (left, right_num) {
                    return Some(angle * num);
                }
                if let (Some(num), Some(angle)) = (left_num, right) {
                    return Some(angle * num);
                }
                None
            }
            CalcExpr::Div(a, b) => {
                let denom = b.eval_unitless()?;
                if denom == 0.0 {
                    return None;
                }
                Some(a.eval_angle_radians()? / denom)
            }
            CalcExpr::Min(values) => {
                let mut best: Option<f32> = None;
                for value in values {
                    let resolved = value.eval_angle_radians()?;
                    best = Some(match best {
                        Some(current) => current.min(resolved),
                        None => resolved,
                    });
                }
                best
            }
            CalcExpr::Max(values) => {
                let mut best: Option<f32> = None;
                for value in values {
                    let resolved = value.eval_angle_radians()?;
                    best = Some(match best {
                        Some(current) => current.max(resolved),
                        None => resolved,
                    });
                }
                best
            }
            CalcExpr::Sin(inner) => {
                let angle = inner.eval_angle_radians()?;
                Some(angle.sin())
            }
        }
    }
}

/// Font family name wrapper for style parsing.
#[derive(Reflect, Debug, Clone, PartialEq)]
pub struct FontFamily(pub String);

/// Timing functions for transitions and animations.
#[derive(Reflect, Debug, Clone, PartialEq, Eq, Copy)]
pub enum TransitionTiming {
    /// Variant `Linear`.
    Linear,
    /// Variant `Ease`.
    Ease,
    /// Variant `EaseIn`.
    EaseIn,
    /// Variant `EaseOut`.
    EaseOut,
    /// Variant `EaseInOut`.
    EaseInOut,
}

impl TransitionTiming {
    /// Applies the timing function to a normalized progress value.
    pub fn apply(self, t: f32) -> f32 {
        match self {
            TransitionTiming::Linear => t,
            TransitionTiming::Ease => t * t * (3.0 - 2.0 * t),
            TransitionTiming::EaseIn => t * t,
            TransitionTiming::EaseOut => 1.0 - (1.0 - t).powi(2),
            TransitionTiming::EaseInOut => {
                if t < 0.5 {
                    2.0 * t * t
                } else {
                    1.0 - (-2.0 * t + 2.0).powi(2) / 2.0
                }
            }
        }
    }

    /// Parses a timing function name into a variant.
    pub fn from_name(value: &str) -> Option<Self> {
        match value.trim().to_ascii_lowercase().as_str() {
            "linear" => Some(Self::Linear),
            "ease" => Some(Self::Ease),
            "ease-in" => Some(Self::EaseIn),
            "ease-out" => Some(Self::EaseOut),
            "ease-in-out" => Some(Self::EaseInOut),
            _ => None,
        }
    }
}

impl Default for TransitionTiming {
    /// Returns the default timing function.
    fn default() -> Self {
        TransitionTiming::EaseInOut
    }
}

/// Direction modes for CSS animations.
#[derive(Reflect, Debug, Clone, PartialEq, Eq, Copy)]
pub enum AnimationDirection {
    /// Variant `Normal`.
    Normal,
    /// Variant `Reverse`.
    Reverse,
    /// Variant `Alternate`.
    Alternate,
    /// Variant `AlternateReverse`.
    AlternateReverse,
}

impl AnimationDirection {
    /// Parses an animation-direction name into a variant.
    pub fn from_name(value: &str) -> Option<Self> {
        match value.trim().to_ascii_lowercase().as_str() {
            "normal" => Some(Self::Normal),
            "reverse" => Some(Self::Reverse),
            "alternate" => Some(Self::Alternate),
            "alternate-reverse" => Some(Self::AlternateReverse),
            _ => None,
        }
    }
}

impl Default for AnimationDirection {
    /// Returns the default animation direction.
    fn default() -> Self {
        AnimationDirection::Normal
    }
}

/// Properties that can be targeted by transitions.
#[derive(Reflect, Debug, Clone, PartialEq, Eq, Copy)]
pub enum TransitionProperty {
    /// Variant `All`.
    All,
    /// Variant `Color`.
    Color,
    /// Variant `Background`.
    Background,
    /// Variant `Transform`.
    Transform,
}

impl Default for TransitionProperty {
    /// Returns the default transition property selection.
    fn default() -> Self {
        TransitionProperty::All
    }
}

/// Parsed animation specification from CSS.
#[derive(Reflect, Debug, Clone, PartialEq)]
pub struct AnimationSpec {
    pub name: String,
    pub duration: f32,
    pub delay: f32,
    pub timing: TransitionTiming,
    pub iterations: Option<f32>,
    pub direction: AnimationDirection,
}

impl Default for AnimationSpec {
    /// Creates a default animation specification.
    fn default() -> Self {
        Self {
            name: String::new(),
            duration: 0.0,
            delay: 0.0,
            timing: TransitionTiming::Ease,
            iterations: Some(1.0),
            direction: AnimationDirection::Normal,
        }
    }
}

/// Parsed transition specification from CSS.
#[derive(Reflect, Debug, Clone, PartialEq)]
pub struct TransitionSpec {
    pub properties: Vec<TransitionProperty>,
    pub duration: f32,
    pub delay: f32,
    pub timing: TransitionTiming,
}

impl Default for TransitionSpec {
    /// Creates a default transition specification.
    fn default() -> Self {
        Self {
            properties: vec![TransitionProperty::All],
            duration: 0.3,
            delay: 0.0,
            timing: TransitionTiming::EaseInOut,
        }
    }
}

/// Parsed keyframe entry for a CSS animation.
#[derive(Reflect, Default, Debug, Clone, PartialEq)]
pub struct AnimationKeyframe {
    pub progress: f32,
    pub style: Style,
}

/// Parsed CSS result for styles and keyframes.
#[derive(Reflect, Default, Debug, Clone, PartialEq)]
pub struct ParsedCss {
    pub styles: HashMap<String, StylePair>,
    pub keyframes: HashMap<String, Vec<AnimationKeyframe>>,
}

/// Breakpoint/media condition expression used for CSS `@media` rules.
#[derive(Debug, Clone, PartialEq)]
pub enum MediaQueryCondition {
    /// Variant `Always`.
    Always,
    /// Variant `Never`.
    Never,
    /// Variant `MinWidth`.
    MinWidth(f32),
    /// Variant `MaxWidth`.
    MaxWidth(f32),
    /// Variant `Width`.
    Width(f32),
    /// Variant `MinHeight`.
    MinHeight(f32),
    /// Variant `MaxHeight`.
    MaxHeight(f32),
    /// Variant `Height`.
    Height(f32),
    /// Variant `OrientationLandscape`.
    OrientationLandscape,
    /// Variant `OrientationPortrait`.
    OrientationPortrait,
    /// Variant `Not`.
    Not(Box<MediaQueryCondition>),
    /// Variant `And`.
    And(Vec<MediaQueryCondition>),
    /// Variant `Or`.
    Or(Vec<MediaQueryCondition>),
}

impl MediaQueryCondition {
    /// Handles `compound_cache_key` in the extended UI workflow.
    fn compound_cache_key(prefix: &str, parts: &[MediaQueryCondition]) -> String {
        let mut key = String::from(prefix);
        key.push('(');
        for (idx, part) in parts.iter().enumerate() {
            if idx > 0 {
                key.push(',');
            }
            key.push_str(&part.cache_key());
        }
        key.push(')');
        key
    }

    /// Returns true if the condition matches the given viewport size.
    pub fn matches_viewport(&self, viewport: Vec2) -> bool {
        const EPSILON: f32 = 0.5;

        match self {
            MediaQueryCondition::Always => true,
            MediaQueryCondition::Never => false,
            MediaQueryCondition::MinWidth(value) => viewport.x + EPSILON >= *value,
            MediaQueryCondition::MaxWidth(value) => viewport.x - EPSILON <= *value,
            MediaQueryCondition::Width(value) => (viewport.x - *value).abs() <= EPSILON,
            MediaQueryCondition::MinHeight(value) => viewport.y + EPSILON >= *value,
            MediaQueryCondition::MaxHeight(value) => viewport.y - EPSILON <= *value,
            MediaQueryCondition::Height(value) => (viewport.y - *value).abs() <= EPSILON,
            MediaQueryCondition::OrientationLandscape => viewport.x >= viewport.y,
            MediaQueryCondition::OrientationPortrait => viewport.y > viewport.x,
            MediaQueryCondition::Not(inner) => !inner.matches_viewport(viewport),
            MediaQueryCondition::And(parts) => parts
                .iter()
                .all(|condition| condition.matches_viewport(viewport)),
            MediaQueryCondition::Or(parts) => parts
                .iter()
                .any(|condition| condition.matches_viewport(viewport)),
        }
    }

    /// Produces a deterministic key used to separate media-scoped selector entries.
    pub fn cache_key(&self) -> String {
        match self {
            MediaQueryCondition::Always => "always".to_string(),
            MediaQueryCondition::Never => "never".to_string(),
            MediaQueryCondition::MinWidth(value) => format!("minw:{value:.3}"),
            MediaQueryCondition::MaxWidth(value) => format!("maxw:{value:.3}"),
            MediaQueryCondition::Width(value) => format!("w:{value:.3}"),
            MediaQueryCondition::MinHeight(value) => format!("minh:{value:.3}"),
            MediaQueryCondition::MaxHeight(value) => format!("maxh:{value:.3}"),
            MediaQueryCondition::Height(value) => format!("h:{value:.3}"),
            MediaQueryCondition::OrientationLandscape => "orientation:landscape".to_string(),
            MediaQueryCondition::OrientationPortrait => "orientation:portrait".to_string(),
            MediaQueryCondition::Not(inner) => format!("not({})", inner.cache_key()),
            MediaQueryCondition::And(parts) => Self::compound_cache_key("and", parts),
            MediaQueryCondition::Or(parts) => Self::compound_cache_key("or", parts),
        }
    }
}

/// Pair of normal and !important styles with origin tracking.
#[derive(Reflect, Default, Debug, Clone, PartialEq)]
pub struct StylePair {
    pub important: Style,
    pub normal: Style,
    pub origin: usize,
    pub selector: String,
    #[reflect(ignore)]
    pub media: Option<MediaQueryCondition>,
}

/// Transforms parsed from CSS transform properties.
#[derive(Reflect, Default, Debug, Clone, PartialEq)]
pub struct TransformStyle {
    pub translation: Option<Val2>,
    pub translation_x: Option<Val>,
    pub translation_y: Option<Val>,
    pub scale: Option<Vec2>,
    pub scale_x: Option<f32>,
    pub scale_y: Option<f32>,
    pub rotation: Option<f32>,
}

impl TransformStyle {
    /// Returns true when no transform values are set.
    pub fn is_empty(&self) -> bool {
        self.translation.is_none()
            && self.translation_x.is_none()
            && self.translation_y.is_none()
            && self.scale.is_none()
            && self.scale_x.is_none()
            && self.scale_y.is_none()
            && self.rotation.is_none()
    }
}

/// Cursor styling, either a system cursor or a custom asset path.
#[derive(Reflect, Debug, Clone, PartialEq)]
pub enum CursorStyle {
    /// Variant `System`.
    System(SystemCursorIcon),
    /// Variant `Custom`.
    Custom(String),
}

/// Text casing transformation parsed from `text-transform`.
#[derive(Reflect, Debug, Clone, Copy, PartialEq, Eq)]
pub enum TextTransform {
    /// Variant `None`.
    None,
    /// Variant `Uppercase`.
    Uppercase,
    /// Variant `Lowercase`.
    Lowercase,
    /// Variant `Capitalize`.
    Capitalize,
}

/// Comprehensive style properties for UI elements.
#[derive(Reflect, Default, Debug, Clone, PartialEq)]
pub struct Style {
    pub display: Option<Display>,
    pub box_sizing: Option<BoxSizing>,
    pub position_type: Option<PositionType>,
    pub width: Option<Val>,
    #[reflect(ignore)]
    pub width_calc: Option<CalcExpr>,
    pub min_width: Option<Val>,
    #[reflect(ignore)]
    pub min_width_calc: Option<CalcExpr>,
    pub max_width: Option<Val>,
    #[reflect(ignore)]
    pub max_width_calc: Option<CalcExpr>,
    pub height: Option<Val>,
    #[reflect(ignore)]
    pub height_calc: Option<CalcExpr>,
    pub min_height: Option<Val>,
    #[reflect(ignore)]
    pub min_height_calc: Option<CalcExpr>,
    pub max_height: Option<Val>,
    #[reflect(ignore)]
    pub max_height_calc: Option<CalcExpr>,
    pub left: Option<Val>,
    #[reflect(ignore)]
    pub left_calc: Option<CalcExpr>,
    pub top: Option<Val>,
    #[reflect(ignore)]
    pub top_calc: Option<CalcExpr>,
    pub right: Option<Val>,
    #[reflect(ignore)]
    pub right_calc: Option<CalcExpr>,
    pub bottom: Option<Val>,
    #[reflect(ignore)]
    pub bottom_calc: Option<CalcExpr>,
    pub padding: Option<UiRect>,
    pub margin: Option<UiRect>,
    pub border: Option<UiRect>,
    pub overflow: Option<Overflow>,
    pub color: Option<Color>,
    pub background: Option<Background>,
    pub backdrop_filter: Option<BackdropFilter>,
    pub background_position: Option<BackgroundPosition>,
    pub background_size: Option<BackgroundSize>,
    pub background_attachment: Option<BackgroundAttachment>,
    pub border_color: Option<Color>,
    pub border_width: Option<Val>,
    pub border_radius: Option<Radius>,
    pub outline_width: Option<Val>,
    pub outline_offset: Option<Val>,
    pub outline_color: Option<Color>,
    pub font_size: Option<FontSize>,
    pub font_family: Option<FontFamily>,
    pub font_weight: Option<FontWeight>,
    pub line_height: Option<LineHeight>,
    pub box_shadow: Option<BoxShadow>,
    pub text_shadow: Option<TextShadow>,
    pub text_transform: Option<TextTransform>,
    pub justify_content: Option<JustifyContent>,
    pub justify_items: Option<JustifyItems>,
    pub justify_self: Option<JustifySelf>,
    pub align_content: Option<AlignContent>,
    pub align_items: Option<AlignItems>,
    pub align_self: Option<AlignSelf>,
    pub flex_direction: Option<FlexDirection>,
    pub flex_grow: Option<f32>,
    pub flex_shrink: Option<f32>,
    pub flex_basis: Option<Val>,
    #[reflect(ignore)]
    pub flex_basis_calc: Option<CalcExpr>,
    pub flex_wrap: Option<FlexWrap>,
    pub grid_row: Option<GridPlacement>,
    pub grid_column: Option<GridPlacement>,
    pub grid_auto_flow: Option<GridAutoFlow>,
    pub grid_template_rows: Option<Vec<RepeatedGridTrack>>,
    pub grid_template_columns: Option<Vec<RepeatedGridTrack>>,
    pub grid_auto_rows: Option<Vec<GridTrack>>,
    pub grid_auto_columns: Option<Vec<GridTrack>>,
    pub gap: Option<Val>,
    #[reflect(ignore)]
    pub gap_calc: Option<CalcExpr>,
    pub row_gap: Option<Val>,
    #[reflect(ignore)]
    pub row_gap_calc: Option<CalcExpr>,
    pub column_gap: Option<Val>,
    #[reflect(ignore)]
    pub column_gap_calc: Option<CalcExpr>,
    pub text_align: Option<Justify>,
    pub text_wrap: Option<LineBreak>,
    pub z_index: Option<i32>,
    pub cursor: Option<CursorStyle>,
    pub pointer_events: Option<Pickable>,
    pub scrollbar_width: Option<f32>,
    pub transition: Option<TransitionSpec>,
    pub transform: TransformStyle,
    pub animation: Option<AnimationSpec>,
}

impl Style {
    /// Merges another `Style` into this one, overriding any set fields.
    pub fn merge(&mut self, other: &Style) {
        merge_opt(&mut self.display, &other.display);
        merge_opt(&mut self.box_sizing, &other.box_sizing);
        merge_opt(&mut self.position_type, &other.position_type);

        merge_val_with_calc(
            &mut self.width,
            &mut self.width_calc,
            &other.width,
            &other.width_calc,
        );
        merge_val_with_calc(
            &mut self.min_width,
            &mut self.min_width_calc,
            &other.min_width,
            &other.min_width_calc,
        );
        merge_val_with_calc(
            &mut self.max_width,
            &mut self.max_width_calc,
            &other.max_width,
            &other.max_width_calc,
        );

        merge_val_with_calc(
            &mut self.height,
            &mut self.height_calc,
            &other.height,
            &other.height_calc,
        );
        merge_val_with_calc(
            &mut self.min_height,
            &mut self.min_height_calc,
            &other.min_height,
            &other.min_height_calc,
        );
        merge_val_with_calc(
            &mut self.max_height,
            &mut self.max_height_calc,
            &other.max_height,
            &other.max_height_calc,
        );

        merge_val_with_calc(
            &mut self.left,
            &mut self.left_calc,
            &other.left,
            &other.left_calc,
        );
        merge_val_with_calc(
            &mut self.top,
            &mut self.top_calc,
            &other.top,
            &other.top_calc,
        );
        merge_val_with_calc(
            &mut self.right,
            &mut self.right_calc,
            &other.right,
            &other.right_calc,
        );
        merge_val_with_calc(
            &mut self.bottom,
            &mut self.bottom_calc,
            &other.bottom,
            &other.bottom_calc,
        );

        merge_opt(&mut self.padding, &other.padding);
        merge_opt(&mut self.margin, &other.margin);
        merge_opt(&mut self.border, &other.border);

        merge_opt(&mut self.overflow, &other.overflow);

        merge_opt(&mut self.color, &other.color);
        merge_opt(&mut self.background, &other.background);
        merge_opt(&mut self.backdrop_filter, &other.backdrop_filter);
        merge_opt(&mut self.background_position, &other.background_position);
        merge_opt(&mut self.background_size, &other.background_size);
        merge_opt(
            &mut self.background_attachment,
            &other.background_attachment,
        );

        merge_opt(&mut self.border_color, &other.border_color);
        merge_opt(&mut self.border_width, &other.border_width);
        merge_opt(&mut self.border_radius, &other.border_radius);
        merge_opt(&mut self.outline_width, &other.outline_width);
        merge_opt(&mut self.outline_offset, &other.outline_offset);
        merge_opt(&mut self.outline_color, &other.outline_color);

        merge_opt(&mut self.font_size, &other.font_size);
        merge_opt(&mut self.font_family, &other.font_family);
        merge_opt(&mut self.font_weight, &other.font_weight);
        merge_opt(&mut self.line_height, &other.line_height);
        merge_opt(&mut self.box_shadow, &other.box_shadow);
        merge_opt(&mut self.text_shadow, &other.text_shadow);
        merge_opt(&mut self.text_transform, &other.text_transform);

        merge_opt(&mut self.justify_content, &other.justify_content);
        merge_opt(&mut self.justify_items, &other.justify_items);
        merge_opt(&mut self.justify_self, &other.justify_self);

        merge_opt(&mut self.align_content, &other.align_content);
        merge_opt(&mut self.align_items, &other.align_items);
        merge_opt(&mut self.align_self, &other.align_self);

        merge_opt(&mut self.flex_direction, &other.flex_direction);
        merge_opt(&mut self.flex_wrap, &other.flex_wrap);
        merge_opt(&mut self.flex_grow, &other.flex_grow);
        merge_opt(&mut self.flex_shrink, &other.flex_shrink);
        merge_val_with_calc(
            &mut self.flex_basis,
            &mut self.flex_basis_calc,
            &other.flex_basis,
            &other.flex_basis_calc,
        );

        merge_opt(&mut self.grid_row, &other.grid_row);
        merge_opt(&mut self.grid_column, &other.grid_column);
        merge_opt(&mut self.grid_auto_flow, &other.grid_auto_flow);

        merge_opt(&mut self.grid_template_rows, &other.grid_template_rows);
        merge_opt(
            &mut self.grid_template_columns,
            &other.grid_template_columns,
        );
        merge_opt(&mut self.grid_auto_rows, &other.grid_auto_rows);
        merge_opt(&mut self.grid_auto_columns, &other.grid_auto_columns);

        merge_val_with_calc(
            &mut self.gap,
            &mut self.gap_calc,
            &other.gap,
            &other.gap_calc,
        );
        merge_val_with_calc(
            &mut self.row_gap,
            &mut self.row_gap_calc,
            &other.row_gap,
            &other.row_gap_calc,
        );
        merge_val_with_calc(
            &mut self.column_gap,
            &mut self.column_gap_calc,
            &other.column_gap,
            &other.column_gap_calc,
        );

        merge_opt(&mut self.text_align, &other.text_align);
        merge_opt(&mut self.text_wrap, &other.text_wrap);

        merge_opt(&mut self.z_index, &other.z_index);
        merge_opt(&mut self.cursor, &other.cursor);
        merge_opt(&mut self.pointer_events, &other.pointer_events);

        merge_opt(&mut self.scrollbar_width, &other.scrollbar_width);
        merge_opt(&mut self.transition, &other.transition);

        merge_opt(
            &mut self.transform.translation,
            &other.transform.translation,
        );
        merge_opt(
            &mut self.transform.translation_x,
            &other.transform.translation_x,
        );
        merge_opt(
            &mut self.transform.translation_y,
            &other.transform.translation_y,
        );
        merge_opt(&mut self.transform.scale, &other.transform.scale);
        merge_opt(&mut self.transform.scale_x, &other.transform.scale_x);
        merge_opt(&mut self.transform.scale_y, &other.transform.scale_y);
        merge_opt(&mut self.transform.rotation, &other.transform.rotation);

        merge_opt(&mut self.animation, &other.animation);
    }
}

/// Copies a source value into a destination if the source is set.
#[inline]
fn merge_opt<T: Clone>(dst: &mut Option<T>, src: &Option<T>) {
    if let Some(v) = src.as_ref() {
        *dst = Some(v.clone());
    }
}

/// Handles `merge_val_with_calc` in the extended UI workflow.
#[inline]
fn merge_val_with_calc<T: Clone>(
    dst_val: &mut Option<T>,
    dst_calc: &mut Option<CalcExpr>,
    src_val: &Option<T>,
    src_calc: &Option<CalcExpr>,
) {
    if let Some(calc) = src_calc.as_ref() {
        *dst_calc = Some(calc.clone());
        *dst_val = None;
    } else if let Some(val) = src_val.as_ref() {
        *dst_val = Some(val.clone());
        *dst_calc = None;
    }
}

/// Bevy plugin registering style-related reflection data.
pub struct ExtendedStylingPlugin;

impl Plugin for ExtendedStylingPlugin {
    /// Registers reflected style-related components.
    fn build(&self, app: &mut App) {
        app.register_type::<UiStyle>();
        app.register_type::<CssClass>();
        app.register_type::<CssID>();
    }
}