Skip to main content

waft_material/
flexible_space_bar.rs

1//! Flutter counterpart: material_ui's `flexible_space_bar.dart`.
2
3use waft_animation::{Curve, Curves, Interval, Tween};
4use waft_embedder::{
5    ImageFilter, Matrix4, Offset, Size, TargetPlatform, TextBaseline, TextDirection,
6};
7use waft_foundation::{App, DiagnosticPropertiesBuilder, DoubleProperty, Handle};
8use waft_painting::{Alignment, EdgeInsetsGeometry};
9use waft_rendering::{
10    AnyOffsetLayer, AnyRenderBox, AnyRenderObject, BoxConstraints, BoxHitTestResult,
11    ContainerLayer, OffsetLayerMixin, OpacityLayer, PaintingContext, RenderBox, RenderBoxData,
12    RenderHandle, RenderObject, RenderObjectData, RenderObjectWithChildData,
13    RenderObjectWithChildMixin, RenderProxyBoxMixin,
14};
15use waft_widgets::{
16    Align, BackdropFilter, BuildContext, ClipRect, ColoredBox, DefaultTextStyle, Directionality,
17    InheritedWidget, IntoWidget, KeyRef, LayoutBuilder, Opacity, Padding, Positioned,
18    RenderObjectWidget, Semantics, SingleChildRenderObjectWidget, SizedBox, Stack, State,
19    StateData, StatefulWidget, Transform, WidgetRef,
20};
21
22use crate::colors::Colors;
23use crate::constants::K_TOOLBAR_HEIGHT;
24use crate::theme::Theme;
25
26/// The collapsing effect while the space bar collapses from its full size.
27#[derive(Clone, Copy, Debug, PartialEq, Eq)]
28pub enum CollapseMode {
29    /// The background widget will scroll in a parallax fashion.
30    Parallax,
31
32    /// The background widget pin in place until it reaches the min extent.
33    Pin,
34
35    /// The background widget will act as normal with no collapsing effect.
36    None,
37}
38
39/// The stretching effect while the space bar stretches beyond its full size.
40#[derive(Clone, Copy, Debug, PartialEq, Eq)]
41pub enum StretchMode {
42    /// The background widget will expand to fill the extra space.
43    ZoomBackground,
44
45    /// The background will blur using a [`ImageFilter::blur`] effect.
46    BlurBackground,
47
48    /// The title will fade away as the user over-scrolls.
49    FadeTitle,
50}
51
52/// The part of a Material Design `AppBar` that expands, collapses, and
53/// stretches.
54///
55/// Most commonly used in the `SliverAppBar::flexible_space` field, a flexible
56/// space bar expands and contracts as the app scrolls so that the `AppBar`
57/// reaches from the top of the app to the top of the scrolling contents of the
58/// app. When using `SliverAppBar::flexible_space`, the `SliverAppBar::expanded_height`
59/// must be large enough to accommodate the `SliverAppBar::flexible_space` widget.
60///
61/// Furthermore is included functionality for stretch behavior. When
62/// `SliverAppBar::stretch` is true, and your `ScrollPhysics` allow for
63/// overscroll, this space will stretch with the overscroll.
64///
65/// The widget that sizes the `AppBar` must wrap it in the widget returned by
66/// [`FlexibleSpaceBar::create_settings`], to convey sizing information down to the
67/// [`FlexibleSpaceBar`].
68///
69/// See also:
70///
71///  * `SliverAppBar`, which implements the expanding and contracting.
72///  * `AppBar`, which is used by `SliverAppBar`.
73///  * <https://material.io/design/components/app-bars-top.html#behavior>
74#[derive(Debug)]
75pub struct FlexibleSpaceBar {
76    pub key: Option<KeyRef>,
77
78    /// The primary contents of the flexible space bar when expanded.
79    ///
80    /// Typically a `Text` widget.
81    pub title: Option<WidgetRef>,
82
83    /// Shown behind the [`title`](Self::title) when expanded.
84    ///
85    /// Typically an `Image` widget with `Image::fit` set to `BoxFit::Cover`.
86    pub background: Option<WidgetRef>,
87
88    /// Whether the title should be centered.
89    ///
90    /// If the length of the title is greater than the available space, set
91    /// this property to false. This aligns the title to the start of the
92    /// flexible space bar and applies [`title_padding`](Self::title_padding) to the title.
93    ///
94    /// By default this property is true if the current target platform
95    /// is [`TargetPlatform::IOS`] or [`TargetPlatform::MacOS`], false otherwise.
96    pub center_title: Option<bool>,
97
98    /// Collapse effect while scrolling.
99    ///
100    /// Defaults to [`CollapseMode::Parallax`].
101    pub collapse_mode: CollapseMode,
102
103    /// Stretch effect while over-scrolling.
104    ///
105    /// Defaults to include [`StretchMode::ZoomBackground`].
106    pub stretch_modes: Vec<StretchMode>,
107
108    /// Defines how far the [`title`](Self::title) is inset from either the widget's
109    /// bottom-left or its center.
110    ///
111    /// Typically this property is used to adjust how far the title is
112    /// inset from the bottom-left and it is specified along with
113    /// [`center_title`](Self::center_title) false.
114    ///
115    /// If [`center_title`](Self::center_title) is true, then the title is centered within the
116    /// flexible space bar with a bottom padding of 16.0 pixels.
117    ///
118    /// If [`center_title`](Self::center_title) is false and
119    /// [`FlexibleSpaceBarSettings::has_leading`] is true,
120    /// then the title is aligned to the start of the flexible space bar with the
121    /// [`title_padding`](Self::title_padding) applied. If [`title_padding`](Self::title_padding)
122    /// is null, then defaults to start padding of 72.0 pixels and bottom padding of 16.0 pixels.
123    pub title_padding: Option<EdgeInsetsGeometry>,
124
125    /// Defines how much the title is scaled when the FlexibleSpaceBar is expanded
126    /// due to the user scrolling downwards. The title is scaled uniformly on the
127    /// x and y axes while maintaining its bottom-left position (bottom-center if
128    /// [`center_title`](Self::center_title) is true).
129    ///
130    /// Defaults to 1.5 and must be greater than 1.
131    pub expanded_title_scale: f64,
132}
133
134impl FlexibleSpaceBar {
135    /// Creates a flexible space bar; Dart's optional named arguments are the setters.
136    ///
137    /// Most commonly used in the `AppBar::flexible_space` field.
138    pub fn new() -> FlexibleSpaceBar {
139        FlexibleSpaceBar {
140            key: None,
141            title: None,
142            background: None,
143            center_title: None,
144            collapse_mode: CollapseMode::Parallax,
145            stretch_modes: vec![StretchMode::ZoomBackground],
146            title_padding: None,
147            expanded_title_scale: 1.5,
148        }
149    }
150
151    /// Dart `FlexibleSpaceBar(key:)`.
152    pub fn key(mut self, key: KeyRef) -> FlexibleSpaceBar {
153        self.key = Some(key);
154        self
155    }
156
157    /// Dart `FlexibleSpaceBar(title:)`.
158    #[cfg_attr(debug_assertions, track_caller)]
159    pub fn title<K>(mut self, title: impl IntoWidget<K>) -> FlexibleSpaceBar {
160        self.title = Some(title.into_widget());
161        self
162    }
163
164    /// Dart `FlexibleSpaceBar(background:)`.
165    #[cfg_attr(debug_assertions, track_caller)]
166    pub fn background<K>(mut self, background: impl IntoWidget<K>) -> FlexibleSpaceBar {
167        self.background = Some(background.into_widget());
168        self
169    }
170
171    /// Dart `FlexibleSpaceBar(centerTitle:)`.
172    pub fn center_title(mut self, center_title: bool) -> FlexibleSpaceBar {
173        self.center_title = Some(center_title);
174        self
175    }
176
177    /// Dart `FlexibleSpaceBar(titlePadding:)`.
178    pub fn title_padding(
179        mut self,
180        title_padding: impl Into<EdgeInsetsGeometry>,
181    ) -> FlexibleSpaceBar {
182        let title_padding = title_padding.into();
183        self.title_padding = Some(title_padding);
184        self
185    }
186
187    /// Dart `FlexibleSpaceBar(collapseMode:)`.
188    pub fn collapse_mode(mut self, collapse_mode: CollapseMode) -> FlexibleSpaceBar {
189        self.collapse_mode = collapse_mode;
190        self
191    }
192
193    /// Dart `FlexibleSpaceBar(stretchModes:)`.
194    pub fn stretch_modes(mut self, stretch_modes: Vec<StretchMode>) -> FlexibleSpaceBar {
195        self.stretch_modes = stretch_modes;
196        self
197    }
198
199    /// Dart `FlexibleSpaceBar(expandedTitleScale:)`.
200    pub fn expanded_title_scale(mut self, expanded_title_scale: f64) -> FlexibleSpaceBar {
201        debug_assert!(expanded_title_scale >= 1.0);
202        self.expanded_title_scale = expanded_title_scale;
203        self
204    }
205
206    /// Wraps a widget that contains an `AppBar` to convey sizing information down
207    /// to the [`FlexibleSpaceBar`].
208    ///
209    /// Used by `Scaffold` and `SliverAppBar`.
210    ///
211    /// `toolbar_opacity` affects how transparent the text within the toolbar
212    /// appears. `min_extent` sets the minimum height of the resulting
213    /// [`FlexibleSpaceBar`] when fully collapsed. `max_extent` sets the maximum
214    /// height of the resulting [`FlexibleSpaceBar`] when fully expanded.
215    /// `current_extent` sets the scale of the [`FlexibleSpaceBar::background`] and
216    /// [`FlexibleSpaceBar::title`] widgets of [`FlexibleSpaceBar`] upon
217    /// initialization. `is_scrolled_under` is true if the [`FlexibleSpaceBar`]
218    /// overlaps the app's primary scrollable, false if it does not, and null
219    /// if the caller has not determined as much.
220    /// See also:
221    ///
222    ///  * [`FlexibleSpaceBarSettings`] which creates a settings object that can be
223    ///    used to specify these settings to a [`FlexibleSpaceBar`].
224    ///
225    /// Dart's optional named arguments are the setters of the builder; `build` fills
226    /// `min_extent` and `max_extent` from `current_extent` and `toolbar_opacity` with 1.0.
227    #[cfg_attr(debug_assertions, track_caller)]
228    pub fn create_settings<K>(
229        current_extent: f64,
230        child: impl IntoWidget<K>,
231    ) -> FlexibleSpaceBarSettingsBuilder {
232        FlexibleSpaceBarSettingsBuilder {
233            toolbar_opacity: None,
234            min_extent: None,
235            max_extent: None,
236            is_scrolled_under: None,
237            has_leading: None,
238            current_extent,
239            child: child.into_widget(),
240        }
241    }
242}
243
244impl Default for FlexibleSpaceBar {
245    fn default() -> FlexibleSpaceBar {
246        FlexibleSpaceBar::new()
247    }
248}
249
250/// The optional arguments of [`FlexibleSpaceBar::create_settings`].
251pub struct FlexibleSpaceBarSettingsBuilder {
252    toolbar_opacity: Option<f64>,
253    min_extent: Option<f64>,
254    max_extent: Option<f64>,
255    is_scrolled_under: Option<bool>,
256    has_leading: Option<bool>,
257    current_extent: f64,
258    child: WidgetRef,
259}
260
261impl FlexibleSpaceBarSettingsBuilder {
262    /// Dart `createSettings(toolbarOpacity:)`.
263    pub fn toolbar_opacity(mut self, toolbar_opacity: f64) -> FlexibleSpaceBarSettingsBuilder {
264        self.toolbar_opacity = Some(toolbar_opacity);
265        self
266    }
267
268    /// Dart `createSettings(minExtent:)`.
269    pub fn min_extent(mut self, min_extent: f64) -> FlexibleSpaceBarSettingsBuilder {
270        self.min_extent = Some(min_extent);
271        self
272    }
273
274    /// Dart `createSettings(maxExtent:)`.
275    pub fn max_extent(mut self, max_extent: f64) -> FlexibleSpaceBarSettingsBuilder {
276        self.max_extent = Some(max_extent);
277        self
278    }
279
280    /// Dart `createSettings(isScrolledUnder:)`.
281    pub fn is_scrolled_under(mut self, is_scrolled_under: bool) -> FlexibleSpaceBarSettingsBuilder {
282        self.is_scrolled_under = Some(is_scrolled_under);
283        self
284    }
285
286    /// Dart `createSettings(hasLeading:)`.
287    pub fn has_leading(mut self, has_leading: bool) -> FlexibleSpaceBarSettingsBuilder {
288        self.has_leading = Some(has_leading);
289        self
290    }
291
292    /// The settings widget Dart's `createSettings` returns.
293    pub fn build(self) -> FlexibleSpaceBarSettings {
294        let mut settings = FlexibleSpaceBarSettings::new(
295            self.toolbar_opacity.unwrap_or(1.0),
296            self.min_extent.unwrap_or(self.current_extent),
297            self.max_extent.unwrap_or(self.current_extent),
298            self.current_extent,
299            self.child,
300        );
301        settings.is_scrolled_under = self.is_scrolled_under;
302        settings.has_leading = self.has_leading;
303        settings
304    }
305}
306
307impl StatefulWidget for FlexibleSpaceBar {
308    type State = FlexibleSpaceBarState;
309
310    fn key(&self) -> Option<&KeyRef> {
311        self.key.as_ref()
312    }
313
314    fn create_state(&self) -> FlexibleSpaceBarState {
315        FlexibleSpaceBarState {
316            state: StateData::new(),
317        }
318    }
319}
320
321/// Dart's `_FlexibleSpaceBarState`.
322pub struct FlexibleSpaceBarState {
323    state: StateData<FlexibleSpaceBar>,
324}
325
326impl FlexibleSpaceBarState {
327    fn get_effective_center_title(self: Handle<Self>, app: &App, platform: TargetPlatform) -> bool {
328        self.widget(app).center_title.unwrap_or(match platform {
329            TargetPlatform::Android
330            | TargetPlatform::Fuchsia
331            | TargetPlatform::Linux
332            | TargetPlatform::Windows => false,
333            TargetPlatform::IOS | TargetPlatform::MacOS => true,
334        })
335    }
336
337    fn get_title_alignment(
338        self: Handle<Self>,
339        app: &mut App,
340        effective_center_title: bool,
341    ) -> Alignment {
342        if effective_center_title {
343            return Alignment::BOTTOM_CENTER;
344        }
345        let context = self.context(app);
346        match Directionality::of(app, context) {
347            TextDirection::Rtl => Alignment::BOTTOM_RIGHT,
348            TextDirection::Ltr => Alignment::BOTTOM_LEFT,
349        }
350    }
351
352    fn get_collapse_padding(
353        self: Handle<Self>,
354        app: &mut App,
355        t: f64,
356        settings: &FlexibleSpaceBarSettings,
357    ) -> f64 {
358        match self.widget(app).collapse_mode {
359            CollapseMode::Pin => -(settings.max_extent - settings.current_extent),
360            CollapseMode::None => 0.0,
361            CollapseMode::Parallax => {
362                let delta_extent = settings.max_extent - settings.min_extent;
363                -transform_tween(app, 0.0, delta_extent / 4.0, t)
364            }
365        }
366    }
367}
368
369/// Dart's `Tween<double>(begin: begin, end: end).transform(t)`.
370fn transform_tween(app: &mut App, begin: f64, end: f64, t: f64) -> f64 {
371    let tween = Tween::new(app, Some(begin), Some(end));
372    waft_animation::Animatable::transform(&tween, app, t)
373}
374
375impl State for FlexibleSpaceBarState {
376    type Widget = FlexibleSpaceBar;
377    waft_widgets::state_accessors!();
378
379    fn build(self: Handle<Self>, _app: &mut App, _context: BuildContext) -> WidgetRef {
380        LayoutBuilder::new(move |app, context, constraints| {
381            self.build_with_constraints(app, context, constraints.constraints())
382        })
383        .into_widget()
384    }
385}
386
387impl FlexibleSpaceBarState {
388    /// The builder of the `LayoutBuilder` Dart's `build` returns.
389    fn build_with_constraints(
390        self: Handle<Self>,
391        app: &mut App,
392        context: BuildContext,
393        constraints: BoxConstraints,
394    ) -> WidgetRef {
395        let settings = context
396            .depend_on_inherited_widget_of_exact_type::<FlexibleSpaceBarSettings>(app)
397            .expect("a FlexibleSpaceBarSettings above the FlexibleSpaceBar")
398            .clone();
399
400        let mut children: Vec<WidgetRef> = Vec::new();
401
402        let delta_extent = settings.max_extent - settings.min_extent;
403
404        // 0.0 -> Expanded
405        // 1.0 -> Collapsed to toolbar
406        let t = waft_embedder::clamp_double(
407            1.0 - (settings.current_extent - settings.min_extent) / delta_extent,
408            0.0,
409            1.0,
410        );
411
412        // background
413        if let Some(background) = self.widget(app).background.clone() {
414            let fade_start = f64::max(0.0, 1.0 - K_TOOLBAR_HEIGHT / delta_extent);
415            const FADE_END: f64 = 1.0;
416            debug_assert!(fade_start <= FADE_END);
417            // If the min and max extent are the same, the app bar cannot collapse
418            // and the content should be visible, so opacity = 1.
419            let opacity = if settings.max_extent == settings.min_extent {
420                1.0
421            } else {
422                1.0 - Interval::new(fade_start, FADE_END, Curves::linear()).transform(t)
423            };
424            let mut height = settings.max_extent;
425
426            // StretchMode.zoomBackground
427            let stretch_modes = self.widget(app).stretch_modes.clone();
428            if stretch_modes.contains(&StretchMode::ZoomBackground)
429                && constraints.max_height > height
430            {
431                height = constraints.max_height;
432            }
433            let top_padding = self.get_collapse_padding(app, t, &settings);
434            children.push(
435                Positioned::new(FlexibleSpaceHeaderOpacity::new(opacity, background))
436                    .top(top_padding)
437                    .left(0.0)
438                    .right(0.0)
439                    .height(height)
440                    .into_widget(),
441            );
442
443            // StretchMode.blurBackground
444            if stretch_modes.contains(&StretchMode::BlurBackground)
445                && constraints.max_height > settings.max_extent
446            {
447                let blur_amount = (constraints.max_height - settings.max_extent) / 10.0;
448                children.push(
449                    Positioned::fill(
450                        BackdropFilter::filter(ImageFilter::blur(blur_amount, blur_amount))
451                            .child(ColoredBox::new(Colors::TRANSPARENT)),
452                    )
453                    .into_widget(),
454                );
455            }
456        }
457
458        // title
459        if let Some(title) = self.widget(app).title.clone() {
460            let theme = Theme::of(app, context);
461
462            let mut title = match theme.platform {
463                TargetPlatform::IOS | TargetPlatform::MacOS => title,
464                TargetPlatform::Android
465                | TargetPlatform::Fuchsia
466                | TargetPlatform::Linux
467                | TargetPlatform::Windows => Semantics::new()
468                    .names_route(true)
469                    .child(title)
470                    .into_widget(),
471            };
472
473            // StretchMode.fadeTitle
474            if self
475                .widget(app)
476                .stretch_modes
477                .contains(&StretchMode::FadeTitle)
478                && constraints.max_height > settings.max_extent
479            {
480                let stretch_opacity = 1.0
481                    - waft_embedder::clamp_double(
482                        (constraints.max_height - settings.max_extent) / 100.0,
483                        0.0,
484                        1.0,
485                    );
486                title = Opacity::new(stretch_opacity).child(title).into_widget();
487            }
488
489            let opacity = settings.toolbar_opacity;
490            if opacity > 0.0 {
491                let mut title_style = if theme.use_material3 {
492                    theme.text_theme.title_large.clone()
493                } else {
494                    theme.primary_text_theme.title_large.clone()
495                }
496                .expect("the text theme has a title large style");
497                #[allow(deprecated)]
498                let title_color = title_style
499                    .color
500                    .as_ref()
501                    .expect("the title large style has a color")
502                    .with_opacity(opacity);
503                title_style = title_style.copy_with().color(title_color);
504                let effective_center_title = self.get_effective_center_title(app, theme.platform);
505                let leading_padding = if settings.has_leading.unwrap_or(true) {
506                    72.0
507                } else {
508                    0.0
509                };
510                let padding =
511                    self.widget(app)
512                        .title_padding
513                        .unwrap_or(EdgeInsetsGeometry::directional(
514                            if effective_center_title {
515                                0.0
516                            } else {
517                                leading_padding
518                            },
519                            0.0,
520                            0.0,
521                            16.0,
522                        ));
523                let expanded_title_scale = self.widget(app).expanded_title_scale;
524                let scale_value = transform_tween(app, expanded_title_scale, 1.0, t);
525                let scale_transform = Matrix4::scale(scale_value as f32, scale_value as f32);
526                let title_alignment = self.get_title_alignment(app, effective_center_title);
527                children.push(
528                    Padding::new(padding)
529                        .child(
530                            Transform::new(scale_transform)
531                                .alignment(title_alignment.into())
532                                .child(
533                                    Align::new().alignment(title_alignment.into()).child(
534                                        DefaultTextStyle::new(
535                                            title_style,
536                                            LayoutBuilder::new(
537                                                move |_app, _context, constraints| {
538                                                    SizedBox::new()
539                                                        .width(constraints.max_width / scale_value)
540                                                        .child(
541                                                            Align::new()
542                                                                .alignment(title_alignment.into())
543                                                                .child(title.clone()),
544                                                        )
545                                                        .into_widget()
546                                                },
547                                            )
548                                            .into_widget(),
549                                        ),
550                                    ),
551                                ),
552                        )
553                        .into_widget(),
554                );
555            }
556        }
557
558        ClipRect::new()
559            .child(Stack::new().children(children))
560            .into_widget()
561    }
562}
563
564/// Provides sizing and opacity information to a [`FlexibleSpaceBar`].
565///
566/// See also:
567///
568///  * [`FlexibleSpaceBar`] which creates a flexible space bar.
569#[derive(Clone, Debug)]
570pub struct FlexibleSpaceBarSettings {
571    pub key: Option<KeyRef>,
572
573    /// Affects how transparent the text within the toolbar appears.
574    pub toolbar_opacity: f64,
575
576    /// Minimum height of the resulting [`FlexibleSpaceBar`] when fully collapsed.
577    pub min_extent: f64,
578
579    /// Maximum height of the resulting [`FlexibleSpaceBar`] when fully expanded.
580    pub max_extent: f64,
581
582    /// If the [`FlexibleSpaceBar::title`] or the [`FlexibleSpaceBar::background`] is
583    /// not null, then this value is used to calculate the relative scale of
584    /// these elements upon initialization.
585    pub current_extent: f64,
586
587    /// True if the FlexibleSpaceBar overlaps the primary scrollable's contents.
588    ///
589    /// This value is used by the `AppBar` to resolve
590    /// `AppBar::background_color` against `WidgetState::ScrolledUnder`,
591    /// i.e. to enable apps to specify different colors when content
592    /// has been scrolled up and behind the app bar.
593    ///
594    /// Null if the caller hasn't determined if the FlexibleSpaceBar
595    /// overlaps the primary scrollable's contents.
596    pub is_scrolled_under: Option<bool>,
597
598    /// True if the FlexibleSpaceBar has a leading widget.
599    ///
600    /// This value is used by the [`FlexibleSpaceBar`] to determine
601    /// if there should be a gap between the leading widget and
602    /// the title.
603    ///
604    /// Null if the caller hasn't determined if the FlexibleSpaceBar
605    /// has a leading widget.
606    pub has_leading: Option<bool>,
607
608    pub child: WidgetRef,
609}
610
611impl FlexibleSpaceBarSettings {
612    /// Creates a Flexible Space Bar Settings widget.
613    ///
614    /// Used by `Scaffold` and `SliverAppBar`. `child` must have a
615    /// [`FlexibleSpaceBar`] widget in its tree for the settings to take affect.
616    #[cfg_attr(debug_assertions, track_caller)]
617    pub fn new<K>(
618        toolbar_opacity: f64,
619        min_extent: f64,
620        max_extent: f64,
621        current_extent: f64,
622        child: impl IntoWidget<K>,
623    ) -> FlexibleSpaceBarSettings {
624        debug_assert!(min_extent >= 0.0);
625        debug_assert!(max_extent >= 0.0);
626        debug_assert!(current_extent >= 0.0);
627        debug_assert!(toolbar_opacity >= 0.0);
628        debug_assert!(min_extent <= max_extent);
629        debug_assert!(min_extent <= current_extent);
630        debug_assert!(current_extent <= max_extent);
631        FlexibleSpaceBarSettings {
632            key: None,
633            toolbar_opacity,
634            min_extent,
635            max_extent,
636            current_extent,
637            is_scrolled_under: None,
638            has_leading: None,
639            child: child.into_widget(),
640        }
641    }
642
643    /// Dart `FlexibleSpaceBarSettings(key:)`.
644    pub fn key(mut self, key: KeyRef) -> FlexibleSpaceBarSettings {
645        self.key = Some(key);
646        self
647    }
648
649    /// Dart `FlexibleSpaceBarSettings(isScrolledUnder:)`.
650    pub fn is_scrolled_under(mut self, is_scrolled_under: bool) -> FlexibleSpaceBarSettings {
651        self.is_scrolled_under = Some(is_scrolled_under);
652        self
653    }
654
655    /// Dart `FlexibleSpaceBarSettings(hasLeading:)`.
656    pub fn has_leading(mut self, has_leading: bool) -> FlexibleSpaceBarSettings {
657        self.has_leading = Some(has_leading);
658        self
659    }
660}
661
662impl InheritedWidget for FlexibleSpaceBarSettings {
663    fn key(&self) -> Option<&KeyRef> {
664        self.key.as_ref()
665    }
666
667    fn child(&self) -> &WidgetRef {
668        &self.child
669    }
670
671    fn update_should_notify(&self, old_widget: &FlexibleSpaceBarSettings) -> bool {
672        self.toolbar_opacity != old_widget.toolbar_opacity
673            || self.min_extent != old_widget.min_extent
674            || self.max_extent != old_widget.max_extent
675            || self.current_extent != old_widget.current_extent
676            || self.is_scrolled_under != old_widget.is_scrolled_under
677            || self.has_leading != old_widget.has_leading
678    }
679}
680
681// We need the child widget to repaint, however both the opacity
682// and potentially `widget.background` can be constant which won't
683// lead to repainting.
684// see: https://github.com/flutter/flutter/issues/127836
685/// Dart's `_FlexibleSpaceHeaderOpacity`.
686#[derive(Debug)]
687pub(crate) struct FlexibleSpaceHeaderOpacity {
688    opacity: f64,
689    child: WidgetRef,
690}
691
692impl FlexibleSpaceHeaderOpacity {
693    #[cfg_attr(debug_assertions, track_caller)]
694    fn new<K>(opacity: f64, child: impl IntoWidget<K>) -> FlexibleSpaceHeaderOpacity {
695        FlexibleSpaceHeaderOpacity {
696            opacity,
697            child: child.into_widget(),
698        }
699    }
700}
701
702impl RenderObjectWidget for FlexibleSpaceHeaderOpacity {
703    type RenderObject = RenderFlexibleSpaceHeaderOpacity;
704
705    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
706        RenderFlexibleSpaceHeaderOpacity::new(app, self.opacity).as_object()
707    }
708
709    fn update_render_object(
710        &self,
711        app: &mut App,
712        _context: BuildContext,
713        render_object: RenderHandle<RenderFlexibleSpaceHeaderOpacity>,
714    ) {
715        render_object.set_opacity(app, self.opacity);
716    }
717}
718
719impl SingleChildRenderObjectWidget for FlexibleSpaceHeaderOpacity {
720    fn child(&self) -> Option<&WidgetRef> {
721        Some(&self.child)
722    }
723}
724
725/// Dart's `_RenderFlexibleSpaceHeaderOpacity`: a `RenderOpacity` that is not a repaint
726/// boundary and keeps its own `OpacityLayer` in `layer`.
727pub(crate) struct RenderFlexibleSpaceHeaderOpacity {
728    render_object: RenderObjectData,
729    render_box: RenderBoxData,
730    child: RenderObjectWithChildData<AnyRenderBox>,
731    alpha: i32,
732    opacity: f64,
733}
734
735impl RenderFlexibleSpaceHeaderOpacity {
736    fn new(app: &mut App, opacity: f64) -> RenderHandle<Self> {
737        debug_assert!((0.0..=1.0).contains(&opacity));
738        RenderHandle::new_box(
739            app,
740            RenderFlexibleSpaceHeaderOpacity {
741                render_object: RenderObjectData::new(),
742                render_box: RenderBoxData::new(),
743                child: RenderObjectWithChildData::new(),
744                alpha: waft_embedder::Color::get_alpha_from_opacity(opacity),
745                opacity,
746            },
747        )
748    }
749
750    /// Sets the fraction to scale the child's alpha value.
751    fn set_opacity(self: RenderHandle<Self>, app: &mut App, value: f64) {
752        debug_assert!((0.0..=1.0).contains(&value));
753        if self.get(app).opacity == value {
754            return;
755        }
756        let did_need_compositing = self.always_needs_compositing(app);
757        let this = self.get_mut(app);
758        this.opacity = value;
759        this.alpha = waft_embedder::Color::get_alpha_from_opacity(value);
760        if did_need_compositing != self.always_needs_compositing(app) {
761            self.mark_needs_compositing_bits_update(app);
762        }
763        self.mark_needs_composited_layer_update(app);
764    }
765}
766
767impl RenderObjectWithChildMixin for RenderFlexibleSpaceHeaderOpacity {
768    type ChildType = AnyRenderBox;
769
770    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
771        &self.get(app).child
772    }
773
774    fn child_data_mut(
775        self: RenderHandle<Self>,
776        app: &mut App,
777    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
778        &mut self.get_mut(app).child
779    }
780}
781
782impl RenderProxyBoxMixin for RenderFlexibleSpaceHeaderOpacity {}
783
784impl RenderObject for RenderFlexibleSpaceHeaderOpacity {
785    waft_rendering::render_object_accessors!();
786
787    fn debug_fill_properties(
788        self: RenderHandle<Self>,
789        app: &App,
790        properties: &mut DiagnosticPropertiesBuilder,
791    ) {
792        // Dart's `_RenderFlexibleSpaceHeaderOpacity` inherits `RenderOpacity.debugFillProperties`;
793        // the `alwaysIncludeSemantics` flag is semantics.
794        properties.add(DoubleProperty::new("opacity", self.get(app).opacity));
795    }
796
797    fn always_needs_compositing(self: RenderHandle<Self>, app: &App) -> bool {
798        self.child(app).is_some() && self.get(app).alpha > 0
799    }
800
801    fn is_repaint_boundary(self: RenderHandle<Self>, _app: &App) -> bool {
802        false
803    }
804
805    fn update_composited_layer(
806        self: RenderHandle<Self>,
807        app: &mut App,
808        old_layer: Option<AnyOffsetLayer>,
809    ) -> AnyOffsetLayer {
810        let layer = match old_layer {
811            Some(old) => app
812                .handle::<OpacityLayer>(old.id())
813                .expect("RenderOpacity reuses an OpacityLayer"),
814            None => OpacityLayer::new(app),
815        };
816        layer.set_alpha(app, self.get(app).alpha);
817        layer.as_offset_layer()
818    }
819
820    fn paints_child(self: RenderHandle<Self>, app: &App, child: AnyRenderObject) -> bool {
821        debug_assert!(child.parent(app) == Some(self.as_object()));
822        self.get(app).alpha > 0
823    }
824
825    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
826        RenderProxyBoxMixin::perform_layout(self, app);
827    }
828
829    fn paint(
830        self: RenderHandle<Self>,
831        app: &mut App,
832        context: &mut PaintingContext,
833        offset: Offset,
834    ) {
835        if self.child(app).is_none() {
836            return;
837        }
838        let opacity = self.get(app).opacity;
839        if (opacity * 255.0).round() <= 0.0 {
840            self.as_object().set_layer(app, None);
841            return;
842        }
843        debug_assert!(self.as_object().needs_compositing(app));
844        let old_layer = self.as_object().layer_as::<OpacityLayer>(app);
845        let layer = context.push_opacity(
846            app,
847            offset,
848            (opacity * 255.0).round() as i32,
849            |app, context, offset| {
850                // `RenderOpacity.paint`, which `super.paint` reaches.
851                if self.child(app).is_none() || self.get(app).alpha == 0 {
852                    return;
853                }
854                RenderProxyBoxMixin::paint(self, app, context, offset);
855            },
856            old_layer,
857        );
858        self.as_object()
859            .set_layer(app, Some(layer.as_container_layer()));
860    }
861
862    fn visit_children(
863        self: RenderHandle<Self>,
864        app: &App,
865        visitor: &mut dyn FnMut(AnyRenderObject),
866    ) {
867        if let Some(child) = self.child(app) {
868            visitor(child.as_object());
869        }
870    }
871}
872
873impl RenderBox for RenderFlexibleSpaceHeaderOpacity {
874    waft_rendering::render_box_accessors!();
875
876    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
877        RenderProxyBoxMixin::setup_parent_data(self, app, child);
878    }
879
880    fn apply_paint_transform(
881        self: RenderHandle<Self>,
882        app: &App,
883        child: AnyRenderObject,
884        transform: &mut Matrix4,
885    ) {
886        RenderProxyBoxMixin::apply_paint_transform(self, app, child, transform);
887    }
888
889    fn hit_test_children(
890        self: RenderHandle<Self>,
891        app: &mut App,
892        result: &mut BoxHitTestResult<'_>,
893        position: Offset,
894    ) -> bool {
895        RenderProxyBoxMixin::hit_test_children(self, app, result, position)
896    }
897
898    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
899        RenderProxyBoxMixin::compute_min_intrinsic_width(self, app, height)
900    }
901
902    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
903        RenderProxyBoxMixin::compute_max_intrinsic_width(self, app, height)
904    }
905
906    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
907        RenderProxyBoxMixin::compute_min_intrinsic_height(self, app, width)
908    }
909
910    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
911        RenderProxyBoxMixin::compute_max_intrinsic_height(self, app, width)
912    }
913
914    fn compute_distance_to_actual_baseline(
915        self: RenderHandle<Self>,
916        app: &mut App,
917        baseline: TextBaseline,
918    ) -> Option<f64> {
919        RenderProxyBoxMixin::compute_distance_to_actual_baseline(self, app, baseline)
920    }
921
922    fn compute_dry_baseline(
923        self: RenderHandle<Self>,
924        app: &mut App,
925        constraints: BoxConstraints,
926        baseline: TextBaseline,
927    ) -> Option<f64> {
928        RenderProxyBoxMixin::compute_dry_baseline(self, app, constraints, baseline)
929    }
930
931    fn compute_dry_layout(
932        self: RenderHandle<Self>,
933        app: &mut App,
934        constraints: BoxConstraints,
935    ) -> Size {
936        RenderProxyBoxMixin::compute_dry_layout(self, app, constraints)
937    }
938}
939
940#[cfg(test)]
941mod tests {
942    //! Cases of `test/flexible_space_bar_test.dart`, `flexible_space_bar_collapse_mode_test.dart`
943    //! and `flexible_space_bar_stretch_mode_test.dart`. Where a Dart case drags or stretches a
944    //! `SliverAppBar` in a scroll view, or measures FlexibleSpaceBar-in-`AppBar` text, the
945    //! settings the app bar would convey at that point are given by hand with
946    //! [`FlexibleSpaceBar::create_settings`], in a box of the height the app bar would be.
947    //! Each case's name says which Dart case it follows.
948
949    use std::cell::RefCell;
950    use std::rc::Rc;
951
952    use waft_embedder::Rect;
953    use waft_painting::{AlignmentGeometry, TextStyle};
954    use waft_rendering::OpacityLayer;
955    use waft_widgets::{Builder, Center, Container, GlobalKey, Text, TextOverflow};
956
957    use waft_widgets::testing::{
958        TargetPlatformVariant, WidgetTester, find, test_widgets, test_widgets_variant,
959    };
960
961    use super::*;
962    use crate::app_bar::{AppBar, SliverAppBar};
963    use crate::material::Material;
964    use crate::scaffold::Scaffold;
965    use crate::theme_data::ThemeData;
966    use crate::tooltip::tests::{m3, pump_app};
967
968    /// What `FlexibleSpaceBar.createSettings` is given by an app bar.
969    #[derive(Clone, Copy)]
970    struct Extents {
971        current: f64,
972        min: f64,
973        max: f64,
974    }
975
976    impl Extents {
977        /// An app bar that cannot collapse: `AppBar` conveys one extent for all three.
978        fn fixed(extent: f64) -> Extents {
979            Extents {
980                current: extent,
981                min: extent,
982                max: extent,
983            }
984        }
985    }
986
987    /// A box as wide as the test view and `height` high at the top left, holding `bar` under
988    /// settings of `extents`.
989    fn bar_in_box(extents: Extents, height: f64, bar: FlexibleSpaceBar) -> WidgetRef {
990        let settings = FlexibleSpaceBar::create_settings(extents.current, bar)
991            .min_extent(extents.min)
992            .max_extent(extents.max)
993            .build();
994        Align::new()
995            .alignment(AlignmentGeometry::TOP_LEFT)
996            .child(SizedBox::new().width(800.0).height(height).child(settings))
997            .into_widget()
998    }
999
1000    fn pump_bar(
1001        tester: &mut WidgetTester,
1002        platform: TargetPlatform,
1003        extents: Extents,
1004        height: f64,
1005        bar: FlexibleSpaceBar,
1006    ) {
1007        pump_app(
1008            tester,
1009            move |app| ThemeData::builder().platform(platform).build(app),
1010            move |_app| bar_in_box(extents, height, bar),
1011        );
1012    }
1013
1014    /// A `Text::new("X")` that tests can find.
1015    fn keyed_title(key: &GlobalKey) -> SizedBox {
1016        SizedBox::new()
1017            .key(key.clone().into())
1018            .child(Text::new("X"))
1019    }
1020
1021    /// The global rectangle of `key`'s widget.
1022    fn rect_of_key(tester: &WidgetTester, key: &GlobalKey) -> Rect {
1023        tester.global_rect(tester.render_object(key).as_box().expect("a render box"))
1024    }
1025
1026    /// Dart's `getTitleBottomLeft`: the title's left, and the distance from its bottom to the
1027    /// bottom of the space bar.
1028    fn title_bottom_left(tester: &WidgetTester, key: &GlobalKey) -> Offset {
1029        let title = rect_of_key(tester, key);
1030        let bar = *find::by_type::<FlexibleSpaceBar>()
1031            .evaluate(tester)
1032            .first()
1033            .expect("a FlexibleSpaceBar");
1034        let bar = tester.get_rect(bar);
1035        Offset::new(title.left, bar.bottom - title.bottom)
1036    }
1037
1038    fn title_bottom_left_case(
1039        tester: &mut WidgetTester,
1040        platform: TargetPlatform,
1041        center_title: Option<bool>,
1042        title_padding: Option<EdgeInsetsGeometry>,
1043    ) -> Offset {
1044        let key = GlobalKey::new();
1045        let mut bar = FlexibleSpaceBar::new().title(keyed_title(&key));
1046        if let Some(center_title) = center_title {
1047            bar = bar.center_title(center_title);
1048        }
1049        if let Some(title_padding) = title_padding {
1050            bar = bar.title_padding(title_padding);
1051        }
1052        pump_bar(tester, platform, Extents::fixed(56.0), 56.0, bar);
1053        title_bottom_left(tester, &key)
1054    }
1055
1056    /// Dart's `pumpWidget(Container(key: UniqueKey()))`: clears the widget tree to avoid
1057    /// animating between platforms.
1058    fn clear_tree(tester: &mut WidgetTester) {
1059        tester.pump_widget(
1060            Container::new()
1061                .key(waft_foundation::UniqueKey::new().into())
1062                .into_widget(),
1063        );
1064    }
1065
1066    #[test]
1067    fn flexible_space_bar_centers_title_on_ios() {
1068        test_widgets(|tester| {
1069            let pump = |tester: &mut WidgetTester, platform: TargetPlatform| {
1070                pump_app(
1071                    tester,
1072                    move |app| ThemeData::builder().platform(platform).build(app),
1073                    |_app| {
1074                        Scaffold::new()
1075                            .app_bar(waft_widgets::PreferredSizeWidgetRef::new(
1076                                AppBar::new().flexible_space(
1077                                    FlexibleSpaceBar::new().title(waft_widgets::Text::new("X")),
1078                                ),
1079                            ))
1080                            .into_widget()
1081                    },
1082                );
1083            };
1084            let title = |tester: &WidgetTester| {
1085                tester.global_rect(tester.render_box_of(find::text("X").evaluate(tester)[0]))
1086            };
1087            pump(tester, TargetPlatform::Android);
1088            let rect = title(tester);
1089            assert!(rect.center().dx() < 400.0 - rect.width() / 2.0);
1090
1091            for platform in [TargetPlatform::IOS, TargetPlatform::MacOS] {
1092                // Clear the widget tree to avoid animating between platforms.
1093                tester.pump_widget(
1094                    Container::new()
1095                        .key(waft_foundation::UniqueKey::new().into())
1096                        .into_widget(),
1097                );
1098
1099                pump(tester, platform);
1100                let rect = title(tester);
1101                assert!(rect.center().dx() > 400.0 - rect.width() / 2.0);
1102                assert!(rect.center().dx() < 400.0 + rect.width() / 2.0);
1103            }
1104        });
1105    }
1106
1107    #[test]
1108    fn material3_flexible_space_bar_title_padding_defaults() {
1109        test_widgets(|tester| {
1110            let left = Offset::new(72.0, 16.0);
1111            let center = Offset::new(389.0, 16.0);
1112            let cases = [
1113                (TargetPlatform::Android, None, left),
1114                (TargetPlatform::Android, Some(true), center),
1115                (TargetPlatform::IOS, None, center),
1116                (TargetPlatform::IOS, Some(false), left),
1117                (TargetPlatform::MacOS, None, center),
1118                (TargetPlatform::MacOS, Some(false), left),
1119            ];
1120            let mut previous = None;
1121            for (platform, center_title, expected) in cases {
1122                if previous.is_some() && previous != Some(platform) {
1123                    clear_tree(tester);
1124                }
1125                previous = Some(platform);
1126                assert_eq!(
1127                    title_bottom_left_case(tester, platform, center_title, None),
1128                    expected,
1129                    "{platform:?} with centerTitle {center_title:?}"
1130                );
1131            }
1132        });
1133    }
1134
1135    #[test]
1136    fn material3_flexible_space_bar_title_padding_override() {
1137        test_widgets(|tester| {
1138            let left = Offset::ZERO;
1139            let center = Offset::new(389.0, 0.0);
1140            let cases = [
1141                (TargetPlatform::Android, None, left),
1142                (TargetPlatform::Android, Some(true), center),
1143                (TargetPlatform::IOS, None, center),
1144                (TargetPlatform::IOS, Some(false), left),
1145                (TargetPlatform::MacOS, None, center),
1146                (TargetPlatform::MacOS, Some(false), left),
1147                (TargetPlatform::Windows, None, left),
1148                (TargetPlatform::Windows, Some(true), center),
1149                (TargetPlatform::Linux, None, left),
1150                (TargetPlatform::Linux, Some(true), center),
1151            ];
1152            let mut previous = None;
1153            for (platform, center_title, expected) in cases {
1154                if previous.is_some() && previous != Some(platform) {
1155                    clear_tree(tester);
1156                }
1157                previous = Some(platform);
1158                assert_eq!(
1159                    title_bottom_left_case(
1160                        tester,
1161                        platform,
1162                        center_title,
1163                        Some(EdgeInsetsGeometry::ZERO)
1164                    ),
1165                    expected,
1166                    "{platform:?} with centerTitle {center_title:?}"
1167                );
1168            }
1169        });
1170    }
1171
1172    /// Dart's `TestDelegate`: a header whose extents are the settings' and that builds them.
1173    #[derive(Debug)]
1174    struct TestDelegate {
1175        settings: FlexibleSpaceBarSettings,
1176    }
1177
1178    impl waft_widgets::SliverPersistentHeaderDelegate for TestDelegate {
1179        fn build(
1180            &self,
1181            _app: &mut App,
1182            _context: BuildContext,
1183            _shrink_offset: f64,
1184            _overlaps_content: bool,
1185        ) -> WidgetRef {
1186            self.settings.clone().into_widget()
1187        }
1188
1189        fn min_extent(&self) -> f64 {
1190            self.settings.min_extent
1191        }
1192
1193        fn max_extent(&self) -> f64 {
1194            self.settings.max_extent
1195        }
1196
1197        fn should_rebuild(
1198            &self,
1199            _old_delegate: &dyn waft_widgets::SliverPersistentHeaderDelegate,
1200        ) -> bool {
1201            false
1202        }
1203
1204        fn as_any(&self) -> &dyn std::any::Any {
1205            self
1206        }
1207    }
1208
1209    // This is a regression test for https://github.com/flutter/flutter/issues/132030.
1210    #[test]
1211    fn flexible_space_bar_settings_has_leading_provides_a_gap_between_leading_and_title() {
1212        test_widgets(|tester| {
1213            let custom_settings = FlexibleSpaceBar::create_settings(
1214                200.0,
1215                AppBar::new()
1216                    .leading(waft_widgets::Icon::new(Some(crate::icons::Icons::menu())))
1217                    .flexible_space(
1218                        FlexibleSpaceBar::new()
1219                            .title(waft_widgets::Text::new("title ".repeat(10)))
1220                            // Set centerTitle to false to create a gap between the leading widget
1221                            // and the long title.
1222                            .center_title(false),
1223                    ),
1224            )
1225            .has_leading(true)
1226            .build();
1227
1228            pump_app(tester, m3, move |_app| {
1229                Scaffold::new()
1230                    .body(
1231                        waft_widgets::CustomScrollView::new().slivers([
1232                            waft_widgets::SliverPersistentHeader::new(Rc::new(TestDelegate {
1233                                settings: custom_settings,
1234                            }))
1235                            .floating(true)
1236                            .pinned(true)
1237                            .into_widget(),
1238                            waft_widgets::SliverToBoxAdapter::new()
1239                                .child(
1240                                    Container::new()
1241                                        .height(1200.0)
1242                                        .color(crate::colors::Colors::ORANGE.shade400()),
1243                                )
1244                                .into_widget(),
1245                        ]),
1246                    )
1247                    .into_widget()
1248            });
1249
1250            tester.pump_and_settle();
1251            let text = find::by_type::<waft_widgets::Text>().evaluate(tester)[0];
1252            let left = tester.get_rect(text).left;
1253            assert!((left - 72.0).abs() < 0.01, "{left}");
1254        });
1255    }
1256
1257    #[test]
1258    fn flexible_space_bar_settings_without_a_leading_widget_has_no_gap() {
1259        test_widgets(|tester| {
1260            let key = GlobalKey::new();
1261            let settings = FlexibleSpaceBar::create_settings(
1262                200.0,
1263                FlexibleSpaceBar::new()
1264                    .title(keyed_title(&key))
1265                    .center_title(false),
1266            )
1267            .has_leading(false)
1268            .build();
1269            pump_app(tester, m3, move |_app| settings.into_widget());
1270            assert_eq!(rect_of_key(tester, &key).left, 0.0);
1271        });
1272    }
1273
1274    /// Dart's `Material3 - FlexibleSpaceBarSettings provides settings to a FlexibleSpaceBar`:
1275    /// the title's scale at half way between the extents, and its text colour at the toolbar
1276    /// opacity.
1277    #[test]
1278    fn material3_flexible_space_bar_settings_provides_settings_to_a_flexible_space_bar() {
1279        test_widgets(|tester| {
1280            let style = Rc::new(RefCell::new(None));
1281            let title = Builder::new({
1282                let style = Rc::clone(&style);
1283                move |app, context| {
1284                    *style.borrow_mut() = Some(DefaultTextStyle::of(app, context).style.clone());
1285                    SizedBox::shrink().into_widget()
1286                }
1287            });
1288            let settings = FlexibleSpaceBar::create_settings(
1289                200.0,
1290                FlexibleSpaceBar::new()
1291                    .title(title)
1292                    .background(SizedBox::shrink())
1293                    .collapse_mode(CollapseMode::Pin),
1294            )
1295            .min_extent(100.0)
1296            .max_extent(300.0)
1297            .toolbar_opacity(0.5)
1298            .build();
1299            pump_app(tester, m3, move |_app| {
1300                Align::new()
1301                    .alignment(AlignmentGeometry::TOP_LEFT)
1302                    .child(SizedBox::new().width(800.0).height(300.0).child(settings))
1303                    .into_widget()
1304            });
1305
1306            // The current (200) is half way between the min (100) and max (300) and the
1307            // lerp values used to calculate the scale are 1 and 1.5, so we check for 1.25.
1308            let transform = find::by_type::<Transform>().evaluate(tester);
1309            let transform = *transform.first().expect("the title's Transform");
1310            let scale = tester.widget(transform, |transform: &Transform| transform.transform);
1311            assert_eq!(scale, Matrix4::scale(1.25, 1.25));
1312
1313            // The space bar rect always starts fully expanded.
1314            let clip_rect = *find::by_type::<ClipRect>()
1315                .evaluate(tester)
1316                .last()
1317                .expect("the space bar's ClipRect");
1318            let clip_size = tester.render_box_of(clip_rect).size(&tester.cell.borrow());
1319            assert_eq!(clip_size.height(), 300.0);
1320
1321            let style = style.borrow().clone().expect("the title was built");
1322            #[allow(deprecated)]
1323            let alpha = style.color.expect("a title colour").alpha();
1324            assert_eq!(alpha, 128); // Which is alpha of .5
1325        });
1326    }
1327
1328    /// Dart's `tester.getRect(finder)`: `element`'s box with both corners mapped to the view,
1329    /// so a scale above it scales the rectangle.
1330    fn transformed_rect(tester: &WidgetTester, element: waft_widgets::AnyElement) -> Rect {
1331        let render = tester.render_box_of(element);
1332        let app = tester.cell.borrow();
1333        let size = render.size(&app);
1334        let top_left = render.local_to_global(&app, Offset::ZERO, None);
1335        let bottom_right =
1336            render.local_to_global(&app, Offset::new(size.width(), size.height()), None);
1337        Rect::from_ltrb(
1338            top_left.dx(),
1339            top_left.dy(),
1340            bottom_right.dx(),
1341            bottom_right.dy(),
1342        )
1343    }
1344
1345    const TITLE_FONT_SIZE: f64 = 20.0;
1346    const EXPANDED_HEIGHT: f64 = 300.0;
1347
1348    /// The title of the width-constraint cases: Dart's `Text('X' * count, maxLines: 1,
1349    /// overflow: TextOverflow.ellipsis, style: style)`, which the box's constraints cut to
1350    /// one line as wide as they allow.
1351    fn constrained_title(count: usize, style: TextStyle) -> WidgetRef {
1352        Text::new("X".repeat(count))
1353            .max_lines(1)
1354            .overflow(TextOverflow::Ellipsis)
1355            .style(style)
1356            .into_widget()
1357    }
1358
1359    /// The `SliverAppBar(expandedHeight: 300, pinned: true, stretch: true, flexibleSpace:
1360    /// FlexibleSpaceBar(titlePadding: EdgeInsets.zero, title: title, centerTitle: false))` of
1361    /// the width-constraint cases.
1362    fn constrained_title_app_bar(
1363        title: WidgetRef,
1364        expanded_title_scale: Option<f64>,
1365    ) -> SliverAppBar {
1366        let mut bar = FlexibleSpaceBar::new()
1367            .title_padding(EdgeInsetsGeometry::ZERO)
1368            .title(title)
1369            .center_title(false);
1370        if let Some(expanded_title_scale) = expanded_title_scale {
1371            bar = bar.expanded_title_scale(expanded_title_scale);
1372        }
1373        SliverAppBar::new()
1374            .expanded_height(EXPANDED_HEIGHT)
1375            .pinned(true)
1376            .stretch(true)
1377            .flexible_space(bar)
1378    }
1379
1380    /// Dart's 'FlexibleSpaceBar sets width constraints for the title' under `theme`, its title
1381    /// styled `style`: the global rectangle of the title.
1382    fn width_constrained_title_rect(
1383        tester: &mut WidgetTester,
1384        theme: fn(&App) -> ThemeData,
1385        style: TextStyle,
1386    ) -> Rect {
1387        let width = Rc::new(std::cell::Cell::new(0.0));
1388        let seen_width = Rc::clone(&width);
1389        pump_app(tester, theme, move |_app| {
1390            Scaffold::new()
1391                .body(Builder::new(move |app, context| {
1392                    seen_width.set(waft_widgets::MediaQuery::size_of(app, context).width());
1393                    waft_widgets::CustomScrollView::new()
1394                        .slivers([constrained_title_app_bar(
1395                            constrained_title(2000, style.clone()),
1396                            None,
1397                        )
1398                        .into_widget()])
1399                        .into_widget()
1400                }))
1401                .into_widget()
1402        });
1403        let text_width = width.get();
1404        assert_eq!(text_width, 800.0);
1405        let title = find::by_type::<Text>().evaluate(tester)[0];
1406        transformed_rect(tester, title)
1407    }
1408
1409    fn assert_rect_more_or_less_equals(actual: Rect, expected: Rect) {
1410        const EPSILON: f64 = 0.0001;
1411        assert!(
1412            (actual.left - expected.left).abs() <= EPSILON
1413                && (actual.top - expected.top).abs() <= EPSILON
1414                && (actual.right - expected.right).abs() <= EPSILON
1415                && (actual.bottom - expected.bottom).abs() <= EPSILON,
1416            "{actual:?} is not {expected:?}"
1417        );
1418    }
1419
1420    #[test]
1421    fn material3_flexible_space_bar_sets_width_constraints_for_the_title() {
1422        test_widgets(|tester| {
1423            let rect = width_constrained_title_rect(
1424                tester,
1425                m3,
1426                TextStyle::new().font_size(TITLE_FONT_SIZE).height(1.0),
1427            );
1428            // The title is scaled and transformed to be 1.5 times bigger, when the
1429            // FlexibleSpaceBar is fully expanded, thus we expect the width to be
1430            // 1.5 times smaller than the full width. The height of the text is the same
1431            // as the font size, with 10 dps bottom margin.
1432            assert_rect_more_or_less_equals(
1433                rect,
1434                Rect::from_ltrb(
1435                    0.0,
1436                    EXPANDED_HEIGHT - TITLE_FONT_SIZE - 10.0,
1437                    800.0,
1438                    EXPANDED_HEIGHT,
1439                ),
1440            );
1441        });
1442    }
1443
1444    // This is a regression test for https://github.com/flutter/flutter/issues/14227
1445    #[test]
1446    fn material2_flexible_space_bar_sets_width_constraints_for_the_title() {
1447        test_widgets(|tester| {
1448            let rect = width_constrained_title_rect(
1449                tester,
1450                crate::tooltip::tests::m2,
1451                TextStyle::new().font_size(TITLE_FONT_SIZE),
1452            );
1453            assert_rect_more_or_less_equals(
1454                rect,
1455                Rect::from_ltrb(
1456                    0.0,
1457                    EXPANDED_HEIGHT - TITLE_FONT_SIZE - 10.0,
1458                    800.0,
1459                    EXPANDED_HEIGHT,
1460                ),
1461            );
1462        });
1463    }
1464
1465    /// Dart's 'FlexibleSpaceBar sets constraints for the title - override expandedTitleScale'
1466    /// under `theme`, its title styled `style`.
1467    fn expanded_title_scale_case(
1468        tester: &mut WidgetTester,
1469        theme: fn(&App) -> ThemeData,
1470        style: TextStyle,
1471    ) {
1472        const EXPANDED_TITLE_SCALE: f64 = 3.0;
1473        pump_app(tester, theme, move |_app| {
1474            Scaffold::new()
1475                .body(
1476                    waft_widgets::CustomScrollView::new().slivers([
1477                        constrained_title_app_bar(
1478                            constrained_title(41, style.clone()),
1479                            Some(EXPANDED_TITLE_SCALE),
1480                        )
1481                        .into_widget(),
1482                        waft_widgets::SliverList::builder(|_app, _context, index| {
1483                            Some(
1484                                SizedBox::new()
1485                                    .height(200.0)
1486                                    .child(
1487                                        Center::new().child(waft_widgets::Text::new(format!(
1488                                            "Item {index}"
1489                                        ))),
1490                                    )
1491                                    .into_widget(),
1492                            )
1493                        })
1494                        .item_count(3)
1495                        .into_widget(),
1496                    ]),
1497                )
1498                .into_widget()
1499        });
1500        let center_of_text = |tester: &WidgetTester, text: &str| {
1501            let element = find::text(text).evaluate(tester)[0];
1502            tester.get_rect(element).center()
1503        };
1504
1505        // We drag up to fully collapse the space bar.
1506        let start = center_of_text(tester, "Item 0");
1507        tester.drag_from(start, Offset::new(0.0, -600.0), 1);
1508        tester.pump_and_settle();
1509
1510        let title = |tester: &WidgetTester| find::by_type::<Text>().evaluate(tester)[0];
1511        let collapsed_width = transformed_rect(tester, title(tester)).width();
1512
1513        // We drag down to fully expand the space bar.
1514        let start = center_of_text(tester, "Item 2");
1515        tester.drag_from(start, Offset::new(0.0, 600.0), 2);
1516        tester.pump_and_settle();
1517
1518        // The title is shifted by this margin to maintain the position of the
1519        // bottom edge.
1520        let bottom_margin = TITLE_FONT_SIZE * (EXPANDED_TITLE_SCALE - 1.0);
1521
1522        let text_width = collapsed_width;
1523        // The title is scaled and transformed to be 3 times bigger, when the
1524        // FlexibleSpaceBar is fully expanded, thus we expect the width to be
1525        // 3 times smaller than the full width. The height of the text is the same
1526        // as the font size, with 40 dps bottom margin to maintain its bottom position.
1527        assert_rect_more_or_less_equals(
1528            transformed_rect(tester, title(tester)),
1529            Rect::from_ltrb(
1530                0.0,
1531                EXPANDED_HEIGHT - TITLE_FONT_SIZE - bottom_margin,
1532                text_width,
1533                EXPANDED_HEIGHT,
1534            ),
1535        );
1536    }
1537
1538    #[test]
1539    fn material3_flexible_space_bar_sets_constraints_for_the_title_override_expanded_title_scale() {
1540        test_widgets(|tester| {
1541            expanded_title_scale_case(
1542                tester,
1543                m3,
1544                TextStyle::new().font_size(TITLE_FONT_SIZE).height(1.0),
1545            );
1546        });
1547    }
1548
1549    #[test]
1550    fn material2_flexible_space_bar_sets_constraints_for_the_title_override_expanded_title_scale() {
1551        test_widgets(|tester| {
1552            expanded_title_scale_case(
1553                tester,
1554                crate::tooltip::tests::m2,
1555                TextStyle::new().font_size(TITLE_FONT_SIZE),
1556            );
1557        });
1558    }
1559
1560    /// Dart's `FlexibleSpaceBar.background is visible when using height other than
1561    /// kToolbarHeight`: an app bar that cannot collapse shows its background in full.
1562    #[test]
1563    fn flexible_space_bar_background_is_visible_when_using_height_other_than_k_toolbar_height() {
1564        test_widgets(|tester| {
1565            pump_bar(
1566                tester,
1567                TargetPlatform::Android,
1568                Extents::fixed(300.0),
1569                300.0,
1570                FlexibleSpaceBar::new()
1571                    .title(Text::new("Title"))
1572                    .background(Text::new("Background"))
1573                    .collapse_mode(CollapseMode::Pin),
1574            );
1575            let opacity = *find::by_type::<FlexibleSpaceHeaderOpacity>()
1576                .evaluate(tester)
1577                .first()
1578                .expect("a FlexibleSpaceHeaderOpacity");
1579            assert_eq!(
1580                tester.widget(opacity, |widget: &FlexibleSpaceHeaderOpacity| widget
1581                    .opacity),
1582                1.0
1583            );
1584        });
1585    }
1586
1587    // This is a regression test for https://github.com/flutter/flutter/issues/138608.
1588    #[test]
1589    fn flexible_space_bar_centers_title_with_a_leading_widget() {
1590        test_widgets(|tester| {
1591            pump_app(tester, m3, |_app| {
1592                Material::new()
1593                    .child(
1594                        waft_widgets::CustomScrollView::new().slivers([SliverAppBar::new()
1595                            .leading(waft_widgets::Icon::new(Some(crate::icons::Icons::menu())))
1596                            .flexible_space(
1597                                FlexibleSpaceBar::new()
1598                                    .center_title(true)
1599                                    .title(waft_widgets::Text::new("X")),
1600                            )
1601                            .into_widget()]),
1602                    )
1603                    .into_widget()
1604            });
1605
1606            let app_bar = find::by_type::<AppBar>().evaluate(tester)[0];
1607            let app_bar_center = tester.get_rect(app_bar).center();
1608            let title = find::text("X").evaluate(tester)[0];
1609            let title_center = tester.get_rect(title).center();
1610            assert_eq!(app_bar_center.dx(), title_center.dx());
1611        });
1612    }
1613
1614    // This is a regression test for https://github.com/flutter/flutter/issues/138296.
1615    #[test]
1616    fn material3_default_title_color() {
1617        test_widgets(|tester| {
1618            let theme = ThemeData::new(&tester.cell.borrow());
1619            pump_app(tester, m3, |_app| {
1620                Material::new()
1621                    .child(
1622                        waft_widgets::CustomScrollView::new().slivers([SliverAppBar::new()
1623                            .flexible_space(
1624                                FlexibleSpaceBar::new().title(waft_widgets::Text::new("Title")),
1625                            )
1626                            .into_widget()]),
1627                    )
1628                    .into_widget()
1629            });
1630
1631            let title = find::text("Title").evaluate(tester)[0];
1632            let style = DefaultTextStyle::of(&mut tester.cell.borrow_mut(), title).style;
1633            assert_eq!(
1634                style.color,
1635                theme.text_theme.title_large.expect("a style").color
1636            );
1637        });
1638    }
1639
1640    #[test]
1641    fn flexible_space_bar_does_not_crash_at_zero_area() {
1642        test_widgets(|tester| {
1643            pump_app(tester, m3, |_app| {
1644                Center::new()
1645                    .child(SizedBox::shrink().child(Scaffold::new().app_bar(
1646                        waft_widgets::PreferredSizeWidgetRef::new(AppBar::new().flexible_space(
1647                            FlexibleSpaceBar::new().title(waft_widgets::Text::new("X")),
1648                        )),
1649                    )))
1650                    .into_widget()
1651            });
1652            let bar = *find::by_type::<FlexibleSpaceBar>()
1653                .evaluate(tester)
1654                .first()
1655                .expect("a FlexibleSpaceBar");
1656            assert_eq!(
1657                tester.render_box_of(bar).size(&tester.cell.borrow()),
1658                Size::ZERO
1659            );
1660        });
1661    }
1662
1663    /// The top of the background at `current`, in a space bar that collapses from 250 to 56 and
1664    /// is as high as `current`: the position the Dart collapse mode cases read after dragging
1665    /// the scroll view by `250 - current`.
1666    fn background_top(tester: &mut WidgetTester, collapse_mode: CollapseMode, current: f64) -> f64 {
1667        let key = GlobalKey::new();
1668        pump_bar(
1669            tester,
1670            TargetPlatform::Android,
1671            Extents {
1672                current,
1673                min: 56.0,
1674                max: 250.0,
1675            },
1676            current,
1677            FlexibleSpaceBar::new()
1678                .background(Container::new().key(key.clone().into()))
1679                .collapse_mode(collapse_mode),
1680        );
1681        rect_of_key(tester, &key).top
1682    }
1683
1684    #[test]
1685    fn flexible_space_bar_collapse_mode_none() {
1686        test_widgets(|tester| {
1687            assert_eq!(background_top(tester, CollapseMode::None, 250.0), 0.0);
1688            assert_eq!(background_top(tester, CollapseMode::None, 150.0), 0.0);
1689        });
1690    }
1691
1692    #[test]
1693    fn flexible_space_bar_collapse_mode_pin() {
1694        test_widgets(|tester| {
1695            assert_eq!(background_top(tester, CollapseMode::Pin, 250.0), 0.0);
1696            assert_eq!(background_top(tester, CollapseMode::Pin, 150.0), -100.0);
1697        });
1698    }
1699
1700    #[test]
1701    fn flexible_space_bar_collapse_mode_parallax() {
1702        test_widgets(|tester| {
1703            assert_eq!(background_top(tester, CollapseMode::Parallax, 250.0), 0.0);
1704            let top = background_top(tester, CollapseMode::Parallax, 150.0);
1705            assert!(top < 10.0);
1706            assert!(top > -50.0);
1707        });
1708    }
1709
1710    /// The background's size when the space bar is `height` high and its settings say it
1711    /// expands to 250: more than that is the overscroll a stretching `SliverAppBar` gives it.
1712    fn background_height(
1713        tester: &mut WidgetTester,
1714        stretch_modes: Vec<StretchMode>,
1715        height: f64,
1716    ) -> f64 {
1717        let key = GlobalKey::new();
1718        pump_bar(
1719            tester,
1720            TargetPlatform::Android,
1721            Extents {
1722                current: 250.0,
1723                min: 56.0,
1724                max: 250.0,
1725            },
1726            height,
1727            FlexibleSpaceBar::new()
1728                .background(Container::new().key(key.clone().into()))
1729                .stretch_modes(stretch_modes),
1730        );
1731        rect_of_key(tester, &key).height()
1732    }
1733
1734    #[test]
1735    fn flexible_space_bar_stretch_mode_default_zoom_background() {
1736        test_widgets(|tester| {
1737            let before = background_height(tester, vec![StretchMode::ZoomBackground], 250.0);
1738            let after = background_height(tester, vec![StretchMode::ZoomBackground], 350.0);
1739            assert!(before < after);
1740        });
1741    }
1742
1743    #[test]
1744    fn flexible_space_bar_stretch_mode_blur_background_does_not_zoom_the_background() {
1745        test_widgets(|tester| {
1746            let before = background_height(tester, vec![StretchMode::BlurBackground], 250.0);
1747            let after = background_height(tester, vec![StretchMode::BlurBackground], 350.0);
1748            assert_eq!(before, after);
1749        });
1750    }
1751
1752    /// Dart's `FlexibleSpaceBar stretch mode blurBackground` is a golden case; this checks what
1753    /// the golden shows the cause of: the backdrop filter is there only while stretched.
1754    #[test]
1755    fn flexible_space_bar_stretch_mode_blur_background_blurs_only_when_stretched() {
1756        test_widgets(|tester| {
1757            for (height, filters) in [(250.0, 0), (350.0, 1)] {
1758                pump_bar(
1759                    tester,
1760                    TargetPlatform::Android,
1761                    Extents {
1762                        current: 250.0,
1763                        min: 56.0,
1764                        max: 250.0,
1765                    },
1766                    height,
1767                    FlexibleSpaceBar::new()
1768                        .stretch_modes(vec![StretchMode::BlurBackground])
1769                        .background(Container::new()),
1770                );
1771                assert_eq!(
1772                    find::by_type::<waft_widgets::BackdropFilter>()
1773                        .evaluate(tester)
1774                        .len(),
1775                    filters
1776                );
1777            }
1778        });
1779    }
1780
1781    /// The opacity of the `Opacity` around the title when the space bar is `height` high.
1782    fn fade_title_opacity(tester: &mut WidgetTester, height: f64) -> f64 {
1783        let key = GlobalKey::new();
1784        pump_bar(
1785            tester,
1786            TargetPlatform::Android,
1787            Extents {
1788                current: 250.0,
1789                min: 56.0,
1790                max: 250.0,
1791            },
1792            height,
1793            FlexibleSpaceBar::new()
1794                .stretch_modes(vec![StretchMode::FadeTitle])
1795                .title(keyed_title(&key)),
1796        );
1797        let title = *find::by_type::<SizedBox>()
1798            .evaluate(tester)
1799            .iter()
1800            .find(|element| {
1801                tester.ancestors(**element).iter().any(|ancestor| {
1802                    let app = tester.cell.borrow();
1803                    waft_widgets::downcast_widget::<Opacity>(&**ancestor.widget(&app)).is_some()
1804                })
1805            })
1806            .expect("a title under an Opacity");
1807        let opacity = tester.ancestor_of_type::<Opacity>(title);
1808        tester.widget(opacity, |opacity: &Opacity| opacity.opacity)
1809    }
1810
1811    #[test]
1812    fn flexible_space_bar_stretch_mode_fade_title() {
1813        test_widgets(|tester| {
1814            assert_eq!(fade_title_opacity(tester, 260.0).round(), 1.0);
1815            assert_eq!(fade_title_opacity(tester, 350.0), 0.0);
1816        });
1817    }
1818
1819    /// Dart's `RenderRebuildTracker`: a painter that counts its paints.
1820    struct PaintCounter {
1821        count: Rc<std::cell::Cell<usize>>,
1822    }
1823
1824    impl waft_rendering::CustomPainter for PaintCounter {
1825        fn paint(&self, _app: &mut App, _canvas: &mut waft_embedder::Canvas, _size: Size) {
1826            self.count.set(self.count.get() + 1);
1827        }
1828
1829        fn should_repaint(
1830            &self,
1831            _app: &App,
1832            _old_delegate: &dyn waft_rendering::CustomPainter,
1833        ) -> bool {
1834            false
1835        }
1836
1837        fn as_any(&self) -> &dyn std::any::Any {
1838            self
1839        }
1840    }
1841
1842    /// Pumps on `tester` a space bar with `background`, at `current` of an app bar that
1843    /// collapses from 200 to 56 and is as high as `current`, where Dart's cases drag the
1844    /// `SliverAppBar` to; answers the alpha of the `OpacityLayer` around the background.
1845    fn pump_collapsing<K>(
1846        tester: &mut WidgetTester,
1847        current: f64,
1848        background: impl IntoWidget<K>,
1849    ) -> Option<i32> {
1850        pump_bar(
1851            tester,
1852            TargetPlatform::Android,
1853            Extents {
1854                current,
1855                min: 56.0,
1856                max: 200.0,
1857            },
1858            current,
1859            FlexibleSpaceBar::new().background(background),
1860        );
1861        let render = tester.first::<RenderFlexibleSpaceHeaderOpacity>();
1862        let app = tester.cell.borrow();
1863        render
1864            .as_object()
1865            .layer_as::<OpacityLayer>(&app)
1866            .map(|layer| layer.alpha(&app).expect("an alpha"))
1867    }
1868
1869    /// Dart's `FlexibleSpaceBar rebuilds when scrolling.`, with the space bar's extents given
1870    /// where the scrolled `SliverAppBar` would have them: expanded, collapsing, collapsed.
1871    #[test]
1872    fn flexible_space_bar_rebuilds_when_scrolling() {
1873        test_widgets(|tester| {
1874            let count = Rc::new(std::cell::Cell::new(0));
1875            let background = || {
1876                waft_widgets::AspectRatio::new(1.7).child(waft_widgets::CustomPaint::new().painter(
1877                    PaintCounter {
1878                        count: Rc::clone(&count),
1879                    },
1880                ))
1881            };
1882
1883            assert_eq!(pump_collapsing(tester, 200.0, background()), Some(255));
1884            assert_eq!(count.get(), 1);
1885
1886            let alpha = pump_collapsing(tester, 80.0, background()).expect("a layer while fading");
1887            assert!(alpha < 255);
1888
1889            assert_eq!(pump_collapsing(tester, 56.0, background()), None);
1890            assert!(count.get() > 1);
1891            assert!(
1892                tester
1893                    .all::<RenderFlexibleSpaceHeaderOpacity>()
1894                    .iter()
1895                    .all(|render| {
1896                        let app = tester.cell.borrow();
1897                        render.as_object().layer_as::<OpacityLayer>(&app).is_none()
1898                    })
1899            );
1900        });
1901    }
1902
1903    /// Dart's `_FlexibleSpaceHeaderOpacity with near zero opacity avoids compositing`, with the
1904    /// space bar's extent given where the dragged `SliverAppBar` would have it.
1905    #[test]
1906    fn flexible_space_header_opacity_with_near_zero_opacity_avoids_compositing() {
1907        for platform in [
1908            TargetPlatform::Android,
1909            TargetPlatform::IOS,
1910            TargetPlatform::Fuchsia,
1911        ] {
1912            test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
1913                let pump = |tester: &mut WidgetTester, current: f64| {
1914                    pump_bar(
1915                        tester,
1916                        platform,
1917                        Extents {
1918                            current,
1919                            min: 56.0,
1920                            max: 200.0,
1921                        },
1922                        current,
1923                        FlexibleSpaceBar::new().background(SizedBox::new()),
1924                    );
1925                };
1926                pump(tester, 200.0);
1927                // Ensure collapsed height - current extent is near zero for the
1928                // FlexibleSpaceBar to avoid compositing.
1929                pump(tester, 56.087_878_920_261_29);
1930                tester.pump_and_settle();
1931                let render = tester.first::<RenderFlexibleSpaceHeaderOpacity>();
1932                let app = tester.cell.borrow();
1933                assert!(
1934                    render.as_object().layer_as::<OpacityLayer>(&app).is_none(),
1935                    "{platform:?}"
1936                );
1937            });
1938        }
1939    }
1940
1941    /// Dart's `_RenderFlexibleSpaceHeaderOpacity` fills no properties of its own; it inherits
1942    /// `RenderOpacity.debugFillProperties`'s `opacity` line.
1943    #[test]
1944    fn a_header_opacity_fills_the_opacity_it_inherits() {
1945        use waft_foundation::{AppCell, DiagnosticPropertiesBuilder, DiagnosticsNode};
1946
1947        let cell = AppCell::new();
1948        let mut app = cell.borrow_mut();
1949        let render = RenderFlexibleSpaceHeaderOpacity::new(&mut app, 0.5);
1950        let mut properties = DiagnosticPropertiesBuilder::new();
1951        RenderObject::debug_fill_properties(render, &app, &mut properties);
1952        let names: Vec<&str> = properties
1953            .properties
1954            .iter()
1955            .filter_map(|property| property.name())
1956            .collect();
1957        assert_eq!(names, ["opacity"]);
1958    }
1959}