bevy_react_core 0.8.0

The core bridge of bevy-react (drive bevy_ui from React over an embedded V8 runtime). Apps depend on the `bevy-react` crate.
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
//! Keyword-valued style properties: the `keyword_fields!` table decodes each
//! wire keyword straight into the `bevy_ui`/`bevy_text` enum it drives.

use std::fmt;

use bevy::text::{FontWeight, Justify, LineBreak};
use bevy::ui::{
    AlignContent, AlignItems, AlignSelf, BoxSizing, Display, FlexDirection, FlexWrap, FocusPolicy,
    GridAutoFlow, JustifyContent, JustifyItems, JustifySelf, OverflowAxis,
};

use serde::de::{self, Deserializer, Visitor};

use super::background_image::BackgroundImageMode;
use super::decode_warn;
use crate::image_rendering::ImageRendering;
use crate::scrollbar::{HorizontalEdge, ScrollbarPosition, VerticalEdge};
use crate::style::KeywordTable;
use crate::style::props::{LayerCache, PositionMode};

/// A keyword kind's [`KeywordTable`] (`as TABLE` in `keyword_fields!`) for
/// the property codec that decodes through it; nothing for a kind that only
/// decodes a sub-field of another property's value.
macro_rules! keyword_table {
    (; $($rest:tt)*) => {};
    ($table:ident; $fn_name:ident, $kind:literal, $ty:ty, [$($kw:literal),+]) => {
        /// The keyword table of this kind, for the style registry's codec.
        pub(crate) static $table: KeywordTable<$ty> = KeywordTable {
            kind: $kind,
            keywords: &[$($kw),+],
            decode: {
                fn decode(
                    d: &mut dyn erased_serde::Deserializer<'_>,
                ) -> Result<Option<$ty>, erased_serde::Error> {
                    $fn_name(d)
                }
                decode
            },
        };
    };
}

/// Declares one `deserialize_with` fn per keyword kind (and, with
/// `as TABLE`, the [`KeywordTable`] a keyword-valued property's codec uses),
/// decoding the wire keyword straight into the `bevy_ui`/`bevy_text` enum it
/// drives. An unrecognized keyword warns (naming the kind and value) and falls
/// back to the enum's bevy default — a typo must not abort the commit batch. A
/// JSON `null` decodes to `None`; any other non-string value keeps
/// hard-erroring, like [`Length`](super::units::Length).
macro_rules! keyword_fields {
    ( $(
        $(#[$meta:meta])*
        fn $fn_name:ident($kind:literal) -> $ty:ty $(as $table:ident)? {
            $( $($kw:literal)|+ => $variant:ident ),+ $(,)?
        }
    )+ ) => { $(
        $(#[$meta])*
        pub(crate) fn $fn_name<'de, D: Deserializer<'de>>(d: D) -> Result<Option<$ty>, D::Error> {
            struct V;
            impl<'de> Visitor<'de> for V {
                type Value = Option<$ty>;
                fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
                    f.write_str(concat!("a `", $kind, "` keyword string"))
                }
                fn visit_str<E: de::Error>(self, s: &str) -> Result<Self::Value, E> {
                    Ok(Some(match s {
                        $( $($kw)|+ => <$ty>::$variant, )+
                        _ => {
                            decode_warn(
                                $kind,
                                s,
                                &format!("unrecognized {} {s:?}", $kind),
                            );
                            <$ty>::default()
                        }
                    }))
                }
                fn visit_unit<E: de::Error>(self) -> Result<Self::Value, E> {
                    Ok(None)
                }
                fn visit_none<E: de::Error>(self) -> Result<Self::Value, E> {
                    Ok(None)
                }
            }
            d.deserialize_any(V)
        }

        keyword_table! { $($table)?; $fn_name, $kind, $ty, [$( $($kw),+ ),+] }
    )+ };
}

keyword_fields! {
    fn de_display("display") -> Display as DISPLAY_KEYWORDS {
        "flex" => Flex, "grid" => Grid, "block" => Block, "none" => None,
    }
    fn de_layer_cache("cache") -> LayerCache as LAYER_CACHE_KEYWORDS {
        "auto" => Auto, "always" => Always, "never" => Never,
    }
    fn de_box_sizing("boxSizing") -> BoxSizing as BOX_SIZING_KEYWORDS {
        "borderBox" | "border-box" => BorderBox,
        "contentBox" | "content-box" => ContentBox,
    }
    fn de_position_type("positionType") -> PositionMode as POSITION_TYPE_KEYWORDS {
        "absolute" => Absolute, "relative" => Relative, "fixed" => Fixed,
    }
    fn de_overflow_axis("overflow") -> OverflowAxis as OVERFLOW_KEYWORDS {
        "visible" => Visible, "clip" => Clip, "hidden" => Hidden, "scroll" => Scroll,
    }
    // `start`/`end` are the physical variants, `flexStart`/`flexEnd` the
    // flow-relative ones — they diverge in grid and reversed-flex containers,
    // so the keywords must not collapse together. The alignment enums' bevy
    // default is the keyword-less `Default` variant ("align per the layout
    // spec"), which is also the unrecognized-keyword fallback. The `safe*`
    // keywords are bevy's `*Safe` variants (aligned like the plain keyword
    // while the content fits, at the start once it would overflow) — every
    // one each enum has: the grid-only `justifyItems`/`justifySelf` have no
    // flow-relative pair.
    fn de_align_items("alignItems") -> AlignItems as ALIGN_ITEMS_KEYWORDS {
        "start" => Start, "end" => End,
        "flexStart" => FlexStart, "flexEnd" => FlexEnd,
        "center" => Center, "baseline" => Baseline, "stretch" => Stretch,
        "safeStart" => StartSafe, "safeEnd" => EndSafe,
        "safeFlexStart" => FlexStartSafe, "safeFlexEnd" => FlexEndSafe,
        "safeCenter" => CenterSafe,
    }
    fn de_justify_items("justifyItems") -> JustifyItems as JUSTIFY_ITEMS_KEYWORDS {
        "start" => Start, "end" => End,
        "center" => Center, "baseline" => Baseline, "stretch" => Stretch,
        "safeStart" => StartSafe, "safeEnd" => EndSafe, "safeCenter" => CenterSafe,
    }
    fn de_align_self("alignSelf") -> AlignSelf as ALIGN_SELF_KEYWORDS {
        "auto" => Auto, "start" => Start, "end" => End,
        "flexStart" => FlexStart, "flexEnd" => FlexEnd,
        "center" => Center, "baseline" => Baseline, "stretch" => Stretch,
        "safeStart" => StartSafe, "safeEnd" => EndSafe,
        "safeFlexStart" => FlexStartSafe, "safeFlexEnd" => FlexEndSafe,
        "safeCenter" => CenterSafe,
    }
    fn de_justify_self("justifySelf") -> JustifySelf as JUSTIFY_SELF_KEYWORDS {
        "auto" => Auto, "start" => Start, "end" => End,
        "center" => Center, "baseline" => Baseline, "stretch" => Stretch,
        "safeStart" => StartSafe, "safeEnd" => EndSafe, "safeCenter" => CenterSafe,
    }
    fn de_align_content("alignContent") -> AlignContent as ALIGN_CONTENT_KEYWORDS {
        "start" => Start, "end" => End,
        "flexStart" => FlexStart, "flexEnd" => FlexEnd,
        "center" => Center, "stretch" => Stretch,
        "spaceBetween" => SpaceBetween, "spaceEvenly" => SpaceEvenly,
        "spaceAround" => SpaceAround,
        "safeStart" => StartSafe, "safeEnd" => EndSafe,
        "safeFlexStart" => FlexStartSafe, "safeFlexEnd" => FlexEndSafe,
        "safeCenter" => CenterSafe,
    }
    fn de_justify_content("justifyContent") -> JustifyContent as JUSTIFY_CONTENT_KEYWORDS {
        "start" => Start, "end" => End,
        "flexStart" => FlexStart, "flexEnd" => FlexEnd,
        "center" => Center, "stretch" => Stretch,
        "spaceBetween" => SpaceBetween, "spaceEvenly" => SpaceEvenly,
        "spaceAround" => SpaceAround,
        "safeStart" => StartSafe, "safeEnd" => EndSafe,
        "safeFlexStart" => FlexStartSafe, "safeFlexEnd" => FlexEndSafe,
        "safeCenter" => CenterSafe,
    }
    fn de_flex_direction("flexDirection") -> FlexDirection as FLEX_DIRECTION_KEYWORDS {
        "row" => Row, "column" => Column,
        "rowReverse" => RowReverse, "columnReverse" => ColumnReverse,
    }
    fn de_flex_wrap("flexWrap") -> FlexWrap as FLEX_WRAP_KEYWORDS {
        "nowrap" | "noWrap" => NoWrap, "wrap" => Wrap, "wrapReverse" => WrapReverse,
    }
    fn de_grid_auto_flow("gridAutoFlow") -> GridAutoFlow as GRID_AUTO_FLOW_KEYWORDS {
        "row" => Row, "column" => Column,
        "rowDense" => RowDense, "columnDense" => ColumnDense,
    }
    // Unknown values fall back to `Pass` (bevy's default) so a typo stays
    // click-through rather than silently swallowing pointer interaction.
    fn de_focus_policy("focusPolicy") -> FocusPolicy as FOCUS_POLICY_KEYWORDS {
        "block" => Block, "pass" => Pass,
    }
    fn de_text_align("textAlign") -> Justify as TEXT_ALIGN_KEYWORDS {
        "left" => Left, "center" => Center, "right" => Right,
        "justify" => Justified, "start" => Start, "end" => End,
    }
    fn de_line_break("lineBreak") -> LineBreak as LINE_BREAK_KEYWORDS {
        "wordBoundary" => WordBoundary, "anyCharacter" => AnyCharacter,
        "wordOrCharacter" => WordOrCharacter, "noWrap" => NoWrap,
    }
    // Unknown keywords (incl. `<image>`-only modes like "auto"/"sliced") fall
    // back to the layout-inert `Stretch`.
    fn de_bg_image_mode("backgroundImage") -> BackgroundImageMode {
        "stretch" => Stretch, "repeat" => Repeat,
        "repeatX" => RepeatX, "repeatY" => RepeatY,
    }
    // The sub-fields of a styled `scrollbar` object (decoded inside its own
    // visitor, hence no table).
    fn de_scrollbar_position("scrollbar") -> ScrollbarPosition {
        "gutter" => Gutter, "float" => Float,
    }
    fn de_scrollbar_vertical_side("scrollbar") -> HorizontalEdge {
        "left" => Left, "right" => Right,
    }
    fn de_scrollbar_horizontal_side("scrollbar") -> VerticalEdge {
        "top" => Top, "bottom" => Bottom,
    }
    // GPU sampling vocabulary on purpose (no CSS `smooth`/`pixelated`
    // aliases); unknown → `auto`, which never touches the asset.
    fn de_image_rendering("imageRendering") -> ImageRendering as IMAGE_RENDERING_KEYWORDS {
        "auto" => Auto, "bilinear" => Bilinear,
        "trilinear" => Trilinear, "nearest" => Nearest,
    }
}

/// `fontWeight`: a named keyword or a numeric weight string (`"600"`). Not a
/// [`keyword_fields!`] entry because of the numeric form. Unrecognized → warn +
/// `NORMAL` (400).
pub(crate) fn de_font_weight<'de, D: Deserializer<'de>>(
    d: D,
) -> Result<Option<FontWeight>, D::Error> {
    struct V;
    impl<'de> Visitor<'de> for V {
        type Value = Option<FontWeight>;
        fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
            f.write_str("a `fontWeight` keyword or numeric weight string")
        }
        fn visit_str<E: de::Error>(self, s: &str) -> Result<Self::Value, E> {
            Ok(Some(match s {
                "thin" => FontWeight::THIN,
                "light" => FontWeight(300),
                "normal" => FontWeight::NORMAL,
                "medium" => FontWeight(500),
                "semibold" => FontWeight(600),
                "bold" => FontWeight::BOLD,
                "black" => FontWeight::BLACK,
                other => other.parse::<u16>().map(FontWeight).unwrap_or_else(|_| {
                    decode_warn(
                        "fontWeight",
                        other,
                        &format!("unrecognized fontWeight {other:?}"),
                    );
                    FontWeight::NORMAL
                }),
            }))
        }
        fn visit_unit<E: de::Error>(self) -> Result<Self::Value, E> {
            Ok(None)
        }
        fn visit_none<E: de::Error>(self) -> Result<Self::Value, E> {
            Ok(None)
        }
    }
    d.deserialize_any(V)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::style::Style;
    use crate::style::props::{
        ALIGN_CONTENT, ALIGN_ITEMS, ALIGN_SELF, BOX_SIZING, DISPLAY, FLEX_DIRECTION, FLEX_WRAP,
        FOCUS_POLICY, FONT_WEIGHT, JUSTIFY_CONTENT, JUSTIFY_ITEMS, JUSTIFY_SELF, LINE_BREAK,
        TEXT_ALIGN,
    };

    /// Keyword style fields decode straight into their `bevy_ui`/`bevy_text`
    /// enums; `start`/`end` map to the physical `Start`/`End` variants while
    /// `flexStart`/`flexEnd` map to the flow-relative `FlexStart`/`FlexEnd`.
    /// They diverge in grid and reversed-flex containers, so the keywords must
    /// not collapse together.
    #[test]
    fn keyword_fields_decode_to_bevy_enums() {
        let s: Style = serde_json::from_value(serde_json::json!({
            "display": "grid",
            "alignItems": "start",
            "alignSelf": "flexStart",
            "alignContent": "spaceBetween",
            "justifyContent": "flexEnd",
            "flexWrap": "nowrap",
            "focusPolicy": "block",
            "textAlign": "justify",
            "lineBreak": "anyCharacter",
        }))
        .expect("keyword style decodes");
        assert_eq!(s.get(&DISPLAY).copied(), Some(Display::Grid));
        assert_eq!(s.get(&ALIGN_ITEMS).copied(), Some(AlignItems::Start));
        assert_eq!(s.get(&ALIGN_SELF).copied(), Some(AlignSelf::FlexStart));
        assert_eq!(
            s.get(&ALIGN_CONTENT).copied(),
            Some(AlignContent::SpaceBetween)
        );
        assert_eq!(
            s.get(&JUSTIFY_CONTENT).copied(),
            Some(JustifyContent::FlexEnd)
        );
        assert_eq!(s.get(&FLEX_WRAP).copied(), Some(FlexWrap::NoWrap));
        assert_eq!(s.get(&FOCUS_POLICY).copied(), Some(FocusPolicy::Block));
        assert_eq!(s.get(&TEXT_ALIGN).copied(), Some(Justify::Justified));
        assert_eq!(s.get(&LINE_BREAK).copied(), Some(LineBreak::AnyCharacter));

        let s: Style = serde_json::from_value(serde_json::json!({
            "alignItems": "flexStart",
            "justifyContent": "start",
            // both keyword spellings of boxSizing are accepted
            "boxSizing": "border-box",
            "flexWrap": "noWrap",
        }))
        .expect("alias keywords decode");
        assert_eq!(s.get(&ALIGN_ITEMS).copied(), Some(AlignItems::FlexStart));
        assert_eq!(
            s.get(&JUSTIFY_CONTENT).copied(),
            Some(JustifyContent::Start)
        );
        assert_eq!(s.get(&BOX_SIZING).copied(), Some(BoxSizing::BorderBox));
        assert_eq!(s.get(&FLEX_WRAP).copied(), Some(FlexWrap::NoWrap));
    }

    /// The `safe*` alignment keywords decode to bevy's `*Safe` variants, on
    /// each property that has them: all five on the four flex/grid ones, the
    /// three physical ones on the grid-only `justifyItems`/`justifySelf`.
    #[test]
    fn safe_alignment_keywords_decode_to_the_safe_variants() {
        let s: Style = serde_json::from_value(serde_json::json!({
            "alignItems": "safeCenter",
            "alignSelf": "safeFlexEnd",
            "alignContent": "safeEnd",
            "justifyContent": "safeFlexStart",
            "justifyItems": "safeStart",
            "justifySelf": "safeCenter",
        }))
        .expect("keyword style decodes");
        assert_eq!(s.get(&ALIGN_ITEMS).copied(), Some(AlignItems::CenterSafe));
        assert_eq!(s.get(&ALIGN_SELF).copied(), Some(AlignSelf::FlexEndSafe));
        assert_eq!(s.get(&ALIGN_CONTENT).copied(), Some(AlignContent::EndSafe));
        assert_eq!(
            s.get(&JUSTIFY_CONTENT).copied(),
            Some(JustifyContent::FlexStartSafe)
        );
        assert_eq!(
            s.get(&JUSTIFY_ITEMS).copied(),
            Some(JustifyItems::StartSafe)
        );
        assert_eq!(s.get(&JUSTIFY_SELF).copied(), Some(JustifySelf::CenterSafe));
        for table in [
            ALIGN_ITEMS_KEYWORDS.keywords,
            JUSTIFY_CONTENT_KEYWORDS.keywords,
        ] {
            let safe = table.iter().filter(|k| k.starts_with("safe")).count();
            assert_eq!(safe, 5, "{table:?}");
        }
        // No flow-relative pair on the grid-only keys: the keyword warns and
        // falls back like any unknown one.
        let s: Style =
            serde_json::from_value(serde_json::json!({ "justifyItems": "safeFlexStart" }))
                .expect("decodes");
        assert_eq!(s.get(&JUSTIFY_ITEMS).copied(), Some(JustifyItems::Default));
    }

    /// What the keyword promises, under bevy's real layout: two 80px items
    /// in a 100px row overflow on both sides when centered, and start at the
    /// row's own start with `safeCenter`. Items that fit are centered by
    /// both.
    #[test]
    fn safe_center_falls_back_to_start_on_overflow() {
        use bevy::prelude::*;
        let mut app = crate::transition::layout_tests::layout_app();
        let root = app
            .world_mut()
            .spawn(Node {
                width: Val::Vw(100.0),
                height: Val::Vh(100.0),
                flex_direction: FlexDirection::Column,
                ..Default::default()
            })
            .id();
        let mut row = |justify: &str, width: f32| {
            let style: Style =
                serde_json::from_value(serde_json::json!({ "justifyContent": justify }))
                    .expect("decodes");
            let row = Node {
                width: Val::Px(100.0),
                height: Val::Px(20.0),
                justify_content: style.get(&JUSTIFY_CONTENT).copied().unwrap(),
                ..Default::default()
            };
            let row = app.world_mut().spawn((row, ChildOf(root))).id();
            let item = Node {
                width: Val::Px(width),
                flex_shrink: 0.0,
                ..Default::default()
            };
            let first = app.world_mut().spawn((item.clone(), ChildOf(row))).id();
            app.world_mut().spawn((item, ChildOf(row)));
            (row, first)
        };
        let rows = [
            (row("center", 80.0), -30.0),
            (row("safeCenter", 80.0), 0.0),
            (row("center", 20.0), 30.0),
            (row("safeCenter", 20.0), 30.0),
        ];
        app.update();
        let left = |e: Entity| {
            let node = app.world().entity(e).get::<ComputedNode>().unwrap();
            let global = app.world().entity(e).get::<UiGlobalTransform>().unwrap();
            global.translation.x - 0.5 * node.size.x
        };
        for ((row, first), offset) in rows {
            assert_eq!(left(first) - left(row), offset);
        }
    }

    /// An unrecognized enum keyword falls back to the bevy default (and warns)
    /// rather than aborting the batch or being silently dropped — a valid
    /// sibling field still decodes.
    #[test]
    fn unknown_enum_keywords_fall_back_to_default() {
        let s: Style = serde_json::from_value(serde_json::json!({
            "display": "flx",
            "alignItems": "centre",
            "flexDirection": "sideways",
            "textAlign": "middle",
            "fontWeight": "heavyish",
            "focusPolicy": "weird",
            // A valid sibling proves the fallbacks didn't abort the Style.
            "lineBreak": "wordBoundary",
        }))
        .expect("bad keywords must not abort deserialization");
        assert_eq!(s.get(&DISPLAY).copied(), Some(Display::default()));
        assert_eq!(s.get(&ALIGN_ITEMS).copied(), Some(AlignItems::default()));
        assert_eq!(
            s.get(&FLEX_DIRECTION).copied(),
            Some(FlexDirection::default())
        );
        assert_eq!(s.get(&TEXT_ALIGN).copied(), Some(Justify::default()));
        assert_eq!(s.get(&FONT_WEIGHT).copied(), Some(FontWeight::NORMAL));
        assert_eq!(s.get(&FOCUS_POLICY).copied(), Some(FocusPolicy::Pass));
        assert_eq!(s.get(&LINE_BREAK).copied(), Some(LineBreak::WordBoundary));
    }

    /// `fontWeight` takes a named keyword or a numeric weight string.
    #[test]
    fn font_weight_keywords_and_numeric() {
        let fw = |v: serde_json::Value| {
            serde_json::from_value::<Style>(serde_json::json!({ "fontWeight": v }))
                .expect("fontWeight decodes")
                .get(&FONT_WEIGHT)
                .copied()
        };
        assert_eq!(fw("bold".into()), Some(FontWeight::BOLD));
        assert_eq!(fw("600".into()), Some(FontWeight(600)));
        assert_eq!(fw("thin".into()), Some(FontWeight::THIN));
    }
}