bevy_ecss 0.7.0

Allows using a subset of CSS to interact with Bevy ECS
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
use bevy::{ecs::query::QueryItem, prelude::*};

use crate::EcssError;

use super::{Property, PropertyValues};

pub(crate) use style::*;
pub(crate) use text::*;

/// Impls for `bevy_ui` [`Style`] component
mod style {
    use super::*;
    /// Implements a new property for [`Style`] component which expects a rect value.
    macro_rules! impl_style_rect {
        ($name:expr, $struct:ident, $style_prop:ident$(.$style_field:ident)*) => {
            #[doc = "Applies the `"]
            #[doc = $name]
            #[doc = "` property on [Style::"]
            #[doc = stringify!($style_prop)]
            $(#[doc = concat!("::",stringify!($style_field))])*
            #[doc = "](`Style`) field of all sections on matched [`Style`] components."]
            #[derive(Default)]
            pub(crate) struct $struct;

            impl Property for $struct {
                type Cache = UiRect;
                type Components = &'static mut Style;
                type Filters = With<Node>;

                fn name() -> &'static str {
                    $name
                }

                fn parse<'a>(values: &PropertyValues) -> Result<Self::Cache, EcssError> {
                    if let Some(val) = values.rect() {
                        Ok(val)
                    } else {
                        Err(EcssError::InvalidPropertyValue(Self::name().to_string()))
                    }
                }

                fn apply<'w>(
                    cache: &Self::Cache,
                    mut components: QueryItem<Self::Components>,
                    _asset_server: &AssetServer,
                    _commands: &mut Commands,
                ) {
                    components.$style_prop$(.$style_field)? = *cache;
                }
            }
        };
    }

    impl_style_rect!("margin", MarginProperty, margin);
    impl_style_rect!("padding", PaddingProperty, padding);
    impl_style_rect!("border", BorderProperty, border);

    /// Implements a new property for [`Style`] component which expects a single value.
    macro_rules! impl_style_single_value {
        ($name:expr, $struct:ident, $cache:ty, $parse_func:ident, $style_prop:ident$(.$style_field:ident)*) => {
            #[doc = "Applies the `"]
            #[doc = $name]
            #[doc = "` property on [Style::"]
            #[doc = stringify!($style_prop)]
            $(#[doc = concat!("::",stringify!($style_field))])*
            #[doc = "](`Style`) field of all sections on matched [`Style`] components."]
            #[derive(Default)]
            pub(crate) struct $struct;

            impl Property for $struct {
                type Cache = $cache;
                type Components = &'static mut Style;
                type Filters = With<Node>;

                fn name() -> &'static str {
                    $name
                }

                fn parse<'a>(values: &PropertyValues) -> Result<Self::Cache, EcssError> {
                    if let Some(val) = values.$parse_func() {
                        Ok(val)
                    } else {
                        Err(EcssError::InvalidPropertyValue(Self::name().to_string()))
                    }
                }

                fn apply<'w>(
                    cache: &Self::Cache,
                    mut components: QueryItem<Self::Components>,
                    _asset_server: &AssetServer,
                    _commands: &mut Commands,
                ) {
                    components.$style_prop$(.$style_field)? = *cache;
                }
            }
        };
    }

    // Val properties
    impl_style_single_value!("left", LeftProperty, Val, val, left);
    impl_style_single_value!("right", RightProperty, Val, val, right);
    impl_style_single_value!("top", TopProperty, Val, val, top);
    impl_style_single_value!("bottom", BottomProperty, Val, val, bottom);

    impl_style_single_value!("width", WidthProperty, Val, val, width);
    impl_style_single_value!("height", HeightProperty, Val, val, height);

    impl_style_single_value!("min-width", MinWidthProperty, Val, val, min_width);
    impl_style_single_value!("min-height", MinHeightProperty, Val, val, min_height);

    impl_style_single_value!("max-width", MaxWidthProperty, Val, val, max_width);
    impl_style_single_value!("max-height", MaxHeightProperty, Val, val, max_height);

    impl_style_single_value!("flex-basis", FlexBasisProperty, Val, val, flex_basis);

    impl_style_single_value!("flex-grow", FlexGrowProperty, f32, f32, flex_grow);
    impl_style_single_value!("flex-shrink", FlexShrinkProperty, f32, f32, flex_shrink);

    impl_style_single_value!("row-gap", RowGapProperty, Val, val, row_gap);
    impl_style_single_value!("column-gap", ColumnGapProperty, Val, val, column_gap);

    impl_style_single_value!(
        "aspect-ratio",
        AspectRatioProperty,
        Option<f32>,
        option_f32,
        aspect_ratio
    );

    /// Implements a new property for [`Style`] component which expects an enum.
    macro_rules! impl_style_enum {
        ($cache:ty, $name:expr, $struct:ident, $style_prop:ident$(.$style_field:ident)*, $($prop:expr => $variant:expr),+$(,)?) => {
            #[doc = "Applies the `"]
            #[doc = $name]
            #[doc = "` property on [Style::"]
            #[doc = stringify!($style_prop)]
            #[doc = "]("]
            #[doc = concat!("`", stringify!($cache), "`")]
            #[doc = ") field of all sections on matched [`Style`] components."]
            #[derive(Default)]
            pub(crate) struct $struct;

            impl Property for $struct {
                type Cache = $cache;
                type Components = &'static mut Style;
                type Filters = With<Node>;

                fn name() -> &'static str {
                    $name
                }

                fn parse<'a>(values: &PropertyValues) -> Result<Self::Cache, EcssError> {
                    if let Some(identifier) = values.identifier() {
                        use $cache::*;
                        // Chain if-let when `cargofmt` supports it
                        // https://github.com/rust-lang/rustfmt/pull/5203
                        match identifier {
                            $($prop => return Ok($variant)),+,
                            _ => (),
                        }
                    }

                    Err(EcssError::InvalidPropertyValue(Self::name().to_string()))
                }

                fn apply<'w>(
                    cache: &Self::Cache,
                    mut components: QueryItem<Self::Components>,
                    _asset_server: &AssetServer,
                    _commands: &mut Commands,
                ) {
                    components.$style_prop$(.$style_field)? = *cache;
                }
            }
        };
    }

    impl_style_enum!(Display, "display", DisplayProperty, display,
        "flex" => Flex,
        "none" => None
    );

    impl_style_enum!(PositionType, "position-type", PositionTypeProperty, position_type,
        "absolute" => Absolute,
        "relative" => Relative,
    );

    impl_style_enum!(Direction, "direction", DirectionProperty, direction,
        "inherit" => Inherit,
        "left-to-right" => LeftToRight,
        "right-to-left" => RightToLeft,
    );

    impl_style_enum!(FlexDirection, "flex-direction", FlexDirectionProperty, flex_direction,
        "row" => Row,
        "column" => Column,
        "row-reverse" => RowReverse,
        "column-reverse" => ColumnReverse,
    );

    impl_style_enum!(FlexWrap, "flex-wrap", FlexWrapProperty, flex_wrap,
        "no-wrap" => NoWrap,
        "wrap" => Wrap,
        "wrap-reverse" => WrapReverse,
    );

    impl_style_enum!(AlignItems, "align-items", AlignItemsProperty, align_items,
        "flex-start" => FlexStart,
        "flex-end" => FlexEnd,
        "center" => Center,
        "baseline" => Baseline,
        "stretch" => Stretch,
    );

    impl_style_enum!(AlignSelf, "align-self", AlignSelfProperty, align_self,
        "auto" => Auto,
        "flex-start" => FlexStart,
        "flex-end" => FlexEnd,
        "center" => Center,
        "baseline" => Baseline,
        "stretch" => Stretch,
    );

    impl_style_enum!(AlignContent, "align-content", AlignContentProperty, align_content,
        "flex-start" => FlexStart,
        "flex-end" => FlexEnd,
        "center" => Center,
        "stretch" => Stretch,
        "space-between" => SpaceBetween,
        "space-around" => SpaceAround,
    );

    impl_style_enum!(JustifyContent, "justify-content", JustifyContentProperty, justify_content,
        "flex-start" => FlexStart,
        "flex-end" => FlexEnd,
        "center" => Center,
        "space-between" => SpaceBetween,
        "space-around" => SpaceAround,
        "space-evenly" => SpaceEvenly,
    );

    impl_style_enum!(OverflowAxis, "overflow-x", OverflowAxisXProperty, overflow.x,
        "visible" => Visible,
        "hidden" => Clip,
    );

    impl_style_enum!(OverflowAxis, "overflow-y", OverflowAxisYProperty, overflow.y,
        "visible" => Visible,
        "hidden" => Clip,
    );
}

/// Impls for `bevy_text` [`Text`] component
mod text {
    use super::*;

    /// Applies the `color` property on [`TextStyle::color`](`TextStyle`) field of all sections on matched [`Text`] components.
    #[derive(Default)]
    pub(crate) struct FontColorProperty;

    impl Property for FontColorProperty {
        type Cache = Color;
        type Components = &'static mut Text;
        type Filters = With<Node>;

        fn name() -> &'static str {
            "color"
        }

        fn parse<'a>(values: &PropertyValues) -> Result<Self::Cache, EcssError> {
            if let Some(color) = values.color() {
                Ok(color)
            } else {
                Err(EcssError::InvalidPropertyValue(Self::name().to_string()))
            }
        }

        fn apply<'w>(
            cache: &Self::Cache,
            mut components: QueryItem<Self::Components>,
            _asset_server: &AssetServer,
            _commands: &mut Commands,
        ) {
            components
                .sections
                .iter_mut()
                .for_each(|section| section.style.color = *cache);
        }
    }

    /// Applies the `font` property on [`TextStyle::font`](`TextStyle`) property of all sections on matched [`Text`] components.
    #[derive(Default)]
    pub(crate) struct FontProperty;

    impl Property for FontProperty {
        type Cache = String;
        type Components = &'static mut Text;
        type Filters = With<Node>;

        fn name() -> &'static str {
            "font"
        }

        fn parse<'a>(values: &PropertyValues) -> Result<Self::Cache, EcssError> {
            if let Some(path) = values.string() {
                Ok(path)
            } else {
                Err(EcssError::InvalidPropertyValue(Self::name().to_string()))
            }
        }

        fn apply<'w>(
            cache: &Self::Cache,
            mut components: QueryItem<Self::Components>,
            asset_server: &AssetServer,
            _commands: &mut Commands,
        ) {
            components
                .sections
                .iter_mut()
                .for_each(|section| section.style.font = asset_server.load(cache));
        }
    }

    /// Applies the `font-size` property on [`TextStyle::font_size`](`TextStyle`) property of all sections on matched [`Text`] components.
    #[derive(Default)]
    pub(crate) struct FontSizeProperty;

    impl Property for FontSizeProperty {
        type Cache = f32;
        type Components = &'static mut Text;
        type Filters = With<Node>;

        fn name() -> &'static str {
            "font-size"
        }

        fn parse<'a>(values: &PropertyValues) -> Result<Self::Cache, EcssError> {
            if let Some(size) = values.f32() {
                Ok(size)
            } else {
                Err(EcssError::InvalidPropertyValue(Self::name().to_string()))
            }
        }

        fn apply<'w>(
            cache: &Self::Cache,
            mut components: QueryItem<Self::Components>,
            _asset_server: &AssetServer,
            _commands: &mut Commands,
        ) {
            components
                .sections
                .iter_mut()
                .for_each(|section| section.style.font_size = *cache);
        }
    }

    /// Applies the `text-align` property on [`Text::horizontal`](`JustifyText`) components.
    #[derive(Default)]
    pub(crate) struct TextAlignProperty;

    impl Property for TextAlignProperty {
        // Using Option since Cache must impl Default, which  doesn't
        type Cache = Option<JustifyText>;
        type Components = &'static mut Text;
        type Filters = With<Node>;

        fn name() -> &'static str {
            "text-align"
        }

        fn parse<'a>(values: &PropertyValues) -> Result<Self::Cache, EcssError> {
            if let Some(ident) = values.identifier() {
                match ident {
                    "left" => return Ok(Some(JustifyText::Left)),
                    "center" => return Ok(Some(JustifyText::Center)),
                    "right" => return Ok(Some(JustifyText::Right)),
                    _ => (),
                }
            }
            Err(EcssError::InvalidPropertyValue(Self::name().to_string()))
        }

        fn apply<'w>(
            cache: &Self::Cache,
            mut components: QueryItem<Self::Components>,
            _asset_server: &AssetServer,
            _commands: &mut Commands,
        ) {
            components.justify = cache.expect("Should always have a inner value");
        }
    }

    /// Apply a custom `text-content` which updates [`TextSection::value`](`TextSection`) of all sections on matched [`Text`] components
    #[derive(Default)]
    pub(crate) struct TextContentProperty;

    impl Property for TextContentProperty {
        type Cache = String;
        type Components = &'static mut Text;
        type Filters = With<Node>;

        fn name() -> &'static str {
            "text-content"
        }

        fn parse<'a>(values: &PropertyValues) -> Result<Self::Cache, EcssError> {
            if let Some(content) = values.string() {
                Ok(content)
            } else {
                Err(EcssError::InvalidPropertyValue(Self::name().to_string()))
            }
        }

        fn apply<'w>(
            cache: &Self::Cache,
            mut components: QueryItem<Self::Components>,
            _asset_server: &AssetServer,
            _commands: &mut Commands,
        ) {
            components
                .sections
                .iter_mut()
                // TODO: Maybe change this so each line break is a new section
                .for_each(|section| section.value = cache.clone());
        }
    }
}

/// Applies the `background-color` property on [`BackgroundColor`] component of matched entities.
#[derive(Default)]
pub(crate) struct BackgroundColorProperty;

impl Property for BackgroundColorProperty {
    type Cache = Color;
    type Components = Entity;
    type Filters = With<BackgroundColor>;

    fn name() -> &'static str {
        "background-color"
    }

    fn parse<'a>(values: &PropertyValues) -> Result<Self::Cache, EcssError> {
        if let Some(color) = values.color() {
            Ok(color)
        } else {
            Err(EcssError::InvalidPropertyValue(Self::name().to_string()))
        }
    }

    fn apply<'w>(
        cache: &Self::Cache,
        components: QueryItem<Self::Components>,
        _asset_server: &AssetServer,
        commands: &mut Commands,
    ) {
        commands.entity(components).insert(BackgroundColor(*cache));
    }
}

/// Applies the `border-color` property on [`BorderColor`] component of matched entities.
#[derive(Default)]
pub struct BorderColorProperty;

impl Property for BorderColorProperty {
    type Cache = Color;
    type Components = Entity;
    type Filters = With<BorderColor>;

    fn name() -> &'static str {
        "border-color"
    }

    fn parse<'a>(values: &PropertyValues) -> Result<Self::Cache, EcssError> {
        if let Some(color) = values.color() {
            Ok(color)
        } else {
            Err(EcssError::InvalidPropertyValue(Self::name().to_string()))
        }
    }

    fn apply<'w>(
        cache: &Self::Cache,
        components: QueryItem<Self::Components>,
        _asset_server: &AssetServer,
        commands: &mut Commands,
    ) {
        commands.entity(components).insert(BorderColor(*cache));
    }
}

/// Applies the `image-path` property on [`bevy::ui::UiImage`] texture property of all sections on matched [`bevy::ui::UiImage`] components.
#[derive(Default)]
pub struct ImageProperty;

impl Property for ImageProperty {
    type Cache = String;
    type Components = &'static mut UiImage;
    type Filters = With<Node>;

    fn name() -> &'static str {
        "image-path"
    }

    fn parse<'a>(values: &PropertyValues) -> Result<Self::Cache, EcssError> {
        if let Some(path) = values.string() {
            Ok(path)
        } else {
            Err(EcssError::InvalidPropertyValue(Self::name().to_string()))
        }
    }

    fn apply<'w>(
        cache: &Self::Cache,
        mut components: QueryItem<Self::Components>,
        asset_server: &AssetServer,
        _commands: &mut Commands,
    ) {
        components.texture = asset_server.load(cache);
    }
}