Skip to main content

cranpose_ui/widgets/
dialog.rs

1//! Modal dialogs.
2//!
3//! A dialog is the one surface that takes the whole screen's attention: while
4//! it is open, everything behind it is inert, a back gesture closes it rather
5//! than the screen behind it, a screen reader announces it and stays inside it,
6//! and a text field inside it keeps its focus while everything outside loses
7//! the ability to take focus away.
8//!
9//! Dialogs are built on [`crate::widgets::popup`], so their content escapes
10//! every ancestor clip and draws above the whole application, and they are
11//! centred inside the window insets so the system bars and the on-screen
12//! keyboard never cover them.
13
14#![allow(non_snake_case)]
15
16use std::rc::Rc;
17
18use cranpose_ui_graphics::{Color, Point, Rect, Size};
19use cranpose_ui_layout::Alignment;
20
21use super::{
22    box_widget::{Box, BoxSpec},
23    popup::{PopupDismissable, local_popup_viewport},
24};
25use crate::{Modifier, SemanticsWidgetRole, composable, safe_area::window_insets};
26
27/// Why a dialog is being asked to close.
28#[derive(Clone, Copy, Debug, PartialEq, Eq)]
29pub enum DismissReason {
30    /// The user tapped outside the dialog's surface.
31    OutsideTap,
32    /// The user made the platform's back gesture, or pressed Escape.
33    BackRequested,
34}
35
36/// How a dialog behaves.
37#[derive(Clone, Copy, Debug, PartialEq, Eq)]
38pub struct DialogSpec {
39    /// Whether a tap outside the dialog dismisses it.
40    pub dismiss_on_outside_tap: bool,
41    /// Whether the platform's back gesture dismisses it.
42    pub dismiss_on_back: bool,
43    /// Whether the dialog keeps clear of the system bars and the on-screen
44    /// keyboard. A dialog that draws its own full-bleed surface turns this off.
45    pub apply_window_insets: bool,
46}
47
48impl Default for DialogSpec {
49    fn default() -> Self {
50        Self {
51            dismiss_on_outside_tap: true,
52            dismiss_on_back: true,
53            apply_window_insets: true,
54        }
55    }
56}
57
58impl DialogSpec {
59    /// A dialog the user must answer: neither an outside tap nor a back
60    /// gesture closes it, so only the dialog's own controls can.
61    pub const fn required() -> Self {
62        Self {
63            dismiss_on_outside_tap: false,
64            dismiss_on_back: false,
65            apply_window_insets: true,
66        }
67    }
68
69    /// Sets whether an outside tap dismisses the dialog.
70    pub const fn with_dismiss_on_outside_tap(mut self, dismiss: bool) -> Self {
71        self.dismiss_on_outside_tap = dismiss;
72        self
73    }
74
75    /// Sets whether the back gesture dismisses the dialog.
76    pub const fn with_dismiss_on_back(mut self, dismiss: bool) -> Self {
77        self.dismiss_on_back = dismiss;
78        self
79    }
80
81    /// Sets whether the dialog keeps clear of system insets.
82    pub const fn with_window_insets(mut self, apply: bool) -> Self {
83        self.apply_window_insets = apply;
84        self
85    }
86}
87
88/// The default dim behind a dialog, matching what every platform's own modal
89/// surfaces use closely enough that a dialog does not look foreign.
90pub const DEFAULT_SCRIM: Color = Color(0.0, 0.0, 0.0, 0.4);
91
92/// The rectangle a dialog's surface is placed in.
93///
94/// The dialog fills the window minus its insets; the surface itself is centred
95/// inside that and sized by its own content.
96pub(crate) fn dialog_bounds(viewport: Size, insets: cranpose_ui_graphics::EdgeInsets) -> Rect {
97    let width = (viewport.width - insets.left - insets.right).max(0.0);
98    let height = (viewport.height - insets.top - insets.bottom).max(0.0);
99    Rect::from_origin_size(
100        Point {
101            x: insets.left,
102            y: insets.top,
103        },
104        Size { width, height },
105    )
106}
107
108/// A modal dialog holding `content`, dismissed through `on_dismiss`.
109///
110/// `on_dismiss` receives why the dialog is closing, so an application can treat
111/// "tapped away" differently from "went back" — a draft, for example, is
112/// usually kept in one case and discarded in the other.
113///
114/// ```rust,no_run
115/// # use cranpose_ui::widgets::{Dialog, DialogSpec};
116/// # use cranpose_ui::Modifier;
117/// # fn Content() {}
118/// # let open = true;
119/// if open {
120///     Dialog(
121///         DialogSpec::default(),
122///         |_reason| { /* close it */ },
123///         || {
124///             Content();
125///         },
126///     );
127/// }
128/// ```
129#[composable]
130pub fn Dialog<C>(spec: DialogSpec, on_dismiss: impl Fn(DismissReason) + 'static, content: C)
131where
132    C: Fn() + 'static,
133{
134    DialogWithScrim(spec, DEFAULT_SCRIM, on_dismiss, content);
135}
136
137/// A modal dialog whose scrim colour is chosen by the caller.
138#[composable]
139pub fn DialogWithScrim<C>(
140    spec: DialogSpec,
141    scrim: Color,
142    on_dismiss: impl Fn(DismissReason) + 'static,
143    content: C,
144) where
145    C: Fn() + 'static,
146{
147    let own_modal_depth =
148        cranpose_core::remember(|| crate::modal::current_modal_depth() + 1).with(|depth| *depth);
149
150    let viewport = local_popup_viewport().current().get();
151    let insets = if spec.apply_window_insets {
152        window_insets().combined()
153    } else {
154        cranpose_ui_graphics::EdgeInsets::default()
155    };
156    let bounds = dialog_bounds(viewport, insets);
157
158    let on_dismiss = Rc::new(on_dismiss);
159    let content = Rc::new(content);
160
161    let dismiss_on_outside_tap = spec.dismiss_on_outside_tap;
162    let scrim_dismiss = {
163        let on_dismiss = Rc::clone(&on_dismiss);
164        move || {
165            if dismiss_on_outside_tap {
166                on_dismiss(DismissReason::OutsideTap);
167            }
168        }
169    };
170
171    let dismiss_on_back = spec.dismiss_on_back;
172    let back = {
173        let on_dismiss = Rc::clone(&on_dismiss);
174        cranpose_core::rememberUpdatedState::<Rc<dyn Fn()>>(Rc::new(move || {
175            if dismiss_on_back {
176                on_dismiss(DismissReason::BackRequested);
177            }
178        }))
179    };
180    cranpose_core::DisposableEffect((), move |scope| {
181        let registration = crate::modal::register_modal(Rc::new(move || (back.value())()));
182        scope.on_dispose(move || drop(registration))
183    });
184
185    PopupDismissable(bounds, Point { x: 0.0, y: 0.0 }, scrim_dismiss, move || {
186        let content = Rc::clone(&content);
187        Box(
188            Modifier::empty()
189                .size(Size {
190                    width: bounds.width,
191                    height: bounds.height,
192                })
193                .background(scrim)
194                .semantics(move |config| {
195                    config.role = Some(SemanticsWidgetRole::Dialog);
196                    config.is_modal = true;
197                }),
198            BoxSpec::default().content_alignment(Alignment::CENTER),
199            move || {
200                let content = Rc::clone(&content);
201                cranpose_core::CompositionLocalProvider(
202                    [crate::modal::local_modal_depth().provides(own_modal_depth)],
203                    move || content(),
204                );
205            },
206        );
207    });
208}
209
210#[cfg(test)]
211mod tests {
212    use super::*;
213
214    #[test]
215    fn a_dialog_fills_the_window_inside_its_insets() {
216        let viewport = Size {
217            width: 400.0,
218            height: 800.0,
219        };
220        let insets = cranpose_ui_graphics::EdgeInsets::from_components(8.0, 24.0, 8.0, 48.0);
221        let bounds = dialog_bounds(viewport, insets);
222        assert_eq!(bounds.x, 8.0);
223        assert_eq!(bounds.y, 24.0);
224        assert_eq!(bounds.width, 384.0);
225        assert_eq!(bounds.height, 728.0);
226    }
227
228    #[test]
229    fn insets_larger_than_the_window_collapse_rather_than_going_negative() {
230        let viewport = Size {
231            width: 100.0,
232            height: 100.0,
233        };
234        let insets = cranpose_ui_graphics::EdgeInsets::from_components(80.0, 80.0, 80.0, 80.0);
235        let bounds = dialog_bounds(viewport, insets);
236        assert_eq!(bounds.width, 0.0);
237        assert_eq!(bounds.height, 0.0);
238    }
239
240    #[test]
241    fn a_required_dialog_refuses_both_dismissals_but_still_covers_the_screen() {
242        let spec = DialogSpec::required();
243        assert!(!spec.dismiss_on_outside_tap);
244        assert!(!spec.dismiss_on_back);
245        assert!(spec.apply_window_insets);
246    }
247
248    #[test]
249    fn the_default_dialog_dismisses_both_ways_until_told_otherwise() {
250        let spec = DialogSpec::default();
251        assert!(spec.dismiss_on_outside_tap);
252        assert!(spec.dismiss_on_back);
253        assert!(!spec.with_dismiss_on_back(false).dismiss_on_back);
254        assert!(
255            !spec
256                .with_dismiss_on_outside_tap(false)
257                .dismiss_on_outside_tap
258        );
259        assert!(!spec.with_window_insets(false).apply_window_insets);
260    }
261
262    #[test]
263    fn a_dialog_traps_focus_inside_it_and_releases_it_on_close() {
264        use std::cell::{Cell, RefCell};
265
266        use cranpose_core::{
267            Composition, MemoryApplier, MutableState, NodeId, location_key, mutableStateOf,
268            remember,
269        };
270        use cranpose_foundation::{PointerEvent, PointerEventKind, text::TextFieldState};
271        use cranpose_ui_graphics::Size;
272
273        use crate::{
274            layout::{LayoutBox, LayoutEngine, LayoutTree},
275            text::TextStyle,
276            text_field_focus::{focused_editor_state, has_focused_field},
277            widgets::{basic_text_field::BasicTextField, popup::PopupHost},
278        };
279
280        let _app_context = crate::render_state::app_context_test_scope();
281        crate::modal::clear_modals();
282
283        let mut composition = Composition::new(MemoryApplier::new());
284
285        let outside_state = TextFieldState::new("outside");
286        let inside_state = TextFieldState::new("inside");
287        let outside_id: Rc<Cell<Option<NodeId>>> = Rc::new(Cell::new(None));
288        let inside_id: Rc<Cell<Option<NodeId>>> = Rc::new(Cell::new(None));
289        let dialog_open_slot: Rc<RefCell<Option<MutableState<bool>>>> = Rc::new(RefCell::new(None));
290
291        let mut content = {
292            let outside_id = Rc::clone(&outside_id);
293            let inside_id = Rc::clone(&inside_id);
294            let dialog_open_slot = Rc::clone(&dialog_open_slot);
295            move || {
296                let outside_id = Rc::clone(&outside_id);
297                let inside_id = Rc::clone(&inside_id);
298                let dialog_open_slot = Rc::clone(&dialog_open_slot);
299                PopupHost(move || {
300                    let dialog_open = remember(|| mutableStateOf(true)).with(|state| *state);
301                    *dialog_open_slot.borrow_mut() = Some(dialog_open);
302
303                    outside_id.set(Some(BasicTextField(
304                        outside_state,
305                        Modifier::empty(),
306                        TextStyle::default(),
307                    )));
308
309                    if dialog_open.value() {
310                        let inside_id = Rc::clone(&inside_id);
311                        Dialog(
312                            DialogSpec::default(),
313                            |_reason: DismissReason| {},
314                            move || {
315                                inside_id.set(Some(BasicTextField(
316                                    inside_state,
317                                    Modifier::empty(),
318                                    TextStyle::default(),
319                                )));
320                            },
321                        );
322                    }
323                });
324            }
325        };
326
327        let key = location_key(file!(), line!(), column!());
328        composition.render(key, &mut content).expect("render");
329
330        let mut settle = move |composition: &mut Composition<MemoryApplier>| -> LayoutTree {
331            for _ in 0..16 {
332                if !composition.should_render() {
333                    break;
334                }
335                composition.reconcile(key, &mut content).expect("reconcile");
336            }
337            let root = composition.root().expect("root");
338            let handle = composition.runtime_handle();
339            let mut applier = composition.applier_mut();
340            applier.set_runtime_handle(handle);
341            let layout = applier
342                .compute_layout(root, Size::new(400.0, 800.0))
343                .expect("layout");
344            applier.clear_runtime_handle();
345            drop(applier);
346            layout
347        };
348
349        fn find_node(node: &LayoutBox, id: NodeId) -> Option<&LayoutBox> {
350            if node.node_id == id {
351                return Some(node);
352            }
353            node.children.iter().find_map(|child| find_node(child, id))
354        }
355
356        fn tap(layout_root: &LayoutBox, id: &Rc<Cell<Option<NodeId>>>) {
357            let id = id.get().expect("field composed");
358            let node = find_node(layout_root, id).expect("field placed in the layout");
359            let handler = node
360                .node_data
361                .modifier_slices()
362                .pointer_inputs()
363                .first()
364                .cloned()
365                .expect("field has a pointer handler");
366            let position = cranpose_ui_graphics::Point { x: 1.0, y: 1.0 };
367            handler(PointerEvent::new(
368                PointerEventKind::Down,
369                position,
370                position,
371            ));
372        }
373
374        let mut layout = settle(&mut composition);
375        for _ in 0..7 {
376            layout = settle(&mut composition);
377        }
378
379        tap(layout.root(), &inside_id);
380        assert!(has_focused_field(), "the dialog's own field must focus");
381        assert_eq!(
382            focused_editor_state().map(|s| s.text),
383            Some("inside".to_string()),
384            "the dialog's own field must be the one focused"
385        );
386
387        tap(layout.root(), &outside_id);
388        assert_eq!(
389            focused_editor_state().map(|s| s.text),
390            Some("inside".to_string()),
391            "a field behind an open dialog must not take focus from it"
392        );
393
394        let dialog_open = dialog_open_slot
395            .borrow()
396            .as_ref()
397            .copied()
398            .expect("dialog_open captured");
399        dialog_open.set(false);
400        layout = settle(&mut composition);
401        assert!(
402            !has_focused_field(),
403            "closing the dialog must release focus from the field it held"
404        );
405
406        tap(layout.root(), &outside_id);
407        assert_eq!(
408            focused_editor_state().map(|s| s.text),
409            Some("outside".to_string()),
410            "once the dialog is closed, the field behind it must be focusable"
411        );
412
413        crate::modal::clear_modals();
414        crate::text_field_focus::clear_focus();
415    }
416}