haalka::pointer_event_aware

Trait PointerEventAware

Source
pub trait PointerEventAware: RawElWrapper {
Show 22 methods // Provided methods fn on_hovered_change_with_system<Marker>( self, handler: impl IntoSystem<(Entity, bool), (), Marker> + Send + 'static, ) -> Self { ... } fn on_hovered_change( self, handler: impl FnMut(bool) + Send + Sync + 'static, ) -> Self { ... } fn hovered_sync(self, hovered: Mutable<bool>) -> Self { ... } fn on_click_with_system<Marker>( self, handler: impl IntoSystem<(Entity, Pointer<Click>), (), Marker> + Send + 'static, ) -> Self { ... } fn on_click(self, handler: impl FnMut() + Send + Sync + 'static) -> Self { ... } fn on_click_propagation_stoppable( self, handler: impl FnMut() + Send + Sync + 'static, propagation_stopped: impl Signal<Item = bool> + Send + 'static, ) -> Self { ... } fn on_click_stop_propagation( self, handler: impl FnMut() + Send + Sync + 'static, ) -> Self { ... } fn on_right_click( self, handler: impl FnMut() + Send + Sync + 'static, ) -> Self { ... } fn on_click_outside_with_system<Marker>( self, handler: impl IntoSystem<(Entity, Pointer<Click>), (), Marker> + Send + 'static, ) -> Self { ... } fn on_click_outside( self, handler: impl FnMut() + Send + Sync + 'static, ) -> Self { ... } fn on_pressed_with_system_blockable<Marker, Blocked: Component>( self, handler: impl IntoSystem<(Entity, bool), (), Marker> + Send + 'static, ) -> Self { ... } fn on_pressed_change_with_system<Marker>( self, handler: impl IntoSystem<(Entity, bool), (), Marker> + Send + 'static, ) -> Self { ... } fn on_pressed_change( self, handler: impl FnMut(bool) + Send + Sync + 'static, ) -> Self { ... } fn on_pressing_with_system_blockable<Marker, Blocked: Component>( self, handler: impl IntoSystem<Entity, (), Marker> + Send + 'static, ) -> Self { ... } fn on_pressing_blockable<Blocked: Component>( self, handler: impl FnMut() + Send + Sync + 'static, ) -> Self { ... } fn on_pressing_blockable_signal( self, handler: impl FnMut() + Send + Sync + 'static, blocked: impl Signal<Item = bool> + Send + 'static, ) -> Self { ... } fn on_pressing(self, handler: impl FnMut() + Send + Sync + 'static) -> Self { ... } fn on_pressing_with_system_throttled<Fut: Future<Output = ()> + Send + 'static, Marker>( self, handler: impl IntoSystem<Entity, (), Marker> + Send + 'static, throttle: impl FnMut() -> Fut + Send + 'static, ) -> Self { ... } fn on_pressing_with_system_with_sleep_throttle<Marker>( self, handler: impl IntoSystem<Entity, (), Marker> + Send + 'static, duration: Duration, ) -> Self { ... } fn on_pressing_throttled<Fut: Future<Output = ()> + Send + 'static>( self, handler: impl FnMut() + Send + Sync + 'static, throttle: impl FnMut() -> Fut + Send + 'static, ) -> Self { ... } fn on_pressing_with_sleep_throttle( self, handler: impl FnMut() + Send + Sync + 'static, duration: Duration, ) -> Self { ... } fn pressed_sync(self, pressed: Mutable<bool>) -> Self { ... }
}
Expand description

Enables reacting to pointer events like hover, click, and press. Port of MoonZoon’s PointerEventAware.

Provided Methods§

Source

fn on_hovered_change_with_system<Marker>( self, handler: impl IntoSystem<(Entity, bool), (), Marker> + Send + 'static, ) -> Self

When this element’s hovered state changes, run a System which takes In this element’s Entity and its current hovered state. This method can be called repeatedly to register many such handlers.

Source

fn on_hovered_change( self, handler: impl FnMut(bool) + Send + Sync + 'static, ) -> Self

When this element’s hover state changes, run a function with its current hovered state. This method can be called repeatedly to register many such handlers.

Examples found in repository?
examples/scroll_grid.rs (lines 77-81)
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
fn letter(
    x: usize,
    y: usize,
    letter_color: impl Signal<Item = LetterColor> + Send + 'static,
) -> impl Element {
    El::<TextBundle>::new()
    .on_hovered_change(move |is_hovered| {
        if is_hovered {
            async_world().insert_resource(HoveredCell(x, y)).apply(spawn).detach()
        }
    })
    .text_signal(
        letter_color.map(|LetterColor { letter, color }|
            Text::from_section(
                letter,
                TextStyle {
                    font_size: LETTER_SIZE,
                    color,
                    ..default()
                },
            )
        )
    )
}

#[derive(Clone, Default)]
struct LetterColor {
    letter: String,
    color: Color,
}

#[derive(Resource)]
struct Rails {
    vertical: Vec<Vec<LetterColor>>,
    horizontal: Vec<Vec<LetterColor>>,
}

const ROYGBIV: &[Srgba] = &[
    bevy::color::palettes::css::RED,
    bevy::color::palettes::css::ORANGE,
    bevy::color::palettes::css::YELLOW,
    bevy::color::palettes::css::GREEN,
    bevy::color::palettes::css::BLUE,
    bevy::color::palettes::css::INDIGO,
    bevy::color::palettes::css::VIOLET,
];

static CELLS: Lazy<Vec<Vec<Mutable<LetterColor>>>> = Lazy::new(|| {
    let cells = (0..5)
        .map(|_| (0..5).map(|_| Mutable::new(default())).collect::<Vec<_>>())
        .collect::<Vec<_>>();
    let letters = "abcdefghijklmnopqrstuvwxyz";
    for i in 0..5 {
        for (j, letter) in letters.chars().skip(i).take(5).enumerate() {
            cells[i][j].set(LetterColor {
                letter: letter.to_string(),
                color: ROYGBIV[i].into(),
            });
        }
    }
    cells
});

fn ui_root() -> impl Element {
    El::<NodeBundle>::new()
        .width(Val::Percent(100.))
        .height(Val::Percent(100.))
        .align_content(Align::center())
        .child(
            Grid::<NodeBundle>::new()
                .with_style(|mut style| style.column_gap = Val::Px(15.))
                .on_hovered_change(move |is_hovered| {
                    if !is_hovered {
                        async_world().remove_resource::<HoveredCell>().apply(spawn).detach()
                    }
                })
                .row_wrap_cell_width(48.)
                .width(Val::Px(300.))
                .height(Val::Px(5. * LETTER_SIZE))
                .align(Align::center())
                .cells(CELLS.iter().enumerate().flat_map(|(x, cells)| {
                    cells
                        .iter()
                        .enumerate()
                        .map(move |(y, cell)| letter(x, y, cell.signal_cloned()))
                })),
        )
}
More examples
Hide additional examples
examples/main_menu.rs (line 630)
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
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
fn menu_item(label: &str, body: impl Element, hovered: Mutable<bool>) -> Stack<NodeBundle> {
    Stack::<NodeBundle>::new()
        .background_color_signal(
            hovered
                .signal()
                .map_bool(|| NORMAL_BUTTON.lighter(0.05), || NORMAL_BUTTON)
                .map(BackgroundColor),
        )
        .on_hovered_change(move |is_hovered| only_one_up_flipper(&hovered, &MENU_ITEM_HOVERED_OPTION, Some(is_hovered)))
        .width(Val::Percent(100.))
        .height(Val::Px(MENU_ITEM_HEIGHT))
        .with_style(|mut style| style.padding = UiRect::axes(Val::Px(BASE_PADDING), Val::Px(BASE_PADDING / 2.)))
        .layer(
            El::<TextBundle>::new()
                .text(text(label))
                .align(Align::new().left().center_y()),
        )
        .layer(body.align(Align::new().right().center_y()))
}

struct Dropdown {
    el: El<NodeBundle>,
    controlling: Mutable<bool>,
}

fn focus_on_signal<E: Element>(element: E, signal: impl Signal<Item = bool> + Send + 'static) -> E {
    element.update_raw_el(|raw_el| {
        raw_el.on_signal(signal.dedupe(), |entity, focus| async move {
            if focus {
                // at first, i was using a `static_ref` global `Mutable<Option<Entity>>` for this
                // and wrapping it in a resource for accessing it in the menu input event systems, but this is an
                // anti pattern; the ecs should not be polling reactive ui state for syncing its own
                // state/systems (there's an example of this anti pattern in the ecs world ui world sync example https://github.com/databasedav/haalka/blob/main/examples/ecs_ui_sync/src/main.rs#L154);
                // instead, like we do here, simply use the `async_world` to update the ecs state *exactly and only*
                // when it needs to be
                async_world().insert_resource(FocusedEntity(entity)).await;
                // TODO: remove reference to ecs world ui world sync example once fixed
            }
        })
    })
}

impl Dropdown {
    fn new<T: Clone + PartialEq + Display + Send + Sync + 'static>(
        options: MutableVec<T>,
        selected: Mutable<Option<T>>,
        clearable: bool,
    ) -> Self {
        let show_dropdown = Mutable::new(false);
        let hovered = Mutable::new(false);
        let controlling = Mutable::new(false);
        let options_hovered =
            MutableVec::new_with_values((0..options.lock_ref().len()).map(|_| Mutable::new(false)).collect());
        let el = {
            El::<NodeBundle>::new()
            .apply(|element| focus_on_signal(element, controlling.signal()))
            .apply(|element| {
                input_event_listener_controller(
                    element,
                    controlling.signal(),
                    clone!((show_dropdown, hovered, options, options_hovered, selected) move || {
                        On::<MenuInputEvent>::run(clone!((show_dropdown, hovered, options, options_hovered, selected) move |mut event: ListenerMut<MenuInputEvent>| {
                            match event.input {
                                MenuInput::Up | MenuInput::Down => {
                                    if show_dropdown.get() {
                                        event.stop_propagation();
                                        let hovered_option = options_hovered.lock_ref().iter().position(|hovered| hovered.get());
                                        if let Some(i) = hovered_option {
                                            options_hovered.lock_ref()[i].set(false);
                                        }
                                        let (mut i, step) = {
                                            if matches!(event.input, MenuInput::Up) {
                                                (hovered_option.unwrap_or(options.lock_ref().len() - 1) as isize, -1)
                                            } else {
                                                (hovered_option.unwrap_or(0) as isize, 1)
                                            }
                                        };
                                        if hovered_option.is_some() || (selected.lock_ref().is_some() && Some(&options.lock_ref()[i as usize]) == selected.lock_ref().as_ref()) {
                                            for _ in 0..options.lock_ref().len() {
                                                i = (i + step + options.lock_ref().len() as isize) % options.lock_ref().len() as isize;
                                                if Some(&options.lock_ref()[i as usize]) != selected.lock_ref().as_ref() {
                                                    break;
                                                }
                                            }
                                        }
                                        options_hovered.lock_ref()[i as usize].set(true);
                                    } else {
                                        hovered.set_neq(false);
                                    }
                                }
                                MenuInput::Select => {
                                    hovered.set_neq(!show_dropdown.get());
                                    let hovered_option = options_hovered.lock_ref().iter().position(|hovered| hovered.get());
                                    if let Some(i) = hovered_option {
                                        options_hovered.lock_ref()[i].set(false);
                                        selected.set_neq(Some(options.lock_ref()[i].clone()));
                                    }
                                    flip(&show_dropdown);
                                    for hovered in options_hovered.lock_ref().iter() {
                                        hovered.set(false);
                                    }
                                },
                                MenuInput::Back => {
                                    if show_dropdown.get() {
                                        event.stop_propagation();
                                        for hovering in options_hovered.lock_ref().iter() {
                                            hovering.set(false);
                                        }
                                        flip(&show_dropdown);
                                    }
                                    hovered.set(false);
                                },
                                MenuInput::Delete => {
                                    if clearable {
                                        selected.take();
                                    }
                                },
                                _ => ()
                            }
                        }))
                    })
                )
            })
            .child(
                Button::new()
                .width(Val::Px(300.))
                .hovered_signal(hovered.signal())
                .body(
                    Stack::<NodeBundle>::new()
                    .width(Val::Percent(100.))
                    .with_style(|mut style| style.padding = UiRect::horizontal(Val::Px(BASE_PADDING)))
                    .layer(
                        El::<TextBundle>::new()
                        .align(Align::new().left())
                        .text_signal(
                            selected.signal_cloned()
                            .map(|selected_option| {
                                selected_option.map(|option| option.to_string()).unwrap_or_default()
                            })
                            .map(text)
                        )
                    )
                    .layer(
                        Row::<NodeBundle>::new()
                        .with_style(|mut style| style.column_gap = Val::Px(BASE_PADDING))
                        .align(Align::new().right())
                        .item_signal(
                            // TODO: this should just work, but compiler asks for type info
                            // clearable.then(||
                            //     selected.signal_ref(Option::is_some).dedupe()
                            //     .map_true(clone!((selected) move || x_button(clone!((selected) move || { selected.take(); }))))
                            // )
                            if clearable {
                                selected.signal_ref(Option::is_some).dedupe()
                                .map_true(clone!((selected) move || x_button(clone!((selected) move || { selected.take(); }))))
                                .boxed()
                            } else {
                                always(None).boxed()
                            }
                        )
                        .item(
                            El::<TextBundle>::new()
                            // TODO: need to figure out to rotate in place (around center)
                            // .on_signal_with_transform(show_dropdown.signal(), |transform, showing| {
                            //     transform.rotate_around(Vec3::X, Quat::from_rotation_z((if showing { 180.0f32 } else { 0. }).to_radians()));
                            // })
                            .text(text("v"))
                        )
                    )
                )
                .on_click(clone!((show_dropdown) move || {
                    only_one_up_flipper(&show_dropdown, &DROPDOWN_SHOWING_OPTION, None);
                }))
            )
            // TODO: this should be element below signal
            .child_signal(
                show_dropdown.signal()
                .map_true(clone!((options, show_dropdown, selected) move || {
                    Column::<NodeBundle>::new()
                    .width(Val::Percent(100.))
                    .with_style(|mut style| {
                        style.position_type = PositionType::Absolute;
                        style.top = Val::Percent(100.);
                    })
                    .items_signal_vec(
                        options.signal_vec_cloned()
                        .enumerate()
                        .filter_signal_cloned(clone!((selected) move |(_, option)| {
                            selected.signal_ref(clone!((option) move |selected_option| {
                                selected_option.as_ref() != Some(&option)
                            }))
                            .dedupe()
                        }))
                        .map_signal(clone!((selected, show_dropdown, options_hovered) move |(i_mutable, option)| {
                            i_mutable.signal()
                            .map_some(clone!((options_hovered, selected, show_dropdown, option) move |i| {
                                if let Some(hovered) = options_hovered.lock_ref().get(i) {
                                    text_button(
                                        always(option.to_string()),
                                        clone!((selected, show_dropdown, option) move || {
                                            selected.set_neq(Some(option.clone()));
                                            flip(&show_dropdown);
                                        })
                                    )
                                    .width(Val::Percent(100.))
                                    .hovered_signal(hovered.signal())
                                    .apply(Some)
                                } else {
                                    None
                                }
                            }))
                        }))
                        .map(Option::flatten)
                    )
                }))
            )
        };
        Self { el, controlling }
    }
}

impl ElementWrapper for Dropdown {
    type EL = El<NodeBundle>;
    fn element_mut(&mut self) -> &mut Self::EL {
        &mut self.el
    }
}

impl Controllable for Dropdown {
    fn controlling(&self) -> &Mutable<bool> {
        &self.controlling
    }
}

fn focus_on_no_child_hovered<E: Element>(
    element: E,
    hovereds: impl SignalVec<Item = Mutable<bool>> + Send + 'static,
) -> E {
    focus_on_signal(element, {
        hovereds
            .map_signal(|hovered| hovered.signal())
            .to_signal_map(|is_hovereds| !is_hovereds.iter().copied().any(identity))
            .dedupe()
    })
}

fn sub_menu_child_hover_manager<E: Element>(element: E, hovereds: MutableVec<Mutable<bool>>) -> E {
    let l = hovereds.lock_ref().len();
    element.apply(|element| {
        input_event_listener_controller(
            element,
            always(true),
            clone!((hovereds) move || {
                On::<MenuInputEvent>::run(clone!((hovereds) move |event: ListenerMut<MenuInputEvent>| {
                    let hovereds_lock = hovereds.lock_ref();
                    match event.input {
                        MenuInput::Up | MenuInput::Down => {
                            let hovered_option = hovereds_lock.iter().position(|hovered| hovered.get());
                            if let Some(i) = hovered_option {
                                hovereds_lock[i].set(false);
                                let new_i = if matches!(event.input, MenuInput::Up) { i + l - 1 } else { i + 1 } % l;
                                hovereds_lock[new_i].set(true);
                            } else {
                                let i = if matches!(event.input, MenuInput::Up) { hovereds_lock.len() - 1 } else { 0 };
                                hovereds_lock[i].set(true);
                            }
                        },
                        MenuInput::Back => {
                            if hovereds_lock.iter().any(|hovered| hovered.get()) {
                                for hovered in hovereds_lock.iter() {
                                    hovered.set(false)
                                }
                            } else {
                                SHOW_SUB_MENU.set(None);
                            }
                        },
                        _ => ()
                    }
                }))
            }),
        )
    })
}

fn make_controlling_menu_item(label: &str, el: impl Controllable + Element) -> (Stack<NodeBundle>, Mutable<bool>) {
    let hovered = Mutable::new(false);
    (
        menu_item(label, el.controlling_signal(hovered.signal()), hovered.clone()),
        hovered,
    )
}

fn audio_menu() -> Column<NodeBundle> {
    let items_hovereds = [
        make_controlling_menu_item(
            "dropdown",
            Dropdown::new(
                MutableVec::new_with_values(options(4)),
                MISC_DEMO_SETTINGS.dropdown.clone(),
                true,
            ),
        ),
        make_controlling_menu_item(
            "radio group",
            RadioGroup::new(
                MutableVec::new_with_values(options(3)),
                MISC_DEMO_SETTINGS.radio_group.clone(),
            ),
        ),
        make_controlling_menu_item("checkbox", Checkbox::new(MISC_DEMO_SETTINGS.checkbox.clone())),
        make_controlling_menu_item(
            "iterable options",
            IterableOptions::new(
                MutableVec::new_with_values(options(4)),
                MISC_DEMO_SETTINGS.iterable_options.clone(),
            ),
        ),
        make_controlling_menu_item("master volume", Slider::new(AUDIO_SETTINGS.master_volume.clone())),
        make_controlling_menu_item("effect volume", Slider::new(AUDIO_SETTINGS.effect_volume.clone())),
        make_controlling_menu_item("music volume", Slider::new(AUDIO_SETTINGS.music_volume.clone())),
        make_controlling_menu_item("voice volume", Slider::new(AUDIO_SETTINGS.voice_volume.clone())),
    ];
    let l = items_hovereds.len();
    let (items, hovereds): (Vec<_>, Vec<_>) = items_hovereds.into_iter().unzip();
    let hovereds = MutableVec::new_with_values(hovereds);
    menu_base(SUB_MENU_WIDTH, SUB_MENU_HEIGHT, "audio menu")
        .apply(|element| focus_on_no_child_hovered(element, hovereds.signal_vec_cloned()))
        .apply(|element| sub_menu_child_hover_manager(element, hovereds.clone()))
        .items(
            items
                .into_iter()
                .enumerate()
                .map(move |(i, item)| item.z_index(ZIndex::Local((l - i) as i32))),
        )
}

fn graphics_menu() -> Column<NodeBundle> {
    let preset_quality = GRAPHICS_SETTINGS.preset_quality.clone();
    let texture_quality = GRAPHICS_SETTINGS.texture_quality.clone();
    let shadow_quality = GRAPHICS_SETTINGS.shadow_quality.clone();
    let bloom_quality = GRAPHICS_SETTINGS.bloom_quality.clone();
    let non_preset_qualities = MutableVec::new_with_values(vec![
        texture_quality.clone(),
        shadow_quality.clone(),
        bloom_quality.clone(),
    ]);
    let preset_broadcaster = spawn(clone!((preset_quality, non_preset_qualities) async move {
        preset_quality.signal()
        .for_each_sync(|preset_quality_option| {
            if let Some(preset_quality) = preset_quality_option {
                for quality in non_preset_qualities.lock_ref().iter() {
                    quality.set_neq(Some(preset_quality));
                }
            }
        })
        .await;
    }));
    let preset_controller = spawn(clone!((preset_quality) async move {
        non_preset_qualities.signal_vec_cloned()
        .map_signal(|quality| quality.signal())
        .to_signal_map(|qualities| {
            let mut qualities = qualities.iter();
            let mut preset = preset_quality.lock_mut();
            if preset.is_none() {
                let first = qualities.next().unwrap();  // always populated
                if qualities.all(|quality| quality == first) {
                    *preset = *first;
                }
            } else if preset.is_some() && qualities.any(|quality| quality != &*preset) {
                *preset = None;
            }
        })
        .to_future()
        .await;
    }));
    let items = [
        ("preset quality", preset_quality, true),
        ("texture quality", texture_quality, false),
        ("shadow quality", shadow_quality, false),
        ("bloom quality", bloom_quality, false),
    ];
    let l = items.len();
    let hovereds = MutableVec::new_with_values((0..l).map(|_| Mutable::new(false)).collect::<Vec<_>>());
    menu_base(SUB_MENU_WIDTH, SUB_MENU_HEIGHT, "graphics menu")
        .apply(|element| focus_on_no_child_hovered(element, hovereds.signal_vec_cloned()))
        .apply(|element| sub_menu_child_hover_manager(element, hovereds.clone()))
        .update_raw_el(|raw_el| raw_el.hold_tasks([preset_broadcaster, preset_controller]))
        .items({
            let hovereds = hovereds.lock_ref().iter().cloned().collect::<Vec<_>>();
            items
                .into_iter()
                .zip(hovereds)
                .enumerate()
                .map(move |(i, ((label, quality, clearable), hovered))| {
                    menu_item(
                        label,
                        {
                            Dropdown::new(
                                MutableVec::new_with_values(Quality::iter().collect()),
                                quality,
                                clearable,
                            )
                            .controlling_signal(hovered.signal())
                        },
                        hovered,
                    )
                    .z_index(ZIndex::Local((l - i) as i32))
                })
        })
        .item(
            // solely here to dehover dropdown menu items  // TODO: this can also be solved by
            // allowing setting Over/Out order at runtime or implementing .on_hovered_outside, i
            // should do both of these
            El::<NodeBundle>::new()
                .height(Val::Px(
                    SUB_MENU_HEIGHT - (l + 1) as f32 * MENU_ITEM_HEIGHT - BASE_PADDING * 2.,
                ))
                .on_hovered_change(|is_hovered| {
                    if is_hovered {
                        if let Some(hovered) = MENU_ITEM_HOVERED_OPTION.take() {
                            hovered.set(false);
                        }
                    }
                }),
        )
}
Source

fn hovered_sync(self, hovered: Mutable<bool>) -> Self

Sync a Mutable<bool> with this element’s hovered state.

Examples found in repository?
examples/responsive_menu.rs (line 104)
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
fn nine_slice_button() -> impl Element {
    let hovered = Mutable::new(false);
    let pressed = Mutable::new(false);
    NineSliceEl::new(map_ref! {
        let hovered = hovered.signal(),
        let pressed = pressed.signal() => {
            if *pressed {
                2
            } else if *hovered {
                1
            } else {
                0
            }
        }
    })
    .width(Val::Px(100.))
    .height(Val::Px(50.))
    .hovered_sync(hovered)
    .pressed_sync(pressed)
}
More examples
Hide additional examples
examples/counter.rs (line 55)
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
fn counter_button(counter: Mutable<i32>, label: &str, step: i32) -> impl Element {
    let hovered = Mutable::new(false);
    El::<NodeBundle>::new()
        .width(Val::Px(45.0))
        .align_content(Align::center())
        .background_color_signal(
            hovered
                .signal()
                .map_bool(|| Color::hsl(300., 0.75, 0.85), || Color::hsl(300., 0.75, 0.75))
                .map(BackgroundColor),
        )
        .hovered_sync(hovered)
        .on_click(move || *counter.lock_mut() += step)
        .child(El::<TextBundle>::new().text(text(label)))
}
examples/ecs_ui_sync.rs (line 126)
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
fn incrde_button(value: Mutable<f32>, incr: f32) -> impl Element {
    let hovered = Mutable::new(false);
    let f = move || {
        let new = (*value.lock_ref() + incr).max(0.);
        *value.lock_mut() = new;
    };
    El::<NodeBundle>::new()
        .width(Val::Px(45.0))
        .align_content(Align::center())
        .background_color_signal(
            hovered
                .signal()
                .map_bool(|| Color::hsl(300., 0.75, 0.85), || Color::hsl(300., 0.75, 0.75))
                .map(BackgroundColor),
        )
        .hovered_sync(hovered)
        .on_pressing_with_sleep_throttle(f, Duration::from_millis(50))
        .child(El::<TextBundle>::new().text(text(if incr.is_sign_positive() { "+" } else { "-" })))
}
examples/snake.rs (line 208)
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
fn restart_button() -> impl Element {
    let hovered = Mutable::new(false);
    El::<NodeBundle>::new()
        .align(Align::center())
        .width(Val::Px(250.))
        .height(Val::Px(80.))
        .background_color_signal(
            hovered
                .signal()
                .map_bool(|| bevy::color::palettes::basic::GRAY.into(), || Color::BLACK)
                .map(BackgroundColor),
        )
        .hovered_sync(hovered)
        .align_content(Align::center())
        .on_click(|| async_world().send_event(Restart).apply(spawn).detach())
        .child(El::<TextBundle>::new().text(Text::from_section(
            "restart",
            TextStyle {
                font_size: 60.,
                color: Color::WHITE,
                ..default()
            },
        )))
}

fn text(string: &str) -> Text {
    Text::from_section(
        string,
        TextStyle {
            font_size: 30.,
            ..default()
        },
    )
}

#[derive(Event)]
enum GridSizeChange {
    Incr,
    Decr,
}

// TODO: move this back inside the on_click ? (initial motivation for moving to event was
// potentially addressing the grid float precision shenanigans)
fn grid_size_changer(mut events: EventReader<GridSizeChange>, mut spawn_food: EventWriter<SpawnFood>) {
    for event in events.read() {
        let cur_size = GRID_SIZE.get();
        match event {
            GridSizeChange::Incr => {
                let mut cells_lock = CELLS.lock_mut();
                for i in 0..cur_size + 1 {
                    cells_lock.insert_cloned((i, cur_size), Mutable::new(Cell::Empty));
                    cells_lock.insert_cloned((cur_size, i), Mutable::new(Cell::Empty));
                }
                GRID_SIZE.update(|size| size + 1);
            }
            GridSizeChange::Decr => {
                if cur_size > 2 {
                    let mut cells_lock = CELLS.lock_mut();
                    let indices = (0..cur_size)
                        .map(|i| (i, cur_size - 1))
                        .chain((0..cur_size).map(|i| (cur_size - 1, i)))
                        .collect::<Vec<_>>();
                    if indices.iter().all(|index| {
                        cells_lock
                            .get(index)
                            .map(|cell| !matches!(cell.get(), Cell::Snake))
                            .unwrap_or(false)
                    }) {
                        let mut removed = vec![];
                        for index in indices {
                            removed.push(cells_lock.remove(&index));
                        }
                        if removed
                            .into_iter()
                            .flatten()
                            .any(|removed| matches!(removed.get(), Cell::Food))
                        {
                            spawn_food.send_default();
                        }
                        GRID_SIZE.update(|size| size - 1);
                    }
                }
            }
        }
    }
}

fn text_button(text_: &str) -> impl Element + PointerEventAware {
    let hovered = Mutable::new(false);
    El::<NodeBundle>::new()
        .width(Val::Px(45.0))
        .align_content(Align::center())
        .background_color_signal(
            hovered
                .signal()
                .map_bool(|| SNAKE_COLOR, || EMPTY_COLOR)
                .map(BackgroundColor),
        )
        .hovered_sync(hovered)
        .child(El::<TextBundle>::new().text(text(text_)))
}
examples/healthbar.rs (line 230)
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
fn respawn_button() -> impl Element {
    let hovered = Mutable::new(false);
    El::<NodeBundle>::new()
        .align(Align::center())
        .width(Val::Px(250.))
        .height(Val::Px(80.))
        .background_color_signal(
            hovered
                .signal()
                .map_bool(|| bevy::color::palettes::basic::GRAY.into(), || Color::BLACK)
                .map(BackgroundColor),
        )
        .hovered_sync(hovered)
        .align_content(Align::center())
        .on_click(|| async_world().send_event(SpawnPlayer).apply(spawn).detach())
        .child(El::<TextBundle>::new().text(Text::from_section(
            "respawn",
            TextStyle {
                font_size: 60.,
                color: Color::WHITE,
                ..default()
            },
        )))
}
examples/scroll.rs (line 53)
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
fn letter_column(rotate: usize, color: Color) -> impl Element {
    let hovered = Mutable::new(false);
    Column::<NodeBundle>::new()
        .height(Val::Px(5. * LETTER_SIZE))
        .mutable_viewport(Overflow::clip_y(), LimitToBody::Vertical)
        .on_scroll_with_system_disableable_signal(
            BasicScrollHandler::new()
                .direction(ScrollDirection::Vertical)
                .pixels(LETTER_SIZE)
                .into_system(),
            signal::or(signal::not(hovered.signal()), SHIFTED.signal()),
        )
        .with_style(move |mut style| style.top = Val::Px(-LETTER_SIZE * rotate as f32))
        .hovered_sync(hovered)
        .items(
            "abcdefghijklmnopqrstuvwxyz"
                .chars()
                .map(move |c| letter(&c.to_string(), color)),
        )
}

fn ui_root() -> impl Element {
    let hovered = Mutable::new(false);
    El::<NodeBundle>::new()
        .width(Val::Percent(100.))
        .height(Val::Percent(100.))
        .align_content(Align::center())
        .child(
            Row::<NodeBundle>::new()
                .with_style(|mut style: Mut<'_, Style>| {
                    style.column_gap = Val::Px(30.);
                    style.padding = UiRect::horizontal(Val::Px(7.5));
                })
                .width(Val::Px(300.))
                .mutable_viewport(Overflow::clip_x(), LimitToBody::Horizontal)
                .on_scroll_with_system_disableable_signal(
                    BasicScrollHandler::new()
                        .direction(ScrollDirection::Horizontal)
                        // TODO: special handler for auto discrete like rectray https://github.com/mintlu8/bevy-rectray/blob/main/examples/scroll_discrete.rs
                        .pixels(63.)
                        .into_system(),
                    signal::not(signal::and(hovered.signal(), SHIFTED.signal())),
                )
                .hovered_sync(hovered)
                .items(
                    [
                        bevy::color::palettes::css::RED,
                        bevy::color::palettes::css::ORANGE,
                        bevy::color::palettes::css::YELLOW,
                        bevy::color::palettes::css::GREEN,
                        bevy::color::palettes::css::BLUE,
                        bevy::color::palettes::css::INDIGO,
                        bevy::color::palettes::css::VIOLET,
                    ]
                    .into_iter()
                    .enumerate()
                    .map(|(i, color)| letter_column(i, color.into())),
                ),
        )
}
Source

fn on_click_with_system<Marker>( self, handler: impl IntoSystem<(Entity, Pointer<Click>), (), Marker> + Send + 'static, ) -> Self

Run a System when this element is clicked.

Examples found in repository?
examples/key_values_sorted.rs (lines 416-435)
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
fn ui_root() -> impl Element {
    El::<NodeBundle>::new()
        .ui_root()
        .width(Val::Percent(100.))
        .height(Val::Percent(100.))
        .align_content(Align::center())
        .child(
            Row::<NodeBundle>::new()
                .height(Val::Percent(100.))
                .with_style(|mut style| style.column_gap = Val::Px(70.))
                .item(
                    Column::<NodeBundle>::new()
                        .with_style(|mut style| style.row_gap = Val::Px(20.))
                        .item(sort_button(KeyValue::Key))
                        .item(sort_button(KeyValue::Value)),
                )
                .item(
                    Column::<NodeBundle>::new()
                        .with_style(|mut style| style.row_gap = Val::Px(10.))
                        .height(Val::Percent(90.))
                        .width(Val::Px(INPUT_WIDTH * 2. + INPUT_HEIGHT + 10. * 2.))
                        .align_content(Align::center())
                        .item(key_values().height(Val::Percent(90.)))
                        .item({
                            let hovered = Mutable::new(false);
                            El::<NodeBundle>::new()
                                .width(Val::Px(INPUT_WIDTH))
                                .height(Val::Px(INPUT_HEIGHT))
                                .background_color_signal(
                                    hovered
                                        .signal()
                                        .map_bool(|| bevy::color::palettes::basic::GREEN.into(), || *DARK_GRAY)
                                        .map(BackgroundColor::from),
                                )
                                .hovered_sync(hovered)
                                .align_content(Align::center())
                                .child(El::<TextBundle>::new().text(Text::from_section(
                                    "+",
                                    TextStyle {
                                        font_size: 30.0,
                                        ..default()
                                    },
                                )))
                                .on_click_with_system(|_: In<_>, mut commands: Commands| {
                                    commands.remove_resource::<FocusedTextInput>(); // TODO: shouldn't need this, can remove once https://github.com/Dimchikkk/bevy_cosmic_edit/issues/145
                                    clear_focus();
                                    PAIRS.lock_mut().push_cloned(RowData {
                                        key: {
                                            let data = TextInputData::new("");
                                            data.focus.set(true);
                                            data
                                        },
                                        value: TextInputData::new(""),
                                    });
                                    async {
                                        // TODO: need "after rendered" hook to exactly sync when this scroll should be
                                        // triggered
                                        sleep(Duration::from_millis(25)).await;
                                        scroll_to_bottom()
                                    }
                                    .apply(spawn)
                                    .detach();
                                })
                        }),
                ),
        )
}
Source

fn on_click(self, handler: impl FnMut() + Send + Sync + 'static) -> Self

Run a function when this element is left clicked.

Examples found in repository?
examples/main_menu.rs (line 179)
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
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
fn text_button(
    text_signal: impl Signal<Item = String> + Send + 'static,
    on_click: impl FnMut() + Send + Sync + 'static,
) -> Button {
    Button::new()
        .width(Val::Px(200.))
        .body(El::<TextBundle>::new().text_signal(text_signal.map(text)))
        .on_click(on_click)
}

fn sub_menu_button(sub_menu: SubMenu) -> Button {
    text_button(always(sub_menu.to_string()), move || {
        SHOW_SUB_MENU.set_neq(Some(sub_menu))
    })
}

fn menu_base(width: f32, height: f32, title: &str) -> Column<NodeBundle> {
    Column::<NodeBundle>::new()
        .width(Val::Px(width))
        .height(Val::Px(height))
        .with_style(|mut style| style.border = UiRect::all(Val::Px(BASE_BORDER_WIDTH)))
        .border_color(BorderColor(Color::BLACK))
        .background_color(BackgroundColor(NORMAL_BUTTON))
        .item(
            El::<NodeBundle>::new()
                .height(Val::Px(MENU_ITEM_HEIGHT))
                .with_style(|mut style| {
                    style.padding = UiRect::all(Val::Px(BASE_PADDING * 2.));
                })
                .child(
                    El::<TextBundle>::new()
                        .align(Align::new().top().left())
                        .text(text(title)),
                ),
        )
}

// global ui state comes in super handy sometimes ...
// here, we use a global to keep track of any dropdowns that are dropped down, passing it to
// `only_one_up_flipper` to ensure only one is dropped down at a time; a mutable for this can be
// managed more locally, but adds significant unwieldiness
static DROPDOWN_SHOWING_OPTION: Lazy<Mutable<Option<Mutable<bool>>>> = Lazy::new(default);

fn lil_baby_button() -> Button {
    Button::new()
        .width(Val::Px(LIL_BABY_BUTTON_SIZE))
        .height(Val::Px(LIL_BABY_BUTTON_SIZE))
}

trait Controllable: ElementWrapper
where
    Self: Sized + 'static,
{
    fn controlling(&self) -> &Mutable<bool>;

    fn controlling_signal(mut self, controlling_signal: impl Signal<Item = bool> + Send + 'static) -> Self {
        let syncer = spawn(sync(controlling_signal, self.controlling().clone()));
        self = self.update_raw_el(|raw_el| raw_el.hold_tasks([syncer]));
        self
    }
}

struct Checkbox {
    el: Button,
    controlling: Mutable<bool>,
}

impl Checkbox {
    fn new(checked: Mutable<bool>) -> Self {
        let (controlling, controlling_signal) = Mutable::new_and_signal(false);
        Self {
            el: {
                lil_baby_button()
                    .apply(|element| focus_on_signal(element, controlling.signal()))
                    .apply(|element| {
                        // input handling is conveniently defined within the body of the widget itself
                        input_event_listener_controller(
                            element,
                            controlling_signal,
                            clone!((checked) move || {
                                // TODO: i don't actually need the exclusivity of `run` here, is there a way to avoid it ?
                                On::<MenuInputEvent>::run(clone!((checked) move |event: ListenerMut<MenuInputEvent>| {
                                    match event.input {
                                        MenuInput::Select => {
                                            checked.set_neq(!checked.get());
                                        },
                                        MenuInput::Delete => {
                                            checked.set(false);
                                        },
                                        _ => ()
                                    }
                                }))
                            }),
                        )
                    })
                    .on_click(clone!((checked) move || flip(&checked)))
                    .selected_signal(checked.signal())
            },
            controlling,
        }
    }
}

impl ElementWrapper for Checkbox {
    type EL = Button;
    fn element_mut(&mut self) -> &mut Self::EL {
        &mut self.el
    }
}

impl Controllable for Checkbox {
    fn controlling(&self) -> &Mutable<bool> {
        &self.controlling
    }
}

#[derive(Clone, Copy, EnumIter, PartialEq, Display)]
enum Quality {
    Low,
    Medium,
    High,
    Ultra,
}

struct RadioGroup {
    el: Row<NodeBundle>,
    controlling: Mutable<bool>,
}

impl RadioGroup {
    fn new<T: Clone + PartialEq + Display + Send + Sync + 'static>(
        options: MutableVec<T>,
        selected: Mutable<Option<usize>>,
    ) -> Self {
        let (controlling, controlling_signal) = Mutable::new_and_signal(false);
        Self {
            el: {
                Row::<NodeBundle>::new()
                .apply(|element| focus_on_signal(element, controlling.signal()))
                .apply(|element| {
                    input_event_listener_controller(
                        element,
                        controlling_signal,
                        clone!((options, selected) move || {
                            On::<MenuInputEvent>::run(clone!((options, selected) move |event: ListenerMut<MenuInputEvent>| {
                                match event.input {
                                    MenuInput::Left | MenuInput::Right => {
                                        let selected_option = selected.lock_ref().as_ref().copied();
                                        let (mut i, step) = {
                                            if matches!(event.input, MenuInput::Left) {
                                                (selected_option.unwrap_or(options.lock_ref().len() - 1) as isize, -1)
                                            } else {
                                                (selected_option.unwrap_or(0) as isize, 1)
                                            }
                                        };
                                        if selected_option.is_some() {
                                            i = (i + step + options.lock_ref().len() as isize) % options.lock_ref().len() as isize;
                                        }
                                        selected.set(Some(i as usize));
                                    },
                                    MenuInput::Delete => {
                                        selected.take();
                                    },
                                    _ => ()
                                }
                            }))
                        })
                    )
                })
                .items_signal_vec(
                    options.signal_vec_cloned().enumerate()
                    .map(clone!((selected) move |(i_option_mutable, option)| {
                        text_button(
                            always(option.to_string()),
                            clone!((selected, i_option_mutable) move || {
                                if selected.get() == i_option_mutable.get() {
                                    selected.set(None);
                                } else {
                                    selected.set(i_option_mutable.get());
                                }
                            })
                        )
                        // the `Checkbox` just used a flippable `Mutable<bool>` to persist the selectedness, and we could
                        // have done the same here, e.g. a separate `clicked: Mutable<bool>` for every text button, but then to
                        // get exclusivity we would have iterate over the other `clicked` mutables and flip them; again, this
                        // is a totally valid option, but it's more convenient in this case to centrally track selectedness
                        // with a `Mutable<Option<usize>>` so we get exclusivity for free; also notice that the index from the
                        // `.enumerate` is a mutable, this is because the options vec is also reactive, so the indicies of items
                        // can change, so this solution isn't actually correct for dynamic options, but it's fine for this example
                        .selected_signal(signal_eq(selected.signal_cloned(), i_option_mutable.signal()))
                    }))
                )
            },
            controlling,
        }
    }
}

impl ElementWrapper for RadioGroup {
    type EL = Row<NodeBundle>;
    fn element_mut(&mut self) -> &mut Self::EL {
        &mut self.el
    }
}

impl Controllable for RadioGroup {
    fn controlling(&self) -> &Mutable<bool> {
        &self.controlling
    }
}

enum LeftRight {
    Left,
    Right,
}

fn centered_arrow_text(direction: LeftRight) -> El<TextBundle> {
    El::<TextBundle>::new()
        .with_style(|mut style| {
            // manually centered
            style.bottom = Val::Px(2.);
            style.right = Val::Px(2.);
        })
        .text(
            match direction {
                LeftRight::Left => "<",
                LeftRight::Right => ">",
            }
            .apply(text),
        )
}

struct IterableOptions {
    el: Row<NodeBundle>,
    controlling: Mutable<bool>,
}

const FLASH_MS: f32 = 50.; // TODO: address background/border color desyncing

impl IterableOptions {
    fn new<T: Clone + PartialEq + Display + Send + Sync + 'static>(
        options: MutableVec<T>,
        selected: Mutable<T>,
    ) -> Self {
        let (controlling, controlling_signal) = Mutable::new_and_signal(false);
        let left_pressed = Mutable::new(false);
        let right_pressed = Mutable::new(false);
        Self {
            el: {
                Row::<NodeBundle>::new()
                .apply(|element| focus_on_signal(element, controlling.signal()))
                .apply(|element| {
                    input_event_listener_controller(
                        element,
                        controlling_signal,
                        clone!((options, selected, left_pressed, right_pressed) move || {
                            // TODO: only allowing one flasher like this doesn't prevent desyncing either ...
                            let left_flasher = Mutable::new(None);
                            let right_flasher = Mutable::new(None);
                            On::<MenuInputEvent>::run(clone!((options, selected, left_pressed, right_pressed) move |event: ListenerMut<MenuInputEvent>| {
                                match event.input {
                                    MenuInput::Left | MenuInput::Right => {
                                        let i_option = options.lock_ref().iter().position(|option| option == &*selected.lock_ref()).map(|i| i as isize);
                                        if let Some(mut i) = i_option {
                                            let step = {
                                                (if matches!(event.input, MenuInput::Left) {
                                                    left_pressed.set(true);
                                                    left_flasher.set(Some(spawn(clone!((left_pressed) async move {
                                                        sleep(Duration::from_millis(FLASH_MS as u64)).await;
                                                        left_pressed.signal().wait_for(true).await;  // TODO: this doesn't prevent desyncing, could be lower level issue ...
                                                        left_pressed.set(false);
                                                    }))));
                                                    -1
                                                } else {
                                                    right_pressed.set(true);
                                                    right_flasher.set(Some(spawn(clone!((right_pressed) async move {
                                                        sleep(Duration::from_millis(FLASH_MS as u64)).await;
                                                        right_pressed.signal().wait_for(true).await;
                                                        right_pressed.set(false);
                                                    }))));
                                                    1
                                                })
                                                as isize
                                            };
                                            i = (i + step + options.lock_ref().len() as isize) % options.lock_ref().len() as isize;
                                            selected.set(options.lock_ref()[i as usize].clone());
                                        }
                                    },
                                    _ => ()
                                }
                            }))
                        })
                    )
                })
                .with_style(|mut style| style.column_gap = Val::Px(BASE_PADDING * 2.))
                .item({
                    lil_baby_button()
                    .selected_signal(left_pressed.signal())
                    .on_click(clone!((selected, options) move || {
                        let options_lock = options.lock_ref();
                        if let Some(i) = options_lock.iter().position(|option| option == &*selected.lock_ref()) {
                            selected.set_neq(options_lock.iter().rev().cycle().nth(options_lock.len() - i).unwrap().clone());
                        }
                    }))
                    .body(centered_arrow_text(LeftRight::Left))
                })
                .item(
                    El::<TextBundle>::new()
                    .text_signal(selected.signal_cloned().map(text))
                )
                .item({
                    lil_baby_button()
                    .selected_signal(right_pressed.signal())
                    .on_click(clone!((selected, options) move || {
                        let options_lock = options.lock_ref();
                        if let Some(i) = options_lock.iter().position(|option| option == &*selected.lock_ref()) {
                            selected.set_neq(options_lock.iter().cycle().nth(i + 1).unwrap().clone());
                        }
                    }))
                    .body(centered_arrow_text(LeftRight::Right))
                })
            },
            controlling,
        }
    }
}

impl ElementWrapper for IterableOptions {
    type EL = Row<NodeBundle>;
    fn element_mut(&mut self) -> &mut Self::EL {
        &mut self.el
    }
}

impl Controllable for IterableOptions {
    fn controlling(&self) -> &Mutable<bool> {
        &self.controlling
    }
}

struct Slider {
    el: Row<NodeBundle>,
    controlling: Mutable<bool>,
}

impl Slider {
    fn new(value: Mutable<f32>) -> Self {
        let (controlling, controlling_signal) = Mutable::new_and_signal(false);
        Self {
            el: {
                let slider_width = 400.;
                let slider_padding = 5.;
                let max = slider_width - slider_padding - LIL_BABY_BUTTON_SIZE - BASE_BORDER_WIDTH;
                let left = Mutable::new(value.get() / 100. * max);
                let value_setter = spawn(clone!((left, value) async move {
                    left.signal().for_each_sync(|left| value.set_neq(left / max * 100.)).await;
                }));
                Row::<NodeBundle>::new()
                    .update_raw_el(|raw_el| raw_el.insert(SliderTag))
                    .apply(|element| focus_on_signal(element, controlling.signal()))
                    .apply(|element| {
                        input_event_listener_controller(
                            element,
                            controlling_signal,
                            clone!((left) move || {
                                On::<MenuInputEvent>::run(clone!((left) move |event: ListenerMut<MenuInputEvent>| {
                                    match event.input {
                                        MenuInput::Left | MenuInput::Right => {
                                            let dir = if matches!(event.input, MenuInput::Left) { -1. } else { 1. };
                                            left.update(move |left| (left + dir * max * 0.001).max(0.).min(max));
                                        },
                                        _ => ()
                                    }
                                }))
                            }),
                        )
                    })
                    .update_raw_el(|raw_el| raw_el.hold_tasks([value_setter]))
                    .with_style(|mut style| style.column_gap = Val::Px(10.))
                    .item(
                        El::<TextBundle>::new().text_signal(value.signal().map(|value| text(format!("{:.1}", value)))),
                    )
                    .item(
                        Stack::<NodeBundle>::new()
                            .width(Val::Px(slider_width))
                            .height(Val::Px(5.))
                            .with_style(move |mut style| style.padding = UiRect::horizontal(Val::Px(slider_padding)))
                            .background_color(BackgroundColor(Color::BLACK))
                            .layer({
                                let dragging = Mutable::new(false);
                                lil_baby_button()
                                    .selected_signal(dragging.signal())
                                    .el // we need lower level access now
                                    .on_signal_with_style(left.signal(), |mut style, left| style.left = Val::Px(left))
                                    .align(Align::new().center_y())
                                    .update_raw_el(|raw_el| {
                                        raw_el.insert((
                                            On::<Pointer<DragStart>>::run(
                                                clone!((dragging) move || dragging.set_neq(true)),
                                            ),
                                            On::<Pointer<DragEnd>>::run(move || dragging.set_neq(false)),
                                            On::<Pointer<Drag>>::run(move |drag: Listener<Pointer<Drag>>| {
                                                left.set_neq((left.get() + drag.delta.x).max(0.).min(max));
                                            }),
                                        ))
                                    })
                            }),
                    )
            },
            controlling,
        }
    }
}

impl ElementWrapper for Slider {
    type EL = Row<NodeBundle>;
    fn element_mut(&mut self) -> &mut Self::EL {
        &mut self.el
    }
}

impl Controllable for Slider {
    fn controlling(&self) -> &Mutable<bool> {
        &self.controlling
    }
}

fn options(n: usize) -> Vec<String> {
    (1..=n).map(|i| format!("option {}", i)).collect()
}

fn only_one_up_flipper(
    to_flip: &Mutable<bool>,
    already_up_option: &Mutable<Option<Mutable<bool>>>,
    target_option: Option<bool>,
) {
    let cur = target_option.map(|target| !target).unwrap_or(to_flip.get());
    if cur {
        already_up_option.take();
    } else {
        if let Some(previous) = &*already_up_option.lock_ref() {
            previous.set(false);
        }
        already_up_option.set(Some(to_flip.clone()));
    }
    to_flip.set(!cur);
}

static MENU_ITEM_HOVERED_OPTION: Lazy<Mutable<Option<Mutable<bool>>>> = Lazy::new(default);

fn menu_item(label: &str, body: impl Element, hovered: Mutable<bool>) -> Stack<NodeBundle> {
    Stack::<NodeBundle>::new()
        .background_color_signal(
            hovered
                .signal()
                .map_bool(|| NORMAL_BUTTON.lighter(0.05), || NORMAL_BUTTON)
                .map(BackgroundColor),
        )
        .on_hovered_change(move |is_hovered| only_one_up_flipper(&hovered, &MENU_ITEM_HOVERED_OPTION, Some(is_hovered)))
        .width(Val::Percent(100.))
        .height(Val::Px(MENU_ITEM_HEIGHT))
        .with_style(|mut style| style.padding = UiRect::axes(Val::Px(BASE_PADDING), Val::Px(BASE_PADDING / 2.)))
        .layer(
            El::<TextBundle>::new()
                .text(text(label))
                .align(Align::new().left().center_y()),
        )
        .layer(body.align(Align::new().right().center_y()))
}

struct Dropdown {
    el: El<NodeBundle>,
    controlling: Mutable<bool>,
}

fn focus_on_signal<E: Element>(element: E, signal: impl Signal<Item = bool> + Send + 'static) -> E {
    element.update_raw_el(|raw_el| {
        raw_el.on_signal(signal.dedupe(), |entity, focus| async move {
            if focus {
                // at first, i was using a `static_ref` global `Mutable<Option<Entity>>` for this
                // and wrapping it in a resource for accessing it in the menu input event systems, but this is an
                // anti pattern; the ecs should not be polling reactive ui state for syncing its own
                // state/systems (there's an example of this anti pattern in the ecs world ui world sync example https://github.com/databasedav/haalka/blob/main/examples/ecs_ui_sync/src/main.rs#L154);
                // instead, like we do here, simply use the `async_world` to update the ecs state *exactly and only*
                // when it needs to be
                async_world().insert_resource(FocusedEntity(entity)).await;
                // TODO: remove reference to ecs world ui world sync example once fixed
            }
        })
    })
}

impl Dropdown {
    fn new<T: Clone + PartialEq + Display + Send + Sync + 'static>(
        options: MutableVec<T>,
        selected: Mutable<Option<T>>,
        clearable: bool,
    ) -> Self {
        let show_dropdown = Mutable::new(false);
        let hovered = Mutable::new(false);
        let controlling = Mutable::new(false);
        let options_hovered =
            MutableVec::new_with_values((0..options.lock_ref().len()).map(|_| Mutable::new(false)).collect());
        let el = {
            El::<NodeBundle>::new()
            .apply(|element| focus_on_signal(element, controlling.signal()))
            .apply(|element| {
                input_event_listener_controller(
                    element,
                    controlling.signal(),
                    clone!((show_dropdown, hovered, options, options_hovered, selected) move || {
                        On::<MenuInputEvent>::run(clone!((show_dropdown, hovered, options, options_hovered, selected) move |mut event: ListenerMut<MenuInputEvent>| {
                            match event.input {
                                MenuInput::Up | MenuInput::Down => {
                                    if show_dropdown.get() {
                                        event.stop_propagation();
                                        let hovered_option = options_hovered.lock_ref().iter().position(|hovered| hovered.get());
                                        if let Some(i) = hovered_option {
                                            options_hovered.lock_ref()[i].set(false);
                                        }
                                        let (mut i, step) = {
                                            if matches!(event.input, MenuInput::Up) {
                                                (hovered_option.unwrap_or(options.lock_ref().len() - 1) as isize, -1)
                                            } else {
                                                (hovered_option.unwrap_or(0) as isize, 1)
                                            }
                                        };
                                        if hovered_option.is_some() || (selected.lock_ref().is_some() && Some(&options.lock_ref()[i as usize]) == selected.lock_ref().as_ref()) {
                                            for _ in 0..options.lock_ref().len() {
                                                i = (i + step + options.lock_ref().len() as isize) % options.lock_ref().len() as isize;
                                                if Some(&options.lock_ref()[i as usize]) != selected.lock_ref().as_ref() {
                                                    break;
                                                }
                                            }
                                        }
                                        options_hovered.lock_ref()[i as usize].set(true);
                                    } else {
                                        hovered.set_neq(false);
                                    }
                                }
                                MenuInput::Select => {
                                    hovered.set_neq(!show_dropdown.get());
                                    let hovered_option = options_hovered.lock_ref().iter().position(|hovered| hovered.get());
                                    if let Some(i) = hovered_option {
                                        options_hovered.lock_ref()[i].set(false);
                                        selected.set_neq(Some(options.lock_ref()[i].clone()));
                                    }
                                    flip(&show_dropdown);
                                    for hovered in options_hovered.lock_ref().iter() {
                                        hovered.set(false);
                                    }
                                },
                                MenuInput::Back => {
                                    if show_dropdown.get() {
                                        event.stop_propagation();
                                        for hovering in options_hovered.lock_ref().iter() {
                                            hovering.set(false);
                                        }
                                        flip(&show_dropdown);
                                    }
                                    hovered.set(false);
                                },
                                MenuInput::Delete => {
                                    if clearable {
                                        selected.take();
                                    }
                                },
                                _ => ()
                            }
                        }))
                    })
                )
            })
            .child(
                Button::new()
                .width(Val::Px(300.))
                .hovered_signal(hovered.signal())
                .body(
                    Stack::<NodeBundle>::new()
                    .width(Val::Percent(100.))
                    .with_style(|mut style| style.padding = UiRect::horizontal(Val::Px(BASE_PADDING)))
                    .layer(
                        El::<TextBundle>::new()
                        .align(Align::new().left())
                        .text_signal(
                            selected.signal_cloned()
                            .map(|selected_option| {
                                selected_option.map(|option| option.to_string()).unwrap_or_default()
                            })
                            .map(text)
                        )
                    )
                    .layer(
                        Row::<NodeBundle>::new()
                        .with_style(|mut style| style.column_gap = Val::Px(BASE_PADDING))
                        .align(Align::new().right())
                        .item_signal(
                            // TODO: this should just work, but compiler asks for type info
                            // clearable.then(||
                            //     selected.signal_ref(Option::is_some).dedupe()
                            //     .map_true(clone!((selected) move || x_button(clone!((selected) move || { selected.take(); }))))
                            // )
                            if clearable {
                                selected.signal_ref(Option::is_some).dedupe()
                                .map_true(clone!((selected) move || x_button(clone!((selected) move || { selected.take(); }))))
                                .boxed()
                            } else {
                                always(None).boxed()
                            }
                        )
                        .item(
                            El::<TextBundle>::new()
                            // TODO: need to figure out to rotate in place (around center)
                            // .on_signal_with_transform(show_dropdown.signal(), |transform, showing| {
                            //     transform.rotate_around(Vec3::X, Quat::from_rotation_z((if showing { 180.0f32 } else { 0. }).to_radians()));
                            // })
                            .text(text("v"))
                        )
                    )
                )
                .on_click(clone!((show_dropdown) move || {
                    only_one_up_flipper(&show_dropdown, &DROPDOWN_SHOWING_OPTION, None);
                }))
            )
            // TODO: this should be element below signal
            .child_signal(
                show_dropdown.signal()
                .map_true(clone!((options, show_dropdown, selected) move || {
                    Column::<NodeBundle>::new()
                    .width(Val::Percent(100.))
                    .with_style(|mut style| {
                        style.position_type = PositionType::Absolute;
                        style.top = Val::Percent(100.);
                    })
                    .items_signal_vec(
                        options.signal_vec_cloned()
                        .enumerate()
                        .filter_signal_cloned(clone!((selected) move |(_, option)| {
                            selected.signal_ref(clone!((option) move |selected_option| {
                                selected_option.as_ref() != Some(&option)
                            }))
                            .dedupe()
                        }))
                        .map_signal(clone!((selected, show_dropdown, options_hovered) move |(i_mutable, option)| {
                            i_mutable.signal()
                            .map_some(clone!((options_hovered, selected, show_dropdown, option) move |i| {
                                if let Some(hovered) = options_hovered.lock_ref().get(i) {
                                    text_button(
                                        always(option.to_string()),
                                        clone!((selected, show_dropdown, option) move || {
                                            selected.set_neq(Some(option.clone()));
                                            flip(&show_dropdown);
                                        })
                                    )
                                    .width(Val::Percent(100.))
                                    .hovered_signal(hovered.signal())
                                    .apply(Some)
                                } else {
                                    None
                                }
                            }))
                        }))
                        .map(Option::flatten)
                    )
                }))
            )
        };
        Self { el, controlling }
    }
More examples
Hide additional examples
examples/counter.rs (line 56)
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
fn counter_button(counter: Mutable<i32>, label: &str, step: i32) -> impl Element {
    let hovered = Mutable::new(false);
    El::<NodeBundle>::new()
        .width(Val::Px(45.0))
        .align_content(Align::center())
        .background_color_signal(
            hovered
                .signal()
                .map_bool(|| Color::hsl(300., 0.75, 0.85), || Color::hsl(300., 0.75, 0.75))
                .map(BackgroundColor),
        )
        .hovered_sync(hovered)
        .on_click(move || *counter.lock_mut() += step)
        .child(El::<TextBundle>::new().text(text(label)))
}
examples/snake.rs (line 210)
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
fn restart_button() -> impl Element {
    let hovered = Mutable::new(false);
    El::<NodeBundle>::new()
        .align(Align::center())
        .width(Val::Px(250.))
        .height(Val::Px(80.))
        .background_color_signal(
            hovered
                .signal()
                .map_bool(|| bevy::color::palettes::basic::GRAY.into(), || Color::BLACK)
                .map(BackgroundColor),
        )
        .hovered_sync(hovered)
        .align_content(Align::center())
        .on_click(|| async_world().send_event(Restart).apply(spawn).detach())
        .child(El::<TextBundle>::new().text(Text::from_section(
            "restart",
            TextStyle {
                font_size: 60.,
                color: Color::WHITE,
                ..default()
            },
        )))
}
examples/healthbar.rs (line 232)
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
fn respawn_button() -> impl Element {
    let hovered = Mutable::new(false);
    El::<NodeBundle>::new()
        .align(Align::center())
        .width(Val::Px(250.))
        .height(Val::Px(80.))
        .background_color_signal(
            hovered
                .signal()
                .map_bool(|| bevy::color::palettes::basic::GRAY.into(), || Color::BLACK)
                .map(BackgroundColor),
        )
        .hovered_sync(hovered)
        .align_content(Align::center())
        .on_click(|| async_world().send_event(SpawnPlayer).apply(spawn).detach())
        .child(El::<TextBundle>::new().text(Text::from_section(
            "respawn",
            TextStyle {
                font_size: 60.,
                color: Color::WHITE,
                ..default()
            },
        )))
}
examples/calculator.rs (lines 73-86)
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
fn input_button(symbol: &'static str) -> impl Element {
    let hovered = Mutable::new(false);
    button(symbol)
        .cursor(CursorIcon::Pointer)
        .background_color_signal(hovered.signal().map_bool(|| BLUE, || PINK).map(BackgroundColor))
        .hovered_sync(hovered)
        .on_click(move || {
            let mut output = OUTPUT.lock_mut();
            if symbol == "=" {
                if let Ok(result) = Context::<f64>::default().evaluate(&output) {
                    if let Some(result) = Decimal::from_f64((result * 100.).round() / 100.) {
                        *output = result.normalize().to_string();
                        return;
                    }
                }
                ERROR.set_neq(true);
            } else {
                *output += symbol;
            }
        })
}

static OUTPUT: Lazy<Mutable<String>> = Lazy::new(default);
static ERROR: Lazy<Mutable<bool>> = Lazy::new(default);

fn display() -> impl Element {
    textable_element(OUTPUT.signal_cloned())
        .with_style(|mut style| {
            style.padding = UiRect::all(Val::Px(GAP));
            style.overflow = Overflow::clip();
        })
        .update_raw_el(|raw_el| {
            raw_el.component_signal::<Outline, _>(
                ERROR
                    .signal()
                    .map_true(|| Outline::new(Val::Px(4.0), Val::ZERO, bevy::color::palettes::basic::RED.into())),
            )
        })
        .width(Val::Px(BUTTON_SIZE * 3. + GAP * 2.))
        .height(Val::Px(BUTTON_SIZE))
        .background_color(BackgroundColor(BLUE))
        .align_content(Align::new().right().center_y())
}

fn clear_button() -> impl Element {
    let hovered = Mutable::new(false);
    let output_empty = OUTPUT.signal_ref(String::is_empty).broadcast();
    button("c")
        .background_color_signal(
            map_ref! {
                let output_empty = output_empty.signal(),
                let hovered = hovered.signal() => {
                    if *output_empty {
                        BLUE
                    } else if *hovered {
                        bevy::color::palettes::basic::RED.into()
                    } else {
                        PINK
                    }
                }
            }
            .dedupe()
            .map(BackgroundColor),
        )
        .cursor_disableable_signal(CursorIcon::Pointer, output_empty.signal())
        .hovered_sync(hovered)
        .on_click(|| OUTPUT.lock_mut().clear())
}
examples/align.rs (line 83)
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
fn alignment_button(alignment: Alignment) -> impl Element {
    let hovered = Mutable::new(false);
    El::<NodeBundle>::new()
        .align(Align::center())
        .width(Val::Px(250.))
        .height(Val::Px(80.))
        .background_color_signal(
            signal::or(
                hovered.signal(),
                ALIGNMENT
                    .signal()
                    .map(move |other_alignment| alignment == other_alignment),
            )
            .map_bool(|| bevy::color::palettes::basic::GRAY.into(), || Color::BLACK)
            .map(BackgroundColor),
        )
        .hovered_sync(hovered)
        .align_content(Align::center())
        .on_click(move || ALIGNMENT.set(alignment))
        .child(El::<TextBundle>::new().text(text(
            match alignment {
                Alignment::Self_ => "align self",
                Alignment::Content => "align content",
            },
            30.,
        )))
}

fn ui_root() -> impl Element {
    Column::<NodeBundle>::new()
        .width(Val::Percent(100.))
        .height(Val::Percent(100.))
        .with_style(|mut style| style.row_gap = Val::Px(15.))
        .align_content(Align::center())
        .align(Align::center())
        .item(
            Row::<NodeBundle>::new()
                .with_style(|mut style| style.column_gap = Val::Px(15.))
                .item(container("Column", Column::<NodeBundle>::new().items(rectangles())))
                .item(container("El", El::<NodeBundle>::new().child(rectangle(1))))
                // TODO: is this align content behavior buggy?
                .item(container("Grid", Grid::<NodeBundle>::new().cells(rectangles()))),
        )
        .item(
            Row::<NodeBundle>::new()
                .with_style(|mut style| style.column_gap = Val::Px(15.))
                .item(
                    Column::<NodeBundle>::new()
                        .with_style(|mut style| style.row_gap = Val::Px(15.))
                        .item(alignment_button(Alignment::Self_))
                        .item(alignment_button(Alignment::Content)),
                )
                .item(
                    Stack::<NodeBundle>::new()
                        .layers(RectangleAlignment::iter().map(align_switcher))
                        .apply(container_style),
                ),
        )
        .item(
            Row::<NodeBundle>::new()
                .with_style(|mut style| style.column_gap = Val::Px(15.))
                .item(container("Row", Row::<NodeBundle>::new().items(rectangles())))
                // TODO: is this align content behavior buggy?
                .item(container("Stack", Stack::<NodeBundle>::new().layers(rectangles()))),
        )
}

fn container_style<E: RawElWrapper + Sizeable>(el: E) -> E {
    el.width(Val::Px(278.)).height(Val::Px(200.)).update_raw_el(|raw_el| {
        raw_el
            .insert::<BorderColor>(bevy::color::palettes::basic::GRAY.into())
            .with_component::<Style>(|mut style| {
                style.border = UiRect::all(Val::Px(3.));
            })
    })
}

fn text(text: &str, font_size: f32) -> Text {
    Text::from_section(text, TextStyle { font_size, ..default() })
}

fn container(name: &str, element: impl Element + Sizeable) -> impl Element {
    Column::<NodeBundle>::new()
        .item(
            El::<TextBundle>::new()
                .align(Align::new().center_x())
                .text(text(name, 30.)),
        )
        .item(
            element
                .align_content_signal(
                    ALIGNMENT
                        .signal()
                        .map(|alignment| matches!(alignment, Alignment::Content))
                        .map_true_signal(|| {
                            RECTANGLE_CONTENT_ALIGNMENT
                                .signal_ref(|alignment| alignment.map(|alignment| alignment.to_align()))
                        })
                        .map(Option::flatten),
                )
                .apply(container_style),
        )
}

fn rectangle(index: i32) -> impl Element {
    let size = 40;
    El::<NodeBundle>::new()
        .width(Val::Px(size as f32))
        .height(Val::Px(size as f32))
        .background_color(BackgroundColor(bevy::color::palettes::css::DARK_GREEN.into()))
        .align_signal(
            ALIGNMENT
                .signal()
                .map(|alignment| matches!(alignment, Alignment::Self_))
                .map_true_signal(|| {
                    RECTANGLE_SELF_ALIGNMENT.signal_ref(|alignment| alignment.map(|alignment| alignment.to_align()))
                })
                .map(Option::flatten),
        )
        .child(
            El::<TextBundle>::new()
                .align(Align::center())
                .text(text(&index.to_string(), 14.)),
        )
}

fn rectangles() -> Vec<impl Element> {
    (1..=2).map(rectangle).collect()
}

fn align_switcher(rectangle_alignment: RectangleAlignment) -> impl Element {
    let (hovered, hovered_signal) = Mutable::new_and_signal(false);
    El::<NodeBundle>::new()
        .align(rectangle_alignment.to_align())
        .background_color_signal(
            signal::or(
                ALIGNMENT
                    .signal()
                    .map(|alignment| match alignment {
                        Alignment::Self_ => RECTANGLE_SELF_ALIGNMENT.signal(),
                        Alignment::Content => RECTANGLE_CONTENT_ALIGNMENT.signal(),
                    })
                    .flatten()
                    .map(move |selected_option| selected_option == Some(rectangle_alignment)),
                hovered_signal,
            )
            .map_bool(
                || bevy::color::palettes::basic::BLUE.into(),
                || bevy::color::palettes::css::MIDNIGHT_BLUE.into(),
            ),
        )
        .with_style(|mut style| style.padding = UiRect::all(Val::Px(5.)))
        .child(El::<TextBundle>::new().text(text(&rectangle_alignment.to_string(), 14.)))
        .hovered_sync(hovered)
        .on_click(move || {
            match ALIGNMENT.get() {
                Alignment::Self_ => &RECTANGLE_SELF_ALIGNMENT,
                Alignment::Content => &RECTANGLE_CONTENT_ALIGNMENT,
            }
            .set(Some(rectangle_alignment));
        })
}
Source

fn on_click_propagation_stoppable( self, handler: impl FnMut() + Send + Sync + 'static, propagation_stopped: impl Signal<Item = bool> + Send + 'static, ) -> Self

Run a function when this element is left clicked, reactively controlling whether the click bubbles up the hierarchy with a Signal.

Source

fn on_click_stop_propagation( self, handler: impl FnMut() + Send + Sync + 'static, ) -> Self

Run a function when this element is left clicked, stopping the click from bubbling up the hierarchy.

Examples found in repository?
examples/challenge07.rs (line 151)
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
fn x_button(on_click: impl FnMut() + Send + Sync + 'static) -> impl Element {
    let hovered = Mutable::new(false);
    El::<NodeBundle>::new()
        .background_color(BackgroundColor(Color::NONE))
        // stop propagation because otherwise clearing the dropdown will drop down the
        // options too; the x should eat the click
        .on_click_stop_propagation(on_click)
        .child(
            El::<TextBundle>::new().text(text("x")).on_signal_with_text(
                hovered
                    .signal()
                    .map_bool(|| bevy::color::palettes::basic::RED.into(), || Color::WHITE),
                |mut text, color| {
                    if let Some(section) = text.sections.first_mut() {
                        section.style.color = color;
                    }
                },
            ),
        )
        .hovered_sync(hovered)
}
More examples
Hide additional examples
examples/main_menu.rs (line 1056)
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
fn x_button(on_click: impl FnMut() + Send + Sync + 'static) -> impl Element {
    let hovered = Mutable::new(false);
    El::<NodeBundle>::new()
        .background_color(BackgroundColor(Color::NONE))
        .hovered_sync(hovered.clone())
        // stop propagation because otherwise clearing the dropdown will drop down the
        // options too; the x should eat the click
        .on_click_stop_propagation(on_click)
        .child(
            El::<TextBundle>::new().text(text("x")).on_signal_with_text(
                hovered
                    .signal()
                    .map_bool(|| bevy::color::palettes::basic::RED.into(), || TEXT_COLOR),
                |mut text, color| {
                    if let Some(section) = text.sections.first_mut() {
                        section.style.color = color;
                    }
                },
            ),
        )
}
Source

fn on_right_click(self, handler: impl FnMut() + Send + Sync + 'static) -> Self

Run a function when this element is right clicked.

Source

fn on_click_outside_with_system<Marker>( self, handler: impl IntoSystem<(Entity, Pointer<Click>), (), Marker> + Send + 'static, ) -> Self

When a Pointer<Click> is received outside this Element or its descendents, run a System that takes In this element’s Entity and the Pointer<Click>. Requires the UiRoot Resource to exist in the World. This method can be called repeatedly to register many such handlers.

Examples found in repository?
examples/character_editor.rs (lines 153-155)
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
fn ui_root() -> impl Element {
    El::<NodeBundle>::new()
        .ui_root()
        .width(Val::Percent(100.))
        .height(Val::Percent(100.))
        .align_content(Align::center())
        .child(
            Stack::<NodeBundle>::new()
                .width(Val::Percent(100.))
                .height(Val::Percent(100.))
                .layer(
                    Column::<NodeBundle>::new()
                        .align(Align::new().center_y().right())
                        .with_style(|mut style| {
                            style.padding.right = Val::Percent(20.);
                            style.row_gap = Val::Px(20.);
                        })
                        .item({
                            let focused = Mutable::new(false);
                            let name = Mutable::new(String::new());
                            let name_shape_syncer = name.signal_cloned().for_each_sync(|name| {
                                if let Some((i, shape)) =
                                    Shape::iter().enumerate().find(|(_, shape)| shape.to_string() == name)
                                {
                                    SELECTED_SHAPE.set_neq(shape);
                                    if let Val::Px(height) = BUTTON_HEIGHT {
                                        SCROLL_POSITION.set(i as f32 * -height);
                                    }
                                }
                            });
                            TextInput::new()
                                .update_raw_el(move |raw_el| raw_el.hold_tasks([spawn(name_shape_syncer)]))
                                .width(BUTTON_WIDTH)
                                .height(Val::Px(40.))
                                .mode(CosmicWrap::InfiniteLine)
                                .scroll_disabled()
                                .cursor_color(CursorColor(Color::WHITE))
                                .fill_color(CosmicBackgroundColor(NORMAL_BUTTON))
                                .attrs(TextAttrs::new().color(Color::WHITE))
                                .placeholder(
                                    Placeholder::new()
                                        .text("name")
                                        .attrs(TextAttrs::new().color(bevy::color::palettes::basic::GRAY)),
                                )
                                .focus_signal(focused.signal())
                                .focused_sync(focused)
                                .on_change_sync(name)
                                .on_click_outside_with_system(|In(_), mut commands: Commands| {
                                    commands.remove_resource::<FocusedTextInput>()
                                })
                        })
                        .item({
                            let hovereds = MutableVec::new_with_values(
                                (0..Shape::iter().count()).map(|_| Mutable::new(false)).collect(),
                            );
                            Column::<NodeBundle>::new()
                                .height(Val::Px(200.))
                                .align(Align::new().center_x())
                                .mutable_viewport(Overflow::clip_y(), LimitToBody::Vertical)
                                .on_scroll_with_system_on_hover(
                                    BasicScrollHandler::new()
                                        .direction(ScrollDirection::Vertical)
                                        .pixels(20.)
                                        .into_system(),
                                )
                                .viewport_y_signal(SCROLL_POSITION.signal())
                                .items({
                                    let hovereds = hovereds.lock_ref().iter().cloned().collect::<Vec<_>>();
                                    Shape::iter()
                                        .zip(hovereds)
                                        .map(move |(shape, hovered)| button(shape, hovered))
                                })
                        }),
                ),
        )
}
Source

fn on_click_outside(self, handler: impl FnMut() + Send + Sync + 'static) -> Self

When a Pointer<Click> is received outside this Element or its descendents, run a function. Requires the UiRoot Resource to exist in the World. This method can be called repeatedly to register many such handlers.

Source

fn on_pressed_with_system_blockable<Marker, Blocked: Component>( self, handler: impl IntoSystem<(Entity, bool), (), Marker> + Send + 'static, ) -> Self

On frames where this element is pressed or gets unpressed and does not have a Blocked Component, run a System which takes In this element’s Entity and its current pressed state. This method can be called repeatedly to register many such handlers.

Source

fn on_pressed_change_with_system<Marker>( self, handler: impl IntoSystem<(Entity, bool), (), Marker> + Send + 'static, ) -> Self

When this element’s pressed state changes, run a System which takes In this element’s Entity and its current pressed state. This method can be called repeatedly to register many such handlers.

Source

fn on_pressed_change( self, handler: impl FnMut(bool) + Send + Sync + 'static, ) -> Self

When this element’s pressed state changes, run a function with its current pressed state.

Source

fn on_pressing_with_system_blockable<Marker, Blocked: Component>( self, handler: impl IntoSystem<Entity, (), Marker> + Send + 'static, ) -> Self

On frames where this element is being pressed and does not have a Blocked Component, run a System which takes In this element’s Entity. This method can be called repeatedly to register many such handlers.

Source

fn on_pressing_blockable<Blocked: Component>( self, handler: impl FnMut() + Send + Sync + 'static, ) -> Self

On frames where this element is being pressed, run a function.

Source

fn on_pressing_blockable_signal( self, handler: impl FnMut() + Send + Sync + 'static, blocked: impl Signal<Item = bool> + Send + 'static, ) -> Self

On frames where this element is being pressed, run a function, reactively controlling whether the press is blocked with a Signal.

Source

fn on_pressing(self, handler: impl FnMut() + Send + Sync + 'static) -> Self

When this element is being pressed, run a function.

Source

fn on_pressing_with_system_throttled<Fut: Future<Output = ()> + Send + 'static, Marker>( self, handler: impl IntoSystem<Entity, (), Marker> + Send + 'static, throttle: impl FnMut() -> Fut + Send + 'static, ) -> Self

When this element is being pressed, run a System which takes In this element’s Entity, waiting for the Future returned by throttle to complete before running the handler again.

Source

fn on_pressing_with_system_with_sleep_throttle<Marker>( self, handler: impl IntoSystem<Entity, (), Marker> + Send + 'static, duration: Duration, ) -> Self

When this element is being pressed, run a System which takes In this element’s Entity, waiting for duration before running the handler again.

Examples found in repository?
examples/snake.rs (lines 142-147)
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
fn hud(score: Mutable<u32>, size: Mutable<usize>, tick_rate: Mutable<u32>) -> impl Element {
    Column::<NodeBundle>::new()
        .width(Val::Px((WIDTH - SIDE) as f32))
        .with_style(|mut style| style.row_gap = Val::Px(10.))
        .align_content(Align::center())
        .item(El::<TextBundle>::new().text_signal(score.signal().map(|score| {
            Text::from_section(
                score.to_string(),
                TextStyle {
                    font_size: 300.,
                    ..default()
                },
            )
        })))
        .item(
            Row::<NodeBundle>::new()
                .with_style(|mut style| style.column_gap = Val::Px(10.))
                .item(El::<TextBundle>::new().text(text("grid size:")))
                .item(El::<TextBundle>::new().text_signal(size.signal().map(|size| text(&size.to_string()))))
                .item(text_button("-").on_pressing_with_system_with_sleep_throttle(
                    |_: In<_>, mut grid_size_changes: EventWriter<GridSizeChange>| {
                        grid_size_changes.send(GridSizeChange::Decr);
                    },
                    Duration::from_millis(100),
                ))
                .item(text_button("+").on_pressing_with_system_with_sleep_throttle(
                    |_: In<_>, mut grid_size_changes: EventWriter<GridSizeChange>| {
                        grid_size_changes.send(GridSizeChange::Incr);
                    },
                    Duration::from_millis(100),
                )),
        )
        .item(
            Row::<NodeBundle>::new()
                .with_style(|mut style| style.column_gap = Val::Px(10.))
                .item(El::<TextBundle>::new().text(text("tick rate:")))
                .item(El::<TextBundle>::new().text_signal(tick_rate.signal().map(|size| text(&size.to_string()))))
                .item(text_button("-").on_pressing_with_system_with_sleep_throttle(
                    |_: In<_>, world: &mut World| {
                        let cur_rate = TICK_RATE.get();
                        if cur_rate > 1 {
                            TICK_RATE.update(|rate| rate - 1);
                            world.insert_resource(Time::<Fixed>::from_seconds(1. / (cur_rate - 1) as f64));
                        }
                    },
                    Duration::from_millis(100),
                ))
                .item(text_button("+").on_pressing_with_system_with_sleep_throttle(
                    |_: In<_>, world: &mut World| {
                        let cur_rate = TICK_RATE.get();
                        TICK_RATE.update(|rate| rate + 1);
                        world.insert_resource(Time::<Fixed>::from_seconds(1. / (cur_rate + 1) as f64));
                    },
                    Duration::from_millis(100),
                )),
        )
}
Source

fn on_pressing_throttled<Fut: Future<Output = ()> + Send + 'static>( self, handler: impl FnMut() + Send + Sync + 'static, throttle: impl FnMut() -> Fut + Send + 'static, ) -> Self

When this element is being pressed, run a function, waiting for the Future returned by throttle to complete before running the handler again.

Source

fn on_pressing_with_sleep_throttle( self, handler: impl FnMut() + Send + Sync + 'static, duration: Duration, ) -> Self

When this element is being pressed, run a function, waiting for duration before running the handler again.

Examples found in repository?
examples/ecs_ui_sync.rs (line 127)
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
fn incrde_button(value: Mutable<f32>, incr: f32) -> impl Element {
    let hovered = Mutable::new(false);
    let f = move || {
        let new = (*value.lock_ref() + incr).max(0.);
        *value.lock_mut() = new;
    };
    El::<NodeBundle>::new()
        .width(Val::Px(45.0))
        .align_content(Align::center())
        .background_color_signal(
            hovered
                .signal()
                .map_bool(|| Color::hsl(300., 0.75, 0.85), || Color::hsl(300., 0.75, 0.75))
                .map(BackgroundColor),
        )
        .hovered_sync(hovered)
        .on_pressing_with_sleep_throttle(f, Duration::from_millis(50))
        .child(El::<TextBundle>::new().text(text(if incr.is_sign_positive() { "+" } else { "-" })))
}
Source

fn pressed_sync(self, pressed: Mutable<bool>) -> Self

Sync a Mutable with this element’s pressed state.

Examples found in repository?
examples/responsive_menu.rs (line 105)
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
fn nine_slice_button() -> impl Element {
    let hovered = Mutable::new(false);
    let pressed = Mutable::new(false);
    NineSliceEl::new(map_ref! {
        let hovered = hovered.signal(),
        let pressed = pressed.signal() => {
            if *pressed {
                2
            } else if *hovered {
                1
            } else {
                0
            }
        }
    })
    .width(Val::Px(100.))
    .height(Val::Px(50.))
    .hovered_sync(hovered)
    .pressed_sync(pressed)
}
More examples
Hide additional examples
examples/challenge07.rs (line 142)
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
fn button() -> El<NodeBundle> {
    let (pressed, pressed_signal) = Mutable::new_and_signal(false);
    let (hovered, hovered_signal) = Mutable::new_and_signal(false);
    let pressed_hovered_broadcaster =
        map_ref!(pressed_signal, hovered_signal => (*pressed_signal, *hovered_signal)).broadcast();
    let border_color_signal = {
        pressed_hovered_broadcaster
            .signal()
            .map(|(pressed, hovered)| {
                if pressed {
                    bevy::color::palettes::basic::RED.into()
                } else if hovered {
                    Color::WHITE
                } else {
                    Color::BLACK
                }
            })
            .map(BorderColor)
    };
    let background_color_signal = {
        pressed_hovered_broadcaster
            .signal()
            .map(|(pressed, hovered)| {
                if pressed {
                    PRESSED_BUTTON
                } else if hovered {
                    HOVERED_BUTTON
                } else {
                    NORMAL_BUTTON
                }
            })
            .map(BackgroundColor)
    };
    El::<NodeBundle>::new()
        .width(Val::Px(150.0))
        .height(Val::Px(65.))
        .with_style(|mut style| style.border = UiRect::all(Val::Px(5.0)))
        .align_content(Align::center())
        .border_color_signal(border_color_signal)
        .background_color_signal(background_color_signal)
        .hovered_sync(hovered)
        .cursor_disableable_signal(CursorIcon::Grabbing, pressed.signal().dedupe())
        .pressed_sync(pressed)
}
examples/character_editor.rs (line 94)
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
fn button(shape: Shape, hovered: Mutable<bool>) -> impl Element {
    let selected = SELECTED_SHAPE.signal().eq(shape);
    let (pressed, pressed_signal) = Mutable::new_and_signal(false);
    let hovered_signal = hovered.signal();
    let selected_hovered_broadcaster =
        map_ref!(selected, pressed_signal, hovered_signal => (*selected || *pressed_signal, *hovered_signal))
            .broadcast();
    let border_color_signal = {
        selected_hovered_broadcaster
            .signal()
            .map(|(selected, hovered)| {
                if selected {
                    bevy::color::palettes::basic::RED.into()
                } else if hovered {
                    Color::WHITE
                } else {
                    Color::BLACK
                }
            })
            .map(BorderColor)
    };
    let background_color_signal = {
        selected_hovered_broadcaster
            .signal()
            .map(|(selected, hovered)| {
                if selected {
                    CLICKED_BUTTON
                } else if hovered {
                    HOVERED_BUTTON
                } else {
                    NORMAL_BUTTON
                }
            })
            .map(BackgroundColor)
    };
    El::<NodeBundle>::new()
        .width(BUTTON_WIDTH)
        .height(BUTTON_HEIGHT)
        .with_style(|mut style| style.border = UiRect::all(Val::Px(5.)))
        .align_content(Align::center())
        .border_color_signal(border_color_signal)
        .background_color_signal(background_color_signal)
        .hovered_sync(hovered)
        .pressed_sync(pressed)
        .on_click(move || SELECTED_SHAPE.set_neq(shape))
        .child(El::<TextBundle>::new().text(Text::from_section(
            shape.to_string(),
            TextStyle {
                font_size: 40.0,
                color: Color::srgb(0.9, 0.9, 0.9),
                ..default()
            },
        )))
}
examples/main_menu.rs (line 128)
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
    fn new() -> Self {
        let (selected, selected_signal) = Mutable::new_and_signal(false);
        let (pressed, pressed_signal) = Mutable::new_and_signal(false);
        let (hovered, hovered_signal) = Mutable::new_and_signal(false);
        let selected_hovered_broadcaster = map_ref!(selected_signal, pressed_signal, hovered_signal => (*selected_signal || *pressed_signal, *hovered_signal)).broadcast();
        let border_color_signal = {
            selected_hovered_broadcaster
                .signal()
                .map(|(selected, hovered)| {
                    if selected {
                        bevy::color::palettes::basic::RED.into()
                    } else if hovered {
                        Color::WHITE
                    } else {
                        Color::BLACK
                    }
                })
                .map(BorderColor)
        };
        let background_color_signal = {
            selected_hovered_broadcaster
                .signal()
                .map(|(selected, hovered)| {
                    if selected {
                        CLICKED_BUTTON
                    } else if hovered {
                        HOVERED_BUTTON
                    } else {
                        NORMAL_BUTTON
                    }
                })
                .map(BackgroundColor)
        };
        Self {
            el: {
                El::<NodeBundle>::new()
                    .height(Val::Px(DEFAULT_BUTTON_HEIGHT))
                    .with_style(|mut style| {
                        style.border = UiRect::all(Val::Px(BASE_BORDER_WIDTH));
                    })
                    .pressed_sync(pressed)
                    .align_content(Align::center())
                    .hovered_sync(hovered.clone())
                    .border_color_signal(border_color_signal)
                    .background_color_signal(background_color_signal)
            },
            selected,
            hovered,
        }
    }
examples/button.rs (line 71)
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
fn button(font: Handle<Font>) -> impl Element {
    let (pressed, pressed_signal) = Mutable::new_and_signal(false);
    let (hovered, hovered_signal) = Mutable::new_and_signal(false);
    let pressed_hovered_broadcaster =
        map_ref!(pressed_signal, hovered_signal => (*pressed_signal, *hovered_signal)).broadcast();
    let border_color_signal = {
        pressed_hovered_broadcaster
            .signal()
            .map(|(pressed, hovered)| {
                if pressed {
                    bevy::color::palettes::basic::RED.into()
                } else if hovered {
                    Color::WHITE
                } else {
                    Color::BLACK
                }
            })
            .map(BorderColor)
    };
    let background_color_signal = {
        pressed_hovered_broadcaster
            .signal()
            .map(|(pressed, hovered)| {
                if pressed {
                    PRESSED_BUTTON
                } else if hovered {
                    HOVERED_BUTTON
                } else {
                    NORMAL_BUTTON
                }
            })
            .map(BackgroundColor)
    };
    El::<NodeBundle>::new()
        .width(Val::Px(150.0))
        .height(Val::Px(65.))
        .with_style(|mut style| style.border = UiRect::all(Val::Px(5.0)))
        .align_content(Align::center())
        .border_color_signal(border_color_signal)
        .background_color_signal(background_color_signal)
        .border_radius(BorderRadius::MAX)
        .hovered_sync(hovered)
        .pressed_sync(pressed)
        .child(
            El::<TextBundle>::new().text_signal(
                pressed_hovered_broadcaster
                    .signal()
                    .map(|(pressed, hovered)| {
                        if pressed {
                            "Press"
                        } else if hovered {
                            "Hover"
                        } else {
                            "Button"
                        }
                    })
                    .map(move |string| {
                        Text::from_section(
                            string,
                            TextStyle {
                                font: font.clone(),
                                font_size: 40.0,
                                color: Color::srgb(0.9, 0.9, 0.9),
                            },
                        )
                    }),
            ),
        )
}

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementors§

Source§

impl PointerEventAware for TextInput

Source§

impl<NodeType: Bundle> PointerEventAware for Grid<NodeType>

Source§

impl<NodeType: Bundle> PointerEventAware for Column<NodeType>

Source§

impl<NodeType: Bundle> PointerEventAware for El<NodeType>

Source§

impl<NodeType: Bundle> PointerEventAware for Row<NodeType>

Source§

impl<NodeType: Bundle> PointerEventAware for Stack<NodeType>