bevy_extended_ui 1.3.0-beta.2

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
pub mod components;
pub mod paint;
pub mod parser;

use crate::io::CssAsset;
use crate::styles::components::UiStyle;
use bevy::prelude::*;
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)]
#[reflect(Component)]
pub struct CssClass(pub Vec<String>);

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

#[derive(Component, Reflect, Debug, Clone, Default)]
#[reflect(Component)]
pub struct CssSource(pub Vec<Handle<CssAsset>>);

impl CssSource {
    pub fn from_path(asset_server: &AssetServer, path: &str) -> Self {
        Self(vec![asset_server.load::<CssAsset>(path.to_string())])
    }

    pub fn push_path(&mut self, asset_server: &AssetServer, path: &str) {
        self.0.push(asset_server.load::<CssAsset>(path.to_string()));
    }

    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.
     *
     * @param val The radius value to use for all four corners.
     * @return A new `Radius` with uniform corner radii.
     */
    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 and optional image.
#[derive(Reflect, Debug, Clone, PartialEq)]
pub struct Background {
    pub color: Color,
    pub image: Option<String>,
}

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

/// Constants for common font weight values.
#[derive(Reflect, Debug, Clone, PartialEq, Copy)]
pub enum FontWeight {
    Thin = 100,
    ExtraLight = 200,
    Light = 300,
    Normal = 400,
    Medium = 500,
    SemiBold = 600,
    Bold = 700,
    ExtraBold = 800,
    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)]
pub enum IconPlace {
    Left,
    Right,
}

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

/// Represents a font size value, either in pixels or rem units.
#[derive(Reflect, Debug, Clone, PartialEq)]
pub enum FontVal {
    Px(f32),
    Rem(f32),
}

impl Default for FontVal {
    /**
     * Returns the default font size of 12 pixels.
     */
    fn default() -> Self {
        FontVal::Px(12.0)
    }
}

impl FontVal {
    /**
     * Computes the absolute font size in pixels, resolving rem units using a base size.
     *
     * @param base Optional base font size in pixels for rem calculations. Defaults to 1.0 if not provided.
     * @return The computed font size in pixels.
     */
    pub fn get(&self, base: Option<f32>) -> f32 {
        match self {
            FontVal::Px(x) => x.clone(),
            FontVal::Rem(x) => x * base.unwrap_or(1.0),
        }
    }
}

#[derive(Reflect, Debug, Clone, PartialEq)]
pub struct FontFamily(pub String);

#[derive(Reflect, Debug, Clone, PartialEq, Eq, Copy)]
pub enum TransitionTiming {
    Linear,
    Ease,
    EaseIn,
    EaseOut,
    EaseInOut,
}

impl TransitionTiming {
    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
                }
            }
        }
    }

    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 {
    fn default() -> Self {
        TransitionTiming::EaseInOut
    }
}

#[derive(Reflect, Debug, Clone, PartialEq, Eq, Copy)]
pub enum AnimationDirection {
    Normal,
    Reverse,
    Alternate,
    AlternateReverse,
}

impl AnimationDirection {
    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 {
    fn default() -> Self {
        AnimationDirection::Normal
    }
}

#[derive(Reflect, Debug, Clone, PartialEq, Eq, Copy)]
pub enum TransitionProperty {
    All,
    Color,
    Background,
    Transform,
}

impl Default for TransitionProperty {
    fn default() -> Self {
        TransitionProperty::All
    }
}

#[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 {
    fn default() -> Self {
        Self {
            name: String::new(),
            duration: 0.0,
            delay: 0.0,
            timing: TransitionTiming::Ease,
            iterations: Some(1.0),
            direction: AnimationDirection::Normal,
        }
    }
}

#[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 {
    fn default() -> Self {
        Self {
            properties: vec![TransitionProperty::All],
            duration: 0.3,
            delay: 0.0,
            timing: TransitionTiming::EaseInOut,
        }
    }
}

#[derive(Reflect, Default, Debug, Clone, PartialEq)]
pub struct AnimationKeyframe {
    pub progress: f32,
    pub style: Style,
}

#[derive(Reflect, Default, Debug, Clone, PartialEq)]
pub struct ParsedCss {
    pub styles: HashMap<String, StylePair>,
    pub keyframes: HashMap<String, Vec<AnimationKeyframe>>,
}

#[derive(Reflect, Default, Debug, Clone, PartialEq)]
pub struct StylePair {
    pub important: Style,
    pub normal: Style,
    pub origin: usize,
}

#[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 {
    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()
    }
}

/// 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>,
    pub min_width: Option<Val>,
    pub max_width: Option<Val>,
    pub height: Option<Val>,
    pub min_height: Option<Val>,
    pub max_height: Option<Val>,
    pub left: Option<Val>,
    pub top: Option<Val>,
    pub right: Option<Val>,
    pub bottom: Option<Val>,
    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 border_color: Option<Color>,
    pub border_width: Option<Val>,
    pub border_radius: Option<Radius>,
    pub font_size: Option<FontVal>,
    pub font_family: Option<FontFamily>,
    pub font_weight: Option<FontWeight>,
    pub box_shadow: Option<BoxShadow>,
    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>,
    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>,
    pub text_wrap: Option<LineBreak>,
    pub z_index: Option<i32>,
    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.
     * For each field, if the other style has a value set (`Some`), it overwrites this style's value.
     *
     * @param other The other style to merge from.
     */
    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_opt(&mut self.width, &other.width);
        merge_opt(&mut self.min_width, &other.min_width);
        merge_opt(&mut self.max_width, &other.max_width);

        merge_opt(&mut self.height, &other.height);
        merge_opt(&mut self.min_height, &other.min_height);
        merge_opt(&mut self.max_height, &other.max_height);

        merge_opt(&mut self.left, &other.left);
        merge_opt(&mut self.top, &other.top);
        merge_opt(&mut self.right, &other.right);
        merge_opt(&mut self.bottom, &other.bottom);

        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.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.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.box_shadow, &other.box_shadow);

        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_opt(&mut self.flex_basis, &other.flex_basis);

        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_opt(&mut self.gap, &other.gap);

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

        merge_opt(&mut self.z_index, &other.z_index);
        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);
    }
}

#[inline]
fn merge_opt<T: Clone>(dst: &mut Option<T>, src: &Option<T>) {
    if let Some(v) = src.as_ref() {
        *dst = Some(v.clone());
    }
}

pub struct ExtendedStylingPlugin;

impl Plugin for ExtendedStylingPlugin {
    fn build(&self, app: &mut App) {
        app.register_type::<UiStyle>();
        app.register_type::<CssClass>();
        app.register_type::<CssID>();
    }
}