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
/*!
[`ButtonBundle`]: bevy::prelude::ButtonBundle
[Changed]: bevy::prelude::Changed
[doc-root]: ./index.html
[`Entity`]: bevy::prelude::Entity
[entity-id]: bevy::ecs::system::EntityCommands::id
[`FocusableButtonBundle`]: components::FocusableButtonBundle
[`Focusable::cancel`]: resolve::Focusable::cancel
[`Focusable::block`]: resolve::Focusable::block
[`Focusable::dormant`]: resolve::Focusable::dormant
[`Focusable`]: resolve::Focusable
[`Focusable::lock`]: resolve::Focusable::lock
[`generic_default_mouse_input`]: systems::generic_default_mouse_input
[`InputMapping`]: systems::InputMapping
[`InputMapping::keyboard_navigation`]: systems::InputMapping::keyboard_navigation
[module-event_helpers]: events::NavEventReaderExt
[module-marking]: mark
[module-systems]: systems
[Name]: bevy::core::Name
[`NavEvent::FocusChanged`]: events::NavEvent::FocusChanged
[`NavEvent`]: events::NavEvent
[`NavEvent::InitiallyFocused`]: events::NavEvent::InitiallyFocused
[`MenuSetting`]: menu::MenuSetting
[`NavMenu`]: menu::MenuSetting
[`MenuBuilder`]: menu::MenuBuilder
[MenuBuilder::reachable_from]: menu::MenuBuilder::EntityParent
[MenuBuilder::reachable_from_named]: menu::MenuBuilder::from_named
[`NavRequest`]: events::NavRequest
[`NavRequest::Action`]: events::NavRequest::Action
[`NavRequest::FocusOn`]: events::NavRequest::FocusOn
[`NavRequest::Free`]: events::NavRequest::Unlock
[`NavRequest::Unlock`]: events::NavRequest::Unlock
[`NavRequest::ScopeMove`]: events::NavRequest::ScopeMove
[`NavRequestSystem`]: NavRequestSystem
*/
#![forbid(missing_docs)]
#![doc = include_str!("../Readme.md")]
mod commands;
#[cfg(feature = "bevy_ui")]
pub mod components;
pub mod events;
mod marker;
pub mod menu;
mod named;
mod resolve;
pub mod systems;

use std::marker::PhantomData;

use bevy::app::PluginGroupBuilder;
use bevy::ecs::system::{SystemParam, SystemParamItem};
use bevy::prelude::*;

pub use non_empty_vec::NonEmpty;

#[cfg(feature = "bevy_ui")]
use resolve::UiProjectionQuery;

/// Default imports for `bevy_ui_navigation`.
pub mod prelude {
    pub use crate::events::{NavEvent, NavEventReaderExt, NavRequest};
    pub use crate::menu::{MenuBuilder, MenuSetting};
    pub use crate::resolve::{
        FocusAction, FocusState, Focusable, Focused, MenuNavigationStrategy, NavLock,
    };
    pub use crate::NavRequestSystem;
    #[cfg(feature = "bevy_ui")]
    pub use crate::{DefaultNavigationPlugins, NavigationPlugin};
}
/// Utilities to mark focusables within a menu with a specific component.
pub mod mark {
    pub use crate::menu::NavMarker;
    pub use crate::NavMarkerPropagationPlugin;
}
/// Types useful to define your own custom navigation inputs.
pub mod custom {
    #[cfg(feature = "bevy_ui")]
    pub use crate::resolve::UiProjectionQuery;
    pub use crate::resolve::{Rect, ScreenBoundaries};
    pub use crate::GenericNavigationPlugin;
}

/// Plugin for menu marker propagation.
///
/// For a marker of type `T` to be propagated when using
/// [`mark::NavMarker`], you need to add a
/// `NavMarkerPropagationPlugin<T>` to your bevy app. It is possible to add any
/// amount of `NavMarkerPropagationPlugin<T>` for as many `T` you need to
/// propagate through the menu system.
pub struct NavMarkerPropagationPlugin<T>(PhantomData<T>);
impl<T> NavMarkerPropagationPlugin<T> {
    #[allow(clippy::new_without_default)]
    /// Create a new [`NavMarkerPropagationPlugin`].
    pub fn new() -> Self {
        NavMarkerPropagationPlugin(PhantomData)
    }
}

impl<T: 'static + Sync + Send + Component + Clone> Plugin for NavMarkerPropagationPlugin<T> {
    fn build(&self, app: &mut App) {
        app.add_system(marker::mark_new_menus::<T>)
            .add_system(marker::mark_new_focusables::<T>);
    }
}

/// The label of the system in which the [`NavRequest`] events are handled, the
/// focus state of the [`Focusable`]s is updated and the [`NavEvent`] events
/// are sent.
///
/// Systems updating visuals of UI elements should run _after_ the `NavRequestSystem`,
/// while systems that emit [`NavRequest`] should run _before_ it.
/// For example, an input system should run before the `NavRequestSystem`.
///
/// Failing to do so won't cause logical errors, but will make the UI feel more slugish
/// than necessary. This is especially critical of you are running on low framerate.
///
/// # Example
///
/// ```rust, no_run
/// use bevy_ui_navigation::prelude::*;
/// use bevy_ui_navigation::events::Direction;
/// use bevy_ui_navigation::custom::GenericNavigationPlugin;
/// use bevy::prelude::*;
/// # use std::marker::PhantomData;
/// # use bevy::ecs::system::SystemParam;
/// # #[derive(SystemParam)] struct MoveCursor3d<'w, 's> {
/// #   #[system_param(ignore)] _foo: PhantomData<(&'w (), &'s ())>
/// # }
/// # impl<'w, 's> MenuNavigationStrategy for MoveCursor3d<'w, 's> {
/// #   fn resolve_2d<'a>(
/// #       &self,
/// #       focused: Entity,
/// #       direction: Direction,
/// #       cycles: bool,
/// #       siblings: &'a [Entity],
/// #   ) -> Option<&'a Entity> { None }
/// # }
/// # fn button_system() {}
/// fn main() {
///     App::new()
///         .add_plugin(GenericNavigationPlugin::<MoveCursor3d>::new())
///         // ...
///         // Add the button color update system after the focus update system
///         .add_system(button_system.after(NavRequestSystem))
///         // ...
///         .run();
/// }
/// ```
///
/// [`NavRequest`]: prelude::NavRequest
/// [`NavEvent`]: prelude::NavEvent
/// [`Focusable`]: prelude::Focusable
#[derive(Clone, Debug, Hash, PartialEq, Eq, SystemSet)]
pub struct NavRequestSystem;

/// The navigation plugin.
///
/// Add it to your app with `.add_plugin(NavigationPlugin::new())` and send
/// [`NavRequest`]s to move focus within declared [`Focusable`] entities.
///
/// You should prefer `bevy_ui` provided defaults
/// if you don't want to bother with that.
///
/// # Note on generic parameters
///
/// The `STGY` type parameter might seem complicated, but all you have to do
/// is for your type to implement [`SystemParam`] and [`MenuNavigationStrategy`].
///
/// [`MenuNavigationStrategy`]: resolve::MenuNavigationStrategy
/// [`Focusable`]: prelude::Focusable
/// [`NavRequest`]: prelude::NavRequest
#[derive(Default)]
pub struct GenericNavigationPlugin<STGY>(PhantomData<fn() -> STGY>);
#[cfg(feature = "bevy_ui")]
/// A default [`GenericNavigationPlugin`] for `bevy_ui`.
pub type NavigationPlugin<'w, 's> = GenericNavigationPlugin<UiProjectionQuery<'w, 's>>;

impl<STGY: resolve::MenuNavigationStrategy> GenericNavigationPlugin<STGY> {
    /// Create a new [`GenericNavigationPlugin`] with the provided `STGY`,
    /// see also [`resolve::MenuNavigationStrategy`].
    pub fn new() -> Self {
        Self(PhantomData)
    }
}
impl<STGY: SystemParam + 'static> Plugin for GenericNavigationPlugin<STGY>
where
    for<'w, 's> SystemParamItem<'w, 's, STGY>: resolve::MenuNavigationStrategy,
{
    fn build(&self, app: &mut App) {
        #[cfg(feature = "bevy_reflect")]
        app.register_type::<resolve::Focusable>()
            .register_type::<resolve::FocusState>()
            .register_type::<resolve::FocusAction>()
            .register_type::<menu::MenuSetting>()
            .register_type::<resolve::TreeMenu>();

        app.add_event::<events::NavRequest>()
            .add_event::<events::NavEvent>()
            .insert_resource(resolve::NavLock::new())
            .add_system(resolve::set_first_focused.before(NavRequestSystem))
            .add_system(resolve::consistent_menu.before(NavRequestSystem))
            .add_system(resolve::listen_nav_requests::<STGY>.in_set(NavRequestSystem))
            .add_system(
                named::resolve_named_menus
                    .before(resolve::insert_tree_menus)
                    .in_base_set(CoreSet::PreUpdate),
            )
            .add_system(resolve::insert_tree_menus.in_base_set(CoreSet::PreUpdate));
    }
}

/// The navigation plugin and the default input scheme.
///
/// Add it to your app with `.add_plugins(DefaultNavigationPlugins)`.
///
/// This provides default implementations for input handling, if you want
/// your own custom input handling, you should use [`NavigationPlugin`] and
/// provide your own input handling systems.
#[cfg(feature = "bevy_ui")]
pub struct DefaultNavigationPlugins;
#[cfg(feature = "bevy_ui")]
impl PluginGroup for DefaultNavigationPlugins {
    fn build(self) -> PluginGroupBuilder {
        PluginGroupBuilder::start::<Self>()
            .add(NavigationPlugin::new())
            .add(systems::DefaultNavigationSystems)
    }
}

#[cfg(test)]
mod test {
    use crate::prelude::*;
    use bevy::{
        ecs::{event::Event, world::EntityMut},
        prelude::*,
    };

    use super::*;
    // Why things might fail?
    // -> State becomes inconsistent, assumptions are broken
    // How would assumptions be broken?
    // -> The ECS hierarchy changed under our feet
    // -> state was modified by users and we didn't expect it
    // -> internal state is not updated correctly to reflect the actual state
    // Consistency design:
    // - Strong dependency on bevy hierarchy not being mucked with
    //   (doesn't handle changed parents well)
    // - Need to get rid of TreeMenu::active_child probably
    // - Possible to "check and fix" the state in a system that accepts
    //   Changed<Parent> + RemovedComponent<Focusable | TreeMenu | Parent>
    // - But the check cannot anticipate when the hierarchy is changed,
    //   so we are doomed to expose to users inconsistent states
    //   -> implication: we don't need to maintain it in real time, since
    //      after certain hierarchy manipulations, it will be inconsistent either way.
    //      So we could do with only checking and updating when receiving
    //      NavRequest (sounds like good use case for system chaining)

    /// Define a menu structure to spawn.
    ///
    /// This just describes the menu structure,  use [`SpawnHierarchy::spawn`],
    /// to spawn the entities in the world,.
    enum SpawnHierarchy {
        Rootless(SpawnRootless),
        Menu(SpawnMenu),
    }
    impl SpawnHierarchy {
        fn spawn(self, world: &mut World) {
            match self {
                Self::Rootless(menu) => menu.spawn(world),
                Self::Menu(menu) => menu.spawn(&mut world.spawn_empty()),
            };
        }
    }
    struct SpawnFocusable {
        name: &'static str,
        prioritized: bool,
        child_menu: Option<SpawnMenu>,
    }

    impl SpawnFocusable {
        fn spawn(self, mut entity: EntityMut) {
            let SpawnFocusable {
                name,
                prioritized,
                child_menu,
            } = self;
            entity.insert(Name::new(name));
            let focusable = if prioritized {
                Focusable::new().prioritized()
            } else {
                Focusable::new()
            };
            entity.insert(focusable);
            if let Some(child_menu) = child_menu {
                // SAFETY: we do not call any methods on `entity` after `world_mut()`
                unsafe {
                    child_menu.spawn(&mut entity.world_mut().spawn_empty());
                };
                std::mem::drop(entity);
            }
        }
    }
    struct SpawnMenu {
        name: &'static str,
        children: Vec<SpawnFocusable>,
    }
    impl SpawnMenu {
        fn spawn(self, entity: &mut EntityMut) {
            let SpawnMenu { name, children } = self;
            let parent_focusable = name.strip_suffix(" Menu");
            let menu_builder = match parent_focusable {
                Some(name) => MenuBuilder::from_named(name),
                None => MenuBuilder::Root,
            };
            entity.insert((Name::new(name), menu_builder, MenuSetting::new()));
            entity.with_children(|commands| {
                for child in children.into_iter() {
                    child.spawn(commands.spawn_empty());
                }
            });
        }
    }
    struct SpawnRootless {
        focusables: Vec<SpawnFocusable>,
    }
    impl SpawnRootless {
        fn spawn(self, world: &mut World) {
            for focusable in self.focusables.into_iter() {
                focusable.spawn(world.spawn_empty())
            }
        }
    }
    /// Define a `SpawnHierarchy`.
    ///
    /// Syntax:
    /// - `spawn_hierarchy![ <focus_kind>, ... ]`:
    ///   A hierarchy of focusable components with a root menu.
    /// - `spawn_hierarchy!(@rootless [ <focus_kind> , ...] )`:
    ///   A hierarchy of focusable components **without** a root menu.
    /// - `<focus_kind>` is one of the following:
    ///   - `focusable("Custom")`: a focusable with the `Name::new("Custom")` component
    ///   - `focusable_to("Custom" [ <focus_kind> , ...] )`:
    ///     a focusable with the `Name::new("Custom")` component, parent of a menu (`MenuBuilder`)
    ///     marked with the `Name::new("Custom Menu")` component. The menu content is the
    ///     content of the provided list
    ///   - `prioritized("Custom")`: a focusable with the `Name::new("Custom")` component,
    ///     spawned with `Focusable::new().prioritized()`.
    macro_rules! spawn_hierarchy {
        ( @rootless [ $( $elem_kind:ident $elem_args:tt ),* $(,)? ] ) => (
            SpawnHierarchy::Rootless(SpawnRootless {
                focusables: vec![ $(
                    spawn_hierarchy!(@elem $elem_kind $elem_args),
                )* ],
            })
        );
        ( @menu $name:expr, $( $elem_name:ident $elem_args:tt ),* $(,)? ) => (
            SpawnMenu {
                name: $name,
                children: vec![ $(
                    spawn_hierarchy!(@elem $elem_name $elem_args),
                )* ],
            }
        );
        ( @elem prioritized ( $name:literal ) ) => (
            SpawnFocusable {
                name: $name,
                prioritized: true,
                child_menu: None,
            }
        );
        ( @elem focusable ( $name:literal ) ) => (
            SpawnFocusable {
                name: $name,
                prioritized: false,
                child_menu: None,
            }
        );
        ( @elem focusable_to ( $name:literal [ $( $submenu:tt )* ] ) ) => (
            SpawnFocusable {
                name: $name,
                prioritized: false,
                child_menu: Some( spawn_hierarchy!(@menu concat!( $name , " Menu"),  $( $submenu )* ) ),
            }
        );
        ($( $elem_name:ident $elem_args:tt ),* $(,)? ) => (
            SpawnHierarchy::Menu(spawn_hierarchy!(@menu "Root", $( $elem_name $elem_args ),*))
        );
    }

    /// Assert identity of a list of entities by their `Name` component
    /// (makes understanding test failures easier)
    ///
    /// This is a macro, so that when there is an assert failure or panic,
    /// the line of code it points to is the calling site,
    /// rather than the function body.
    ///
    /// There is nothing beside that that would prevent converting this into a function.
    macro_rules! assert_expected_focus_change {
        ($app:expr, $events:expr, $expected_from:expr, $expected_to:expr $(,)?) => {
            if let [NavEvent::FocusChanged { to, from }] = $events {
                let actual_from = $app.name_list(&*from);
                assert_eq!(&*actual_from, $expected_from);

                let actual_to = $app.name_list(&*to);
                assert_eq!(&*actual_to, $expected_to);
            } else {
                panic!(
                    "Expected a signle FocusChanged NavEvent, got: {:#?}",
                    $events
                );
            }
        };
    }

    // A navigation strategy that does nothing, useful for testing.
    #[derive(SystemParam)]
    struct MockNavigationStrategy<'w, 's> {
        #[system_param(ignore)]
        _f: PhantomData<fn() -> (&'w (), &'s ())>,
    }
    // Just to make the next `impl` block shorter, unused otherwise.
    use events::Direction as D;
    impl<'w, 's> MenuNavigationStrategy for MockNavigationStrategy<'w, 's> {
        fn resolve_2d<'a>(&self, _: Entity, _: D, _: bool, _: &'a [Entity]) -> Option<&'a Entity> {
            None
        }
    }
    fn receive_events<E: Event + Clone>(world: &World) -> Vec<E> {
        let events = world.resource::<Events<E>>();
        events.iter_current_update_events().cloned().collect()
    }

    /// Wrapper around `App` to make it easier to test the navigation systems.
    struct NavEcsMock {
        app: App,
    }
    impl NavEcsMock {
        fn currently_focused(&mut self) -> &str {
            let mut query = self.app.world.query_filtered::<&Name, With<Focused>>();
            &**query.iter(&self.app.world).next().unwrap()
        }
        fn kill_named(&mut self, to_kill: &str) -> Vec<NavEvent> {
            let mut query = self.app.world.query::<(Entity, &Name)>();
            let requested = query
                .iter(&self.app.world)
                .find_map(|(e, name)| (&**name == to_kill).then(|| e));
            if let Some(to_kill) = requested {
                self.app.world.despawn(to_kill);
            }
            self.app.update();
            receive_events(&mut self.app.world)
        }
        fn name_list(&mut self, entity_list: &[Entity]) -> Vec<&str> {
            let mut query = self.app.world.query::<&Name>();
            entity_list
                .iter()
                .filter_map(|e| query.get(&self.app.world, *e).ok())
                .map(|name| &**name)
                .collect()
        }
        fn new(hierarchy: SpawnHierarchy) -> Self {
            let mut app = App::new();
            app.add_plugin(GenericNavigationPlugin::<MockNavigationStrategy>::new());
            hierarchy.spawn(&mut app.world);
            // Run once to convert the `MenuSetting` and `MenuBuilder` into `TreeMenu`.
            app.update();

            Self { app }
        }
        fn run_focus_on(&mut self, entity_name: &str) -> Vec<NavEvent> {
            let mut query = self.app.world.query::<(Entity, &Name)>();
            let requested = query
                .iter(&self.app.world)
                .find_map(|(e, name)| (&**name == entity_name).then(|| e))
                .unwrap();
            self.app.world.send_event(NavRequest::FocusOn(requested));
            self.app.update();
            receive_events(&mut self.app.world)
        }
        fn run_request(&mut self, request: NavRequest) -> Vec<NavEvent> {
            self.app.world.send_event(request);
            self.app.update();
            receive_events(&mut self.app.world)
        }
        fn state_of(&mut self, requested: &str) -> FocusState {
            let mut query = self.app.world.query::<(&Focusable, &Name)>();
            let requested = query
                .iter(&self.app.world)
                .find_map(|(focus, name)| (&**name == requested).then(|| focus));
            requested.unwrap().state()
        }
    }

    // ====
    // Expected basic functionalities
    // ====

    #[test]
    fn move_in_menuless() {
        let mut app = NavEcsMock::new(spawn_hierarchy!(@rootless [
            prioritized("Initial"),
            focusable("Left"),
            focusable("Right"),
        ]));
        assert_eq!(app.currently_focused(), "Initial");
        app.run_focus_on("Left");
        assert_eq!(app.currently_focused(), "Left");
    }

    #[test]
    fn deep_initial_focusable() {
        let mut app = NavEcsMock::new(spawn_hierarchy![
            focusable("Middle"),
            focusable_to("Left" [
                focusable("LCenter1"),
                focusable("LCenter2"),
                focusable_to("LTop" [
                    prioritized("LTopForward"),
                    focusable("LTopBackward"),
                ]),
                focusable("LCenter3"),
                focusable("LBottom"),
            ]),
            focusable("Right"),
        ]);
        use FocusState::{Active, Inert};
        assert_eq!(app.currently_focused(), "LTopForward");
        assert_eq!(app.state_of("Left"), Active);
        assert_eq!(app.state_of("Right"), Inert);
        assert_eq!(app.state_of("Middle"), Inert);
        assert_eq!(app.state_of("LTop"), Active);
        assert_eq!(app.state_of("LCenter1"), Inert);
        assert_eq!(app.state_of("LTopBackward"), Inert);
    }

    #[test]
    fn move_in_complex_menu_hierarchy() {
        let mut app = NavEcsMock::new(spawn_hierarchy![
            prioritized("Initial"),
            focusable_to("Left" [
                focusable_to("LTop" [
                    focusable("LTopForward"),
                    focusable("LTopBackward"),
                ]),
                focusable_to("LBottom" [
                    focusable("LBottomForward"),
                    focusable("LBottomForward1"),
                    focusable("LBottomForward2"),
                    prioritized("LBottomBackward"),
                    focusable("LBottomForward3"),
                    focusable("LBottomForward4"),
                    focusable("LBottomForward5"),
                ]),
            ]),
            focusable_to("Right" [
                focusable_to("RTop" [
                    focusable("RTopForward"),
                    focusable("RTopBackward"),
                ]),
                focusable("RBottom"),
            ]),
        ]);
        assert_eq!(app.currently_focused(), "Initial");

        // Move deep into a menu
        let events = app.run_focus_on("RBottom");
        assert_expected_focus_change!(app, &events[..], ["Initial"], ["RBottom", "Right"]);

        // Go up and back down several layers of menus
        let events = app.run_focus_on("LTopForward");
        assert_expected_focus_change!(
            app,
            &events[..],
            ["RBottom", "Right"],
            ["LTopForward", "LTop", "Left"],
        );
        // See if cancel event works
        let events = app.run_request(NavRequest::Cancel);
        assert_expected_focus_change!(app, &events[..], ["LTopForward", "LTop"], ["LTop"]);

        // Move to sibling within menu
        let events = app.run_focus_on("LBottom");
        assert_expected_focus_change!(app, &events[..], ["LTop"], ["LBottom"]);

        // Move down into menu by activating a focusable
        // (also make sure `prioritized` works)
        let events = app.run_request(NavRequest::Action);
        assert_expected_focus_change!(
            app,
            &events[..],
            ["LBottom"],
            ["LBottomBackward", "LBottom"]
        );
    }

    // ====
    // What happens when Focused element is killed
    // ====

    // Select a new focusable in the same menu (or anything if no menus exist)
    #[test]
    fn focus_rootless_kill_robust() {
        let mut app = NavEcsMock::new(spawn_hierarchy!(@rootless [
            prioritized("Initial"),
            focusable("Right"),
        ]));
        assert_eq!(app.currently_focused(), "Initial");
        app.kill_named("Initial");
        assert_eq!(app.currently_focused(), "Right");

        app.kill_named("Right");
        let events = app.run_request(NavRequest::Action);
        assert_eq!(events.len(), 0, "{:#?}", events);
    }

    // Go up the menu tree if it was the last focusable in the menu
    // And swap to something in the same menu if focusable killed in it.
    #[test]
    fn menu_elem_kill_robust() {
        let mut app = NavEcsMock::new(spawn_hierarchy![
            focusable_to("Left" [
                focusable("LTop"),
                focusable("LBottom"),
            ]),
            focusable_to("Antony" [
                prioritized("Caesar"),
                focusable("Brutus"),
            ]),
            focusable_to("Octavian" [
                focusable("RTop"),
                focusable("RBottom"),
            ]),
        ]);
        // NOTE: was broken because didn't properly set
        // active_child and Active when initial focus was given to
        // a deep element.
        assert_eq!(app.currently_focused(), "Caesar");
        assert_eq!(app.state_of("Antony"), FocusState::Active);
        app.kill_named("Caesar");
        assert_eq!(app.currently_focused(), "Brutus");
        app.kill_named("Brutus");
        assert_eq!(app.currently_focused(), "Antony");
    }

    // ====
    // removal of parent menu and focusables
    // ====

    // Relink the child menu to the removed parent's parents
    // Make sure this works with root as well
    // Relink when the focusable parent of a menu is killed
    // NOTE: user is warned against engaging in such operations, implementation can wait

    // ====
    // some reparenting potential problems
    // ====

    // Focused element is reparented to a new menu
    // Active element is reparented to a new menu
    // NOTE: those are not expected to work. Currently considered a user error.
}