Skip to main content

waft_widgets/widgets/
tap_region.rs

1//! Flutter counterpart: `widgets/tap_region.dart`.
2
3use std::any::TypeId;
4use std::collections::{HashMap, HashSet};
5use std::fmt::{self, Debug};
6use std::rc::Rc;
7
8use waft_embedder::{Matrix4, Offset, Size, TextBaseline};
9use waft_foundation::{
10    App, DiagnosticPropertiesBuilder, DiagnosticsProperty, FlagProperty, Handle, HandleId,
11};
12use waft_gestures::{
13    GestureArenaMember, GestureBinding, GestureDisposition, HitTestEntry, HitTestTarget,
14    PointerDownEvent, PointerEvent, PointerUpEvent,
15};
16use waft_rendering::{
17    AnyRenderBox, AnyRenderObject, BoxConstraints, BoxHitTestResult, HitTestBehavior,
18    PaintingContext, RenderBox, RenderBoxData, RenderHandle, RenderObject, RenderObjectData,
19    RenderObjectWithChildData, RenderObjectWithChildMixin, RenderProxyBoxMixin,
20    RenderProxyBoxWithHitTestBehavior,
21};
22
23use crate::framework::{
24    BuildContext, IntoWidget, KeyRef, RenderObjectWidget, SingleChildRenderObjectWidget, WidgetRef,
25};
26use crate::widgets::editable_text::EditableText;
27use crate::widgets::routes::AnyModalRoute;
28use waft_foundation::Ref;
29
30/// Enable if you want verbose logging about tap region changes.
31const K_DEBUG_TAP_REGION: bool = false;
32
33fn tap_region_debug(message: &str, details: &[&str]) -> bool {
34    if K_DEBUG_TAP_REGION {
35        eprintln!("TAP REGION: {message}");
36        for detail in details {
37            eprintln!("    {detail}");
38        }
39    }
40    true
41}
42
43/// Signature for a callback called for a [`PointerDownEvent`] relative to a [`TapRegion`].
44///
45/// See also:
46///
47///  * [`TapRegion::on_tap_outside`], which is of this type.
48///  * [`TapRegion::on_tap_inside`], which is of this type.
49///  * [`TapRegionUpCallback`], which is similar but for [`PointerUpEvent`]s.
50pub type TapRegionCallback = Rc<dyn Fn(&mut App, PointerDownEvent)>;
51
52/// Signature for a callback called for a [`PointerUpEvent`] relative to a [`TapRegion`].
53///
54/// See also:
55///
56///  * [`TapRegion::on_tap_up_outside`], which is of this type.
57///  * [`TapRegion::on_tap_up_inside`], which is of this type.
58///  * [`TapRegionCallback`], which is similar but for [`PointerDownEvent`]s.
59pub type TapRegionUpCallback = Rc<dyn Fn(&mut App, PointerUpEvent)>;
60
61/// Dart's `Object?` [`TapRegion::group_id`]: identity-comparable group keys.
62///
63/// [`TypeId`] matches [`EditableText::group_id`](crate::EditableText::group_id). [`HandleId`]
64/// is a handle's identity when the group is an arena object.
65#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
66pub enum TapRegionGroupId {
67    /// A type object, as `groupId: EditableText` in Dart.
68    Type(TypeId),
69    /// An arena object's identity.
70    Handle(HandleId),
71}
72
73impl From<TypeId> for TapRegionGroupId {
74    fn from(id: TypeId) -> TapRegionGroupId {
75        TapRegionGroupId::Type(id)
76    }
77}
78
79impl From<HandleId> for TapRegionGroupId {
80    fn from(id: HandleId) -> TapRegionGroupId {
81        TapRegionGroupId::Handle(id)
82    }
83}
84
85impl fmt::Display for TapRegionGroupId {
86    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87        match self {
88            TapRegionGroupId::Type(id) => write!(f, "{id:?}"),
89            TapRegionGroupId::Handle(id) => write!(f, "#{:05x}", id.identity_hash()),
90        }
91    }
92}
93
94/// An interface for registering and unregistering a [`RenderTapRegion`]
95/// (typically created with a [`TapRegion`] widget) with a
96/// [`RenderTapRegionSurface`] (typically created with a [`TapRegionSurface`]
97/// widget).
98pub trait TapRegionRegistry: RenderObject {
99    /// Register the given [`RenderTapRegion`] with the registry.
100    fn register_tap_region(
101        self: RenderHandle<Self>,
102        app: &mut App,
103        region: RenderHandle<RenderTapRegion>,
104    );
105
106    /// Unregister the given [`RenderTapRegion`] with the registry.
107    fn unregister_tap_region(
108        self: RenderHandle<Self>,
109        app: &mut App,
110        region: RenderHandle<RenderTapRegion>,
111    );
112
113    /// Allows finding of the nearest [`TapRegionRegistry`], such as a
114    /// [`RenderTapRegionSurface`].
115    ///
116    /// Panics if a [`TapRegionRegistry`] isn't found.
117    ///
118    /// Dart `TapRegionRegistry.of`.
119    fn of(app: &App, context: BuildContext) -> RenderHandle<RenderTapRegionSurface> {
120        Self::maybe_of(app, context).unwrap_or_else(|| {
121            panic!(
122                "TapRegionRegistry.of() was called with a context that does not contain a \
123                 TapRegionSurface widget.\n\
124                 No TapRegionSurface widget ancestor could be found starting from the context \
125                 that was passed to TapRegionRegistry.of().\n\
126                 The context used was:\n  {}",
127                context.widget(app).type_name()
128            )
129        })
130    }
131
132    /// Allows finding of the nearest [`TapRegionRegistry`], such as a
133    /// [`RenderTapRegionSurface`].
134    ///
135    /// Dart `TapRegionRegistry.maybeOf`.
136    fn maybe_of(app: &App, context: BuildContext) -> Option<RenderHandle<RenderTapRegionSurface>> {
137        context.find_ancestor_render_object_of_type::<RenderTapRegionSurface>(app)
138    }
139}
140
141/// A widget that provides notification of a tap inside or outside of a set of
142/// registered regions, without participating in the [gesture
143/// disambiguation](https://flutter.dev/to/gesture-disambiguation)
144/// system.
145///
146/// The regions are defined by adding [`TapRegion`] widgets to the widget tree
147/// around the regions of interest, and they will register with this
148/// [`TapRegionSurface`]. Each of the tap regions can optionally belong to a group
149/// by assigning a [`TapRegion::group_id`], where all the regions with the same
150/// group id act as if they were all one region.
151///
152/// When a tap down or tap up outside of a registered region or region group is
153/// detected, its [`TapRegion::on_tap_outside`] or [`TapRegion::on_tap_up_outside`]
154/// callback is called, respectively. If the tap is outside one member of a
155/// group, but inside another, no notification is made.
156///
157/// When a tap down or tap up inside of a registered region or region group is
158/// detected, its [`TapRegion::on_tap_inside`] or [`TapRegion::on_tap_up_inside`]
159/// callback is called, respectively. If the tap is inside one member of a
160/// group, all members are notified.
161///
162/// The [`TapRegionSurface`] should be defined at the highest level needed to
163/// encompass the entire area where taps should be monitored. This is typically
164/// around the entire app. If the entire app isn't covered, then taps outside of
165/// the [`TapRegionSurface`] will be ignored and no [`TapRegion::on_tap_outside`] or
166/// [`TapRegion::on_tap_up_outside`] calls will be made for those events.
167///
168/// [`TapRegion`]s register only with the nearest ancestor [`TapRegionSurface`].
169///
170/// See also:
171///
172///  * [`RenderTapRegionSurface`], the render object that is inserted into the
173///    render tree by this widget.
174#[derive(Debug)]
175pub struct TapRegionSurface {
176    /// See [`Widget::key`](crate::Widget::key).
177    pub key: Option<KeyRef>,
178    /// The widget below this widget in the tree.
179    pub child: WidgetRef,
180}
181
182impl TapRegionSurface {
183    /// Creates a [`TapRegionSurface`].
184    ///
185    /// The [`child`](Self::child) attribute is required.
186    #[cfg_attr(debug_assertions, track_caller)]
187    pub fn new<K>(child: impl IntoWidget<K>) -> TapRegionSurface {
188        TapRegionSurface {
189            key: None,
190            child: child.into_widget(),
191        }
192    }
193
194    /// Dart `TapRegionSurface(key:)`.
195    pub fn key(mut self, key: KeyRef) -> TapRegionSurface {
196        self.key = Some(key);
197        self
198    }
199}
200
201impl RenderObjectWidget for TapRegionSurface {
202    type RenderObject = RenderTapRegionSurface;
203
204    fn key(&self) -> Option<&KeyRef> {
205        self.key.as_ref()
206    }
207
208    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
209        RenderTapRegionSurface::new(app, None).as_object()
210    }
211
212    fn update_render_object(
213        &self,
214        _app: &mut App,
215        _context: BuildContext,
216        _render_object: RenderHandle<RenderTapRegionSurface>,
217    ) {
218    }
219}
220
221impl SingleChildRenderObjectWidget for TapRegionSurface {
222    fn child(&self) -> Option<&WidgetRef> {
223        Some(&self.child)
224    }
225}
226
227/// Classified registered regions for one event.
228struct ClassifiedTapRegions {
229    inside: Vec<RenderHandle<RenderTapRegion>>,
230    outside: Vec<RenderHandle<RenderTapRegion>>,
231}
232
233/// A render object that provides notification of a tap inside or outside of a
234/// set of registered regions, without participating in the [gesture
235/// disambiguation](https://flutter.dev/to/gesture-disambiguation) system
236/// (other than to consume tap down events if [`TapRegion::consume_outside_taps`] is
237/// true).
238///
239/// See [`TapRegionSurface`].
240pub struct RenderTapRegionSurface {
241    render_object: RenderObjectData,
242    render_box: RenderBoxData,
243    child: RenderObjectWithChildData<AnyRenderBox>,
244    registered_regions: HashSet<RenderHandle<RenderTapRegion>>,
245    group_id_to_regions: HashMap<TapRegionGroupId, HashSet<RenderHandle<RenderTapRegion>>>,
246    dummy_tap: Ref<DummyTapRecognizer>,
247}
248
249impl RenderTapRegionSurface {
250    /// Creates a [`RenderTapRegionSurface`].
251    pub fn new(app: &mut App, child: Option<AnyRenderBox>) -> RenderHandle<RenderTapRegionSurface> {
252        let dummy_tap = app.create(DummyTapRecognizer);
253        let this = RenderHandle::new_box(
254            app,
255            RenderTapRegionSurface {
256                render_object: RenderObjectData::new(),
257                render_box: RenderBoxData::new(),
258                child: RenderObjectWithChildData::new(),
259                registered_regions: HashSet::new(),
260                group_id_to_regions: HashMap::new(),
261                dummy_tap,
262            },
263        );
264        this.set_child(app, child);
265        this
266    }
267
268    /// Dart `TapRegionRegistry.of`.
269    pub fn of(app: &App, context: BuildContext) -> RenderHandle<Self> {
270        <Self as TapRegionRegistry>::of(app, context)
271    }
272
273    /// Dart `TapRegionRegistry.maybeOf`.
274    pub fn maybe_of(app: &App, context: BuildContext) -> Option<RenderHandle<Self>> {
275        <Self as TapRegionRegistry>::maybe_of(app, context)
276    }
277
278    /// Classifies registered tap regions as inside or outside based on which
279    /// regions appear in the hit test path. Grouped regions are treated as a
280    /// single unit: if any member of a group is hit, all members are considered
281    /// inside.
282    fn classify_regions(
283        self: RenderHandle<Self>,
284        app: &App,
285        path: &[HandleId],
286    ) -> ClassifiedTapRegions {
287        let hit_ids: HashSet<HandleId> = path.iter().copied().collect();
288        let registered = &self.get(app).registered_regions;
289        debug_assert!(tap_region_debug(
290            &format!(
291                "Tap event hit {} descendants.",
292                registered
293                    .iter()
294                    .filter(|region| hit_ids.contains(&region.handle().id()))
295                    .count()
296            ),
297            &[],
298        ));
299
300        let mut inside_regions = HashSet::new();
301        for region in registered {
302            if !hit_ids.contains(&region.handle().id()) {
303                continue;
304            }
305            match region.group_id(app) {
306                None => {
307                    inside_regions.insert(*region);
308                }
309                Some(group_id) => {
310                    let members = self
311                        .get(app)
312                        .group_id_to_regions
313                        .get(&group_id)
314                        .expect("a grouped registered region has a group set");
315                    inside_regions.extend(members.iter().copied());
316                }
317            }
318        }
319        // Materialize the outside list so callbacks that mutate registrations
320        // during iteration do not affect the snapshot we are walking.
321        let outside = registered
322            .iter()
323            .copied()
324            .filter(|region| !inside_regions.contains(region))
325            .collect();
326        ClassifiedTapRegions {
327            inside: inside_regions.into_iter().collect(),
328            outside,
329        }
330    }
331
332    /// Flutter's `handleEvent` after the cached hit-test path is recovered.
333    fn handle_event_from_cache(
334        self: RenderHandle<Self>,
335        app: &mut App,
336        event: &PointerEvent,
337        path: &[HandleId],
338    ) {
339        debug_assert!({
340            let all_enabled = self
341                .get(app)
342                .registered_regions
343                .iter()
344                .all(|region| region.enabled(app));
345            if !all_enabled {
346                panic!("A RenderTapRegion was registered when it was disabled.");
347            }
348            true
349        });
350
351        if !matches!(event, PointerEvent::Down(_) | PointerEvent::Up(_)) {
352            return;
353        }
354
355        if self.get(app).registered_regions.is_empty() {
356            debug_assert!(tap_region_debug(
357                "Ignored tap event because no regions are registered.",
358                &[],
359            ));
360            return;
361        }
362
363        let ClassifiedTapRegions { inside, outside } = self.classify_regions(app, path);
364
365        let mut consume_outside_taps = false;
366        for region in outside {
367            match event {
368                PointerEvent::Down(event) => {
369                    debug_assert!(tap_region_debug(
370                        &format!("Calling onTapOutside for {region:?}"),
371                        &[],
372                    ));
373                    if let Some(callback) = region.on_tap_outside(app) {
374                        callback(app, event.clone());
375                    }
376                }
377                PointerEvent::Up(event) => {
378                    debug_assert!(tap_region_debug(
379                        &format!("Calling onTapUpOutside for {region:?}"),
380                        &[],
381                    ));
382                    if let Some(callback) = region.on_tap_up_outside(app) {
383                        callback(app, event.clone());
384                    }
385                }
386                _ => {}
387            }
388            if region.consume_outside_taps(app) {
389                debug_assert!(tap_region_debug(
390                    &format!(
391                        "Stopping tap propagation for {region:?} (and all of {:?})",
392                        region.group_id(app)
393                    ),
394                    &[],
395                ));
396                consume_outside_taps = true;
397            }
398        }
399        for region in inside {
400            match event {
401                PointerEvent::Down(event) => {
402                    debug_assert!(tap_region_debug(
403                        &format!("Calling onTapInside for {region:?}"),
404                        &[],
405                    ));
406                    if let Some(callback) = region.on_tap_inside(app) {
407                        callback(app, event.clone());
408                    }
409                }
410                PointerEvent::Up(event) => {
411                    debug_assert!(tap_region_debug(
412                        &format!("Calling onTapUpInside for {region:?}"),
413                        &[],
414                    ));
415                    if let Some(callback) = region.on_tap_up_inside(app) {
416                        callback(app, event.clone());
417                    }
418                }
419                _ => {}
420            }
421        }
422
423        // If any of the "outside" regions have consumeOutsideTaps set, then stop
424        // the propagation of the event through the gesture recognizer by adding it
425        // to the recognizer and immediately resolving it.
426        if consume_outside_taps && let PointerEvent::Down(event) = event {
427            let dummy = DummyTapRecognizerMember(self.get(app).dummy_tap.handle());
428            GestureBinding::instance(app)
429                .gesture_arena(app)
430                .add(app, event.pointer, dummy)
431                .resolve(app, GestureDisposition::Accepted);
432        }
433    }
434}
435
436impl TapRegionRegistry for RenderTapRegionSurface {
437    fn register_tap_region(
438        self: RenderHandle<Self>,
439        app: &mut App,
440        region: RenderHandle<RenderTapRegion>,
441    ) {
442        debug_assert!(tap_region_debug(
443            &format!("Region {region:?} registered."),
444            &[],
445        ));
446        debug_assert!(!self.get(app).registered_regions.contains(&region));
447        self.get_mut(app).registered_regions.insert(region);
448        if let Some(group_id) = region.group_id(app) {
449            self.get_mut(app)
450                .group_id_to_regions
451                .entry(group_id)
452                .or_default()
453                .insert(region);
454        }
455    }
456
457    fn unregister_tap_region(
458        self: RenderHandle<Self>,
459        app: &mut App,
460        region: RenderHandle<RenderTapRegion>,
461    ) {
462        debug_assert!(tap_region_debug(
463            &format!("Region {region:?} unregistered."),
464            &[],
465        ));
466        debug_assert!(self.get(app).registered_regions.contains(&region));
467        self.get_mut(app).registered_regions.remove(&region);
468        if let Some(group_id) = region.group_id(app) {
469            debug_assert!(self.get(app).group_id_to_regions.contains_key(&group_id));
470            let empty = {
471                let members = self
472                    .get_mut(app)
473                    .group_id_to_regions
474                    .get_mut(&group_id)
475                    .expect("checked");
476                members.remove(&region);
477                members.is_empty()
478            };
479            if empty {
480                self.get_mut(app).group_id_to_regions.remove(&group_id);
481            }
482        }
483    }
484}
485
486/// Dart's `Expando<BoxHitTestResult>` keyed by the surface's hit-test entry: the
487/// path snapshot lives on the entry so each concurrent pointer keeps its own
488/// classification input.
489#[derive(Debug)]
490struct TapRegionSurfaceHitTarget {
491    surface: RenderHandle<RenderTapRegionSurface>,
492    path: Vec<HandleId>,
493}
494
495impl HitTestTarget for TapRegionSurfaceHitTarget {
496    fn handle_event(&self, app: &mut App, event: &PointerEvent, _entry: &HitTestEntry) {
497        self.surface.handle_event_from_cache(app, event, &self.path);
498    }
499
500    fn arena_id(&self) -> Option<HandleId> {
501        Some(self.surface.handle().id())
502    }
503}
504
505/// A dummy tap recognizer so that we don't have to deal with the lifecycle of
506/// `TapGestureRecognizer`, since we're just going to immediately resolve it
507/// anyhow.
508struct DummyTapRecognizer;
509
510#[derive(Clone, Copy)]
511struct DummyTapRecognizerMember(Handle<DummyTapRecognizer>);
512
513impl GestureArenaMember for DummyTapRecognizerMember {
514    fn accept_gesture(&self, _app: &mut App, _pointer: i64) {}
515
516    fn reject_gesture(&self, _app: &mut App, _pointer: i64) {}
517
518    fn member_id(&self) -> HandleId {
519        self.0.id()
520    }
521}
522
523impl RenderObjectWithChildMixin for RenderTapRegionSurface {
524    type ChildType = AnyRenderBox;
525
526    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
527        &self.get(app).child
528    }
529
530    fn child_data_mut(
531        self: RenderHandle<Self>,
532        app: &mut App,
533    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
534        &mut self.get_mut(app).child
535    }
536}
537
538impl RenderProxyBoxMixin for RenderTapRegionSurface {}
539
540impl RenderProxyBoxWithHitTestBehavior for RenderTapRegionSurface {
541    fn behavior(self: RenderHandle<Self>, _app: &App) -> HitTestBehavior {
542        HitTestBehavior::DeferToChild
543    }
544}
545
546impl RenderObject for RenderTapRegionSurface {
547    waft_rendering::render_object_accessors!();
548
549    fn debug_fill_properties(
550        self: RenderHandle<Self>,
551        app: &App,
552        properties: &mut DiagnosticPropertiesBuilder,
553    ) {
554        RenderProxyBoxWithHitTestBehavior::debug_fill_properties(self, app, properties);
555    }
556
557    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
558        RenderProxyBoxMixin::perform_layout(self, app);
559    }
560
561    fn paint(
562        self: RenderHandle<Self>,
563        app: &mut App,
564        context: &mut PaintingContext,
565        offset: Offset,
566    ) {
567        RenderProxyBoxMixin::paint(self, app, context, offset);
568    }
569
570    fn visit_children(
571        self: RenderHandle<Self>,
572        app: &App,
573        visitor: &mut dyn FnMut(AnyRenderObject),
574    ) {
575        if let Some(child) = self.child(app) {
576            visitor(child.as_object());
577        }
578    }
579}
580
581impl RenderBox for RenderTapRegionSurface {
582    waft_rendering::render_box_accessors!();
583
584    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
585        RenderProxyBoxMixin::setup_parent_data(self, app, child);
586    }
587
588    fn apply_paint_transform(
589        self: RenderHandle<Self>,
590        app: &App,
591        child: AnyRenderObject,
592        transform: &mut Matrix4,
593    ) {
594        RenderProxyBoxMixin::apply_paint_transform(self, app, child, transform);
595    }
596
597    fn hit_test(
598        self: RenderHandle<Self>,
599        app: &mut App,
600        result: &mut BoxHitTestResult<'_>,
601        position: Offset,
602    ) -> bool {
603        if !self.size(app).contains(position) {
604            return false;
605        }
606
607        let hit_target = RenderBox::hit_test_children(self, app, result, position)
608            || RenderBox::hit_test_self(self, app, position);
609
610        if hit_target {
611            let path = result
612                .path()
613                .iter()
614                .filter_map(|entry| entry.target().arena_id())
615                .collect();
616            result.add(HitTestEntry::new(TapRegionSurfaceHitTarget {
617                surface: self,
618                path,
619            }));
620        }
621
622        hit_target
623    }
624
625    fn hit_test_self(self: RenderHandle<Self>, app: &App, position: Offset) -> bool {
626        RenderProxyBoxWithHitTestBehavior::hit_test_self(self, app, position)
627    }
628
629    fn hit_test_children(
630        self: RenderHandle<Self>,
631        app: &mut App,
632        result: &mut BoxHitTestResult<'_>,
633        position: Offset,
634    ) -> bool {
635        RenderProxyBoxMixin::hit_test_children(self, app, result, position)
636    }
637
638    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
639        RenderProxyBoxMixin::compute_min_intrinsic_width(self, app, height)
640    }
641
642    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
643        RenderProxyBoxMixin::compute_max_intrinsic_width(self, app, height)
644    }
645
646    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
647        RenderProxyBoxMixin::compute_min_intrinsic_height(self, app, width)
648    }
649
650    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
651        RenderProxyBoxMixin::compute_max_intrinsic_height(self, app, width)
652    }
653
654    fn compute_distance_to_actual_baseline(
655        self: RenderHandle<Self>,
656        app: &mut App,
657        baseline: TextBaseline,
658    ) -> Option<f64> {
659        RenderProxyBoxMixin::compute_distance_to_actual_baseline(self, app, baseline)
660    }
661
662    fn compute_dry_baseline(
663        self: RenderHandle<Self>,
664        app: &mut App,
665        constraints: BoxConstraints,
666        baseline: TextBaseline,
667    ) -> Option<f64> {
668        RenderProxyBoxMixin::compute_dry_baseline(self, app, constraints, baseline)
669    }
670
671    fn compute_dry_layout(
672        self: RenderHandle<Self>,
673        app: &mut App,
674        constraints: BoxConstraints,
675    ) -> Size {
676        RenderProxyBoxMixin::compute_dry_layout(self, app, constraints)
677    }
678}
679
680/// A widget that defines a region that can detect taps inside or outside of
681/// itself and any group of regions it belongs to, without participating in the
682/// [gesture
683/// disambiguation](https://flutter.dev/to/gesture-disambiguation) system
684/// (other than to consume tap down events if [`consume_outside_taps`](Self::consume_outside_taps) is true).
685///
686/// This widget indicates to the nearest ancestor [`TapRegionSurface`] that the
687/// region occupied by its child will participate in the tap detection for that
688/// surface.
689///
690/// If this region belongs to a group (by virtue of its [`group_id`](Self::group_id)), all the
691/// regions in the group will act as one.
692///
693/// If there is no [`TapRegionSurface`] ancestor, [`TapRegion`] will do nothing.
694///
695/// [`TapRegion`] is aware of the routes in the navigator, so that [`on_tap_outside`](Self::on_tap_outside)
696/// or [`on_tap_up_outside`](Self::on_tap_up_outside) isn't called after the user navigates to a different page.
697pub struct TapRegion {
698    /// See [`Widget::key`](crate::Widget::key).
699    pub key: Option<KeyRef>,
700    /// The widget below this widget in the tree.
701    pub child: WidgetRef,
702    /// Whether or not this [`TapRegion`] is enabled as part of the composite region.
703    pub enabled: bool,
704    /// How to behave during hit testing when deciding how the hit test propagates
705    /// to children and whether to consider targets behind this [`TapRegion`].
706    ///
707    /// Defaults to [`HitTestBehavior::DeferToChild`].
708    pub behavior: HitTestBehavior,
709    /// A callback to be invoked when a tap down is detected outside of this
710    /// [`TapRegion`] and any other region with the same [`group_id`](Self::group_id), if any.
711    pub on_tap_outside: Option<TapRegionCallback>,
712    /// A callback to be invoked when a tap down is detected inside of this
713    /// [`TapRegion`], or any other tap region with the same [`group_id`](Self::group_id), if any.
714    pub on_tap_inside: Option<TapRegionCallback>,
715    /// A callback to be invoked when a tap up is detected outside of this
716    /// [`TapRegion`] and any other region with the same [`group_id`](Self::group_id), if any.
717    pub on_tap_up_outside: Option<TapRegionUpCallback>,
718    /// A callback to be invoked when a tap up is detected inside of this
719    /// [`TapRegion`], or any other tap region with the same [`group_id`](Self::group_id), if any.
720    pub on_tap_up_inside: Option<TapRegionUpCallback>,
721    /// An optional group ID that groups [`TapRegion`]s together so that they
722    /// operate as one region. If any member of a group is hit by a particular
723    /// tap, then the [`on_tap_outside`](Self::on_tap_outside) / [`on_tap_up_outside`](Self::on_tap_up_outside) will not be called for
724    /// any members of the group. If any member of the group is hit, then all
725    /// members will have their [`on_tap_inside`](Self::on_tap_inside) / [`on_tap_up_inside`](Self::on_tap_up_inside) called.
726    ///
727    /// If the group id is `None`, then only this region is hit tested.
728    pub group_id: Option<TapRegionGroupId>,
729    /// If true, then the group that this region belongs to will stop the
730    /// propagation of all events in the gesture arena.
731    ///
732    /// Defaults to false.
733    pub consume_outside_taps: bool,
734    /// An optional debug label to help with debugging in debug mode.
735    ///
736    /// Will be `None` in release mode.
737    pub debug_label: Option<String>,
738}
739
740impl TapRegion {
741    /// Creates a [`TapRegion`].
742    ///
743    /// The [`child`](Self::child) argument is required.
744    #[cfg_attr(debug_assertions, track_caller)]
745    pub fn new<K>(child: impl IntoWidget<K>) -> TapRegion {
746        TapRegion {
747            key: None,
748            child: child.into_widget(),
749            enabled: true,
750            behavior: HitTestBehavior::DeferToChild,
751            on_tap_outside: None,
752            on_tap_inside: None,
753            on_tap_up_outside: None,
754            on_tap_up_inside: None,
755            group_id: None,
756            consume_outside_taps: false,
757            debug_label: None,
758        }
759    }
760
761    /// Dart `TapRegion(key:)`.
762    pub fn key(mut self, key: KeyRef) -> TapRegion {
763        self.key = Some(key);
764        self
765    }
766
767    /// Dart `TapRegion(enabled:)`.
768    pub fn enabled(mut self, enabled: bool) -> TapRegion {
769        self.enabled = enabled;
770        self
771    }
772
773    /// Dart `TapRegion(behavior:)`.
774    pub fn behavior(mut self, behavior: HitTestBehavior) -> TapRegion {
775        self.behavior = behavior;
776        self
777    }
778
779    /// Dart `TapRegion(onTapOutside:)`.
780    pub fn on_tap_outside(mut self, on_tap_outside: TapRegionCallback) -> TapRegion {
781        self.on_tap_outside = Some(on_tap_outside);
782        self
783    }
784
785    /// Dart `TapRegion(onTapInside:)`.
786    pub fn on_tap_inside(mut self, on_tap_inside: TapRegionCallback) -> TapRegion {
787        self.on_tap_inside = Some(on_tap_inside);
788        self
789    }
790
791    /// Dart `TapRegion(onTapUpOutside:)`.
792    pub fn on_tap_up_outside(mut self, on_tap_up_outside: TapRegionUpCallback) -> TapRegion {
793        self.on_tap_up_outside = Some(on_tap_up_outside);
794        self
795    }
796
797    /// Dart `TapRegion(onTapUpInside:)`.
798    pub fn on_tap_up_inside(mut self, on_tap_up_inside: TapRegionUpCallback) -> TapRegion {
799        self.on_tap_up_inside = Some(on_tap_up_inside);
800        self
801    }
802
803    /// Dart `TapRegion(groupId:)`.
804    pub fn group_id(mut self, group_id: impl Into<TapRegionGroupId>) -> TapRegion {
805        self.group_id = Some(group_id.into());
806        self
807    }
808
809    /// Dart `TapRegion(consumeOutsideTaps:)`.
810    pub fn consume_outside_taps(mut self, consume_outside_taps: bool) -> TapRegion {
811        self.consume_outside_taps = consume_outside_taps;
812        self
813    }
814
815    /// Dart `TapRegion(debugLabel:)`.
816    pub fn debug_label(mut self, debug_label: impl Into<String>) -> TapRegion {
817        self.debug_label = if cfg!(debug_assertions) {
818            Some(debug_label.into())
819        } else {
820            None
821        };
822        self
823    }
824
825    fn apply_to_render_object(
826        &self,
827        app: &mut App,
828        context: BuildContext,
829        render_object: RenderHandle<RenderTapRegion>,
830    ) {
831        let is_current = AnyModalRoute::is_current_of(app, context).unwrap_or(true);
832        render_object.set_registry(app, RenderTapRegionSurface::maybe_of(app, context));
833        render_object.set_enabled(app, self.enabled);
834        render_object.set_consume_outside_taps(app, is_current && self.consume_outside_taps);
835        render_object.set_behavior(app, self.behavior);
836        render_object.set_group_id(app, self.group_id);
837        render_object.set_on_tap_outside(
838            app,
839            if is_current {
840                self.on_tap_outside.clone()
841            } else {
842                None
843            },
844        );
845        render_object.set_on_tap_inside(app, self.on_tap_inside.clone());
846        render_object.set_on_tap_up_outside(
847            app,
848            if is_current {
849                self.on_tap_up_outside.clone()
850            } else {
851                None
852            },
853        );
854        render_object.set_on_tap_up_inside(app, self.on_tap_up_inside.clone());
855        if cfg!(debug_assertions) {
856            render_object.set_debug_label(app, self.debug_label.clone());
857        }
858    }
859}
860
861impl RenderObjectWidget for TapRegion {
862    type RenderObject = RenderTapRegion;
863
864    fn key(&self) -> Option<&KeyRef> {
865        self.key.as_ref()
866    }
867
868    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
869        properties.add(
870            FlagProperty::new("enabled", Some(self.enabled))
871                .if_false("DISABLED")
872                .default_value(Some(true)),
873        );
874        properties.add(
875            DiagnosticsProperty::new("behavior", self.behavior)
876                .default_value(Some(HitTestBehavior::DeferToChild)),
877        );
878        properties.add(
879            DiagnosticsProperty::<String>::new("debugLabel", self.debug_label.clone())
880                .default_value(None),
881        );
882        properties.add(
883            DiagnosticsProperty::<String>::new(
884                "groupId",
885                self.group_id.map(|group_id| group_id.to_string()),
886            )
887            .default_value(None),
888        );
889    }
890
891    fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject {
892        let is_current = AnyModalRoute::is_current_of(app, context).unwrap_or(true);
893        let render_object = RenderTapRegion::new(
894            app,
895            RenderTapRegionSurface::maybe_of(app, context),
896            self.enabled,
897            is_current && self.consume_outside_taps,
898            if is_current {
899                self.on_tap_outside.clone()
900            } else {
901                None
902            },
903            self.on_tap_inside.clone(),
904            if is_current {
905                self.on_tap_up_outside.clone()
906            } else {
907                None
908            },
909            self.on_tap_up_inside.clone(),
910            self.behavior,
911            self.group_id,
912            self.debug_label.clone(),
913        );
914        render_object.as_object()
915    }
916
917    fn update_render_object(
918        &self,
919        app: &mut App,
920        context: BuildContext,
921        render_object: RenderHandle<RenderTapRegion>,
922    ) {
923        self.apply_to_render_object(app, context, render_object);
924    }
925}
926
927impl SingleChildRenderObjectWidget for TapRegion {
928    fn child(&self) -> Option<&WidgetRef> {
929        Some(&self.child)
930    }
931}
932
933impl Debug for TapRegion {
934    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
935        f.debug_struct("TapRegion")
936            .field("key", &self.key)
937            .field("enabled", &self.enabled)
938            .field("behavior", &self.behavior)
939            .field(
940                "on_tap_outside",
941                &self.on_tap_outside.as_ref().map(|_| ".."),
942            )
943            .field("on_tap_inside", &self.on_tap_inside.as_ref().map(|_| ".."))
944            .field(
945                "on_tap_up_outside",
946                &self.on_tap_up_outside.as_ref().map(|_| ".."),
947            )
948            .field(
949                "on_tap_up_inside",
950                &self.on_tap_up_inside.as_ref().map(|_| ".."),
951            )
952            .field("group_id", &self.group_id)
953            .field("consume_outside_taps", &self.consume_outside_taps)
954            .field("debug_label", &self.debug_label)
955            .field("child", &self.child)
956            .finish()
957    }
958}
959
960/// A render object that defines a region that can detect taps inside or outside
961/// of itself and any group of regions it belongs to, without participating in
962/// the [gesture
963/// disambiguation](https://flutter.dev/to/gesture-disambiguation) system.
964///
965/// See [`TapRegion`].
966pub struct RenderTapRegion {
967    render_object: RenderObjectData,
968    render_box: RenderBoxData,
969    child: RenderObjectWithChildData<AnyRenderBox>,
970    is_registered: bool,
971    on_tap_outside: Option<TapRegionCallback>,
972    on_tap_inside: Option<TapRegionCallback>,
973    on_tap_up_outside: Option<TapRegionUpCallback>,
974    on_tap_up_inside: Option<TapRegionUpCallback>,
975    debug_label: Option<String>,
976    enabled: bool,
977    consume_outside_taps: bool,
978    group_id: Option<TapRegionGroupId>,
979    registry: Option<RenderHandle<RenderTapRegionSurface>>,
980    behavior: HitTestBehavior,
981}
982
983impl RenderTapRegion {
984    /// Creates a [`RenderTapRegion`].
985    #[allow(clippy::too_many_arguments)]
986    pub fn new(
987        app: &mut App,
988        registry: Option<RenderHandle<RenderTapRegionSurface>>,
989        enabled: bool,
990        consume_outside_taps: bool,
991        on_tap_outside: Option<TapRegionCallback>,
992        on_tap_inside: Option<TapRegionCallback>,
993        on_tap_up_outside: Option<TapRegionUpCallback>,
994        on_tap_up_inside: Option<TapRegionUpCallback>,
995        behavior: HitTestBehavior,
996        group_id: Option<TapRegionGroupId>,
997        debug_label: Option<String>,
998    ) -> RenderHandle<RenderTapRegion> {
999        let this = RenderHandle::new_box(
1000            app,
1001            RenderTapRegion {
1002                render_object: RenderObjectData::new(),
1003                render_box: RenderBoxData::new(),
1004                child: RenderObjectWithChildData::new(),
1005                is_registered: false,
1006                on_tap_outside,
1007                on_tap_inside,
1008                on_tap_up_outside,
1009                on_tap_up_inside,
1010                debug_label: if cfg!(debug_assertions) {
1011                    debug_label
1012                } else {
1013                    None
1014                },
1015                enabled,
1016                consume_outside_taps,
1017                group_id,
1018                registry,
1019                behavior,
1020            },
1021        );
1022        this.set_child(app, None);
1023        this
1024    }
1025
1026    /// A callback to be invoked when a tap down is detected outside of this
1027    /// [`RenderTapRegion`] and any other region with the same [`group_id`](Self::group_id), if any.
1028    pub fn on_tap_outside(self: RenderHandle<Self>, app: &App) -> Option<TapRegionCallback> {
1029        self.get(app).on_tap_outside.clone()
1030    }
1031
1032    /// Sets [`on_tap_outside`](Self::on_tap_outside).
1033    pub fn set_on_tap_outside(
1034        self: RenderHandle<Self>,
1035        app: &mut App,
1036        value: Option<TapRegionCallback>,
1037    ) {
1038        self.get_mut(app).on_tap_outside = value;
1039    }
1040
1041    /// A callback to be invoked when a tap down is detected inside of this
1042    /// [`RenderTapRegion`], or any other tap region with the same [`group_id`](Self::group_id), if any.
1043    pub fn on_tap_inside(self: RenderHandle<Self>, app: &App) -> Option<TapRegionCallback> {
1044        self.get(app).on_tap_inside.clone()
1045    }
1046
1047    /// Sets [`on_tap_inside`](Self::on_tap_inside).
1048    pub fn set_on_tap_inside(
1049        self: RenderHandle<Self>,
1050        app: &mut App,
1051        value: Option<TapRegionCallback>,
1052    ) {
1053        self.get_mut(app).on_tap_inside = value;
1054    }
1055
1056    /// A callback to be invoked when a tap up is detected outside of this
1057    /// [`RenderTapRegion`] and any other region with the same [`group_id`](Self::group_id), if any.
1058    pub fn on_tap_up_outside(self: RenderHandle<Self>, app: &App) -> Option<TapRegionUpCallback> {
1059        self.get(app).on_tap_up_outside.clone()
1060    }
1061
1062    /// Sets [`on_tap_up_outside`](Self::on_tap_up_outside).
1063    pub fn set_on_tap_up_outside(
1064        self: RenderHandle<Self>,
1065        app: &mut App,
1066        value: Option<TapRegionUpCallback>,
1067    ) {
1068        self.get_mut(app).on_tap_up_outside = value;
1069    }
1070
1071    /// A callback to be invoked when a tap up is detected inside of this
1072    /// [`RenderTapRegion`], or any other tap region with the same [`group_id`](Self::group_id), if any.
1073    pub fn on_tap_up_inside(self: RenderHandle<Self>, app: &App) -> Option<TapRegionUpCallback> {
1074        self.get(app).on_tap_up_inside.clone()
1075    }
1076
1077    /// Sets [`on_tap_up_inside`](Self::on_tap_up_inside).
1078    pub fn set_on_tap_up_inside(
1079        self: RenderHandle<Self>,
1080        app: &mut App,
1081        value: Option<TapRegionUpCallback>,
1082    ) {
1083        self.get_mut(app).on_tap_up_inside = value;
1084    }
1085
1086    /// A label used in debug builds. Will be `None` in release builds.
1087    pub fn debug_label(self: RenderHandle<Self>, app: &App) -> Option<String> {
1088        self.get(app).debug_label.clone()
1089    }
1090
1091    /// Sets [`debug_label`](Self::debug_label).
1092    pub fn set_debug_label(self: RenderHandle<Self>, app: &mut App, value: Option<String>) {
1093        self.get_mut(app).debug_label = if cfg!(debug_assertions) { value } else { None };
1094    }
1095
1096    /// Whether or not this region should participate in the composite region.
1097    pub fn enabled(self: RenderHandle<Self>, app: &App) -> bool {
1098        self.get(app).enabled
1099    }
1100
1101    /// Sets [`enabled`](Self::enabled).
1102    pub fn set_enabled(self: RenderHandle<Self>, app: &mut App, value: bool) {
1103        if self.get(app).enabled != value {
1104            self.get_mut(app).enabled = value;
1105            self.mark_needs_layout(app);
1106        }
1107    }
1108
1109    /// Whether or not the tap event that triggers a call to [`on_tap_outside`](Self::on_tap_outside)
1110    /// or [`on_tap_up_outside`](Self::on_tap_up_outside) will continue on to participate in the gesture arena.
1111    pub fn consume_outside_taps(self: RenderHandle<Self>, app: &App) -> bool {
1112        self.get(app).consume_outside_taps
1113    }
1114
1115    /// Sets [`consume_outside_taps`](Self::consume_outside_taps).
1116    pub fn set_consume_outside_taps(self: RenderHandle<Self>, app: &mut App, value: bool) {
1117        if self.get(app).consume_outside_taps != value {
1118            self.get_mut(app).consume_outside_taps = value;
1119            self.mark_needs_layout(app);
1120        }
1121    }
1122
1123    /// An optional group ID that groups [`RenderTapRegion`]s together so that they
1124    /// operate as one region.
1125    pub fn group_id(self: RenderHandle<Self>, app: &App) -> Option<TapRegionGroupId> {
1126        self.get(app).group_id
1127    }
1128
1129    /// Sets [`group_id`](Self::group_id).
1130    pub fn set_group_id(self: RenderHandle<Self>, app: &mut App, value: Option<TapRegionGroupId>) {
1131        if self.get(app).group_id != value {
1132            // If the group changes, we need to unregister and re-register under the
1133            // new group. The re-registration happens automatically in layout().
1134            self.unregister_if_registered(app);
1135            self.get_mut(app).group_id = value;
1136            self.mark_needs_layout(app);
1137        }
1138    }
1139
1140    /// The registry that this [`RenderTapRegion`] should register with.
1141    ///
1142    /// If the registry is `None`, then this region will not be registered
1143    /// anywhere, and will not do any tap detection.
1144    ///
1145    /// A [`RenderTapRegionSurface`] is a [`TapRegionRegistry`].
1146    pub fn registry(
1147        self: RenderHandle<Self>,
1148        app: &App,
1149    ) -> Option<RenderHandle<RenderTapRegionSurface>> {
1150        self.get(app).registry
1151    }
1152
1153    /// Sets [`registry`](Self::registry).
1154    pub fn set_registry(
1155        self: RenderHandle<Self>,
1156        app: &mut App,
1157        value: Option<RenderHandle<RenderTapRegionSurface>>,
1158    ) {
1159        if self.get(app).registry != value {
1160            self.unregister_if_registered(app);
1161            self.get_mut(app).registry = value;
1162            self.mark_needs_layout(app);
1163        }
1164    }
1165
1166    /// Sets [`behavior`](RenderProxyBoxWithHitTestBehavior::behavior).
1167    pub fn set_behavior(self: RenderHandle<Self>, app: &mut App, value: HitTestBehavior) {
1168        self.get_mut(app).behavior = value;
1169    }
1170
1171    fn unregister_if_registered(self: RenderHandle<Self>, app: &mut App) {
1172        if !self.get(app).is_registered {
1173            return;
1174        }
1175        let registry = self
1176            .get(app)
1177            .registry
1178            .expect("a registered region has a registry");
1179        registry.unregister_tap_region(app, self);
1180        self.get_mut(app).is_registered = false;
1181    }
1182
1183    fn sync_registration(self: RenderHandle<Self>, app: &mut App) {
1184        let Some(registry) = self.get(app).registry else {
1185            return;
1186        };
1187        if self.get(app).is_registered {
1188            registry.unregister_tap_region(app, self);
1189        }
1190        let should_be_registered = self.get(app).enabled && self.get(app).registry.is_some();
1191        if should_be_registered {
1192            registry.register_tap_region(app, self);
1193        }
1194        self.get_mut(app).is_registered = should_be_registered;
1195    }
1196}
1197
1198impl RenderObjectWithChildMixin for RenderTapRegion {
1199    type ChildType = AnyRenderBox;
1200
1201    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
1202        &self.get(app).child
1203    }
1204
1205    fn child_data_mut(
1206        self: RenderHandle<Self>,
1207        app: &mut App,
1208    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
1209        &mut self.get_mut(app).child
1210    }
1211}
1212
1213impl RenderProxyBoxMixin for RenderTapRegion {}
1214
1215impl RenderProxyBoxWithHitTestBehavior for RenderTapRegion {
1216    fn behavior(self: RenderHandle<Self>, app: &App) -> HitTestBehavior {
1217        self.get(app).behavior
1218    }
1219}
1220
1221impl RenderObject for RenderTapRegion {
1222    waft_rendering::render_object_accessors!();
1223
1224    fn debug_fill_properties(
1225        self: RenderHandle<Self>,
1226        app: &App,
1227        properties: &mut DiagnosticPropertiesBuilder,
1228    ) {
1229        RenderProxyBoxWithHitTestBehavior::debug_fill_properties(self, app, properties);
1230        properties.add(
1231            DiagnosticsProperty::<String>::new("debugLabel", self.debug_label(app))
1232                .default_value(None),
1233        );
1234        properties.add(
1235            DiagnosticsProperty::<TapRegionGroupId>::new("groupId", self.group_id(app))
1236                .default_value(None),
1237        );
1238        properties.add(
1239            FlagProperty::new("enabled", Some(self.enabled(app)))
1240                .if_false("DISABLED")
1241                .default_value(Some(true)),
1242        );
1243    }
1244
1245    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
1246        RenderProxyBoxMixin::perform_layout(self, app);
1247        self.sync_registration(app);
1248    }
1249
1250    fn did_detach(self: RenderHandle<Self>, app: &mut App) {
1251        self.unregister_if_registered(app);
1252        if let Some(child) = self.child(app) {
1253            child.as_object().detach(app);
1254        }
1255    }
1256
1257    fn paint(
1258        self: RenderHandle<Self>,
1259        app: &mut App,
1260        context: &mut PaintingContext,
1261        offset: Offset,
1262    ) {
1263        RenderProxyBoxMixin::paint(self, app, context, offset);
1264    }
1265
1266    fn visit_children(
1267        self: RenderHandle<Self>,
1268        app: &App,
1269        visitor: &mut dyn FnMut(AnyRenderObject),
1270    ) {
1271        if let Some(child) = self.child(app) {
1272            visitor(child.as_object());
1273        }
1274    }
1275}
1276
1277impl RenderBox for RenderTapRegion {
1278    waft_rendering::render_box_accessors!();
1279
1280    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
1281        RenderProxyBoxMixin::setup_parent_data(self, app, child);
1282    }
1283
1284    fn apply_paint_transform(
1285        self: RenderHandle<Self>,
1286        app: &App,
1287        child: AnyRenderObject,
1288        transform: &mut Matrix4,
1289    ) {
1290        RenderProxyBoxMixin::apply_paint_transform(self, app, child, transform);
1291    }
1292
1293    fn hit_test(
1294        self: RenderHandle<Self>,
1295        app: &mut App,
1296        result: &mut BoxHitTestResult<'_>,
1297        position: Offset,
1298    ) -> bool {
1299        RenderProxyBoxWithHitTestBehavior::hit_test(self, app, result, position)
1300    }
1301
1302    fn hit_test_self(self: RenderHandle<Self>, app: &App, position: Offset) -> bool {
1303        RenderProxyBoxWithHitTestBehavior::hit_test_self(self, app, position)
1304    }
1305
1306    fn hit_test_children(
1307        self: RenderHandle<Self>,
1308        app: &mut App,
1309        result: &mut BoxHitTestResult<'_>,
1310        position: Offset,
1311    ) -> bool {
1312        RenderProxyBoxMixin::hit_test_children(self, app, result, position)
1313    }
1314
1315    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
1316        RenderProxyBoxMixin::compute_min_intrinsic_width(self, app, height)
1317    }
1318
1319    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
1320        RenderProxyBoxMixin::compute_max_intrinsic_width(self, app, height)
1321    }
1322
1323    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
1324        RenderProxyBoxMixin::compute_min_intrinsic_height(self, app, width)
1325    }
1326
1327    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
1328        RenderProxyBoxMixin::compute_max_intrinsic_height(self, app, width)
1329    }
1330
1331    fn compute_distance_to_actual_baseline(
1332        self: RenderHandle<Self>,
1333        app: &mut App,
1334        baseline: TextBaseline,
1335    ) -> Option<f64> {
1336        RenderProxyBoxMixin::compute_distance_to_actual_baseline(self, app, baseline)
1337    }
1338
1339    fn compute_dry_baseline(
1340        self: RenderHandle<Self>,
1341        app: &mut App,
1342        constraints: BoxConstraints,
1343        baseline: TextBaseline,
1344    ) -> Option<f64> {
1345        RenderProxyBoxMixin::compute_dry_baseline(self, app, constraints, baseline)
1346    }
1347
1348    fn compute_dry_layout(
1349        self: RenderHandle<Self>,
1350        app: &mut App,
1351        constraints: BoxConstraints,
1352    ) -> Size {
1353        RenderProxyBoxMixin::compute_dry_layout(self, app, constraints)
1354    }
1355}
1356
1357/// A [`TapRegion`] that adds its children to the tap region group for widgets
1358/// based on the [`EditableText`] text editing widget, such as `TextField` and
1359/// `CupertinoTextField`.
1360///
1361/// Widgets that are wrapped with a [`TextFieldTapRegion`] are considered to be
1362/// part of a text field for purposes of unfocus behavior. So, when the user
1363/// taps on them, the currently focused text field won't be unfocused by
1364/// default.
1365///
1366/// See also:
1367///
1368///  * [`TapRegion`], the widget that this widget uses to add widgets to the group
1369///    of text fields.
1370///
1371/// Dart's `class TextFieldTapRegion extends TapRegion`: a distinct widget type
1372/// whose behaviour is [`TapRegion`]'s with [`group_id`](TapRegion::group_id) defaulting to
1373/// [`TypeId::of::<EditableText>()`].
1374pub struct TextFieldTapRegion {
1375    /// See [`TapRegion::key`].
1376    pub key: Option<KeyRef>,
1377    /// See [`TapRegion::child`].
1378    pub child: WidgetRef,
1379    /// See [`TapRegion::enabled`].
1380    pub enabled: bool,
1381    /// See [`TapRegion::behavior`].
1382    pub behavior: HitTestBehavior,
1383    /// See [`TapRegion::on_tap_outside`].
1384    pub on_tap_outside: Option<TapRegionCallback>,
1385    /// See [`TapRegion::on_tap_inside`].
1386    pub on_tap_inside: Option<TapRegionCallback>,
1387    /// See [`TapRegion::on_tap_up_outside`].
1388    pub on_tap_up_outside: Option<TapRegionUpCallback>,
1389    /// See [`TapRegion::on_tap_up_inside`].
1390    pub on_tap_up_inside: Option<TapRegionUpCallback>,
1391    /// See [`TapRegion::group_id`]. Defaults to [`TypeId::of::<EditableText>()`].
1392    pub group_id: Option<TapRegionGroupId>,
1393    /// See [`TapRegion::consume_outside_taps`].
1394    pub consume_outside_taps: bool,
1395    /// See [`TapRegion::debug_label`].
1396    pub debug_label: Option<String>,
1397}
1398
1399impl TextFieldTapRegion {
1400    /// Creates a [`TextFieldTapRegion`].
1401    ///
1402    /// The [`child`](Self::child) field is required.
1403    #[cfg_attr(debug_assertions, track_caller)]
1404    pub fn new<K>(child: impl IntoWidget<K>) -> TextFieldTapRegion {
1405        TextFieldTapRegion {
1406            key: None,
1407            child: child.into_widget(),
1408            enabled: true,
1409            behavior: HitTestBehavior::DeferToChild,
1410            on_tap_outside: None,
1411            on_tap_inside: None,
1412            on_tap_up_outside: None,
1413            on_tap_up_inside: None,
1414            group_id: Some(TapRegionGroupId::Type(TypeId::of::<EditableText>())),
1415            consume_outside_taps: false,
1416            debug_label: None,
1417        }
1418    }
1419
1420    /// Dart `TextFieldTapRegion(key:)`.
1421    pub fn key(mut self, key: KeyRef) -> TextFieldTapRegion {
1422        self.key = Some(key);
1423        self
1424    }
1425
1426    /// Dart `TextFieldTapRegion(enabled:)`.
1427    pub fn enabled(mut self, enabled: bool) -> TextFieldTapRegion {
1428        self.enabled = enabled;
1429        self
1430    }
1431
1432    /// Dart `TextFieldTapRegion(behavior:)`.
1433    pub fn behavior(mut self, behavior: HitTestBehavior) -> TextFieldTapRegion {
1434        self.behavior = behavior;
1435        self
1436    }
1437
1438    /// Dart `TextFieldTapRegion(onTapOutside:)`.
1439    pub fn on_tap_outside(mut self, on_tap_outside: TapRegionCallback) -> TextFieldTapRegion {
1440        self.on_tap_outside = Some(on_tap_outside);
1441        self
1442    }
1443
1444    /// Dart `TextFieldTapRegion(onTapInside:)`.
1445    pub fn on_tap_inside(mut self, on_tap_inside: TapRegionCallback) -> TextFieldTapRegion {
1446        self.on_tap_inside = Some(on_tap_inside);
1447        self
1448    }
1449
1450    /// Dart `TextFieldTapRegion(onTapUpOutside:)`.
1451    pub fn on_tap_up_outside(
1452        mut self,
1453        on_tap_up_outside: TapRegionUpCallback,
1454    ) -> TextFieldTapRegion {
1455        self.on_tap_up_outside = Some(on_tap_up_outside);
1456        self
1457    }
1458
1459    /// Dart `TextFieldTapRegion(onTapUpInside:)`.
1460    pub fn on_tap_up_inside(mut self, on_tap_up_inside: TapRegionUpCallback) -> TextFieldTapRegion {
1461        self.on_tap_up_inside = Some(on_tap_up_inside);
1462        self
1463    }
1464
1465    /// Dart `TextFieldTapRegion(groupId:)`.
1466    pub fn group_id(mut self, group_id: impl Into<TapRegionGroupId>) -> TextFieldTapRegion {
1467        self.group_id = Some(group_id.into());
1468        self
1469    }
1470
1471    /// Dart `TextFieldTapRegion(consumeOutsideTaps:)`.
1472    pub fn consume_outside_taps(mut self, consume_outside_taps: bool) -> TextFieldTapRegion {
1473        self.consume_outside_taps = consume_outside_taps;
1474        self
1475    }
1476
1477    /// Dart `TextFieldTapRegion(debugLabel:)`.
1478    pub fn debug_label(mut self, debug_label: impl Into<String>) -> TextFieldTapRegion {
1479        self.debug_label = if cfg!(debug_assertions) {
1480            Some(debug_label.into())
1481        } else {
1482            None
1483        };
1484        self
1485    }
1486
1487    fn as_tap_region(&self) -> TapRegion {
1488        TapRegion {
1489            key: self.key.clone(),
1490            child: self.child.clone(),
1491            enabled: self.enabled,
1492            behavior: self.behavior,
1493            on_tap_outside: self.on_tap_outside.clone(),
1494            on_tap_inside: self.on_tap_inside.clone(),
1495            on_tap_up_outside: self.on_tap_up_outside.clone(),
1496            on_tap_up_inside: self.on_tap_up_inside.clone(),
1497            group_id: self.group_id,
1498            consume_outside_taps: self.consume_outside_taps,
1499            debug_label: self.debug_label.clone(),
1500        }
1501    }
1502}
1503
1504impl RenderObjectWidget for TextFieldTapRegion {
1505    type RenderObject = RenderTapRegion;
1506
1507    fn key(&self) -> Option<&KeyRef> {
1508        self.key.as_ref()
1509    }
1510
1511    fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject {
1512        self.as_tap_region().create_render_object(app, context)
1513    }
1514
1515    fn update_render_object(
1516        &self,
1517        app: &mut App,
1518        context: BuildContext,
1519        render_object: RenderHandle<RenderTapRegion>,
1520    ) {
1521        self.as_tap_region()
1522            .apply_to_render_object(app, context, render_object);
1523    }
1524}
1525
1526impl SingleChildRenderObjectWidget for TextFieldTapRegion {
1527    fn child(&self) -> Option<&WidgetRef> {
1528        Some(&self.child)
1529    }
1530}
1531
1532impl Debug for TextFieldTapRegion {
1533    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1534        self.as_tap_region().fmt(f)
1535    }
1536}
1537
1538#[cfg(test)]
1539mod tests {
1540    use std::cell::Cell;
1541    use std::rc::Rc;
1542
1543    use waft_embedder::Offset;
1544    use waft_foundation::{AppCell, DiagnosticLevel};
1545    use waft_gestures::{HitTestResult, PointerDownEvent, PointerEvent};
1546    use waft_rendering::{
1547        BoxHitTestResult, HitTestBehavior, RenderBox, RenderObjectWithChildMixin,
1548    };
1549
1550    use super::*;
1551    use crate::test_harness::Harness;
1552    use crate::widgets::basic::SizedBox;
1553
1554    fn tree(child: WidgetRef) -> WidgetRef {
1555        TapRegionSurface::new(child).into_widget()
1556    }
1557
1558    #[test]
1559    fn registers_on_layout_and_unregisters_when_disabled() {
1560        let cell = AppCell::new();
1561        let mut app = cell.borrow_mut();
1562        let harness = Harness::mount(
1563            &mut app,
1564            tree(
1565                TapRegion::new(SizedBox::expand())
1566                    .behavior(HitTestBehavior::Opaque)
1567                    .into_widget(),
1568            ),
1569        );
1570        harness.pump(&mut app);
1571
1572        let surface = harness
1573            .render_root(&app)
1574            .child(&app)
1575            .expect("the surface")
1576            .as_object()
1577            .downcast::<RenderTapRegionSurface>(&app)
1578            .expect("RenderTapRegionSurface");
1579        let region = surface
1580            .child(&app)
1581            .expect("the region")
1582            .as_object()
1583            .downcast::<RenderTapRegion>(&app)
1584            .expect("RenderTapRegion");
1585        assert!(surface.get(&app).registered_regions.contains(&region));
1586        assert!(region.get(&app).is_registered);
1587
1588        harness.set_child(
1589            &mut app,
1590            tree(
1591                TapRegion::new(SizedBox::expand())
1592                    .enabled(false)
1593                    .behavior(HitTestBehavior::Opaque)
1594                    .into_widget(),
1595            ),
1596        );
1597        harness.pump(&mut app);
1598
1599        let surface = harness
1600            .render_root(&app)
1601            .child(&app)
1602            .expect("the surface")
1603            .as_object()
1604            .downcast::<RenderTapRegionSurface>(&app)
1605            .expect("RenderTapRegionSurface");
1606        assert!(surface.get(&app).registered_regions.is_empty());
1607    }
1608
1609    #[test]
1610    fn hit_test_classifies_inside_and_outside() {
1611        let cell = AppCell::new();
1612        let mut app = cell.borrow_mut();
1613        let inside = Rc::new(Cell::new(0u32));
1614        let outside = Rc::new(Cell::new(0u32));
1615        let on_inside = {
1616            let inside = Rc::clone(&inside);
1617            Rc::new(move |_app: &mut App, _event: PointerDownEvent| {
1618                inside.set(inside.get() + 1);
1619            }) as TapRegionCallback
1620        };
1621        let on_outside = {
1622            let outside = Rc::clone(&outside);
1623            Rc::new(move |_app: &mut App, _event: PointerDownEvent| {
1624                outside.set(outside.get() + 1);
1625            }) as TapRegionCallback
1626        };
1627
1628        let harness = Harness::mount(
1629            &mut app,
1630            tree(
1631                TapRegion::new(
1632                    SizedBox {
1633                        width: Some(50.0),
1634                        height: Some(50.0),
1635                        ..Default::default()
1636                    }
1637                    .into_widget(),
1638                )
1639                .behavior(HitTestBehavior::Opaque)
1640                .on_tap_inside(on_inside)
1641                .on_tap_outside(on_outside)
1642                .into_widget(),
1643            ),
1644        );
1645        harness.pump(&mut app);
1646
1647        let surface = harness
1648            .render_root(&app)
1649            .child(&app)
1650            .expect("the surface")
1651            .as_object()
1652            .downcast::<RenderTapRegionSurface>(&app)
1653            .expect("RenderTapRegionSurface");
1654
1655        let mut result = HitTestResult::new();
1656        {
1657            let mut box_result = BoxHitTestResult::wrap(&mut result);
1658            assert!(RenderBox::hit_test(
1659                surface,
1660                &mut app,
1661                &mut box_result,
1662                Offset::new(10.0, 10.0)
1663            ));
1664        }
1665        let event = PointerEvent::Down(PointerDownEvent {
1666            position: Offset::new(10.0, 10.0),
1667            ..PointerDownEvent::default()
1668        });
1669        for entry in result.path() {
1670            entry.target().handle_event(&mut app, &event, entry);
1671        }
1672        assert_eq!(inside.get(), 1);
1673        assert_eq!(outside.get(), 0);
1674    }
1675
1676    #[test]
1677    fn text_field_tap_region_defaults_group_id_to_editable_text() {
1678        let region = TextFieldTapRegion::new(SizedBox::expand());
1679        assert_eq!(
1680            region.group_id,
1681            Some(TapRegionGroupId::Type(TypeId::of::<EditableText>()))
1682        );
1683    }
1684
1685    /// `tap_region.dart`'s `RenderTapRegion.debugFillProperties`: the behavior it inherits from
1686    /// its proxy box, its label, its group, and `DISABLED` when it cannot register.
1687    #[test]
1688    fn a_tap_region_dump_shows_its_label_group_and_disabled_state() {
1689        let cell = AppCell::new();
1690        let mut app = cell.borrow_mut();
1691        let harness = Harness::mount(
1692            &mut app,
1693            tree(
1694                TapRegion::new(SizedBox::expand())
1695                    .behavior(HitTestBehavior::Opaque)
1696                    .enabled(false)
1697                    .debug_label("region")
1698                    .group_id(TypeId::of::<EditableText>())
1699                    .into_widget(),
1700            ),
1701        );
1702        harness.pump(&mut app);
1703
1704        let surface = harness
1705            .render_root(&app)
1706            .child(&app)
1707            .expect("the surface")
1708            .as_object()
1709            .downcast::<RenderTapRegionSurface>(&app)
1710            .expect("RenderTapRegionSurface");
1711        let region = surface
1712            .child(&app)
1713            .expect("the region")
1714            .as_object()
1715            .downcast::<RenderTapRegion>(&app)
1716            .expect("RenderTapRegion");
1717
1718        let dump = region
1719            .as_object()
1720            .to_string_deep_with(&app, DiagnosticLevel::Info);
1721        assert!(dump.contains("behavior: opaque"), "{dump}");
1722        assert!(dump.contains("debugLabel: region"), "{dump}");
1723        assert!(dump.contains("groupId: "), "{dump}");
1724        assert!(dump.contains("DISABLED"), "{dump}");
1725    }
1726}