From 718d2ddb7b3e8179e36ef4881e94d7facbd17b28 Mon Sep 17 00:00:00 2001 From: pml68 Date: Sat, 5 Jul 2025 09:14:58 +0200 Subject: feat: add `on_press` and `on_press_with` methods for backdrop clicks --- src/dialog.rs | 49 ++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 40 insertions(+), 9 deletions(-) (limited to 'src/dialog.rs') diff --git a/src/dialog.rs b/src/dialog.rs index fd46bc2..0d3bbd5 100644 --- a/src/dialog.rs +++ b/src/dialog.rs @@ -42,6 +42,7 @@ pub struct Dialog< title: Option>, content: Element<'a, Message, Theme, Renderer>, buttons: Vec>, + on_press: Option Message + 'a>>, font: Option, width: Length, height: Length, @@ -96,6 +97,7 @@ where title: None, content, buttons, + on_press: None, font: None, width: size.width.fluid(), height: size.height.fluid(), @@ -116,6 +118,27 @@ where self } + /// Sets the message that will be produced when the [`Dialog`]'s backdrop is pressed. + pub fn on_press(mut self, on_press: Message) -> Self + where + Message: Clone, + { + self.on_press = Some(Box::new(move || on_press.clone())); + self + } + + /// Sets the message that will be produced when the [`Dialog`]'s backdrop is pressed. + /// + /// This is analogous to [`Dialog::on_press`], but using a closure to produce + /// the message. + pub fn on_press_with( + mut self, + on_press: impl Fn() -> Message + 'a, + ) -> Self { + self.on_press = Some(Box::new(on_press)); + self + } + /// Sets the [`Dialog`]'s width. pub fn width(mut self, width: impl Into) -> Self { self.width = width.into(); @@ -349,7 +372,7 @@ where .clip(true) }); - modal(self.base, dialog, self.class) + modal(self.base, dialog, self.on_press, self.class) } } @@ -370,6 +393,7 @@ where fn modal<'a, Message, Theme, Renderer>( base: impl Into>, content: Option>>, + on_press: Option Message + 'a>, class: ::Class<'a>, ) -> Element<'a, Message, Theme, Renderer> where @@ -380,14 +404,21 @@ where From>, { let area = content.map(|content| { - opaque(mouse_area(center(opaque(content)).style(move |theme| { - container::Style { - background: Some( - Catalog::style(theme, &class).backdrop_color.into(), - ), - ..Default::default() - } - }))) + let backdrop = + mouse_area(center(opaque(content)).style(move |theme| { + container::Style { + background: Some( + Catalog::style(theme, &class).backdrop_color.into(), + ), + ..Default::default() + } + })); + + if let Some(on_press) = on_press { + opaque(backdrop.on_press(on_press())) + } else { + opaque(backdrop) + } }); stack![base.into()].push_maybe(area).into() -- cgit v1.2.3