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
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
//! `tabIndex` → `TabIndex`, and [`sync_focus`]: `FocusState`, `focusStyle`
//! and the `focus`/`blur` events off bevy's `InputFocus`, through the op
//! harness.

use bevy::a11y::AccessibilityNode;
use bevy::input_focus::tab_navigation::{TabGroup, TabIndex};
use bevy::input_focus::{FocusCause, InputFocus, InputFocusVisible};
use bevy::prelude::*;
use serde_json::json;

use super::sync_focus;
use crate::bridge::{FocusState, OutboundResource};
use crate::protocol::op::Op;
use crate::protocol::outbound::Outbound;
use crate::protocol::{NodeId, ROOT_ID};
use crate::reconcile::test_util::{create, ent, op_app_with, update};
use crate::reconcile::{apply_interaction_styles, apply_js_ops};

type Outbox = tokio::sync::mpsc::UnboundedReceiver<Outbound>;

/// The op harness with bevy's focus resources, [`sync_focus`] and the
/// restyle scheduled as the plugin does, and a readable outbound channel.
fn focus_app(setup: impl FnOnce(&mut App)) -> (App, crossbeam_channel::Sender<Vec<Op>>, Outbox) {
    let (mut app, tx) = op_app_with(|app| {
        app.init_resource::<InputFocus>()
            .init_resource::<InputFocusVisible>()
            .add_systems(
                Update,
                (
                    sync_focus.after(apply_js_ops),
                    apply_interaction_styles.after(sync_focus),
                ),
            );
        setup(app);
    });
    let (out, rx) = tokio::sync::mpsc::unbounded_channel();
    app.insert_resource(OutboundResource(out));
    (app, tx, rx)
}

fn focus(app: &mut App, id: NodeId) {
    let entity = ent(app, id);
    app.world_mut()
        .resource_mut::<InputFocus>()
        .set(entity, FocusCause::Navigated);
}

fn focused(app: &App) -> Option<Entity> {
    app.world().resource::<InputFocus>().get()
}

/// The element events sent since the last call, as `(node, event)`.
fn events(rx: &mut Outbox) -> Vec<(NodeId, String)> {
    std::iter::from_fn(|| rx.try_recv().ok())
        .filter_map(|out| match out {
            Outbound::ElementEvent { id, event, .. } => Some((id, event)),
            _ => None,
        })
        .collect()
}

fn sent(pairs: &[(NodeId, &str)]) -> Vec<(NodeId, String)> {
    pairs.iter().map(|(id, e)| (*id, (*e).to_owned())).collect()
}

fn background(app: &App, id: NodeId) -> Color {
    app.world().get::<BackgroundColor>(ent(app, id)).unwrap().0
}

/// `tabIndex` lands as bevy's `TabIndex` (with an accessibility node, which
/// bevy_winit needs on the focused entity), follows a change, and goes when
/// unset; a node without it carries neither.
#[test]
fn tab_index_stamps_and_unsets() {
    let (mut app, tx, _rx) = focus_app(|_| {});
    tx.send(vec![
        create(1, "node", json!({ "tabIndex": 0 })),
        create(2, "node", json!({})),
    ])
    .unwrap();
    app.update();
    let (node, plain) = (ent(&app, 1), ent(&app, 2));
    assert_eq!(app.world().get::<TabIndex>(node), Some(&TabIndex(0)));
    assert!(app.world().get::<AccessibilityNode>(node).is_some());
    assert!(app.world().get::<TabIndex>(plain).is_none());
    assert!(app.world().get::<AccessibilityNode>(plain).is_none());

    tx.send(vec![update(1, "node", json!({ "tabIndex": -1 }), &[], &[])])
        .unwrap();
    app.update();
    assert_eq!(app.world().get::<TabIndex>(node), Some(&TabIndex(-1)));

    tx.send(vec![update(1, "node", json!({}), &["tabIndex"], &[])])
        .unwrap();
    app.update();
    assert!(app.world().get::<TabIndex>(node).is_none());
}

/// A text input is focusable without a `tabIndex` (`0`); the prop overrides,
/// and unsetting it returns to the default.
#[test]
fn an_input_is_focusable_by_default() {
    let (mut app, tx, _rx) = focus_app(|_| {});
    tx.send(vec![
        create(1, "editableText", json!({})),
        create(2, "editableText", json!({ "tabIndex": -1 })),
    ])
    .unwrap();
    app.update();
    let index = |app: &App, id| app.world().get::<TabIndex>(ent(app, id)).copied();
    assert_eq!(index(&app, 1), Some(TabIndex(0)));
    assert_eq!(index(&app, 2), Some(TabIndex(-1)));

    tx.send(vec![update(
        2,
        "editableText",
        json!({}),
        &["tabIndex"],
        &[],
    )])
    .unwrap();
    app.update();
    assert_eq!(index(&app, 2), Some(TabIndex(0)));
}

/// A `<root>` is a tab group of its own, after the window tree's.
#[test]
fn a_root_is_a_tab_group() {
    let (mut app, tx, _rx) = focus_app(|_| {});
    tx.send(vec![create(1, "root", json!({}))]).unwrap();
    app.update();
    let group = app.world().get::<TabGroup>(ent(&app, 1)).expect("a group");
    assert_eq!((group.order, group.modal), (1, false));
}

/// Moving the focus sends the old element's `blur`, then the new one's
/// `focus`, once per frame — to elements with the handler only.
#[test]
fn blur_then_focus_once_per_frame() {
    let (mut app, tx, mut rx) = focus_app(|_| {});
    let handlers = || json!({ "tabIndex": 0, "onFocus": true, "onBlur": true });
    tx.send(vec![
        create(1, "node", handlers()),
        create(2, "node", handlers()),
        create(3, "node", json!({ "tabIndex": 0 })),
    ])
    .unwrap();
    app.update();

    focus(&mut app, 1);
    app.update();
    assert_eq!(events(&mut rx), sent(&[(1, "focus")]));

    focus(&mut app, 2);
    app.update();
    assert_eq!(events(&mut rx), sent(&[(1, "blur"), (2, "focus")]));

    // Away and back within one frame: nothing happened.
    focus(&mut app, 1);
    focus(&mut app, 2);
    app.update();
    assert_eq!(events(&mut rx), []);

    focus(&mut app, 3);
    app.update();
    assert_eq!(events(&mut rx), sent(&[(2, "blur")]));

    app.world_mut().resource_mut::<InputFocus>().clear();
    app.update();
    assert_eq!(events(&mut rx), [], "node 3 has no handlers");

    // A handler dropped by a re-render is no longer called.
    tx.send(vec![update(1, "node", json!({}), &["onFocus"], &[])])
        .unwrap();
    focus(&mut app, 1);
    app.update();
    assert_eq!(events(&mut rx), []);
}

/// `focusStyle` applies in the frame the focus moves, and leaves with it.
#[test]
fn focus_style_lands_the_same_frame() {
    let (mut app, tx, _rx) = focus_app(|_| {});
    tx.send(vec![create(
        1,
        "node",
        json!({
            "tabIndex": 0,
            "style": { "backgroundColor": "red" },
            "focusStyle": { "backgroundColor": "blue" },
        }),
    )])
    .unwrap();
    app.update();
    let (red, blue) = (
        crate::ui_map::parse_color("red"),
        crate::ui_map::parse_color("blue"),
    );
    assert_eq!(background(&app, 1), red);

    focus(&mut app, 1);
    app.update();
    assert_eq!(background(&app, 1), blue);

    app.world_mut().resource_mut::<InputFocus>().clear();
    app.update();
    assert_eq!(background(&app, 1), red);
}

/// A `focusStyle` that arrives while the element is focused applies.
#[test]
fn a_focus_style_added_while_focused_applies() {
    let (mut app, tx, _rx) = focus_app(|_| {});
    tx.send(vec![create(1, "node", json!({ "tabIndex": 0 }))])
        .unwrap();
    app.update();
    focus(&mut app, 1);
    app.update();

    tx.send(vec![update(
        1,
        "node",
        json!({ "focusStyle": { "backgroundColor": "blue" } }),
        &[],
        &[],
    )])
    .unwrap();
    app.update();
    assert_eq!(background(&app, 1), crate::ui_map::parse_color("blue"));
}

/// An element that unmounts while focused gives the focus up at once (bevy
/// alone would keep naming the dead entity until the next key press). Its
/// `blur` is not sent: the handlers went with it.
#[test]
fn an_unmounted_focused_node_releases_the_focus() {
    let (mut app, tx, mut rx) = focus_app(|_| {});
    tx.send(vec![
        create(1, "node", json!({ "tabIndex": 0, "onBlur": true })),
        Op::Append {
            parent: ROOT_ID,
            child: 1,
        },
    ])
    .unwrap();
    app.update();
    focus(&mut app, 1);
    app.update();
    assert!(focused(&app).is_some());

    tx.send(vec![Op::Remove {
        parent: ROOT_ID,
        child: 1,
    }])
    .unwrap();
    app.update();
    assert_eq!(focused(&app), None);
    assert_eq!(events(&mut rx), []);
}

/// A control that becomes disabled while focused gives the focus up (with
/// its `blur`), and is focusable again once enabled.
#[test]
fn a_disabled_control_gives_the_focus_up() {
    let (mut app, tx, mut rx) = focus_app(|_| {});
    tx.send(vec![create(1, "editableText", json!({ "onBlur": true }))])
        .unwrap();
    app.update();
    focus(&mut app, 1);
    app.update();
    let index = |app: &App| app.world().get::<TabIndex>(ent(app, 1)).copied();

    tx.send(vec![update(
        1,
        "editableText",
        json!({ "disabled": true }),
        &[],
        &[],
    )])
    .unwrap();
    app.update();
    assert_eq!(focused(&app), None);
    assert_eq!(events(&mut rx), sent(&[(1, "blur")]));
    assert_eq!(index(&app), None, "nothing to press or Tab to");

    tx.send(vec![update(
        1,
        "editableText",
        json!({}),
        &["disabled"],
        &[],
    )])
    .unwrap();
    app.update();
    assert_eq!(index(&app), Some(TabIndex(0)));
}

/// `disabled` on a `<button>`: bevy's marker, and no `TabIndex` — a press
/// resolves past it and Tab skips it.
#[test]
fn a_disabled_button_is_not_focusable() {
    let (mut app, tx, _rx) = focus_app(|_| {});
    tx.send(vec![create(
        1,
        "button",
        json!({ "tabIndex": 0, "disabled": true }),
    )])
    .unwrap();
    app.update();
    let button = ent(&app, 1);
    let state = |app: &App| {
        let entity = app.world().entity(button);
        (
            entity.contains::<bevy::ui::InteractionDisabled>(),
            entity.contains::<TabIndex>(),
        )
    };
    assert_eq!(state(&app), (true, false));

    tx.send(vec![update(
        1,
        "button",
        json!({ "disabled": false }),
        &[],
        &[],
    )])
    .unwrap();
    app.update();
    assert_eq!(state(&app), (false, true));
}

/// The indicator bit follows bevy's `InputFocusVisible` while the focus
/// stays put; a text input shows it however it was focused — and its
/// `focusVisibleStyle` applies, with or without a `focusStyle`.
#[test]
fn the_indicator_follows_input_focus_visible() {
    let (mut app, tx, _rx) = focus_app(|_| {});
    let styled = || json!({ "tabIndex": 0, "focusStyle": { "backgroundColor": "blue" } });
    tx.send(vec![
        create(1, "node", styled()),
        create(
            2,
            "editableText",
            json!({
                "style": { "backgroundColor": "red" },
                "focusVisibleStyle": { "backgroundColor": "blue" },
            }),
        ),
    ])
    .unwrap();
    app.update();
    let state = |app: &App, id| *app.world().get::<FocusState>(ent(app, id)).unwrap();
    let on = |visible| FocusState {
        focused: true,
        visible,
    };

    focus(&mut app, 1);
    app.update();
    assert_eq!(state(&app, 1), on(false));

    app.world_mut().resource_mut::<InputFocusVisible>().0 = true;
    app.update();
    assert_eq!(state(&app, 1), on(true));

    app.world_mut().resource_mut::<InputFocusVisible>().0 = false;
    app.update();
    assert_eq!(state(&app, 1), on(false));

    focus(&mut app, 2);
    app.update();
    assert_eq!(state(&app, 1), FocusState::default());
    assert_eq!(state(&app, 2), on(true));
    assert_eq!(background(&app, 2), crate::ui_map::parse_color("blue"));
}

/// With bevy's `TabNavigationPlugin` (the app's opt-in) Tab walks the
/// focusables under a tab group in tree order, skipping negative indices,
/// and turns the focus indicator on.
#[test]
fn tab_walks_the_focusables() {
    use bevy::input::keyboard::{Key, KeyCode, KeyboardInput};
    use bevy::input::{ButtonState, InputPlugin};
    use bevy::input_focus::InputDispatchPlugin;
    use bevy::input_focus::tab_navigation::TabNavigationPlugin;
    use bevy::window::PrimaryWindow;

    let (mut app, tx, mut rx) = focus_app(|app| {
        app.add_plugins((InputPlugin, InputDispatchPlugin, TabNavigationPlugin))
            // What the key dispatch reads in a full app.
            .add_message::<bevy::input::gamepad::GamepadButtonChangedEvent>()
            .add_message::<bevy::input::mouse::MouseWheel>();
    });
    // The Tab observer attaches to the windows that exist at startup.
    let window = app
        .world_mut()
        .spawn((Window::default(), PrimaryWindow))
        .id();
    let root = app.world().resource::<crate::bridge::JsBridge>().nodes[&ROOT_ID];
    app.world_mut().entity_mut(root).insert(TabGroup::new(0));
    let mut ops = Vec::new();
    for (id, index) in [(1, 0), (2, -1), (3, 0)] {
        ops.push(create(
            id,
            "node",
            json!({ "tabIndex": index, "onFocus": true }),
        ));
        ops.push(Op::Append {
            parent: ROOT_ID,
            child: id,
        });
    }
    tx.send(ops).unwrap();
    app.update();
    // No visibility propagation here; Tab skips hidden subtrees.
    for id in 1..=3 {
        let entity = ent(&app, id);
        app.world_mut()
            .entity_mut(entity)
            .insert(InheritedVisibility::VISIBLE);
    }

    let tab = |app: &mut App| {
        for state in [ButtonState::Pressed, ButtonState::Released] {
            app.world_mut().write_message(KeyboardInput {
                key_code: KeyCode::Tab,
                logical_key: Key::Tab,
                state,
                text: None,
                repeat: false,
                window,
            });
            app.update();
        }
        focused(app)
    };
    assert_eq!(tab(&mut app), Some(ent(&app, 1)));
    assert_eq!(tab(&mut app), Some(ent(&app, 3)), "-1 is skipped");
    assert_eq!(tab(&mut app), Some(ent(&app, 1)), "and Tab wraps");
    assert!(app.world().resource::<InputFocusVisible>().0);
    assert_eq!(
        events(&mut rx),
        sent(&[(1, "focus"), (3, "focus"), (1, "focus")])
    );
}

/// Enter and Space click a focused `<button>`, once per key press: not on a
/// repeat, not on the release, and only a `<button>` (a focused
/// `<node onClick>` is not activated, as on the web).
#[test]
fn enter_and_space_click_a_focused_button() {
    use bevy::input::keyboard::{Key, KeyCode, KeyboardInput};
    use bevy::input::{ButtonState, InputPlugin};
    use bevy::input_focus::InputDispatchPlugin;
    use bevy::window::PrimaryWindow;

    let (mut app, tx, mut rx) = focus_app(|app| {
        // Bevy's own button widget handles the same keys (and stops their
        // propagation), as in a full app.
        app.add_plugins((
            InputPlugin,
            InputDispatchPlugin,
            bevy::ui_widgets::ButtonPlugin,
        ))
        // What the key dispatch reads in a full app.
        .add_message::<bevy::input::gamepad::GamepadButtonChangedEvent>()
        .add_message::<bevy::input::mouse::MouseWheel>()
        .add_observer(super::click_focused_button);
    });
    let window = app
        .world_mut()
        .spawn((Window::default(), PrimaryWindow))
        .id();
    tx.send(vec![
        create(1, "button", json!({ "tabIndex": 0, "onClick": true })),
        create(2, "node", json!({ "tabIndex": 0, "onClick": true })),
        create(
            3,
            "button",
            json!({ "tabIndex": 0, "onClick": true, "disabled": true }),
        ),
    ])
    .unwrap();
    app.update();
    let mut key = |app: &mut App, key_code, state, repeat| {
        app.world_mut().write_message(KeyboardInput {
            key_code,
            logical_key: Key::Enter,
            state,
            text: None,
            repeat,
            window,
        });
        app.update();
        std::iter::from_fn(|| rx.try_recv().ok())
            .filter_map(|out| match out {
                Outbound::UiEvent { event } => Some((event.id, event.kind)),
                _ => None,
            })
            .collect::<Vec<_>>()
    };
    let click = [(1, "click".to_owned())];
    let (down, up) = (ButtonState::Pressed, ButtonState::Released);

    focus(&mut app, 1);
    assert_eq!(key(&mut app, KeyCode::Enter, down, false), click);
    assert_eq!(key(&mut app, KeyCode::Enter, down, true), [], "a repeat");
    assert_eq!(key(&mut app, KeyCode::Enter, up, false), [], "the release");
    assert_eq!(key(&mut app, KeyCode::Space, down, false), click);
    assert_eq!(key(&mut app, KeyCode::KeyA, down, false), []);

    focus(&mut app, 2);
    assert_eq!(key(&mut app, KeyCode::Enter, down, false), [], "a node");

    // A disabled button: not even with a focus forced onto it.
    focus(&mut app, 3);
    assert_eq!(key(&mut app, KeyCode::Enter, down, false), []);
    assert_eq!(focused(&app), None);
}