From 3411aba768dc87f74d9713ba76c36a836c72d307 Mon Sep 17 00:00:00 2001 From: Antoine Beyeler <49431240+abey79@users.noreply.github.com> Date: Tue, 3 Dec 2024 11:46:37 +0100 Subject: [PATCH] Modals: Add `UiKind::Modal`, and consume escape-key properly (#5414) Small fixes/improvements to `Modal` - Fixes #5413 --- crates/egui/src/containers/modal.rs | 11 ++++++++--- crates/egui/src/ui_stack.rs | 10 ++++++++++ 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/crates/egui/src/containers/modal.rs b/crates/egui/src/containers/modal.rs index 25f3fbce7ca..521b9dedba4 100644 --- a/crates/egui/src/containers/modal.rs +++ b/crates/egui/src/containers/modal.rs @@ -1,5 +1,5 @@ use crate::{ - Area, Color32, Context, Frame, Id, InnerResponse, Order, Response, Sense, Ui, UiBuilder, + Area, Color32, Context, Frame, Id, InnerResponse, Order, Response, Sense, Ui, UiBuilder, UiKind, }; use emath::{Align2, Vec2}; @@ -32,6 +32,7 @@ impl Modal { /// - order: foreground pub fn default_area(id: Id) -> Area { Area::new(id) + .kind(UiKind::Modal) .sense(Sense::hover()) .anchor(Align2::CENTER_CENTER, Vec2::ZERO) .order(Order::Foreground) @@ -153,8 +154,12 @@ impl ModalResponse { /// - this is the topmost modal, no popup is open and the escape key was pressed pub fn should_close(&self) -> bool { let ctx = &self.response.ctx; - let escape_clicked = ctx.input(|i| i.key_pressed(crate::Key::Escape)); + + // this is a closure so that `Esc` is consumed only if the modal is topmost + let escape_clicked = + || ctx.input_mut(|i| i.consume_key(crate::Modifiers::NONE, crate::Key::Escape)); + self.backdrop_response.clicked() - || (self.is_top_modal && !self.any_popup_open && escape_clicked) + || (self.is_top_modal && !self.any_popup_open && escape_clicked()) } } diff --git a/crates/egui/src/ui_stack.rs b/crates/egui/src/ui_stack.rs index 7aae3f2fbeb..7aa131bec7a 100644 --- a/crates/egui/src/ui_stack.rs +++ b/crates/egui/src/ui_stack.rs @@ -24,6 +24,9 @@ pub enum UiKind { /// A bottom [`crate::TopBottomPanel`]. BottomPanel, + /// A modal [`crate::Modal`]. + Modal, + /// A [`crate::Frame`]. Frame, @@ -82,6 +85,7 @@ impl UiKind { Self::Window | Self::Menu + | Self::Modal | Self::Popup | Self::Tooltip | Self::Picker @@ -228,6 +232,12 @@ impl UiStack { self.kind().map_or(false, |kind| kind.is_panel()) } + /// Is this [`crate::Ui`] an [`crate::Area`]? + #[inline] + pub fn is_area_ui(&self) -> bool { + self.kind().map_or(false, |kind| kind.is_area()) + } + /// Is this a root [`crate::Ui`], i.e. created with [`crate::Ui::new()`]? #[inline] pub fn is_root_ui(&self) -> bool {