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                .focus_target()
195                .semantics(move |config| {
196                    config.role = Some(SemanticsWidgetRole::Dialog);
197                    config.is_modal = true;
198                }),
199            BoxSpec::default().content_alignment(Alignment::CENTER),
200            move || {
201                let content = Rc::clone(&content);
202                cranpose_core::CompositionLocalProvider(
203                    [crate::modal::local_modal_depth().provides(own_modal_depth)],
204                    move || content(),
205                );
206            },
207        );
208    });
209}
210
211#[cfg(test)]
212mod tests {
213    use super::*;
214
215    #[test]
216    fn a_dialog_fills_the_window_inside_its_insets() {
217        let viewport = Size {
218            width: 400.0,
219            height: 800.0,
220        };
221        let insets = cranpose_ui_graphics::EdgeInsets::from_components(8.0, 24.0, 8.0, 48.0);
222        let bounds = dialog_bounds(viewport, insets);
223        assert_eq!(bounds.x, 8.0);
224        assert_eq!(bounds.y, 24.0);
225        assert_eq!(bounds.width, 384.0);
226        assert_eq!(bounds.height, 728.0);
227    }
228
229    #[test]
230    fn insets_larger_than_the_window_collapse_rather_than_going_negative() {
231        let viewport = Size {
232            width: 100.0,
233            height: 100.0,
234        };
235        let insets = cranpose_ui_graphics::EdgeInsets::from_components(80.0, 80.0, 80.0, 80.0);
236        let bounds = dialog_bounds(viewport, insets);
237        assert_eq!(bounds.width, 0.0);
238        assert_eq!(bounds.height, 0.0);
239    }
240
241    #[test]
242    fn a_required_dialog_refuses_both_dismissals_but_still_covers_the_screen() {
243        let spec = DialogSpec::required();
244        assert!(!spec.dismiss_on_outside_tap);
245        assert!(!spec.dismiss_on_back);
246        assert!(spec.apply_window_insets);
247    }
248
249    #[test]
250    fn the_default_dialog_dismisses_both_ways_until_told_otherwise() {
251        let spec = DialogSpec::default();
252        assert!(spec.dismiss_on_outside_tap);
253        assert!(spec.dismiss_on_back);
254        assert!(!spec.with_dismiss_on_back(false).dismiss_on_back);
255        assert!(
256            !spec
257                .with_dismiss_on_outside_tap(false)
258                .dismiss_on_outside_tap
259        );
260        assert!(!spec.with_window_insets(false).apply_window_insets);
261    }
262
263    #[test]
264    fn a_dialog_traps_focus_inside_it_and_releases_it_on_close() {
265        use std::cell::{Cell, RefCell};
266
267        use cranpose_core::{
268            Composition, MemoryApplier, MutableState, NodeId, location_key, mutableStateOf,
269            remember,
270        };
271        use cranpose_foundation::{PointerEvent, PointerEventKind, text::TextFieldState};
272        use cranpose_ui_graphics::Size;
273
274        use crate::{
275            layout::{LayoutBox, LayoutEngine, LayoutTree},
276            text::TextStyle,
277            text_field_focus::{focused_editor_state, has_focused_field},
278            widgets::{basic_text_field::BasicTextField, popup::PopupHost},
279        };
280
281        let _app_context = crate::render_state::app_context_test_scope();
282        crate::modal::clear_modals();
283
284        let mut composition = Composition::new(MemoryApplier::new());
285
286        let outside_state = TextFieldState::new("outside");
287        let inside_state = TextFieldState::new("inside");
288        let outside_id: Rc<Cell<Option<NodeId>>> = Rc::new(Cell::new(None));
289        let inside_id: Rc<Cell<Option<NodeId>>> = Rc::new(Cell::new(None));
290        let dialog_open_slot: Rc<RefCell<Option<MutableState<bool>>>> = Rc::new(RefCell::new(None));
291
292        let mut content = {
293            let outside_id = Rc::clone(&outside_id);
294            let inside_id = Rc::clone(&inside_id);
295            let dialog_open_slot = Rc::clone(&dialog_open_slot);
296            move || {
297                let outside_id = Rc::clone(&outside_id);
298                let inside_id = Rc::clone(&inside_id);
299                let dialog_open_slot = Rc::clone(&dialog_open_slot);
300                PopupHost(move || {
301                    let dialog_open = remember(|| mutableStateOf(true)).with(|state| *state);
302                    *dialog_open_slot.borrow_mut() = Some(dialog_open);
303
304                    outside_id.set(Some(BasicTextField(
305                        outside_state,
306                        Modifier::empty(),
307                        TextStyle::default(),
308                    )));
309
310                    if dialog_open.value() {
311                        let inside_id = Rc::clone(&inside_id);
312                        Dialog(
313                            DialogSpec::default(),
314                            |_reason: DismissReason| {},
315                            move || {
316                                inside_id.set(Some(BasicTextField(
317                                    inside_state,
318                                    Modifier::empty(),
319                                    TextStyle::default(),
320                                )));
321                            },
322                        );
323                    }
324                });
325            }
326        };
327
328        let key = location_key(file!(), line!(), column!());
329        composition.render(key, &mut content).expect("render");
330
331        let mut settle = move |composition: &mut Composition<MemoryApplier>| -> LayoutTree {
332            for _ in 0..16 {
333                if !composition.should_render() {
334                    break;
335                }
336                composition.reconcile(key, &mut content).expect("reconcile");
337            }
338            let root = composition.root().expect("root");
339            let handle = composition.runtime_handle();
340            let mut applier = composition.applier_mut();
341            applier.set_runtime_handle(handle);
342            let layout = applier
343                .compute_layout(root, Size::new(400.0, 800.0))
344                .expect("layout");
345            applier.clear_runtime_handle();
346            drop(applier);
347            layout
348        };
349
350        fn find_node(node: &LayoutBox, id: NodeId) -> Option<&LayoutBox> {
351            if node.node_id == id {
352                return Some(node);
353            }
354            node.children.iter().find_map(|child| find_node(child, id))
355        }
356
357        fn tap(layout_root: &LayoutBox, id: &Rc<Cell<Option<NodeId>>>) {
358            let id = id.get().expect("field composed");
359            let node = find_node(layout_root, id).expect("field placed in the layout");
360            let handler = node
361                .node_data
362                .modifier_slices()
363                .pointer_inputs()
364                .first()
365                .cloned()
366                .expect("field has a pointer handler");
367            let position = cranpose_ui_graphics::Point { x: 1.0, y: 1.0 };
368            handler(PointerEvent::new(
369                PointerEventKind::Down,
370                position,
371                position,
372            ));
373        }
374
375        let mut layout = settle(&mut composition);
376        for _ in 0..7 {
377            layout = settle(&mut composition);
378        }
379
380        tap(layout.root(), &inside_id);
381        assert!(has_focused_field(), "the dialog's own field must focus");
382        assert_eq!(
383            focused_editor_state().map(|s| s.text),
384            Some("inside".to_string()),
385            "the dialog's own field must be the one focused"
386        );
387
388        tap(layout.root(), &outside_id);
389        assert_eq!(
390            focused_editor_state().map(|s| s.text),
391            Some("inside".to_string()),
392            "a field behind an open dialog must not take focus from it"
393        );
394
395        let dialog_open = dialog_open_slot
396            .borrow()
397            .as_ref()
398            .copied()
399            .expect("dialog_open captured");
400        dialog_open.set(false);
401        layout = settle(&mut composition);
402        assert!(
403            !has_focused_field(),
404            "closing the dialog must release focus from the field it held"
405        );
406
407        tap(layout.root(), &outside_id);
408        assert_eq!(
409            focused_editor_state().map(|s| s.text),
410            Some("outside".to_string()),
411            "once the dialog is closed, the field behind it must be focusable"
412        );
413
414        crate::modal::clear_modals();
415        crate::text_field_focus::clear_focus();
416    }
417}