Skip to content

Commit

Permalink
update example
Browse files Browse the repository at this point in the history
  • Loading branch information
xarvic committed Sep 20, 2022
1 parent 0807c31 commit eff2716
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 4 deletions.
15 changes: 11 additions & 4 deletions druid/examples/menu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,22 +74,29 @@ fn build_menu() -> Menu<AppState> {
)
.entry(
MenuItem::new("1 Selected")
.on_activate(|_, data: &mut AppState, _|if data.value == 1 {data.value = 0} else {data.value = 1})
.selected_if(|data: &AppState, _|data.value == 1)
.radio_item(1, Some(0))
.lens(AppState::value)
)
.entry(
MenuItem::new("2 Selected")
.on_activate(|_, data: &mut AppState, _|if data.value == 2 {data.value = 0} else {data.value = 2})
.selected_if(|data: &AppState, _|data.value == 2)
.radio_item(2, Some(0))
.lens(AppState::value)
)
.entry(
// Implementing the radio item from hand
MenuItem::new("3 Selected")
.on_activate(|_, data: &mut AppState, _|if data.value == 3 {data.value = 0} else {data.value = 3})
.selected_if(|data: &AppState, _|data.value == 3)
)
.separator()
.entry(
MenuItem::new("CheckBox")
.toggle_data()
.lens(AppState::option)
)
.entry(
// Implementing the CheckBox from hand
MenuItem::new("Manual CheckBox")
.on_activate(|_, data: &mut AppState, _|data.option = !data.option)
.selected_if(|data: &AppState, _|data.option)
)
Expand Down
29 changes: 29 additions & 0 deletions druid/src/menu/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -638,6 +638,23 @@ impl<T: Data> MenuItem<T> {
self.on_activate(move |ctx, _data, _env| ctx.submit_command(cmd.clone()))
}

/// Turns this `MenuItem` into a `RadioButton`
///
/// When selected this MenuItem will set the provided value as data.
/// If data is equal to the provided value the Item is selected otherwise not.
pub fn radio_item(self, value: T, unselect: Option<T>) -> Self where T: PartialEq {
let value2 = value.clone();
self
.on_activate(move |_, data: &mut T, _|{
if data != value {
*data = value.clone();
} else if let Some(value) = unselect.clone() {
*data = value;
}
})
.selected_if(move |data, _|data == value2)
}

/// Provide a hotkey for activating this menu item.
///
/// This is equivalent to
Expand Down Expand Up @@ -723,6 +740,18 @@ impl<T: Data> MenuItem<T> {
}
}

impl MenuItem<bool> {
/// Turns the MenuItem into a CheckBox.
///
/// this is a convenience method which sets the `on_activate` and `selected_if` callbacks
/// to behave like a `CheckBox`.
pub fn toggle_data(self) -> Self {
self
.on_activate(|_, data, _|*data = !*data)
.selected_if(|data, _|*data)
}
}

impl<T: Data> MenuVisitor<T> for Menu<T> {
fn activate(&mut self, ctx: &mut MenuEventCtx, id: MenuItemId, data: &mut T, env: &Env) {
for child in &mut self.children {
Expand Down

0 comments on commit eff2716

Please sign in to comment.