Skip to main content

waft_widgets/widgets/
visibility.rs

1//! Flutter counterpart: the `Visibility` half of `widgets/indexed_stack.dart`.
2//!
3//! Flutter deleted `widgets/visibility.dart` and moved `Visibility`, `SliverVisibility` and
4//! their shared `_VisibilityScope` next to `IndexedStack`. `IndexedStack` and the scope live
5//! in `basic.rs`, where the rest of `indexed_stack.dart` was ported; `Visibility` keeps the
6//! file name Flutter used until then. `SliverVisibility` waits on the sliver widgets it
7//! builds (see `PORTING.md`).
8
9use waft_embedder::{Matrix4, Offset, Size, TextBaseline};
10use waft_foundation::{App, DiagnosticPropertiesBuilder, FlagProperty};
11use waft_rendering::{
12    AnyRenderBox, AnyRenderObject, BoxConstraints, BoxHitTestResult, PaintingContext, RenderBox,
13    RenderBoxData, RenderHandle, RenderObject, RenderObjectData, RenderObjectWithChildData,
14    RenderObjectWithChildMixin, RenderProxyBoxMixin,
15};
16
17use crate::framework::{
18    BuildContext, IntoWidget, KeyRef, RenderObjectWidget, SingleChildRenderObjectWidget,
19    StatelessWidget, WidgetRef, downcast_widget,
20};
21use crate::widgets::basic::{IgnorePointer, Offstage, SizedBox, VisibilityScope};
22use crate::widgets::focus_scope::ExcludeFocus;
23use crate::widgets::ticker_provider::TickerMode;
24
25/// Whether to show or hide a child.
26///
27/// By default, the [`visible`](Self::visible) property controls whether the
28/// [`child`](Self::child) is included in the subtree or not; when it is not
29/// [`visible`](Self::visible), the [`replacement`](Self::replacement) child (typically a
30/// zero-sized box) is included instead.
31///
32/// A variety of flags can be used to tweak exactly how the child is hidden.
33/// (Changing the flags dynamically is discouraged, as it can cause the
34/// [`child`](Self::child) subtree to be rebuilt, with any state in the subtree being
35/// discarded. Typically, only the [`visible`](Self::visible) flag is changed dynamically.)
36///
37/// These widgets provide some of the facets of this one:
38///
39///  * [`Opacity`](crate::Opacity), which can stop its child from being painted.
40///  * [`Offstage`], which can stop its child from being laid out or painted.
41///  * [`TickerMode`], which can stop its child from being animated.
42///  * `ExcludeSemantics`, which can hide the child from accessibility tools.
43///  * [`IgnorePointer`], which can disable touch interactions with the child.
44///
45/// Using this widget is not necessary to hide children. The simplest way to hide a child is
46/// just to not include it, or, if a child _must_ be given (e.g. because the parent is a
47/// stateless widget) then to use [`SizedBox::shrink`] instead of the child that would
48/// otherwise be included.
49///
50/// See also:
51///
52///  * `AnimatedSwitcher`, which can fade from one child to the next as the subtree changes.
53///  * `AnimatedCrossFade`, which can fade between two specific children.
54///  * `SliverVisibility`, the sliver equivalent of this widget.
55#[derive(Debug)]
56pub struct Visibility {
57    /// See [`Widget::key`](crate::Widget::key).
58    pub key: Option<KeyRef>,
59
60    /// The widget to show or hide, as controlled by [`visible`](Self::visible).
61    pub child: WidgetRef,
62
63    /// The widget to use when the child is not [`visible`](Self::visible), assuming that none
64    /// of the `maintain` flags (in particular, [`maintain_state`](Self::maintain_state)) are
65    /// set.
66    ///
67    /// The normal behavior is to replace the widget with a zero by zero box
68    /// ([`SizedBox::shrink`]).
69    ///
70    /// See also:
71    ///
72    ///  * `AnimatedCrossFade`, which can animate between two children.
73    pub replacement: WidgetRef,
74
75    /// Switches between showing the [`child`](Self::child) or hiding it.
76    ///
77    /// The `maintain` flags should be set to the same values regardless of the state of the
78    /// [`visible`](Self::visible) property, otherwise they will not operate correctly
79    /// (specifically, the state will be lost regardless of the state of
80    /// [`maintain_state`](Self::maintain_state) whenever any of the `maintain` flags are
81    /// changed, since doing so will result in a subtree shape change).
82    ///
83    /// Unless [`maintain_state`](Self::maintain_state) is set, the [`child`](Self::child)
84    /// subtree will be disposed (removed from the tree) while hidden.
85    pub visible: bool,
86
87    /// Whether to maintain the `State` objects of the [`child`](Self::child) subtree when it
88    /// is not [`visible`](Self::visible).
89    ///
90    /// Keeping the state of the subtree is potentially expensive (because it means all the
91    /// objects are still in memory; their resources are not released). It should only be
92    /// maintained if it cannot be recreated on demand. One example of when the state would be
93    /// maintained is if the child subtree contains a [`Navigator`](crate::Navigator), since
94    /// that widget maintains elaborate state that cannot be recreated on the fly.
95    ///
96    /// If this property is true, an [`Offstage`] widget is used to hide the child instead of
97    /// replacing it with [`replacement`](Self::replacement).
98    ///
99    /// If this property is false, then [`maintain_animation`](Self::maintain_animation) must
100    /// also be false.
101    ///
102    /// If this property is false, then [`maintain_focusability`](Self::maintain_focusability)
103    /// must also be false.
104    ///
105    /// Dynamically changing this value may cause the current state of the subtree to be lost
106    /// (and a new instance of the subtree, with new `State` objects, to be immediately created
107    /// if [`visible`](Self::visible) is true).
108    pub maintain_state: bool,
109
110    /// Whether to maintain animations within the [`child`](Self::child) subtree when it is not
111    /// [`visible`](Self::visible).
112    ///
113    /// To set this, [`maintain_state`](Self::maintain_state) must also be set.
114    ///
115    /// Keeping animations active when the widget is not visible is even more expensive than
116    /// only maintaining the state.
117    ///
118    /// One example when this might be useful is if the subtree is animating its layout in time
119    /// with an `AnimationController`, and the result of that layout is being used to influence
120    /// some other logic. If this flag is false, then any `AnimationController`s hosted inside
121    /// the [`child`](Self::child) subtree will be muted while the [`visible`](Self::visible)
122    /// flag is false.
123    ///
124    /// If this property is true, no [`TickerMode`] widget is used.
125    ///
126    /// If this property is false, then [`maintain_size`](Self::maintain_size) must also be
127    /// false.
128    ///
129    /// Dynamically changing this value may cause the current state of the subtree to be lost
130    /// (and a new instance of the subtree, with new `State` objects, to be immediately created
131    /// if [`visible`](Self::visible) is true).
132    pub maintain_animation: bool,
133
134    /// Whether to maintain space for where the widget would have been.
135    ///
136    /// To set this, [`maintain_animation`](Self::maintain_animation) and
137    /// [`maintain_state`](Self::maintain_state) must also be set.
138    ///
139    /// Maintaining the size when the widget is not [`visible`](Self::visible) is not notably
140    /// more expensive than just keeping animations running without maintaining the size, and
141    /// may in some circumstances be slightly cheaper if the subtree is simple and the
142    /// [`visible`](Self::visible) property is frequently toggled, since it avoids triggering a
143    /// layout change when the [`visible`](Self::visible) property is toggled. If the
144    /// [`child`](Self::child) subtree is not trivial then it is significantly cheaper to not
145    /// even keep the state (see [`maintain_state`](Self::maintain_state)).
146    ///
147    /// If this property is false, [`Offstage`] is used.
148    ///
149    /// If this property is false, then [`maintain_semantics`](Self::maintain_semantics) and
150    /// [`maintain_interactivity`](Self::maintain_interactivity) must also be false.
151    ///
152    /// Dynamically changing this value may cause the current state of the subtree to be lost
153    /// (and a new instance of the subtree, with new `State` objects, to be immediately created
154    /// if [`visible`](Self::visible) is true).
155    ///
156    /// See also:
157    ///
158    ///  * `AnimatedOpacity` and [`FadeTransition`](crate::FadeTransition), which apply
159    ///    animations to the opacity for a more subtle effect.
160    pub maintain_size: bool,
161
162    /// Whether to maintain the semantics for the widget when it is hidden (e.g. for
163    /// accessibility).
164    ///
165    /// To set this, [`maintain_size`](Self::maintain_size) must also be set.
166    ///
167    /// By default, with [`maintain_semantics`](Self::maintain_semantics) set to false, the
168    /// [`child`](Self::child) is not visible to accessibility tools when it is hidden from the
169    /// user. If this flag is set to true, then accessibility tools will report the widget as
170    /// if it was present.
171    ///
172    /// Nothing reads this flag while accessibility is deferred (see `PORTING.md`).
173    pub maintain_semantics: bool,
174
175    /// Whether to allow the widget to be interactive when hidden.
176    ///
177    /// To set this, [`maintain_size`](Self::maintain_size) must also be set.
178    ///
179    /// By default, with [`maintain_interactivity`](Self::maintain_interactivity) set to false,
180    /// touch events cannot reach the [`child`](Self::child) when it is hidden from the user.
181    /// If this flag is set to true, then touch events will nonetheless be passed through.
182    pub maintain_interactivity: bool,
183
184    /// Whether to allow the widget to receive focus when hidden. Only in effect if
185    /// [`visible`](Self::visible) is false.
186    ///
187    /// To set this to true, [`maintain_state`](Self::maintain_state) must also be set to true.
188    ///
189    /// By default, with [`maintain_focusability`](Self::maintain_focusability) set to false,
190    /// focus events cannot reach the [`child`](Self::child) when this widget is not
191    /// [`visible`](Self::visible) because an [`ExcludeFocus`] widget is used to exclude the
192    /// child subtree from the focus tree. If this flag is set to true, then focus events will
193    /// reach the child subtree.
194    pub maintain_focusability: bool,
195}
196
197impl Visibility {
198    /// Control whether the given [`child`](Self::child) is [`visible`](Self::visible); Dart's
199    /// optional named arguments are the setters.
200    ///
201    /// The [`maintain_semantics`](Self::maintain_semantics) and
202    /// [`maintain_interactivity`](Self::maintain_interactivity) flags can only be set if
203    /// [`maintain_size`](Self::maintain_size) is set.
204    ///
205    /// The [`maintain_size`](Self::maintain_size) flag can only be set if
206    /// [`maintain_animation`](Self::maintain_animation) is set.
207    ///
208    /// The [`maintain_animation`](Self::maintain_animation) flag can only be set if
209    /// [`maintain_state`](Self::maintain_state) is set.
210    #[cfg_attr(debug_assertions, track_caller)]
211    pub fn new<K>(child: impl IntoWidget<K>) -> Visibility {
212        Visibility {
213            key: None,
214            child: child.into_widget(),
215            replacement: SizedBox::shrink().into_widget(),
216            visible: true,
217            maintain_state: false,
218            maintain_animation: false,
219            maintain_size: false,
220            maintain_semantics: false,
221            maintain_interactivity: false,
222            maintain_focusability: false,
223        }
224    }
225
226    /// Control whether the given [`child`](Self::child) is [`visible`](Self::visible).
227    ///
228    /// This is equivalent to [`Visibility::new`] with all "maintain" fields set to true. This
229    /// constructor should be used in place of an [`Opacity`](crate::Opacity) widget that only
230    /// takes on values of `0.0` or `1.0`, as it avoids extra compositing when fully opaque.
231    #[cfg_attr(debug_assertions, track_caller)]
232    pub fn maintain<K>(child: impl IntoWidget<K>) -> Visibility {
233        Visibility {
234            key: None,
235            child: child.into_widget(),
236            // Unused since maintain_state is always true.
237            replacement: SizedBox::shrink().into_widget(),
238            visible: true,
239            maintain_state: true,
240            maintain_animation: true,
241            maintain_size: true,
242            maintain_semantics: true,
243            maintain_interactivity: true,
244            maintain_focusability: true,
245        }
246    }
247
248    /// Dart `Visibility(key:)`.
249    pub fn key(mut self, key: KeyRef) -> Visibility {
250        self.key = Some(key);
251        self
252    }
253
254    /// Dart `Visibility(replacement:)`.
255    #[cfg_attr(debug_assertions, track_caller)]
256    pub fn replacement<K>(mut self, replacement: impl IntoWidget<K>) -> Visibility {
257        self.replacement = replacement.into_widget();
258        self
259    }
260
261    /// Dart `Visibility(visible:)`.
262    pub fn visible(mut self, visible: bool) -> Visibility {
263        self.visible = visible;
264        self
265    }
266
267    /// Dart `Visibility(maintainState:)`.
268    pub fn maintain_state(mut self, maintain_state: bool) -> Visibility {
269        self.maintain_state = maintain_state;
270        self
271    }
272
273    /// Dart `Visibility(maintainAnimation:)`.
274    pub fn maintain_animation(mut self, maintain_animation: bool) -> Visibility {
275        self.maintain_animation = maintain_animation;
276        self
277    }
278
279    /// Dart `Visibility(maintainSize:)`.
280    pub fn maintain_size(mut self, maintain_size: bool) -> Visibility {
281        self.maintain_size = maintain_size;
282        self
283    }
284
285    /// Dart `Visibility(maintainSemantics:)`.
286    pub fn maintain_semantics(mut self, maintain_semantics: bool) -> Visibility {
287        self.maintain_semantics = maintain_semantics;
288        self
289    }
290
291    /// Dart `Visibility(maintainInteractivity:)`.
292    pub fn maintain_interactivity(mut self, maintain_interactivity: bool) -> Visibility {
293        self.maintain_interactivity = maintain_interactivity;
294        self
295    }
296
297    /// Dart `Visibility(maintainFocusability:)`.
298    pub fn maintain_focusability(mut self, maintain_focusability: bool) -> Visibility {
299        self.maintain_focusability = maintain_focusability;
300        self
301    }
302
303    /// Tells the visibility state of an element in the tree based off its ancestor
304    /// [`Visibility`] elements.
305    ///
306    /// If there's one or more [`Visibility`] widgets in the ancestor tree, this will return
307    /// true if and only if all of those widgets have [`visible`](Self::visible) set to true.
308    /// If there is no [`Visibility`] widget in the ancestor tree of the specified build
309    /// context, this will return true.
310    ///
311    /// This will register a dependency from the specified context on any [`Visibility`]
312    /// elements in the ancestor tree, such that if any of their visibilities changes, the
313    /// specified context will be rebuilt.
314    pub fn of(app: &mut App, context: BuildContext) -> bool {
315        let mut is_visible = true;
316        let mut ancestor_context = context;
317        let mut ancestor =
318            ancestor_context.get_element_for_inherited_widget_of_exact_type::<VisibilityScope>(app);
319        while is_visible && let Some(current) = ancestor {
320            let widget = context.depend_on_inherited_element(app, current, None);
321            let scope = downcast_widget::<VisibilityScope>(&*widget).expect("a VisibilityScope");
322            is_visible = scope.is_visible;
323            current.visit_ancestor_elements(app, &mut |parent| {
324                ancestor_context = parent;
325                false
326            });
327            ancestor = ancestor_context
328                .get_element_for_inherited_widget_of_exact_type::<VisibilityScope>(app);
329        }
330        is_visible
331    }
332}
333
334impl StatelessWidget for Visibility {
335    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
336        properties.add(
337            FlagProperty::new("visible", Some(self.visible))
338                .if_false("hidden")
339                .if_true("visible"),
340        );
341        properties.add(
342            FlagProperty::new("maintainState", Some(self.maintain_state)).if_false("maintainState"),
343        );
344        properties.add(
345            FlagProperty::new("maintainAnimation", Some(self.maintain_animation))
346                .if_false("maintainAnimation"),
347        );
348        properties.add(
349            FlagProperty::new("maintainSize", Some(self.maintain_size)).if_false("maintainSize"),
350        );
351        properties.add(
352            FlagProperty::new("maintainSemantics", Some(self.maintain_semantics))
353                .if_false("maintainSemantics"),
354        );
355        properties.add(
356            FlagProperty::new("maintainInteractivity", Some(self.maintain_interactivity))
357                .if_false("maintainInteractivity"),
358        );
359    }
360
361    fn key(&self) -> Option<&KeyRef> {
362        self.key.as_ref()
363    }
364
365    fn debug_check_constructor(&self) {
366        debug_assert!(
367            self.maintain_state || !self.maintain_animation,
368            "Cannot maintain animations if the state is not also maintained."
369        );
370        debug_assert!(
371            self.maintain_animation || !self.maintain_size,
372            "Cannot maintain size if animations are not maintained."
373        );
374        debug_assert!(
375            self.maintain_size || !self.maintain_semantics,
376            "Cannot maintain semantics if size is not maintained."
377        );
378        debug_assert!(
379            self.maintain_size || !self.maintain_interactivity,
380            "Cannot maintain interactivity if size is not maintained."
381        );
382        debug_assert!(
383            self.maintain_state || !self.maintain_focusability,
384            "Cannot maintain focusability if the state is not also maintained."
385        );
386    }
387
388    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
389        let mut result = ExcludeFocus::new(self.child.clone())
390            .excluding(!self.visible && !self.maintain_focusability)
391            .into_widget();
392        if self.maintain_size {
393            result = RawVisibility::new(self.visible)
394                .child(
395                    IgnorePointer::new()
396                        .ignoring(!self.visible && !self.maintain_interactivity)
397                        .child(result),
398                )
399                .into_widget();
400        } else {
401            debug_assert!(!self.maintain_interactivity);
402            debug_assert!(!self.maintain_semantics);
403            debug_assert!(!self.maintain_size);
404            if self.maintain_state {
405                if !self.maintain_animation {
406                    result = TickerMode::new(self.visible, result).into_widget();
407                }
408                result = Offstage::new()
409                    .offstage(!self.visible)
410                    .child(result)
411                    .into_widget();
412            } else {
413                debug_assert!(!self.maintain_animation);
414                debug_assert!(!self.maintain_state);
415                result = if self.visible {
416                    self.child.clone()
417                } else {
418                    self.replacement.clone()
419                };
420            }
421        }
422        VisibilityScope {
423            is_visible: self.visible,
424            child: result,
425        }
426        .into_widget()
427    }
428}
429
430/// A widget that conditionally hides its child, but without the forced compositing of
431/// [`Opacity`](crate::Opacity).
432///
433/// A fully opaque [`Opacity`](crate::Opacity) widget is required to leave its opacity layer in
434/// the layer tree. This forces all parent render objects to also composite, which can break a
435/// simple scene into many different layers. This can be significantly more expensive, so the
436/// issue is avoided by a specialized render object that does not ever force compositing.
437///
438/// Dart's `_Visibility`, which takes this name because [`Visibility`] holds its own.
439#[derive(Debug)]
440struct RawVisibility {
441    visible: bool,
442    child: Option<WidgetRef>,
443}
444
445impl RawVisibility {
446    fn new(visible: bool) -> RawVisibility {
447        RawVisibility {
448            visible,
449            child: None,
450        }
451    }
452
453    #[cfg_attr(debug_assertions, track_caller)]
454    fn child<K>(mut self, child: impl IntoWidget<K>) -> RawVisibility {
455        self.child = Some(child.into_widget());
456        self
457    }
458}
459
460impl RenderObjectWidget for RawVisibility {
461    type RenderObject = RenderVisibility;
462
463    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
464        RenderVisibility::new(app, self.visible, None).as_object()
465    }
466
467    fn update_render_object(
468        &self,
469        app: &mut App,
470        _context: BuildContext,
471        render_object: RenderHandle<RenderVisibility>,
472    ) {
473        render_object.set_visible(app, self.visible);
474    }
475}
476
477impl SingleChildRenderObjectWidget for RawVisibility {
478    fn child(&self) -> Option<&WidgetRef> {
479        self.child.as_ref()
480    }
481}
482
483/// The render object of [`RawVisibility`]: a proxy box that skips painting its child while it
484/// is not [`visible`](Self::visible).
485///
486/// Dart's `_RenderVisibility`.
487struct RenderVisibility {
488    render_object: RenderObjectData,
489    render_box: RenderBoxData,
490    child: RenderObjectWithChildData<AnyRenderBox>,
491    visible: bool,
492}
493
494impl RenderVisibility {
495    fn new(
496        app: &mut App,
497        visible: bool,
498        child: Option<AnyRenderBox>,
499    ) -> RenderHandle<RenderVisibility> {
500        let this = RenderHandle::new_box(
501            app,
502            RenderVisibility {
503                render_object: RenderObjectData::new(),
504                render_box: RenderBoxData::new(),
505                child: RenderObjectWithChildData::new(),
506                visible,
507            },
508        );
509        this.set_child(app, child);
510        this
511    }
512
513    /// Whether the child is painted.
514    fn visible(self: RenderHandle<Self>, app: &App) -> bool {
515        self.get(app).visible
516    }
517
518    /// Sets [`visible`](Self::visible).
519    fn set_visible(self: RenderHandle<Self>, app: &mut App, value: bool) {
520        if value == self.visible(app) {
521            return;
522        }
523        self.get_mut(app).visible = value;
524        self.mark_needs_paint(app);
525    }
526}
527
528impl RenderObjectWithChildMixin for RenderVisibility {
529    type ChildType = AnyRenderBox;
530
531    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
532        &self.get(app).child
533    }
534
535    fn child_data_mut(
536        self: RenderHandle<Self>,
537        app: &mut App,
538    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
539        &mut self.get_mut(app).child
540    }
541}
542
543impl RenderProxyBoxMixin for RenderVisibility {}
544
545impl RenderObject for RenderVisibility {
546    waft_rendering::render_object_accessors!();
547
548    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
549        RenderProxyBoxMixin::perform_layout(self, app);
550    }
551
552    fn paint(
553        self: RenderHandle<Self>,
554        app: &mut App,
555        context: &mut PaintingContext,
556        offset: Offset,
557    ) {
558        if !self.visible(app) {
559            return;
560        }
561        RenderProxyBoxMixin::paint(self, app, context, offset);
562    }
563
564    fn visit_children(
565        self: RenderHandle<Self>,
566        app: &App,
567        visitor: &mut dyn FnMut(AnyRenderObject),
568    ) {
569        if let Some(child) = self.child(app) {
570            visitor(child.as_object());
571        }
572    }
573}
574
575impl RenderBox for RenderVisibility {
576    waft_rendering::render_box_accessors!();
577
578    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
579        RenderProxyBoxMixin::setup_parent_data(self, app, child);
580    }
581
582    fn apply_paint_transform(
583        self: RenderHandle<Self>,
584        app: &App,
585        child: AnyRenderObject,
586        transform: &mut Matrix4,
587    ) {
588        RenderProxyBoxMixin::apply_paint_transform(self, app, child, transform);
589    }
590
591    fn hit_test_children(
592        self: RenderHandle<Self>,
593        app: &mut App,
594        result: &mut BoxHitTestResult<'_>,
595        position: Offset,
596    ) -> bool {
597        RenderProxyBoxMixin::hit_test_children(self, app, result, position)
598    }
599
600    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
601        RenderProxyBoxMixin::compute_min_intrinsic_width(self, app, height)
602    }
603
604    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
605        RenderProxyBoxMixin::compute_max_intrinsic_width(self, app, height)
606    }
607
608    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
609        RenderProxyBoxMixin::compute_min_intrinsic_height(self, app, width)
610    }
611
612    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
613        RenderProxyBoxMixin::compute_max_intrinsic_height(self, app, width)
614    }
615
616    fn compute_distance_to_actual_baseline(
617        self: RenderHandle<Self>,
618        app: &mut App,
619        baseline: TextBaseline,
620    ) -> Option<f64> {
621        RenderProxyBoxMixin::compute_distance_to_actual_baseline(self, app, baseline)
622    }
623
624    fn compute_dry_baseline(
625        self: RenderHandle<Self>,
626        app: &mut App,
627        constraints: BoxConstraints,
628        baseline: TextBaseline,
629    ) -> Option<f64> {
630        RenderProxyBoxMixin::compute_dry_baseline(self, app, constraints, baseline)
631    }
632
633    fn compute_dry_layout(
634        self: RenderHandle<Self>,
635        app: &mut App,
636        constraints: BoxConstraints,
637    ) -> Size {
638        RenderProxyBoxMixin::compute_dry_layout(self, app, constraints)
639    }
640}
641
642#[cfg(test)]
643mod tests {
644    use std::cell::Cell;
645    use std::rc::Rc;
646
647    use waft_embedder::{Size, TextDirection};
648    use waft_foundation::{App, AppCell, Handle};
649    use waft_rendering::{ErasedLayer, RenderConstrainedBox, RenderIgnorePointer, RenderOffstage};
650
651    use super::*;
652    use crate::framework::{State, StateData, StatefulWidget};
653    use crate::test_harness::Harness;
654    use crate::widgets::basic::{Directionality, IndexedStack, RepaintBoundary};
655
656    /// What a [`Probe`] saw the last time it built.
657    #[derive(Debug, Default)]
658    struct Report {
659        builds: Cell<u32>,
660        live: Cell<i32>,
661        visible: Cell<bool>,
662        ticking: Cell<bool>,
663        focusable: Cell<bool>,
664    }
665
666    /// A stateful leaf that reports what [`Visibility::of`], [`TickerMode`] and the enclosing
667    /// [`ExcludeFocus`] say where it builds, and lays out at 10 by 10.
668    #[derive(Debug)]
669    struct Probe {
670        report: Rc<Report>,
671    }
672
673    impl Probe {
674        fn new(report: &Rc<Report>) -> Probe {
675            Probe {
676                report: Rc::clone(report),
677            }
678        }
679    }
680
681    impl StatefulWidget for Probe {
682        type State = ProbeState;
683
684        fn create_state(&self) -> ProbeState {
685            ProbeState {
686                state: StateData::new(),
687            }
688        }
689    }
690
691    struct ProbeState {
692        state: StateData<Probe>,
693    }
694
695    impl ProbeState {
696        fn report(self: Handle<Self>, app: &App) -> Rc<Report> {
697            Rc::clone(&self.widget(app).report)
698        }
699    }
700
701    impl State for ProbeState {
702        type Widget = Probe;
703        crate::state_accessors!();
704
705        fn init_state(self: Handle<Self>, app: &mut App) {
706            let report = self.report(app);
707            report.live.set(report.live.get() + 1);
708        }
709
710        fn dispose(self: Handle<Self>, app: &mut App) {
711            let report = self.report(app);
712            report.live.set(report.live.get() - 1);
713        }
714
715        fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
716            let report = self.report(app);
717            report.builds.set(report.builds.get() + 1);
718            report.visible.set(Visibility::of(app, context));
719            report
720                .ticking
721                .set(TickerMode::values_of(app, context).enabled);
722            report.focusable.set(
723                context
724                    .find_ancestor_widget_of_exact_type::<ExcludeFocus>(app)
725                    .is_none_or(|exclude_focus| !exclude_focus.excluding),
726            );
727            SizedBox::new().width(10.0).height(10.0).into_widget()
728        }
729    }
730
731    /// The render object under the test root, typed.
732    fn root_child<T: RenderObject>(harness: &Harness, app: &App) -> RenderHandle<T> {
733        harness
734            .render_root(app)
735            .child(app)
736            .expect("a child")
737            .as_object()
738            .downcast::<T>(app)
739            .expect("the widget's render object")
740    }
741
742    #[test]
743    fn a_hidden_visibility_replaces_the_child_and_discards_its_state() {
744        let cell = AppCell::new();
745        let mut app = cell.borrow_mut();
746        let report = Rc::new(Report::default());
747        let harness = Harness::mount(&mut app, Visibility::new(Probe::new(&report)).into_widget());
748        harness.pump(&mut app);
749        assert_eq!(report.live.get(), 1);
750        assert_eq!(
751            root_child::<RenderConstrainedBox>(&harness, &app).size(&app),
752            Size::new(10.0, 10.0),
753            "a visible child is the subtree, without the ExcludeFocus"
754        );
755
756        harness.set_child(
757            &mut app,
758            Visibility::new(Probe::new(&report))
759                .visible(false)
760                .into_widget(),
761        );
762        harness.pump(&mut app);
763        assert_eq!(report.live.get(), 0, "the child subtree was disposed");
764        assert_eq!(
765            root_child::<RenderConstrainedBox>(&harness, &app).size(&app),
766            Size::ZERO,
767            "the replacement is a zero-sized box"
768        );
769    }
770
771    #[test]
772    fn a_hidden_visibility_takes_the_replacement_it_is_given() {
773        let cell = AppCell::new();
774        let mut app = cell.borrow_mut();
775        let harness = Harness::mount(
776            &mut app,
777            Visibility::new(SizedBox::new().width(10.0).height(10.0))
778                .replacement(SizedBox::new().width(4.0).height(4.0))
779                .visible(false)
780                .into_widget(),
781        );
782        harness.pump(&mut app);
783        assert_eq!(
784            root_child::<RenderConstrainedBox>(&harness, &app).size(&app),
785            Size::new(4.0, 4.0)
786        );
787    }
788
789    #[test]
790    fn maintain_state_hides_the_child_offstage_and_mutes_its_tickers() {
791        let cell = AppCell::new();
792        let mut app = cell.borrow_mut();
793        let report = Rc::new(Report::default());
794        let visibility = |visible: bool, report: &Rc<Report>| {
795            Visibility::new(Probe::new(report))
796                .visible(visible)
797                .maintain_state(true)
798                .into_widget()
799        };
800        let harness = Harness::mount(&mut app, visibility(true, &report));
801        harness.pump(&mut app);
802        let offstage = root_child::<RenderOffstage>(&harness, &app);
803        assert!(!offstage.offstage(&app));
804        assert!(report.ticking.get());
805        assert!(report.focusable.get());
806
807        harness.set_child(&mut app, visibility(false, &report));
808        harness.pump(&mut app);
809        assert_eq!(report.live.get(), 1, "the state survives the hiding");
810        assert!(offstage.offstage(&app), "an Offstage hides the child");
811        assert_eq!(offstage.size(&app), Size::ZERO, "it takes up no room");
812        assert!(!report.ticking.get(), "a TickerMode mutes the child");
813        assert!(
814            !report.focusable.get(),
815            "an ExcludeFocus excludes the child"
816        );
817    }
818
819    #[test]
820    fn maintain_animation_leaves_out_the_ticker_mode() {
821        let cell = AppCell::new();
822        let mut app = cell.borrow_mut();
823        let report = Rc::new(Report::default());
824        let harness = Harness::mount(
825            &mut app,
826            Visibility::new(Probe::new(&report))
827                .visible(false)
828                .maintain_state(true)
829                .maintain_animation(true)
830                .into_widget(),
831        );
832        harness.pump(&mut app);
833        assert!(root_child::<RenderOffstage>(&harness, &app).offstage(&app));
834        assert!(report.ticking.get(), "no TickerMode is in the tree");
835    }
836
837    #[test]
838    fn maintain_focusability_keeps_the_hidden_child_focusable() {
839        let cell = AppCell::new();
840        let mut app = cell.borrow_mut();
841        let report = Rc::new(Report::default());
842        let harness = Harness::mount(
843            &mut app,
844            Visibility::new(Probe::new(&report))
845                .visible(false)
846                .maintain_state(true)
847                .maintain_focusability(true)
848                .into_widget(),
849        );
850        harness.pump(&mut app);
851        assert!(report.focusable.get());
852    }
853
854    #[test]
855    fn maintain_size_keeps_the_layout_and_stops_the_paint() {
856        let cell = AppCell::new();
857        let mut app = cell.borrow_mut();
858        let report = Rc::new(Report::default());
859        let harness = Harness::mount(
860            &mut app,
861            Visibility::maintain(Probe::new(&report))
862                .visible(false)
863                .into_widget(),
864        );
865        harness.pump(&mut app);
866
867        let visibility = root_child::<RenderVisibility>(&harness, &app);
868        assert!(!visibility.visible(&app), "the child is not painted");
869        assert_eq!(
870            visibility.size(&app),
871            Size::new(10.0, 10.0),
872            "the space the child would have taken is kept"
873        );
874        assert_eq!(report.live.get(), 1);
875        assert!(report.ticking.get(), "no TickerMode is in the tree");
876        assert!(
877            report.focusable.get(),
878            "Visibility.maintain keeps the focus"
879        );
880        let ignore_pointer = visibility
881            .child(&app)
882            .expect("an IgnorePointer")
883            .as_object()
884            .downcast::<RenderIgnorePointer>(&app)
885            .expect("an IgnorePointer");
886        assert!(
887            !ignore_pointer.ignoring(&app),
888            "Visibility.maintain keeps the interactivity"
889        );
890
891        harness.set_child(
892            &mut app,
893            Visibility::maintain(Probe::new(&report)).into_widget(),
894        );
895        harness.pump(&mut app);
896        assert!(visibility.visible(&app));
897    }
898
899    /// A repaint boundary's layer is detached while nothing paints it (`layers_test.dart`:
900    /// `non-painted layers are detached`).
901    #[test]
902    fn a_hidden_child_whose_size_is_maintained_is_not_painted() {
903        let cell = AppCell::new();
904        let mut app = cell.borrow_mut();
905        let tree = |visible: bool| {
906            Visibility::maintain(
907                RepaintBoundary::new().child(SizedBox::new().width(10.0).height(10.0)),
908            )
909            .visible(visible)
910            .into_widget()
911        };
912        let harness = Harness::mount(&mut app, tree(true));
913        harness.pump(&mut app);
914        let boundary = root_child::<RenderVisibility>(&harness, &app)
915            .child(&app)
916            .expect("an IgnorePointer")
917            .as_object()
918            .downcast::<RenderIgnorePointer>(&app)
919            .expect("an IgnorePointer")
920            .child(&app)
921            .expect("a RepaintBoundary")
922            .as_object();
923        assert!(
924            boundary
925                .debug_layer(&app)
926                .expect("painted")
927                .as_layer()
928                .attached(&app),
929            "a visible child paints"
930        );
931
932        harness.set_child(&mut app, tree(false));
933        harness.pump(&mut app);
934        assert!(
935            !boundary
936                .debug_layer(&app)
937                .expect("a layer")
938                .as_layer()
939                .attached(&app),
940            "the hidden child is not painted"
941        );
942    }
943
944    #[test]
945    fn maintain_size_alone_hides_the_child_from_pointers() {
946        let cell = AppCell::new();
947        let mut app = cell.borrow_mut();
948        let harness = Harness::mount(
949            &mut app,
950            Visibility::new(SizedBox::new().width(10.0).height(10.0))
951                .visible(false)
952                .maintain_state(true)
953                .maintain_animation(true)
954                .maintain_size(true)
955                .into_widget(),
956        );
957        harness.pump(&mut app);
958
959        let visibility = root_child::<RenderVisibility>(&harness, &app);
960        assert!(!visibility.visible(&app));
961        assert_eq!(visibility.size(&app), Size::new(10.0, 10.0));
962        let ignore_pointer = visibility
963            .child(&app)
964            .expect("an IgnorePointer")
965            .as_object()
966            .downcast::<RenderIgnorePointer>(&app)
967            .expect("an IgnorePointer");
968        assert!(ignore_pointer.ignoring(&app));
969    }
970
971    #[test]
972    fn maintain_interactivity_lets_pointers_through_a_hidden_child() {
973        let cell = AppCell::new();
974        let mut app = cell.borrow_mut();
975        let harness = Harness::mount(
976            &mut app,
977            Visibility::new(SizedBox::new().width(10.0).height(10.0))
978                .visible(false)
979                .maintain_state(true)
980                .maintain_animation(true)
981                .maintain_size(true)
982                .maintain_interactivity(true)
983                .into_widget(),
984        );
985        harness.pump(&mut app);
986        let ignore_pointer = root_child::<RenderVisibility>(&harness, &app)
987            .child(&app)
988            .expect("an IgnorePointer")
989            .as_object()
990            .downcast::<RenderIgnorePointer>(&app)
991            .expect("an IgnorePointer");
992        assert!(!ignore_pointer.ignoring(&app));
993    }
994
995    #[test]
996    fn visibility_of_is_true_without_an_ancestor_visibility() {
997        let cell = AppCell::new();
998        let mut app = cell.borrow_mut();
999        let report = Rc::new(Report::default());
1000        let harness = Harness::mount(&mut app, Probe::new(&report).into_widget());
1001        harness.pump(&mut app);
1002        assert!(report.visible.get());
1003    }
1004
1005    #[test]
1006    fn visibility_of_reports_every_ancestor_scope() {
1007        let cell = AppCell::new();
1008        let mut app = cell.borrow_mut();
1009        let report = Rc::new(Report::default());
1010        let nested = |outer: bool, inner: bool, report: &Rc<Report>| {
1011            Visibility::new(
1012                Visibility::new(Probe::new(report))
1013                    .visible(inner)
1014                    .maintain_state(true),
1015            )
1016            .visible(outer)
1017            .maintain_state(true)
1018            .into_widget()
1019        };
1020        let harness = Harness::mount(&mut app, nested(true, true, &report));
1021        harness.pump(&mut app);
1022        assert!(report.visible.get());
1023
1024        harness.set_child(&mut app, nested(true, false, &report));
1025        harness.pump(&mut app);
1026        assert!(!report.visible.get(), "the nearest scope hides it");
1027
1028        harness.set_child(&mut app, nested(false, true, &report));
1029        harness.pump(&mut app);
1030        assert!(!report.visible.get(), "an outer scope hides it too");
1031    }
1032
1033    #[test]
1034    fn visibility_of_rebuilds_its_dependents() {
1035        let cell = AppCell::new();
1036        let mut app = cell.borrow_mut();
1037        let report = Rc::new(Report::default());
1038        let visibility = |visible: bool, report: &Rc<Report>| {
1039            Visibility::new(Probe::new(report))
1040                .visible(visible)
1041                .maintain_state(true)
1042                .maintain_animation(true)
1043                .into_widget()
1044        };
1045        let harness = Harness::mount(&mut app, visibility(true, &report));
1046        harness.pump(&mut app);
1047        let builds = report.builds.get();
1048
1049        harness.set_child(&mut app, visibility(false, &report));
1050        harness.pump(&mut app);
1051        assert!(report.builds.get() > builds, "the scope notified it");
1052        assert!(!report.visible.get());
1053    }
1054
1055    #[test]
1056    fn visibility_of_reports_an_indexed_stack_scope() {
1057        let cell = AppCell::new();
1058        let mut app = cell.borrow_mut();
1059        let report = Rc::new(Report::default());
1060        let harness = Harness::mount(
1061            &mut app,
1062            Directionality::new(
1063                TextDirection::Ltr,
1064                IndexedStack::new().index(Some(1)).children([
1065                    Probe::new(&report).into_widget(),
1066                    SizedBox::new().width(10.0).height(10.0).into_widget(),
1067                ]),
1068            )
1069            .into_widget(),
1070        );
1071        harness.pump(&mut app);
1072        assert!(
1073            !report.visible.get(),
1074            "the scope IndexedStack builds is the one Visibility.of reads"
1075        );
1076    }
1077}