Skip to main content

waft_widgets/widgets/
modal_barrier.rs

1//! Flutter counterpart: `widgets/modal_barrier.dart`.
2
3use std::any::TypeId;
4use std::fmt::{self, Debug};
5use std::rc::Rc;
6
7use waft_animation::AnimationRef;
8use waft_embedder::{Color, TargetPlatform};
9use waft_foundation::{App, Handle, Listenable, Listener, ValueNotifier};
10use waft_gestures::{
11    BaseTapData, BaseTapGestureRecognizer, BaseTapLeaf, BaseTapLeafData, GestureDisposition,
12    GestureRecognizer, GestureRecognizerData, K_PRESS_TIMEOUT, OneSequenceData,
13    OneSequenceLeafData, PointerCancelEvent, PointerDownEvent, PointerEvent, PointerUpEvent,
14    PrimaryPointerData, PrimaryPointerGestureRecognizer, PrimaryPointerLeaf,
15    PrimaryPointerLeafData, RecognizerLeaf, RecognizerLeafData, UNSET_TOUCH_SLOP,
16};
17use waft_painting::{EdgeInsets, Matrix4};
18use waft_rendering::{BoxConstraints, HitTestBehavior};
19use waft_services::SystemMouseCursors;
20
21use crate::framework::{BuildContext, IntoWidget, KeyRef, StatelessWidget, WidgetRef};
22use crate::widgets::basic::{
23    BlockSemantics, ColoredBox, ConstrainedBox, Directionality, ExcludeSemantics, MouseRegion,
24    Semantics,
25};
26use crate::widgets::debug::debug_check_has_directionality;
27use crate::widgets::gesture_detector::{
28    GestureRecognizerFactories, GestureRecognizerFactory, RawGestureDetector,
29};
30use crate::widgets::navigator::Navigator;
31use crate::widgets::transitions::AnimatedWidget;
32use waft_foundation::Ref;
33
34/// A widget that prevents the user from interacting with widgets behind itself.
35///
36/// The modal barrier is the scrim that is rendered behind each route, which generally prevents
37/// the user from interacting with the route below the current route, and normally partially
38/// obscures such routes.
39///
40/// For example, when a dialog is on the screen, the page below the dialog is usually darkened
41/// by the modal barrier.
42///
43/// See also:
44///
45///  * [`ModalRoute`](crate::ModalRoute), which indirectly uses this widget.
46///  * [`AnimatedModalBarrier`], which is similar but takes an animated
47///    [`color`](Self::color) instead of a single color value.
48pub struct ModalBarrier {
49    pub key: Option<KeyRef>,
50    /// If non-`None`, fill the barrier with this color.
51    pub color: Option<Color>,
52    /// Specifies if the barrier will be dismissed when the user taps on it.
53    ///
54    /// If true, and [`on_dismiss`](Self::on_dismiss) is non-`None`,
55    /// [`on_dismiss`](Self::on_dismiss) will be called, otherwise the current route will be
56    /// popped from the ambient [`Navigator`].
57    ///
58    /// If false, tapping on the barrier has no effect.
59    pub dismissible: bool,
60    /// Called when the barrier is being dismissed.
61    ///
62    /// If non-`None`, [`on_dismiss`](Self::on_dismiss) will be called in place of popping the
63    /// current route. It is up to the callback to handle dismissing the barrier.
64    ///
65    /// If `None`, the ambient [`Navigator`]'s current route will be popped.
66    ///
67    /// This field is ignored if [`dismissible`](Self::dismissible) is false.
68    pub on_dismiss: Option<Listener>,
69    /// Whether the modal barrier semantics are included in the semantics tree.
70    pub barrier_semantics_dismissible: Option<bool>,
71    /// Semantics label used for the barrier if it is [`dismissible`](Self::dismissible).
72    ///
73    /// The semantics label is read out by accessibility tools when the barrier is focused.
74    pub semantics_label: Option<String>,
75    /// Contains a value of type [`EdgeInsets`] that specifies how the semantics node rectangle
76    /// of the widget should be clipped.
77    pub clip_details_notifier: Option<Ref<ValueNotifier<EdgeInsets>>>,
78    /// This hint text instructs users what they are able to do when they tap on the
79    /// [`ModalBarrier`].
80    pub semantics_on_tap_hint: Option<String>,
81}
82
83impl ModalBarrier {
84    /// Creates a widget that blocks user interaction; Dart's optional arguments are the
85    /// setters.
86    ///
87    /// Dart's defaults: `dismissible` true, `barrier_semantics_dismissible` true.
88    pub fn new() -> ModalBarrier {
89        ModalBarrier {
90            key: None,
91            color: None,
92            dismissible: true,
93            on_dismiss: None,
94            barrier_semantics_dismissible: Some(true),
95            semantics_label: None,
96            clip_details_notifier: None,
97            semantics_on_tap_hint: None,
98        }
99    }
100
101    /// Dart `ModalBarrier(key:)`.
102    pub fn key(mut self, key: KeyRef) -> ModalBarrier {
103        self.key = Some(key);
104        self
105    }
106
107    /// Dart `ModalBarrier(color:)`.
108    pub fn color(mut self, color: Color) -> ModalBarrier {
109        self.color = Some(color);
110        self
111    }
112
113    /// Dart `ModalBarrier(dismissible:)`.
114    pub fn dismissible(mut self, dismissible: bool) -> ModalBarrier {
115        self.dismissible = dismissible;
116        self
117    }
118
119    /// Dart `ModalBarrier(onDismiss:)`.
120    pub fn on_dismiss(mut self, on_dismiss: Listener) -> ModalBarrier {
121        self.on_dismiss = Some(on_dismiss);
122        self
123    }
124
125    /// Dart `ModalBarrier(barrierSemanticsDismissible:)`.
126    pub fn barrier_semantics_dismissible(
127        mut self,
128        barrier_semantics_dismissible: bool,
129    ) -> ModalBarrier {
130        self.barrier_semantics_dismissible = Some(barrier_semantics_dismissible);
131        self
132    }
133
134    /// [`barrier_semantics_dismissible`](Self::barrier_semantics_dismissible), for a caller
135    /// that already holds the `Option` Dart's named argument carries.
136    pub fn maybe_barrier_semantics_dismissible(
137        mut self,
138        barrier_semantics_dismissible: Option<bool>,
139    ) -> ModalBarrier {
140        self.barrier_semantics_dismissible = barrier_semantics_dismissible;
141        self
142    }
143
144    /// Dart `ModalBarrier(semanticsLabel:)`.
145    pub fn semantics_label(mut self, semantics_label: String) -> ModalBarrier {
146        self.semantics_label = Some(semantics_label);
147        self
148    }
149
150    /// [`semantics_label`](Self::semantics_label), for a caller that already holds the
151    /// `Option` Dart's named argument carries.
152    pub fn maybe_semantics_label(mut self, semantics_label: Option<String>) -> ModalBarrier {
153        self.semantics_label = semantics_label;
154        self
155    }
156
157    /// Dart `ModalBarrier(clipDetailsNotifier:)`.
158    pub fn clip_details_notifier(
159        mut self,
160        clip_details_notifier: Ref<ValueNotifier<EdgeInsets>>,
161    ) -> ModalBarrier {
162        self.clip_details_notifier = Some(clip_details_notifier);
163        self
164    }
165
166    /// Dart `ModalBarrier(semanticsOnTapHint:)`.
167    pub fn semantics_on_tap_hint(mut self, semantics_on_tap_hint: String) -> ModalBarrier {
168        self.semantics_on_tap_hint = Some(semantics_on_tap_hint);
169        self
170    }
171}
172
173impl Default for ModalBarrier {
174    fn default() -> ModalBarrier {
175        ModalBarrier::new()
176    }
177}
178
179impl Debug for ModalBarrier {
180    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
181        f.debug_struct("ModalBarrier")
182            .field("color", &self.color)
183            .field("dismissible", &self.dismissible)
184            .finish_non_exhaustive()
185    }
186}
187
188impl StatelessWidget for ModalBarrier {
189    fn key(&self) -> Option<&KeyRef> {
190        self.key.as_ref()
191    }
192
193    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
194        debug_assert!(
195            !self.dismissible
196                || self.semantics_label.is_none()
197                || debug_check_has_directionality(app, context, None, None, None)
198        );
199        let platform_supports_dismissing_barrier = match app.platform().target_platform() {
200            TargetPlatform::Fuchsia | TargetPlatform::Linux | TargetPlatform::Windows => false,
201            TargetPlatform::Android | TargetPlatform::IOS | TargetPlatform::MacOS => true,
202        };
203        let semantics_dismissible = self.dismissible && platform_supports_dismissing_barrier;
204        let modal_barrier_semantics_dismissible = self
205            .barrier_semantics_dismissible
206            .unwrap_or(semantics_dismissible);
207
208        let dismissible = self.dismissible;
209        let on_dismiss = self.on_dismiss.clone();
210        let handle_dismiss = Listener::new(move |app: &mut App| {
211            if !dismissible {
212                return;
213            }
214            match on_dismiss.clone() {
215                Some(on_dismiss) => on_dismiss.call(app),
216                None => {
217                    Navigator::maybe_pop(app, context, None);
218                }
219            }
220        });
221
222        let mut constrained = ConstrainedBox::new(BoxConstraints::expand(None, None));
223        if let Some(color) = self.color {
224            constrained = constrained.child(ColoredBox::new(color));
225        }
226        let mut semantics = Semantics::new();
227        if let Some(semantics_on_tap_hint) = &self.semantics_on_tap_hint {
228            semantics = semantics.on_tap_hint(semantics_on_tap_hint.clone());
229        }
230        if semantics_dismissible && self.semantics_label.is_some() {
231            let on_tap = handle_dismiss.clone();
232            let on_dismiss = handle_dismiss.clone();
233            semantics = semantics
234                .on_tap(Rc::new(move |app: &mut App| on_tap.call(app)))
235                .on_dismiss(Rc::new(move |app: &mut App| on_dismiss.call(app)));
236        }
237        if semantics_dismissible && let Some(semantics_label) = &self.semantics_label {
238            semantics = semantics.label(semantics_label.clone());
239        }
240        if semantics_dismissible && self.semantics_label.is_some() {
241            semantics = semantics.text_direction(Directionality::of(app, context));
242        }
243        let barrier = semantics.child(
244            MouseRegion::new()
245                .cursor(SystemMouseCursors::BASIC.into())
246                .child(constrained),
247        );
248
249        // Developers can set [dismissible: true] and [barrierSemanticsDismissible: true]
250        // to allow assistive technology users to dismiss a modal BottomSheet by
251        // tapping on the Scrim focus.
252        // On iOS, some modal barriers are not dismissible in accessibility mode.
253        let excluding = !semantics_dismissible || !modal_barrier_semantics_dismissible;
254
255        // Dart wraps the barrier in `_SemanticsClipper` here when `!excluding` and a
256        // `clipDetailsNotifier` is given; it only clips the barrier's semantics bounds, which
257        // wait with the semantics tree.
258
259        BlockSemantics::new()
260            .child(ExcludeSemantics::new().excluding(excluding).child(
261                ModalBarrierGestureDetector {
262                    child: barrier.into_widget(),
263                    on_dismiss: handle_dismiss,
264                },
265            ))
266            .into_widget()
267    }
268}
269
270/// A widget that prevents the user from interacting with widgets behind itself, and can be
271/// configured with an animated color value.
272///
273/// This widget is similar to [`ModalBarrier`] except that it takes an animated
274/// [`color`](Self::color) instead of a single color.
275///
276/// See also:
277///
278///  * [`ModalRoute`](crate::ModalRoute), which uses this widget.
279pub struct AnimatedModalBarrier {
280    pub key: Option<KeyRef>,
281    /// If non-`None`, fill the barrier with this color.
282    pub color: AnimationRef<Option<Color>>,
283    /// Whether touching the barrier will pop the current route off the [`Navigator`].
284    pub dismissible: bool,
285    /// Semantics label used for the barrier if it is [`dismissible`](Self::dismissible).
286    pub semantics_label: Option<String>,
287    /// Whether the modal barrier semantics are included in the semantics tree.
288    pub barrier_semantics_dismissible: Option<bool>,
289    /// Called when the barrier is being dismissed.
290    pub on_dismiss: Option<Listener>,
291    /// See [`ModalBarrier::clip_details_notifier`].
292    pub clip_details_notifier: Option<Ref<ValueNotifier<EdgeInsets>>>,
293    /// See [`ModalBarrier::semantics_on_tap_hint`].
294    pub semantics_on_tap_hint: Option<String>,
295}
296
297impl AnimatedModalBarrier {
298    /// Creates a widget that blocks user interaction; Dart's optional arguments are the
299    /// setters.
300    ///
301    /// Dart's default: `dismissible` true.
302    pub fn new(color: AnimationRef<Option<Color>>) -> AnimatedModalBarrier {
303        AnimatedModalBarrier {
304            key: None,
305            color,
306            dismissible: true,
307            semantics_label: None,
308            barrier_semantics_dismissible: None,
309            on_dismiss: None,
310            clip_details_notifier: None,
311            semantics_on_tap_hint: None,
312        }
313    }
314
315    /// Dart `AnimatedModalBarrier(key:)`.
316    pub fn key(mut self, key: KeyRef) -> AnimatedModalBarrier {
317        self.key = Some(key);
318        self
319    }
320
321    /// Dart `AnimatedModalBarrier(dismissible:)`.
322    pub fn dismissible(mut self, dismissible: bool) -> AnimatedModalBarrier {
323        self.dismissible = dismissible;
324        self
325    }
326
327    /// Dart `AnimatedModalBarrier(semanticsLabel:)`.
328    pub fn semantics_label(mut self, semantics_label: String) -> AnimatedModalBarrier {
329        self.semantics_label = Some(semantics_label);
330        self
331    }
332
333    /// [`semantics_label`](Self::semantics_label), for a caller that already holds the
334    /// `Option` Dart's named argument carries.
335    pub fn maybe_semantics_label(
336        mut self,
337        semantics_label: Option<String>,
338    ) -> AnimatedModalBarrier {
339        self.semantics_label = semantics_label;
340        self
341    }
342
343    /// Dart `AnimatedModalBarrier(barrierSemanticsDismissible:)`.
344    pub fn barrier_semantics_dismissible(
345        mut self,
346        barrier_semantics_dismissible: bool,
347    ) -> AnimatedModalBarrier {
348        self.barrier_semantics_dismissible = Some(barrier_semantics_dismissible);
349        self
350    }
351
352    /// Dart `AnimatedModalBarrier(onDismiss:)`.
353    pub fn on_dismiss(mut self, on_dismiss: Listener) -> AnimatedModalBarrier {
354        self.on_dismiss = Some(on_dismiss);
355        self
356    }
357
358    /// Dart `AnimatedModalBarrier(clipDetailsNotifier:)`.
359    pub fn clip_details_notifier(
360        mut self,
361        clip_details_notifier: Ref<ValueNotifier<EdgeInsets>>,
362    ) -> AnimatedModalBarrier {
363        self.clip_details_notifier = Some(clip_details_notifier);
364        self
365    }
366
367    /// Dart `AnimatedModalBarrier(semanticsOnTapHint:)`.
368    pub fn semantics_on_tap_hint(mut self, semantics_on_tap_hint: String) -> AnimatedModalBarrier {
369        self.semantics_on_tap_hint = Some(semantics_on_tap_hint);
370        self
371    }
372}
373
374impl Debug for AnimatedModalBarrier {
375    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
376        f.debug_struct("AnimatedModalBarrier")
377            .field("dismissible", &self.dismissible)
378            .finish_non_exhaustive()
379    }
380}
381
382impl AnimatedWidget for AnimatedModalBarrier {
383    fn key(&self) -> Option<&KeyRef> {
384        self.key.as_ref()
385    }
386
387    fn listenable(&self) -> Rc<dyn Listenable> {
388        Rc::new(self.color.clone())
389    }
390
391    fn build(&self, app: &mut App, _context: BuildContext) -> WidgetRef {
392        let mut barrier = ModalBarrier::new()
393            .dismissible(self.dismissible)
394            .maybe_semantics_label(self.semantics_label.clone())
395            .maybe_barrier_semantics_dismissible(self.barrier_semantics_dismissible);
396        if let Some(color) = self.color.value(app) {
397            barrier = barrier.color(color);
398        }
399        if let Some(on_dismiss) = self.on_dismiss.clone() {
400            barrier = barrier.on_dismiss(on_dismiss);
401        }
402        if let Some(clip_details_notifier) = self.clip_details_notifier.clone() {
403            barrier = barrier.clip_details_notifier(clip_details_notifier);
404        }
405        if let Some(semantics_on_tap_hint) = self.semantics_on_tap_hint.clone() {
406            barrier = barrier.semantics_on_tap_hint(semantics_on_tap_hint);
407        }
408        barrier.into_widget()
409    }
410}
411
412/// Recognizes a tap down by any pointer button.
413///
414/// It is similar to `TapGestureRecognizer::on_tap_down`, but accepts any single button, which
415/// means the gesture also takes part in gesture arenas.
416struct AnyTapGestureRecognizer {
417    recognizer: GestureRecognizerData,
418    one_sequence: OneSequenceData,
419    primary: PrimaryPointerData,
420    base_tap: BaseTapData,
421    on_any_tap_up: Option<Listener>,
422}
423
424impl AnyTapGestureRecognizer {
425    fn new(app: &mut App) -> Ref<AnyTapGestureRecognizer> {
426        app.create(AnyTapGestureRecognizer {
427            recognizer: GestureRecognizerData::new(),
428            one_sequence: OneSequenceData::new(),
429            primary: PrimaryPointerData::new(
430                Some(K_PRESS_TIMEOUT),
431                Some(UNSET_TOUCH_SLOP),
432                Some(UNSET_TOUCH_SLOP),
433            ),
434            base_tap: BaseTapData::new(),
435            on_any_tap_up: None,
436        })
437    }
438}
439
440impl RecognizerLeafData for AnyTapGestureRecognizer {
441    fn recognizer(&self) -> &GestureRecognizerData {
442        &self.recognizer
443    }
444
445    fn recognizer_mut(&mut self) -> &mut GestureRecognizerData {
446        &mut self.recognizer
447    }
448}
449
450impl OneSequenceLeafData for AnyTapGestureRecognizer {
451    fn one_sequence(&self) -> &OneSequenceData {
452        &self.one_sequence
453    }
454
455    fn one_sequence_mut(&mut self) -> &mut OneSequenceData {
456        &mut self.one_sequence
457    }
458}
459
460impl PrimaryPointerLeafData for AnyTapGestureRecognizer {
461    fn primary(&self) -> &PrimaryPointerData {
462        &self.primary
463    }
464
465    fn primary_mut(&mut self) -> &mut PrimaryPointerData {
466        &mut self.primary
467    }
468}
469
470impl BaseTapLeafData for AnyTapGestureRecognizer {
471    fn base_tap(&self) -> &BaseTapData {
472        &self.base_tap
473    }
474
475    fn base_tap_mut(&mut self) -> &mut BaseTapData {
476        &mut self.base_tap
477    }
478}
479
480impl RecognizerLeaf for AnyTapGestureRecognizer {
481    fn add_allowed_pointer(self: Handle<Self>, app: &mut App, event: PointerDownEvent) {
482        BaseTapGestureRecognizer::add_allowed_pointer(self, app, event);
483    }
484
485    fn handle_non_allowed_pointer(self: Handle<Self>, app: &mut App, event: &PointerDownEvent) {
486        PrimaryPointerGestureRecognizer::handle_non_allowed_pointer(self, app, event);
487    }
488
489    fn start_tracking_pointer(
490        self: Handle<Self>,
491        app: &mut App,
492        pointer: i64,
493        transform: Option<Matrix4>,
494    ) {
495        BaseTapGestureRecognizer::start_tracking_pointer(self, app, pointer, transform);
496    }
497
498    fn handle_event(self: Handle<Self>, app: &mut App, event: PointerEvent) {
499        PrimaryPointerGestureRecognizer::handle_event(self, app, event);
500    }
501
502    fn is_pointer_allowed(self: Handle<Self>, app: &App, event: &PointerDownEvent) -> bool {
503        if app.get(self).on_any_tap_up.is_none() {
504            return false;
505        }
506        GestureRecognizer::is_pointer_allowed(self, app, event)
507    }
508
509    fn accept_gesture(self: Handle<Self>, app: &mut App, pointer: i64) {
510        BaseTapGestureRecognizer::accept_gesture(self, app, pointer);
511    }
512
513    fn reject_gesture(self: Handle<Self>, app: &mut App, pointer: i64) {
514        BaseTapGestureRecognizer::reject_gesture(self, app, pointer);
515    }
516
517    fn did_stop_tracking_last_pointer(self: Handle<Self>, app: &mut App, pointer: i64) {
518        PrimaryPointerGestureRecognizer::did_stop_tracking_last_pointer(self, app, pointer);
519    }
520
521    fn resolve(self: Handle<Self>, app: &mut App, disposition: GestureDisposition) {
522        BaseTapGestureRecognizer::resolve(self, app, disposition);
523    }
524
525    fn dispose(self: Handle<Self>, app: &mut App) {
526        PrimaryPointerGestureRecognizer::dispose(self, app);
527    }
528
529    fn debug_description(self: Handle<Self>) -> &'static str {
530        "any tap"
531    }
532}
533
534impl PrimaryPointerLeaf for AnyTapGestureRecognizer {
535    fn handle_primary_pointer(self: Handle<Self>, app: &mut App, event: PointerEvent) {
536        BaseTapGestureRecognizer::handle_primary_pointer(self, app, event);
537    }
538
539    fn did_exceed_deadline(self: Handle<Self>, app: &mut App) {
540        BaseTapGestureRecognizer::did_exceed_deadline(self, app);
541    }
542}
543
544impl BaseTapLeaf for AnyTapGestureRecognizer {
545    fn handle_tap_down(self: Handle<Self>, _app: &mut App, _down: &PointerDownEvent) {
546        // Do nothing.
547    }
548
549    fn handle_tap_up(
550        self: Handle<Self>,
551        app: &mut App,
552        _down: &PointerDownEvent,
553        _up: &PointerUpEvent,
554    ) {
555        if let Some(on_any_tap_up) = app.get(self).on_any_tap_up.clone() {
556            GestureRecognizer::invoke_callback(self, app, "onAnyTapUp", move |app| {
557                on_any_tap_up.call(app)
558            });
559        }
560    }
561
562    fn handle_tap_cancel(
563        self: Handle<Self>,
564        _app: &mut App,
565        _down: &PointerDownEvent,
566        _cancel: Option<&PointerCancelEvent>,
567        _reason: &str,
568    ) {
569        // Do nothing.
570    }
571}
572
573/// Dart's `_AnyTapGestureRecognizerFactory`.
574struct AnyTapGestureRecognizerFactory {
575    on_any_tap_up: Option<Listener>,
576}
577
578impl GestureRecognizerFactory<AnyTapGestureRecognizer> for AnyTapGestureRecognizerFactory {
579    fn constructor(&self, app: &mut App) -> Ref<AnyTapGestureRecognizer> {
580        AnyTapGestureRecognizer::new(app)
581    }
582
583    fn initializer(&self, app: &mut App, instance: Handle<AnyTapGestureRecognizer>) {
584        app.get_mut(instance).on_any_tap_up = self.on_any_tap_up.clone();
585    }
586}
587
588/// A gesture detector used by [`ModalBarrier`]. It only has one callback, which recognizes a
589/// tap up unconditionally.
590struct ModalBarrierGestureDetector {
591    /// The widget below this widget in the tree.
592    child: WidgetRef,
593    /// Immediately called when an event that should dismiss the modal barrier has happened.
594    on_dismiss: Listener,
595}
596
597impl Debug for ModalBarrierGestureDetector {
598    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
599        f.write_str("ModalBarrierGestureDetector")
600    }
601}
602
603impl StatelessWidget for ModalBarrierGestureDetector {
604    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
605        let gestures: GestureRecognizerFactories = vec![(
606            TypeId::of::<AnyTapGestureRecognizer>(),
607            AnyTapGestureRecognizerFactory {
608                on_any_tap_up: Some(self.on_dismiss.clone()),
609            }
610            .into_factory(),
611        )];
612
613        RawGestureDetector::new()
614            .gestures(gestures)
615            .behavior(HitTestBehavior::Opaque)
616            .child(self.child.clone())
617            .into_widget()
618    }
619}