Skip to main content

waft_material/
tabs.rs

1//! Flutter counterpart: material_ui's `tabs.dart` (and `generated/tabs_defaults_m3.g.dart`).
2
3use std::any::Any;
4use std::cell::{Cell, RefCell};
5use std::f64::consts::PI;
6use std::fmt;
7use std::rc::{Rc, Weak};
8use std::time::Duration;
9
10use waft_animation::{
11    Animation, AnimationRef, AnimationStatus, AnimationStatusListener, AnimationWithParent,
12    AnyAnimation, ColorTween, CurvedAnimation, Curves, ReverseAnimation,
13    k_always_dismissed_animation,
14};
15use waft_embedder::{
16    Brightness, Canvas, Clip, Color, Offset, Paint, PaintStyle, Rect, SemanticsRole, Size, Stroke,
17    TextBaseline, TextDirection, clamp_double, lerp_double,
18};
19use waft_foundation::{
20    App, ChangeNotifier, ChangeNotifierData, DiagnosticPropertiesBuilder, DiagnosticsNode, Handle,
21    K_IS_WEB, Listenable, ListenableObject, Listener, MergingListenable, OptionRetained, Ref,
22    StringProperty, Task, ValueChanged,
23};
24use waft_gestures::DragStartBehavior;
25use waft_painting::{
26    AlignmentGeometry, AnyColor, Axis, BorderRadius, BorderStyle, BoxPainter, BoxShape,
27    DecorationRef, EdgeInsetsDirectional, EdgeInsetsGeometry, ImageConfiguration, TextOverflow,
28    TextScaler, TextStyle, VerticalDirection, draw_line,
29};
30use waft_rendering::{
31    AnyRenderBox, AnyRenderObject, BoxConstraints, BoxHitTestResult, ContainerBoxParentData,
32    ContainerRenderObjectData, ContainerRenderObjectMixin, CrossAxisAlignment, CustomPainter,
33    FlexParentData, MainAxisAlignment, MainAxisSize, PaintingContext, PipelineOwner, RenderBox,
34    RenderBoxContainerDefaultsMixin, RenderBoxData, RenderFlexData, RenderFlexMixin, RenderHandle,
35    RenderObject, RenderObjectData, ViewportOffset,
36};
37use waft_scheduler::{FrameCallback, SchedulerBinding};
38use waft_services::MouseCursorRef;
39use waft_widgets::{
40    Align, AnimatedBuilder, AnimatedWidget, AnyScrollPosition, BoxDecoration, BuildContext, Center,
41    ClampingScrollPhysics, Column, Container, CustomPaint, DefaultTextStyle, Directionality,
42    Expanded, Flex, GlobalKey, IconTheme, IconThemeData, IntoWidget, KeyRef, KeyedSubtree,
43    LimitedBox, MaybeWidgetStateProperty, MediaQuery, MergeSemantics, MultiChildRenderObjectWidget,
44    NotificationListener, Padding, PageController, PageScrollPhysics, PageView,
45    PreferredSizeWidget, RenderObjectWidget, Row, ScrollActivityDelegate, ScrollConfiguration,
46    ScrollContext, ScrollControllerData, ScrollControllerLeaf, ScrollEndNotification,
47    ScrollNotification, ScrollPhysics, ScrollPhysicsRef, ScrollPosition, ScrollPositionBase,
48    ScrollPositionData, ScrollPositionRef, ScrollPositionWithSingleContext,
49    ScrollPositionWithSingleContextData, ScrollPositionWithSingleContextLeaf,
50    ScrollUpdateNotification, Semantics, SingleChildScrollView, SizedBox, Stack, State, StateData,
51    StatefulWidget, StatelessWidget, Text, WidgetRef, WidgetState, WidgetStateMouseCursor,
52    WidgetStateProperty, WidgetStatePropertyRef, WidgetStates,
53};
54
55use crate::colors::Colors;
56use crate::constants::{
57    K_DEFAULT_ICON_DARK_COLOR, K_DEFAULT_ICON_LIGHT_COLOR, K_TAB_LABEL_PADDING,
58    K_TAB_SCROLL_DURATION,
59};
60use crate::debug::{debug_check_has_material, debug_check_has_material_localizations};
61use crate::ink_well::{InkWell, InteractiveInkFeatureFactoryRef};
62use crate::material::{Material, MaterialType};
63use crate::material_localizations::MaterialLocalizations;
64use crate::tab_bar_theme::{TabBarTheme, TabBarThemeData, TabBarThemeDataGetters};
65use crate::tab_controller::{DefaultTabController, TabController};
66use crate::tab_indicator::UnderlineTabIndicator;
67use crate::theme::Theme;
68
69use crate::generated::tabs_defaults_m3::{TabsPrimaryDefaultsM3, TabsSecondaryDefaultsM3};
70use crate::theme_data_getters::DefaultsContext;
71
72const K_TAB_HEIGHT: f64 = 46.0;
73const K_TEXT_AND_ICON_TAB_HEIGHT: f64 = 72.0;
74const K_START_OFFSET: f64 = 52.0;
75const K_MIN_PRIMARY_TAB_INDICATOR_WIDTH: f64 = 24.0;
76
77/// Defines how the bounds of the selected tab indicator are computed.
78///
79/// See also:
80///
81///  * `TabBar`, which displays a row of tabs.
82///  * `TabBarView`, which displays a widget for the currently selected tab.
83///  * `TabBar::indicator`, which defines the appearance of the selected tab
84///    indicator relative to the tab's bounds.
85#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
86pub enum TabBarIndicatorSize {
87    /// The tab indicator's bounds are as wide as the space occupied by the tab
88    /// in the tab bar: from the right edge of the previous tab to the left edge
89    /// of the next tab.
90    Tab,
91
92    /// The tab's bounds are only as wide as the (centered) tab widget itself.
93    ///
94    /// This value is used to align the tab's label, typically a `Tab`
95    /// widget's text or icon, with the selected tab indicator.
96    Label,
97}
98
99/// Defines how tabs are aligned horizontally in a `TabBar`.
100///
101/// See also:
102///
103///   * `TabBar`, which displays a row of tabs.
104///   * `TabBarView`, which displays a widget for the currently selected tab.
105///   * `TabBar::tab_alignment`, which defines the horizontal alignment of the
106///     tabs within the `TabBar`.
107#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
108pub enum TabAlignment {
109    // TODO(tahatesser): Add a link to the Material Design spec for
110    // horizontal offset when it is available.
111    // It's currently sourced from androidx/compose/material3/TabRow.kt.
112    /// If `TabBar::is_scrollable` is true, tabs are aligned to the
113    /// start of the `TabBar`. Otherwise throws an exception.
114    ///
115    /// It is not recommended to set [`TabAlignment::Start`] when
116    /// `ThemeData::use_material3` is false.
117    Start,
118
119    /// If `TabBar::is_scrollable` is true, tabs are aligned to the
120    /// start of the `TabBar` with an offset of 52.0 pixels.
121    /// Otherwise throws an exception.
122    ///
123    /// It is not recommended to set [`TabAlignment::StartOffset`] when
124    /// `ThemeData::use_material3` is false.
125    StartOffset,
126
127    /// If `TabBar::is_scrollable` is false, tabs are stretched to fill the
128    /// `TabBar`. Otherwise throws an exception.
129    Fill,
130
131    /// Tabs are aligned to the center of the `TabBar`.
132    Center,
133}
134
135/// Defines how the tab indicator animates when the selected tab changes.
136///
137/// See also:
138///  * `TabBar`, which displays a row of tabs.
139///  * `TabBarThemeData`, which can be used to configure the appearance of the tab
140///    indicator.
141#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
142pub enum TabIndicatorAnimation {
143    /// The tab indicator animates linearly.
144    Linear,
145
146    /// The tab indicator animates with an elastic effect.
147    Elastic,
148}
149
150/// A Material Design `TabBar` tab.
151///
152/// If both [`icon`](Self::icon) and [`text`](Self::text) are provided, the text is displayed
153/// below the icon.
154///
155/// See also:
156///
157///  * [`TabBar`], which displays a row of tabs.
158///  * [`TabBarView`], which displays a widget for the currently selected tab.
159///  * [`TabController`], which coordinates tab selection between a [`TabBar`] and a
160///    [`TabBarView`].
161///  * <https://material.io/design/components/tabs.html>
162#[derive(Debug, Default)]
163pub struct Tab {
164    pub key: Option<KeyRef>,
165
166    /// The text to display as the tab's label.
167    ///
168    /// Must not be used in combination with [`child`](Self::child).
169    pub text: Option<String>,
170
171    /// The widget to be used as the tab's label.
172    ///
173    /// Usually a `Text` widget, possibly wrapped in a `Semantics` widget.
174    ///
175    /// Must not be used in combination with [`text`](Self::text).
176    pub child: Option<WidgetRef>,
177
178    /// An icon to display as the tab's label.
179    pub icon: Option<WidgetRef>,
180
181    /// The margin added around the tab's icon.
182    ///
183    /// Only useful when used in combination with [`icon`](Self::icon), and either one of
184    /// [`text`](Self::text) or [`child`](Self::child) is non-null.
185    ///
186    /// Defaults to 2 pixels of bottom margin. If `ThemeData::use_material3` is false,
187    /// then defaults to 10 pixels of bottom margin.
188    pub icon_margin: Option<EdgeInsetsGeometry>,
189
190    /// The height of the [`Tab`].
191    ///
192    /// If null, the height will be calculated based on the content of the [`Tab`]. When `icon`
193    /// is not null along with `child` or `text`, the default height is 72.0 pixels. Without an
194    /// `icon`, the height is 46.0 pixels.
195    ///
196    /// The provided tab height cannot be lower than the default height. Use
197    /// `PreferredSize` widget to adjust the overall [`TabBar`] height and match
198    /// the provided tab [`height`](Self::height).
199    pub height: Option<f64>,
200}
201
202impl Tab {
203    /// Creates a Material Design [`TabBar`] tab; Dart's named arguments are the setters.
204    ///
205    /// At least one of [`text`](Self::text), [`icon`](Self::icon), and [`child`](Self::child)
206    /// must be non-null. The [`text`](Self::text) and [`child`](Self::child) arguments must not
207    /// be used at the same time. The [`icon_margin`](Self::icon_margin) is only useful when
208    /// [`icon`](Self::icon) and either one of [`text`](Self::text) or [`child`](Self::child) is
209    /// non-null.
210    pub fn new() -> Tab {
211        Tab::default()
212    }
213
214    /// Dart `Tab(key:)`.
215    pub fn key(mut self, key: KeyRef) -> Tab {
216        self.key = Some(key);
217        self
218    }
219
220    /// Dart `Tab(text:)`.
221    pub fn text(mut self, text: impl Into<String>) -> Tab {
222        self.text = Some(text.into());
223        self
224    }
225
226    /// Dart `Tab(icon:)`.
227    #[cfg_attr(debug_assertions, track_caller)]
228    pub fn icon<K>(mut self, icon: impl IntoWidget<K>) -> Tab {
229        self.icon = Some(icon.into_widget());
230        self
231    }
232
233    /// Dart `Tab(iconMargin:)`.
234    pub fn icon_margin(mut self, icon_margin: impl Into<EdgeInsetsGeometry>) -> Tab {
235        self.icon_margin = Some(icon_margin.into());
236        self
237    }
238
239    /// Dart `Tab(height:)`.
240    pub fn height(mut self, height: f64) -> Tab {
241        self.height = Some(height);
242        self
243    }
244
245    /// Dart `Tab(child:)`.
246    #[cfg_attr(debug_assertions, track_caller)]
247    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> Tab {
248        self.child = Some(child.into_widget());
249        self
250    }
251
252    fn build_label_text(&self) -> WidgetRef {
253        match &self.child {
254            Some(child) => child.clone(),
255            None => Text::new(self.text.clone().expect("a tab label has text or a child"))
256                .soft_wrap(false)
257                .overflow(TextOverflow::Fade)
258                .into_widget(),
259        }
260    }
261}
262
263impl StatelessWidget for Tab {
264    fn key(&self) -> Option<&KeyRef> {
265        self.key.as_ref()
266    }
267
268    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
269        properties.add(StringProperty::new("text", self.text.clone()).default_value(None));
270    }
271
272    fn debug_check_constructor(&self) {
273        debug_assert!(
274            self.text.is_some() || self.child.is_some() || self.icon.is_some(),
275            "Tab requires at least one of text, child, or icon to be non-null."
276        );
277        debug_assert!(
278            self.text.is_none() || self.child.is_none(),
279            "Provide either text or child, not both, when creating a Tab."
280        );
281    }
282
283    fn as_preferred_size_widget(&self) -> Option<&dyn PreferredSizeWidget> {
284        Some(self)
285    }
286
287    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
288        debug_assert!(debug_check_has_material(app, context));
289
290        let calculated_height;
291        let label;
292        if self.icon.is_none() {
293            calculated_height = K_TAB_HEIGHT;
294            label = self.build_label_text();
295        } else if self.text.is_none() && self.child.is_none() {
296            calculated_height = K_TAB_HEIGHT;
297            label = self.icon.clone().expect("checked above");
298        } else {
299            calculated_height = K_TEXT_AND_ICON_TAB_HEIGHT;
300            let effective_icon_margin = self.icon_margin.unwrap_or_else(|| {
301                if Theme::of(app, context).use_material3 {
302                    TabsPrimaryDefaultsM3::ICON_MARGIN
303                } else {
304                    TabsDefaultsM2::ICON_MARGIN
305                }
306            });
307            label = Column::new()
308                .main_axis_alignment(MainAxisAlignment::Center)
309                .children([
310                    Padding::new(effective_icon_margin)
311                        .child(self.icon.clone().expect("checked above"))
312                        .into_widget(),
313                    self.build_label_text(),
314                ])
315                .into_widget();
316        }
317
318        SizedBox::new()
319            .height(self.height.unwrap_or(calculated_height))
320            .child(Center::new().width_factor(1.0).child(label))
321            .into_widget()
322    }
323}
324
325impl PreferredSizeWidget for Tab {
326    fn preferred_size(&self) -> waft_widgets::AnySize {
327        if let Some(height) = self.height {
328            Size::from_height(height).into()
329        } else if (self.text.is_some() || self.child.is_some()) && self.icon.is_some() {
330            Size::from_height(K_TEXT_AND_ICON_TAB_HEIGHT).into()
331        } else {
332            Size::from_height(K_TAB_HEIGHT).into()
333        }
334    }
335}
336
337/// Dart's `item is PreferredSizeWidget ? item.preferredSize : …` on an erased tab.
338fn preferred_size_of(tab: &WidgetRef) -> Option<Size> {
339    tab.as_preferred_size_widget()
340        .map(|widget| widget.preferred_size().size())
341}
342
343/// Dart's `_TabStyle`.
344struct TabStyle {
345    animation: AnimationRef<f64>,
346    is_selected: bool,
347    #[allow(
348        dead_code,
349        reason = "Dart's `_TabStyle.isPrimary`, which Dart reads nowhere either"
350    )]
351    is_primary: bool,
352    label_color: Option<AnyColor>,
353    unselected_label_color: Option<Color>,
354    label_style: Option<TextStyle>,
355    unselected_label_style: Option<TextStyle>,
356    defaults: Rc<dyn TabBarThemeDataGetters>,
357    child: WidgetRef,
358}
359
360impl fmt::Debug for TabStyle {
361    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
362        f.debug_struct("TabStyle")
363            .field("animation", &self.animation)
364            .field("is_selected", &self.is_selected)
365            .field("label_color", &self.label_color)
366            .field("unselected_label_color", &self.unselected_label_color)
367            .field("label_style", &self.label_style)
368            .field("unselected_label_style", &self.unselected_label_style)
369            .field("child", &self.child)
370            .finish_non_exhaustive()
371    }
372}
373
374impl TabStyle {
375    /// Dart's `_resolveWithLabelColor`: the colour of a label, between selected and not as
376    /// the animation stands.
377    fn resolve_with_label_color(
378        &self,
379        app: &mut App,
380        context: BuildContext,
381        icon_theme: Option<&IconThemeData>,
382        states: &WidgetStates,
383    ) -> Color {
384        let theme_data = Theme::of(app, context);
385        let tab_bar_theme = TabBarTheme::of(app, context);
386        let animation = self.animation.clone();
387
388        // labelStyle.color (and tabBarTheme.labelStyle.color) is not considered
389        // as it'll be a breaking change without a possible migration plan. for
390        // details: https://github.com/flutter/flutter/pull/109541#issuecomment-1294241417
391        let selected_color: AnyColor = self
392            .label_color
393            .clone()
394            .or_else(|| tab_bar_theme.label_color.clone())
395            .or_else(|| {
396                self.label_style
397                    .as_ref()
398                    .and_then(|style| style.color.clone())
399            })
400            .or_else(|| {
401                tab_bar_theme
402                    .label_style
403                    .as_ref()
404                    .and_then(|style| style.color.clone())
405            })
406            .or_else(|| self.defaults.label_color(app))
407            .expect("the tab defaults have a label color");
408
409        let unselected_color: Color;
410        let selected_color: Color = if let Some(state_color) =
411            selected_color.as_widget_state_property()
412        {
413            unselected_color = state_color.resolve(&WidgetStates::new());
414            state_color.resolve(&WidgetStates::from([WidgetState::Selected]))
415        } else {
416            // unselectedLabelColor and tabBarTheme.unselectedLabelColor are ignored
417            // when labelColor is a WidgetStateColor.
418            let selected_color = selected_color.color();
419            unselected_color = self
420                .unselected_label_color
421                .or(tab_bar_theme.unselected_label_color)
422                .or_else(|| {
423                    self.unselected_label_style
424                        .as_ref()
425                        .and_then(|style| style.color.as_ref().map(AnyColor::color))
426                })
427                .or_else(|| {
428                    tab_bar_theme
429                        .unselected_label_style
430                        .as_ref()
431                        .and_then(|style| style.color.as_ref().map(AnyColor::color))
432                })
433                .or_else(|| icon_theme.and_then(|theme| theme.color.as_ref().map(AnyColor::color)))
434                .unwrap_or_else(|| {
435                    if theme_data.use_material3 {
436                        self.defaults
437                            .unselected_label_color(app)
438                            .expect("the Material 3 tab defaults have an unselected color")
439                    } else {
440                        selected_color.with_alpha(0xB2) // 70% alpha
441                    }
442                });
443            selected_color
444        };
445
446        let value = animation.value(app);
447        if states.contains(&WidgetState::Selected) {
448            return Color::lerp(Some(selected_color), Some(unselected_color), value)
449                .expect("two colors lerp to a color");
450        }
451        Color::lerp(Some(unselected_color), Some(selected_color), value)
452            .expect("two colors lerp to a color")
453    }
454}
455
456impl AnimatedWidget for TabStyle {
457    fn listenable(&self) -> Rc<dyn Listenable> {
458        Rc::new(self.animation.clone())
459    }
460
461    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
462        let theme = Theme::of(app, context);
463        let tab_bar_theme = TabBarTheme::of(app, context);
464        let animation = self.animation.clone();
465
466        let states = if self.is_selected {
467            WidgetStates::from([WidgetState::Selected])
468        } else {
469            WidgetStates::new()
470        };
471
472        // To enable TextStyle.lerp(style1, style2, value), both styles must have
473        // the same value of inherit. Force that to be inherit=true here.
474        let selected_style = self
475            .defaults
476            .label_style(app)
477            .expect("the tab defaults have a label style")
478            .merge(
479                self.label_style
480                    .as_ref()
481                    .or(tab_bar_theme.label_style.as_ref()),
482            )
483            .copy_with()
484            .inherit(true);
485        let unselected_style = self
486            .defaults
487            .unselected_label_style(app)
488            .expect("the tab defaults have an unselected label style")
489            .merge(
490                self.unselected_label_style
491                    .as_ref()
492                    .or(tab_bar_theme.unselected_label_style.as_ref())
493                    .or(self.label_style.as_ref()),
494            )
495            .copy_with()
496            .inherit(true);
497        let value = animation.value(app);
498        let text_style = if self.is_selected {
499            TextStyle::lerp(Some(&selected_style), Some(&unselected_style), value)
500        } else {
501            TextStyle::lerp(Some(&unselected_style), Some(&selected_style), value)
502        }
503        .expect("two styles lerp to a style");
504        let default_icon_color = match theme.color_scheme.brightness() {
505            Brightness::Light => K_DEFAULT_ICON_DARK_COLOR,
506            Brightness::Dark => K_DEFAULT_ICON_LIGHT_COLOR,
507        };
508        let icon_theme = IconTheme::of(app, context);
509        let custom_icon_theme = (icon_theme.color.as_ref().map(AnyColor::color)
510            != Some(default_icon_color))
511        .then_some(icon_theme);
512        let icon_color =
513            self.resolve_with_label_color(app, context, custom_icon_theme.as_ref(), &states);
514        let label_color = self.resolve_with_label_color(app, context, None, &states);
515
516        DefaultTextStyle::new(
517            text_style.copy_with().color(label_color),
518            IconTheme::merge(
519                None,
520                IconThemeData::new()
521                    .size(
522                        custom_icon_theme
523                            .as_ref()
524                            .and_then(|theme| theme.size)
525                            .unwrap_or(24.0),
526                    )
527                    .color(icon_color),
528                self.child.clone(),
529            ),
530        )
531        .into_widget()
532    }
533}
534
535/// Dart's `_LayoutCallback`.
536type LayoutCallback = Rc<dyn Fn(&mut App, Vec<f64>, TextDirection, f64)>;
537
538/// Dart's `_TabLabelBarRenderer extends RenderFlex`.
539struct TabLabelBarRenderer {
540    render_object: RenderObjectData,
541    render_box: RenderBoxData,
542    container: ContainerRenderObjectData<AnyRenderBox>,
543    flex: RenderFlexData,
544    on_perform_layout: LayoutCallback,
545}
546
547impl TabLabelBarRenderer {
548    #[expect(
549        clippy::too_many_arguments,
550        reason = "Dart's named arguments, in Dart's order"
551    )]
552    fn new(
553        app: &mut App,
554        direction: Axis,
555        main_axis_size: MainAxisSize,
556        main_axis_alignment: MainAxisAlignment,
557        cross_axis_alignment: CrossAxisAlignment,
558        text_direction: TextDirection,
559        vertical_direction: VerticalDirection,
560        on_perform_layout: LayoutCallback,
561    ) -> RenderHandle<TabLabelBarRenderer> {
562        let flex = RenderFlexData::new()
563            .direction(direction)
564            .main_axis_size(main_axis_size)
565            .main_axis_alignment(main_axis_alignment)
566            .cross_axis_alignment(cross_axis_alignment)
567            .text_direction(Some(text_direction))
568            .vertical_direction(vertical_direction);
569        RenderHandle::new_box(
570            app,
571            TabLabelBarRenderer {
572                render_object: RenderObjectData::new(),
573                render_box: RenderBoxData::new(),
574                container: ContainerRenderObjectData::new(),
575                flex,
576                on_perform_layout,
577            },
578        )
579    }
580}
581
582impl ContainerRenderObjectMixin for TabLabelBarRenderer {
583    type ChildType = AnyRenderBox;
584    type ParentDataType = FlexParentData;
585
586    fn container_data(
587        self: RenderHandle<Self>,
588        app: &App,
589    ) -> &ContainerRenderObjectData<AnyRenderBox> {
590        &self.get(app).container
591    }
592
593    fn container_data_mut(
594        self: RenderHandle<Self>,
595        app: &mut App,
596    ) -> &mut ContainerRenderObjectData<AnyRenderBox> {
597        &mut self.get_mut(app).container
598    }
599}
600
601impl RenderBoxContainerDefaultsMixin for TabLabelBarRenderer {}
602
603impl RenderFlexMixin for TabLabelBarRenderer {
604    fn flex_data(self: RenderHandle<Self>, app: &App) -> &RenderFlexData {
605        &self.get(app).flex
606    }
607
608    fn flex_data_mut(self: RenderHandle<Self>, app: &mut App) -> &mut RenderFlexData {
609        &mut self.get_mut(app).flex
610    }
611}
612
613impl RenderObject for TabLabelBarRenderer {
614    waft_rendering::render_object_accessors!();
615
616    fn debug_fill_properties(
617        self: RenderHandle<Self>,
618        app: &App,
619        properties: &mut DiagnosticPropertiesBuilder,
620    ) {
621        // Dart's `_TabLabelBarRenderer` inherits `RenderFlex.debugFillProperties`.
622        RenderFlexMixin::debug_fill_properties(self, app, properties);
623    }
624
625    fn debug_describe_children(
626        self: RenderHandle<Self>,
627        app: &App,
628    ) -> Vec<Rc<dyn DiagnosticsNode>> {
629        ContainerRenderObjectMixin::debug_describe_children(self, app)
630    }
631
632    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
633        RenderFlexMixin::perform_layout(self, app);
634        // xOffsets will contain childCount+1 values, giving the offsets of the
635        // leading edge of the first tab as the first value, of the leading edge of
636        // the each subsequent tab as each subsequent value, and of the trailing
637        // edge of the last tab as the last value.
638        let mut child = self.first_child(app);
639        let mut x_offsets = Vec::new();
640        while let Some(current) = child {
641            let child_parent_data = current.as_object().parent_data_of::<FlexParentData>(app);
642            x_offsets.push(child_parent_data.offset().dx());
643            child = self.child_after(app, current);
644        }
645        let text_direction = RenderFlexMixin::text_direction(self, app)
646            .expect("a tab label bar has a text direction");
647        let width = self.size(app).width();
648        match text_direction {
649            TextDirection::Rtl => x_offsets.insert(0, width),
650            TextDirection::Ltr => x_offsets.push(width),
651        }
652        let on_perform_layout = Rc::clone(&self.get(app).on_perform_layout);
653        on_perform_layout(app, x_offsets, text_direction, width);
654    }
655
656    fn visit_children(
657        self: RenderHandle<Self>,
658        app: &App,
659        visitor: &mut dyn FnMut(AnyRenderObject),
660    ) {
661        ContainerRenderObjectMixin::visit_children(self, app, visitor)
662    }
663
664    fn did_attach(self: RenderHandle<Self>, app: &mut App, owner: Handle<PipelineOwner>) {
665        ContainerRenderObjectMixin::did_attach(self, app, owner)
666    }
667
668    fn did_detach(self: RenderHandle<Self>, app: &mut App) {
669        ContainerRenderObjectMixin::did_detach(self, app)
670    }
671
672    fn redepth_children(self: RenderHandle<Self>, app: &mut App) {
673        ContainerRenderObjectMixin::redepth_children(self, app)
674    }
675
676    fn paint(
677        self: RenderHandle<Self>,
678        app: &mut App,
679        context: &mut PaintingContext,
680        offset: Offset,
681    ) {
682        RenderFlexMixin::paint(self, app, context, offset)
683    }
684
685    fn dispose(self: RenderHandle<Self>, app: &mut App) {
686        RenderFlexMixin::dispose(self, app)
687    }
688
689    fn describe_approximate_paint_clip(
690        self: RenderHandle<Self>,
691        app: &App,
692        child: AnyRenderObject,
693    ) -> Option<Rect> {
694        RenderFlexMixin::describe_approximate_paint_clip(self, app, child)
695    }
696}
697
698impl RenderBox for TabLabelBarRenderer {
699    waft_rendering::render_box_accessors!();
700
701    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
702        RenderFlexMixin::setup_parent_data(self, app, child)
703    }
704
705    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
706        RenderFlexMixin::compute_min_intrinsic_width(self, app, height)
707    }
708
709    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
710        RenderFlexMixin::compute_max_intrinsic_width(self, app, height)
711    }
712
713    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
714        RenderFlexMixin::compute_min_intrinsic_height(self, app, width)
715    }
716
717    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
718        RenderFlexMixin::compute_max_intrinsic_height(self, app, width)
719    }
720
721    fn compute_distance_to_actual_baseline(
722        self: RenderHandle<Self>,
723        app: &mut App,
724        baseline: TextBaseline,
725    ) -> Option<f64> {
726        RenderFlexMixin::compute_distance_to_actual_baseline(self, app, baseline)
727    }
728
729    fn compute_dry_baseline(
730        self: RenderHandle<Self>,
731        app: &mut App,
732        constraints: BoxConstraints,
733        baseline: TextBaseline,
734    ) -> Option<f64> {
735        RenderFlexMixin::compute_dry_baseline(self, app, constraints, baseline)
736    }
737
738    fn compute_dry_layout(
739        self: RenderHandle<Self>,
740        app: &mut App,
741        constraints: BoxConstraints,
742    ) -> Size {
743        RenderFlexMixin::compute_dry_layout(self, app, constraints)
744    }
745
746    fn hit_test_children(
747        self: RenderHandle<Self>,
748        app: &mut App,
749        result: &mut BoxHitTestResult<'_>,
750        position: Offset,
751    ) -> bool {
752        RenderFlexMixin::hit_test_children(self, app, result, position)
753    }
754}
755
756// This class and its renderer class only exist to report the widths of the tabs
757// upon layout. The tab widths are only used at paint time (see _IndicatorPainter)
758// or in response to input.
759/// Dart's `_TabLabelBar extends Flex`: a [`Flex`] whose render object reports the tabs'
760/// offsets after each layout.
761struct TabLabelBar {
762    flex: Flex,
763    on_perform_layout: LayoutCallback,
764}
765
766impl TabLabelBar {
767    fn new(
768        children: Vec<WidgetRef>,
769        on_perform_layout: LayoutCallback,
770        main_axis_size: MainAxisSize,
771    ) -> TabLabelBar {
772        TabLabelBar {
773            flex: Flex::new(Axis::Horizontal)
774                .main_axis_alignment(MainAxisAlignment::Start)
775                .cross_axis_alignment(CrossAxisAlignment::Center)
776                .vertical_direction(VerticalDirection::Down)
777                .main_axis_size(main_axis_size)
778                .children(children),
779            on_perform_layout,
780        }
781    }
782}
783
784impl fmt::Debug for TabLabelBar {
785    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
786        f.debug_struct("TabLabelBar")
787            .field("flex", &self.flex)
788            .finish()
789    }
790}
791
792impl RenderObjectWidget for TabLabelBar {
793    type RenderObject = TabLabelBarRenderer;
794
795    fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject {
796        let text_direction = self
797            .flex
798            .get_effective_text_direction(app, context)
799            .expect("a horizontal flex has a text direction");
800        TabLabelBarRenderer::new(
801            app,
802            self.flex.direction,
803            self.flex.main_axis_size,
804            self.flex.main_axis_alignment,
805            self.flex.cross_axis_alignment,
806            text_direction,
807            self.flex.vertical_direction,
808            Rc::clone(&self.on_perform_layout),
809        )
810        .as_object()
811    }
812
813    fn update_render_object(
814        &self,
815        app: &mut App,
816        context: BuildContext,
817        render_object: RenderHandle<TabLabelBarRenderer>,
818    ) {
819        // Dart's `super.updateRenderObject`, `Flex.updateRenderObject`.
820        render_object.set_direction(app, self.flex.direction);
821        render_object.set_main_axis_alignment(app, self.flex.main_axis_alignment);
822        render_object.set_main_axis_size(app, self.flex.main_axis_size);
823        render_object.set_cross_axis_alignment(app, self.flex.cross_axis_alignment);
824        let text_direction = self.flex.get_effective_text_direction(app, context);
825        render_object.set_text_direction(app, text_direction);
826        render_object.set_vertical_direction(app, self.flex.vertical_direction);
827        render_object.set_text_baseline(app, self.flex.text_baseline);
828        render_object.set_clip_behavior(app, self.flex.clip_behavior);
829        render_object.set_spacing(app, self.flex.spacing);
830        render_object.get_mut(app).on_perform_layout = Rc::clone(&self.on_perform_layout);
831    }
832}
833
834impl MultiChildRenderObjectWidget for TabLabelBar {
835    fn children(&self) -> &[WidgetRef] {
836        &self.flex.children
837    }
838}
839
840fn index_change_progress(app: &App, controller: Handle<TabController>) -> f64 {
841    let controller_value = controller
842        .animation(app)
843        .expect("a valid controller has an animation")
844        .value(app);
845    let previous_index = controller.previous_index(app) as f64;
846    let current_index = controller.index(app) as f64;
847
848    // The controller's offset is changing because the user is dragging the
849    // TabBarView's PageView to the left or right.
850    if !controller.index_is_changing(app) {
851        return clamp_double((current_index - controller_value).abs(), 0.0, 1.0);
852    }
853
854    // The TabController animation's value is changing from previousIndex to currentIndex.
855    (controller_value - current_index).abs() / (current_index - previous_index).abs()
856}
857
858/// A stroke paint of `color`, `stroke_width` wide: Dart's `Paint()..color..strokeWidth`.
859fn divider_paint(color: Color, stroke_width: f64) -> Paint {
860    let mut paint = Paint::from_color(color.into());
861    paint.style = PaintStyle::Stroke(Stroke::new(stroke_width as f32));
862    paint
863}
864
865/// Dart's `_DividerPainter`.
866struct DividerPainter {
867    divider_color: Color,
868    divider_height: f64,
869}
870
871impl CustomPainter for DividerPainter {
872    fn paint(&self, _app: &mut App, canvas: &mut Canvas, size: Size) {
873        if self.divider_height <= 0.0 {
874            return;
875        }
876
877        let paint = divider_paint(self.divider_color, self.divider_height);
878        let stroke_width = self.divider_height;
879
880        draw_line(
881            canvas,
882            Offset::new(0.0, size.height() - (stroke_width / 2.0)),
883            Offset::new(size.width(), size.height() - (stroke_width / 2.0)),
884            &paint,
885        );
886    }
887
888    fn should_repaint(&self, _app: &App, old_delegate: &dyn CustomPainter) -> bool {
889        let Some(old_delegate) = old_delegate.as_any().downcast_ref::<DividerPainter>() else {
890            return true;
891        };
892        old_delegate.divider_color != self.divider_color
893            || old_delegate.divider_height != self.divider_height
894    }
895
896    fn as_any(&self) -> &dyn Any {
897        self
898    }
899}
900
901// A ChangeNotifier for triggering repaints when async resources load.
902/// Dart's `_IndicatorPainterNotifier`.
903struct IndicatorPainterNotifier {
904    change_notifier: ChangeNotifierData,
905}
906
907impl IndicatorPainterNotifier {
908    fn new(app: &mut App) -> Ref<IndicatorPainterNotifier> {
909        app.create(IndicatorPainterNotifier {
910            change_notifier: ChangeNotifierData::new(),
911        })
912    }
913
914    fn notify(self: Handle<Self>, app: &mut App) {
915        self.notify_listeners(app);
916    }
917}
918
919impl ChangeNotifier for IndicatorPainterNotifier {
920    fn change_notifier_data(&self) -> &ChangeNotifierData {
921        &self.change_notifier
922    }
923
924    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
925        &mut self.change_notifier
926    }
927}
928
929/// Dart's `_IndicatorPainter`.
930///
931/// One painter is shared by the tab bar's state, which saves the tabs' offsets into it after
932/// each layout and asks it for tab centres, and its `CustomPaint`; what Dart's painter
933/// mutates is in cells.
934struct IndicatorPainter {
935    controller: Ref<TabController>,
936    indicator: DecorationRef,
937    indicator_size: TabBarIndicatorSize,
938    minimum_indicator_width: Option<f64>,
939    indicator_padding: EdgeInsetsGeometry,
940    tab_keys: Rc<RefCell<Vec<GlobalKey>>>,
941    label_paddings: Rc<RefCell<Vec<EdgeInsetsGeometry>>>,
942    divider_color: Option<Color>,
943    divider_height: Option<f64>,
944    show_divider: bool,
945    device_pixel_ratio: Option<f64>,
946    indicator_animation: TabIndicatorAnimation,
947    text_direction: TextDirection,
948    repaint_notifier: Ref<IndicatorPainterNotifier>,
949    repaint: Rc<dyn Listenable>,
950
951    // _currentTabOffsets and _currentTextDirection are set each time TabBar
952    // layout is completed. These values can be null when TabBar contains no
953    // tabs, since there are nothing to lay out.
954    current_tab_offsets: RefCell<Option<Vec<f64>>>,
955    current_text_direction: Cell<Option<TextDirection>>,
956
957    current_rect: Cell<Option<Rect>>,
958    painter: RefCell<Option<Box<dyn BoxPainter>>>,
959    needs_paint: Cell<bool>,
960    this: Weak<IndicatorPainter>,
961}
962
963/// Dart's `_IndicatorPainter` constructor arguments.
964struct IndicatorPainterArguments {
965    controller: Ref<TabController>,
966    indicator: DecorationRef,
967    indicator_size: TabBarIndicatorSize,
968    minimum_indicator_width: Option<f64>,
969    tab_keys: Rc<RefCell<Vec<GlobalKey>>>,
970    old: Option<Rc<IndicatorPainter>>,
971    indicator_padding: EdgeInsetsGeometry,
972    label_paddings: Rc<RefCell<Vec<EdgeInsetsGeometry>>>,
973    divider_color: Option<Color>,
974    divider_height: Option<f64>,
975    show_divider: bool,
976    device_pixel_ratio: Option<f64>,
977    indicator_animation: TabIndicatorAnimation,
978    text_direction: TextDirection,
979}
980
981impl IndicatorPainter {
982    /// Dart's factory: the repaint notifier is made here so that it can be both the painter's
983    /// repaint listenable (with the controller's animation) and its own field.
984    fn new(app: &mut App, arguments: IndicatorPainterArguments) -> Rc<IndicatorPainter> {
985        // Initializing [_IndicatorPainterNotifier] here that allows the
986        // repaint notifier to be used in the super constructor call
987        // (within [Listenable.merge]) while also being stored as a private field.
988        //
989        // The notifier is to trigger a repaint when asynchronous resources,
990        // like images in the indicator [Decoration], are finished loading.
991        let repaint_notifier = IndicatorPainterNotifier::new(app);
992        let animation = arguments
993            .controller
994            .animation(app)
995            .and_then(|animation| animation.upgrade(app));
996        let repaint: Rc<dyn Listenable> = Rc::new(MergingListenable::new(vec![
997            animation.map(|animation| Rc::new(animation) as Rc<dyn Listenable>),
998            Some(Rc::new(repaint_notifier.clone()) as Rc<dyn Listenable>),
999        ]));
1000        let painter = Rc::new_cyclic(|this| IndicatorPainter {
1001            controller: arguments.controller,
1002            indicator: arguments.indicator,
1003            indicator_size: arguments.indicator_size,
1004            minimum_indicator_width: arguments.minimum_indicator_width,
1005            indicator_padding: arguments.indicator_padding,
1006            tab_keys: arguments.tab_keys,
1007            label_paddings: arguments.label_paddings,
1008            divider_color: arguments.divider_color,
1009            divider_height: arguments.divider_height,
1010            show_divider: arguments.show_divider,
1011            device_pixel_ratio: arguments.device_pixel_ratio,
1012            indicator_animation: arguments.indicator_animation,
1013            text_direction: arguments.text_direction,
1014            repaint_notifier,
1015            repaint,
1016            current_tab_offsets: RefCell::new(None),
1017            current_text_direction: Cell::new(None),
1018            current_rect: Cell::new(None),
1019            painter: RefCell::new(None),
1020            needs_paint: Cell::new(false),
1021            this: this.clone(),
1022        });
1023        if let Some(old) = arguments.old {
1024            painter.save_tab_offsets(
1025                old.current_tab_offsets.borrow().clone(),
1026                old.current_text_direction.get(),
1027            );
1028        }
1029        painter
1030    }
1031
1032    fn mark_needs_paint(&self, app: &mut App) {
1033        self.needs_paint.set(true);
1034        self.repaint_notifier.notify(app);
1035    }
1036
1037    fn dispose(&self, app: &mut App) {
1038        if let Some(painter) = self.painter.borrow_mut().as_mut() {
1039            painter.dispose();
1040        }
1041        ChangeNotifierData::dispose(app, &self.repaint_notifier);
1042    }
1043
1044    fn save_tab_offsets(
1045        &self,
1046        tab_offsets: Option<Vec<f64>>,
1047        text_direction: Option<TextDirection>,
1048    ) {
1049        *self.current_tab_offsets.borrow_mut() = tab_offsets;
1050        self.current_text_direction.set(text_direction);
1051    }
1052
1053    // _currentTabOffsets[index] is the offset of the start edge of the tab at index, and
1054    // _currentTabOffsets[_currentTabOffsets.length] is the end edge of the last tab.
1055    fn max_tab_index(&self) -> usize {
1056        self.current_tab_offsets
1057            .borrow()
1058            .as_ref()
1059            .expect("the tabs were laid out")
1060            .len()
1061            - 2
1062    }
1063
1064    fn center_of(&self, tab_index: usize) -> f64 {
1065        let offsets = self.current_tab_offsets.borrow();
1066        let offsets = offsets.as_ref().expect("the tabs were laid out");
1067        debug_assert!(!offsets.is_empty());
1068        debug_assert!(tab_index <= offsets.len() - 2);
1069        (offsets[tab_index] + offsets[tab_index + 1]) / 2.0
1070    }
1071
1072    fn indicator_rect(&self, app: &mut App, tab_bar_size: Size, tab_index: usize) -> Rect {
1073        let current_text_direction = self
1074            .current_text_direction
1075            .get()
1076            .expect("the tabs were laid out");
1077        let (mut tab_left, mut tab_right) = {
1078            let offsets = self.current_tab_offsets.borrow();
1079            let offsets = offsets.as_ref().expect("the tabs were laid out");
1080            debug_assert!(!offsets.is_empty());
1081            debug_assert!(tab_index <= offsets.len() - 2);
1082            match current_text_direction {
1083                TextDirection::Rtl => (offsets[tab_index + 1], offsets[tab_index]),
1084                TextDirection::Ltr => (offsets[tab_index], offsets[tab_index + 1]),
1085            }
1086        };
1087
1088        if self.indicator_size == TabBarIndicatorSize::Label {
1089            let tab_key = self.tab_keys.borrow()[tab_index].clone();
1090            let tab_width = tab_key
1091                .current_context(app)
1092                .and_then(|context| context.size(app))
1093                .expect("a laid-out tab has a size")
1094                .width();
1095            let label_padding = self.label_paddings.borrow()[tab_index];
1096            let insets = label_padding.resolve(Some(current_text_direction));
1097            let delta = ((tab_right - tab_left) - (tab_width + insets.horizontal())) / 2.0;
1098            tab_left += delta + insets.left;
1099            tab_right = tab_left + tab_width;
1100        }
1101
1102        let indicator_width = tab_right - tab_left;
1103        if let Some(minimum_width) = self.minimum_indicator_width
1104            && indicator_width < minimum_width
1105        {
1106            let tab_center = (tab_left + tab_right) / 2.0;
1107            tab_left = tab_center - minimum_width / 2.0;
1108            tab_right = tab_center + minimum_width / 2.0;
1109        }
1110
1111        let insets = self.indicator_padding.resolve(Some(current_text_direction));
1112        let rect = Rect::from_ltwh(tab_left, 0.0, tab_right - tab_left, tab_bar_size.height());
1113
1114        if !rect
1115            .size()
1116            .ge(&EdgeInsetsGeometry::from(insets).collapsed_size())
1117        {
1118            panic!(
1119                "indicatorPadding insets should be less than Tab Size\n\
1120                 Rect Size : {:?}, Insets: {:?}",
1121                rect.size(),
1122                insets
1123            );
1124        }
1125        insets.deflate_rect(rect)
1126    }
1127
1128    /// Applies the linear effect to the indicator.
1129    fn apply_linear_effect(&self, app: &mut App, size: Size, value: f64) -> Option<Rect> {
1130        let index = self.controller.index(app) as f64;
1131        let ltr = index > value;
1132        let max_tab_index = self.max_tab_index() as f64;
1133        let from = (if ltr { value.floor() } else { value.ceil() }).clamp(0.0, max_tab_index);
1134        let to = (if ltr { from + 1.0 } else { from - 1.0 }).clamp(0.0, max_tab_index);
1135        let from_rect = self.indicator_rect(app, size, from as usize);
1136        let to_rect = self.indicator_rect(app, size, to as usize);
1137        Rect::lerp(Some(from_rect), Some(to_rect), (value - from).abs())
1138    }
1139
1140    // Ease out sine (decelerating).
1141    fn decelerate_interpolation(fraction: f64) -> f64 {
1142        ((fraction * PI) / 2.0).sin()
1143    }
1144
1145    // Ease in sine (accelerating).
1146    fn accelerate_interpolation(fraction: f64) -> f64 {
1147        1.0 - ((fraction * PI) / 2.0).cos()
1148    }
1149
1150    /// Applies the elastic effect to the indicator.
1151    fn apply_elastic_effect(&self, app: &mut App, size: Size, value: f64) -> Option<Rect> {
1152        let controller = self.controller.clone();
1153        let index = controller.index(app) as f64;
1154        let mut progress_left = (index - value).abs();
1155        let index_is_changing = controller.index_is_changing(app);
1156        let max_tab_index = self.max_tab_index() as f64;
1157
1158        let to = if progress_left == 0.0 || !index_is_changing {
1159            match self.text_direction {
1160                TextDirection::Ltr => value.ceil(),
1161                TextDirection::Rtl => value.floor(),
1162            }
1163            .clamp(0.0, max_tab_index)
1164        } else {
1165            index
1166        };
1167        let from = if progress_left == 0.0 || !index_is_changing {
1168            match self.text_direction {
1169                TextDirection::Ltr => to - 1.0,
1170                TextDirection::Rtl => to + 1.0,
1171            }
1172            .clamp(0.0, max_tab_index)
1173        } else {
1174            controller.previous_index(app) as f64
1175        };
1176        let to_rect = self.indicator_rect(app, size, to as usize);
1177        let from_rect = self.indicator_rect(app, size, from as usize);
1178        let rect = Rect::lerp(Some(from_rect), Some(to_rect), (value - from).abs())
1179            .expect("two rects lerp to a rect");
1180
1181        // If the tab animation is completed, there is no need to stretch the indicator
1182        // This only works for the tab change animation via tab index, not when
1183        // dragging a [TabBarView], but it's still ok, to avoid unnecessary calculations.
1184        if controller
1185            .animation(app)
1186            .expect("a valid controller has an animation")
1187            .is_completed(app)
1188        {
1189            return Some(rect);
1190        }
1191
1192        let tab_change_progress = if index_is_changing {
1193            let tabs_delta =
1194                (controller.index(app) as f64 - controller.previous_index(app) as f64).abs();
1195            if tabs_delta != 0.0 {
1196                progress_left /= tabs_delta;
1197            }
1198            1.0 - clamp_double(progress_left, 0.0, 1.0)
1199        } else {
1200            (index - value).abs()
1201        };
1202
1203        // If the animation has finished, there is no need to apply the stretch effect.
1204        if tab_change_progress == 1.0 {
1205            return Some(rect);
1206        }
1207
1208        let is_moving_right = match self.text_direction {
1209            TextDirection::Ltr => {
1210                if index_is_changing {
1211                    index > value
1212                } else {
1213                    value > index
1214                }
1215            }
1216            TextDirection::Rtl => {
1217                if index_is_changing {
1218                    value > index
1219                } else {
1220                    index > value
1221                }
1222            }
1223        };
1224        let (left_fraction, right_fraction) = if is_moving_right {
1225            (
1226                Self::accelerate_interpolation(tab_change_progress),
1227                Self::decelerate_interpolation(tab_change_progress),
1228            )
1229        } else {
1230            (
1231                Self::decelerate_interpolation(tab_change_progress),
1232                Self::accelerate_interpolation(tab_change_progress),
1233            )
1234        };
1235
1236        let lerp = |a: f64, b: f64, t: f64| {
1237            lerp_double(Some(a), Some(b), t).expect("two values lerp to a value")
1238        };
1239        let (lerp_rect_left, lerp_rect_right);
1240
1241        // The controller.indexIsChanging is true when the Tab is pressed, instead of swipe to change tabs.
1242        // If the tab is pressed then only lerp between fromRect and toRect.
1243        if index_is_changing {
1244            lerp_rect_left = lerp(from_rect.left, to_rect.left, left_fraction);
1245            lerp_rect_right = lerp(from_rect.right, to_rect.right, right_fraction);
1246        } else {
1247            // Switch the Rect left and right lerp order based on swipe direction.
1248            lerp_rect_left = if is_moving_right {
1249                lerp(from_rect.left, to_rect.left, left_fraction)
1250            } else {
1251                lerp(to_rect.left, from_rect.left, left_fraction)
1252            };
1253            lerp_rect_right = if is_moving_right {
1254                lerp(from_rect.right, to_rect.right, right_fraction)
1255            } else {
1256                lerp(to_rect.right, from_rect.right, right_fraction)
1257            };
1258        }
1259
1260        Some(Rect::from_ltrb(
1261            lerp_rect_left,
1262            rect.top,
1263            lerp_rect_right,
1264            rect.bottom,
1265        ))
1266    }
1267}
1268
1269impl CustomPainter for IndicatorPainter {
1270    fn repaint(&self) -> Option<&Rc<dyn Listenable>> {
1271        Some(&self.repaint)
1272    }
1273
1274    fn paint(&self, app: &mut App, canvas: &mut Canvas, size: Size) {
1275        self.needs_paint.set(false);
1276        if self.painter.borrow().is_none() {
1277            let this = self.this.clone();
1278            let on_changed: Rc<dyn Fn(&mut App)> = Rc::new(move |app| {
1279                if let Some(this) = this.upgrade() {
1280                    this.mark_needs_paint(app);
1281                }
1282            });
1283            *self.painter.borrow_mut() = Some(self.indicator.create_box_painter(Some(on_changed)));
1284        }
1285
1286        let value = self
1287            .controller
1288            .animation(app)
1289            .expect("a painted indicator has a valid controller")
1290            .value(app);
1291
1292        let current_rect = match self.indicator_animation {
1293            TabIndicatorAnimation::Linear => self.apply_linear_effect(app, size, value),
1294            TabIndicatorAnimation::Elastic => self.apply_elastic_effect(app, size, value),
1295        };
1296        self.current_rect.set(current_rect);
1297
1298        let current_rect = current_rect.expect("the indicator has a rect");
1299
1300        let configuration = ImageConfiguration {
1301            size: Some(current_rect.size()),
1302            text_direction: self.current_text_direction.get(),
1303            device_pixel_ratio: self.device_pixel_ratio,
1304            ..ImageConfiguration::EMPTY
1305        };
1306        let divider_height = self.divider_height.unwrap_or(0.0);
1307        if self.show_divider && self.divider_height.expect("a shown divider has a height") > 0.0 {
1308            let divider_paint = divider_paint(
1309                self.divider_color.expect("a shown divider has a color"),
1310                divider_height,
1311            );
1312            let divider_p1 = Offset::new(0.0, size.height() - (divider_height / 2.0));
1313            let divider_p2 = Offset::new(size.width(), size.height() - (divider_height / 2.0));
1314            draw_line(canvas, divider_p1, divider_p2, &divider_paint);
1315        }
1316        self.painter
1317            .borrow_mut()
1318            .as_mut()
1319            .expect("made above")
1320            .paint(canvas, current_rect.top_left(), &configuration);
1321    }
1322
1323    fn should_repaint(&self, _app: &App, old_delegate: &dyn CustomPainter) -> bool {
1324        let Some(old) = old_delegate.as_any().downcast_ref::<IndicatorPainter>() else {
1325            return true;
1326        };
1327        self.needs_paint.get()
1328            || self.controller != old.controller
1329            || self.indicator != old.indicator
1330            || self.minimum_indicator_width != old.minimum_indicator_width
1331            || self.tab_keys.borrow().len() != old.tab_keys.borrow().len()
1332            || *self.current_tab_offsets.borrow() != *old.current_tab_offsets.borrow()
1333            || self.current_text_direction.get() != old.current_text_direction.get()
1334    }
1335
1336    fn as_any(&self) -> &dyn Any {
1337        self
1338    }
1339}
1340
1341/// Dart's `_ChangeAnimation`: how far the controller's animation has come from the previous
1342/// index to the current one.
1343struct ChangeAnimation {
1344    controller: Ref<TabController>,
1345}
1346
1347impl ChangeAnimation {
1348    fn new(app: &mut App, controller: Ref<TabController>) -> Ref<ChangeAnimation> {
1349        app.create(ChangeAnimation { controller })
1350    }
1351}
1352
1353impl AnimationWithParent<f64> for ChangeAnimation {
1354    fn parent(self: Handle<Self>, app: &App) -> AnyAnimation<f64> {
1355        app.get(self)
1356            .controller
1357            .animation(app)
1358            .expect("a change animation's controller is valid")
1359    }
1360}
1361
1362impl Animation<f64> for ChangeAnimation {
1363    fn add_listener(self: Handle<Self>, app: &mut App, listener: Listener) {
1364        AnimationWithParent::add_listener(self, app, listener)
1365    }
1366
1367    fn remove_listener(self: Handle<Self>, app: &mut App, listener: &Listener) {
1368        if app.get(self).controller.animation(app).is_some() {
1369            AnimationWithParent::remove_listener(self, app, listener)
1370        }
1371    }
1372
1373    fn add_status_listener(self: Handle<Self>, app: &mut App, listener: AnimationStatusListener) {
1374        AnimationWithParent::add_status_listener(self, app, listener)
1375    }
1376
1377    fn remove_status_listener(
1378        self: Handle<Self>,
1379        app: &mut App,
1380        listener: &AnimationStatusListener,
1381    ) {
1382        if app.get(self).controller.animation(app).is_some() {
1383            AnimationWithParent::remove_status_listener(self, app, listener)
1384        }
1385    }
1386
1387    fn status(self: Handle<Self>, app: &App) -> AnimationStatus {
1388        AnimationWithParent::status(self, app)
1389    }
1390
1391    fn value(self: Handle<Self>, app: &App) -> f64 {
1392        index_change_progress(app, app.get(self).controller.handle())
1393    }
1394}
1395
1396/// Dart's `_DragAnimation`: how far the `TabBarView` has been dragged from the tab at
1397/// `index`.
1398struct DragAnimation {
1399    controller: Ref<TabController>,
1400    index: usize,
1401}
1402
1403impl DragAnimation {
1404    fn new(app: &mut App, controller: Ref<TabController>, index: usize) -> Ref<DragAnimation> {
1405        app.create(DragAnimation { controller, index })
1406    }
1407}
1408
1409impl AnimationWithParent<f64> for DragAnimation {
1410    fn parent(self: Handle<Self>, app: &App) -> AnyAnimation<f64> {
1411        app.get(self)
1412            .controller
1413            .animation(app)
1414            .expect("a drag animation's controller is valid")
1415    }
1416}
1417
1418impl Animation<f64> for DragAnimation {
1419    fn add_listener(self: Handle<Self>, app: &mut App, listener: Listener) {
1420        AnimationWithParent::add_listener(self, app, listener)
1421    }
1422
1423    fn remove_listener(self: Handle<Self>, app: &mut App, listener: &Listener) {
1424        if app.get(self).controller.animation(app).is_some() {
1425            AnimationWithParent::remove_listener(self, app, listener)
1426        }
1427    }
1428
1429    fn add_status_listener(self: Handle<Self>, app: &mut App, listener: AnimationStatusListener) {
1430        AnimationWithParent::add_status_listener(self, app, listener)
1431    }
1432
1433    fn remove_status_listener(
1434        self: Handle<Self>,
1435        app: &mut App,
1436        listener: &AnimationStatusListener,
1437    ) {
1438        if app.get(self).controller.animation(app).is_some() {
1439            AnimationWithParent::remove_status_listener(self, app, listener)
1440        }
1441    }
1442
1443    fn status(self: Handle<Self>, app: &App) -> AnimationStatus {
1444        AnimationWithParent::status(self, app)
1445    }
1446
1447    fn value(self: Handle<Self>, app: &App) -> f64 {
1448        let this = app.get(self);
1449        let controller = this.controller.clone();
1450        debug_assert!(!controller.index_is_changing(app));
1451        let controller_max_value = controller.length(app) as f64 - 1.0;
1452        let controller_value = clamp_double(
1453            controller
1454                .animation(app)
1455                .expect("a drag animation's controller is valid")
1456                .value(app),
1457            0.0,
1458            controller_max_value,
1459        );
1460        clamp_double((controller_value - this.index as f64).abs(), 0.0, 1.0)
1461    }
1462}
1463
1464// This class, and TabBarScrollController, only exist to handle the case
1465// where a scrollable TabBar has a non-zero initialIndex. In that case we can
1466// only compute the scroll position's initial scroll offset (the "correct"
1467// pixels value) after the TabBar viewport width and scroll limits are known.
1468/// Dart's `_TabBarScrollPosition`.
1469struct TabBarScrollPosition {
1470    change_notifier: ChangeNotifierData,
1471    scroll_position: ScrollPositionData,
1472    single_context: ScrollPositionWithSingleContextData,
1473    tab_bar: Handle<TabBarState>,
1474    viewport_dimension_was_non_zero: bool,
1475    // The scroll position should be adjusted at least once.
1476    needs_pixels_correction: bool,
1477}
1478
1479impl TabBarScrollPosition {
1480    fn new(
1481        app: &mut App,
1482        physics: ScrollPhysicsRef,
1483        context: Rc<dyn ScrollContext>,
1484        old_position: Option<AnyScrollPosition>,
1485        tab_bar: Handle<TabBarState>,
1486    ) -> Ref<TabBarScrollPosition> {
1487        let scroll_position = ScrollPositionData::new(app, physics, context, true, None);
1488        let this = app.create(TabBarScrollPosition {
1489            change_notifier: ChangeNotifierData::new(),
1490            scroll_position,
1491            single_context: ScrollPositionWithSingleContextData::new(),
1492            tab_bar,
1493            viewport_dimension_was_non_zero: false,
1494            needs_pixels_correction: true,
1495        });
1496        ScrollPositionWithSingleContext::init(this.handle(), app, None, old_position);
1497        this
1498    }
1499
1500    fn mark_needs_pixels_correction(self: Handle<Self>, app: &mut App) {
1501        app.get_mut(self).needs_pixels_correction = true;
1502    }
1503}
1504
1505impl ChangeNotifier for TabBarScrollPosition {
1506    fn change_notifier_data(&self) -> &ChangeNotifierData {
1507        &self.change_notifier
1508    }
1509
1510    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
1511        &mut self.change_notifier
1512    }
1513}
1514
1515impl ViewportOffset for TabBarScrollPosition {
1516    fn pixels(self: Handle<Self>, app: &App) -> f64 {
1517        ScrollPositionBase::pixels(self, app)
1518    }
1519
1520    fn has_pixels(self: Handle<Self>, app: &App) -> bool {
1521        ScrollPositionBase::has_pixels(self, app)
1522    }
1523
1524    fn apply_viewport_dimension(
1525        self: Handle<Self>,
1526        app: &mut App,
1527        viewport_dimension: f64,
1528    ) -> bool {
1529        ScrollPositionBase::apply_viewport_dimension(self, app, viewport_dimension)
1530    }
1531
1532    fn apply_content_dimensions(
1533        self: Handle<Self>,
1534        app: &mut App,
1535        min_scroll_extent: f64,
1536        max_scroll_extent: f64,
1537    ) -> bool {
1538        let mut result = true;
1539        if !app.get(self).viewport_dimension_was_non_zero {
1540            let was_non_zero = self.viewport_dimension(app) != 0.0;
1541            app.get_mut(self).viewport_dimension_was_non_zero = was_non_zero;
1542        }
1543        // If the viewport never had a non-zero dimension, we just want to jump
1544        // to the initial scroll position to avoid strange scrolling effects in
1545        // release mode: the viewport temporarily may have a dimension of zero
1546        // before the actual dimension is calculated. In that scenario, setting
1547        // the actual dimension would cause a strange scroll effect without this
1548        // guard because the super call below would start a ballistic scroll activity.
1549        let this = app.get(self);
1550        if !this.viewport_dimension_was_non_zero || this.needs_pixels_correction {
1551            app.get_mut(self).needs_pixels_correction = false;
1552            let tab_bar = app.get(self).tab_bar;
1553            let viewport_dimension = self.viewport_dimension(app);
1554            let initial_scroll_offset = tab_bar.initial_scroll_offset(
1555                app,
1556                viewport_dimension,
1557                min_scroll_extent,
1558                max_scroll_extent,
1559            );
1560            self.correct_pixels(app, initial_scroll_offset);
1561            result = false;
1562        }
1563        ScrollPositionBase::apply_content_dimensions(
1564            self,
1565            app,
1566            min_scroll_extent,
1567            max_scroll_extent,
1568        ) && result
1569    }
1570
1571    fn correct_by(self: Handle<Self>, app: &mut App, correction: f64) {
1572        ScrollPositionBase::correct_by(self, app, correction);
1573    }
1574
1575    fn jump_to(self: Handle<Self>, app: &mut App, value: f64) {
1576        ScrollPositionWithSingleContextLeaf::jump_to(self, app, value);
1577    }
1578
1579    fn animate_to(
1580        self: Handle<Self>,
1581        app: &mut App,
1582        to: f64,
1583        duration: Duration,
1584        curve: Rc<dyn waft_animation::Curve>,
1585    ) -> waft_foundation::CompleterFuture<()> {
1586        ScrollPositionWithSingleContextLeaf::animate_to(self, app, to, duration, curve)
1587    }
1588
1589    fn move_to(
1590        self: Handle<Self>,
1591        app: &mut App,
1592        to: f64,
1593        duration: Option<Duration>,
1594        curve: Option<Rc<dyn waft_animation::Curve>>,
1595        clamp: Option<bool>,
1596    ) -> waft_foundation::CompleterFuture<()> {
1597        ScrollPositionBase::move_to(self, app, to, duration, curve, clamp)
1598    }
1599
1600    fn user_scroll_direction(self: Handle<Self>, app: &App) -> waft_rendering::ScrollDirection {
1601        ScrollPositionWithSingleContextLeaf::user_scroll_direction(self, app)
1602    }
1603
1604    fn allow_implicit_scrolling(self: Handle<Self>, app: &App) -> bool {
1605        ScrollPositionBase::allow_implicit_scrolling(self, app)
1606    }
1607}
1608
1609impl ScrollPosition for TabBarScrollPosition {
1610    waft_widgets::scroll_position_with_single_context_overrides!();
1611}
1612
1613impl ScrollActivityDelegate for TabBarScrollPosition {
1614    waft_widgets::scroll_position_with_single_context_delegate_overrides!();
1615}
1616
1617impl ScrollPositionWithSingleContextLeaf for TabBarScrollPosition {
1618    waft_widgets::scroll_position_with_single_context_accessors!();
1619}
1620
1621/// The `ScrollController` for a [`TabBar`] widget.
1622pub struct TabBarScrollController {
1623    change_notifier: ChangeNotifierData,
1624    scroll_controller: ScrollControllerData,
1625    /// The state of the [`TabBar`] widget to which this controller is attached.
1626    ///
1627    /// Is `None` if this controller is not attached to a [`TabBar`].
1628    tab_bar_state: Option<Handle<TabBarState>>,
1629}
1630
1631impl TabBarScrollController {
1632    /// Creates a scroll controller for a [`TabBar`], with Dart's `ScrollController` defaults.
1633    pub fn new(app: &mut App) -> Ref<TabBarScrollController> {
1634        app.create(TabBarScrollController {
1635            change_notifier: ChangeNotifierData::new(),
1636            scroll_controller: ScrollControllerData::new(0.0, true, None, None, None),
1637            tab_bar_state: None,
1638        })
1639    }
1640
1641    /// Asserts that this controller is currently attached to a [`TabBar`]'s `State`.
1642    ///
1643    /// To invoke this function, wrap it in an assert:
1644    /// `debug_assert!(controller.debug_check_has_tab_bar_state(app))`.
1645    ///
1646    /// Does nothing if asserts are disabled. Always returns true.
1647    pub fn debug_check_has_tab_bar_state(self: Handle<Self>, app: &App) -> bool {
1648        debug_assert!(
1649            app.get(self).tab_bar_state.is_some(),
1650            "This TabBarScrollController is not attached to any TabBar."
1651        );
1652        true
1653    }
1654}
1655
1656impl ChangeNotifier for TabBarScrollController {
1657    fn change_notifier_data(&self) -> &ChangeNotifierData {
1658        &self.change_notifier
1659    }
1660
1661    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
1662        &mut self.change_notifier
1663    }
1664}
1665
1666impl ScrollControllerLeaf for TabBarScrollController {
1667    waft_widgets::scroll_controller_accessors!();
1668
1669    fn create_scroll_position(
1670        self: Handle<Self>,
1671        app: &mut App,
1672        physics: ScrollPhysicsRef,
1673        context: Rc<dyn ScrollContext>,
1674        old_position: Option<AnyScrollPosition>,
1675    ) -> ScrollPositionRef {
1676        debug_assert!(self.debug_check_has_tab_bar_state(app));
1677
1678        let tab_bar = app.get(self).tab_bar_state.expect("asserted above");
1679        TabBarScrollPosition::new(app, physics, context, old_position, tab_bar).into_erased()
1680    }
1681
1682    fn dispose(self: Handle<Self>, app: &mut App) {
1683        app.get_mut(self).tab_bar_state = None;
1684        waft_widgets::ScrollController::dispose(self.as_controller(), app);
1685    }
1686}
1687
1688/// Signature for [`TabBar`] callbacks that report that an underlying value has
1689/// changed for a given [`Tab`] at `index`.
1690///
1691/// Used for [`TabBar::on_hover`] and [`TabBar::on_focus_change`] callbacks The provided
1692/// `value` being true indicates focus has been gained, or a pointer has hovered
1693/// over the tab, with false indicated focus has been lost or the pointer has
1694/// exited hovering.
1695pub type TabValueChanged<T> = Rc<dyn Fn(&mut App, T, usize)>;
1696
1697/// A Material Design primary tab bar.
1698///
1699/// Primary tabs are placed at the top of the content pane under a top app bar.
1700/// They display the main content destinations.
1701///
1702/// Typically created as the `AppBar::bottom` part of an `AppBar` and in
1703/// conjunction with a [`TabBarView`].
1704///
1705/// If a [`TabController`] is not provided, then a [`DefaultTabController`] ancestor
1706/// must be provided instead. The tab controller's [`TabController::length`] must
1707/// equal the length of the [`tabs`](Self::tabs) list and the length of the
1708/// [`TabBarView::children`] list.
1709///
1710/// Requires one of its ancestors to be a [`Material`] widget.
1711///
1712/// Uses values from [`TabBarThemeData`] if it is set in the current context.
1713///
1714/// See also:
1715///
1716///  * [`TabBar::secondary`], for a secondary tab bar.
1717///  * [`TabBarView`], which displays page views that correspond to each tab.
1718///  * [`TabController`], which coordinates tab selection between a [`TabBar`] and a
1719///    [`TabBarView`].
1720///  * <https://m3.material.io/components/tabs/overview>, the Material 3
1721///    tab bar specification.
1722pub struct TabBar {
1723    pub key: Option<KeyRef>,
1724
1725    /// Typically a list of two or more [`Tab`] widgets.
1726    ///
1727    /// The length of this list must match the [`controller`](Self::controller)'s
1728    /// [`TabController::length`] and the length of the [`TabBarView::children`] list.
1729    pub tabs: Vec<WidgetRef>,
1730
1731    /// This widget's selection and animation state.
1732    ///
1733    /// If [`TabController`] is not provided, then the value of [`DefaultTabController::of`]
1734    /// will be used.
1735    pub controller: Option<Ref<TabController>>,
1736
1737    /// The [`TabBarScrollController`] for this [`TabBar`].
1738    ///
1739    /// This controller can be used to manipulate the scroll position of the [`TabBar`].
1740    pub scroll_controller: Option<Ref<TabBarScrollController>>,
1741
1742    /// Whether this tab bar can be scrolled horizontally.
1743    ///
1744    /// If [`is_scrollable`](Self::is_scrollable) is true, then each tab is as wide as needed
1745    /// for its label and the entire [`TabBar`] is scrollable. Otherwise each tab gets an equal
1746    /// share of the available space.
1747    pub is_scrollable: bool,
1748
1749    /// The amount of space by which to inset the tab bar.
1750    ///
1751    /// When [`is_scrollable`](Self::is_scrollable) is false, this will yield the same result
1752    /// as if [`TabBar`] was wrapped in a `Padding` widget. When
1753    /// [`is_scrollable`](Self::is_scrollable) is true, the scrollable itself is inset,
1754    /// allowing the padding to scroll with the tab bar, rather than enclosing it.
1755    pub padding: Option<EdgeInsetsGeometry>,
1756
1757    /// The color of the line that appears below the selected tab.
1758    ///
1759    /// If this parameter is null, then the value of the Theme's indicatorColor
1760    /// property is used.
1761    ///
1762    /// If [`indicator`](Self::indicator) is specified or provided from [`TabBarThemeData`],
1763    /// this property is ignored.
1764    pub indicator_color: Option<Color>,
1765
1766    /// The thickness of the line that appears below the selected tab.
1767    ///
1768    /// The value of this parameter must be greater than zero.
1769    ///
1770    /// If `ThemeData::use_material3` is true and [`TabBar`] is used to create a
1771    /// primary tab bar, the default value is 3.0. If the provided value is less
1772    /// than 3.0, the default value is used.
1773    ///
1774    /// If `ThemeData::use_material3` is true and [`TabBar::secondary`] is used to
1775    /// create a secondary tab bar, the default value is 2.0.
1776    ///
1777    /// If `ThemeData::use_material3` is false, the default value is 2.0.
1778    ///
1779    /// If [`indicator`](Self::indicator) is specified or provided from [`TabBarThemeData`],
1780    /// this property is ignored. Otherwise, when drawing the default underline
1781    /// indicator, the value of this parameter must be greater than zero.
1782    pub indicator_weight: f64,
1783
1784    /// The padding for the indicator.
1785    ///
1786    /// The default value of this property is `EdgeInsets::ZERO`.
1787    ///
1788    /// For [`is_scrollable`](Self::is_scrollable) tab bars, specifying `K_TAB_LABEL_PADDING`
1789    /// will align the indicator with the tab's text for [`Tab`] widgets and all but the
1790    /// shortest [`Tab::text`] values.
1791    pub indicator_padding: EdgeInsetsGeometry,
1792
1793    /// Defines the appearance of the selected tab indicator.
1794    ///
1795    /// If [`indicator`](Self::indicator) is specified or provided from [`TabBarThemeData`],
1796    /// the [`indicator_color`](Self::indicator_color) and
1797    /// [`indicator_weight`](Self::indicator_weight) properties are ignored.
1798    ///
1799    /// The default, underline-style, selected tab indicator can be defined with
1800    /// [`UnderlineTabIndicator`].
1801    ///
1802    /// The indicator's size is based on the tab's bounds. If
1803    /// [`indicator_size`](Self::indicator_size) is [`TabBarIndicatorSize::Tab`] the tab's
1804    /// bounds are as wide as the space occupied by the tab in the tab bar. If
1805    /// [`indicator_size`](Self::indicator_size) is [`TabBarIndicatorSize::Label`], then the
1806    /// tab's bounds are only as wide as the tab widget itself.
1807    ///
1808    /// See also:
1809    ///
1810    ///  * [`splash_border_radius`](Self::splash_border_radius), which defines the clipping
1811    ///    radius of the splash and is generally used with `BoxDecoration::border_radius`.
1812    pub indicator: Option<DecorationRef>,
1813
1814    /// Whether this tab bar should automatically adjust the
1815    /// [`indicator_color`](Self::indicator_color).
1816    ///
1817    /// The default value of this property is true.
1818    ///
1819    /// If [`automatic_indicator_color_adjustment`](Self::automatic_indicator_color_adjustment)
1820    /// is true, then the [`indicator_color`](Self::indicator_color) will be automatically
1821    /// adjusted to `Colors::WHITE` when the [`indicator_color`](Self::indicator_color) is same
1822    /// as `Material::color` of the [`Material`] parent widget.
1823    pub automatic_indicator_color_adjustment: bool,
1824
1825    /// Defines how the selected tab indicator's size is computed.
1826    ///
1827    /// The size of the selected tab indicator is defined relative to the
1828    /// tab's overall bounds if [`indicator_size`](Self::indicator_size) is
1829    /// [`TabBarIndicatorSize::Tab`] (the default) or relative to the bounds of the tab's
1830    /// widget if [`indicator_size`](Self::indicator_size) is [`TabBarIndicatorSize::Label`].
1831    ///
1832    /// The selected tab's location appearance can be refined further with
1833    /// the [`indicator_color`](Self::indicator_color),
1834    /// [`indicator_weight`](Self::indicator_weight),
1835    /// [`indicator_padding`](Self::indicator_padding), and [`indicator`](Self::indicator)
1836    /// properties.
1837    pub indicator_size: Option<TabBarIndicatorSize>,
1838
1839    /// The color of the divider.
1840    ///
1841    /// If the [`divider_color`](Self::divider_color) is `Colors::TRANSPARENT`, then the
1842    /// divider will not be drawn.
1843    ///
1844    /// If null and `ThemeData::use_material3` is false, [`TabBarThemeData::divider_color`]
1845    /// color is used. If that is null and `ThemeData::use_material3` is true,
1846    /// `ColorScheme::outline_variant` will be used, otherwise divider will not be drawn.
1847    pub divider_color: Option<Color>,
1848
1849    /// The height of the divider.
1850    ///
1851    /// If the [`divider_height`](Self::divider_height) is zero or negative, then the divider
1852    /// will not be drawn.
1853    ///
1854    /// If null and `ThemeData::use_material3` is true, [`TabBarThemeData::divider_height`] is
1855    /// used. If that is also null and `ThemeData::use_material3` is true, 1.0 will be used.
1856    /// Otherwise divider will not be drawn.
1857    pub divider_height: Option<f64>,
1858
1859    /// The color of selected tab labels.
1860    ///
1861    /// If null, then [`TabBarThemeData::label_color`] is used. If that is also null and
1862    /// `ThemeData::use_material3` is true, `ColorScheme::primary` will be used,
1863    /// otherwise the color of the `ThemeData::primary_text_theme`'s
1864    /// `TextTheme::body_large` text color is used.
1865    ///
1866    /// If [`label_color`](Self::label_color) (or, if null, [`TabBarThemeData::label_color`])
1867    /// is a `WidgetStateColor`, then the effective tab color will depend on the
1868    /// `WidgetState::Selected` state, i.e. if the [`Tab`] is selected or not,
1869    /// ignoring [`unselected_label_color`](Self::unselected_label_color) even if it's non-null.
1870    ///
1871    /// When this color or the [`TabBarThemeData::label_color`] is specified, it overrides
1872    /// the `TextStyle::color` specified for the [`label_style`](Self::label_style) or the
1873    /// [`TabBarThemeData::label_style`].
1874    ///
1875    /// See also:
1876    ///
1877    ///   * [`unselected_label_color`](Self::unselected_label_color), for color of unselected
1878    ///     tab labels.
1879    pub label_color: Option<AnyColor>,
1880
1881    /// The text style of the selected tab labels.
1882    ///
1883    /// The color specified in [`label_style`](Self::label_style) and
1884    /// [`TabBarThemeData::label_style`] is used to style the label when
1885    /// [`label_color`](Self::label_color) or [`TabBarThemeData::label_color`] are not
1886    /// specified.
1887    ///
1888    /// If [`unselected_label_style`](Self::unselected_label_style) is null, then this text
1889    /// style will be used for both selected and unselected label styles.
1890    ///
1891    /// If this property is null, then [`TabBarThemeData::label_style`] will be used.
1892    ///
1893    /// If that is also null and `ThemeData::use_material3` is true, `TextTheme::title_small`
1894    /// will be used, otherwise the text style of the `ThemeData::primary_text_theme`'s
1895    /// `TextTheme::body_large` definition is used.
1896    pub label_style: Option<TextStyle>,
1897
1898    /// The padding added to each of the tab labels.
1899    ///
1900    /// If there are few tabs with both icon and text and few
1901    /// tabs with only icon or text, this padding is vertically
1902    /// adjusted to provide uniform padding to all tabs.
1903    ///
1904    /// If this property is null, then `K_TAB_LABEL_PADDING` is used.
1905    pub label_padding: Option<EdgeInsetsGeometry>,
1906
1907    /// The color of unselected tab labels.
1908    ///
1909    /// If [`label_color`](Self::label_color) (or, if null, [`TabBarThemeData::label_color`])
1910    /// is a `WidgetStateColor`, then the unselected tabs are rendered with
1911    /// that `WidgetStateColor`'s resolved color for unselected state, even if
1912    /// [`unselected_label_color`](Self::unselected_label_color) is non-null.
1913    ///
1914    /// If null, then [`TabBarThemeData::unselected_label_color`] is used. If that is also
1915    /// null and `ThemeData::use_material3` is true, `ColorScheme::on_surface_variant`
1916    /// will be used, otherwise unselected tab labels are rendered with
1917    /// [`label_color`](Self::label_color) at 70% opacity.
1918    ///
1919    /// When this color or the [`TabBarThemeData::unselected_label_color`] is specified, it
1920    /// overrides the `TextStyle::color` specified for the
1921    /// [`unselected_label_style`](Self::unselected_label_style) or the
1922    /// [`TabBarThemeData::unselected_label_style`].
1923    ///
1924    /// See also:
1925    ///
1926    ///  * [`label_color`](Self::label_color), for color of selected tab labels.
1927    pub unselected_label_color: Option<Color>,
1928
1929    /// The text style of the unselected tab labels.
1930    ///
1931    /// The color specified in [`unselected_label_style`](Self::unselected_label_style) and
1932    /// [`TabBarThemeData::unselected_label_style`] is used to style the label when
1933    /// [`unselected_label_color`](Self::unselected_label_color) or
1934    /// [`TabBarThemeData::unselected_label_color`] are not specified.
1935    ///
1936    /// If this property is null, then [`TabBarThemeData::unselected_label_style`] will be
1937    /// used.
1938    ///
1939    /// If that is also null and `ThemeData::use_material3` is true, `TextTheme::title_small`
1940    /// will be used, otherwise then the [`label_style`](Self::label_style) value is used. If
1941    /// [`label_style`](Self::label_style) is null, the text style of the
1942    /// `ThemeData::primary_text_theme`'s `TextTheme::body_large` definition is used.
1943    pub unselected_label_style: Option<TextStyle>,
1944
1945    /// Defines the ink response focus, hover, and splash colors.
1946    ///
1947    /// If non-null, it is resolved against one of `WidgetState::Focused`,
1948    /// `WidgetState::Hovered`, and `WidgetState::Pressed`.
1949    ///
1950    /// `WidgetState::Pressed` triggers a ripple (an ink splash), per
1951    /// the current Material Design spec.
1952    ///
1953    /// If the overlay color is null or resolves to null, then if `ThemeData::use_material3`
1954    /// is false, the default values for `InkResponse::focus_color`,
1955    /// `InkResponse::hover_color`, `InkResponse::splash_color`, and
1956    /// `InkResponse::highlight_color` will be used instead. If `ThemeData::use_material3`
1957    /// if true, the default values are:
1958    /// * selected:
1959    ///   * pressed - ThemeData.colorScheme.primary(0.1)
1960    ///   * hovered - ThemeData.colorScheme.primary(0.08)
1961    ///   * focused - ThemeData.colorScheme.primary(0.1)
1962    /// * pressed - ThemeData.colorScheme.primary(0.1)
1963    /// * hovered - ThemeData.colorScheme.onSurface(0.08)
1964    /// * focused - ThemeData.colorScheme.onSurface(0.1)
1965    pub overlay_color: Option<WidgetStatePropertyRef<Option<Color>>>,
1966
1967    /// Determines the way that drag start behavior is handled.
1968    pub drag_start_behavior: DragStartBehavior,
1969
1970    /// The cursor for a mouse pointer when it enters or is hovering over the
1971    /// individual tab widgets.
1972    ///
1973    /// If [`mouse_cursor`](Self::mouse_cursor) is a `WidgetStateMouseCursor`,
1974    /// `WidgetStateProperty::resolve` is used for the following `WidgetState`s:
1975    ///
1976    ///  * `WidgetState::Selected`.
1977    ///
1978    /// If null, then the value of [`TabBarThemeData::mouse_cursor`] is used. If
1979    /// that is also null, then `WidgetStateMouseCursor::clickable` is used.
1980    pub mouse_cursor: Option<MouseCursorRef>,
1981
1982    /// Whether detected gestures should provide acoustic and/or haptic feedback.
1983    ///
1984    /// For example, on Android a tap will produce a clicking sound and a long-press
1985    /// will produce a short vibration, when feedback is enabled.
1986    ///
1987    /// Defaults to true.
1988    pub enable_feedback: Option<bool>,
1989
1990    /// An optional callback that's called when the [`TabBar`] is tapped.
1991    ///
1992    /// The callback is applied to the index of the tab where the tap occurred.
1993    ///
1994    /// This callback has no effect on the default handling of taps. It's for
1995    /// applications that want to do a little extra work when a tab is tapped,
1996    /// even if the tap doesn't change the TabController's index. TabBar
1997    /// [`on_tap`](Self::on_tap) callbacks should not make changes to the TabController since
1998    /// that would interfere with the default tap handler.
1999    pub on_tap: Option<ValueChanged<usize>>,
2000
2001    /// An optional callback that's called when a [`Tab`]'s hover state in the
2002    /// [`TabBar`] changes.
2003    ///
2004    /// Called when a pointer enters or exits the ink response area of the [`Tab`].
2005    ///
2006    /// The value passed to the callback is true if a pointer has entered the
2007    /// [`Tab`] at `index` and false if a pointer has exited.
2008    ///
2009    /// When hover is moved from one tab directly to another, this will be called
2010    /// twice. First to represent hover exiting the initial tab, and then second
2011    /// for the pointer entering hover over the next tab.
2012    pub on_hover: Option<TabValueChanged<bool>>,
2013
2014    /// An optional callback that's called when a [`Tab`]'s focus state in the
2015    /// [`TabBar`] changes.
2016    ///
2017    /// Called when the node for the [`Tab`] at `index` gains or loses focus.
2018    ///
2019    /// The value passed to the callback is true if the node has gained focus for
2020    /// the [`Tab`] at `index` and false if focus has been lost.
2021    ///
2022    /// When focus is moved from one tab directly to another, this will be called
2023    /// twice. First to represent focus being lost by the initially focused tab,
2024    /// and then second for the next tab gaining focus.
2025    pub on_focus_change: Option<TabValueChanged<bool>>,
2026
2027    /// How the [`TabBar`]'s scroll view should respond to user input.
2028    ///
2029    /// For example, determines how the scroll view continues to animate after the
2030    /// user stops dragging the scroll view.
2031    ///
2032    /// Defaults to matching platform conventions.
2033    pub physics: Option<ScrollPhysicsRef>,
2034
2035    /// Creates the tab bar's [`InkWell`] splash factory, which defines
2036    /// the appearance of "ink" splashes that occur in response to taps.
2037    ///
2038    /// Use `NoSplash::splash_factory` to defeat ink splash rendering. For example
2039    /// to defeat both the splash and the hover/pressed overlay, but not the
2040    /// keyboard focused overlay:
2041    ///
2042    /// ```text
2043    /// TabBar::new(tabs)
2044    ///     .splash_factory(NoSplash::splash_factory())
2045    ///     .overlay_color(<dyn WidgetStateProperty<Option<Color>>>::resolve_with(|states| {
2046    ///         if states.contains(&WidgetState::Focused) { None } else { Some(Colors::TRANSPARENT) }
2047    ///     }))
2048    /// ```
2049    pub splash_factory: Option<InteractiveInkFeatureFactoryRef>,
2050
2051    /// Defines the clipping radius of splashes that extend outside the bounds of the tab.
2052    ///
2053    /// This can be useful to match the `BoxDecoration::border_radius` provided as
2054    /// [`indicator`](Self::indicator).
2055    ///
2056    /// If this property is null, it is interpreted as `BorderRadius::ZERO`.
2057    pub splash_border_radius: Option<BorderRadius>,
2058
2059    /// Specifies the horizontal alignment of the tabs within a [`TabBar`].
2060    ///
2061    /// If [`TabBar::is_scrollable`] is false, only [`TabAlignment::Fill`] and
2062    /// [`TabAlignment::Center`] are supported. Otherwise an exception is thrown.
2063    ///
2064    /// If [`TabBar::is_scrollable`] is true, only [`TabAlignment::Start`],
2065    /// [`TabAlignment::StartOffset`], and [`TabAlignment::Center`] are supported. Otherwise
2066    /// an exception is thrown.
2067    ///
2068    /// If this is null, then the value of [`TabBarThemeData::tab_alignment`] is used.
2069    ///
2070    /// If [`TabBarThemeData::tab_alignment`] is null and `ThemeData::use_material3` is true,
2071    /// then [`TabAlignment::StartOffset`] is used if [`is_scrollable`](Self::is_scrollable)
2072    /// is true, otherwise [`TabAlignment::Fill`] is used.
2073    ///
2074    /// If [`TabBarThemeData::tab_alignment`] is null and `ThemeData::use_material3` is false,
2075    /// then [`TabAlignment::Center`] is used if [`is_scrollable`](Self::is_scrollable) is
2076    /// true, otherwise [`TabAlignment::Fill`] is used.
2077    pub tab_alignment: Option<TabAlignment>,
2078
2079    /// Specifies the text scaling behavior for the [`Tab`] label.
2080    ///
2081    /// If this is null, then the value of [`TabBarThemeData::text_scaler`] is used. If that is
2082    /// also null, then the text scaling behavior is determined by the
2083    /// `MediaQueryData::text_scaler` from the ambient [`MediaQuery`], or 1.0 if there is no
2084    /// [`MediaQuery`] in scope.
2085    ///
2086    /// See also:
2087    ///   * [`TextScaler`], which is used to scale text based on the device's text scale
2088    ///     factor.
2089    pub text_scaler: Option<TextScaler>,
2090
2091    /// Specifies the animation behavior of the tab indicator.
2092    ///
2093    /// If this is null, then the value of [`TabBarThemeData::indicator_animation`] is used.
2094    /// If that is also null, then the tab indicator will animate linearly if the
2095    /// [`indicator_size`](Self::indicator_size) is [`TabBarIndicatorSize::Tab`], otherwise it
2096    /// will animate with an elastic effect if the [`indicator_size`](Self::indicator_size) is
2097    /// [`TabBarIndicatorSize::Label`].
2098    ///
2099    /// See also:
2100    ///
2101    ///  * [`TabIndicatorAnimation`], which specifies the animation behavior of the tab
2102    ///    indicator.
2103    pub indicator_animation: Option<TabIndicatorAnimation>,
2104
2105    /// Whether this tab bar is a primary tab bar.
2106    ///
2107    /// Otherwise, it is a secondary tab bar.
2108    is_primary: bool,
2109}
2110
2111impl TabBar {
2112    /// Creates a Material Design primary tab bar; Dart's named arguments are the setters.
2113    ///
2114    /// The length of the [`tabs`](Self::tabs) argument must match the
2115    /// [`controller`](Self::controller)'s [`TabController::length`].
2116    ///
2117    /// If a [`TabController`] is not provided, then there must be a
2118    /// [`DefaultTabController`] ancestor.
2119    ///
2120    /// The [`indicator_weight`](Self::indicator_weight) parameter defaults to 2.
2121    ///
2122    /// The [`indicator_padding`](Self::indicator_padding) parameter defaults to
2123    /// `EdgeInsets::ZERO`.
2124    ///
2125    /// If [`indicator`](Self::indicator) is not null or provided from [`TabBarTheme`],
2126    /// then [`indicator_color`](Self::indicator_color) is ignored.
2127    ///
2128    /// The [`indicator_weight`](Self::indicator_weight) does not affect the visual appearance
2129    /// of the indicator when a custom [`indicator`](Self::indicator) is provided. However,
2130    /// it may still be used to compute the TabBar's preferred size.
2131    pub fn new(tabs: impl IntoIterator<Item = WidgetRef>) -> TabBar {
2132        TabBar::with_primary(tabs, true)
2133    }
2134
2135    /// Creates a Material Design secondary tab bar.
2136    ///
2137    /// Secondary tabs are used within a content area to further separate related
2138    /// content and establish hierarchy.
2139    ///
2140    /// See also:
2141    ///
2142    ///  * [`TabBar::new`], for a primary tab bar.
2143    ///  * [`TabBarView`], which displays page views that correspond to each tab.
2144    ///  * [`TabController`], which coordinates tab selection between a [`TabBar`] and a
2145    ///    [`TabBarView`].
2146    ///  * <https://m3.material.io/components/tabs/overview>, the Material 3
2147    ///    tab bar specification.
2148    pub fn secondary(tabs: impl IntoIterator<Item = WidgetRef>) -> TabBar {
2149        TabBar::with_primary(tabs, false)
2150    }
2151
2152    fn with_primary(tabs: impl IntoIterator<Item = WidgetRef>, is_primary: bool) -> TabBar {
2153        TabBar {
2154            key: None,
2155            tabs: tabs.into_iter().collect(),
2156            controller: None,
2157            scroll_controller: None,
2158            is_scrollable: false,
2159            padding: None,
2160            indicator_color: None,
2161            automatic_indicator_color_adjustment: true,
2162            indicator_weight: 2.0,
2163            indicator_padding: EdgeInsetsGeometry::ZERO,
2164            indicator: None,
2165            indicator_size: None,
2166            divider_color: None,
2167            divider_height: None,
2168            label_color: None,
2169            label_style: None,
2170            label_padding: None,
2171            unselected_label_color: None,
2172            unselected_label_style: None,
2173            drag_start_behavior: DragStartBehavior::Start,
2174            overlay_color: None,
2175            mouse_cursor: None,
2176            enable_feedback: None,
2177            on_tap: None,
2178            on_hover: None,
2179            on_focus_change: None,
2180            physics: None,
2181            splash_factory: None,
2182            splash_border_radius: None,
2183            tab_alignment: None,
2184            text_scaler: None,
2185            indicator_animation: None,
2186            is_primary,
2187        }
2188    }
2189
2190    /// Dart `TabBar(key:)`.
2191    pub fn key(mut self, key: KeyRef) -> TabBar {
2192        self.key = Some(key);
2193        self
2194    }
2195
2196    /// Dart `TabBar(controller:)`.
2197    pub fn controller(mut self, controller: Ref<TabController>) -> TabBar {
2198        self.controller = Some(controller);
2199        self
2200    }
2201
2202    /// Dart `TabBar(scrollController:)`.
2203    pub fn scroll_controller(mut self, scroll_controller: Ref<TabBarScrollController>) -> TabBar {
2204        self.scroll_controller = Some(scroll_controller);
2205        self
2206    }
2207
2208    /// Dart `TabBar(isScrollable:)`.
2209    pub fn is_scrollable(mut self, is_scrollable: bool) -> TabBar {
2210        self.is_scrollable = is_scrollable;
2211        self
2212    }
2213
2214    /// Dart `TabBar(padding:)`.
2215    pub fn padding(mut self, padding: impl Into<EdgeInsetsGeometry>) -> TabBar {
2216        self.padding = Some(padding.into());
2217        self
2218    }
2219
2220    /// Dart `TabBar(indicatorColor:)`.
2221    pub fn indicator_color(mut self, indicator_color: Color) -> TabBar {
2222        self.indicator_color = Some(indicator_color);
2223        self
2224    }
2225
2226    /// Dart `TabBar(automaticIndicatorColorAdjustment:)`.
2227    pub fn automatic_indicator_color_adjustment(
2228        mut self,
2229        automatic_indicator_color_adjustment: bool,
2230    ) -> TabBar {
2231        self.automatic_indicator_color_adjustment = automatic_indicator_color_adjustment;
2232        self
2233    }
2234
2235    /// Dart `TabBar(indicatorWeight:)`.
2236    pub fn indicator_weight(mut self, indicator_weight: f64) -> TabBar {
2237        self.indicator_weight = indicator_weight;
2238        self
2239    }
2240
2241    /// Dart `TabBar(indicatorPadding:)`.
2242    pub fn indicator_padding(mut self, indicator_padding: impl Into<EdgeInsetsGeometry>) -> TabBar {
2243        self.indicator_padding = indicator_padding.into();
2244        self
2245    }
2246
2247    /// Dart `TabBar(indicator:)`.
2248    pub fn indicator(mut self, indicator: impl Into<DecorationRef>) -> TabBar {
2249        self.indicator = Some(indicator.into());
2250        self
2251    }
2252
2253    /// Dart `TabBar(indicatorSize:)`.
2254    pub fn indicator_size(mut self, indicator_size: TabBarIndicatorSize) -> TabBar {
2255        self.indicator_size = Some(indicator_size);
2256        self
2257    }
2258
2259    /// Dart `TabBar(dividerColor:)`.
2260    pub fn divider_color(mut self, divider_color: Color) -> TabBar {
2261        self.divider_color = Some(divider_color);
2262        self
2263    }
2264
2265    /// Dart `TabBar(dividerHeight:)`.
2266    pub fn divider_height(mut self, divider_height: f64) -> TabBar {
2267        self.divider_height = Some(divider_height);
2268        self
2269    }
2270
2271    /// Dart `TabBar(labelColor:)`.
2272    pub fn label_color(mut self, label_color: impl Into<AnyColor>) -> TabBar {
2273        self.label_color = Some(label_color.into());
2274        self
2275    }
2276
2277    /// Dart `TabBar(labelStyle:)`.
2278    pub fn label_style(mut self, label_style: TextStyle) -> TabBar {
2279        self.label_style = Some(label_style);
2280        self
2281    }
2282
2283    /// Dart `TabBar(labelPadding:)`.
2284    pub fn label_padding(mut self, label_padding: impl Into<EdgeInsetsGeometry>) -> TabBar {
2285        self.label_padding = Some(label_padding.into());
2286        self
2287    }
2288
2289    /// Dart `TabBar(unselectedLabelColor:)`.
2290    pub fn unselected_label_color(mut self, unselected_label_color: Color) -> TabBar {
2291        self.unselected_label_color = Some(unselected_label_color);
2292        self
2293    }
2294
2295    /// Dart `TabBar(unselectedLabelStyle:)`.
2296    pub fn unselected_label_style(mut self, unselected_label_style: TextStyle) -> TabBar {
2297        self.unselected_label_style = Some(unselected_label_style);
2298        self
2299    }
2300
2301    /// Dart `TabBar(dragStartBehavior:)`.
2302    pub fn drag_start_behavior(mut self, drag_start_behavior: DragStartBehavior) -> TabBar {
2303        self.drag_start_behavior = drag_start_behavior;
2304        self
2305    }
2306
2307    /// Dart `TabBar(overlayColor:)`.
2308    pub fn overlay_color(mut self, overlay_color: WidgetStatePropertyRef<Option<Color>>) -> TabBar {
2309        self.overlay_color = Some(overlay_color);
2310        self
2311    }
2312
2313    /// Dart `TabBar(mouseCursor:)`.
2314    pub fn mouse_cursor(mut self, mouse_cursor: impl Into<MouseCursorRef>) -> TabBar {
2315        self.mouse_cursor = Some(mouse_cursor.into());
2316        self
2317    }
2318
2319    /// Dart `TabBar(enableFeedback:)`.
2320    pub fn enable_feedback(mut self, enable_feedback: bool) -> TabBar {
2321        self.enable_feedback = Some(enable_feedback);
2322        self
2323    }
2324
2325    /// Dart `TabBar(onTap:)`.
2326    pub fn on_tap(mut self, on_tap: impl Fn(&mut App, usize) + 'static) -> TabBar {
2327        self.on_tap = Some(Rc::new(on_tap));
2328        self
2329    }
2330
2331    /// Dart `TabBar(onHover:)`.
2332    pub fn on_hover(mut self, on_hover: impl Fn(&mut App, bool, usize) + 'static) -> TabBar {
2333        self.on_hover = Some(Rc::new(on_hover));
2334        self
2335    }
2336
2337    /// Dart `TabBar(onFocusChange:)`.
2338    pub fn on_focus_change(
2339        mut self,
2340        on_focus_change: impl Fn(&mut App, bool, usize) + 'static,
2341    ) -> TabBar {
2342        self.on_focus_change = Some(Rc::new(on_focus_change));
2343        self
2344    }
2345
2346    /// Dart `TabBar(physics:)`.
2347    pub fn physics(mut self, physics: ScrollPhysicsRef) -> TabBar {
2348        self.physics = Some(physics);
2349        self
2350    }
2351
2352    /// Dart `TabBar(splashFactory:)`.
2353    pub fn splash_factory(mut self, splash_factory: InteractiveInkFeatureFactoryRef) -> TabBar {
2354        self.splash_factory = Some(splash_factory);
2355        self
2356    }
2357
2358    /// Dart `TabBar(splashBorderRadius:)`.
2359    pub fn splash_border_radius(mut self, splash_border_radius: BorderRadius) -> TabBar {
2360        self.splash_border_radius = Some(splash_border_radius);
2361        self
2362    }
2363
2364    /// Dart `TabBar(tabAlignment:)`.
2365    pub fn tab_alignment(mut self, tab_alignment: TabAlignment) -> TabBar {
2366        self.tab_alignment = Some(tab_alignment);
2367        self
2368    }
2369
2370    /// Dart `TabBar(textScaler:)`.
2371    pub fn text_scaler(mut self, text_scaler: TextScaler) -> TabBar {
2372        self.text_scaler = Some(text_scaler);
2373        self
2374    }
2375
2376    /// Dart `TabBar(indicatorAnimation:)`.
2377    pub fn indicator_animation(mut self, indicator_animation: TabIndicatorAnimation) -> TabBar {
2378        self.indicator_animation = Some(indicator_animation);
2379        self
2380    }
2381
2382    /// Returns whether the [`TabBar`] contains a tab with both text and icon.
2383    ///
2384    /// [`TabBar`] uses this to give uniform padding to all tabs in cases where
2385    /// there are some tabs with both text and icon and some which contain only
2386    /// text or icon.
2387    pub fn tab_has_text_and_icon(&self) -> bool {
2388        self.tabs
2389            .iter()
2390            .filter_map(preferred_size_of)
2391            .any(|size| size.height() == K_TEXT_AND_ICON_TAB_HEIGHT)
2392    }
2393}
2394
2395impl PreferredSizeWidget for TabBar {
2396    /// A size whose height depends on if the tabs have both icons and text.
2397    ///
2398    /// `AppBar` uses this size to compute its own preferred size.
2399    fn preferred_size(&self) -> waft_widgets::AnySize {
2400        let mut max_height = K_TAB_HEIGHT;
2401        for item in &self.tabs {
2402            if let Some(size) = preferred_size_of(item) {
2403                let item_height = size.height();
2404                max_height = item_height.max(max_height);
2405            }
2406        }
2407        Size::from_height(max_height + self.indicator_weight).into()
2408    }
2409}
2410
2411impl fmt::Debug for TabBar {
2412    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2413        f.debug_struct("TabBar")
2414            .field("tabs", &self.tabs.len())
2415            .field("is_scrollable", &self.is_scrollable)
2416            .field("is_primary", &self.is_primary)
2417            .finish()
2418    }
2419}
2420
2421impl StatefulWidget for TabBar {
2422    type State = TabBarState;
2423
2424    fn key(&self) -> Option<&KeyRef> {
2425        self.key.as_ref()
2426    }
2427
2428    fn as_preferred_size_widget(&self) -> Option<&dyn PreferredSizeWidget> {
2429        Some(self)
2430    }
2431
2432    fn create_state(&self) -> TabBarState {
2433        TabBarState {
2434            state: StateData::new(),
2435            internal_scroll_controller: None,
2436            controller: None,
2437            indicator_painter: None,
2438            current_index: None,
2439            tab_strip_width: 0.0,
2440            tab_keys: Rc::new(RefCell::new(Vec::new())),
2441            label_paddings: Rc::new(RefCell::new(Vec::new())),
2442            debug_has_scheduled_valid_tabs_count_check: false,
2443        }
2444    }
2445}
2446
2447/// Dart's `_TabBarState`.
2448pub struct TabBarState {
2449    state: StateData<TabBar>,
2450    internal_scroll_controller: Option<Ref<TabBarScrollController>>,
2451    controller: Option<Ref<TabController>>,
2452    indicator_painter: Option<Rc<IndicatorPainter>>,
2453    current_index: Option<usize>,
2454    /// Dart's `late double _tabStripWidth`, set by the first layout.
2455    tab_strip_width: f64,
2456    /// Shared with the indicator painter, as Dart hands the painter this state's list.
2457    tab_keys: Rc<RefCell<Vec<GlobalKey>>>,
2458    /// Shared with the indicator painter, as Dart hands the painter this state's list.
2459    label_paddings: Rc<RefCell<Vec<EdgeInsetsGeometry>>>,
2460    debug_has_scheduled_valid_tabs_count_check: bool,
2461}
2462
2463impl TabBarState {
2464    fn defaults(self: Handle<Self>, app: &mut App) -> Rc<dyn TabBarThemeDataGetters> {
2465        let context = self.context(app);
2466        let widget = self.widget(app);
2467        let (is_primary, is_scrollable) = (widget.is_primary, widget.is_scrollable);
2468        if Theme::of(app, context).use_material3 {
2469            if is_primary {
2470                Rc::new(TabsPrimaryDefaultsM3::new(context, is_scrollable))
2471            } else {
2472                Rc::new(TabsSecondaryDefaultsM3::new(context, is_scrollable))
2473            }
2474        } else {
2475            Rc::new(TabsDefaultsM2::new(context, is_scrollable))
2476        }
2477    }
2478
2479    fn effective_scroll_controller(
2480        self: Handle<Self>,
2481        app: &mut App,
2482    ) -> Ref<TabBarScrollController> {
2483        if let Some(scroll_controller) = self.widget(app).scroll_controller.clone() {
2484            if let Some(internal) = app.get_mut(self).internal_scroll_controller.take() {
2485                internal.dispose(app);
2486            }
2487
2488            return scroll_controller;
2489        }
2490
2491        match app.get(self).internal_scroll_controller.clone() {
2492            Some(internal) => internal,
2493            None => {
2494                let internal = TabBarScrollController::new(app);
2495                app.get_mut(self).internal_scroll_controller = Some(internal.clone());
2496                internal
2497            }
2498        }
2499    }
2500
2501    fn get_indicator(
2502        self: Handle<Self>,
2503        app: &mut App,
2504        indicator_size: TabBarIndicatorSize,
2505    ) -> DecorationRef {
2506        let context = self.context(app);
2507        let theme = Theme::of(app, context);
2508        let tab_bar_theme = TabBarTheme::of(app, context);
2509
2510        if let Some(indicator) = &self.widget(app).indicator {
2511            return indicator.clone();
2512        }
2513        if let Some(indicator) = &tab_bar_theme.indicator {
2514            return indicator.clone();
2515        }
2516        let widget = self.widget(app);
2517        if cfg!(debug_assertions) && widget.indicator_weight <= 0.0 {
2518            panic!(
2519                "Invalid indicatorWeight for TabBar.\n\
2520                 The indicatorWeight must be greater than zero when the TabBar draws its \
2521                 default underline indicator, that is when no indicator is provided by the \
2522                 TabBar or the TabBarTheme.\n\
2523                 To fix this, set indicatorWeight to a value greater than zero, or provide an \
2524                 indicator with the TabBar.indicator or TabBarThemeData.indicator property."
2525            );
2526        }
2527
2528        let (indicator_color, automatic_adjustment, indicator_weight, is_primary) = (
2529            widget.indicator_color,
2530            widget.automatic_indicator_color_adjustment,
2531            widget.indicator_weight,
2532            widget.is_primary,
2533        );
2534        let mut color = indicator_color
2535            .or(tab_bar_theme.indicator_color)
2536            .or_else(|| self.defaults(app).indicator_color(app))
2537            .expect("the tab defaults have an indicator color");
2538        // ThemeData tries to avoid this by having indicatorColor avoid being the
2539        // primaryColor. However, it's possible that the tab bar is on a
2540        // Material that isn't the primaryColor. In that case, if the indicator
2541        // color ends up matching the material's color, then this overrides it.
2542        // When that happens, automatic transitions of the theme will likely look
2543        // ugly as the indicator color suddenly snaps to white at one end, but it's
2544        // not clear how to avoid that any further.
2545        //
2546        // The material's color might be null (if it's a transparency). In that case
2547        // there's no good way for us to find out what the color is so we don't.
2548        //
2549        // TODO(xu-baolin): Remove automatic adjustment to white color indicator
2550        // with a better long-term solution.
2551        // https://github.com/flutter/flutter/pull/68171#pullrequestreview-517753917
2552        if automatic_adjustment
2553            && Some(color.to_argb32())
2554                == Material::maybe_of(app, context)
2555                    .and_then(|material| material.color(app))
2556                    .map(|material_color| material_color.to_argb32())
2557        {
2558            color = Colors::WHITE;
2559        }
2560
2561        let effective_indicator_weight = if theme.use_material3 {
2562            indicator_weight.max(if is_primary {
2563                TabsPrimaryDefaultsM3::indicator_weight(indicator_size)
2564            } else {
2565                TabsSecondaryDefaultsM3::INDICATOR_WEIGHT
2566            })
2567        } else {
2568            indicator_weight
2569        };
2570        // Only Material 3 primary TabBar with label indicatorSize should be rounded.
2571        let primary_with_label_indicator = match indicator_size {
2572            TabBarIndicatorSize::Label => is_primary,
2573            TabBarIndicatorSize::Tab => false,
2574        };
2575        let effective_border_radius =
2576            (theme.use_material3 && primary_with_label_indicator).then(|| {
2577                BorderRadius::only(
2578                    waft_embedder::Radius::circular(effective_indicator_weight),
2579                    waft_embedder::Radius::circular(effective_indicator_weight),
2580                    waft_embedder::Radius::ZERO,
2581                    waft_embedder::Radius::ZERO,
2582                )
2583            });
2584        let mut indicator = UnderlineTabIndicator::new().border_side(
2585            // TODO(tahatesser): Make sure this value matches Material 3 Tabs spec
2586            // when `preferredSize`and `indicatorWeight` are updated to support Material 3
2587            // https://m3.material.io/components/tabs/specs#149a189f-9039-4195-99da-15c205d20e30,
2588            // https://github.com/flutter/flutter/issues/116136
2589            waft_painting::BorderSide::new(
2590                color,
2591                effective_indicator_weight,
2592                BorderStyle::Solid,
2593                waft_painting::BorderSide::STROKE_ALIGN_INSIDE,
2594            ),
2595        );
2596        indicator.border_radius = effective_border_radius;
2597        DecorationRef::new(indicator)
2598    }
2599
2600    // If the TabBar is rebuilt with a new tab controller, the caller should
2601    // dispose the old one. In that case the old controller's animation will be
2602    // null and should not be accessed.
2603    fn controller_is_valid(self: Handle<Self>, app: &App) -> bool {
2604        app.get(self)
2605            .controller
2606            .handle()
2607            .is_some_and(|controller| controller.animation(app).is_some())
2608    }
2609
2610    fn animation_tick_listener(self: Handle<Self>) -> Listener {
2611        Listener::handle_method(self, Self::handle_tab_controller_animation_tick)
2612    }
2613
2614    fn tick_listener(self: Handle<Self>) -> Listener {
2615        Listener::handle_method(self, Self::handle_tab_controller_tick)
2616    }
2617
2618    fn update_tab_controller(self: Handle<Self>, app: &mut App) {
2619        let context = self.context(app);
2620        let new_controller = match self.widget(app).controller.clone() {
2621            Some(controller) => Some(controller),
2622            None => DefaultTabController::maybe_of(app, context),
2623        };
2624        if cfg!(debug_assertions) && new_controller.is_none() {
2625            panic!(
2626                "No TabController for TabBar.\n\
2627                 When creating a TabBar, you must either provide an explicit TabController \
2628                 using the \"controller\" property, or you must ensure that there is a \
2629                 DefaultTabController above the TabBar.\n\
2630                 In this case, there was neither an explicit controller nor a default \
2631                 controller."
2632            );
2633        }
2634
2635        if new_controller == app.get(self).controller {
2636            return;
2637        }
2638
2639        if self.controller_is_valid(app) {
2640            let controller = app.get(self).controller.handle().expect("checked above");
2641            let animation = controller.animation(app).expect("checked above");
2642            animation.remove_listener(app, &self.animation_tick_listener());
2643            controller.remove_listener(app, &self.tick_listener());
2644        }
2645        app.get_mut(self).controller = new_controller.clone();
2646        if let Some(controller) = new_controller {
2647            let animation = controller
2648                .animation(app)
2649                .expect("a new controller is not disposed");
2650            animation.add_listener(app, self.animation_tick_listener());
2651            controller.add_listener(app, self.tick_listener());
2652            app.get_mut(self).current_index = Some(controller.index(app));
2653        }
2654    }
2655
2656    fn update_scroll_controller(
2657        self: Handle<Self>,
2658        app: &mut App,
2659        old_scroll_controller: Option<Ref<TabBarScrollController>>,
2660    ) {
2661        let scroll_controller = self.widget(app).scroll_controller.clone();
2662        if old_scroll_controller != scroll_controller
2663            && let Some(old_scroll_controller) = old_scroll_controller
2664        {
2665            app.get_mut(&old_scroll_controller).tab_bar_state = None;
2666        }
2667        if let Some(scroll_controller) = scroll_controller {
2668            if let Some(internal) = app.get(self).internal_scroll_controller.handle() {
2669                app.get_mut(internal).tab_bar_state = None;
2670            }
2671            app.get_mut(&scroll_controller).tab_bar_state = Some(self);
2672        } else {
2673            let internal = match app.get(self).internal_scroll_controller.clone() {
2674                Some(internal) => internal,
2675                None => {
2676                    let internal = TabBarScrollController::new(app);
2677                    app.get_mut(self).internal_scroll_controller = Some(internal.clone());
2678                    internal
2679                }
2680            };
2681            app.get_mut(&internal).tab_bar_state = Some(self);
2682        }
2683    }
2684
2685    fn init_indicator_painter(self: Handle<Self>, app: &mut App) {
2686        let context = self.context(app);
2687        let theme = Theme::of(app, context);
2688        let tab_bar_theme = TabBarTheme::of(app, context);
2689        let widget = self.widget(app);
2690        let indicator_size = match widget.indicator_size.or(tab_bar_theme.indicator_size) {
2691            Some(indicator_size) => indicator_size,
2692            None => self
2693                .defaults(app)
2694                .indicator_size(app)
2695                .expect("the tab defaults have an indicator size"),
2696        };
2697        let widget = self.widget(app);
2698        let uses_default_primary_label_indicator = theme.use_material3
2699            && widget.is_primary
2700            && indicator_size == TabBarIndicatorSize::Label
2701            && widget.indicator.is_none()
2702            && tab_bar_theme.indicator.is_none();
2703
2704        let old_painter = app.get_mut(self).indicator_painter.take();
2705
2706        let default_tab_indicator_animation = match indicator_size {
2707            TabBarIndicatorSize::Label => TabIndicatorAnimation::Elastic,
2708            TabBarIndicatorSize::Tab => TabIndicatorAnimation::Linear,
2709        };
2710
2711        let indicator_painter = if !self.controller_is_valid(app) {
2712            None
2713        } else {
2714            let indicator = self.get_indicator(app, indicator_size);
2715            let defaults = self.defaults(app);
2716            let widget = self.widget(app);
2717            let (divider_color, divider_height) = (widget.divider_color, widget.divider_height);
2718            let divider_color = divider_color
2719                .or(tab_bar_theme.divider_color)
2720                .or_else(|| defaults.divider_color(app));
2721            let divider_height = divider_height
2722                .or(tab_bar_theme.divider_height)
2723                .or_else(|| defaults.divider_height(app));
2724            let widget = self.widget(app);
2725            let arguments = IndicatorPainterArguments {
2726                controller: app.get(self).controller.clone().expect("checked valid"),
2727                indicator,
2728                indicator_size,
2729                minimum_indicator_width: uses_default_primary_label_indicator
2730                    .then_some(K_MIN_PRIMARY_TAB_INDICATOR_WIDTH),
2731                indicator_padding: widget.indicator_padding,
2732                tab_keys: Rc::clone(&app.get(self).tab_keys),
2733                // Passing old painter so that the constructor can copy some values from it.
2734                old: old_painter.clone(),
2735                label_paddings: Rc::clone(&app.get(self).label_paddings),
2736                divider_color,
2737                divider_height,
2738                show_divider: theme.use_material3 && !widget.is_scrollable,
2739                device_pixel_ratio: None,
2740                indicator_animation: widget
2741                    .indicator_animation
2742                    .or(tab_bar_theme.indicator_animation)
2743                    .unwrap_or(default_tab_indicator_animation),
2744                text_direction: TextDirection::Ltr,
2745            };
2746            let device_pixel_ratio = MediaQuery::device_pixel_ratio_of(app, context);
2747            let text_direction = Directionality::of(app, context);
2748            Some(IndicatorPainter::new(
2749                app,
2750                IndicatorPainterArguments {
2751                    device_pixel_ratio: Some(device_pixel_ratio),
2752                    text_direction,
2753                    ..arguments
2754                },
2755            ))
2756        };
2757        app.get_mut(self).indicator_painter = indicator_painter;
2758
2759        if let Some(old_painter) = old_painter {
2760            old_painter.dispose(app);
2761        }
2762    }
2763
2764    fn indicator_painter(self: Handle<Self>, app: &App) -> Rc<IndicatorPainter> {
2765        Rc::clone(
2766            app.get(self)
2767                .indicator_painter
2768                .as_ref()
2769                .expect("a tab bar with a valid controller has an indicator painter"),
2770        )
2771    }
2772
2773    fn max_tab_index(self: Handle<Self>, app: &App) -> usize {
2774        self.indicator_painter(app).max_tab_index()
2775    }
2776
2777    fn tab_scroll_offset(
2778        self: Handle<Self>,
2779        app: &mut App,
2780        index: usize,
2781        viewport_width: f64,
2782        min_extent: f64,
2783        max_extent: f64,
2784    ) -> f64 {
2785        if !self.widget(app).is_scrollable {
2786            return 0.0;
2787        }
2788        let mut tab_center = self.indicator_painter(app).center_of(index);
2789        let padding_start;
2790        let context = self.context(app);
2791        let padding = self.widget(app).padding;
2792        match Directionality::of(app, context) {
2793            TextDirection::Rtl => {
2794                padding_start = padding
2795                    .map(|padding| padding.resolve(Some(TextDirection::Rtl)).right)
2796                    .unwrap_or(0.0);
2797                tab_center = app.get(self).tab_strip_width - tab_center;
2798            }
2799            TextDirection::Ltr => {
2800                padding_start = padding
2801                    .map(|padding| padding.resolve(Some(TextDirection::Ltr)).left)
2802                    .unwrap_or(0.0);
2803            }
2804        }
2805
2806        clamp_double(
2807            tab_center + padding_start - viewport_width / 2.0,
2808            min_extent,
2809            max_extent,
2810        )
2811    }
2812
2813    fn tab_centered_scroll_offset(self: Handle<Self>, app: &mut App, index: usize) -> f64 {
2814        let position = self.effective_scroll_controller(app).position(app);
2815
2816        let viewport_dimension = position.viewport_dimension(app);
2817        let min_scroll_extent = position.min_scroll_extent(app);
2818        let max_scroll_extent = position.max_scroll_extent(app);
2819        self.tab_scroll_offset(
2820            app,
2821            index,
2822            viewport_dimension,
2823            min_scroll_extent,
2824            max_scroll_extent,
2825        )
2826    }
2827
2828    fn initial_scroll_offset(
2829        self: Handle<Self>,
2830        app: &mut App,
2831        viewport_width: f64,
2832        min_extent: f64,
2833        max_extent: f64,
2834    ) -> f64 {
2835        let current_index = app.get(self).current_index.expect("a controller is set");
2836        self.tab_scroll_offset(app, current_index, viewport_width, min_extent, max_extent)
2837    }
2838
2839    fn scroll_to_current_index(self: Handle<Self>, app: &mut App) {
2840        let current_index = app.get(self).current_index.expect("a controller is set");
2841        let offset = self.tab_centered_scroll_offset(app, current_index);
2842
2843        let scroll_controller = self.effective_scroll_controller(app);
2844        drop(scroll_controller.animate_to(app, offset, K_TAB_SCROLL_DURATION, Curves::ease()));
2845    }
2846
2847    fn scroll_to_controller_value(self: Handle<Self>, app: &mut App) {
2848        let current_index = app.get(self).current_index.expect("a controller is set");
2849        let leading_position =
2850            (current_index > 0).then(|| self.tab_centered_scroll_offset(app, current_index - 1));
2851        let middle_position = self.tab_centered_scroll_offset(app, current_index);
2852        let trailing_position = (current_index < self.max_tab_index(app))
2853            .then(|| self.tab_centered_scroll_offset(app, current_index + 1));
2854
2855        let controller = app
2856            .get(self)
2857            .controller
2858            .handle()
2859            .expect("a controller is set");
2860        let index = controller.index(app) as f64;
2861        let value = controller
2862            .animation(app)
2863            .expect("a valid controller has an animation")
2864            .value(app);
2865        let lerp = |a: f64, b: f64, t: f64| {
2866            lerp_double(Some(a), Some(b), t).expect("two values lerp to a value")
2867        };
2868        let delta = value - index;
2869        let offset = if delta == -1.0 {
2870            leading_position.unwrap_or(middle_position)
2871        } else if delta == 1.0 {
2872            trailing_position.unwrap_or(middle_position)
2873        } else if delta == 0.0 {
2874            middle_position
2875        } else if delta < 0.0 {
2876            match leading_position {
2877                None => middle_position,
2878                Some(leading_position) => lerp(middle_position, leading_position, index - value),
2879            }
2880        } else {
2881            match trailing_position {
2882                None => middle_position,
2883                Some(trailing_position) => lerp(middle_position, trailing_position, value - index),
2884            }
2885        };
2886
2887        let scroll_controller = self.effective_scroll_controller(app);
2888        scroll_controller.jump_to(app, offset);
2889    }
2890
2891    fn handle_tab_controller_animation_tick(self: Handle<Self>, app: &mut App) {
2892        debug_assert!(self.mounted(app));
2893        let controller = app
2894            .get(self)
2895            .controller
2896            .handle()
2897            .expect("listening to a controller");
2898        if !controller.index_is_changing(app) && self.widget(app).is_scrollable {
2899            // Sync the TabBar's scroll position with the TabBarView's PageView.
2900            app.get_mut(self).current_index = Some(controller.index(app));
2901            self.scroll_to_controller_value(app);
2902        }
2903    }
2904
2905    fn handle_tab_controller_tick(self: Handle<Self>, app: &mut App) {
2906        let controller = app
2907            .get(self)
2908            .controller
2909            .handle()
2910            .expect("listening to a controller");
2911        if Some(controller.index(app)) != app.get(self).current_index {
2912            app.get_mut(self).current_index = Some(controller.index(app));
2913            if self.widget(app).is_scrollable {
2914                self.scroll_to_current_index(app);
2915            }
2916        }
2917        self.set_state(app, |_state| {
2918            // Rebuild the tabs after a (potentially animated) index change
2919            // has completed.
2920        });
2921    }
2922
2923    // Called each time layout completes.
2924    fn save_tab_offsets(
2925        self: Handle<Self>,
2926        app: &mut App,
2927        tab_offsets: Vec<f64>,
2928        text_direction: TextDirection,
2929        width: f64,
2930    ) {
2931        app.get_mut(self).tab_strip_width = width;
2932        if let Some(indicator_painter) = &app.get(self).indicator_painter {
2933            indicator_painter.save_tab_offsets(Some(tab_offsets), Some(text_direction));
2934        }
2935    }
2936
2937    fn handle_tap(self: Handle<Self>, app: &mut App, index: usize) {
2938        debug_assert!(index < self.widget(app).tabs.len());
2939        let controller = app
2940            .get(self)
2941            .controller
2942            .handle()
2943            .expect("a tapped tab bar has a controller");
2944        controller.animate_to(app, index, None, None);
2945        if let Some(on_tap) = self.widget(app).on_tap.clone() {
2946            on_tap(app, index);
2947        }
2948    }
2949
2950    fn build_styled_tab(
2951        self: Handle<Self>,
2952        app: &App,
2953        child: WidgetRef,
2954        is_selected: bool,
2955        animation: AnimationRef<f64>,
2956        defaults: &Rc<dyn TabBarThemeDataGetters>,
2957    ) -> WidgetRef {
2958        let widget = self.widget(app);
2959        TabStyle {
2960            animation,
2961            is_selected,
2962            is_primary: widget.is_primary,
2963            label_color: widget.label_color.clone(),
2964            unselected_label_color: widget.unselected_label_color,
2965            label_style: widget.label_style.clone(),
2966            unselected_label_style: widget.unselected_label_style.clone(),
2967            defaults: Rc::clone(defaults),
2968            child,
2969        }
2970        .into_widget()
2971    }
2972
2973    fn debug_schedule_check_has_valid_tabs_count(self: Handle<Self>, app: &mut App) -> bool {
2974        if app.get(self).debug_has_scheduled_valid_tabs_count_check {
2975            return true;
2976        }
2977        SchedulerBinding::add_post_frame_callback(
2978            app,
2979            FrameCallback::new(move |app, _duration| {
2980                if !app.contains(self) {
2981                    return;
2982                }
2983                app.get_mut(self).debug_has_scheduled_valid_tabs_count_check = false;
2984                if !self.mounted(app) {
2985                    return;
2986                }
2987                let controller = app
2988                    .get(self)
2989                    .controller
2990                    .handle()
2991                    .expect("a mounted tab bar has a controller");
2992                let length = controller.length(app);
2993                let tab_count = self.widget(app).tabs.len();
2994                if cfg!(debug_assertions) && length != tab_count {
2995                    panic!(
2996                        "Controller's length property ({length}) does not match the number of \
2997                         tabs ({tab_count}) present in TabBar's tabs property."
2998                    );
2999                }
3000            }),
3001            None,
3002        );
3003        app.get_mut(self).debug_has_scheduled_valid_tabs_count_check = true;
3004        true
3005    }
3006
3007    fn debug_tab_alignment_is_valid(
3008        self: Handle<Self>,
3009        app: &App,
3010        tab_alignment: TabAlignment,
3011    ) -> bool {
3012        if cfg!(debug_assertions) {
3013            let is_scrollable = self.widget(app).is_scrollable;
3014            if is_scrollable && tab_alignment == TabAlignment::Fill {
3015                panic!("{tab_alignment:?} is only valid for non-scrollable tab bars.");
3016            }
3017            if !is_scrollable
3018                && (tab_alignment == TabAlignment::Start
3019                    || tab_alignment == TabAlignment::StartOffset)
3020            {
3021                panic!("{tab_alignment:?} is only valid for scrollable tab bars.");
3022            }
3023        }
3024        true
3025    }
3026}
3027
3028impl State for TabBarState {
3029    type Widget = TabBar;
3030    waft_widgets::state_accessors!();
3031
3032    fn init_state(self: Handle<Self>, app: &mut App) {
3033        // If indicatorSize is TabIndicatorSize.label, _tabKeys[i] is used to find
3034        // the width of tab widget i. See _IndicatorPainter.indicatorRect().
3035        let tab_count = self.widget(app).tabs.len();
3036        let this = app.get(self);
3037        *this.tab_keys.borrow_mut() = (0..tab_count).map(|_| GlobalKey::new()).collect();
3038        *this.label_paddings.borrow_mut() = vec![EdgeInsetsGeometry::ZERO; tab_count];
3039    }
3040
3041    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
3042        self.update_scroll_controller(app, None);
3043        self.update_tab_controller(app);
3044        self.init_indicator_painter(app);
3045    }
3046
3047    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &TabBar) {
3048        let widget = self.widget(app);
3049        if widget.controller != old_widget.controller
3050            || widget.scroll_controller != old_widget.scroll_controller
3051        {
3052            self.update_scroll_controller(app, old_widget.scroll_controller.clone());
3053            self.update_tab_controller(app);
3054            self.init_indicator_painter(app);
3055
3056            // Adjust scroll position.
3057            let scroll_controller = self.effective_scroll_controller(app);
3058            if scroll_controller.has_clients(app) {
3059                let position = scroll_controller.position(app);
3060                if let Some(position) = position.downcast::<TabBarScrollPosition>(app) {
3061                    position.mark_needs_pixels_correction(app);
3062                }
3063            }
3064        } else if widget.indicator_color != old_widget.indicator_color
3065            || widget.indicator_weight != old_widget.indicator_weight
3066            || widget.indicator_size != old_widget.indicator_size
3067            || widget.indicator_padding != old_widget.indicator_padding
3068            || widget.indicator != old_widget.indicator
3069            || widget.divider_color != old_widget.divider_color
3070            || widget.divider_height != old_widget.divider_height
3071            || widget.indicator_animation != old_widget.indicator_animation
3072        {
3073            self.init_indicator_painter(app);
3074        }
3075
3076        let tab_count = self.widget(app).tabs.len();
3077        let this = app.get(self);
3078        let mut tab_keys = this.tab_keys.borrow_mut();
3079        let mut label_paddings = this.label_paddings.borrow_mut();
3080        if tab_count > tab_keys.len() {
3081            let delta = tab_count - tab_keys.len();
3082            tab_keys.extend((0..delta).map(|_| GlobalKey::new()));
3083            label_paddings.extend(std::iter::repeat_n(EdgeInsetsGeometry::ZERO, delta));
3084        } else if tab_count < tab_keys.len() {
3085            tab_keys.truncate(tab_count);
3086            // Dart removes `_labelPaddings` from the new tab count up to `_tabKeys.length`,
3087            // which it has just shortened to that count: nothing.
3088            let end = tab_keys.len();
3089            label_paddings.drain(tab_count..end);
3090        }
3091    }
3092
3093    fn dispose(self: Handle<Self>, app: &mut App) {
3094        self.indicator_painter(app).dispose(app);
3095        if self.controller_is_valid(app) {
3096            let controller = app.get(self).controller.handle().expect("checked valid");
3097            let animation = controller.animation(app).expect("checked valid");
3098            animation.remove_listener(app, &self.animation_tick_listener());
3099            controller.remove_listener(app, &self.tick_listener());
3100        }
3101        app.get_mut(self).controller = None;
3102        if let Some(internal) = app.get(self).internal_scroll_controller.handle() {
3103            internal.dispose(app);
3104        }
3105        if let Some(scroll_controller) = self.widget(app).scroll_controller.clone() {
3106            app.get_mut(&scroll_controller).tab_bar_state = None;
3107        }
3108        // We don't own the _controller Animation, so it's not disposed here.
3109    }
3110
3111    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
3112        debug_assert!(debug_check_has_material_localizations(app, context));
3113        debug_assert!(self.debug_schedule_check_has_valid_tabs_count(app));
3114        let theme = Theme::of(app, context);
3115        let tab_bar_theme = TabBarTheme::of(app, context);
3116        let defaults = self.defaults(app);
3117        let effective_tab_alignment = self
3118            .widget(app)
3119            .tab_alignment
3120            .or(tab_bar_theme.tab_alignment)
3121            .or_else(|| defaults.tab_alignment(app))
3122            .expect("the tab defaults have a tab alignment");
3123        debug_assert!(self.debug_tab_alignment_is_valid(app, effective_tab_alignment));
3124
3125        let localizations = <dyn MaterialLocalizations>::of(app, context);
3126        let controller = app
3127            .get(self)
3128            .controller
3129            .clone()
3130            .expect("a built tab bar has a controller");
3131        let indicator_weight = self.widget(app).indicator_weight;
3132        if controller.length(app) == 0 {
3133            return LimitedBox::new()
3134                .max_width(0.0)
3135                .child(
3136                    SizedBox::new()
3137                        .width(f64::INFINITY)
3138                        .height(K_TAB_HEIGHT + indicator_weight),
3139                )
3140                .into_widget();
3141        }
3142
3143        let widget = self.widget(app);
3144        let tab_count = widget.tabs.len();
3145        let mut wrapped_tabs: Vec<WidgetRef> = (0..tab_count)
3146            .map(|index| {
3147                let widget = self.widget(app);
3148                let mut padding = widget
3149                    .label_padding
3150                    .or(tab_bar_theme.label_padding)
3151                    .unwrap_or(K_TAB_LABEL_PADDING.into());
3152                const VERTICAL_ADJUSTMENT: f64 = (K_TEXT_AND_ICON_TAB_HEIGHT - K_TAB_HEIGHT) / 2.0;
3153
3154                let tab = &widget.tabs[index];
3155                if preferred_size_of(tab).is_some_and(|size| size.height() == K_TAB_HEIGHT)
3156                    && widget.tab_has_text_and_icon()
3157                {
3158                    padding = padding.add(EdgeInsetsGeometry::symmetric(VERTICAL_ADJUSTMENT, 0.0));
3159                }
3160                let this = app.get(self);
3161                this.label_paddings.borrow_mut()[index] = padding;
3162                let tab_key = this.tab_keys.borrow()[index].clone();
3163
3164                Center::new()
3165                    .height_factor(1.0)
3166                    .child(
3167                        Padding::new(padding).child(
3168                            KeyedSubtree::new(widget.tabs[index].clone()).key(tab_key.into()),
3169                        ),
3170                    )
3171                    .into_widget()
3172            })
3173            .collect();
3174
3175        // If the controller was provided by DefaultTabController and we're part
3176        // of a Hero (typically the AppBar), then we will not be able to find the
3177        // controller during a Hero transition. See https://github.com/flutter/flutter/issues/213.
3178        let previous_index = controller.previous_index(app);
3179        let current_index = app.get(self).current_index.expect("a controller is set");
3180
3181        if controller.index_is_changing(app) {
3182            // The user tapped on a tab, the tab controller's animation is running.
3183            debug_assert!(current_index != previous_index);
3184            let animation: AnimationRef<f64> =
3185                ChangeAnimation::new(app, controller.clone()).into_erased();
3186            wrapped_tabs[current_index] = self.build_styled_tab(
3187                app,
3188                wrapped_tabs[current_index].clone(),
3189                true,
3190                animation.clone(),
3191                &defaults,
3192            );
3193            wrapped_tabs[previous_index] = self.build_styled_tab(
3194                app,
3195                wrapped_tabs[previous_index].clone(),
3196                false,
3197                animation,
3198                &defaults,
3199            );
3200        } else {
3201            // The user is dragging the TabBarView's PageView left or right.
3202            let tab_index = current_index;
3203            let center_animation: AnimationRef<f64> =
3204                DragAnimation::new(app, controller.clone(), tab_index).into_erased();
3205            wrapped_tabs[tab_index] = self.build_styled_tab(
3206                app,
3207                wrapped_tabs[tab_index].clone(),
3208                true,
3209                center_animation,
3210                &defaults,
3211            );
3212            if current_index > 0 {
3213                let tab_index = current_index - 1;
3214                let drag_animation: AnimationRef<f64> =
3215                    DragAnimation::new(app, controller.clone(), tab_index).into_erased();
3216                let previous_animation = ReverseAnimation::new(app, drag_animation).into_erased();
3217                wrapped_tabs[tab_index] = self.build_styled_tab(
3218                    app,
3219                    wrapped_tabs[tab_index].clone(),
3220                    false,
3221                    previous_animation,
3222                    &defaults,
3223                );
3224            }
3225            if current_index < tab_count - 1 {
3226                let tab_index = current_index + 1;
3227                let drag_animation: AnimationRef<f64> =
3228                    DragAnimation::new(app, controller.clone(), tab_index).into_erased();
3229                let next_animation = ReverseAnimation::new(app, drag_animation).into_erased();
3230                wrapped_tabs[tab_index] = self.build_styled_tab(
3231                    app,
3232                    wrapped_tabs[tab_index].clone(),
3233                    false,
3234                    next_animation,
3235                    &defaults,
3236                );
3237            }
3238        }
3239
3240        // Add the tap handler to each tab. If the tab bar is not scrollable,
3241        // then give all of the tabs equal flexibility so that they each occupy
3242        // the same share of the tab bar's overall width.
3243        #[expect(
3244            clippy::needless_range_loop,
3245            reason = "Dart's indexed loop over the tabs"
3246        )]
3247        for index in 0..tab_count {
3248            let selected_state: WidgetStates = if Some(index) == app.get(self).current_index {
3249                WidgetStates::from([WidgetState::Selected])
3250            } else {
3251                WidgetStates::new()
3252            };
3253
3254            let widget_ref = context.widget(app).clone();
3255            let widget = waft_widgets::downcast_widget::<TabBar>(&*widget_ref)
3256                .expect("a TabBarState builds its TabBar");
3257            let effective_mouse_cursor: MouseCursorRef = widget
3258                .mouse_cursor
3259                .as_ref()
3260                .and_then(|mouse_cursor| {
3261                    <dyn WidgetStateProperty<MouseCursorRef>>::resolve_as(
3262                        &Some(mouse_cursor.clone()),
3263                        &selected_state,
3264                    )
3265                })
3266                .or_else(|| {
3267                    tab_bar_theme
3268                        .mouse_cursor
3269                        .as_ref()
3270                        .and_then(|mouse_cursor| mouse_cursor.resolve(&selected_state))
3271                })
3272                .unwrap_or_else(|| WidgetStateMouseCursor::clickable().resolve(&selected_state));
3273
3274            let default_overlay_states = selected_state.clone();
3275            let default_overlay_color = defaults.overlay_color(app);
3276            let default_overlay: WidgetStatePropertyRef<Option<Color>> =
3277                <dyn WidgetStateProperty<Option<Color>>>::resolve_with(move |states| {
3278                    let mut effective_states = default_overlay_states.clone();
3279                    effective_states.extend(states.iter().copied());
3280                    default_overlay_color
3281                        .as_ref()
3282                        .and_then(|overlay_color| overlay_color.resolve(&effective_states))
3283                });
3284            let mut ink_well = InkWell::new()
3285                .mouse_cursor(effective_mouse_cursor)
3286                .on_tap(Listener::new(move |app: &mut App| {
3287                    self.handle_tap(app, index);
3288                }))
3289                .on_hover(Rc::new(move |app: &mut App, value: bool| {
3290                    if let Some(on_hover) = self.widget(app).on_hover.clone() {
3291                        on_hover(app, value, index);
3292                    }
3293                }))
3294                .on_focus_change(Rc::new(move |app: &mut App, value: bool| {
3295                    if let Some(on_focus_change) = self.widget(app).on_focus_change.clone() {
3296                        on_focus_change(app, value, index);
3297                    }
3298                }))
3299                .enable_feedback(widget.enable_feedback.unwrap_or(true))
3300                .overlay_color(
3301                    widget
3302                        .overlay_color
3303                        .clone()
3304                        .or_else(|| tab_bar_theme.overlay_color.clone())
3305                        .unwrap_or(default_overlay),
3306                );
3307            if let Some(splash_factory) = widget
3308                .splash_factory
3309                .clone()
3310                .or_else(|| tab_bar_theme.splash_factory.clone())
3311                .or_else(|| defaults.splash_factory(app))
3312            {
3313                ink_well = ink_well.splash_factory(splash_factory);
3314            }
3315            if let Some(border_radius) = widget
3316                .splash_border_radius
3317                .or(tab_bar_theme.splash_border_radius)
3318                .or_else(|| defaults.splash_border_radius(app))
3319            {
3320                ink_well = ink_well.border_radius(border_radius);
3321            }
3322            let selected = Some(index) == app.get(self).current_index;
3323            let mut tab_semantics = Semantics::new().selected(selected);
3324            if !K_IS_WEB {
3325                tab_semantics = tab_semantics
3326                    .label(localizations.tab_label(index as i32 + 1, tab_count as i32));
3327            }
3328            wrapped_tabs[index] = ink_well
3329                .child(
3330                    Padding::new(EdgeInsetsGeometry::only(0.0, 0.0, 0.0, indicator_weight)).child(
3331                        // This has to be wrapped above the Stack to override any role set by the child.
3332                        Semantics::new().role(SemanticsRole::Tab).child(
3333                            Stack::new().children([
3334                                wrapped_tabs[index].clone(),
3335                                tab_semantics.into_widget(),
3336                            ]),
3337                        ),
3338                    ),
3339                )
3340                .into_widget();
3341            wrapped_tabs[index] = MergeSemantics::new()
3342                .child(wrapped_tabs[index].clone())
3343                .into_widget();
3344            if !self.widget(app).is_scrollable && effective_tab_alignment == TabAlignment::Fill {
3345                wrapped_tabs[index] = Expanded::new(wrapped_tabs[index].clone()).into_widget();
3346            }
3347        }
3348
3349        let on_perform_layout: LayoutCallback =
3350            Rc::new(move |app, tab_offsets, text_direction, width| {
3351                self.save_tab_offsets(app, tab_offsets, text_direction, width);
3352            });
3353        let always_dismissed = k_always_dismissed_animation(app);
3354        let widget = self.widget(app);
3355        let mut indicator_paint = CustomPaint::new().child(TabStyle {
3356            animation: always_dismissed,
3357            is_selected: false,
3358            is_primary: widget.is_primary,
3359            label_color: widget.label_color.clone(),
3360            unselected_label_color: widget.unselected_label_color,
3361            label_style: widget.label_style.clone(),
3362            unselected_label_style: widget.unselected_label_style.clone(),
3363            defaults: Rc::clone(&defaults),
3364            child: TabLabelBar::new(
3365                wrapped_tabs,
3366                on_perform_layout,
3367                if effective_tab_alignment == TabAlignment::Fill {
3368                    MainAxisSize::Max
3369                } else {
3370                    MainAxisSize::Min
3371                },
3372            )
3373            .into_widget(),
3374        });
3375        indicator_paint.painter = app
3376            .get(self)
3377            .indicator_painter
3378            .clone()
3379            .map(|painter| painter as Rc<dyn CustomPainter>);
3380        let mut tab_bar = Semantics::new()
3381            .role(SemanticsRole::TabBar)
3382            .container(true)
3383            .explicit_child_nodes(true)
3384            .child(indicator_paint)
3385            .into_widget();
3386
3387        let widget = self.widget(app);
3388        if widget.is_scrollable {
3389            let effective_padding = if effective_tab_alignment == TabAlignment::StartOffset {
3390                Some(
3391                    EdgeInsetsGeometry::from(EdgeInsetsDirectional::only(
3392                        K_START_OFFSET,
3393                        0.0,
3394                        0.0,
3395                        0.0,
3396                    ))
3397                    .add(widget.padding.unwrap_or(EdgeInsetsGeometry::ZERO)),
3398                )
3399            } else {
3400                widget.padding
3401            };
3402
3403            let (drag_start_behavior, physics) =
3404                (widget.drag_start_behavior, widget.physics.clone());
3405            let scroll_behavior = ScrollConfiguration::of(app, context);
3406            let scroll_controller = self.effective_scroll_controller(app);
3407            let mut scroll_view = SingleChildScrollView::new()
3408                .drag_start_behavior(drag_start_behavior)
3409                .scroll_direction(Axis::Horizontal)
3410                .controller(scroll_controller.erase());
3411            if let Some(effective_padding) = effective_padding {
3412                scroll_view = scroll_view.padding(effective_padding);
3413            }
3414            if let Some(physics) = physics {
3415                scroll_view = scroll_view.physics(physics);
3416            }
3417            tab_bar = ScrollConfiguration::new(
3418                // The scrolling tabs should not show an overscroll indicator.
3419                waft_widgets::ScrollBehaviorRef::new(scroll_behavior.copy_with().overscroll(false)),
3420                scroll_view.child(tab_bar),
3421            )
3422            .into_widget();
3423            if theme.use_material3 {
3424                let effective_alignment = match effective_tab_alignment {
3425                    TabAlignment::Center => AlignmentGeometry::CENTER,
3426                    TabAlignment::Start | TabAlignment::StartOffset | TabAlignment::Fill => {
3427                        AlignmentGeometry::CENTER_START
3428                    }
3429                };
3430
3431                let widget = self.widget(app);
3432                let (divider_color, divider_height) = (widget.divider_color, widget.divider_height);
3433                let divider_color = divider_color
3434                    .or(tab_bar_theme.divider_color)
3435                    .or_else(|| defaults.divider_color(app))
3436                    .expect("the Material 3 tab defaults have a divider color");
3437                let divider_height = divider_height
3438                    .or(tab_bar_theme.divider_height)
3439                    .or_else(|| defaults.divider_height(app))
3440                    .expect("the Material 3 tab defaults have a divider height");
3441
3442                let mut align = Align::new()
3443                    .height_factor(1.0)
3444                    .alignment(effective_alignment);
3445                if divider_height <= 0.0 {
3446                    align = align.width_factor(1.0);
3447                }
3448                tab_bar = align.child(tab_bar).into_widget();
3449
3450                if divider_color != Colors::TRANSPARENT && divider_height > 0.0 {
3451                    tab_bar = CustomPaint::new()
3452                        .painter(DividerPainter {
3453                            divider_color,
3454                            divider_height,
3455                        })
3456                        .child(tab_bar)
3457                        .into_widget();
3458                }
3459            }
3460        } else if let Some(padding) = widget.padding {
3461            tab_bar = Padding::new(padding).child(tab_bar).into_widget();
3462        }
3463
3464        let mut media_query_data = MediaQuery::of(app, context).copy_with();
3465        if let Some(text_scaler) = self
3466            .widget(app)
3467            .text_scaler
3468            .clone()
3469            .or_else(|| tab_bar_theme.text_scaler.clone())
3470        {
3471            media_query_data = media_query_data.text_scaler(text_scaler);
3472        }
3473        Material::new()
3474            .r#type(MaterialType::Transparency)
3475            .child(MediaQuery::new(media_query_data, tab_bar).into_widget())
3476            .into_widget()
3477    }
3478}
3479
3480/// A page view that displays the widget which corresponds to the currently
3481/// selected tab.
3482///
3483/// This widget is typically used in conjunction with a [`TabBar`].
3484///
3485/// If a [`TabController`] is not provided, then there must be a [`DefaultTabController`]
3486/// ancestor.
3487///
3488/// The tab controller's [`TabController::length`] must equal the length of the
3489/// [`children`](Self::children) list and the length of the [`TabBar::tabs`] list.
3490///
3491/// To see a sample implementation, visit the [`TabController`] documentation.
3492pub struct TabBarView {
3493    pub key: Option<KeyRef>,
3494
3495    /// This widget's selection and animation state.
3496    ///
3497    /// If [`TabController`] is not provided, then the value of [`DefaultTabController::of`]
3498    /// will be used.
3499    pub controller: Option<Ref<TabController>>,
3500
3501    /// One widget per tab.
3502    ///
3503    /// Its length must match the length of the [`TabBar::tabs`]
3504    /// list, as well as the [`controller`](Self::controller)'s [`TabController::length`].
3505    pub children: Vec<WidgetRef>,
3506
3507    /// How the page view should respond to user input.
3508    ///
3509    /// For example, determines how the page view continues to animate after the
3510    /// user stops dragging the page view.
3511    ///
3512    /// The physics are modified to snap to page boundaries using
3513    /// [`PageScrollPhysics`] prior to being used.
3514    ///
3515    /// Defaults to matching platform conventions.
3516    pub physics: Option<ScrollPhysicsRef>,
3517
3518    /// Determines the way that drag start behavior is handled.
3519    pub drag_start_behavior: DragStartBehavior,
3520
3521    /// The fraction of the viewport that each page should occupy.
3522    ///
3523    /// Defaults to 1.0, which means each page fills the viewport in the scrolling
3524    /// direction.
3525    pub viewport_fraction: f64,
3526
3527    /// The content will be clipped (or not) according to this option.
3528    ///
3529    /// Defaults to [`Clip::HardEdge`].
3530    pub clip_behavior: Clip,
3531}
3532
3533impl TabBarView {
3534    /// Creates a page view with one child per tab.
3535    ///
3536    /// The length of [`children`](Self::children) must be the same as the
3537    /// [`controller`](Self::controller)'s length.
3538    pub fn new(children: impl IntoIterator<Item = WidgetRef>) -> TabBarView {
3539        TabBarView {
3540            key: None,
3541            controller: None,
3542            children: children.into_iter().collect(),
3543            physics: None,
3544            drag_start_behavior: DragStartBehavior::Start,
3545            viewport_fraction: 1.0,
3546            clip_behavior: Clip::HardEdge,
3547        }
3548    }
3549
3550    /// Dart `TabBarView(key:)`.
3551    pub fn key(mut self, key: KeyRef) -> TabBarView {
3552        self.key = Some(key);
3553        self
3554    }
3555
3556    /// Dart `TabBarView(controller:)`.
3557    pub fn controller(mut self, controller: Ref<TabController>) -> TabBarView {
3558        self.controller = Some(controller);
3559        self
3560    }
3561
3562    /// Dart `TabBarView(physics:)`.
3563    pub fn physics(mut self, physics: ScrollPhysicsRef) -> TabBarView {
3564        self.physics = Some(physics);
3565        self
3566    }
3567
3568    /// Dart `TabBarView(dragStartBehavior:)`.
3569    pub fn drag_start_behavior(mut self, drag_start_behavior: DragStartBehavior) -> TabBarView {
3570        self.drag_start_behavior = drag_start_behavior;
3571        self
3572    }
3573
3574    /// Dart `TabBarView(viewportFraction:)`.
3575    pub fn viewport_fraction(mut self, viewport_fraction: f64) -> TabBarView {
3576        self.viewport_fraction = viewport_fraction;
3577        self
3578    }
3579
3580    /// Dart `TabBarView(clipBehavior:)`.
3581    pub fn clip_behavior(mut self, clip_behavior: Clip) -> TabBarView {
3582        self.clip_behavior = clip_behavior;
3583        self
3584    }
3585}
3586
3587impl fmt::Debug for TabBarView {
3588    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3589        f.debug_struct("TabBarView")
3590            .field("children", &self.children.len())
3591            .field("viewport_fraction", &self.viewport_fraction)
3592            .finish()
3593    }
3594}
3595
3596impl StatefulWidget for TabBarView {
3597    type State = TabBarViewState;
3598
3599    fn key(&self) -> Option<&KeyRef> {
3600        self.key.as_ref()
3601    }
3602
3603    fn create_state(&self) -> TabBarViewState {
3604        TabBarViewState {
3605            state: StateData::new(),
3606            controller: None,
3607            page_controller: None,
3608            children_with_key: Vec::new(),
3609            current_index: None,
3610            warp_underway_count: 0,
3611            scroll_underway_count: 0,
3612            debug_has_scheduled_valid_children_count_check: false,
3613        }
3614    }
3615}
3616
3617/// Dart's `_TabBarViewState`.
3618pub struct TabBarViewState {
3619    state: StateData<TabBarView>,
3620    controller: Option<Ref<TabController>>,
3621    page_controller: Option<Ref<PageController>>,
3622    children_with_key: Vec<WidgetRef>,
3623    current_index: Option<usize>,
3624    warp_underway_count: i32,
3625    scroll_underway_count: i32,
3626    debug_has_scheduled_valid_children_count_check: bool,
3627}
3628
3629impl TabBarViewState {
3630    // If the TabBarView is rebuilt with a new tab controller, the caller should
3631    // dispose the old one. In that case the old controller's animation will be
3632    // null and should not be accessed.
3633    fn controller_is_valid(self: Handle<Self>, app: &App) -> bool {
3634        app.get(self)
3635            .controller
3636            .handle()
3637            .is_some_and(|controller| controller.animation(app).is_some())
3638    }
3639
3640    fn controller(self: Handle<Self>, app: &App) -> Handle<TabController> {
3641        app.get(self)
3642            .controller
3643            .handle()
3644            .expect("a tab bar view has a controller")
3645    }
3646
3647    fn page_controller(self: Handle<Self>, app: &App) -> Handle<PageController> {
3648        app.get(self)
3649            .page_controller
3650            .handle()
3651            .expect("made in did_change_dependencies")
3652    }
3653
3654    fn animation_tick_listener(self: Handle<Self>) -> Listener {
3655        Listener::handle_method(self, Self::handle_tab_controller_animation_tick)
3656    }
3657
3658    fn update_tab_controller(self: Handle<Self>, app: &mut App) {
3659        let context = self.context(app);
3660        let new_controller = match self.widget(app).controller.clone() {
3661            Some(controller) => Some(controller),
3662            None => DefaultTabController::maybe_of(app, context),
3663        };
3664        if cfg!(debug_assertions) && new_controller.is_none() {
3665            panic!(
3666                "No TabController for TabBarView.\n\
3667                 When creating a TabBarView, you must either provide an explicit TabController \
3668                 using the \"controller\" property, or you must ensure that there is a \
3669                 DefaultTabController above the TabBarView.\n\
3670                 In this case, there was neither an explicit controller nor a default \
3671                 controller."
3672            );
3673        }
3674
3675        if new_controller == app.get(self).controller {
3676            return;
3677        }
3678
3679        if self.controller_is_valid(app) {
3680            let animation = self.controller(app).animation(app).expect("checked valid");
3681            animation.remove_listener(app, &self.animation_tick_listener());
3682        }
3683        app.get_mut(self).controller = new_controller.clone();
3684        if let Some(controller) = new_controller {
3685            let animation = controller
3686                .animation(app)
3687                .expect("a new controller is not disposed");
3688            animation.add_listener(app, self.animation_tick_listener());
3689        }
3690    }
3691
3692    fn jump_to_page(self: Handle<Self>, app: &mut App, page: usize) {
3693        app.get_mut(self).warp_underway_count += 1;
3694        self.page_controller(app).jump_to_page(app, page as i32);
3695        app.get_mut(self).warp_underway_count -= 1;
3696    }
3697
3698    fn animate_to_page(
3699        self: Handle<Self>,
3700        app: &mut App,
3701        page: usize,
3702        duration: Duration,
3703        curve: Rc<dyn waft_animation::Curve>,
3704    ) -> Task<()> {
3705        app.get_mut(self).warp_underway_count += 1;
3706        let animated = self
3707            .page_controller(app)
3708            .animate_to_page(app, page as i32, duration, curve);
3709        app.spawn(async move |cx| {
3710            animated.await;
3711            cx.update(|app| {
3712                if app.contains(self) {
3713                    app.get_mut(self).warp_underway_count -= 1;
3714                }
3715            });
3716        })
3717    }
3718
3719    fn update_children(self: Handle<Self>, app: &mut App) {
3720        let children = self
3721            .widget(app)
3722            .children
3723            .iter()
3724            .map(|child| {
3725                Semantics::new()
3726                    .role(SemanticsRole::TabPanel)
3727                    .child(child.clone())
3728                    .into_widget()
3729            })
3730            .collect();
3731        app.get_mut(self).children_with_key =
3732            KeyedSubtree::ensure_unique_keys_for_list(children, 0);
3733    }
3734
3735    fn handle_tab_controller_animation_tick(self: Handle<Self>, app: &mut App) {
3736        let controller = self.controller(app);
3737        if app.get(self).scroll_underway_count > 0 || !controller.index_is_changing(app) {
3738            return;
3739        } // This widget is driving the controller's animation.
3740
3741        if Some(controller.index(app)) != app.get(self).current_index {
3742            app.get_mut(self).current_index = Some(controller.index(app));
3743            drop(self.warp_to_current_index(app));
3744        }
3745    }
3746
3747    fn warp_to_current_index(self: Handle<Self>, app: &mut App) -> Task<()> {
3748        let current_index = app.get(self).current_index.expect("a controller is set");
3749        if !self.mounted(app) || self.page_controller(app).page(app) == Some(current_index as f64) {
3750            return Task::ready(());
3751        }
3752
3753        let controller = self.controller(app);
3754        let adjacent_destination =
3755            (current_index as i64 - controller.previous_index(app) as i64).abs() == 1;
3756        let animation_duration = controller.animation_duration(app);
3757        if adjacent_destination {
3758            self.warp_to_adjacent_tab(app, animation_duration)
3759        } else {
3760            self.warp_to_non_adjacent_tab(app, animation_duration)
3761        }
3762    }
3763
3764    fn warp_to_adjacent_tab(self: Handle<Self>, app: &mut App, duration: Duration) -> Task<()> {
3765        let current_index = app.get(self).current_index.expect("a controller is set");
3766        let animated = if duration == Duration::ZERO {
3767            self.jump_to_page(app, current_index);
3768            Task::ready(())
3769        } else {
3770            self.animate_to_page(app, current_index, duration, Curves::ease())
3771        };
3772        app.spawn(async move |cx| {
3773            animated.await;
3774            cx.update(|app| {
3775                if self.mounted(app) {
3776                    self.update_children(app);
3777                    self.set_state(app, |_state| {});
3778                }
3779            });
3780        })
3781    }
3782
3783    fn warp_to_non_adjacent_tab(self: Handle<Self>, app: &mut App, duration: Duration) -> Task<()> {
3784        let previous_index = self.controller(app).previous_index(app);
3785        let current_index = app.get(self).current_index.expect("a controller is set");
3786        debug_assert!((current_index as i64 - previous_index as i64).abs() > 1);
3787
3788        // initialPage defines which page is shown when starting the animation.
3789        // This page is adjacent to the destination page.
3790        let initial_page = if current_index > previous_index {
3791            current_index - 1
3792        } else {
3793            current_index + 1
3794        };
3795
3796        self.set_state(app, |state| {
3797            // Needed for `RenderSliverMultiBoxAdaptor.move` and kept alive children.
3798            // For motivation, see https://github.com/flutter/flutter/pull/29188 and
3799            // https://github.com/flutter/flutter/issues/27010#issuecomment-486475152.
3800            state.children_with_key.swap(initial_page, previous_index);
3801        });
3802
3803        // Make a first jump to the adjacent page.
3804        self.jump_to_page(app, initial_page);
3805
3806        // Jump or animate to the destination page.
3807        let animated = if duration == Duration::ZERO {
3808            self.jump_to_page(app, current_index);
3809            Task::ready(())
3810        } else {
3811            self.animate_to_page(app, current_index, duration, Curves::ease())
3812        };
3813
3814        app.spawn(async move |cx| {
3815            animated.await;
3816            cx.update(|app| {
3817                if self.mounted(app) {
3818                    self.update_children(app);
3819                    self.set_state(app, |_state| {});
3820                }
3821            });
3822        })
3823    }
3824
3825    fn sync_controller_offset(self: Handle<Self>, app: &mut App) {
3826        let controller = self.controller(app);
3827        let page = self
3828            .page_controller(app)
3829            .page(app)
3830            .expect("a scrolled page view has a page");
3831        let offset = clamp_double(page - controller.index(app) as f64, -1.0, 1.0);
3832        controller.set_offset(app, offset);
3833    }
3834
3835    // Called when the PageView scrolls
3836    fn handle_scroll_notification(
3837        self: Handle<Self>,
3838        app: &mut App,
3839        notification: &dyn ScrollNotification,
3840    ) -> bool {
3841        let this = app.get(self);
3842        if this.warp_underway_count > 0 || this.scroll_underway_count > 0 {
3843            return false;
3844        }
3845
3846        if notification.depth() != 0 {
3847            return false;
3848        }
3849
3850        if !self.controller_is_valid(app) {
3851            return false;
3852        }
3853
3854        app.get_mut(self).scroll_underway_count += 1;
3855        let page = self
3856            .page_controller(app)
3857            .page(app)
3858            .expect("a scrolled page view has a page");
3859        let controller = self.controller(app);
3860        if notification.as_any().is::<ScrollUpdateNotification>()
3861            && !controller.index_is_changing(app)
3862        {
3863            let page_changed = (page - controller.index(app) as f64).abs() > 1.0;
3864            if page_changed {
3865                controller.set_index(app, page.round() as usize);
3866                app.get_mut(self).current_index = Some(controller.index(app));
3867            }
3868            self.sync_controller_offset(app);
3869        } else if notification.as_any().is::<ScrollEndNotification>() {
3870            controller.set_index(app, page.round() as usize);
3871            app.get_mut(self).current_index = Some(controller.index(app));
3872            if !controller.index_is_changing(app) {
3873                self.sync_controller_offset(app);
3874            }
3875        }
3876        app.get_mut(self).scroll_underway_count -= 1;
3877
3878        false
3879    }
3880
3881    fn debug_schedule_check_has_valid_children_count(self: Handle<Self>, app: &mut App) -> bool {
3882        if app.get(self).debug_has_scheduled_valid_children_count_check {
3883            return true;
3884        }
3885        SchedulerBinding::add_post_frame_callback(
3886            app,
3887            FrameCallback::new(move |app, _duration| {
3888                if !app.contains(self) {
3889                    return;
3890                }
3891                app.get_mut(self)
3892                    .debug_has_scheduled_valid_children_count_check = false;
3893                if !self.mounted(app) {
3894                    return;
3895                }
3896                let length = self.controller(app).length(app);
3897                let child_count = self.widget(app).children.len();
3898                if cfg!(debug_assertions) && length != child_count {
3899                    panic!(
3900                        "Controller's length property ({length}) does not match the number of \
3901                         children ({child_count}) present in TabBarView's children property."
3902                    );
3903                }
3904            }),
3905            None,
3906        );
3907        app.get_mut(self)
3908            .debug_has_scheduled_valid_children_count_check = true;
3909        true
3910    }
3911}
3912
3913impl State for TabBarViewState {
3914    type Widget = TabBarView;
3915    waft_widgets::state_accessors!();
3916
3917    fn init_state(self: Handle<Self>, app: &mut App) {
3918        self.update_children(app);
3919    }
3920
3921    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
3922        self.update_tab_controller(app);
3923        let current_index = self.controller(app).index(app);
3924        app.get_mut(self).current_index = Some(current_index);
3925        match app.get(self).page_controller.handle() {
3926            None => {
3927                let viewport_fraction = self.widget(app).viewport_fraction;
3928                let page_controller = PageController::new(
3929                    app,
3930                    current_index as i32,
3931                    true,
3932                    viewport_fraction,
3933                    None,
3934                    None,
3935                );
3936                app.get_mut(self).page_controller = Some(page_controller);
3937            }
3938            Some(page_controller) => page_controller.jump_to_page(app, current_index as i32),
3939        }
3940    }
3941
3942    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &TabBarView) {
3943        if self.widget(app).controller != old_widget.controller {
3944            self.update_tab_controller(app);
3945            let current_index = self.controller(app).index(app);
3946            app.get_mut(self).current_index = Some(current_index);
3947            self.jump_to_page(app, current_index);
3948        }
3949        let viewport_fraction = self.widget(app).viewport_fraction;
3950        if viewport_fraction != old_widget.viewport_fraction {
3951            if let Some(page_controller) = app.get_mut(self).page_controller.take() {
3952                page_controller.dispose(app);
3953            }
3954            let current_index = app.get(self).current_index.expect("a controller is set");
3955            let page_controller = PageController::new(
3956                app,
3957                current_index as i32,
3958                true,
3959                viewport_fraction,
3960                None,
3961                None,
3962            );
3963            app.get_mut(self).page_controller = Some(page_controller);
3964        }
3965        // While a warp is under way, we stop updating the tab page contents.
3966        // This is tracked in https://github.com/flutter/flutter/issues/31269.
3967        let widget = self.widget(app);
3968        // Dart compares the two lists by identity; a rebuilt list of the same widgets is the
3969        // same list here.
3970        let children_changed = widget.children.len() != old_widget.children.len()
3971            || widget
3972                .children
3973                .iter()
3974                .zip(&old_widget.children)
3975                .any(|(child, old_child)| !Rc::ptr_eq(child, old_child));
3976        if children_changed && app.get(self).warp_underway_count == 0 {
3977            self.update_children(app);
3978        }
3979    }
3980
3981    fn dispose(self: Handle<Self>, app: &mut App) {
3982        if self.controller_is_valid(app) {
3983            let animation = self.controller(app).animation(app).expect("checked valid");
3984            animation.remove_listener(app, &self.animation_tick_listener());
3985        }
3986        app.get_mut(self).controller = None;
3987        if let Some(page_controller) = app.get(self).page_controller.handle() {
3988            page_controller.dispose(app);
3989        }
3990        // We don't own the _controller Animation, so it's not disposed here.
3991    }
3992
3993    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
3994        debug_assert!(self.debug_schedule_check_has_valid_children_count(app));
3995
3996        let widget = self.widget(app);
3997        let physics = match widget.physics.clone() {
3998            None => PageScrollPhysics::new().apply_to(Some(Rc::new(ClampingScrollPhysics::new()))),
3999            Some(physics) => PageScrollPhysics::new().apply_to(Some(physics)),
4000        };
4001        let page_view = PageView::new()
4002            .drag_start_behavior(widget.drag_start_behavior)
4003            .clip_behavior(widget.clip_behavior)
4004            .controller(
4005                app.get(self)
4006                    .page_controller
4007                    .clone()
4008                    .expect("made in did_change_dependencies"),
4009            )
4010            .physics(physics)
4011            .children(app.get(self).children_with_key.clone());
4012        NotificationListener::<dyn ScrollNotification>::new(page_view)
4013            .on_notification(
4014                move |app: &mut App, notification: &dyn ScrollNotification| {
4015                    self.handle_scroll_notification(app, notification)
4016                },
4017            )
4018            .into_widget()
4019    }
4020}
4021
4022/// Displays a single circle with the specified size, border style, border color
4023/// and background colors.
4024///
4025/// Used by [`TabPageSelector`] to indicate the selected page.
4026#[derive(Debug)]
4027pub struct TabPageSelectorIndicator {
4028    pub key: Option<KeyRef>,
4029
4030    /// The indicator circle's background color.
4031    pub background_color: Color,
4032
4033    /// The indicator circle's border color.
4034    pub border_color: Color,
4035
4036    /// The indicator circle's diameter.
4037    pub size: f64,
4038
4039    /// The indicator circle's border style.
4040    ///
4041    /// Defaults to [`BorderStyle::Solid`] if value is not specified.
4042    pub border_style: BorderStyle,
4043}
4044
4045impl TabPageSelectorIndicator {
4046    /// Creates an indicator used by [`TabPageSelector`].
4047    pub fn new(
4048        background_color: Color,
4049        border_color: Color,
4050        size: f64,
4051    ) -> TabPageSelectorIndicator {
4052        TabPageSelectorIndicator {
4053            key: None,
4054            background_color,
4055            border_color,
4056            size,
4057            border_style: BorderStyle::Solid,
4058        }
4059    }
4060
4061    /// Dart `TabPageSelectorIndicator(key:)`.
4062    pub fn key(mut self, key: KeyRef) -> TabPageSelectorIndicator {
4063        self.key = Some(key);
4064        self
4065    }
4066
4067    /// Dart `TabPageSelectorIndicator(borderStyle:)`.
4068    pub fn border_style(mut self, border_style: BorderStyle) -> TabPageSelectorIndicator {
4069        self.border_style = border_style;
4070        self
4071    }
4072}
4073
4074impl StatelessWidget for TabPageSelectorIndicator {
4075    fn key(&self) -> Option<&KeyRef> {
4076        self.key.as_ref()
4077    }
4078
4079    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
4080        Container::new()
4081            .width(self.size)
4082            .height(self.size)
4083            .margin(EdgeInsetsGeometry::all(4.0))
4084            .decoration(
4085                BoxDecoration::new()
4086                    .color(self.background_color)
4087                    .border(waft_painting::Border::all(
4088                        self.border_color,
4089                        1.0,
4090                        self.border_style,
4091                        waft_painting::BorderSide::STROKE_ALIGN_INSIDE,
4092                    ))
4093                    .shape(BoxShape::Circle),
4094            )
4095            .into_widget()
4096    }
4097}
4098
4099/// Uses [`TabPageSelectorIndicator`] to display a row of small circular
4100/// indicators, one per tab.
4101///
4102/// The selected tab's indicator is highlighted. Often used in conjunction with
4103/// a [`TabBarView`].
4104///
4105/// If a [`TabController`] is not provided, then there must be a
4106/// [`DefaultTabController`] ancestor.
4107#[derive(Debug)]
4108pub struct TabPageSelector {
4109    pub key: Option<KeyRef>,
4110
4111    /// This widget's selection and animation state.
4112    ///
4113    /// If [`TabController`] is not provided, then the value of
4114    /// [`DefaultTabController::of`] will be used.
4115    pub controller: Option<Ref<TabController>>,
4116
4117    /// The indicator circle's diameter (the default value is 12.0).
4118    pub indicator_size: f64,
4119
4120    /// The indicator circle's fill color for unselected pages.
4121    ///
4122    /// If this parameter is null, then the indicator is filled with `Colors::TRANSPARENT`.
4123    pub color: Option<Color>,
4124
4125    /// The indicator circle's fill color for selected pages and border color
4126    /// for all indicator circles.
4127    ///
4128    /// If this parameter is null, then the indicator is filled with the theme's
4129    /// `ColorScheme::secondary`.
4130    pub selected_color: Option<Color>,
4131
4132    /// The indicator circle's border style.
4133    ///
4134    /// Defaults to [`BorderStyle::Solid`] if value is not specified.
4135    pub border_style: Option<BorderStyle>,
4136}
4137
4138impl Default for TabPageSelector {
4139    fn default() -> TabPageSelector {
4140        TabPageSelector {
4141            key: None,
4142            controller: None,
4143            indicator_size: 12.0,
4144            color: None,
4145            selected_color: None,
4146            border_style: None,
4147        }
4148    }
4149}
4150
4151impl TabPageSelector {
4152    /// Creates a compact widget that indicates which tab has been selected; Dart's named
4153    /// arguments are the setters.
4154    pub fn new() -> TabPageSelector {
4155        TabPageSelector::default()
4156    }
4157
4158    /// Dart `TabPageSelector(key:)`.
4159    pub fn key(mut self, key: KeyRef) -> TabPageSelector {
4160        self.key = Some(key);
4161        self
4162    }
4163
4164    /// Dart `TabPageSelector(controller:)`.
4165    pub fn controller(mut self, controller: Ref<TabController>) -> TabPageSelector {
4166        self.controller = Some(controller);
4167        self
4168    }
4169
4170    /// Dart `TabPageSelector(indicatorSize:)`.
4171    pub fn indicator_size(mut self, indicator_size: f64) -> TabPageSelector {
4172        debug_assert!(indicator_size > 0.0);
4173        self.indicator_size = indicator_size;
4174        self
4175    }
4176
4177    /// Dart `TabPageSelector(color:)`.
4178    pub fn color(mut self, color: Color) -> TabPageSelector {
4179        self.color = Some(color);
4180        self
4181    }
4182
4183    /// Dart `TabPageSelector(selectedColor:)`.
4184    pub fn selected_color(mut self, selected_color: Color) -> TabPageSelector {
4185        self.selected_color = Some(selected_color);
4186        self
4187    }
4188
4189    /// Dart `TabPageSelector(borderStyle:)`.
4190    pub fn border_style(mut self, border_style: BorderStyle) -> TabPageSelector {
4191        self.border_style = Some(border_style);
4192        self
4193    }
4194}
4195
4196impl StatefulWidget for TabPageSelector {
4197    type State = TabPageSelectorState;
4198
4199    fn key(&self) -> Option<&KeyRef> {
4200        self.key.as_ref()
4201    }
4202
4203    fn create_state(&self) -> TabPageSelectorState {
4204        TabPageSelectorState {
4205            state: StateData::new(),
4206            previous_tab_controller: None,
4207            animation: None,
4208        }
4209    }
4210}
4211
4212/// Dart's `_TabPageSelectorState`.
4213pub struct TabPageSelectorState {
4214    state: StateData<TabPageSelector>,
4215    previous_tab_controller: Option<Ref<TabController>>,
4216    animation: Option<Ref<CurvedAnimation>>,
4217}
4218
4219impl TabPageSelectorState {
4220    fn tab_controller(self: Handle<Self>, app: &mut App) -> Ref<TabController> {
4221        let context = self.context(app);
4222        let tab_controller = match self.widget(app).controller.clone() {
4223            Some(controller) => Some(controller),
4224            None => DefaultTabController::maybe_of(app, context),
4225        };
4226        if cfg!(debug_assertions) && tab_controller.is_none() {
4227            panic!(
4228                "No TabController for TabPageSelectorState.\n\
4229                 When creating a TabPageSelectorState, you must either provide an explicit \
4230                 TabController using the \"controller\" property, or you must ensure that there \
4231                 is a DefaultTabController above the TabPageSelectorState.\n\
4232                 In this case, there was neither an explicit controller nor a default \
4233                 controller."
4234            );
4235        }
4236        tab_controller.expect("asserted above")
4237    }
4238
4239    fn set_animation(self: Handle<Self>, app: &mut App) {
4240        if let Some(animation) = app.get_mut(self).animation.take() {
4241            animation.dispose(app);
4242        }
4243        let parent = self
4244            .tab_controller(app)
4245            .animation(app)
4246            .expect("a selector's controller is valid")
4247            .keep(app);
4248        let animation = CurvedAnimation::new(app, parent, Curves::fast_out_slow_in(), None);
4249        app.get_mut(self).animation = Some(animation);
4250    }
4251
4252    fn build_tab_indicator(
4253        self: Handle<Self>,
4254        app: &App,
4255        tab_index: usize,
4256        tab_controller: Handle<TabController>,
4257        selected_color_tween: &Ref<ColorTween>,
4258        previous_color_tween: &Ref<ColorTween>,
4259    ) -> WidgetRef {
4260        let background = if tab_controller.index_is_changing(app) {
4261            // The selection's animation is animating from previousValue to value.
4262            let t = 1.0 - index_change_progress(app, tab_controller);
4263            if tab_controller.index(app) == tab_index {
4264                selected_color_tween.lerp(app, t)
4265            } else if tab_controller.previous_index(app) == tab_index {
4266                previous_color_tween.lerp(app, t)
4267            } else {
4268                selected_color_tween.begin(app)
4269            }
4270        } else {
4271            // The selection's offset reflects how far the TabBarView has / been dragged
4272            // to the previous page (-1.0 to 0.0) or the next page (0.0 to 1.0).
4273            let offset = tab_controller.offset(app);
4274            let index = tab_controller.index(app);
4275            if index == tab_index {
4276                selected_color_tween.lerp(app, 1.0 - offset.abs())
4277            } else if index + 1 == tab_index && offset > 0.0 {
4278                selected_color_tween.lerp(app, offset)
4279            } else if index == tab_index + 1 && offset < 0.0 {
4280                selected_color_tween.lerp(app, -offset)
4281            } else {
4282                selected_color_tween.begin(app)
4283            }
4284        }
4285        .expect("two colors lerp to a color");
4286        let widget = self.widget(app);
4287        TabPageSelectorIndicator::new(
4288            background,
4289            selected_color_tween
4290                .end(app)
4291                .expect("the selected color tween has an end"),
4292            widget.indicator_size,
4293        )
4294        .border_style(widget.border_style.unwrap_or(BorderStyle::Solid))
4295        .into_widget()
4296    }
4297}
4298
4299impl State for TabPageSelectorState {
4300    type Widget = TabPageSelector;
4301    waft_widgets::state_accessors!();
4302
4303    fn did_update_widget(self: Handle<Self>, app: &mut App, _old_widget: &TabPageSelector) {
4304        let tab_controller = self.tab_controller(app);
4305        let previous_animation = app
4306            .get(self)
4307            .previous_tab_controller
4308            .handle()
4309            .and_then(|controller| controller.animation(app));
4310        if previous_animation != tab_controller.animation(app) {
4311            self.set_animation(app);
4312        }
4313        if app.get(self).previous_tab_controller.as_ref() != Some(&tab_controller) {
4314            app.get_mut(self).previous_tab_controller = Some(tab_controller);
4315        }
4316    }
4317
4318    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
4319        let tab_controller = self.tab_controller(app);
4320        let previous_animation = app
4321            .get(self)
4322            .previous_tab_controller
4323            .handle()
4324            .and_then(|controller| controller.animation(app));
4325        if app.get(self).animation.is_none() || previous_animation != tab_controller.animation(app)
4326        {
4327            self.set_animation(app);
4328        }
4329        if app.get(self).previous_tab_controller.as_ref() != Some(&tab_controller) {
4330            app.get_mut(self).previous_tab_controller = Some(tab_controller);
4331        }
4332    }
4333
4334    fn dispose(self: Handle<Self>, app: &mut App) {
4335        if let Some(animation) = app.get_mut(self).animation.take() {
4336            animation.dispose(app);
4337        }
4338    }
4339
4340    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
4341        let widget = self.widget(app);
4342        let (color, selected_color) = (widget.color, widget.selected_color);
4343        let fix_color = color.unwrap_or(Colors::TRANSPARENT);
4344        let fix_selected_color =
4345            selected_color.unwrap_or_else(|| Theme::of(app, context).color_scheme.secondary());
4346        let selected_color_tween = ColorTween::new(app, Some(fix_color), Some(fix_selected_color));
4347        let previous_color_tween = ColorTween::new(app, Some(fix_selected_color), Some(fix_color));
4348        let localizations = <dyn MaterialLocalizations>::of(app, context);
4349        let animation: AnimationRef<f64> = app
4350            .get(self)
4351            .animation
4352            .as_ref()
4353            .expect("made in did_change_dependencies")
4354            .erase();
4355        AnimatedBuilder::new(Rc::new(animation), move |app, _context, _child| {
4356            let tab_controller = self.tab_controller(app);
4357            let length = tab_controller.length(app);
4358            Semantics::new()
4359                .label(localizations.tab_label(tab_controller.index(app) as i32 + 1, length as i32))
4360                .child(
4361                    Row::new().main_axis_size(MainAxisSize::Min).children(
4362                        (0..length)
4363                            .map(|tab_index| {
4364                                self.build_tab_indicator(
4365                                    app,
4366                                    tab_index,
4367                                    tab_controller.handle(),
4368                                    &selected_color_tween,
4369                                    &previous_color_tween,
4370                                )
4371                            })
4372                            .collect::<Vec<_>>(),
4373                    ),
4374                )
4375                .into_widget()
4376        })
4377        .into_widget()
4378    }
4379}
4380
4381/// Dart's `_TabsDefaultsM2`: hand coded defaults based on Material Design 2.
4382pub(crate) struct TabsDefaultsM2 {
4383    /// Dart's `super(..)` arguments.
4384    tab_bar_theme_data: TabBarThemeData,
4385    context: DefaultsContext,
4386    is_scrollable: bool,
4387}
4388
4389impl TabsDefaultsM2 {
4390    pub(crate) fn new(context: BuildContext, is_scrollable: bool) -> TabsDefaultsM2 {
4391        TabsDefaultsM2 {
4392            tab_bar_theme_data: TabBarThemeData::new().indicator_size(TabBarIndicatorSize::Tab),
4393            context: DefaultsContext::new(context),
4394            is_scrollable,
4395        }
4396    }
4397
4398    pub(crate) const ICON_MARGIN: EdgeInsetsGeometry =
4399        EdgeInsetsGeometry::only(0.0, 0.0, 0.0, 10.0);
4400}
4401
4402impl TabBarThemeDataGetters for TabsDefaultsM2 {
4403    fn tab_bar_theme_data(&self) -> &TabBarThemeData {
4404        &self.tab_bar_theme_data
4405    }
4406
4407    fn indicator_color(&self, app: &mut App) -> Option<Color> {
4408        let theme = self.context.theme(app);
4409        let colors = &theme.color_scheme;
4410        let is_dark = Theme::brightness_of(app, self.context.context()) == Brightness::Dark;
4411        let primary_color = if is_dark {
4412            Colors::GREY.shade900()
4413        } else {
4414            Colors::BLUE.primary()
4415        };
4416        Some(if colors.secondary() == primary_color {
4417            Colors::WHITE
4418        } else {
4419            colors.secondary()
4420        })
4421    }
4422
4423    fn label_color(&self, app: &mut App) -> Option<AnyColor> {
4424        let theme = self.context.theme(app);
4425        let body_large = theme.primary_text_theme.body_large.clone();
4426        Some(
4427            body_large
4428                .as_ref()
4429                .and_then(|style| style.color.clone())
4430                .expect("the primary text theme's body large has a color"),
4431        )
4432    }
4433
4434    fn splash_factory(&self, app: &mut App) -> Option<InteractiveInkFeatureFactoryRef> {
4435        let theme = self.context.theme(app);
4436        Some(theme.splash_factory.clone())
4437    }
4438
4439    fn tab_alignment(&self, _app: &mut App) -> Option<TabAlignment> {
4440        Some(if self.is_scrollable {
4441            TabAlignment::Start
4442        } else {
4443            TabAlignment::Fill
4444        })
4445    }
4446
4447    fn label_style(&self, app: &mut App) -> Option<TextStyle> {
4448        self.context
4449            .theme(app)
4450            .primary_text_theme
4451            .body_large
4452            .clone()
4453    }
4454
4455    fn unselected_label_style(&self, app: &mut App) -> Option<TextStyle> {
4456        self.context
4457            .theme(app)
4458            .primary_text_theme
4459            .body_large
4460            .clone()
4461    }
4462}
4463
4464#[cfg(test)]
4465pub(crate) mod tests {
4466    //! Ported from `test/tabs_test.dart` (with `tabs_utils.dart`'s helpers). The semantics,
4467    //! golden and leak-tracking cases are not ported.
4468
4469    use waft_embedder::{Locale, TargetPlatform};
4470    use waft_rendering::testing::RecordedCall;
4471    use waft_widgets::{AnyElement, DefaultWidgetsLocalizations, Localizations, RichText};
4472
4473    use waft_widgets::testing::{
4474        TestPointer, WidgetTester, expect, find, finds_n_widgets, finds_nothing, finds_one_widget,
4475        test_widgets,
4476    };
4477
4478    use super::*;
4479    use crate::app_bar::AppBar;
4480    use crate::material_localizations::DefaultMaterialLocalizations;
4481    use crate::scaffold::Scaffold;
4482    use crate::test_support::{PaintInspection, material_app};
4483    use crate::theme_data::ThemeData;
4484    use waft_widgets::ScrollControllerLeaf;
4485
4486    /// The theme Dart's `ThemeData(useMaterial3: use_material3, tabBarTheme: tab_bar_theme)`
4487    /// builds.
4488    pub(crate) fn theme(
4489        tester: &WidgetTester,
4490        use_material3: Option<bool>,
4491        tab_bar_theme: Option<TabBarThemeData>,
4492    ) -> ThemeData {
4493        let app = tester.cell.borrow();
4494        let mut builder = ThemeData::builder();
4495        if let Some(use_material3) = use_material3 {
4496            builder = builder.use_material3(use_material3);
4497        }
4498        if let Some(tab_bar_theme) = tab_bar_theme {
4499            builder = builder.tab_bar_theme(tab_bar_theme);
4500        }
4501        builder.build(&app)
4502    }
4503
4504    /// Dart's `boilerplate(child:, textDirection:, theme:)`: the theme, en-US localizations, a
4505    /// `Directionality` and a `Material`.
4506    pub(crate) fn boilerplate<K>(
4507        theme: ThemeData,
4508        text_direction: TextDirection,
4509        child: impl IntoWidget<K>,
4510    ) -> WidgetRef {
4511        Theme::new(
4512            theme,
4513            Localizations::new(
4514                Locale::new("en").country_code("US"),
4515                vec![
4516                    DefaultMaterialLocalizations::delegate(),
4517                    DefaultWidgetsLocalizations::delegate(),
4518                ],
4519            )
4520            .child(Directionality::new(
4521                text_direction,
4522                Material::new().child(child),
4523            )),
4524        )
4525        .into_widget()
4526    }
4527
4528    /// Dart's `buildFrame` arguments.
4529    pub(crate) struct Frame {
4530        pub(crate) tab_bar_key: Option<GlobalKey>,
4531        pub(crate) secondary_tab_bar: bool,
4532        pub(crate) tabs: Vec<&'static str>,
4533        pub(crate) value: &'static str,
4534        pub(crate) is_scrollable: bool,
4535        pub(crate) indicator_color: Option<Color>,
4536        pub(crate) animation_duration: Option<Duration>,
4537        pub(crate) padding: Option<EdgeInsetsGeometry>,
4538        pub(crate) text_direction: TextDirection,
4539        pub(crate) tab_alignment: Option<TabAlignment>,
4540        pub(crate) tab_bar_theme: Option<TabBarThemeData>,
4541        pub(crate) indicator: Option<DecorationRef>,
4542        pub(crate) use_material3: Option<bool>,
4543    }
4544
4545    impl Frame {
4546        pub(crate) fn new(tabs: Vec<&'static str>, value: &'static str) -> Frame {
4547            Frame {
4548                tab_bar_key: None,
4549                secondary_tab_bar: false,
4550                tabs,
4551                value,
4552                is_scrollable: false,
4553                indicator_color: None,
4554                animation_duration: None,
4555                padding: None,
4556                text_direction: TextDirection::Ltr,
4557                tab_alignment: None,
4558                tab_bar_theme: None,
4559                indicator: None,
4560                use_material3: None,
4561            }
4562        }
4563
4564        /// Dart's `buildFrame(..)`.
4565        pub(crate) fn build(self, tester: &WidgetTester) -> WidgetRef {
4566            let theme = theme(tester, self.use_material3, self.tab_bar_theme);
4567            let tabs = self
4568                .tabs
4569                .iter()
4570                .map(|tab| Tab::new().text(*tab).into_widget())
4571                .collect::<Vec<_>>();
4572            let mut tab_bar = if self.secondary_tab_bar {
4573                TabBar::secondary(tabs)
4574            } else {
4575                TabBar::new(tabs)
4576            }
4577            .is_scrollable(self.is_scrollable);
4578            if let Some(key) = self.tab_bar_key {
4579                tab_bar = tab_bar.key(key.into());
4580            }
4581            if let Some(indicator_color) = self.indicator_color {
4582                tab_bar = tab_bar.indicator_color(indicator_color);
4583            }
4584            if let Some(padding) = self.padding {
4585                tab_bar = tab_bar.padding(padding);
4586            }
4587            if let Some(tab_alignment) = self.tab_alignment {
4588                tab_bar = tab_bar.tab_alignment(tab_alignment);
4589            }
4590            if !self.secondary_tab_bar {
4591                tab_bar.indicator = self.indicator;
4592            }
4593            let initial_index = self
4594                .tabs
4595                .iter()
4596                .position(|tab| *tab == self.value)
4597                .expect("the value is one of the tabs");
4598            let mut controller =
4599                DefaultTabController::new(self.tabs.len(), tab_bar).initial_index(initial_index);
4600            if let Some(animation_duration) = self.animation_duration {
4601                controller = controller.animation_duration(animation_duration);
4602            }
4603            boilerplate(theme, self.text_direction, controller)
4604        }
4605    }
4606
4607    /// Dart's `buildLeftRightApp`.
4608    pub(crate) fn build_left_right_app(
4609        tester: &WidgetTester,
4610        tabs: Vec<&'static str>,
4611        value: &'static str,
4612        automatic_indicator_color_adjustment: bool,
4613        theme_data: Option<ThemeData>,
4614    ) -> WidgetRef {
4615        let theme_data = theme_data.unwrap_or_else(|| {
4616            let app = tester.cell.borrow();
4617            ThemeData::builder()
4618                .platform(TargetPlatform::Android)
4619                .build(&app)
4620        });
4621        let initial_index = tabs.iter().position(|tab| *tab == value).expect("a tab");
4622        let tab_widgets = tabs
4623            .iter()
4624            .map(|tab| Tab::new().text(*tab).into_widget())
4625            .collect::<Vec<_>>();
4626        material_app(
4627            theme_data,
4628            DefaultTabController::new(
4629                tabs.len(),
4630                Scaffold::new()
4631                    .app_bar(waft_widgets::PreferredSizeWidgetRef::new(
4632                        AppBar::new().title(Text::new("tabs")).bottom(
4633                            waft_widgets::PreferredSizeWidgetRef::new(
4634                                TabBar::new(tab_widgets).automatic_indicator_color_adjustment(
4635                                    automatic_indicator_color_adjustment,
4636                                ),
4637                            ),
4638                        ),
4639                    ))
4640                    .body(TabBarView::new([
4641                        Center::new().child(Text::new("LEFT CHILD")).into_widget(),
4642                        Center::new().child(Text::new("RIGHT CHILD")).into_widget(),
4643                    ])),
4644            )
4645            .initial_index(initial_index)
4646            .into_widget(),
4647        )
4648    }
4649
4650    /// The `TabController` the `DefaultTabController` above `element` provides: Dart's
4651    /// `DefaultTabController.of(tester.element(finder))`.
4652    pub(crate) fn default_controller_of(
4653        tester: &WidgetTester,
4654        element: AnyElement,
4655    ) -> Ref<TabController> {
4656        let mut app = tester.cell.borrow_mut();
4657        DefaultTabController::of(&mut app, element)
4658    }
4659
4660    /// The first element showing `text`: Dart's `find.text(text)`.
4661    pub(crate) fn text(tester: &WidgetTester, text: &str) -> AnyElement {
4662        *find::text(text)
4663            .evaluate(tester)
4664            .first()
4665            .unwrap_or_else(|| panic!("a Text showing {text:?}"))
4666    }
4667
4668    /// Dart's `tester.tap(finder)`.
4669    pub(crate) fn tap(tester: &mut WidgetTester, element: AnyElement) {
4670        let center = tester.get_center(element);
4671        tester.tap_at(center, 1);
4672    }
4673
4674    /// The only element whose widget is a `W`: Dart's `find.byType(W)` with `findsOneWidget`.
4675    pub(crate) fn only<W: 'static>(tester: &WidgetTester) -> AnyElement {
4676        let found = find::by_type::<W>().evaluate(tester);
4677        assert_eq!(found.len(), 1, "one {}", std::any::type_name::<W>());
4678        found[0]
4679    }
4680
4681    #[test]
4682    fn a_tab_with_an_icon_is_as_wide_as_the_icon_and_46_high() {
4683        test_widgets(|tester| {
4684            let theme = theme(tester, None, None);
4685            tester.pump_widget(material_app(
4686                theme,
4687                Center::new()
4688                    .child(
4689                        Material::new()
4690                            .child(Tab::new().icon(SizedBox::new().width(10.0).height(10.0))),
4691                    )
4692                    .into_widget(),
4693            ));
4694            assert_eq!(tester.get_size(only::<Tab>(tester)), Size::new(10.0, 46.0));
4695        });
4696    }
4697
4698    #[test]
4699    fn a_tab_with_a_child_is_as_wide_as_the_child_and_46_high() {
4700        test_widgets(|tester| {
4701            let theme = theme(tester, None, None);
4702            tester.pump_widget(material_app(
4703                theme,
4704                Center::new()
4705                    .child(
4706                        Material::new()
4707                            .child(Tab::new().child(SizedBox::new().width(10.0).height(10.0))),
4708                    )
4709                    .into_widget(),
4710            ));
4711            assert_eq!(tester.get_size(only::<Tab>(tester)), Size::new(10.0, 46.0));
4712        });
4713    }
4714
4715    #[test]
4716    fn a_tab_with_text_is_as_wide_as_the_text_and_46_high() {
4717        test_widgets(|tester| {
4718            let theme = {
4719                let app = tester.cell.borrow();
4720                ThemeData::builder().font_family("FlutterTest").build(&app)
4721            };
4722            let material3 = theme.use_material3;
4723            tester.pump_widget(material_app(
4724                theme,
4725                Center::new()
4726                    .child(Material::new().child(Tab::new().text("x")))
4727                    .into_widget(),
4728            ));
4729            let paragraph = only::<RichText>(tester);
4730            let render = tester.render_box_of(paragraph);
4731            {
4732                let app = tester.cell.borrow();
4733                let paragraph = render
4734                    .as_object()
4735                    .downcast::<waft_rendering::RenderParagraph>(&app)
4736                    .expect("a paragraph");
4737                assert_eq!(
4738                    paragraph
4739                        .text(&app)
4740                        .style()
4741                        .and_then(|style| style.font_family.clone())
4742                        .as_deref(),
4743                    Some("FlutterTest")
4744                );
4745            }
4746            let expected = if material3 {
4747                Size::new(14.25, 46.0)
4748            } else {
4749                Size::new(14.0, 46.0)
4750            };
4751            assert_eq!(tester.get_size(only::<Tab>(tester)), expected);
4752        });
4753    }
4754
4755    // 'TabBar tap selects tab'.
4756    #[test]
4757    fn tapping_a_tab_selects_it() {
4758        test_widgets(|tester| {
4759            let tabs = vec!["A", "B", "C"];
4760
4761            let frame = Frame::new(tabs.clone(), "C").build(tester);
4762            tester.pump_widget(frame);
4763            expect(tester, &find::text("A"), finds_one_widget());
4764            expect(tester, &find::text("B"), finds_one_widget());
4765            expect(tester, &find::text("C"), finds_one_widget());
4766            let controller = default_controller_of(tester, text(tester, "A"));
4767            {
4768                let app = tester.cell.borrow();
4769                assert_eq!(controller.index(&app), 2);
4770                assert_eq!(controller.previous_index(&app), 2);
4771            }
4772
4773            let frame = Frame::new(tabs.clone(), "C").build(tester);
4774            tester.pump_widget(frame);
4775            let b = text(tester, "B");
4776            tap(tester, b);
4777            tester.pump();
4778            {
4779                let app = tester.cell.borrow();
4780                assert!(controller.index_is_changing(&app));
4781            }
4782            tester.pump_by(Duration::from_secs(1)); // finish the animation
4783            {
4784                let app = tester.cell.borrow();
4785                assert_eq!(controller.index(&app), 1);
4786                assert_eq!(controller.previous_index(&app), 2);
4787                assert!(!controller.index_is_changing(&app));
4788            }
4789
4790            let frame = Frame::new(tabs.clone(), "C").build(tester);
4791            tester.pump_widget(frame);
4792            let c = text(tester, "C");
4793            tap(tester, c);
4794            tester.pump();
4795            tester.pump_by(Duration::from_secs(1));
4796            {
4797                let app = tester.cell.borrow();
4798                assert_eq!(controller.index(&app), 2);
4799                assert_eq!(controller.previous_index(&app), 1);
4800            }
4801
4802            let frame = Frame::new(tabs.clone(), "C").build(tester);
4803            tester.pump_widget(frame);
4804            let a = text(tester, "A");
4805            tap(tester, a);
4806            tester.pump();
4807            tester.pump_by(Duration::from_secs(1));
4808            {
4809                let app = tester.cell.borrow();
4810                assert_eq!(controller.index(&app), 0);
4811                assert_eq!(controller.previous_index(&app), 2);
4812            }
4813        });
4814    }
4815
4816    /// One stroked two-point path `render` or its subtree paints: Dart's `paints..line`.
4817    #[derive(Clone, Copy, Debug)]
4818    pub(crate) struct PaintedLine {
4819        pub(crate) color: Color,
4820        pub(crate) stroke_width: f64,
4821        pub(crate) p1: Offset,
4822        pub(crate) p2: Offset,
4823    }
4824
4825    pub(crate) fn painted_lines(
4826        tester: &WidgetTester,
4827        render: AnyRenderObject,
4828    ) -> Vec<PaintedLine> {
4829        lines_of(&tester.painted_ops(render))
4830    }
4831
4832    /// The lines among `ops`, as `paints..line` reads them.
4833    pub(crate) fn lines_of(ops: &[waft_embedder::valo::Op]) -> Vec<PaintedLine> {
4834        ops.iter()
4835            .filter_map(|op| match RecordedCall::of(op) {
4836                RecordedCall::Line {
4837                    p1,
4838                    p2,
4839                    color,
4840                    stroke_width,
4841                } => Some(PaintedLine {
4842                    color,
4843                    stroke_width: stroke_width.expect("a stroked line"),
4844                    p1,
4845                    p2,
4846                }),
4847                _ => None,
4848            })
4849            .collect()
4850    }
4851
4852    pub(crate) fn argb32(color: waft_embedder::valo::Color) -> u32 {
4853        let channel = |value: f32| (value * 255.0).round() as u32;
4854        (channel(color.a) << 24)
4855            | (channel(color.r) << 16)
4856            | (channel(color.g) << 8)
4857            | channel(color.b)
4858    }
4859
4860    /// Whether `a` and `b` are within `epsilon` of each other: Dart's `moreOrLessEquals`.
4861    pub(crate) fn close(a: f64, b: f64, epsilon: f64) -> bool {
4862        (a - b).abs() <= epsilon
4863    }
4864
4865    /// Whether `line` is `color`, `stroke_width` wide, from exactly `p1` to `p2`, as Dart's
4866    /// `paints..line` asks.
4867    pub(crate) fn is_line(
4868        line: &PaintedLine,
4869        color: Color,
4870        stroke_width: Option<f64>,
4871        p1: Offset,
4872        p2: Offset,
4873    ) -> bool {
4874        line.color.to_argb32() == color.to_argb32()
4875            && stroke_width.is_none_or(|width| line.stroke_width == width)
4876            && line.p1 == p1
4877            && line.p2 == p2
4878    }
4879
4880    /// The render box of the first `W`: Dart's `tester.firstRenderObject<RenderBox>(find.byType(W))`.
4881    pub(crate) fn first_render_box<W: 'static>(tester: &WidgetTester) -> AnyRenderBox {
4882        let element = *find::by_type::<W>()
4883            .evaluate(tester)
4884            .first()
4885            .unwrap_or_else(|| panic!("a {}", std::any::type_name::<W>()));
4886        tester.render_box_of(element)
4887    }
4888
4889    // 'Material3 - Scrollable TabBar tap centers selected tab'.
4890    #[test]
4891    fn material3_tapping_a_tab_of_a_scrollable_tab_bar_centers_it() {
4892        test_widgets(|tester| {
4893            let tabs = vec![
4894                "AAAAAA", "BBBBBB", "CCCCCC", "DDDDDD", "EEEEEE", "FFFFFF", "GGGGGG", "HHHHHH",
4895                "IIIIII", "JJJJJJ", "KKKKKK", "LLLLLL",
4896            ];
4897            let tab_bar_key = GlobalKey::new();
4898            let mut frame = Frame::new(tabs, "AAAAAA");
4899            frame.is_scrollable = true;
4900            frame.tab_bar_key = Some(tab_bar_key.clone());
4901            let frame = frame.build(tester);
4902            tester.pump_widget(frame);
4903            let controller = default_controller_of(tester, text(tester, "AAAAAA"));
4904            assert_eq!(controller.index(&tester.cell.borrow()), 0);
4905
4906            let tab_bar = tester.render_object(&tab_bar_key).as_box().expect("a box");
4907            assert_eq!(tab_bar.size(&tester.cell.borrow()).width(), 800.0);
4908            // The center of the FFFFFF item is to the right of the TabBar's center
4909            assert!(tester.get_center(text(tester, "FFFFFF")).dx() > 401.0);
4910
4911            let f = text(tester, "FFFFFF");
4912            tap(tester, f);
4913            tester.pump_and_settle();
4914            assert_eq!(controller.index(&tester.cell.borrow()), 5);
4915            // The center of the FFFFFF item is now at the TabBar's center
4916            let center = tester.get_center(text(tester, "FFFFFF")).dx();
4917            assert!(close(center, 452.0, 1.0), "{center}");
4918        });
4919    }
4920
4921    // 'TabBarView page left and right test'.
4922    #[test]
4923    fn dragging_a_tab_bar_view_past_its_width_changes_the_page() {
4924        test_widgets(|tester| {
4925            let controller = {
4926                let mut app = tester.cell.borrow_mut();
4927                TabController::new(&mut app, 0, None, 2, waft_widgets::testing::TestVSync)
4928            };
4929            let theme = theme(tester, None, None);
4930            tester.pump_widget(boilerplate(
4931                theme,
4932                TextDirection::Ltr,
4933                TabBarView::new([
4934                    Text::new("First").into_widget(),
4935                    Text::new("Second").into_widget(),
4936                ])
4937                .controller(controller.clone()),
4938            ));
4939            let index = |tester: &WidgetTester| controller.index(&tester.cell.borrow());
4940            assert_eq!(index(tester), 0);
4941
4942            let mut gesture = TestPointer::touch(1);
4943            tester.down(&mut gesture, Offset::new(100.0, 100.0));
4944            assert_eq!(index(tester), 0);
4945
4946            // Drag to the left and right, by less than the TabBarView's width.
4947            // The selected index (controller.index) should not change.
4948            tester.move_to(&mut gesture, Offset::new(0.0, 100.0), true);
4949            tester.move_to(&mut gesture, Offset::new(100.0, 100.0), true);
4950            assert_eq!(index(tester), 0);
4951            expect(tester, &find::text("First"), finds_one_widget());
4952            expect(tester, &find::text("Second"), finds_nothing());
4953
4954            // Drag more than the TabBarView's width to the right. This forces
4955            // the selected index to change to 1.
4956            tester.move_to(&mut gesture, Offset::new(-400.0, 100.0), true);
4957            tester.up(&gesture);
4958            tester.pump(); // start the scroll animation
4959            tester.pump_by(Duration::from_secs(1)); // finish the scroll animation
4960            assert_eq!(index(tester), 1);
4961            expect(tester, &find::text("First"), finds_nothing());
4962            expect(tester, &find::text("Second"), finds_one_widget());
4963
4964            let mut gesture = TestPointer::touch(2);
4965            tester.down(&mut gesture, Offset::new(100.0, 100.0));
4966            assert_eq!(index(tester), 1);
4967
4968            tester.move_to(&mut gesture, Offset::new(0.0, 100.0), true);
4969            tester.move_to(&mut gesture, Offset::new(100.0, 100.0), true);
4970            assert_eq!(index(tester), 1);
4971            expect(tester, &find::text("First"), finds_nothing());
4972            expect(tester, &find::text("Second"), finds_one_widget());
4973
4974            // Drag more than the TabBarView's width to the left. This forces
4975            // the selected index to change back to 0.
4976            tester.move_to(&mut gesture, Offset::new(600.0, 100.0), true);
4977            tester.up(&gesture);
4978            tester.pump(); // start the scroll animation
4979            tester.pump_by(Duration::from_secs(1)); // finish the scroll animation
4980            assert_eq!(index(tester), 0);
4981            expect(tester, &find::text("First"), finds_one_widget());
4982            expect(tester, &find::text("Second"), finds_nothing());
4983        });
4984    }
4985
4986    // 'TabBar default tab indicator (primary)'.
4987    #[test]
4988    fn the_default_primary_indicator_is_a_rounded_label_underline_or_a_tab_line() {
4989        test_widgets(|tester| {
4990            let theme = theme(tester, None, None);
4991            let controller = {
4992                let mut app = tester.cell.borrow_mut();
4993                TabController::new(&mut app, 0, None, 4, waft_widgets::testing::TestVSync)
4994            };
4995            const INDICATOR_WEIGHT_LABEL: f64 = 3.0;
4996            const INDICATOR_WEIGHT_TAB: f64 = 2.0;
4997
4998            let build_tab = |indicator_size: Option<TabBarIndicatorSize>| {
4999                let tabs =
5000                    (0..4).map(|index| Tab::new().text(format!("Tab {index}")).into_widget());
5001                let mut tab_bar = TabBar::new(tabs).controller(controller.clone());
5002                if let Some(indicator_size) = indicator_size {
5003                    tab_bar = tab_bar.indicator_size(indicator_size);
5004                }
5005                material_app(
5006                    theme.clone(),
5007                    boilerplate(
5008                        theme.clone(),
5009                        TextDirection::Ltr,
5010                        waft_widgets::Container::new()
5011                            .alignment(AlignmentGeometry::TOP_LEFT)
5012                            .child(tab_bar),
5013                    ),
5014                )
5015            };
5016
5017            // Test default tab indicator (TabBarIndicatorSize.label).
5018            tester.pump_widget(build_tab(None));
5019
5020            let tab_bar_box = first_render_box::<TabBar>(tester);
5021            assert_eq!(tab_bar_box.size(&tester.cell.borrow()).height(), 48.0);
5022
5023            // Check tab indicator size and color.
5024            let rrect = waft_embedder::RRect::from_ltrb_and_corners(
5025                64.75,
5026                48.0 - INDICATOR_WEIGHT_LABEL,
5027                135.25,
5028                48.0,
5029                waft_embedder::Radius::circular(3.0),
5030                waft_embedder::Radius::circular(3.0),
5031                waft_embedder::Radius::ZERO,
5032                waft_embedder::Radius::ZERO,
5033            );
5034            waft_rendering::testing::assert_paints(
5035                &tester.painted_ops(tab_bar_box.as_object()),
5036                &[waft_rendering::testing::PaintCall::rrect_at(
5037                    rrect,
5038                    Some(theme.color_scheme.primary()),
5039                )],
5040            );
5041
5042            // Test default tab indicator (TabBarIndicatorSize.tab).
5043            tester.pump_widget(build_tab(Some(TabBarIndicatorSize::Tab)));
5044            tester.pump_and_settle();
5045
5046            let tab_bar_box = first_render_box::<TabBar>(tester);
5047            assert_eq!(tab_bar_box.size(&tester.cell.borrow()).height(), 48.0);
5048
5049            const INDICATOR_Y: f64 = 48.0 - (INDICATOR_WEIGHT_TAB / 2.0);
5050            const INDICATOR_LEFT: f64 = INDICATOR_WEIGHT_TAB / 2.0;
5051            const INDICATOR_RIGHT: f64 = 200.0 - (INDICATOR_WEIGHT_TAB / 2.0);
5052
5053            // Check tab indicator size and color.
5054            let lines = painted_lines(tester, tab_bar_box.as_object());
5055            // Divider.
5056            let divider = lines
5057                .iter()
5058                .position(|line| {
5059                    line.color.to_argb32() == theme.color_scheme.outline_variant().to_argb32()
5060                })
5061                .expect("a divider line");
5062            // Tab indicator.
5063            assert!(
5064                lines[divider + 1..].iter().any(|line| is_line(
5065                    line,
5066                    theme.color_scheme.primary(),
5067                    Some(INDICATOR_WEIGHT_TAB),
5068                    Offset::new(INDICATOR_LEFT, INDICATOR_Y),
5069                    Offset::new(INDICATOR_RIGHT, INDICATOR_Y),
5070                )),
5071                "{lines:?}"
5072            );
5073        });
5074    }
5075
5076    mod sizes_styles_and_flings {
5077        //! tabs_test.dart cases from 'indicatorPadding update test' through 'TabBar animationDuration
5078        //! sets indicator animation duration'.
5079
5080        use super::*;
5081
5082        use std::cell::RefCell;
5083
5084        use waft_embedder::{RRect, Radius};
5085        use waft_rendering::RenderParagraph;
5086        use waft_widgets::{Icon, RichText};
5087
5088        use crate::app_bar::AppBar;
5089        use crate::icons::Icons;
5090        use crate::material::RenderInkFeatures;
5091        use crate::scaffold::Scaffold;
5092        use crate::test_support::PaintInspection;
5093        use waft_embedder::valo::Op;
5094        use waft_rendering::testing::{PaintCall, paints};
5095        use waft_widgets::testing::TestVSync;
5096
5097        /// The style of the `Text` showing `text` under a tab's `_TabStyle`: Dart's `getTabText`'s
5098        /// paragraph's `text.style`.
5099        fn tab_text_style(tester: &WidgetTester, label: &str) -> TextStyle {
5100            let styles = find::by_type::<waft_widgets::Animated<TabStyle>>().evaluate(tester);
5101            let element = find::text(label)
5102                .evaluate(tester)
5103                .into_iter()
5104                .find(|element| {
5105                    let ancestors = tester.ancestors(*element);
5106                    styles.iter().any(|style| ancestors.contains(style))
5107                })
5108                .unwrap_or_else(|| panic!("a Text showing {label:?} under a _TabStyle"));
5109            let render = tester.render_box_of(element);
5110            let app = tester.cell.borrow();
5111            let paragraph = render
5112                .as_object()
5113                .downcast::<RenderParagraph>(&app)
5114                .expect("a Text renders a paragraph");
5115            paragraph
5116                .text(&app)
5117                .style()
5118                .cloned()
5119                .expect("the paragraph's text has a style")
5120        }
5121
5122        /// The `fontFamily` of the only `RichText`'s paragraph.
5123        fn rich_text_font_family(tester: &WidgetTester) -> Option<String> {
5124            let render = tester.render_box_of(only::<RichText>(tester));
5125            let app = tester.cell.borrow();
5126            let paragraph = render
5127                .as_object()
5128                .downcast::<RenderParagraph>(&app)
5129                .expect("a paragraph");
5130            paragraph
5131                .text(&app)
5132                .style()
5133                .and_then(|style| style.font_family.clone())
5134        }
5135
5136        fn style_color(style: &TextStyle) -> Option<Color> {
5137            style.color.as_ref().map(AnyColor::color)
5138        }
5139
5140        /// A FlutterTest theme: Dart's `ThemeData(fontFamily: 'FlutterTest')`.
5141        fn flutter_test_theme(tester: &WidgetTester) -> ThemeData {
5142            let app = tester.cell.borrow();
5143            ThemeData::builder().font_family("FlutterTest").build(&app)
5144        }
5145
5146        fn tab_controller(tester: &WidgetTester, length: usize) -> Ref<TabController> {
5147            let mut app = tester.cell.borrow_mut();
5148            TabController::new(&mut app, 0, None, length, TestVSync)
5149        }
5150
5151        fn has_rect(ops: &[Op], color: Color) -> bool {
5152            paints(ops, &[PaintCall::rect(Some(color))]).is_ok()
5153        }
5154
5155        fn has_rect_then_rect(ops: &[Op], color: Color) -> bool {
5156            paints(ops, &[PaintCall::rect(None), PaintCall::rect(Some(color))]).is_ok()
5157        }
5158
5159        fn first_material_paints(tester: &WidgetTester) -> Vec<Op> {
5160            let render = tester.first::<RenderInkFeatures>();
5161            tester.painted_ops(render.as_object())
5162        }
5163
5164        // 'Tab sizing - icon and text'.
5165        #[test]
5166        fn a_tab_with_an_icon_and_text_is_as_wide_as_the_text_and_72_high() {
5167            test_widgets(|tester| {
5168                let theme = flutter_test_theme(tester);
5169                let material3 = theme.use_material3;
5170                tester.pump_widget(material_app(
5171                    theme,
5172                    Center::new()
5173                        .child(
5174                            Material::new().child(
5175                                Tab::new()
5176                                    .icon(SizedBox::new().width(10.0).height(10.0))
5177                                    .text("x"),
5178                            ),
5179                        )
5180                        .into_widget(),
5181                ));
5182                assert_eq!(
5183                    rich_text_font_family(tester).as_deref(),
5184                    Some("FlutterTest")
5185                );
5186                let expected = if material3 {
5187                    Size::new(14.25, 72.0)
5188                } else {
5189                    Size::new(14.0, 72.0)
5190                };
5191                assert_eq!(tester.get_size(only::<Tab>(tester)), expected);
5192            });
5193        }
5194
5195        // 'Tab sizing - icon, iconMargin and text'.
5196        #[test]
5197        fn a_tab_with_an_icon_margin_is_as_wide_as_the_icon_and_its_margin() {
5198            test_widgets(|tester| {
5199                let theme = flutter_test_theme(tester);
5200                tester.pump_widget(material_app(
5201                    theme,
5202                    Center::new()
5203                        .child(
5204                            Material::new().child(
5205                                Tab::new()
5206                                    .icon(SizedBox::new().width(10.0).height(10.0))
5207                                    .icon_margin(EdgeInsetsGeometry::symmetric(0.0, 100.0))
5208                                    .text("x"),
5209                            ),
5210                        )
5211                        .into_widget(),
5212                ));
5213                assert_eq!(
5214                    rich_text_font_family(tester).as_deref(),
5215                    Some("FlutterTest")
5216                );
5217                assert_eq!(tester.get_size(only::<Tab>(tester)), Size::new(210.0, 72.0));
5218            });
5219        }
5220
5221        // 'Tab sizing - icon and child'.
5222        #[test]
5223        fn a_tab_with_an_icon_and_a_child_is_as_wide_as_the_child_and_72_high() {
5224            test_widgets(|tester| {
5225                let theme = flutter_test_theme(tester);
5226                let material3 = theme.use_material3;
5227                tester.pump_widget(material_app(
5228                    theme,
5229                    Center::new()
5230                        .child(
5231                            Material::new().child(
5232                                Tab::new()
5233                                    .icon(SizedBox::new().width(10.0).height(10.0))
5234                                    .child(Text::new("x")),
5235                            ),
5236                        )
5237                        .into_widget(),
5238                ));
5239                assert_eq!(
5240                    rich_text_font_family(tester).as_deref(),
5241                    Some("FlutterTest")
5242                );
5243                let expected = if material3 {
5244                    Size::new(14.25, 72.0)
5245                } else {
5246                    Size::new(14.0, 72.0)
5247                };
5248                assert_eq!(tester.get_size(only::<Tab>(tester)), expected);
5249            });
5250        }
5251
5252        /// Dart's `getIconMargin`: from the bottom of the house icon to the top of the label.
5253        fn icon_margin(tester: &WidgetTester) -> f64 {
5254            let icon_rect = tester.get_rect(tester.element(find::by_icon(&Icons::house()).first()));
5255            let label_rect = tester.get_rect(text(tester, "x"));
5256            label_rect.top - icon_rect.bottom
5257        }
5258
5259        // 'Material2 - Default Tab iconMargin'.
5260        #[test]
5261        fn material2_a_tab_icon_has_10_pixels_below_it_by_default() {
5262            test_widgets(|tester| {
5263                let theme = super::theme(tester, Some(false), None);
5264                tester.pump_widget(material_app(
5265                    theme,
5266                    Material::new()
5267                        .child(Tab::new().icon(Icon::new(Some(Icons::house()))).text("x"))
5268                        .into_widget(),
5269                ));
5270                assert_eq!(icon_margin(tester), 10.0);
5271            });
5272        }
5273
5274        // 'Material3 - Default Tab iconMargin'.
5275        #[test]
5276        fn material3_a_tab_icon_has_2_pixels_below_it_by_default() {
5277            test_widgets(|tester| {
5278                let theme = super::theme(tester, None, None);
5279                tester.pump_widget(material_app(
5280                    theme,
5281                    Material::new()
5282                        .child(Tab::new().icon(Icon::new(Some(Icons::house()))).text("x"))
5283                        .into_widget(),
5284                ));
5285                assert_eq!(icon_margin(tester), 2.0);
5286            });
5287        }
5288
5289        fn tab_bar_paints_line_of(tester: &WidgetTester, color: Color) -> bool {
5290            let tab_bar = first_render_box::<TabBar>(tester);
5291            paints(
5292                &tester.painted_ops(tab_bar.as_object()),
5293                &[PaintCall::Line {
5294                    p1: None,
5295                    p2: None,
5296                    color: Some(color),
5297                    stroke_width: None,
5298                }],
5299            )
5300            .is_ok()
5301        }
5302
5303        // 'Tab color - normal'.
5304        #[test]
5305        fn a_tab_bar_on_a_material_paints_its_divider_or_its_m2_indicator() {
5306            test_widgets(|tester| {
5307                let theme = flutter_test_theme(tester);
5308                let material3 = theme.use_material3;
5309                let controller = tab_controller(tester, 1);
5310                tester.pump_widget(material_app(
5311                    theme.clone(),
5312                    Material::new()
5313                        .child(
5314                            TabBar::new([SizedBox::shrink().into_widget()]).controller(controller),
5315                        )
5316                        .into_widget(),
5317                ));
5318                let expected = if material3 {
5319                    theme.color_scheme.outline_variant()
5320                } else {
5321                    Colors::BLUE.shade500()
5322                };
5323                assert!(tab_bar_paints_line_of(tester, expected));
5324            });
5325        }
5326
5327        // 'Tab color - match'.
5328        #[test]
5329        fn an_m2_indicator_the_color_of_its_material_turns_white() {
5330            test_widgets(|tester| {
5331                let theme = super::theme(tester, None, None);
5332                let material3 = theme.use_material3;
5333                let controller = tab_controller(tester, 1);
5334                tester.pump_widget(material_app(
5335                    theme.clone(),
5336                    Material::new()
5337                        .color(Color::new(0xff2196f3))
5338                        .child(
5339                            TabBar::new([SizedBox::shrink().into_widget()]).controller(controller),
5340                        )
5341                        .into_widget(),
5342                ));
5343                let expected = if material3 {
5344                    theme.color_scheme.outline_variant()
5345                } else {
5346                    Colors::WHITE
5347                };
5348                assert!(tab_bar_paints_line_of(tester, expected));
5349            });
5350        }
5351
5352        // 'Tab color - transparency'.
5353        #[test]
5354        fn a_tab_bar_on_a_transparent_material_keeps_its_indicator_color() {
5355            test_widgets(|tester| {
5356                let theme = super::theme(tester, None, None);
5357                let material3 = theme.use_material3;
5358                let controller = tab_controller(tester, 1);
5359                tester.pump_widget(material_app(
5360                    theme.clone(),
5361                    Material::new()
5362                        .r#type(MaterialType::Transparency)
5363                        .child(
5364                            TabBar::new([SizedBox::shrink().into_widget()]).controller(controller),
5365                        )
5366                        .into_widget(),
5367                ));
5368                let expected = if material3 {
5369                    theme.color_scheme.outline_variant()
5370                } else {
5371                    Colors::BLUE.shade500()
5372                };
5373                assert!(tab_bar_paints_line_of(tester, expected));
5374            });
5375        }
5376
5377        /// Dart's label style cases: the selected and unselected labels' family, size and color.
5378        fn assert_label_styles(
5379            tester: &WidgetTester,
5380            selected: &str,
5381            selected_color: Color,
5382            unselected: &str,
5383            unselected_color: Color,
5384        ) {
5385            expect(tester, &find::text("A"), finds_one_widget());
5386            expect(tester, &find::text("B"), finds_one_widget());
5387            expect(tester, &find::text("C"), finds_one_widget());
5388
5389            // Test selected label text style.
5390            let selected_label = tab_text_style(tester, selected);
5391            assert_eq!(selected_label.font_family.as_deref(), Some("Roboto"));
5392            assert_eq!(selected_label.font_size, Some(14.0));
5393            assert_eq!(style_color(&selected_label), Some(selected_color));
5394
5395            // Test unselected label text style.
5396            let unselected_label = tab_text_style(tester, unselected);
5397            assert_eq!(unselected_label.font_family.as_deref(), Some("Roboto"));
5398            assert_eq!(unselected_label.font_size, Some(14.0));
5399            assert_eq!(style_color(&unselected_label), Some(unselected_color));
5400        }
5401
5402        // 'TabBar default selected/unselected label style (primary)'.
5403        #[test]
5404        fn a_primary_tab_bar_labels_are_primary_when_selected_and_on_surface_variant_otherwise() {
5405            test_widgets(|tester| {
5406                let theme = super::theme(tester, None, None);
5407                let mut frame = Frame::new(vec!["A", "B", "C"], "A");
5408                frame.use_material3 = Some(theme.use_material3);
5409                let frame = frame.build(tester);
5410                tester.pump_widget(frame);
5411                assert_label_styles(
5412                    tester,
5413                    "A",
5414                    theme.color_scheme.primary(),
5415                    "C",
5416                    theme.color_scheme.on_surface_variant(),
5417                );
5418            });
5419        }
5420
5421        // 'TabBar default selected/unselected label style (secondary)'.
5422        #[test]
5423        fn a_secondary_tab_bar_labels_are_on_surface_when_selected_and_on_surface_variant_otherwise()
5424         {
5425            test_widgets(|tester| {
5426                let theme = super::theme(tester, None, None);
5427                let mut frame = Frame::new(vec!["A", "B", "C"], "A");
5428                frame.secondary_tab_bar = true;
5429                frame.use_material3 = Some(theme.use_material3);
5430                let frame = frame.build(tester);
5431                tester.pump_widget(frame);
5432                assert_label_styles(
5433                    tester,
5434                    "A",
5435                    theme.color_scheme.on_surface(),
5436                    "C",
5437                    theme.color_scheme.on_surface_variant(),
5438                );
5439            });
5440        }
5441
5442        // 'Material 3 primary tab indicator has a minimum width of 24dp'.
5443        #[test]
5444        fn a_material3_primary_label_indicator_is_at_least_24_wide() {
5445            test_widgets(|tester| {
5446                let mut frame = Frame::new(vec!["A", "Medium", "Longer Tab"], "A");
5447                frame.use_material3 = Some(true);
5448                let frame = frame.build(tester);
5449                tester.pump_widget(frame);
5450
5451                let tab_bar_box = first_render_box::<TabBar>(tester);
5452                let label_box = tester.render_box_of(text(tester, "A"));
5453                let (label_center, tab_bar_height) = {
5454                    let app = tester.cell.borrow();
5455                    let label_size = label_box.size(&app);
5456                    assert!(label_size.width() < 24.0);
5457                    let global =
5458                        label_box.local_to_global(&app, label_size.center(Offset::ZERO), None);
5459                    (
5460                        tab_bar_box.global_to_local(&app, global, None),
5461                        tab_bar_box.size(&app).height(),
5462                    )
5463                };
5464                let tab_bar = only::<TabBar>(tester);
5465                let primary = {
5466                    let mut app = tester.cell.borrow_mut();
5467                    Theme::of(&mut app, tab_bar).color_scheme.primary()
5468                };
5469                let expected_indicator = Rect::from_ltrb(
5470                    label_center.dx() - 12.0,
5471                    tab_bar_height - 3.0,
5472                    label_center.dx() + 12.0,
5473                    tab_bar_height,
5474                );
5475
5476                waft_rendering::testing::assert_paints(
5477                    &tester.painted_ops(tab_bar_box.as_object()),
5478                    &[waft_rendering::testing::PaintCall::rrect_at(
5479                        RRect::from_rect_and_corners(
5480                            expected_indicator,
5481                            Radius::circular(3.0),
5482                            Radius::circular(3.0),
5483                            Radius::ZERO,
5484                            Radius::ZERO,
5485                        ),
5486                        Some(primary),
5487                    )],
5488                );
5489            });
5490        }
5491
5492        // 'TabBar default tab indicator (secondary)'.
5493        #[test]
5494        fn the_default_secondary_indicator_is_a_tab_wide_line_over_the_divider() {
5495            test_widgets(|tester| {
5496                let theme = super::theme(tester, None, None);
5497                let controller = tab_controller(tester, 4);
5498                const INDICATOR_WEIGHT: f64 = 2.0;
5499
5500                // Test default tab indicator.
5501                let tabs =
5502                    (0..4).map(|index| Tab::new().text(format!("Tab {index}")).into_widget());
5503                tester.pump_widget(material_app(
5504                    theme.clone(),
5505                    boilerplate(
5506                        theme.clone(),
5507                        TextDirection::Ltr,
5508                        waft_widgets::Container::new()
5509                            .alignment(AlignmentGeometry::TOP_LEFT)
5510                            .child(TabBar::secondary(tabs).controller(controller)),
5511                    ),
5512                ));
5513
5514                let tab_bar_box = first_render_box::<TabBar>(tester);
5515                assert_eq!(tab_bar_box.size(&tester.cell.borrow()).height(), 48.0);
5516
5517                const INDICATOR_Y: f64 = 48.0 - (INDICATOR_WEIGHT / 2.0);
5518                const INDICATOR_LEFT: f64 = INDICATOR_WEIGHT / 2.0;
5519                const INDICATOR_RIGHT: f64 = 200.0 - (INDICATOR_WEIGHT / 2.0);
5520
5521                // Check tab indicator size and color.
5522                let lines = painted_lines(tester, tab_bar_box.as_object());
5523                // Divider.
5524                let divider = lines
5525                    .iter()
5526                    .position(|line| {
5527                        line.color.to_argb32() == theme.color_scheme.outline_variant().to_argb32()
5528                    })
5529                    .expect("a divider line");
5530                // Tab indicator.
5531                assert!(
5532                    lines[divider + 1..].iter().any(|line| is_line(
5533                        line,
5534                        theme.color_scheme.primary(),
5535                        Some(INDICATOR_WEIGHT),
5536                        Offset::new(INDICATOR_LEFT, INDICATOR_Y),
5537                        Offset::new(INDICATOR_RIGHT, INDICATOR_Y),
5538                    )),
5539                    "{lines:?}"
5540                );
5541            });
5542        }
5543
5544        /// Dart's `TabBar default overlay` cases: hover and press a selected and an unselected tab
5545        /// with a mouse.
5546        #[allow(deprecated)]
5547        fn check_default_overlay(
5548            tester: &mut WidgetTester,
5549            selected_hovered: Color,
5550            selected_pressed: Color,
5551            unselected_hovered: Color,
5552        ) {
5553            let mut gesture = TestPointer::mouse(1, waft_gestures::K_PRIMARY_BUTTON);
5554            tester.add_pointer(&mut gesture, Offset::ZERO);
5555            let selected = tester.get_center(text(tester, "A"));
5556            tester.move_to(&mut gesture, selected, false);
5557            tester.pump_and_settle();
5558            assert!(has_rect(&first_material_paints(tester), selected_hovered));
5559
5560            tester.down(&mut gesture, selected);
5561            tester.pump_and_settle();
5562            assert!(has_rect_then_rect(
5563                &first_material_paints(tester),
5564                selected_pressed
5565            ));
5566            tester.up(&gesture);
5567            tester.pump_and_settle();
5568
5569            let unselected = tester.get_center(text(tester, "B"));
5570            tester.move_to(&mut gesture, unselected, false);
5571            tester.pump_and_settle();
5572            assert!(has_rect(&first_material_paints(tester), unselected_hovered));
5573
5574            tester.move_to(&mut gesture, selected, false);
5575            tester.pump_and_settle();
5576            assert!(has_rect(&first_material_paints(tester), selected_hovered));
5577
5578            tester.down(&mut gesture, selected);
5579            tester.pump_and_settle();
5580            assert!(has_rect_then_rect(
5581                &first_material_paints(tester),
5582                selected_pressed
5583            ));
5584            tester.up(&gesture);
5585            tester.pump_and_settle();
5586        }
5587
5588        // 'TabBar default overlay (primary)'.
5589        #[test]
5590        #[allow(deprecated)]
5591        fn a_primary_tab_overlay_is_primary_on_the_selected_tab_and_on_surface_on_others() {
5592            test_widgets(|tester| {
5593                let theme = super::theme(tester, None, None);
5594                let mut frame = Frame::new(vec!["A", "B"], "A");
5595                frame.use_material3 = Some(theme.use_material3);
5596                let frame = frame.build(tester);
5597                tester.pump_widget(frame);
5598                let colors = &theme.color_scheme;
5599                check_default_overlay(
5600                    tester,
5601                    colors.primary().with_opacity(0.08),
5602                    colors.primary().with_opacity(0.1),
5603                    colors.on_surface().with_opacity(0.08),
5604                );
5605            });
5606        }
5607
5608        // 'TabBar default overlay (secondary)'.
5609        #[test]
5610        #[allow(deprecated)]
5611        fn a_secondary_tab_overlay_is_on_surface_on_every_tab() {
5612            test_widgets(|tester| {
5613                let theme = super::theme(tester, None, None);
5614                let mut frame = Frame::new(vec!["A", "B"], "A");
5615                frame.secondary_tab_bar = true;
5616                frame.use_material3 = Some(theme.use_material3);
5617                let frame = frame.build(tester);
5618                tester.pump_widget(frame);
5619                let colors = &theme.color_scheme;
5620                check_default_overlay(
5621                    tester,
5622                    colors.on_surface().with_opacity(0.08),
5623                    colors.on_surface().with_opacity(0.1),
5624                    colors.on_surface().with_opacity(0.08),
5625                );
5626            });
5627        }
5628
5629        const TWELVE_TABS: [&str; 12] = [
5630            "AAAAAA", "BBBBBB", "CCCCCC", "DDDDDD", "EEEEEE", "FFFFFF", "GGGGGG", "HHHHHH",
5631            "IIIIII", "JJJJJJ", "KKKKKK", "LLLLLL",
5632        ];
5633
5634        fn index_of(tester: &WidgetTester, controller: Handle<TabController>) -> usize {
5635            controller.index(&tester.cell.borrow())
5636        }
5637
5638        // 'Scrollable TabBar tap selects tab'.
5639        #[test]
5640        fn tapping_a_tab_of_a_scrollable_tab_bar_selects_it() {
5641            test_widgets(|tester| {
5642                let mut frame = Frame::new(vec!["A", "B", "C"], "C");
5643                frame.is_scrollable = true;
5644                let frame = frame.build(tester);
5645                tester.pump_widget(frame);
5646                expect(tester, &find::text("A"), finds_one_widget());
5647                expect(tester, &find::text("B"), finds_one_widget());
5648                expect(tester, &find::text("C"), finds_one_widget());
5649                let controller = default_controller_of(tester, text(tester, "A"));
5650                assert_eq!(index_of(tester, controller.handle()), 2);
5651                assert_eq!(controller.previous_index(&tester.cell.borrow()), 2);
5652
5653                for (label, index) in [("C", 2), ("B", 1), ("A", 0)] {
5654                    let tab = text(tester, label);
5655                    tap(tester, tab);
5656                    tester.pump_and_settle();
5657                    assert_eq!(index_of(tester, controller.handle()), index);
5658                }
5659            });
5660        }
5661
5662        /// Dart's 'Scrollable TabBar ... tap centers selected tab' cases: tap FFFFFF of twelve
5663        /// scrollable tabs and find it centred at `expected`.
5664        fn check_tap_centers_tab(
5665            tester: &mut WidgetTester,
5666            use_material3: Option<bool>,
5667            padding: Option<EdgeInsetsGeometry>,
5668            text_direction: TextDirection,
5669            expected: f64,
5670        ) {
5671            let tab_bar_key = GlobalKey::new();
5672            let mut frame = Frame::new(TWELVE_TABS.to_vec(), "AAAAAA");
5673            frame.is_scrollable = true;
5674            frame.tab_bar_key = Some(tab_bar_key.clone());
5675            frame.padding = padding;
5676            frame.text_direction = text_direction;
5677            frame.use_material3 = use_material3;
5678            let frame = frame.build(tester);
5679            tester.pump_widget(frame);
5680            let controller = default_controller_of(tester, text(tester, "AAAAAA"));
5681            assert_eq!(index_of(tester, controller.handle()), 0);
5682
5683            let tab_bar = tester.render_object(&tab_bar_key).as_box().expect("a box");
5684            assert_eq!(tab_bar.size(&tester.cell.borrow()).width(), 800.0);
5685            let center = tester.get_center(text(tester, "FFFFFF")).dx();
5686            match text_direction {
5687                // The center of the FFFFFF item is to the right of the TabBar's center
5688                TextDirection::Ltr => assert!(center > 401.0, "{center}"),
5689                // The center of the FFFFFF item is to the left of the TabBar's center
5690                TextDirection::Rtl => assert!(center < 401.0, "{center}"),
5691            }
5692
5693            let f = text(tester, "FFFFFF");
5694            tap(tester, f);
5695            tester.pump_and_settle();
5696            assert_eq!(index_of(tester, controller.handle()), 5);
5697            // The center of the FFFFFF item is now at the TabBar's center
5698            let center = tester.get_center(text(tester, "FFFFFF")).dx();
5699            assert!(close(center, expected, 1.0), "{center}");
5700        }
5701
5702        fn padding_right_30_left_60() -> EdgeInsetsGeometry {
5703            EdgeInsetsGeometry::only(60.0, 0.0, 30.0, 0.0)
5704        }
5705
5706        // 'Material2 - Scrollable TabBar tap centers selected tab'.
5707        #[test]
5708        fn material2_tapping_a_tab_of_a_scrollable_tab_bar_centers_it() {
5709            test_widgets(|tester| {
5710                check_tap_centers_tab(tester, Some(false), None, TextDirection::Ltr, 400.0);
5711            });
5712        }
5713
5714        // 'Material2 - Scrollable TabBar, with padding, tap centers selected tab'.
5715        #[test]
5716        fn material2_tapping_a_tab_of_a_padded_scrollable_tab_bar_centers_it() {
5717            test_widgets(|tester| {
5718                check_tap_centers_tab(
5719                    tester,
5720                    Some(false),
5721                    Some(padding_right_30_left_60()),
5722                    TextDirection::Ltr,
5723                    400.0,
5724                );
5725            });
5726        }
5727
5728        // 'Material3 - Scrollable TabBar, with padding, tap centers selected tab'.
5729        #[test]
5730        fn material3_tapping_a_tab_of_a_padded_scrollable_tab_bar_centers_it() {
5731            test_widgets(|tester| {
5732                check_tap_centers_tab(
5733                    tester,
5734                    None,
5735                    Some(padding_right_30_left_60()),
5736                    TextDirection::Ltr,
5737                    452.0,
5738                );
5739            });
5740        }
5741
5742        // 'Material2 - Scrollable TabBar, with padding and TextDirection.rtl, tap centers selected tab'.
5743        #[test]
5744        fn material2_tapping_a_tab_of_a_padded_right_to_left_scrollable_tab_bar_centers_it() {
5745            test_widgets(|tester| {
5746                check_tap_centers_tab(
5747                    tester,
5748                    Some(false),
5749                    Some(padding_right_30_left_60()),
5750                    TextDirection::Rtl,
5751                    400.0,
5752                );
5753            });
5754        }
5755
5756        // 'Material3 - Scrollable TabBar, with padding and TextDirection.rtl, tap centers selected tab'.
5757        #[test]
5758        fn material3_tapping_a_tab_of_a_padded_right_to_left_scrollable_tab_bar_centers_it() {
5759            test_widgets(|tester| {
5760                check_tap_centers_tab(
5761                    tester,
5762                    None,
5763                    Some(padding_right_30_left_60()),
5764                    TextDirection::Rtl,
5765                    348.0,
5766                );
5767            });
5768        }
5769
5770        /// Dart's 'TabBar can be scrolled independent of the selection' cases.
5771        fn check_scrolled_independent_of_selection(
5772            tester: &mut WidgetTester,
5773            use_material3: Option<bool>,
5774            start_limit: f64,
5775        ) {
5776            let tabs = vec![
5777                "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIII", "JJJJ",
5778                "KKKK", "LLLL",
5779            ];
5780            let tab_bar_key = GlobalKey::new();
5781            let mut frame = Frame::new(tabs, "AAAA");
5782            frame.is_scrollable = true;
5783            frame.tab_bar_key = Some(tab_bar_key.clone());
5784            frame.use_material3 = use_material3;
5785            let frame = frame.build(tester);
5786            tester.pump_widget(frame);
5787            let controller = default_controller_of(tester, text(tester, "AAAA"));
5788            assert_eq!(index_of(tester, controller.handle()), 0);
5789
5790            // Fling-scroll the TabBar to the left
5791            assert!(tester.get_center(text(tester, "HHHH")).dx() < start_limit);
5792            let tab_bar_center = tester.get_center(&tab_bar_key);
5793            tester.fling_from(tab_bar_center, Offset::new(-200.0, 0.0), 10000.0, 1);
5794            tester.pump();
5795            tester.pump_by(Duration::from_secs(1)); // finish the scroll animation
5796            assert!(tester.get_center(text(tester, "HHHH")).dx() < 500.0);
5797
5798            // Scrolling the TabBar doesn't change the selection
5799            assert_eq!(index_of(tester, controller.handle()), 0);
5800        }
5801
5802        // 'Material2 - TabBar can be scrolled independent of the selection'.
5803        #[test]
5804        fn material2_flinging_a_scrollable_tab_bar_keeps_the_selection() {
5805            test_widgets(|tester| {
5806                check_scrolled_independent_of_selection(tester, Some(false), 700.0)
5807            });
5808        }
5809
5810        // 'Material3 - TabBar can be scrolled independent of the selection'.
5811        #[test]
5812        fn material3_flinging_a_scrollable_tab_bar_keeps_the_selection() {
5813            test_widgets(|tester| check_scrolled_independent_of_selection(tester, None, 720.0));
5814        }
5815
5816        /// Dart's `TabStateMarker`: a stateful widget whose state carries a `marker`.
5817        #[derive(Debug)]
5818        struct TabStateMarker {
5819            child: Option<WidgetRef>,
5820        }
5821
5822        impl StatefulWidget for TabStateMarker {
5823            type State = TabStateMarkerState;
5824
5825            fn create_state(&self) -> TabStateMarkerState {
5826                TabStateMarkerState {
5827                    state: StateData::new(),
5828                    marker: None,
5829                }
5830            }
5831        }
5832
5833        /// Dart's `TabStateMarkerState`.
5834        struct TabStateMarkerState {
5835            state: StateData<TabStateMarker>,
5836            marker: Option<String>,
5837        }
5838
5839        impl State for TabStateMarkerState {
5840            type Widget = TabStateMarker;
5841            waft_widgets::state_accessors!();
5842
5843            fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
5844                self.widget(app)
5845                    .child
5846                    .clone()
5847                    .unwrap_or_else(|| waft_widgets::Container::new().into_widget())
5848            }
5849        }
5850
5851        // 'TabBarView maintains state'.
5852        #[test]
5853        fn a_tab_bar_view_keeps_the_state_of_the_pages_beside_the_current_one() {
5854            test_widgets(|tester| {
5855                let tabs = ["AAAAAA", "BBBBBB", "CCCCCC", "DDDDDD", "EEEEEE"];
5856                let theme = super::theme(tester, None, None);
5857                let builder = |value: &str| {
5858                    boilerplate(
5859                        theme.clone(),
5860                        TextDirection::Ltr,
5861                        DefaultTabController::new(
5862                            tabs.len(),
5863                            TabBarView::new(tabs.iter().map(|name| {
5864                                TabStateMarker {
5865                                    child: Some(Text::new(*name).into_widget()),
5866                                }
5867                                .into_widget()
5868                            })),
5869                        )
5870                        .initial_index(tabs.iter().position(|tab| *tab == value).expect("a tab")),
5871                    )
5872                };
5873                // Dart's `find.widgetWithText(TabStateMarker, name, skipOffstage: false)`'s state.
5874                let find_state_marker_state = |tester: &WidgetTester, name: &str| {
5875                    let marker = find::by_type::<TabStateMarker>()
5876                        .evaluate(tester)
5877                        .into_iter()
5878                        .find(|marker| {
5879                            find::text(name)
5880                                .evaluate(tester)
5881                                .iter()
5882                                .any(|text| tester.ancestors(*text).contains(marker))
5883                        })
5884                        .unwrap_or_else(|| panic!("a TabStateMarker with {name:?}"));
5885                    marker
5886                        .state_handle::<TabStateMarkerState>(&tester.cell.borrow())
5887                        .expect("a marker state")
5888                };
5889
5890                let mut value = tabs[0];
5891                tester.pump_widget(builder(value));
5892                let controller = default_controller_of(tester, text(tester, "AAAAAA"));
5893
5894                let mut gesture = TestPointer::touch(1);
5895                let start = tester.get_center(text(tester, tabs[0]));
5896                tester.down(&mut gesture, start);
5897                tester.move_to(&mut gesture, start + Offset::new(-600.0, 0.0), true);
5898                tester.pump();
5899                assert_eq!(value, tabs[0]);
5900                let state = find_state_marker_state(tester, tabs[1]);
5901                tester.cell.borrow_mut().get_mut(state).marker = Some("marked".to_string());
5902                tester.up(&gesture);
5903                tester.pump();
5904                tester.pump_by(Duration::from_secs(1));
5905                value = tabs[index_of(tester, controller.handle())];
5906                assert_eq!(value, tabs[1]);
5907                tester.pump_widget(builder(value));
5908                let state = find_state_marker_state(tester, tabs[1]);
5909                assert_eq!(
5910                    tester.cell.borrow().get(state).marker.as_deref(),
5911                    Some("marked")
5912                );
5913
5914                // Move to the third tab.
5915
5916                let mut gesture = TestPointer::touch(2);
5917                let start = tester.get_center(text(tester, tabs[1]));
5918                tester.down(&mut gesture, start);
5919                tester.move_to(&mut gesture, start + Offset::new(-600.0, 0.0), true);
5920                tester.up(&gesture);
5921                tester.pump();
5922                let state = find_state_marker_state(tester, tabs[1]);
5923                assert_eq!(
5924                    tester.cell.borrow().get(state).marker.as_deref(),
5925                    Some("marked")
5926                );
5927                tester.pump_by(Duration::from_secs(1));
5928                value = tabs[index_of(tester, controller.handle())];
5929                assert_eq!(value, tabs[2]);
5930                tester.pump_widget(builder(value));
5931
5932                // The state is now gone.
5933
5934                expect(tester, &find::text(tabs[1]), finds_nothing());
5935
5936                // Move back to the second tab.
5937
5938                let mut gesture = TestPointer::touch(3);
5939                let start = tester.get_center(text(tester, tabs[2]));
5940                tester.down(&mut gesture, start);
5941                tester.move_to(&mut gesture, start + Offset::new(600.0, 0.0), true);
5942                tester.pump();
5943                let marker_state = find_state_marker_state(tester, tabs[1]);
5944                assert_eq!(tester.cell.borrow().get(marker_state).marker, None);
5945                tester.cell.borrow_mut().get_mut(marker_state).marker = Some("marked".to_string());
5946                tester.up(&gesture);
5947                tester.pump();
5948                tester.pump_by(Duration::from_secs(1));
5949                value = tabs[index_of(tester, controller.handle())];
5950                assert_eq!(value, tabs[1]);
5951                tester.pump_widget(builder(value));
5952                let state = find_state_marker_state(tester, tabs[1]);
5953                assert_eq!(
5954                    tester.cell.borrow().get(state).marker.as_deref(),
5955                    Some("marked")
5956                );
5957            });
5958        }
5959
5960        /// `buildLeftRightApp(tabs: ['LEFT', 'RIGHT'], value: 'LEFT')`, pumped, with its controller
5961        /// at 0 and its first page showing.
5962        fn pump_left_right_app(tester: &mut WidgetTester) -> Ref<TabController> {
5963            let app = build_left_right_app(tester, vec!["LEFT", "RIGHT"], "LEFT", true, None);
5964            tester.pump_widget(app);
5965            expect(tester, &find::text("LEFT"), finds_one_widget());
5966            expect(tester, &find::text("RIGHT"), finds_one_widget());
5967            expect(tester, &find::text("LEFT CHILD"), finds_one_widget());
5968            expect(tester, &find::text("RIGHT CHILD"), finds_nothing());
5969
5970            let controller = default_controller_of(tester, text(tester, "LEFT"));
5971            assert_eq!(index_of(tester, controller.handle()), 0);
5972            controller
5973        }
5974
5975        fn assert_page(tester: &WidgetTester, left: bool) {
5976            assert_eq!(
5977                find::text("LEFT CHILD").evaluate(tester).len(),
5978                usize::from(left)
5979            );
5980            assert_eq!(
5981                find::text("RIGHT CHILD").evaluate(tester).len(),
5982                usize::from(!left)
5983            );
5984        }
5985
5986        // 'TabBar left/right fling'.
5987        #[test]
5988        fn flinging_a_tab_bar_view_left_and_right_switches_its_tab() {
5989            test_widgets(|tester| {
5990                let controller = pump_left_right_app(tester);
5991
5992                // Fling to the left, switch from the 'LEFT' tab to the 'RIGHT'
5993                let fling_start = tester.get_center(text(tester, "LEFT CHILD"));
5994                tester.fling_from(fling_start, Offset::new(-200.0, 0.0), 10000.0, 1);
5995                tester.pump_and_settle();
5996                assert_eq!(index_of(tester, controller.handle()), 1);
5997                assert_page(tester, false);
5998
5999                // Fling to the right, switch back to the 'LEFT' tab
6000                let fling_start = tester.get_center(text(tester, "RIGHT CHILD"));
6001                tester.fling_from(fling_start, Offset::new(200.0, 0.0), 10000.0, 2);
6002                tester.pump_and_settle();
6003                assert_eq!(index_of(tester, controller.handle()), 0);
6004                assert_page(tester, true);
6005            });
6006        }
6007
6008        // 'TabBar left/right fling reverse (1)'.
6009        #[test]
6010        fn flinging_the_first_page_right_keeps_it() {
6011            test_widgets(|tester| {
6012                let controller = pump_left_right_app(tester);
6013
6014                let fling_start = tester.get_center(text(tester, "LEFT CHILD"));
6015                tester.fling_from(fling_start, Offset::new(200.0, 0.0), 10000.0, 1);
6016                tester.pump();
6017                tester.pump_by(Duration::from_secs(1)); // finish the scroll animation
6018                assert_eq!(index_of(tester, controller.handle()), 0);
6019                assert_page(tester, true);
6020            });
6021        }
6022
6023        // 'TabBar left/right fling reverse (2)' (the first of the two cases Dart names so).
6024        #[test]
6025        fn flinging_the_first_page_left_settles_on_the_second_after_one_second() {
6026            test_widgets(|tester| {
6027                let controller = pump_left_right_app(tester);
6028
6029                let fling_start = tester.get_center(text(tester, "LEFT CHILD"));
6030                tester.fling_from(fling_start, Offset::new(-200.0, 0.0), 10000.0, 1);
6031                tester.pump();
6032                // this is similar to a test above, but that one does many more pumps
6033                tester.pump_by(Duration::from_secs(1)); // finish the scroll animation
6034                assert_eq!(index_of(tester, controller.handle()), 1);
6035                assert_page(tester, false);
6036            });
6037        }
6038
6039        // 'TabBar left/right fling reverse (2)' (the second, a regression test for
6040        // https://github.com/flutter/flutter/issues/5095). Dart's two move loops run while
6041        // `index > 50` from 0, so never: the gesture is a down and an up.
6042        #[test]
6043        fn a_fling_ended_by_reversing_settles_back_on_its_first_page() {
6044            test_widgets(|tester| {
6045                let controller = pump_left_right_app(tester);
6046
6047                let fling_start = tester.get_center(text(tester, "LEFT CHILD"));
6048                let mut gesture = TestPointer::touch(1);
6049                tester.down(&mut gesture, fling_start);
6050                // End the fling by reversing direction. This should cause not cause
6051                // a change to the selected tab, everything should just settle back to
6052                // where it started.
6053                tester.up(&gesture);
6054                tester.pump();
6055                tester.pump_by(Duration::from_secs(1)); // finish the scroll animation
6056                assert_eq!(index_of(tester, controller.handle()), 0);
6057                assert_page(tester, true);
6058            });
6059        }
6060
6061        /// `TabControllerFrame(length:, initialIndex:, builder:)`: a controller made for the frame,
6062        /// with `TestVSync` where Dart's frame state is the vsync, and the frame `builder` builds.
6063        fn pump_tab_controller_frame(
6064            tester: &mut WidgetTester,
6065            length: usize,
6066            initial_index: usize,
6067            builder: impl FnOnce(Ref<TabController>) -> WidgetRef,
6068        ) -> Ref<TabController> {
6069            let controller = {
6070                let mut app = tester.cell.borrow_mut();
6071                TabController::new(&mut app, initial_index, None, length, TestVSync)
6072            };
6073            tester.pump_widget(builder(controller.clone()));
6074            controller
6075        }
6076
6077        /// The app Dart's `buildTabControllerFrame`s build: a scaffold with a tab bar of `tabs` and a
6078        /// tab bar view of `children`, on `platform`.
6079        fn tab_controller_frame_app(
6080            tester: &WidgetTester,
6081            platform: waft_embedder::TargetPlatform,
6082            tabs: &[&str],
6083            children: &[&str],
6084            controller: Ref<TabController>,
6085        ) -> WidgetRef {
6086            let theme = {
6087                let app = tester.cell.borrow();
6088                ThemeData::builder().platform(platform).build(&app)
6089            };
6090            material_app(
6091                theme,
6092                Scaffold::new()
6093                    .app_bar(waft_widgets::PreferredSizeWidgetRef::new(
6094                        AppBar::new().title(Text::new("tabs")).bottom(
6095                            waft_widgets::PreferredSizeWidgetRef::new(
6096                                TabBar::new(
6097                                    tabs.iter().map(|tab| Tab::new().text(*tab).into_widget()),
6098                                )
6099                                .controller(controller.clone()),
6100                            ),
6101                        ),
6102                    ))
6103                    .body(
6104                        TabBarView::new(
6105                            children
6106                                .iter()
6107                                .map(|child| Center::new().child(Text::new(*child)).into_widget()),
6108                        )
6109                        .controller(controller),
6110                    )
6111                    .into_widget(),
6112            )
6113        }
6114
6115        // 'TabController notifies the index to change when left flinging'.
6116        #[test]
6117        fn flinging_a_tab_bar_view_left_notifies_the_index_of_the_page_it_lands_on() {
6118            test_widgets(|tester| {
6119                let tabs = ["A", "B", "C"];
6120                let theme_tester = WidgetTester::on(waft_embedder::TargetPlatform::Android);
6121                let tab_controller =
6122                    pump_tab_controller_frame(tester, tabs.len(), 2, |controller| {
6123                        tab_controller_frame_app(
6124                            &theme_tester,
6125                            waft_embedder::TargetPlatform::IOS,
6126                            &tabs,
6127                            &["CHILD A", "CHILD B", "CHILD C"],
6128                            controller,
6129                        )
6130                    });
6131                assert_eq!(index_of(tester, tab_controller.handle()), 2);
6132
6133                let notified = Rc::new(RefCell::new(Vec::new()));
6134                let notified_in_listener = Rc::clone(&notified);
6135                let listened = tab_controller.handle();
6136                tab_controller.add_listener(
6137                    &mut tester.cell.borrow_mut(),
6138                    Listener::new(move |app: &mut App| {
6139                        notified_in_listener.borrow_mut().push(listened.index(app));
6140                    }),
6141                );
6142                let fling_start = tester.get_center(text(tester, "CHILD C"));
6143                tester.fling_from(fling_start, Offset::new(600.0, 0.0), 10000.0, 1);
6144                tester.pump_and_settle();
6145                let index_of_b = 1;
6146                for index in notified.borrow().iter() {
6147                    assert_eq!(*index, index_of_b);
6148                }
6149            });
6150        }
6151
6152        // 'TabBar fling velocity' (a regression test for https://github.com/flutter/flutter/issues/7133).
6153        #[test]
6154        fn a_small_slow_fling_of_a_scrollable_tab_bar_keeps_the_second_tab_visible() {
6155            test_widgets(|tester| {
6156                let theme = super::theme(tester, None, None);
6157                tester.pump_widget(material_app(
6158                    theme,
6159                    waft_widgets::Align::new()
6160                        .alignment(AlignmentGeometry::TOP_LEFT)
6161                        .child(
6162                            SizedBox::new().width(300.0).height(200.0).child(
6163                                DefaultTabController::new(
6164                                    TWELVE_TABS.len(),
6165                                    Scaffold::new()
6166                                        .app_bar(waft_widgets::PreferredSizeWidgetRef::new(
6167                                            AppBar::new().title(Text::new("tabs")).bottom(
6168                                                waft_widgets::PreferredSizeWidgetRef::new(
6169                                                    TabBar::new(TWELVE_TABS.iter().map(|tab| {
6170                                                        Tab::new().text(*tab).into_widget()
6171                                                    }))
6172                                                    .is_scrollable(true),
6173                                                ),
6174                                            ),
6175                                        ))
6176                                        .body(TabBarView::new((0..TWELVE_TABS.len()).map(
6177                                            |index| Text::new(index.to_string()).into_widget(),
6178                                        ))),
6179                                ),
6180                            ),
6181                        )
6182                        .into_widget(),
6183                ));
6184
6185                // After a small slow fling to the left, we expect the second item to still be visible.
6186                let start = tester.get_center(text(tester, "AAAAAA"));
6187                tester.fling_from(start, Offset::new(-25.0, 0.0), 100.0, 1);
6188                tester.pump();
6189                tester.pump_by(Duration::from_secs(1)); // finish the scroll animation
6190                let render = tester.render_box_of(text(tester, "BBBBBB"));
6191                let app = tester.cell.borrow();
6192                assert!(render.local_to_global(&app, Offset::ZERO, None).dx() > 0.0);
6193            });
6194        }
6195
6196        // 'TabController change notification'.
6197        #[test]
6198        fn a_tab_controller_notifies_its_listeners_of_taps_and_flings() {
6199            test_widgets(|tester| {
6200                let tabs = ["LEFT", "RIGHT"];
6201                let app = build_left_right_app(tester, tabs.to_vec(), "LEFT", true, None);
6202                tester.pump_widget(app);
6203                let controller = default_controller_of(tester, text(tester, "LEFT"));
6204                assert_eq!(index_of(tester, controller.handle()), 0);
6205
6206                let value = Rc::new(RefCell::new(None::<&'static str>));
6207                let value_in_listener = Rc::clone(&value);
6208                let listened = controller.handle();
6209                controller.add_listener(
6210                    &mut tester.cell.borrow_mut(),
6211                    Listener::new(move |app: &mut App| {
6212                        *value_in_listener.borrow_mut() = Some(tabs[listened.index(app)]);
6213                    }),
6214                );
6215
6216                let right = text(tester, "RIGHT");
6217                tap(tester, right);
6218                tester.pump_and_settle();
6219                assert_eq!(*value.borrow(), Some("RIGHT"));
6220
6221                let left = text(tester, "LEFT");
6222                tap(tester, left);
6223                tester.pump_and_settle();
6224                assert_eq!(*value.borrow(), Some("LEFT"));
6225
6226                let left_fling_start = tester.get_center(text(tester, "LEFT CHILD"));
6227                tester.fling_from(left_fling_start, Offset::new(-200.0, 0.0), 10000.0, 1);
6228                tester.pump_and_settle();
6229                assert_eq!(*value.borrow(), Some("RIGHT"));
6230
6231                let right_fling_start = tester.get_center(text(tester, "RIGHT CHILD"));
6232                tester.fling_from(right_fling_start, Offset::new(200.0, 0.0), 10000.0, 2);
6233                tester.pump_and_settle();
6234                assert_eq!(*value.borrow(), Some("LEFT"));
6235            });
6236        }
6237
6238        // 'Explicit TabController'.
6239        #[test]
6240        fn an_explicit_tab_controller_drives_its_tab_bar_view() {
6241            test_widgets(|tester| {
6242                let tabs = ["LEFT", "RIGHT"];
6243                let theme_tester = WidgetTester::on(waft_embedder::TargetPlatform::Android);
6244                let tab_controller =
6245                    pump_tab_controller_frame(tester, tabs.len(), 1, |controller| {
6246                        tab_controller_frame_app(
6247                            &theme_tester,
6248                            waft_embedder::TargetPlatform::Android,
6249                            &tabs,
6250                            &["LEFT CHILD", "RIGHT CHILD"],
6251                            controller,
6252                        )
6253                    });
6254
6255                expect(tester, &find::text("LEFT"), finds_one_widget());
6256                expect(tester, &find::text("RIGHT"), finds_one_widget());
6257                assert_page(tester, false);
6258                {
6259                    let app = tester.cell.borrow();
6260                    assert_eq!(tab_controller.index(&app), 1);
6261                    assert_eq!(tab_controller.previous_index(&app), 1);
6262                    assert!(!tab_controller.index_is_changing(&app));
6263                    let animation = tab_controller.animation(&app).expect("an animation");
6264                    assert_eq!(animation.value(&app), 1.0);
6265                    assert_eq!(animation.status(&app), AnimationStatus::Forward);
6266                }
6267
6268                tab_controller.set_index(&mut tester.cell.borrow_mut(), 0);
6269                tester.pump_by(Duration::from_millis(500));
6270                tester.pump_by(Duration::from_millis(500));
6271                assert_page(tester, true);
6272
6273                tab_controller.set_index(&mut tester.cell.borrow_mut(), 1);
6274                tester.pump_by(Duration::from_millis(500));
6275                tester.pump_by(Duration::from_millis(500));
6276                assert_page(tester, false);
6277            });
6278        }
6279
6280        // 'TabController listener resets index' (a regression test for the scenario in
6281        // https://github.com/flutter/flutter/pull/7387#pullrequestreview-15630946).
6282        #[test]
6283        fn an_animation_listener_that_resets_the_index_wins() {
6284            test_widgets(|tester| {
6285                let tabs = ["A", "B", "C"];
6286                let theme_tester = WidgetTester::on(waft_embedder::TargetPlatform::Android);
6287                let tab_controller =
6288                    pump_tab_controller_frame(tester, tabs.len(), 0, |controller| {
6289                        tab_controller_frame_app(
6290                            &theme_tester,
6291                            waft_embedder::TargetPlatform::Android,
6292                            &tabs,
6293                            &["CHILD A", "CHILD B", "CHILD C"],
6294                            controller,
6295                        )
6296                    });
6297
6298                let changing_in_listener = Rc::new(RefCell::new(Vec::new()));
6299                let changing = Rc::clone(&changing_in_listener);
6300                {
6301                    let mut app = tester.cell.borrow_mut();
6302                    let animation = tab_controller.animation(&app).expect("an animation");
6303                    animation.add_listener(
6304                        &mut app,
6305                        Listener::new({
6306                            let tab_controller = tab_controller.clone();
6307                            move |app: &mut App| {
6308                                let animation =
6309                                    tab_controller.animation(app).expect("an animation");
6310                                if animation.status(app) == AnimationStatus::Forward {
6311                                    tab_controller.set_index(app, 2);
6312                                }
6313                                changing
6314                                    .borrow_mut()
6315                                    .push(tab_controller.index_is_changing(app));
6316                            }
6317                        }),
6318                    );
6319                }
6320
6321                {
6322                    let app = tester.cell.borrow();
6323                    assert_eq!(tab_controller.index(&app), 0);
6324                    assert!(!tab_controller.index_is_changing(&app));
6325                }
6326
6327                tab_controller.animate_to(
6328                    &mut tester.cell.borrow_mut(),
6329                    1,
6330                    Some(Duration::from_millis(200)),
6331                    Some(Curves::linear()),
6332                );
6333                tester.pump();
6334                tester.pump_by(Duration::from_millis(300));
6335
6336                {
6337                    let app = tester.cell.borrow();
6338                    assert_eq!(tab_controller.index(&app), 2);
6339                    assert!(!tab_controller.index_is_changing(&app));
6340                }
6341                for changing in changing_in_listener.borrow().iter() {
6342                    assert!(*changing);
6343                }
6344            });
6345        }
6346
6347        // 'TabBar unselectedLabelColor control test'.
6348        #[test]
6349        fn the_label_colors_give_the_selected_and_unselected_tabs_their_icon_color() {
6350            test_widgets(|tester| {
6351                let controller = tab_controller(tester, 2);
6352                let first_color = Rc::new(RefCell::new(None::<Color>));
6353                let second_color = Rc::new(RefCell::new(None::<Color>));
6354                let first = Rc::clone(&first_color);
6355                let second = Rc::clone(&second_color);
6356                let theme = super::theme(tester, None, None);
6357                tester.pump_widget(boilerplate(
6358                    theme,
6359                    TextDirection::Ltr,
6360                    TabBar::new([
6361                        waft_widgets::Builder::new(move |app, context| {
6362                            *first.borrow_mut() = IconTheme::of(app, context)
6363                                .color
6364                                .as_ref()
6365                                .map(AnyColor::color);
6366                            Text::new("First").into_widget()
6367                        })
6368                        .into_widget(),
6369                        waft_widgets::Builder::new(move |app, context| {
6370                            *second.borrow_mut() = IconTheme::of(app, context)
6371                                .color
6372                                .as_ref()
6373                                .map(AnyColor::color);
6374                            Text::new("Second").into_widget()
6375                        })
6376                        .into_widget(),
6377                    ])
6378                    .controller(controller)
6379                    .label_color(Colors::GREEN.shade500())
6380                    .unselected_label_color(Colors::BLUE.shade500()),
6381                ));
6382
6383                assert_eq!(*first_color.borrow(), Some(Colors::GREEN.shade500()));
6384                assert_eq!(*second_color.borrow(), Some(Colors::BLUE.shade500()));
6385            });
6386        }
6387
6388        // 'TabBar animationDuration sets indicator animation duration'.
6389        #[test]
6390        fn a_tab_bar_animates_its_selection_over_the_controllers_animation_duration() {
6391            test_widgets(|tester| {
6392                let animation_duration = Duration::from_millis(100);
6393                let build = |tester: &WidgetTester| {
6394                    let mut frame = Frame::new(vec!["A", "B", "C"], "B");
6395                    frame.animation_duration = Some(animation_duration);
6396                    frame.build(tester)
6397                };
6398
6399                let frame = build(tester);
6400                tester.pump_widget(frame);
6401                let controller = default_controller_of(tester, text(tester, "A"));
6402
6403                let a = text(tester, "A");
6404                tap(tester, a);
6405                tester.pump();
6406                assert!(controller.index_is_changing(&tester.cell.borrow()));
6407                tester.pump_by(Duration::from_millis(50));
6408                tester.pump_by(animation_duration);
6409                {
6410                    let app = tester.cell.borrow();
6411                    assert_eq!(controller.index(&app), 0);
6412                    assert_eq!(controller.previous_index(&app), 1);
6413                    assert!(!controller.index_is_changing(&app));
6414                }
6415
6416                //Test when index diff is greater than 1
6417                let frame = build(tester);
6418                tester.pump_widget(frame);
6419                let c = text(tester, "C");
6420                tap(tester, c);
6421                tester.pump();
6422                assert!(controller.index_is_changing(&tester.cell.borrow()));
6423                tester.pump_by(Duration::from_millis(50));
6424                tester.pump_by(animation_duration);
6425                {
6426                    let app = tester.cell.borrow();
6427                    assert_eq!(controller.index(&app), 2);
6428                    assert_eq!(controller.previous_index(&app), 0);
6429                    assert!(!controller.index_is_changing(&app));
6430                }
6431            });
6432        }
6433
6434        // 'tab semantics role test' (a regression test for
6435        // https://github.com/flutter/flutter/issues/169175): a tab whose icon is a zero-size image
6436        // semantics node builds. The semantics tree it made Dart throw on is deferred.
6437        #[test]
6438        fn a_tab_whose_icon_is_a_zero_size_image_builds() {
6439            test_widgets(|tester| {
6440                let theme = super::theme(tester, None, None);
6441                tester.pump_widget(boilerplate(
6442                    theme,
6443                    TextDirection::Ltr,
6444                    DefaultTabController::new(
6445                        1,
6446                        TabBar::new([Tab::new()
6447                            .icon(Semantics::new().image(true).child(SizedBox::shrink()))
6448                            .into_widget()]),
6449                    ),
6450                ));
6451                expect(tester, &find::by_type::<Tab>(), finds_one_widget());
6452            });
6453        }
6454    }
6455
6456    mod tab_bar_views_and_scroll_controllers {
6457        //! tabs_test.dart cases, part b: `ensureVisible does not move TabViews` through
6458        //! `Indicator elastic animation`.
6459
6460        use waft_rendering::testing::{PaintCall, assert_paints};
6461
6462        use super::*;
6463
6464        use waft_foundation::ValueKey;
6465        use waft_widgets::ScrollableState;
6466
6467        use crate::test_support::PaintInspection;
6468        use waft_widgets::testing::TestVSync;
6469
6470        /// Dart's `createTabController(length:, vsync: const TestVSync(), initialIndex:,
6471        /// animationDuration:)`.
6472        fn create_tab_controller(
6473            tester: &WidgetTester,
6474            length: usize,
6475            initial_index: usize,
6476            animation_duration: Option<Duration>,
6477        ) -> Ref<TabController> {
6478            let mut app = tester.cell.borrow_mut();
6479            TabController::new(
6480                &mut app,
6481                initial_index,
6482                animation_duration,
6483                length,
6484                TestVSync,
6485            )
6486        }
6487
6488        /// `tabs.map((String tab) => Tab(text: tab)).toList()`.
6489        fn text_tabs(tabs: &[&str]) -> Vec<WidgetRef> {
6490            tabs.iter()
6491                .map(|tab| Tab::new().text(*tab).into_widget())
6492                .collect()
6493        }
6494
6495        /// A string `Key(key)`.
6496        fn key(key: impl Into<String>) -> KeyRef {
6497            ValueKey::new(key.into()).into()
6498        }
6499
6500        /// `boilerplate(child: child)` with Dart's default theme and a left-to-right direction.
6501        fn boilerplate_ltr<K>(tester: &WidgetTester, child: impl IntoWidget<K>) -> WidgetRef {
6502            let theme = theme(tester, None, None);
6503            boilerplate(theme, TextDirection::Ltr, child)
6504        }
6505
6506        /// The `Column` of a `TabBar` over a 400 square `TabBarView` of three centred texts that
6507        /// several cases build.
6508        fn bar_over_view(
6509            tabs: &[&str],
6510            controller: Ref<TabController>,
6511            view: TabBarView,
6512        ) -> Column {
6513            Column::new().children([
6514                TabBar::new(text_tabs(tabs))
6515                    .controller(controller.clone())
6516                    .into_widget(),
6517                SizedBox::square(Some(400.0))
6518                    .child(view.controller(controller))
6519                    .into_widget(),
6520            ])
6521        }
6522
6523        /// `const <Widget>[Center(child: Text('0')), ..]` for `count` pages.
6524        fn numbered_pages(count: usize) -> Vec<WidgetRef> {
6525            (0..count)
6526                .map(|index| {
6527                    Center::new()
6528                        .child(Text::new(index.to_string()))
6529                        .into_widget()
6530                })
6531                .collect()
6532        }
6533
6534        /// The `PageView`'s controller: Dart's `tester.widget<PageView>(find.byType(PageView))
6535        /// .controller!`.
6536        fn page_controller(tester: &WidgetTester) -> Ref<PageController> {
6537            tester.widget(only::<PageView>(tester), |page_view: &PageView| {
6538                page_view
6539                    .controller
6540                    .clone()
6541                    .expect("a TabBarView's PageView has a controller")
6542            })
6543        }
6544
6545        /// `pageController.position.pixels`.
6546        fn pixels(tester: &WidgetTester, controller: Handle<PageController>) -> f64 {
6547            let app = tester.cell.borrow();
6548            controller.position(&app).pixels(&app)
6549        }
6550
6551        fn index(tester: &WidgetTester, controller: Handle<TabController>) -> usize {
6552            controller.index(&tester.cell.borrow())
6553        }
6554
6555        // 'TabBarView controller sets animation duration'.
6556        #[test]
6557        fn a_tab_bar_view_animates_for_its_controller_s_duration() {
6558            test_widgets(|tester| {
6559                let animation_duration = Duration::from_millis(100);
6560                let tabs = ["A", "B", "C"];
6561                let tab_controller = create_tab_controller(tester, 3, 1, Some(animation_duration));
6562                let frame = boilerplate_ltr(
6563                    tester,
6564                    bar_over_view(
6565                        &tabs,
6566                        tab_controller.clone(),
6567                        TabBarView::new(numbered_pages(3)),
6568                    ),
6569                );
6570                tester.pump_widget(frame);
6571
6572                assert_eq!(index(tester, tab_controller.handle()), 1);
6573
6574                let page_controller = page_controller(tester);
6575
6576                // The TabBarView's page width is 400, so page 0 is at scroll offset 0.0,
6577                // page 1 is at 400.0, page 2 is at 800.0.
6578                assert_eq!(pixels(tester, page_controller.handle()), 400.0);
6579                let c = text(tester, "C");
6580                tap(tester, c);
6581                tester.pump();
6582                assert_eq!(pixels(tester, page_controller.handle()), 400.0);
6583                tester.pump_by(Duration::from_millis(50));
6584                tester.pump_by(animation_duration);
6585                assert_eq!(pixels(tester, page_controller.handle()), 800.0);
6586            });
6587        }
6588
6589        // 'TabBarView animation can be interrupted'.
6590        #[test]
6591        fn a_tab_bar_view_animation_can_be_interrupted() {
6592            test_widgets(|tester| {
6593                let animation_duration = Duration::from_secs(2);
6594                let tabs = ["A", "B", "C"];
6595                let tab_controller = create_tab_controller(tester, 3, 0, Some(animation_duration));
6596                let frame = boilerplate_ltr(
6597                    tester,
6598                    bar_over_view(
6599                        &tabs,
6600                        tab_controller.clone(),
6601                        TabBarView::new(numbered_pages(3)),
6602                    ),
6603                );
6604                tester.pump_widget(frame);
6605
6606                assert_eq!(index(tester, tab_controller.handle()), 0);
6607
6608                let page_controller = page_controller(tester);
6609
6610                assert_eq!(pixels(tester, page_controller.handle()), 0.0);
6611
6612                let c = text(tester, "C");
6613                tap(tester, c);
6614                tester.pump_by(Duration::from_millis(10)); // TODO(bleroux): find why this is needed.
6615
6616                // Runs the animation for half of the animation duration.
6617                tester.pump_by(Duration::from_secs(1));
6618
6619                // The position should be between page 1 and page 2.
6620                let position = pixels(tester, page_controller.handle());
6621                assert!(position > 400.0, "{position}");
6622                assert!(position < 800.0, "{position}");
6623
6624                // Switch to another tab before the end of the animation.
6625                let a = text(tester, "A");
6626                tap(tester, a);
6627                tester.pump_by(Duration::from_millis(10)); // TODO(bleroux): find why this is needed.
6628                tester.pump_by(animation_duration);
6629                assert_eq!(pixels(tester, page_controller.handle()), 0.0);
6630
6631                tester.pump_and_settle(); // Finish the animation.
6632            });
6633        }
6634
6635        // 'TabBarView viewportFraction sets PageView viewport fraction'.
6636        #[test]
6637        fn a_tab_bar_view_gives_its_page_view_its_viewport_fraction() {
6638            test_widgets(|tester| {
6639                let tabs = ["A", "B", "C"];
6640                let tab_controller =
6641                    create_tab_controller(tester, 3, 1, Some(Duration::from_millis(100)));
6642                let frame = boilerplate_ltr(
6643                    tester,
6644                    bar_over_view(
6645                        &tabs,
6646                        tab_controller.clone(),
6647                        TabBarView::new(numbered_pages(3)).viewport_fraction(0.8),
6648                    ),
6649                );
6650                tester.pump_widget(frame);
6651
6652                assert_eq!(index(tester, tab_controller.handle()), 1);
6653
6654                // The TabView was initialized with viewportFraction as 0.8
6655                // So it's expected the PageView inside would obtain the same viewportFraction
6656                let page_controller = page_controller(tester);
6657                assert_eq!(
6658                    page_controller.viewport_fraction(&tester.cell.borrow()),
6659                    0.8
6660                );
6661            });
6662        }
6663
6664        // 'TabBarView viewportFraction is 1 by default'.
6665        #[test]
6666        fn a_tab_bar_view_s_viewport_fraction_is_1_by_default() {
6667            test_widgets(|tester| {
6668                let tabs = ["A", "B", "C"];
6669                let tab_controller =
6670                    create_tab_controller(tester, 3, 1, Some(Duration::from_millis(100)));
6671                let frame = boilerplate_ltr(
6672                    tester,
6673                    bar_over_view(
6674                        &tabs,
6675                        tab_controller.clone(),
6676                        TabBarView::new(numbered_pages(3)),
6677                    ),
6678                );
6679                tester.pump_widget(frame);
6680
6681                assert_eq!(index(tester, tab_controller.handle()), 1);
6682
6683                // The TabView was initialized with default viewportFraction
6684                // So it's expected the PageView inside would obtain the value 1
6685                let page_controller = page_controller(tester);
6686                assert_eq!(
6687                    page_controller.viewport_fraction(&tester.cell.borrow()),
6688                    1.0
6689                );
6690            });
6691        }
6692
6693        // 'TabBarView viewportFraction can be updated'.
6694        #[test]
6695        fn a_tab_bar_view_s_viewport_fraction_can_be_updated() {
6696            test_widgets(|tester| {
6697                let tabs = ["A", "B", "C"];
6698                let build_frame = |tester: &WidgetTester, viewport_fraction: f64| {
6699                    let controller = create_tab_controller(tester, 3, 1, None);
6700                    boilerplate_ltr(
6701                        tester,
6702                        bar_over_view(
6703                            &tabs,
6704                            controller.clone(),
6705                            TabBarView::new(numbered_pages(3)).viewport_fraction(viewport_fraction),
6706                        ),
6707                    )
6708                };
6709
6710                let frame = build_frame(tester, 0.8);
6711                tester.pump_widget(frame);
6712                let controller = page_controller(tester);
6713                assert_eq!(controller.viewport_fraction(&tester.cell.borrow()), 0.8);
6714
6715                // Rebuild with a different viewport fraction.
6716                let frame = build_frame(tester, 0.5);
6717                tester.pump_widget(frame);
6718                let controller = page_controller(tester);
6719                assert_eq!(controller.viewport_fraction(&tester.cell.borrow()), 0.5);
6720            });
6721        }
6722
6723        // 'TabBarView has clipBehavior Clip.hardEdge by default'.
6724        #[test]
6725        fn a_tab_bar_view_clips_hard_edge_by_default() {
6726            test_widgets(|tester| {
6727                let tabs = || {
6728                    vec![
6729                        Text::new("First").into_widget(),
6730                        Text::new("Second").into_widget(),
6731                    ]
6732                };
6733                let frame = boilerplate_ltr(
6734                    tester,
6735                    DefaultTabController::new(2, TabBarView::new(tabs())),
6736                );
6737                tester.pump_widget(frame);
6738                let clip_behavior = tester
6739                    .widget(only::<TabBarView>(tester), |view: &TabBarView| {
6740                        view.clip_behavior
6741                    });
6742                assert_eq!(clip_behavior, Clip::HardEdge);
6743            });
6744        }
6745
6746        // 'TabBarView sets clipBehavior correctly'.
6747        #[test]
6748        fn a_tab_bar_view_gives_its_page_view_its_clip_behavior() {
6749            test_widgets(|tester| {
6750                let tabs = vec![
6751                    Text::new("First").into_widget(),
6752                    Text::new("Second").into_widget(),
6753                ];
6754                let frame = boilerplate_ltr(
6755                    tester,
6756                    DefaultTabController::new(2, TabBarView::new(tabs).clip_behavior(Clip::None)),
6757                );
6758                tester.pump_widget(frame);
6759                let clip_behavior = tester.widget(only::<PageView>(tester), |view: &PageView| {
6760                    view.clip_behavior
6761                });
6762                assert_eq!(clip_behavior, Clip::None);
6763            });
6764        }
6765
6766        /// tabs_utils' `TabIndicatorRecordingCanvas`: the rect of the last line `render` paints in
6767        /// `indicator_color`, inflated by half its 2.0 weight.
6768        fn recorded_indicator_rect(
6769            tester: &WidgetTester,
6770            render: AnyRenderBox,
6771            indicator_color: Color,
6772        ) -> Rect {
6773            const INDICATOR_WEIGHT: f64 = 2.0;
6774            let line = painted_lines(tester, render.as_object())
6775                .into_iter()
6776                .rfind(|line| line.color.to_argb32() == indicator_color.to_argb32())
6777                .expect("an indicator line");
6778            Rect::from_points(line.p1, line.p2).inflate(INDICATOR_WEIGHT / 2.0)
6779        }
6780
6781        // 'TabBar tap skips indicator animation when disabled in controller'.
6782        #[test]
6783        fn a_tap_moves_the_indicator_at_once_when_the_controller_does_not_animate() {
6784            test_widgets(|tester| {
6785                let tabs = vec!["A", "B"];
6786                let indicator_color = Color::new(0xFFFF0000);
6787                let mut frame = Frame::new(tabs, "A");
6788                frame.use_material3 = Some(false);
6789                frame.indicator_color = Some(indicator_color);
6790                frame.animation_duration = Some(Duration::ZERO);
6791                let frame = frame.build(tester);
6792                tester.pump_widget(frame);
6793
6794                let render = first_render_box::<TabBar>(tester);
6795                let indicator_rect0 = recorded_indicator_rect(tester, render, indicator_color);
6796                assert_eq!(indicator_rect0.left, 0.0);
6797                assert_eq!(indicator_rect0.width(), 400.0);
6798                assert_eq!(indicator_rect0.height(), 2.0);
6799
6800                let b = text(tester, "B");
6801                tap(tester, b);
6802                tester.pump();
6803                let indicator_rect2 = recorded_indicator_rect(tester, render, indicator_color);
6804                assert_eq!(indicator_rect2.left, 400.0);
6805                assert_eq!(indicator_rect2.width(), 400.0);
6806                assert_eq!(indicator_rect2.height(), 2.0);
6807            });
6808        }
6809
6810        // 'TabBar tap changes index instantly when animation is disabled in controller'.
6811        #[test]
6812        fn a_tap_changes_the_index_at_once_when_the_controller_does_not_animate() {
6813            test_widgets(|tester| {
6814                let tabs = vec!["A", "B", "C"];
6815                let frame = |tester: &WidgetTester| {
6816                    let mut frame = Frame::new(tabs.clone(), "B");
6817                    frame.animation_duration = Some(Duration::ZERO);
6818                    frame.build(tester)
6819                };
6820                let built = frame(tester);
6821                tester.pump_widget(built);
6822                let controller = default_controller_of(tester, text(tester, "A"));
6823
6824                let a = text(tester, "A");
6825                tap(tester, a);
6826                tester.pump();
6827                {
6828                    let app = tester.cell.borrow();
6829                    assert_eq!(controller.index(&app), 0);
6830                    assert_eq!(controller.previous_index(&app), 1);
6831                    assert!(!controller.index_is_changing(&app));
6832                }
6833
6834                //Test when index diff is greater than 1
6835                let built = frame(tester);
6836                tester.pump_widget(built);
6837                let c = text(tester, "C");
6838                tap(tester, c);
6839                tester.pump();
6840                {
6841                    let app = tester.cell.borrow();
6842                    assert_eq!(controller.index(&app), 2);
6843                    assert_eq!(controller.previous_index(&app), 0);
6844                    assert!(!controller.index_is_changing(&app));
6845                }
6846            });
6847        }
6848
6849        // 'Scrollable TabBar does not have overscroll indicator'.
6850        #[test]
6851        fn a_scrollable_tab_bar_has_no_overscroll_indicator() {
6852            test_widgets(|tester| {
6853                let mut frame = Frame::new(vec!["A", "B", "C"], "A");
6854                frame.is_scrollable = true;
6855                let frame = frame.build(tester);
6856                tester.pump_widget(frame);
6857                assert!(
6858                    find::by_type::<waft_widgets::GlowingOverscrollIndicator>()
6859                        .evaluate(tester)
6860                        .is_empty()
6861                );
6862            });
6863        }
6864
6865        // 'TabBar should not throw when animation is disabled in controller'.
6866        #[test]
6867        fn tabs_added_to_a_tab_bar_whose_controller_does_not_animate_can_be_selected() {
6868            test_widgets(|tester| {
6869                let mut tabs = vec!["A"];
6870
6871                let build_with_tab_bar_view = |tester: &WidgetTester, tabs: &[&'static str]| {
6872                    boilerplate_ltr(
6873                        tester,
6874                        DefaultTabController::new(
6875                            tabs.len(),
6876                            Column::new().children([
6877                                TabBar::new(text_tabs(tabs))
6878                                    .is_scrollable(true)
6879                                    .into_widget(),
6880                                waft_widgets::Flexible::new(TabBarView::new(
6881                                    (0..tabs.len()).map(|index| {
6882                                        Text::new(format!("Tab {index}")).into_widget()
6883                                    }),
6884                                ))
6885                                .into_widget(),
6886                            ]),
6887                        )
6888                        .animation_duration(Duration::ZERO),
6889                    )
6890                };
6891
6892                let frame = build_with_tab_bar_view(tester, &tabs);
6893                tester.pump_widget(frame);
6894                let controller = default_controller_of(tester, text(tester, "A"));
6895                assert_eq!(index(tester, controller.handle()), 0);
6896
6897                tabs.push("B");
6898                let frame = build_with_tab_bar_view(tester, &tabs);
6899                tester.pump_widget(frame);
6900                tabs.push("C");
6901                let frame = build_with_tab_bar_view(tester, &tabs);
6902                tester.pump_widget(frame);
6903                let c = text(tester, "C");
6904                tap(tester, c);
6905                tester.pump_and_settle();
6906                let controller = default_controller_of(tester, text(tester, "A"));
6907                assert_eq!(index(tester, controller.handle()), 2);
6908            });
6909        }
6910
6911        /// The `TabBar` over a 400 square `TabBarView` of `tabs.len()` pages whose controller does
6912        /// not animate, that the skip-animation cases build; answers the controller.
6913        fn pump_unanimated_tabs(
6914            tester: &mut WidgetTester,
6915            tabs: &[&str],
6916            initial_index: usize,
6917        ) -> Ref<TabController> {
6918            let tab_controller =
6919                create_tab_controller(tester, tabs.len(), initial_index, Some(Duration::ZERO));
6920            let frame = boilerplate_ltr(
6921                tester,
6922                bar_over_view(
6923                    tabs,
6924                    tab_controller.clone(),
6925                    TabBarView::new(numbered_pages(tabs.len())),
6926                ),
6927            );
6928            tester.pump_widget(frame);
6929            tab_controller
6930        }
6931
6932        // 'TabBarView skips animation when disabled in controller'.
6933        #[test]
6934        fn a_tab_bar_view_jumps_when_its_controller_does_not_animate() {
6935            test_widgets(|tester| {
6936                let tab_controller = pump_unanimated_tabs(tester, &["A", "B", "C"], 1);
6937
6938                assert_eq!(index(tester, tab_controller.handle()), 1);
6939
6940                let page_controller = page_controller(tester);
6941
6942                // The TabBarView's page width is 400, so page 0 is at scroll offset 0.0,
6943                // page 1 is at 400.0, page 2 is at 800.0.
6944                assert_eq!(pixels(tester, page_controller.handle()), 400.0);
6945                tester.tap(find::text("C"));
6946                tester.pump();
6947                assert_eq!(pixels(tester, page_controller.handle()), 800.0);
6948            });
6949        }
6950
6951        // 'TabBarView skips animation when disabled in controller - skip tabs'.
6952        #[test]
6953        fn a_tab_bar_view_jumps_over_tabs_when_its_controller_does_not_animate() {
6954            test_widgets(|tester| {
6955                let tab_controller = pump_unanimated_tabs(tester, &["A", "B", "C"], 0);
6956
6957                assert_eq!(index(tester, tab_controller.handle()), 0);
6958
6959                let page_controller = page_controller(tester);
6960
6961                // The TabBarView's page width is 400, so page 0 is at scroll offset 0.0,
6962                // page 1 is at 400.0, page 2 is at 800.0.
6963                assert_eq!(pixels(tester, page_controller.handle()), 0.0);
6964                tester.tap(find::text("C"));
6965                tester.pump();
6966                assert_eq!(pixels(tester, page_controller.handle()), 800.0);
6967            });
6968        }
6969
6970        // 'TabBarView skips animation when disabled in controller - skip tabs twice'.
6971        #[test]
6972        fn a_tab_bar_view_jumps_over_tabs_twice_when_its_controller_does_not_animate() {
6973            test_widgets(|tester| {
6974                let tab_controller = pump_unanimated_tabs(tester, &["A", "B", "C"], 0);
6975
6976                assert_eq!(index(tester, tab_controller.handle()), 0);
6977
6978                let page_controller = page_controller(tester);
6979
6980                // The TabBarView's page width is 400, so page 0 is at scroll offset 0.0,
6981                // page 1 is at 400.0, page 2 is at 800.0.
6982                assert_eq!(pixels(tester, page_controller.handle()), 0.0);
6983                tester.tap(find::text("C"));
6984                tester.pump();
6985                assert_eq!(pixels(tester, page_controller.handle()), 800.0);
6986
6987                tester.tap(find::text("A"));
6988                tester.pump();
6989                assert_eq!(pixels(tester, page_controller.handle()), 0.0);
6990            });
6991        }
6992
6993        // 'TabBarView skips animation when disabled in controller - skip tabs followed by single tab navigation'.
6994        #[test]
6995        fn a_tab_bar_view_jumps_over_tabs_then_to_neighbours_when_its_controller_does_not_animate()
6996        {
6997            test_widgets(|tester| {
6998                let tab_controller = pump_unanimated_tabs(tester, &["A", "B", "C"], 0);
6999
7000                assert_eq!(index(tester, tab_controller.handle()), 0);
7001
7002                let page_controller = page_controller(tester);
7003
7004                // The TabBarView's page width is 400, so page 0 is at scroll offset 0.0,
7005                // page 1 is at 400.0, page 2 is at 800.0.
7006                assert_eq!(pixels(tester, page_controller.handle()), 0.0);
7007                tester.tap(find::text("C"));
7008                tester.pump();
7009                assert_eq!(pixels(tester, page_controller.handle()), 800.0);
7010
7011                tester.tap(find::text("B"));
7012                tester.pump();
7013                assert_eq!(pixels(tester, page_controller.handle()), 400.0);
7014
7015                tester.tap(find::text("A"));
7016                tester.pump();
7017                assert_eq!(pixels(tester, page_controller.handle()), 0.0);
7018            });
7019        }
7020
7021        // 'TabBarView skips animation when disabled in controller - two tabs'.
7022        #[test]
7023        fn a_two_tab_bar_view_jumps_when_its_controller_does_not_animate() {
7024            test_widgets(|tester| {
7025                let tab_controller = pump_unanimated_tabs(tester, &["A", "B"], 0);
7026
7027                assert_eq!(index(tester, tab_controller.handle()), 0);
7028
7029                let page_controller = page_controller(tester);
7030
7031                // The TabBarView's page width is 400, so page 0 is at scroll offset 0.0,
7032                // page 1 is at 400.0, page 2 is at 800.0.
7033                assert_eq!(pixels(tester, page_controller.handle()), 0.0);
7034                tester.tap(find::text("B"));
7035                tester.pump();
7036                assert_eq!(pixels(tester, page_controller.handle()), 400.0);
7037            });
7038        }
7039
7040        // 'TabBar tap animates the selection indicator'.
7041        #[test]
7042        fn a_tap_animates_the_selection_indicator() {
7043            test_widgets(|tester| {
7044                // This is a regression test for https://github.com/flutter/flutter/issues/7479
7045                let indicator_color = Color::new(0xFFFF0000);
7046                let mut frame = Frame::new(vec!["A", "B"], "A");
7047                frame.use_material3 = Some(false);
7048                frame.indicator_color = Some(indicator_color);
7049                let frame = frame.build(tester);
7050                tester.pump_widget(frame);
7051
7052                let render = first_render_box::<TabBar>(tester);
7053                let indicator_rect0 = recorded_indicator_rect(tester, render, indicator_color);
7054                assert_eq!(indicator_rect0.left, 0.0);
7055                assert_eq!(indicator_rect0.width(), 400.0);
7056                assert_eq!(indicator_rect0.height(), 2.0);
7057
7058                tester.tap(find::text("B"));
7059                tester.pump();
7060                tester.pump_by(Duration::from_millis(50));
7061                let indicator_rect1 = recorded_indicator_rect(tester, render, indicator_color);
7062                assert!(
7063                    indicator_rect1.left > indicator_rect0.left,
7064                    "{indicator_rect1:?}"
7065                );
7066                assert!(indicator_rect1.right < 800.0, "{indicator_rect1:?}");
7067                assert_eq!(indicator_rect1.height(), 2.0);
7068
7069                tester.pump_by(Duration::from_millis(300));
7070                let indicator_rect2 = recorded_indicator_rect(tester, render, indicator_color);
7071                assert_eq!(indicator_rect2.left, 400.0);
7072                assert_eq!(indicator_rect2.width(), 400.0);
7073                assert_eq!(indicator_rect2.height(), 2.0);
7074            });
7075        }
7076
7077        // 'TabBarView child disposed during animation'.
7078        #[test]
7079        fn a_replaced_tab_bar_stops_listening_to_the_controller() {
7080            test_widgets(|tester| {
7081                // This is a regression test for this patch:
7082                // https://github.com/flutter/flutter/pull/9015
7083                let controller = create_tab_controller(tester, 2, 0, None);
7084
7085                let build_frame = |tester: &WidgetTester| {
7086                    boilerplate_ltr(
7087                        tester,
7088                        TabBar::new([Text::new("A").into_widget(), Text::new("B").into_widget()])
7089                            .key(GlobalKey::new().into())
7090                            .controller(controller.clone()),
7091                    )
7092                };
7093
7094                let frame = build_frame(tester);
7095                tester.pump_widget(frame);
7096
7097                // The original TabBar will be disposed. The controller should no
7098                // longer have any listeners from the original TabBar.
7099                let frame = build_frame(tester);
7100                tester.pump_widget(frame);
7101
7102                controller.set_index(&mut tester.cell.borrow_mut(), 1);
7103                tester.pump_by(Duration::from_millis(300));
7104            });
7105        }
7106
7107        /// tabs_utils' `TabBody`: a page that logs its state's `init` and `dispose`.
7108        #[derive(Debug)]
7109        struct TabBody {
7110            index: usize,
7111            log: Rc<RefCell<Vec<String>>>,
7112            marker: String,
7113        }
7114
7115        impl StatefulWidget for TabBody {
7116            type State = TabBodyState;
7117
7118            fn create_state(&self) -> TabBodyState {
7119                TabBodyState {
7120                    state: StateData::new(),
7121                }
7122            }
7123        }
7124
7125        struct TabBodyState {
7126            state: StateData<TabBody>,
7127        }
7128
7129        impl State for TabBodyState {
7130            type Widget = TabBody;
7131            waft_widgets::state_accessors!();
7132
7133            fn init_state(self: Handle<Self>, app: &mut App) {
7134                let widget = self.widget(app);
7135                widget
7136                    .log
7137                    .borrow_mut()
7138                    .push(format!("init: {}", widget.index));
7139            }
7140
7141            fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &TabBody) {
7142                assert_eq!(old_widget.index, self.widget(app).index);
7143            }
7144
7145            fn dispose(self: Handle<Self>, app: &mut App) {
7146                let widget = self.widget(app);
7147                widget
7148                    .log
7149                    .borrow_mut()
7150                    .push(format!("dispose: {}", widget.index));
7151            }
7152
7153            fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
7154                let widget = self.widget(app);
7155                let label = if widget.marker.is_empty() {
7156                    widget.index.to_string()
7157                } else {
7158                    format!("{}-{}", widget.index, widget.marker)
7159                };
7160                Center::new().child(Text::new(label)).into_widget()
7161            }
7162        }
7163
7164        /// The `TabBarView children updated` group's `buildFrameWithMarker`.
7165        fn build_frame_with_marker(
7166            tester: &WidgetTester,
7167            log: &Rc<RefCell<Vec<String>>>,
7168            marker: &str,
7169        ) -> WidgetRef {
7170            let theme = theme(tester, None, None);
7171            material_app(
7172                theme,
7173                DefaultTabController::new(
7174                    3,
7175                    Scaffold::new()
7176                        .app_bar(waft_widgets::PreferredSizeWidgetRef::new(
7177                            AppBar::new()
7178                                .bottom(waft_widgets::PreferredSizeWidgetRef::new(TabBar::new(
7179                                    text_tabs(&["A", "B", "C"]),
7180                                )))
7181                                .title(Text::new("Tabs Test")),
7182                        ))
7183                        .body(TabBarView::new((0..3).map(|index| {
7184                            TabBody {
7185                                index,
7186                                log: Rc::clone(log),
7187                                marker: marker.to_owned(),
7188                            }
7189                            .into_widget()
7190                        }))),
7191                )
7192                .animation_duration(Duration::from_secs(1))
7193                .into_widget(),
7194            )
7195        }
7196
7197        // 'TabBarView children can be updated during animation to an adjacent tab'.
7198        #[test]
7199        fn tab_bar_view_children_can_be_updated_while_it_animates_to_an_adjacent_tab() {
7200            test_widgets(|tester| {
7201                // Regression test for https://github.com/flutter/flutter/issues/107399
7202                let log = Rc::new(RefCell::new(Vec::new()));
7203
7204                let initial_marker = "before";
7205                let frame = build_frame_with_marker(tester, &log, initial_marker);
7206                tester.pump_widget(frame);
7207                assert_eq!(*log.borrow(), ["init: 0"]);
7208                expect(tester, &find::text("0-before"), finds_one_widget());
7209
7210                // Select the second tab and wait until the transition starts
7211                tester.tap(find::text("B"));
7212                tester.pump_by(Duration::from_millis(100));
7213
7214                // Check that both TabBody's are instantiated while the transition is animating
7215                tester.pump_by(Duration::from_millis(400));
7216                assert_eq!(*log.borrow(), ["init: 0", "init: 1"]);
7217
7218                // Update the TabBody's states while the transition is animating
7219                let updated_marker = "after";
7220                let frame = build_frame_with_marker(tester, &log, updated_marker);
7221                tester.pump_widget(frame);
7222
7223                // Wait until the transition ends
7224                tester.pump_and_settle();
7225
7226                // The TabBody state of the second TabBar should have been updated
7227                expect(tester, &find::text("1-before"), finds_nothing());
7228                expect(tester, &find::text("1-after"), finds_one_widget());
7229            });
7230        }
7231
7232        // 'TabBarView children can be updated during animation to a non adjacent tab'.
7233        #[test]
7234        fn tab_bar_view_children_can_be_updated_while_it_animates_to_a_non_adjacent_tab() {
7235            test_widgets(|tester| {
7236                let log = Rc::new(RefCell::new(Vec::new()));
7237
7238                let initial_marker = "before";
7239                let frame = build_frame_with_marker(tester, &log, initial_marker);
7240                tester.pump_widget(frame);
7241                assert_eq!(*log.borrow(), ["init: 0"]);
7242                expect(tester, &find::text("0-before"), finds_one_widget());
7243
7244                // Select the third tab and wait until the transition starts
7245                tester.tap(find::text("C"));
7246                tester.pump_by(Duration::from_millis(100));
7247
7248                // Check that both TabBody's are instantiated while the transition is animating
7249                tester.pump_by(Duration::from_millis(400));
7250                assert_eq!(*log.borrow(), ["init: 0", "init: 2"]);
7251
7252                // Update the TabBody's states while the transition is animating
7253                let updated_marker = "after";
7254                let frame = build_frame_with_marker(tester, &log, updated_marker);
7255                tester.pump_widget(frame);
7256
7257                // Wait until the transition ends
7258                tester.pump_and_settle();
7259
7260                // The TabBody state of the third TabBar should have been updated
7261                expect(tester, &find::text("2-before"), finds_nothing());
7262                expect(tester, &find::text("2-after"), finds_one_widget());
7263            });
7264        }
7265
7266        /// The centred 400 square `TabBarView` of three pages, under only a `Directionality`, that the
7267        /// scrolls-end cases build.
7268        fn centered_tab_bar_view(view: TabBarView) -> WidgetRef {
7269            Directionality::new(
7270                TextDirection::Ltr,
7271                SizedBox::expand()
7272                    .child(Center::new().child(SizedBox::square(Some(400.0)).child(view))),
7273            )
7274            .into_widget()
7275        }
7276
7277        /// The scrolls-end cases' body: jumps near the pages and checks the index the jumps settle.
7278        fn check_jumps_close_to_a_new_page(
7279            tester: &mut WidgetTester,
7280            tab_controller: Handle<TabController>,
7281        ) {
7282            assert_eq!(index(tester, tab_controller), 1);
7283
7284            let page_controller = page_controller(tester);
7285
7286            // The TabBarView's page width is 400, so page 0 is at scroll offset 0.0,
7287            // page 1 is at 400.0, page 2 is at 800.0.
7288
7289            assert_eq!(pixels(tester, page_controller.handle()), 400.0);
7290
7291            let jump_to = |tester: &mut WidgetTester, value: f64| {
7292                page_controller.jump_to(&mut tester.cell.borrow_mut(), value);
7293            };
7294
7295            // Not close enough to switch to page 2
7296            jump_to(tester, 500.0);
7297            assert_eq!(index(tester, tab_controller), 1);
7298
7299            // Close enough to switch to page 2
7300            jump_to(tester, 700.0);
7301            assert_eq!(index(tester, tab_controller), 2);
7302
7303            // Same behavior going left: not left enough to get to page 0
7304            jump_to(tester, 300.0);
7305            assert_eq!(index(tester, tab_controller), 1);
7306
7307            // Left enough to get to page 0
7308            jump_to(tester, 100.0);
7309            assert_eq!(index(tester, tab_controller), 0);
7310        }
7311
7312        // 'TabBarView scrolls end close to a new page'.
7313        #[test]
7314        fn a_tab_bar_view_scrolled_close_to_a_page_selects_it() {
7315            test_widgets(|tester| {
7316                // This is a regression test for https://github.com/flutter/flutter/issues/9375
7317                let tab_controller = create_tab_controller(tester, 3, 1, None);
7318                tester.pump_widget(centered_tab_bar_view(
7319                    TabBarView::new(numbered_pages(3)).controller(tab_controller.clone()),
7320                ));
7321                check_jumps_close_to_a_new_page(tester, tab_controller.handle());
7322            });
7323        }
7324
7325        // 'On going TabBarView animation can be interrupted by a new animation'.
7326        #[test]
7327        fn an_ongoing_tab_bar_view_animation_can_be_interrupted_by_a_new_one() {
7328            test_widgets(|tester| {
7329                // This is a regression test for https://github.com/flutter/flutter/issues/132293.
7330                let tabs = ["A", "B", "C"];
7331                let tab_controller = create_tab_controller(tester, 3, 0, None);
7332                let frame = boilerplate_ltr(
7333                    tester,
7334                    bar_over_view(
7335                        &tabs,
7336                        tab_controller.clone(),
7337                        TabBarView::new(numbered_pages(3)),
7338                    ),
7339                );
7340                tester.pump_widget(frame);
7341
7342                // First page is visible.
7343                assert_eq!(index(tester, tab_controller.handle()), 0);
7344                expect(tester, &find::text("0"), finds_one_widget());
7345                expect(tester, &find::text("1"), finds_nothing());
7346
7347                // Animate to the second page.
7348                tab_controller.animate_to(&mut tester.cell.borrow_mut(), 1, None, None);
7349                tester.pump();
7350                tester.pump_by(Duration::from_millis(300));
7351
7352                // Animate back to the first page before the previous animation ends.
7353                tab_controller.animate_to(&mut tester.cell.borrow_mut(), 0, None, None);
7354                tester.pump_and_settle();
7355
7356                // First page should be visible.
7357                assert_eq!(index(tester, tab_controller.handle()), 0);
7358                expect(tester, &find::text("0"), finds_one_widget());
7359                expect(tester, &find::text("1"), finds_nothing());
7360            });
7361        }
7362
7363        // 'Can switch to non-neighboring tab in nested TabBarView without crashing'.
7364        #[test]
7365        fn a_tab_bar_view_with_a_nested_tab_bar_view_switches_to_a_non_neighbouring_tab() {
7366            test_widgets(|tester| {
7367                // This is a regression test for https://github.com/flutter/flutter/issues/18756
7368                let main_tab_controller = create_tab_controller(tester, 4, 0, None);
7369                let nested_tab_controller = create_tab_controller(tester, 2, 0, None);
7370                let theme = theme(tester, None, None);
7371                let add_tab = |label: &str| {
7372                    Tab::new()
7373                        .icon(waft_widgets::Icon::new(Some(crate::icons::Icons::add())))
7374                        .text(label)
7375                        .into_widget()
7376                };
7377                let colored =
7378                    |color: Color| waft_widgets::Container::new().color(color).into_widget();
7379
7380                tester.pump_widget(material_app(
7381                    theme,
7382                    Scaffold::new()
7383                        .app_bar(waft_widgets::PreferredSizeWidgetRef::new(
7384                            AppBar::new()
7385                                .title(Text::new("Exception for Nested Tabs"))
7386                                .bottom(waft_widgets::PreferredSizeWidgetRef::new(
7387                                    TabBar::new(["A", "B", "C", "D"].map(add_tab))
7388                                        .controller(main_tab_controller.clone()),
7389                                )),
7390                        ))
7391                        .body(
7392                            TabBarView::new([
7393                                colored(Colors::RED.primary()),
7394                                waft_widgets::ColoredBox::new(Colors::BLUE.primary())
7395                                    .child(
7396                                        Column::new().children([
7397                                            TabBar::new(text_tabs(&["Yellow", "Grey"]))
7398                                                .controller(nested_tab_controller.clone())
7399                                                .into_widget(),
7400                                            Expanded::new(
7401                                                TabBarView::new([
7402                                                    colored(Colors::YELLOW.primary()),
7403                                                    colored(Colors::GREY.primary()),
7404                                                ])
7405                                                .controller(nested_tab_controller),
7406                                            )
7407                                            .into_widget(),
7408                                        ]),
7409                                    )
7410                                    .into_widget(),
7411                                colored(Colors::GREEN.primary()),
7412                                colored(Colors::INDIGO.primary()),
7413                            ])
7414                            .controller(main_tab_controller.clone()),
7415                        )
7416                        .into_widget(),
7417                ));
7418
7419                // expect first tab to be selected
7420                assert_eq!(index(tester, main_tab_controller.handle()), 0);
7421
7422                // tap on third tab
7423                tester.tap(find::text("C"));
7424                tester.pump_and_settle();
7425
7426                // expect third tab to be selected without exceptions
7427                assert_eq!(index(tester, main_tab_controller.handle()), 2);
7428            });
7429        }
7430
7431        /// tabs_utils' `TabKeepAliveInk`: a page kept alive whose text is in an `Ink`.
7432        #[derive(Debug)]
7433        struct TabKeepAliveInk {
7434            title: String,
7435        }
7436
7437        impl StatefulWidget for TabKeepAliveInk {
7438            type State = TabKeepAliveInkState;
7439
7440            fn create_state(&self) -> TabKeepAliveInkState {
7441                TabKeepAliveInkState {
7442                    state: StateData::new(),
7443                    keep_alive: waft_widgets::AutomaticKeepAliveClientMixinData::default(),
7444                }
7445            }
7446        }
7447
7448        struct TabKeepAliveInkState {
7449            state: StateData<TabKeepAliveInk>,
7450            keep_alive: waft_widgets::AutomaticKeepAliveClientMixinData,
7451        }
7452
7453        impl waft_widgets::AutomaticKeepAliveClientMixin for TabKeepAliveInkState {
7454            fn automatic_keep_alive_client_data(
7455                self: Handle<Self>,
7456                app: &App,
7457            ) -> &waft_widgets::AutomaticKeepAliveClientMixinData {
7458                &app.get(self).keep_alive
7459            }
7460
7461            fn automatic_keep_alive_client_data_mut(
7462                self: Handle<Self>,
7463                app: &mut App,
7464            ) -> &mut waft_widgets::AutomaticKeepAliveClientMixinData {
7465                &mut app.get_mut(self).keep_alive
7466            }
7467
7468            fn want_keep_alive(self: Handle<Self>, _app: &App) -> bool {
7469                true
7470            }
7471        }
7472
7473        impl State for TabKeepAliveInkState {
7474            type Widget = TabKeepAliveInk;
7475            waft_widgets::state_accessors!();
7476
7477            fn init_state(self: Handle<Self>, app: &mut App) {
7478                waft_widgets::AutomaticKeepAliveClientMixin::init_state(self, app);
7479            }
7480
7481            fn deactivate(self: Handle<Self>, app: &mut App) {
7482                waft_widgets::AutomaticKeepAliveClientMixin::deactivate(self, app);
7483            }
7484
7485            fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
7486                waft_widgets::AutomaticKeepAliveClientMixin::build(self, app);
7487                crate::ink_decoration::Ink::new()
7488                    .child(Text::new(self.widget(app).title.clone()))
7489                    .into_widget()
7490            }
7491        }
7492
7493        // 'TabBarView can warp when child is kept alive and contains ink'.
7494        #[test]
7495        fn a_tab_bar_view_warps_past_a_kept_alive_page_with_ink() {
7496            test_widgets(|tester| {
7497                // Regression test for https://github.com/flutter/flutter/issues/57662.
7498                let controller = create_tab_controller(tester, 3, 0, None);
7499                let frame = boilerplate_ltr(
7500                    tester,
7501                    TabBarView::new([
7502                        Text::new("Page 1").into_widget(),
7503                        Text::new("Page 2").into_widget(),
7504                        TabKeepAliveInk {
7505                            title: "Page 3".to_owned(),
7506                        }
7507                        .into_widget(),
7508                    ])
7509                    .controller(controller.clone()),
7510                );
7511                tester.pump_widget(frame);
7512
7513                assert_eq!(index(tester, controller.handle()), 0);
7514                expect(tester, &find::text("Page 1"), finds_one_widget());
7515                expect(tester, &find::text("Page 3"), finds_nothing());
7516
7517                controller.set_index(&mut tester.cell.borrow_mut(), 2);
7518                tester.pump_and_settle();
7519                expect(tester, &find::text("Page 1"), finds_nothing());
7520                expect(tester, &find::text("Page 3"), finds_one_widget());
7521
7522                controller.set_index(&mut tester.cell.borrow_mut(), 0);
7523                tester.pump_and_settle();
7524                expect(tester, &find::text("Page 1"), finds_one_widget());
7525                expect(tester, &find::text("Page 3"), finds_nothing());
7526            });
7527        }
7528
7529        /// tabs_utils' `TabBarTestScrollPhysics`: turns a user offset of 10 into 20, on a stiffer
7530        /// spring.
7531        #[derive(Debug, Default)]
7532        struct TabBarTestScrollPhysics {
7533            parent: Option<ScrollPhysicsRef>,
7534        }
7535
7536        impl ScrollPhysics for TabBarTestScrollPhysics {
7537            fn as_any(&self) -> &dyn Any {
7538                self
7539            }
7540
7541            fn parent(&self) -> Option<&ScrollPhysicsRef> {
7542                self.parent.as_ref()
7543            }
7544
7545            fn apply_to(&self, ancestor: Option<ScrollPhysicsRef>) -> ScrollPhysicsRef {
7546                Rc::new(TabBarTestScrollPhysics {
7547                    parent: waft_widgets::ScrollPhysicsBase::build_parent(self, ancestor),
7548                })
7549            }
7550
7551            fn apply_physics_to_user_offset(
7552                &self,
7553                _position: &dyn waft_widgets::ScrollMetrics,
7554                offset: f64,
7555            ) -> f64 {
7556                if offset == 10.0 { 20.0 } else { offset }
7557            }
7558
7559            fn spring(&self) -> waft_physics::SpringDescription {
7560                waft_physics::SpringDescription::with_damping_ratio_value(0.5, 500.0, 1.1)
7561            }
7562        }
7563
7564        // 'TabBarView scrolls end close to a new page with custom physics'.
7565        #[test]
7566        fn a_tab_bar_view_with_custom_physics_scrolled_close_to_a_page_selects_it() {
7567            test_widgets(|tester| {
7568                let tab_controller = create_tab_controller(tester, 3, 1, None);
7569                tester.pump_widget(centered_tab_bar_view(
7570                    TabBarView::new(numbered_pages(3))
7571                        .controller(tab_controller.clone())
7572                        .physics(Rc::new(TabBarTestScrollPhysics::default())),
7573                ));
7574                check_jumps_close_to_a_new_page(tester, tab_controller.handle());
7575            });
7576        }
7577
7578        /// `List<Tab>.generate(count, (int index) => Tab(text: 'TAB #$index'))`.
7579        fn numbered_tabs(count: usize) -> Vec<WidgetRef> {
7580            (0..count)
7581                .map(|index| Tab::new().text(format!("TAB #{index}")).into_widget())
7582                .collect()
7583        }
7584
7585        // 'TabBar accepts custom physics'.
7586        #[test]
7587        fn a_tab_bar_keeps_the_physics_it_is_given() {
7588            test_widgets(|tester| {
7589                let controller = create_tab_controller(tester, 20, 19, None);
7590                let frame = boilerplate_ltr(
7591                    tester,
7592                    TabBar::new(numbered_tabs(20))
7593                        .is_scrollable(true)
7594                        .controller(controller)
7595                        .physics(Rc::new(TabBarTestScrollPhysics::default())),
7596                );
7597                tester.pump_widget(frame);
7598
7599                let physics = tester.widget(only::<TabBar>(tester), |tab_bar: &TabBar| {
7600                    tab_bar.physics.clone().expect("given physics")
7601                });
7602                // Dart's `TabMockScrollMetrics` is a fake the physics never reads.
7603                let metrics = waft_widgets::FixedScrollMetrics::new(
7604                    None,
7605                    None,
7606                    None,
7607                    None,
7608                    waft_painting::AxisDirection::Right,
7609                    1.0,
7610                );
7611                let position = physics.apply_physics_to_user_offset(&metrics, 10.0);
7612
7613                assert_eq!(position, 20.0);
7614            });
7615        }
7616
7617        /// The pixels of the only `Scrollable`'s position: Dart's
7618        /// `tester.state<ScrollableState>(find.byType(Scrollable)).position.pixels`.
7619        fn scrollable_pixels(tester: &WidgetTester) -> f64 {
7620            let element = only::<waft_widgets::Scrollable>(tester);
7621            let app = tester.cell.borrow();
7622            let state = element
7623                .state_handle::<ScrollableState>(&app)
7624                .expect("a scrollable state");
7625            state.position(&app).pixels(&app)
7626        }
7627
7628        fn new_tab_bar_scroll_controller(tester: &WidgetTester) -> Ref<TabBarScrollController> {
7629            TabBarScrollController::new(&mut tester.cell.borrow_mut())
7630        }
7631
7632        /// Whether `controller.debug_check_has_tab_bar_state()` asserts.
7633        fn check_has_tab_bar_state_asserts(
7634            tester: &WidgetTester,
7635            controller: Handle<TabBarScrollController>,
7636        ) -> bool {
7637            std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
7638                controller.debug_check_has_tab_bar_state(&tester.cell.borrow())
7639            }))
7640            .is_err()
7641        }
7642
7643        // 'TabBar accepts external TabBarScrollController'.
7644        #[test]
7645        fn a_tab_bar_scrolls_with_an_external_tab_bar_scroll_controller() {
7646            test_widgets(|tester| {
7647                let tab_bar_controller = create_tab_controller(tester, 6, 5, None);
7648                let tab_scroll_controller = new_tab_bar_scroll_controller(tester);
7649
7650                let frame = boilerplate_ltr(
7651                    tester,
7652                    TabBar::new(numbered_tabs(6))
7653                        .is_scrollable(true)
7654                        .controller(tab_bar_controller)
7655                        .scroll_controller(tab_scroll_controller.clone()),
7656                );
7657                tester.pump_widget(frame);
7658
7659                tab_scroll_controller.jump_to(&mut tester.cell.borrow_mut(), 50.0);
7660                tester.pump();
7661
7662                assert_eq!(scrollable_pixels(tester), 50.0);
7663            });
7664        }
7665
7666        // 'TabBar attaches state to internal TabBarScrollController in didUpdateWidget'.
7667        #[test]
7668        fn a_tab_bar_moving_to_its_internal_scroll_controller_keeps_its_pixels() {
7669            test_widgets(|tester| {
7670                let tab_bar_controller = create_tab_controller(tester, 6, 5, None);
7671                let tab_scroll_controller = new_tab_bar_scroll_controller(tester);
7672
7673                // Attach to the external controller.
7674                let frame = boilerplate_ltr(
7675                    tester,
7676                    TabBar::new(numbered_tabs(6))
7677                        .is_scrollable(true)
7678                        .controller(tab_bar_controller.clone())
7679                        .scroll_controller(tab_scroll_controller.clone()),
7680                );
7681                tester.pump_widget(frame);
7682
7683                let old_pixels = scrollable_pixels(tester);
7684
7685                // Trigger didUpdateWidget for the change to the internal controller.
7686                let frame = boilerplate_ltr(
7687                    tester,
7688                    TabBar::new(numbered_tabs(6))
7689                        .is_scrollable(true)
7690                        .controller(tab_bar_controller),
7691                );
7692                tester.pump_widget(frame);
7693
7694                // Creating the new scroll position should not throw.
7695                // The pixels of the new position should be the same as before the update.
7696                assert_eq!(scrollable_pixels(tester), old_pixels);
7697                assert!(check_has_tab_bar_state_asserts(
7698                    tester,
7699                    tab_scroll_controller.handle()
7700                ));
7701            });
7702        }
7703
7704        // 'TabBar attaches state to external TabBarScrollController in didUpdateWidget'.
7705        #[test]
7706        fn a_tab_bar_moving_to_an_external_scroll_controller_keeps_its_pixels() {
7707            test_widgets(|tester| {
7708                let tab_bar_controller = create_tab_controller(tester, 6, 5, None);
7709                let tab_scroll_controller = new_tab_bar_scroll_controller(tester);
7710
7711                // Attach to the internal controller.
7712                let frame = boilerplate_ltr(
7713                    tester,
7714                    TabBar::new(numbered_tabs(6))
7715                        .is_scrollable(true)
7716                        .controller(tab_bar_controller.clone()),
7717                );
7718                tester.pump_widget(frame);
7719
7720                let old_pixels = scrollable_pixels(tester);
7721
7722                // Trigger didUpdateWidget for the change to the external controller.
7723                let frame = boilerplate_ltr(
7724                    tester,
7725                    TabBar::new(numbered_tabs(6))
7726                        .is_scrollable(true)
7727                        .controller(tab_bar_controller)
7728                        .scroll_controller(tab_scroll_controller.clone()),
7729                );
7730                tester.pump_widget(frame);
7731
7732                // Creating the new scroll position should not throw.
7733                // The pixels of the new position should be the same as before the update.
7734                assert_eq!(scrollable_pixels(tester), old_pixels);
7735
7736                // This should not throw, since the tab bar is attached to the external controller.
7737                assert!(tab_scroll_controller.debug_check_has_tab_bar_state(&tester.cell.borrow()));
7738            });
7739        }
7740
7741        /// `<Tab>[for (int i = 0; i < count; i++) Tab(text: 'Tab $i')]`.
7742        fn tabs_numbered_from_zero(count: usize) -> Vec<WidgetRef> {
7743            (0..count)
7744                .map(|index| Tab::new().text(format!("Tab {index}")).into_widget())
7745                .collect()
7746        }
7747
7748        // 'TabBar correctly detaches old external TabBarScrollController when switched to a new one'.
7749        #[test]
7750        fn a_tab_bar_detaches_the_external_scroll_controller_it_is_switched_from() {
7751            test_widgets(|tester| {
7752                let tab_controller = create_tab_controller(tester, 10, 0, None);
7753                let controller_a = new_tab_bar_scroll_controller(tester);
7754                let controller_b = new_tab_bar_scroll_controller(tester);
7755
7756                let frame = boilerplate_ltr(
7757                    tester,
7758                    TabBar::new(tabs_numbered_from_zero(10))
7759                        .is_scrollable(true)
7760                        .controller(tab_controller.clone())
7761                        .scroll_controller(controller_a.clone()),
7762                );
7763                tester.pump_widget(frame);
7764
7765                assert!(controller_a.debug_check_has_tab_bar_state(&tester.cell.borrow()));
7766                assert!(check_has_tab_bar_state_asserts(
7767                    tester,
7768                    controller_b.handle()
7769                ));
7770
7771                // Switch to controllerB
7772                let frame = boilerplate_ltr(
7773                    tester,
7774                    TabBar::new(tabs_numbered_from_zero(10))
7775                        .is_scrollable(true)
7776                        .controller(tab_controller)
7777                        .scroll_controller(controller_b.clone()),
7778                );
7779                tester.pump_widget(frame);
7780
7781                assert!(controller_b.debug_check_has_tab_bar_state(&tester.cell.borrow()));
7782                assert!(check_has_tab_bar_state_asserts(
7783                    tester,
7784                    controller_a.handle()
7785                ));
7786            });
7787        }
7788
7789        // 'TabBar correctly detaches external TabBarScrollController when disposed'.
7790        #[test]
7791        fn a_disposed_tab_bar_detaches_its_external_scroll_controller() {
7792            test_widgets(|tester| {
7793                let tab_controller = create_tab_controller(tester, 10, 0, None);
7794                let controller = new_tab_bar_scroll_controller(tester);
7795
7796                let frame = boilerplate_ltr(
7797                    tester,
7798                    TabBar::new(tabs_numbered_from_zero(10))
7799                        .is_scrollable(true)
7800                        .controller(tab_controller)
7801                        .scroll_controller(controller.clone()),
7802                );
7803                tester.pump_widget(frame);
7804
7805                assert!(controller.debug_check_has_tab_bar_state(&tester.cell.borrow()));
7806
7807                // Dispose the TabBar by pumping a different widget
7808                let frame = boilerplate_ltr(tester, SizedBox::shrink());
7809                tester.pump_widget(frame);
7810
7811                assert!(check_has_tab_bar_state_asserts(tester, controller.handle()));
7812            });
7813        }
7814
7815        /// The scrollable `TabBar` of six tabs under a `RawScrollbar` on the same external scroll
7816        /// controller, that the scrollbar cases build.
7817        fn pump_tab_bar_in_raw_scrollbar(tester: &mut WidgetTester) {
7818            let tab_bar_controller = create_tab_controller(tester, 6, 5, None);
7819            let tab_scroll_controller = new_tab_bar_scroll_controller(tester);
7820            let frame = boilerplate_ltr(
7821                tester,
7822                waft_widgets::RawScrollbar::new(
7823                    TabBar::new(numbered_tabs(6))
7824                        .is_scrollable(true)
7825                        .controller(tab_bar_controller)
7826                        .scroll_controller(tab_scroll_controller.clone()),
7827                )
7828                .controller(tab_scroll_controller.erase()),
7829            );
7830            tester.pump_widget(frame);
7831        }
7832
7833        // 'TabBar can be wrapped with RawScrollbar'.
7834        #[test]
7835        fn a_tab_bar_can_be_wrapped_in_a_raw_scrollbar() {
7836            test_widgets(|tester| {
7837                // Regression test for https://github.com/flutter/flutter/issues/124608
7838                pump_tab_bar_in_raw_scrollbar(tester);
7839            });
7840        }
7841
7842        // 'TabBar can show scrollbar on hover'.
7843        #[test]
7844        fn a_tab_bar_in_a_raw_scrollbar_shows_the_scrollbar_on_hover() {
7845            test_widgets(|tester| {
7846                // Regression test for https://github.com/flutter/flutter/issues/124608
7847                pump_tab_bar_in_raw_scrollbar(tester);
7848
7849                let tab1 = find::text("TAB #1").evaluate(tester);
7850                assert_eq!(tab1.len(), 1);
7851
7852                // Hover over the tab bar and verify that the scrollbar is shown.
7853                let mut gesture = TestPointer::mouse(1, 0);
7854                tester.add_pointer(&mut gesture, Offset::ZERO);
7855                let center = tester.get_center(tab1[0]);
7856                tester.move_to(&mut gesture, center, false);
7857                tester.pump_and_settle();
7858
7859                // Dart's `paints` on the scrollbar records its whole subtree, repaint boundaries and
7860                // the ink of the materials in it included. Here that is the scrollbar's foreground
7861                // `CustomPaint`, under its repaint boundary, and the ink of each material under it.
7862                let scrollbar = only::<waft_widgets::RawScrollbar>(tester);
7863                let custom_paint = *tester
7864                    .descendants_of_type::<CustomPaint>(scrollbar)
7865                    .first()
7866                    .expect("the scrollbar's CustomPaint");
7867                let painter = tester.render_box_of(custom_paint);
7868                let mut ops = tester.painted_ops(painter.as_object());
7869                let scrollbar_render = tester.render_box_of(scrollbar).as_object();
7870                for material in tester.all::<crate::material::RenderInkFeatures>() {
7871                    let under_scrollbar = {
7872                        let app = tester.cell.borrow();
7873                        let mut ancestor = material.as_object().parent(&app);
7874                        loop {
7875                            match ancestor {
7876                                Some(object) if object == scrollbar_render => break true,
7877                                Some(object) => ancestor = object.parent(&app),
7878                                None => break false,
7879                            }
7880                        }
7881                    };
7882                    if under_scrollbar {
7883                        let mut canvas = Canvas::new();
7884                        material.paint_ink_features(
7885                            &mut tester.cell.borrow_mut(),
7886                            &mut canvas,
7887                            Offset::ZERO,
7888                        );
7889                        ops.extend(canvas.build().ops().iter().cloned());
7890                    }
7891                }
7892                assert_paints(&ops, &[PaintCall::rect(None)]);
7893            });
7894        }
7895
7896        // 'Scrollable TabBar with a non-zero TabController initialIndex'.
7897        #[test]
7898        fn a_scrollable_tab_bar_shows_a_non_zero_initial_index_right_justified() {
7899            test_widgets(|tester| {
7900                // This is a regression test for https://github.com/flutter/flutter/issues/9374
7901                let controller = create_tab_controller(tester, 20, 19, None);
7902                let frame = boilerplate_ltr(
7903                    tester,
7904                    TabBar::new(numbered_tabs(20))
7905                        .is_scrollable(true)
7906                        .controller(controller),
7907                );
7908                tester.pump_widget(frame);
7909
7910                // The initialIndex tab should be visible and right justified
7911                let label = find::text("TAB #19").evaluate(tester);
7912                assert_eq!(label.len(), 1);
7913
7914                // Tabs have a minimum width of 72.0 and 'TAB #19' is wider than
7915                // that. Tabs are padded horizontally with kTabLabelPadding.
7916                let tab_right = 800.0 - K_TAB_LABEL_PADDING.right;
7917
7918                let tab = tester.ancestor_of_type::<Tab>(label[0]);
7919                let right = tester.get_rect(tab).right;
7920                // Dart's `moreOrLessEquals` epsilon is 1e-10; the global rect goes through valo's f32
7921                // `Matrix4` at a scroll offset near 1725, which rounds it to about 1e-4.
7922                assert!(close(right, tab_right, 1e-4), "{right}");
7923            });
7924        }
7925
7926        /// tabs_utils' `tabIndicatorRRectElasticAnimation`.
7927        fn tab_indicator_rrect_elastic_animation(
7928            tab_bar_height: f64,
7929            from_rect: Rect,
7930            to_rect: Rect,
7931            progress: f64,
7932        ) -> waft_embedder::RRect {
7933            const INDICATOR_WEIGHT: f64 = 3.0;
7934            let left_fraction = 1.0 - ((progress * PI) / 2.0).cos();
7935            let right_fraction = ((progress * PI) / 2.0).sin();
7936            let lerp =
7937                |a: f64, b: f64, t: f64| lerp_double(Some(a), Some(b), t).expect("two values");
7938
7939            waft_embedder::RRect::from_ltrb_and_corners(
7940                lerp(from_rect.left, to_rect.left, left_fraction),
7941                tab_bar_height - INDICATOR_WEIGHT,
7942                lerp(from_rect.right, to_rect.right, right_fraction),
7943                tab_bar_height,
7944                waft_embedder::Radius::circular(INDICATOR_WEIGHT),
7945                waft_embedder::Radius::circular(INDICATOR_WEIGHT),
7946                waft_embedder::Radius::ZERO,
7947                waft_embedder::Radius::ZERO,
7948            )
7949        }
7950
7951        // 'Indicator elastic animation'.
7952        #[test]
7953        fn the_label_indicator_stretches_elastically_as_the_offset_changes() {
7954            test_widgets(|tester| {
7955                const INDICATOR_WIDTH: f64 = 50.0;
7956                let tabs = (0..4).map(|index| {
7957                    Tab::new()
7958                        .key(ValueKey::new(index).into())
7959                        .child(SizedBox::new().width(INDICATOR_WIDTH))
7960                        .into_widget()
7961                });
7962                let controller = create_tab_controller(tester, 4, 0, None);
7963                let theme = theme(tester, None, None);
7964                let inner = boilerplate_ltr(
7965                    tester,
7966                    waft_widgets::Container::new()
7967                        .alignment(AlignmentGeometry::TOP_LEFT)
7968                        .child(TabBar::new(tabs).controller(controller.clone())),
7969                );
7970                tester.pump_widget(material_app(theme, inner));
7971
7972                let tab_bar_box = first_render_box::<TabBar>(tester);
7973                let height = tab_bar_box.size(&tester.cell.borrow()).height();
7974                assert_eq!(height, 48.0);
7975
7976                let from_rect = Rect::from_ltrb(75.0, 0.0, 125.0, 48.0);
7977                let mut to_rect = Rect::from_ltrb(75.0, 0.0, 125.0, 48.0);
7978                let paints = |tester: &WidgetTester, rrect| {
7979                    waft_rendering::testing::paints(
7980                        &tester.painted_ops(tab_bar_box.as_object()),
7981                        &[waft_rendering::testing::PaintCall::rrect_at(rrect, None)],
7982                    )
7983                    .is_ok()
7984                };
7985                assert!(paints(
7986                    tester,
7987                    tab_indicator_rrect_elastic_animation(height, from_rect, to_rect, 0.0)
7988                ));
7989
7990                controller.set_offset(&mut tester.cell.borrow_mut(), 0.2);
7991                tester.pump();
7992                to_rect = Rect::from_ltrb(275.0, 0.0, 325.0, 48.0);
7993                assert!(paints(
7994                    tester,
7995                    tab_indicator_rrect_elastic_animation(height, from_rect, to_rect, 0.2)
7996                ));
7997
7998                controller.set_offset(&mut tester.cell.borrow_mut(), 0.5);
7999                tester.pump();
8000                assert!(paints(
8001                    tester,
8002                    tab_indicator_rrect_elastic_animation(height, from_rect, to_rect, 0.5)
8003                ));
8004
8005                controller.set_offset(&mut tester.cell.borrow_mut(), 1.0);
8006                tester.pump();
8007                // When the animation is completed, no stretch is applied.
8008                assert!(paints(
8009                    tester,
8010                    tab_indicator_rrect_elastic_animation(height, from_rect, to_rect, 1.0)
8011                ));
8012            });
8013        }
8014
8015        // 'ensureVisible does not move TabViews'.
8016        #[test]
8017        fn ensure_visible_does_not_move_tab_views() {
8018            test_widgets(|tester| {
8019                let controller = create_tab_controller(tester, 3, 0, None);
8020
8021                let pages = (0..3).map(|page_index| {
8022                    waft_widgets::ListView::new()
8023                        .key(key(format!("list_{page_index}")))
8024                        .children((0..100).map(|list_index| {
8025                            let cell = |column: usize, color: Color| {
8026                                waft_widgets::Container::new()
8027                                    .key(key(format!("{page_index}_{list_index}_{column}")))
8028                                    .color(color)
8029                                    .width(200.0)
8030                                    .height(10.0)
8031                                    .into_widget()
8032                            };
8033                            Row::new()
8034                                .children([
8035                                    cell(0, Colors::RED.primary()),
8036                                    cell(1, Colors::BLUE.primary()),
8037                                    cell(2, Colors::GREEN.primary()),
8038                                ])
8039                                .into_widget()
8040                        }))
8041                        .into_widget()
8042                });
8043                tester.pump_widget(
8044                    Directionality::new(
8045                        TextDirection::Ltr,
8046                        TabBarView::new(pages.collect::<Vec<_>>()).controller(controller.clone()),
8047                    )
8048                    .into_widget(),
8049                );
8050
8051                let found = |tester: &WidgetTester, name: &str| {
8052                    find::by_key(key(name)).evaluate(tester).len()
8053                };
8054                let ensure_visible = |tester: &mut WidgetTester, name: &str| {
8055                    let element = tester.element(find::by_key(key(name)));
8056                    let mut app = tester.cell.borrow_mut();
8057                    drop(waft_widgets::Scrollable::ensure_visible(
8058                        &mut app,
8059                        element,
8060                        0.0,
8061                        Duration::ZERO,
8062                        Curves::ease(),
8063                        waft_widgets::ScrollPositionAlignmentPolicy::Explicit,
8064                    ));
8065                };
8066
8067                assert_eq!(found(tester, "list_0"), 1);
8068                assert_eq!(found(tester, "list_1"), 0);
8069                assert_eq!(found(tester, "0_25_2"), 1);
8070                assert_eq!(found(tester, "1_25_2"), 0);
8071                assert_eq!(found(tester, "1_25_0"), 0);
8072
8073                ensure_visible(tester, "0_25_2");
8074                tester.pump_and_settle();
8075                assert_eq!(found(tester, "0_25_2"), 1);
8076                assert_eq!(found(tester, "1_25_2"), 0);
8077                assert_eq!(found(tester, "1_25_0"), 0);
8078
8079                controller.set_index(&mut tester.cell.borrow_mut(), 1);
8080                tester.pump_and_settle();
8081
8082                assert_eq!(found(tester, "list_0"), 0);
8083                assert_eq!(found(tester, "list_1"), 1);
8084                ensure_visible(tester, "1_25_2");
8085                tester.pump_and_settle();
8086
8087                assert_eq!(found(tester, "0_25_2"), 0);
8088                assert_eq!(found(tester, "1_25_2"), 1);
8089                assert_eq!(found(tester, "1_25_0"), 1);
8090
8091                ensure_visible(tester, "1_25_0");
8092                tester.pump_and_settle();
8093
8094                assert_eq!(found(tester, "0_25_2"), 0);
8095                assert_eq!(found(tester, "1_25_2"), 1);
8096                assert_eq!(found(tester, "1_25_0"), 1);
8097            });
8098        }
8099    }
8100
8101    mod indicators_and_controller_changes {
8102        //! tabs_test.dart cases from 'TabBar with indicatorWeight, indicatorPadding (LTR)' through
8103        //! 'Number of tabs can be updated dynamically'.
8104
8105        use super::*;
8106
8107        use std::cell::{Cell, RefCell};
8108        use std::panic::{AssertUnwindSafe, catch_unwind};
8109
8110        use waft_painting::EdgeInsets;
8111
8112        use waft_embedder::valo::Op;
8113        use waft_rendering::testing::{PaintCall, assert_paints, paints};
8114        use waft_widgets::testing::TestVSync;
8115
8116        /// Dart's `createTabController(length:, vsync: const TestVSync())`.
8117        fn new_controller(tester: &WidgetTester, length: usize) -> Ref<TabController> {
8118            let mut app = tester.cell.borrow_mut();
8119            TabController::new(&mut app, 0, None, length, TestVSync)
8120        }
8121
8122        /// Dart's `Container(alignment: Alignment.topLeft, child: child)`.
8123        fn top_left<K>(child: impl IntoWidget<K>) -> WidgetRef {
8124            waft_widgets::Container::new()
8125                .alignment(AlignmentGeometry::TOP_LEFT)
8126                .child(child)
8127                .into_widget()
8128        }
8129
8130        /// `n` tabs `Tab(text: 'Tab $index')`.
8131        fn text_tabs(n: usize) -> Vec<WidgetRef> {
8132            (0..n)
8133                .map(|index| Tab::new().text(format!("Tab {index}")).into_widget())
8134                .collect()
8135        }
8136
8137        /// Three keyed `SizedBox`es of the given sizes, Dart's `SizedBox(key: UniqueKey(), ..)` tabs.
8138        fn sized_tabs(sizes: &[(f64, f64)]) -> (Vec<GlobalKey>, Vec<WidgetRef>) {
8139            let keys: Vec<GlobalKey> = sizes.iter().map(|_| GlobalKey::new()).collect();
8140            let tabs = sizes
8141                .iter()
8142                .zip(&keys)
8143                .map(|((width, height), key)| {
8144                    SizedBox::new()
8145                        .key(key.clone().into())
8146                        .width(*width)
8147                        .height(*height)
8148                        .into_widget()
8149                })
8150                .collect();
8151            (keys, tabs)
8152        }
8153
8154        /// Dart's `tester.getRect(find.byKey(key))`.
8155        fn rect_of_key(tester: &WidgetTester, key: &GlobalKey) -> Rect {
8156            tester.get_rect(tester.render_object(key).as_box().expect("a render box"))
8157        }
8158
8159        fn deep_lines(tester: &WidgetTester, render: AnyRenderObject) -> Vec<PaintedLine> {
8160            lines_of(&tester.painted_ops_deep(render))
8161        }
8162
8163        fn paints_line(
8164            tester: &WidgetTester,
8165            render: AnyRenderBox,
8166            color: Option<Color>,
8167            stroke_width: f64,
8168            p1: Offset,
8169            p2: Offset,
8170        ) -> bool {
8171            let result = paints(
8172                &tester.painted_ops_deep(render.as_object()),
8173                &[PaintCall::Line {
8174                    p1: Some(p1),
8175                    p2: Some(p2),
8176                    color,
8177                    stroke_width: Some(stroke_width),
8178                }],
8179            );
8180            if let Err(mismatch) = &result {
8181                eprintln!("{mismatch}");
8182            }
8183            result.is_ok()
8184        }
8185
8186        fn paints_rect(
8187            tester: &WidgetTester,
8188            render: AnyRenderBox,
8189            rect: Rect,
8190            color: Color,
8191        ) -> bool {
8192            let result = paints(
8193                &tester.painted_ops_deep(render.as_object()),
8194                &[PaintCall::rect_at(rect, Some(color))],
8195            );
8196            if let Err(mismatch) = &result {
8197                eprintln!("{mismatch}");
8198            }
8199            result.is_ok()
8200        }
8201
8202        fn tab_bar_height(tester: &WidgetTester) -> f64 {
8203            first_render_box::<TabBar>(tester)
8204                .size(&tester.cell.borrow())
8205                .height()
8206        }
8207
8208        fn tab_bar_size(tester: &WidgetTester) -> Size {
8209            first_render_box::<TabBar>(tester).size(&tester.cell.borrow())
8210        }
8211
8212        fn set_index(tester: &WidgetTester, controller: Handle<TabController>, index: usize) {
8213            let mut app = tester.cell.borrow_mut();
8214            controller.set_index(&mut app, index);
8215        }
8216
8217        /// The text of a panic: a `String` or a `&str` payload.
8218        fn panic_message(panic: Box<dyn std::any::Any + Send>) -> String {
8219            panic
8220                .downcast_ref::<String>()
8221                .cloned()
8222                .or_else(|| panic.downcast_ref::<&str>().map(|text| text.to_string()))
8223                .unwrap_or_default()
8224        }
8225
8226        const LABEL_LEFT: f64 = 16.0;
8227        const LABEL_RIGHT: f64 = 16.0;
8228        const LABEL_HORIZONTAL: f64 = 32.0;
8229
8230        // 'TabBar with indicatorWeight, indicatorPadding (LTR)'.
8231        #[test]
8232        fn a_tab_bar_underline_takes_its_weight_and_padding_left_to_right() {
8233            test_widgets(|tester| {
8234                const INDICATOR_COLOR: Color = Color::new(0xFF00FF00);
8235                const INDICATOR_WEIGHT: f64 = 8.0;
8236                const PAD_LEFT: f64 = 8.0;
8237                const PAD_RIGHT: f64 = 4.0;
8238                let controller = new_controller(tester, 4);
8239                let theme = theme(tester, Some(false), None);
8240                tester.pump_widget(boilerplate(
8241                    theme,
8242                    TextDirection::Ltr,
8243                    top_left(
8244                        TabBar::new(text_tabs(4))
8245                            .indicator_weight(INDICATOR_WEIGHT)
8246                            .indicator_color(INDICATOR_COLOR)
8247                            .indicator_padding(EdgeInsetsGeometry::only(
8248                                PAD_LEFT, 0.0, PAD_RIGHT, 0.0,
8249                            ))
8250                            .controller(controller.clone()),
8251                    ),
8252                ));
8253
8254                let tab_bar_box = first_render_box::<TabBar>(tester);
8255                assert_eq!(tab_bar_height(tester), 54.0); // 54 = _kTabHeight(46) + indicatorWeight(8.0)
8256
8257                const INDICATOR_Y: f64 = 54.0 - INDICATOR_WEIGHT / 2.0;
8258                let indicator_left = PAD_LEFT + INDICATOR_WEIGHT / 2.0;
8259                let indicator_right = 200.0 - (PAD_RIGHT + INDICATOR_WEIGHT / 2.0);
8260                assert!(paints_line(
8261                    tester,
8262                    tab_bar_box,
8263                    Some(INDICATOR_COLOR),
8264                    INDICATOR_WEIGHT,
8265                    Offset::new(indicator_left, INDICATOR_Y),
8266                    Offset::new(indicator_right, INDICATOR_Y),
8267                ));
8268
8269                // Select tab 3
8270                set_index(tester, controller.handle(), 3);
8271                tester.pump_and_settle();
8272
8273                let indicator_left = 600.0 + PAD_LEFT + INDICATOR_WEIGHT / 2.0;
8274                let indicator_right = 800.0 - (PAD_RIGHT + INDICATOR_WEIGHT / 2.0);
8275                assert!(paints_line(
8276                    tester,
8277                    tab_bar_box,
8278                    Some(INDICATOR_COLOR),
8279                    INDICATOR_WEIGHT,
8280                    Offset::new(indicator_left, INDICATOR_Y),
8281                    Offset::new(indicator_right, INDICATOR_Y),
8282                ));
8283            });
8284        }
8285
8286        // 'TabBar with indicatorWeight, indicatorPadding (RTL)'.
8287        #[test]
8288        fn a_tab_bar_underline_takes_its_weight_and_padding_right_to_left() {
8289            test_widgets(|tester| {
8290                const INDICATOR_COLOR: Color = Color::new(0xFF00FF00);
8291                const INDICATOR_WEIGHT: f64 = 8.0;
8292                const PAD_LEFT: f64 = 8.0;
8293                const PAD_RIGHT: f64 = 4.0;
8294                let controller = new_controller(tester, 4);
8295                let theme = theme(tester, Some(false), None);
8296                tester.pump_widget(boilerplate(
8297                    theme,
8298                    TextDirection::Rtl,
8299                    top_left(
8300                        TabBar::new(text_tabs(4))
8301                            .indicator_weight(INDICATOR_WEIGHT)
8302                            .indicator_color(INDICATOR_COLOR)
8303                            .indicator_padding(EdgeInsetsGeometry::only(
8304                                PAD_LEFT, 0.0, PAD_RIGHT, 0.0,
8305                            ))
8306                            .controller(controller.clone()),
8307                    ),
8308                ));
8309
8310                let tab_bar_box = first_render_box::<TabBar>(tester);
8311                assert_eq!(tab_bar_height(tester), 54.0); // 54 = _kTabHeight(46) + indicatorWeight(8.0)
8312                assert_eq!(tab_bar_size(tester).width(), 800.0);
8313
8314                const INDICATOR_Y: f64 = 54.0 - INDICATOR_WEIGHT / 2.0;
8315                let indicator_left = 600.0 + PAD_LEFT + INDICATOR_WEIGHT / 2.0;
8316                let indicator_right = 800.0 - PAD_RIGHT - INDICATOR_WEIGHT / 2.0;
8317                assert!(paints_line(
8318                    tester,
8319                    tab_bar_box,
8320                    Some(INDICATOR_COLOR),
8321                    INDICATOR_WEIGHT,
8322                    Offset::new(indicator_left, INDICATOR_Y),
8323                    Offset::new(indicator_right, INDICATOR_Y),
8324                ));
8325
8326                // Select tab 3
8327                set_index(tester, controller.handle(), 3);
8328                tester.pump_and_settle();
8329
8330                let indicator_left = PAD_LEFT + INDICATOR_WEIGHT / 2.0;
8331                let indicator_right = 200.0 - PAD_RIGHT - INDICATOR_WEIGHT / 2.0;
8332                assert!(paints_line(
8333                    tester,
8334                    tab_bar_box,
8335                    Some(INDICATOR_COLOR),
8336                    INDICATOR_WEIGHT,
8337                    Offset::new(indicator_left, INDICATOR_Y),
8338                    Offset::new(indicator_right, INDICATOR_Y),
8339                ));
8340            });
8341        }
8342
8343        // 'TabBar changes indicator attributes'.
8344        #[test]
8345        fn a_rebuilt_tab_bar_paints_its_new_indicator_attributes() {
8346            test_widgets(|tester| {
8347                let controller = new_controller(tester, 4);
8348                let build_frame = |tester: &WidgetTester,
8349                                   indicator_color: Color,
8350                                   indicator_weight: f64,
8351                                   pad_left: f64,
8352                                   pad_right: f64| {
8353                    let theme = theme(tester, Some(false), None);
8354                    boilerplate(
8355                        theme,
8356                        TextDirection::Ltr,
8357                        top_left(
8358                            TabBar::new(text_tabs(4))
8359                                .indicator_weight(indicator_weight)
8360                                .indicator_color(indicator_color)
8361                                .indicator_padding(EdgeInsetsGeometry::only(
8362                                    pad_left, 0.0, pad_right, 0.0,
8363                                ))
8364                                .controller(controller.clone()),
8365                        ),
8366                    )
8367                };
8368
8369                let (indicator_color, indicator_weight, pad_left, pad_right) =
8370                    (Color::new(0xFF00FF00), 8.0, 8.0, 4.0);
8371                let frame = build_frame(
8372                    tester,
8373                    indicator_color,
8374                    indicator_weight,
8375                    pad_left,
8376                    pad_right,
8377                );
8378                tester.pump_widget(frame);
8379
8380                let tab_bar_box = first_render_box::<TabBar>(tester);
8381                assert_eq!(tab_bar_height(tester), 54.0); // 54 = _kTabHeight(46) + indicatorWeight(8.0)
8382
8383                let indicator_y = 54.0 - indicator_weight / 2.0;
8384                let indicator_left = pad_left + indicator_weight / 2.0;
8385                let indicator_right = 200.0 - (pad_right + indicator_weight / 2.0);
8386                assert!(paints_line(
8387                    tester,
8388                    tab_bar_box,
8389                    Some(indicator_color),
8390                    indicator_weight,
8391                    Offset::new(indicator_left, indicator_y),
8392                    Offset::new(indicator_right, indicator_y),
8393                ));
8394
8395                let (indicator_color, indicator_weight, pad_left, pad_right) =
8396                    (Color::new(0xFF0000FF), 4.0, 4.0, 8.0);
8397                let frame = build_frame(
8398                    tester,
8399                    indicator_color,
8400                    indicator_weight,
8401                    pad_left,
8402                    pad_right,
8403                );
8404                tester.pump_widget(frame);
8405
8406                assert_eq!(tab_bar_box.size(&tester.cell.borrow()).height(), 50.0); // 54 = _kTabHeight(46) + indicatorWeight(4.0)
8407
8408                let indicator_y = 50.0 - indicator_weight / 2.0;
8409                let indicator_left = pad_left + indicator_weight / 2.0;
8410                let indicator_right = 200.0 - (pad_right + indicator_weight / 2.0);
8411                assert!(paints_line(
8412                    tester,
8413                    tab_bar_box,
8414                    Some(indicator_color),
8415                    indicator_weight,
8416                    Offset::new(indicator_left, indicator_y),
8417                    Offset::new(indicator_right, indicator_y),
8418                ));
8419            });
8420        }
8421
8422        /// The tab rects of a scrollable tab bar of three sized tabs at `label_left`/`label_right`
8423        /// padding, in the order they are laid out, and the bottom of the last.
8424        fn assert_three_tab_rects(
8425            tester: &WidgetTester,
8426            keys_in_order: [&GlobalKey; 3],
8427            sizes_in_order: [(f64, f64); 3],
8428            tab_bar_height: f64,
8429            indicator_weight: f64,
8430            label_left: f64,
8431            label_right: f64,
8432        ) -> (f64, f64, f64) {
8433            let mut tab_left = label_left;
8434            let mut tab_right = 0.0;
8435            let mut tab_bottom = 0.0;
8436            for (index, (key, (width, height))) in
8437                keys_in_order.iter().zip(sizes_in_order).enumerate()
8438            {
8439                if index > 0 {
8440                    tab_left = tab_right + label_right + label_left;
8441                }
8442                tab_right = tab_left + width;
8443                let tab_top = (tab_bar_height - indicator_weight - height) / 2.0;
8444                tab_bottom = tab_top + height;
8445                let tab_rect = Rect::from_ltrb(tab_left, tab_top, tab_right, tab_bottom);
8446                assert_eq!(rect_of_key(tester, key), tab_rect);
8447            }
8448            (tab_left, tab_right, tab_bottom)
8449        }
8450
8451        // 'TabBar with directional indicatorPadding (LTR)'.
8452        #[test]
8453        fn a_directional_indicator_padding_starts_on_the_left_left_to_right() {
8454            test_widgets(|tester| {
8455                let (keys, tabs) = sized_tabs(&[(130.0, 30.0), (140.0, 40.0), (150.0, 50.0)]);
8456                const INDICATOR_WEIGHT: f64 = 2.0; // the default
8457                let controller = new_controller(tester, 3);
8458                let theme = theme(tester, Some(false), None);
8459                tester.pump_widget(boilerplate(
8460                    theme,
8461                    TextDirection::Ltr,
8462                    top_left(
8463                        TabBar::new(tabs)
8464                            .indicator_padding(EdgeInsetsDirectional::only(100.0, 0.0, 0.0, 0.0))
8465                            .is_scrollable(true)
8466                            .controller(controller),
8467                    ),
8468                ));
8469
8470                let tab_bar_box = first_render_box::<TabBar>(tester);
8471                const TAB_BAR_HEIGHT: f64 = 50.0 + INDICATOR_WEIGHT; // 50 = max tab height
8472                assert_eq!(tab_bar_height(tester), TAB_BAR_HEIGHT);
8473
8474                let (_, _, tab_bottom) = assert_three_tab_rects(
8475                    tester,
8476                    [&keys[0], &keys[1], &keys[2]],
8477                    [(130.0, 30.0), (140.0, 40.0), (150.0, 50.0)],
8478                    TAB_BAR_HEIGHT,
8479                    INDICATOR_WEIGHT,
8480                    LABEL_LEFT,
8481                    LABEL_RIGHT,
8482                );
8483
8484                // Tab 0 selected, indicator padding resolves to left: 100.0
8485                const INDICATOR_LEFT: f64 = 100.0 + INDICATOR_WEIGHT / 2.0;
8486                let indicator_right = 130.0 + LABEL_HORIZONTAL - INDICATOR_WEIGHT / 2.0;
8487                let indicator_y = tab_bottom + INDICATOR_WEIGHT / 2.0;
8488                assert!(paints_line(
8489                    tester,
8490                    tab_bar_box,
8491                    None,
8492                    INDICATOR_WEIGHT,
8493                    Offset::new(INDICATOR_LEFT, indicator_y),
8494                    Offset::new(indicator_right, indicator_y),
8495                ));
8496            });
8497        }
8498
8499        // 'TabBar with directional indicatorPadding (RTL)'.
8500        #[test]
8501        fn a_directional_indicator_padding_starts_on_the_right_right_to_left() {
8502            test_widgets(|tester| {
8503                let (keys, tabs) = sized_tabs(&[(130.0, 30.0), (140.0, 40.0), (150.0, 50.0)]);
8504                const INDICATOR_WEIGHT: f64 = 2.0; // the default
8505                let controller = new_controller(tester, 3);
8506                let theme = theme(tester, Some(false), None);
8507                tester.pump_widget(boilerplate(
8508                    theme,
8509                    TextDirection::Rtl,
8510                    top_left(
8511                        TabBar::new(tabs)
8512                            .indicator_padding(EdgeInsetsDirectional::only(100.0, 0.0, 0.0, 0.0))
8513                            .is_scrollable(true)
8514                            .controller(controller),
8515                    ),
8516                ));
8517
8518                let tab_bar_box = first_render_box::<TabBar>(tester);
8519                const TAB_BAR_HEIGHT: f64 = 50.0 + INDICATOR_WEIGHT; // 50 = max tab height
8520                assert_eq!(tab_bar_height(tester), TAB_BAR_HEIGHT);
8521
8522                let (tab_left, tab_right, _) = assert_three_tab_rects(
8523                    tester,
8524                    [&keys[2], &keys[1], &keys[0]],
8525                    [(150.0, 50.0), (140.0, 40.0), (130.0, 30.0)],
8526                    TAB_BAR_HEIGHT,
8527                    INDICATOR_WEIGHT,
8528                    LABEL_LEFT,
8529                    LABEL_RIGHT,
8530                );
8531
8532                // Tab 0 selected, indicator padding resolves to right: 100.0
8533                let indicator_left = tab_left - LABEL_LEFT + INDICATOR_WEIGHT / 2.0;
8534                let indicator_right = tab_right + LABEL_LEFT - INDICATOR_WEIGHT / 2.0 - 100.0;
8535                const INDICATOR_Y: f64 = 50.0 + INDICATOR_WEIGHT / 2.0;
8536                assert!(paints_line(
8537                    tester,
8538                    tab_bar_box,
8539                    None,
8540                    INDICATOR_WEIGHT,
8541                    Offset::new(indicator_left, INDICATOR_Y),
8542                    Offset::new(indicator_right, INDICATOR_Y),
8543                ));
8544            });
8545        }
8546
8547        /// The custom indicator cases' tab bar of four text tabs with a `BoxDecoration` indicator.
8548        fn custom_indicator_frame(
8549            tester: &WidgetTester,
8550            text_direction: TextDirection,
8551            controller: Ref<TabController>,
8552            indicator_color: Color,
8553            indicator_padding: EdgeInsetsGeometry,
8554        ) -> WidgetRef {
8555            let theme = theme(tester, Some(false), None);
8556            boilerplate(
8557                theme,
8558                text_direction,
8559                top_left(
8560                    TabBar::new(text_tabs(4))
8561                        .indicator(BoxDecoration::new().color(indicator_color))
8562                        .indicator_padding(indicator_padding)
8563                        .controller(controller),
8564                ),
8565            )
8566        }
8567
8568        // 'TabBar with custom indicator and indicatorPadding(LTR)'.
8569        #[test]
8570        fn a_custom_indicator_is_inset_by_its_padding_left_to_right() {
8571            test_widgets(|tester| {
8572                const INDICATOR_COLOR: Color = Color::new(0xFF00FF00);
8573                const PAD_TOP: f64 = 10.0;
8574                const PAD_BOTTOM: f64 = 12.0;
8575                const PAD_LEFT: f64 = 8.0;
8576                const PAD_RIGHT: f64 = 4.0;
8577                let controller = new_controller(tester, 4);
8578                let frame = custom_indicator_frame(
8579                    tester,
8580                    TextDirection::Ltr,
8581                    controller.clone(),
8582                    INDICATOR_COLOR,
8583                    EdgeInsetsGeometry::only(PAD_LEFT, PAD_TOP, PAD_RIGHT, PAD_BOTTOM),
8584                );
8585                tester.pump_widget(frame);
8586
8587                let tab_bar_box = first_render_box::<TabBar>(tester);
8588                assert_eq!(tab_bar_height(tester), 48.0);
8589                // 48 = _kTabHeight(46) + indicatorWeight(2.0) ~default
8590
8591                const INDICATOR_BOTTOM: f64 = 48.0 - PAD_BOTTOM;
8592                const INDICATOR_TOP: f64 = PAD_TOP;
8593                assert!(paints_rect(
8594                    tester,
8595                    tab_bar_box,
8596                    Rect::from_ltrb(PAD_LEFT, INDICATOR_TOP, 200.0 - PAD_RIGHT, INDICATOR_BOTTOM),
8597                    INDICATOR_COLOR,
8598                ));
8599
8600                // Select tab 3
8601                set_index(tester, controller.handle(), 3);
8602                tester.pump_and_settle();
8603
8604                assert!(paints_rect(
8605                    tester,
8606                    tab_bar_box,
8607                    Rect::from_ltrb(
8608                        600.0 + PAD_LEFT,
8609                        INDICATOR_TOP,
8610                        800.0 - PAD_RIGHT,
8611                        INDICATOR_BOTTOM
8612                    ),
8613                    INDICATOR_COLOR,
8614                ));
8615            });
8616        }
8617
8618        // 'TabBar with custom indicator and indicatorPadding (RTL)'.
8619        #[test]
8620        fn a_custom_indicator_is_inset_by_its_padding_right_to_left() {
8621            test_widgets(|tester| {
8622                const INDICATOR_COLOR: Color = Color::new(0xFF00FF00);
8623                const PAD_TOP: f64 = 10.0;
8624                const PAD_BOTTOM: f64 = 12.0;
8625                const PAD_LEFT: f64 = 8.0;
8626                const PAD_RIGHT: f64 = 4.0;
8627                let controller = new_controller(tester, 4);
8628                let frame = custom_indicator_frame(
8629                    tester,
8630                    TextDirection::Rtl,
8631                    controller.clone(),
8632                    INDICATOR_COLOR,
8633                    EdgeInsetsGeometry::only(PAD_LEFT, PAD_TOP, PAD_RIGHT, PAD_BOTTOM),
8634                );
8635                tester.pump_widget(frame);
8636
8637                let tab_bar_box = first_render_box::<TabBar>(tester);
8638                assert_eq!(tab_bar_height(tester), 48.0);
8639                // 48 = _kTabHeight(46) + indicatorWeight(2.0) ~default
8640                assert_eq!(tab_bar_size(tester).width(), 800.0);
8641                const INDICATOR_BOTTOM: f64 = 48.0 - PAD_BOTTOM;
8642                const INDICATOR_TOP: f64 = PAD_TOP;
8643                assert!(paints_rect(
8644                    tester,
8645                    tab_bar_box,
8646                    Rect::from_ltrb(
8647                        600.0 + PAD_LEFT,
8648                        INDICATOR_TOP,
8649                        800.0 - PAD_RIGHT,
8650                        INDICATOR_BOTTOM
8651                    ),
8652                    INDICATOR_COLOR,
8653                ));
8654
8655                // Select tab 3
8656                set_index(tester, controller.handle(), 3);
8657                tester.pump_and_settle();
8658
8659                assert!(paints_rect(
8660                    tester,
8661                    tab_bar_box,
8662                    Rect::from_ltrb(PAD_LEFT, INDICATOR_TOP, 200.0 - PAD_RIGHT, INDICATOR_BOTTOM),
8663                    INDICATOR_COLOR,
8664                ));
8665            });
8666        }
8667
8668        // 'TabBar accepts indicatorWeight: 0 when the indicator comes from TabBarThemeData'.
8669        #[test]
8670        fn a_zero_indicator_weight_is_accepted_with_a_themed_indicator() {
8671            test_widgets(|tester| {
8672                const INDICATOR_COLOR: Color = Color::new(0xFF00FF00);
8673                let build_frame = |tester: &WidgetTester, secondary: bool| {
8674                    let tabs = vec![
8675                        Tab::new().text("A").into_widget(),
8676                        Tab::new().text("B").into_widget(),
8677                    ];
8678                    let theme = theme(
8679                        tester,
8680                        None,
8681                        Some(
8682                            TabBarThemeData::new()
8683                                .indicator(BoxDecoration::new().color(INDICATOR_COLOR))
8684                                .indicator_size(TabBarIndicatorSize::Tab),
8685                        ),
8686                    );
8687                    let tab_bar = if secondary {
8688                        TabBar::secondary(tabs)
8689                    } else {
8690                        TabBar::new(tabs)
8691                    }
8692                    .indicator_weight(0.0);
8693                    boilerplate(
8694                        theme,
8695                        TextDirection::Ltr,
8696                        top_left(DefaultTabController::new(2, tab_bar)),
8697                    )
8698                };
8699
8700                // Primary TabBar: no assertion is thrown and the themed indicator is painted.
8701                let frame = build_frame(tester, false);
8702                tester.pump_widget(frame);
8703
8704                let tab_bar_box = first_render_box::<TabBar>(tester);
8705                // 46 = _kTabHeight(46) with no weight added by the zero indicatorWeight.
8706                assert_eq!(tab_bar_height(tester), 46.0);
8707                assert!(paints_rect(
8708                    tester,
8709                    tab_bar_box,
8710                    Rect::from_ltrb(0.0, 0.0, 400.0, 46.0),
8711                    INDICATOR_COLOR,
8712                ));
8713
8714                // Secondary TabBar: also accepts a zero indicatorWeight with a themed indicator.
8715                let frame = build_frame(tester, true);
8716                tester.pump_widget(frame);
8717            });
8718        }
8719
8720        // 'TabBar accepts indicatorWeight: 0 when the indicator is provided on the widget'.
8721        #[test]
8722        fn a_zero_indicator_weight_is_accepted_with_an_indicator_on_the_widget() {
8723            test_widgets(|tester| {
8724                let theme = theme(tester, None, None);
8725                tester.pump_widget(boilerplate(
8726                    theme,
8727                    TextDirection::Ltr,
8728                    DefaultTabController::new(
8729                        2,
8730                        TabBar::new([
8731                            Tab::new().text("A").into_widget(),
8732                            Tab::new().text("B").into_widget(),
8733                        ])
8734                        .indicator(BoxDecoration::new().color(Color::new(0xFF00FF00)))
8735                        .indicator_weight(0.0),
8736                    ),
8737                ));
8738            });
8739        }
8740
8741        // 'TabBar throws indicatorWeight: 0 with the default underline indicator'.
8742        #[test]
8743        fn a_zero_indicator_weight_panics_with_the_default_underline() {
8744            // Dart pumps both bars into one tester and takes each exception; here the panic
8745            // unwinds the frame, so each bar gets a tester of its own.
8746            for secondary in [false, true] {
8747                test_widgets(|tester| {
8748                    let theme = theme(tester, None, None);
8749                    let tabs = vec![
8750                        Tab::new().text("A").into_widget(),
8751                        Tab::new().text("B").into_widget(),
8752                    ];
8753                    let tab_bar = if secondary {
8754                        TabBar::secondary(tabs)
8755                    } else {
8756                        TabBar::new(tabs)
8757                    }
8758                    .indicator_weight(0.0);
8759                    let frame = boilerplate(
8760                        theme,
8761                        TextDirection::Ltr,
8762                        DefaultTabController::new(2, tab_bar),
8763                    );
8764                    let result = catch_unwind(AssertUnwindSafe(|| tester.pump_widget(frame)));
8765                    let message = panic_message(result.expect_err("the assert fires"));
8766                    assert!(
8767                        message.contains("Invalid indicatorWeight for TabBar."),
8768                        "{message}"
8769                    );
8770                });
8771            }
8772        }
8773
8774        /// The custom indicator cases' scrollable tab bar of three sized tabs with a directional
8775        /// indicator padding.
8776        fn custom_directional_frame(
8777            tester: &WidgetTester,
8778            text_direction: TextDirection,
8779            controller: Ref<TabController>,
8780            tabs: Vec<WidgetRef>,
8781            indicator_color: Color,
8782        ) -> WidgetRef {
8783            let theme = theme(tester, Some(false), None);
8784            boilerplate(
8785                theme,
8786                text_direction,
8787                top_left(
8788                    TabBar::new(tabs)
8789                        .indicator(BoxDecoration::new().color(indicator_color))
8790                        .indicator_padding(EdgeInsetsDirectional::only(8.0, 10.0, 4.0, 12.0))
8791                        .is_scrollable(true)
8792                        .controller(controller),
8793                ),
8794            )
8795        }
8796
8797        // 'TabBar with custom indicator - directional indicatorPadding (LTR)'.
8798        #[test]
8799        fn a_custom_indicator_takes_a_directional_padding_left_to_right() {
8800            test_widgets(|tester| {
8801                let (keys, tabs) = sized_tabs(&[(130.0, 30.0), (140.0, 40.0), (150.0, 50.0)]);
8802                const INDICATOR_COLOR: Color = Color::new(0xFF00FF00);
8803                const PAD_TOP: f64 = 10.0;
8804                const PAD_BOTTOM: f64 = 12.0;
8805                const PAD_START: f64 = 8.0;
8806                const PAD_END: f64 = 4.0;
8807                const INDICATOR_WEIGHT: f64 = 2.0; // the default
8808                let controller = new_controller(tester, 3);
8809                let frame = custom_directional_frame(
8810                    tester,
8811                    TextDirection::Ltr,
8812                    controller.clone(),
8813                    tabs,
8814                    INDICATOR_COLOR,
8815                );
8816                tester.pump_widget(frame);
8817
8818                let tab_bar_box = first_render_box::<TabBar>(tester);
8819                const TAB_BAR_HEIGHT: f64 = 50.0 + INDICATOR_WEIGHT; // 50 = max tab height
8820                assert_eq!(tab_bar_height(tester), TAB_BAR_HEIGHT);
8821
8822                assert_three_tab_rects(
8823                    tester,
8824                    [&keys[0], &keys[1], &keys[2]],
8825                    [(130.0, 30.0), (140.0, 40.0), (150.0, 50.0)],
8826                    TAB_BAR_HEIGHT,
8827                    INDICATOR_WEIGHT,
8828                    LABEL_LEFT,
8829                    LABEL_RIGHT,
8830                );
8831
8832                // Tab 0 selected, indicator padding resolves to left: 8.0, right: 4.0
8833                let indicator_right = 130.0 + LABEL_HORIZONTAL - PAD_END;
8834                assert!(paints_rect(
8835                    tester,
8836                    tab_bar_box,
8837                    Rect::from_ltrb(
8838                        PAD_START,
8839                        PAD_TOP,
8840                        indicator_right,
8841                        TAB_BAR_HEIGHT - PAD_BOTTOM
8842                    ),
8843                    INDICATOR_COLOR,
8844                ));
8845            });
8846        }
8847
8848        // 'TabBar with custom indicator - directional indicatorPadding (RTL)'.
8849        #[test]
8850        fn a_custom_indicator_takes_a_directional_padding_right_to_left() {
8851            test_widgets(|tester| {
8852                let (keys, tabs) = sized_tabs(&[(130.0, 30.0), (140.0, 40.0), (150.0, 50.0)]);
8853                const INDICATOR_COLOR: Color = Color::new(0xFF00FF00);
8854                const PAD_TOP: f64 = 10.0;
8855                const PAD_BOTTOM: f64 = 12.0;
8856                const PAD_START: f64 = 8.0;
8857                const PAD_END: f64 = 4.0;
8858                const INDICATOR_WEIGHT: f64 = 2.0; // the default
8859                let controller = new_controller(tester, 3);
8860                let frame = custom_directional_frame(
8861                    tester,
8862                    TextDirection::Rtl,
8863                    controller.clone(),
8864                    tabs,
8865                    INDICATOR_COLOR,
8866                );
8867                tester.pump_widget(frame);
8868
8869                let tab_bar_box = first_render_box::<TabBar>(tester);
8870                const TAB_BAR_HEIGHT: f64 = 50.0 + INDICATOR_WEIGHT; // 50 = max tab height
8871                assert_eq!(tab_bar_height(tester), TAB_BAR_HEIGHT);
8872
8873                let (tab_left, tab_right, _) = assert_three_tab_rects(
8874                    tester,
8875                    [&keys[2], &keys[1], &keys[0]],
8876                    [(150.0, 50.0), (140.0, 40.0), (130.0, 30.0)],
8877                    TAB_BAR_HEIGHT,
8878                    INDICATOR_WEIGHT,
8879                    LABEL_LEFT,
8880                    LABEL_RIGHT,
8881                );
8882
8883                // Tab 0 selected, indicator padding resolves to left: 4.0, right: 8.0
8884                let indicator_left = tab_left - LABEL_LEFT + PAD_END;
8885                let indicator_right = tab_right + LABEL_LEFT - PAD_START;
8886                assert!(paints_rect(
8887                    tester,
8888                    tab_bar_box,
8889                    Rect::from_ltrb(
8890                        indicator_left,
8891                        PAD_TOP,
8892                        indicator_right,
8893                        TAB_BAR_HEIGHT - PAD_BOTTOM
8894                    ),
8895                    INDICATOR_COLOR,
8896                ));
8897            });
8898        }
8899
8900        // 'TabBar with padding isScrollable: false'.
8901        #[test]
8902        fn a_fixed_tab_bar_is_inset_by_its_padding() {
8903            test_widgets(|tester| {
8904                const INDICATOR_WEIGHT: f64 = 2.0; // default indicator weight
8905                let padding = EdgeInsets::only(3.0, 7.0, 5.0, 3.0);
8906                let (keys, tabs) = sized_tabs(&[(f64::INFINITY, 30.0), (f64::INFINITY, 40.0)]);
8907                let controller = new_controller(tester, 2);
8908                let theme = theme(tester, None, None);
8909                tester.pump_widget(boilerplate(
8910                    theme,
8911                    TextDirection::Ltr,
8912                    top_left(
8913                        TabBar::new(tabs)
8914                            .padding(padding)
8915                            .label_padding(EdgeInsetsGeometry::ZERO)
8916                            .controller(controller),
8917                    ),
8918                ));
8919
8920                let tab_bar_size = tab_bar_size(tester);
8921                let tab_bar_height = 40.0 + INDICATOR_WEIGHT + padding.top + padding.bottom; // 40 = max tab height
8922                assert_eq!(tab_bar_size.height(), tab_bar_height);
8923
8924                let tab_size = (tab_bar_size.width() - padding.horizontal()) / 2.0;
8925
8926                // Tab0 height = 30
8927                let tab_left = padding.left;
8928                let mut tab_right = tab_left + tab_size;
8929                let tab_top = (tab_bar_height - INDICATOR_WEIGHT + (padding.top - padding.bottom)
8930                    - 30.0)
8931                    / 2.0;
8932                let tab_rect = Rect::from_ltrb(tab_left, tab_top, tab_right, tab_top + 30.0);
8933                assert_eq!(rect_of_key(tester, &keys[0]), tab_rect);
8934
8935                // Tab1 height = 40
8936                let tab_left = tab_right;
8937                tab_right = tab_left + tab_size;
8938                let tab_top = (tab_bar_height - INDICATOR_WEIGHT + (padding.top - padding.bottom)
8939                    - 40.0)
8940                    / 2.0;
8941                let tab_rect = Rect::from_ltrb(tab_left, tab_top, tab_right, tab_top + 40.0);
8942                assert_eq!(rect_of_key(tester, &keys[1]), tab_rect);
8943
8944                tab_right += padding.right;
8945                assert_eq!(tab_bar_size.width(), tab_right);
8946            });
8947        }
8948
8949        // 'Material3 - TabBar with padding isScrollable: true'.
8950        #[test]
8951        fn material3_a_scrollable_tab_bar_is_inset_by_its_padding_past_the_start_offset() {
8952            test_widgets(|tester| {
8953                const INDICATOR_WEIGHT: f64 = 2.0; // default indicator weight
8954                let padding = EdgeInsets::only(3.0, 7.0, 5.0, 3.0);
8955                const TAB_START_OFFSET: f64 = 52.0;
8956                let sizes = [(130.0, 30.0), (140.0, 40.0), (150.0, 50.0)];
8957                let (keys, tabs) = sized_tabs(&sizes);
8958                let controller = new_controller(tester, 3);
8959                let theme = theme(tester, None, None);
8960                tester.pump_widget(boilerplate(
8961                    theme,
8962                    TextDirection::Ltr,
8963                    top_left(
8964                        TabBar::new(tabs)
8965                            .padding(padding)
8966                            .label_padding(EdgeInsetsGeometry::ZERO)
8967                            .is_scrollable(true)
8968                            .controller(controller),
8969                    ),
8970                ));
8971
8972                let tab_bar_size = tab_bar_size(tester);
8973                let tab_bar_height = 50.0 + INDICATOR_WEIGHT + padding.top + padding.bottom; // 50 = max tab height
8974                assert_eq!(tab_bar_size.height(), tab_bar_height);
8975
8976                let mut tab_left = padding.left + TAB_START_OFFSET;
8977                let mut tab_right = 0.0;
8978                for (index, (width, height)) in sizes.into_iter().enumerate() {
8979                    if index > 0 {
8980                        tab_left = tab_right;
8981                    }
8982                    tab_right = tab_left + width;
8983                    let tab_top = (tab_bar_height - INDICATOR_WEIGHT
8984                        + (padding.top - padding.bottom)
8985                        - height)
8986                        / 2.0;
8987                    let tab_rect = Rect::from_ltrb(tab_left, tab_top, tab_right, tab_top + height);
8988                    assert_eq!(rect_of_key(tester, &keys[index]), tab_rect);
8989                }
8990
8991                tab_right += padding.right;
8992                // Right tab + remaining space of the stretched tab bar.
8993                assert_eq!(tab_bar_size.width(), tab_right + 320.0);
8994            });
8995        }
8996
8997        // 'TabBar with labelPadding'.
8998        #[test]
8999        fn a_label_padding_spaces_the_tabs_and_the_indicator_follows_it() {
9000            test_widgets(|tester| {
9001                const INDICATOR_WEIGHT: f64 = 2.0; // default indicator weight
9002                let label_padding = EdgeInsets::only(3.0, 0.0, 7.0, 0.0);
9003                let indicator_padding = label_padding;
9004                let (keys, tabs) = sized_tabs(&[(130.0, 30.0), (140.0, 40.0), (150.0, 50.0)]);
9005                let controller = new_controller(tester, 3);
9006                let theme = theme(tester, Some(false), None);
9007                tester.pump_widget(boilerplate(
9008                    theme,
9009                    TextDirection::Ltr,
9010                    top_left(
9011                        TabBar::new(tabs)
9012                            .label_padding(label_padding)
9013                            .indicator_padding(label_padding)
9014                            .is_scrollable(true)
9015                            .controller(controller),
9016                    ),
9017                ));
9018
9019                let tab_bar_box = first_render_box::<TabBar>(tester);
9020                const TAB_BAR_HEIGHT: f64 = 50.0 + INDICATOR_WEIGHT; // 50 = max tab height
9021                assert_eq!(tab_bar_height(tester), TAB_BAR_HEIGHT);
9022
9023                let (_, _, tab_bottom) = assert_three_tab_rects(
9024                    tester,
9025                    [&keys[0], &keys[1], &keys[2]],
9026                    [(130.0, 30.0), (140.0, 40.0), (150.0, 50.0)],
9027                    TAB_BAR_HEIGHT,
9028                    INDICATOR_WEIGHT,
9029                    label_padding.left,
9030                    label_padding.right,
9031                );
9032
9033                // Tab 0 selected, indicatorPadding == labelPadding
9034                let indicator_left = indicator_padding.left + INDICATOR_WEIGHT / 2.0;
9035                let indicator_right = 130.0 + label_padding.horizontal()
9036                    - indicator_padding.right
9037                    - INDICATOR_WEIGHT / 2.0;
9038                let indicator_y = tab_bottom + INDICATOR_WEIGHT / 2.0;
9039                assert!(paints_line(
9040                    tester,
9041                    tab_bar_box,
9042                    None,
9043                    INDICATOR_WEIGHT,
9044                    Offset::new(indicator_left, indicator_y),
9045                    Offset::new(indicator_right, indicator_y),
9046                ));
9047            });
9048        }
9049
9050        // 'TabBar with labelPadding(TabBarIndicatorSize.label)'.
9051        #[test]
9052        fn a_label_sized_indicator_sits_inside_the_label_padding() {
9053            test_widgets(|tester| {
9054                const INDICATOR_WEIGHT: f64 = 2.0; // default indicator weight
9055                let label_padding = EdgeInsets::only(7.0, 0.0, 4.0, 0.0);
9056                let indicator_padding = EdgeInsets::only(3.0, 0.0, 7.0, 0.0);
9057                let (keys, tabs) = sized_tabs(&[(130.0, 30.0), (140.0, 40.0), (150.0, 50.0)]);
9058                let controller = new_controller(tester, 3);
9059                let theme = theme(tester, Some(false), None);
9060                tester.pump_widget(boilerplate(
9061                    theme,
9062                    TextDirection::Ltr,
9063                    top_left(
9064                        TabBar::new(tabs)
9065                            .label_padding(label_padding)
9066                            .indicator_padding(indicator_padding)
9067                            .is_scrollable(true)
9068                            .controller(controller)
9069                            .indicator_size(TabBarIndicatorSize::Label),
9070                    ),
9071                ));
9072
9073                let tab_bar_box = first_render_box::<TabBar>(tester);
9074                const TAB_BAR_HEIGHT: f64 = 50.0 + INDICATOR_WEIGHT; // 50 = max tab height
9075                assert_eq!(tab_bar_height(tester), TAB_BAR_HEIGHT);
9076
9077                let (_, _, tab_bottom) = assert_three_tab_rects(
9078                    tester,
9079                    [&keys[0], &keys[1], &keys[2]],
9080                    [(130.0, 30.0), (140.0, 40.0), (150.0, 50.0)],
9081                    TAB_BAR_HEIGHT,
9082                    INDICATOR_WEIGHT,
9083                    label_padding.left,
9084                    label_padding.right,
9085                );
9086
9087                // Tab 0 selected
9088                let indicator_left =
9089                    indicator_padding.left + label_padding.left + INDICATOR_WEIGHT / 2.0;
9090                let indicator_right =
9091                    label_padding.left + 130.0 - indicator_padding.right - INDICATOR_WEIGHT / 2.0;
9092                let indicator_y = tab_bottom + INDICATOR_WEIGHT / 2.0;
9093                assert!(paints_line(
9094                    tester,
9095                    tab_bar_box,
9096                    None,
9097                    INDICATOR_WEIGHT,
9098                    Offset::new(indicator_left, indicator_y),
9099                    Offset::new(indicator_right, indicator_y),
9100                ));
9101            });
9102        }
9103
9104        // 'Overflowing RTL tab bar'.
9105        #[test]
9106        fn an_overflowing_right_to_left_tab_bar_paints_its_indicator_from_the_far_right() {
9107            test_widgets(|tester| {
9108                // For convenience padded width of each tab will equal 100:
9109                // 68 + kTabLabelPadding.horizontal(32)
9110                let (_, tabs) = sized_tabs(&[(68.0, 40.0); 100]);
9111                let controller = new_controller(tester, 100);
9112                const INDICATOR_WEIGHT: f64 = 2.0; // the default
9113                let theme = theme(tester, Some(false), None);
9114                tester.pump_widget(boilerplate(
9115                    theme,
9116                    TextDirection::Rtl,
9117                    top_left(
9118                        TabBar::new(tabs)
9119                            .is_scrollable(true)
9120                            .controller(controller.clone()),
9121                    ),
9122                ));
9123
9124                let tab_bar_box = first_render_box::<TabBar>(tester);
9125                const TAB_BAR_HEIGHT: f64 = 40.0 + INDICATOR_WEIGHT; // 40 = tab height
9126                assert_eq!(tab_bar_height(tester), TAB_BAR_HEIGHT);
9127
9128                // Tab 0 out of 100 selected
9129                const INDICATOR_Y: f64 = 40.0 + INDICATOR_WEIGHT / 2.0;
9130                assert!(paints_line(
9131                    tester,
9132                    tab_bar_box,
9133                    None,
9134                    INDICATOR_WEIGHT,
9135                    Offset::new(99.0 * 100.0 + INDICATOR_WEIGHT / 2.0, INDICATOR_Y),
9136                    Offset::new(100.0 * 100.0 - INDICATOR_WEIGHT / 2.0, INDICATOR_Y),
9137                ));
9138
9139                {
9140                    let mut app = tester.cell.borrow_mut();
9141                    controller.animate_to(
9142                        &mut app,
9143                        99,
9144                        Some(Duration::from_secs(1)),
9145                        Some(Curves::linear()),
9146                    );
9147                }
9148                tester.pump();
9149                tester.pump_by(Duration::from_millis(500));
9150
9151                // In RTL, the elastic tab animation expands the width of the tab with a negative offset
9152                // when jumping from the first tab to the last tab in a scrollable tab bar.
9153                assert!(paints_line(
9154                    tester,
9155                    tab_bar_box,
9156                    None,
9157                    INDICATOR_WEIGHT,
9158                    Offset::new(4951.0, INDICATOR_Y),
9159                    Offset::new(5049.0, INDICATOR_Y),
9160                ));
9161
9162                tester.pump_by(Duration::from_millis(501));
9163
9164                // Tab 99 out of 100 selected, appears on the far left because RTL.
9165                assert!(paints_line(
9166                    tester,
9167                    tab_bar_box,
9168                    None,
9169                    INDICATOR_WEIGHT,
9170                    Offset::new(INDICATOR_WEIGHT / 2.0, INDICATOR_Y),
9171                    Offset::new(100.0 - INDICATOR_WEIGHT / 2.0, INDICATOR_Y),
9172                ));
9173            });
9174        }
9175
9176        // 'Tab indicator animation test'.
9177        #[test]
9178        fn the_indicator_animates_between_tabs_and_retargets_mid_animation() {
9179            test_widgets(|tester| {
9180                const INDICATOR_WEIGHT: f64 = 8.0;
9181                let controller = new_controller(tester, 4);
9182                let theme = theme(tester, Some(false), None);
9183                tester.pump_widget(boilerplate(
9184                    theme,
9185                    TextDirection::Ltr,
9186                    top_left(
9187                        TabBar::new(text_tabs(4))
9188                            .indicator_weight(INDICATOR_WEIGHT)
9189                            .controller(controller.clone()),
9190                    ),
9191                ));
9192
9193                let tab_bar_box = first_render_box::<TabBar>(tester);
9194                let indicator_at = |tester: &WidgetTester, left: f64, right: f64| {
9195                    const INDICATOR_Y: f64 = 54.0 - INDICATOR_WEIGHT / 2.0;
9196                    paints_line(
9197                        tester,
9198                        tab_bar_box,
9199                        None,
9200                        INDICATOR_WEIGHT,
9201                        Offset::new(left + INDICATOR_WEIGHT / 2.0, INDICATOR_Y),
9202                        Offset::new(right - INDICATOR_WEIGHT / 2.0, INDICATOR_Y),
9203                    )
9204                };
9205                let animate_to = |tester: &WidgetTester, index: usize| {
9206                    let mut app = tester.cell.borrow_mut();
9207                    controller.animate_to(
9208                        &mut app,
9209                        index,
9210                        Some(Duration::from_millis(1000)),
9211                        Some(Curves::linear()),
9212                    );
9213                };
9214
9215                // Initial indicator position.
9216                assert!(indicator_at(tester, 0.0, 200.0));
9217
9218                // Select tab 1.
9219                animate_to(tester, 1);
9220                tester.pump();
9221                tester.pump_by(Duration::from_millis(500));
9222                assert!(indicator_at(tester, 100.0, 300.0));
9223
9224                // Select tab 2 when animation is running.
9225                animate_to(tester, 2);
9226                tester.pump();
9227                tester.pump_by(Duration::from_millis(500));
9228                assert!(indicator_at(tester, 250.0, 450.0));
9229
9230                // Final indicator position.
9231                tester.pump_and_settle();
9232                assert!(indicator_at(tester, 400.0, 600.0));
9233            });
9234        }
9235
9236        /// Dart's `Column(children: [tabBar, Flexible(child: tabBarView)])`.
9237        fn bar_over_view(tab_bar: TabBar, tab_bar_view: TabBarView) -> WidgetRef {
9238            Column::new()
9239                .children([
9240                    tab_bar.into_widget(),
9241                    waft_widgets::Flexible::new(tab_bar_view).into_widget(),
9242                ])
9243                .into_widget()
9244        }
9245
9246        // 'TabBar etc with zero tabs'.
9247        #[test]
9248        fn a_tab_bar_and_view_with_no_tabs_lay_out_and_ignore_flings() {
9249            test_widgets(|tester| {
9250                let controller = new_controller(tester, 0);
9251                let theme = theme(tester, None, None);
9252                tester.pump_widget(boilerplate(
9253                    theme,
9254                    TextDirection::Ltr,
9255                    bar_over_view(
9256                        TabBar::new([]).controller(controller.clone()),
9257                        TabBarView::new([]).controller(controller.clone()),
9258                    ),
9259                ));
9260
9261                assert_eq!(controller.index(&tester.cell.borrow()), 0);
9262                assert_eq!(
9263                    tester.get_size(only::<TabBar>(tester)),
9264                    Size::new(800.0, 48.0)
9265                );
9266                assert_eq!(
9267                    tester.get_size(only::<TabBarView>(tester)),
9268                    Size::new(800.0, 600.0 - 48.0)
9269                );
9270
9271                // A fling in the TabBar or TabBarView, shouldn't do anything.
9272                let bar = tester.get_center(only::<TabBar>(tester));
9273                tester.fling_from(bar, Offset::new(-100.0, 0.0), 5000.0, 1);
9274                tester.pump_and_settle();
9275
9276                let view = tester.get_center(only::<TabBarView>(tester));
9277                tester.fling_from(view, Offset::new(100.0, 0.0), 5000.0, 2);
9278                tester.pump_and_settle();
9279
9280                assert_eq!(controller.index(&tester.cell.borrow()), 0);
9281            });
9282        }
9283
9284        // 'TabBar etc with one tab'.
9285        #[test]
9286        fn a_tab_bar_and_view_with_one_tab_center_it_and_ignore_flings() {
9287            test_widgets(|tester| {
9288                let controller = new_controller(tester, 1);
9289                let theme = theme(tester, None, None);
9290                tester.pump_widget(boilerplate(
9291                    theme,
9292                    TextDirection::Ltr,
9293                    bar_over_view(
9294                        TabBar::new([Tab::new().text("TAB").into_widget()])
9295                            .controller(controller.clone()),
9296                        TabBarView::new([Text::new("PAGE").into_widget()])
9297                            .controller(controller.clone()),
9298                    ),
9299                ));
9300
9301                assert_eq!(controller.index(&tester.cell.borrow()), 0);
9302                expect(tester, &find::text("TAB"), finds_one_widget());
9303                expect(tester, &find::text("PAGE"), finds_one_widget());
9304                assert_eq!(
9305                    tester.get_size(only::<TabBar>(tester)),
9306                    Size::new(800.0, 48.0)
9307                );
9308                assert_eq!(
9309                    tester.get_size(only::<TabBarView>(tester)),
9310                    Size::new(800.0, 600.0 - 48.0)
9311                );
9312
9313                // The one tab should be center vis the app's width (800).
9314                let tab_rect = |tester: &WidgetTester| {
9315                    let tab = tester
9316                        .element(find::ancestor(find::text("TAB"), find::by_type::<Tab>()).first());
9317                    tester.get_rect(tab)
9318                };
9319                let tab_left = tab_rect(tester).left;
9320                let tab_right = tab_rect(tester).right;
9321                // To the precision of the f32 transform `local_to_global` maps through.
9322                let tab_center = tab_left + (tab_right - tab_left) / 2.0;
9323                assert!(close(tab_center, 400.0, 1e-4), "{tab_center}");
9324
9325                // A fling in the TabBar or TabBarView, shouldn't move the tab.
9326                let bar = tester.get_center(only::<TabBar>(tester));
9327                tester.fling_from(bar, Offset::new(-100.0, 0.0), 5000.0, 1);
9328                tester.pump_by(Duration::from_millis(50));
9329                assert_eq!(tab_rect(tester).left, tab_left);
9330                assert_eq!(tab_rect(tester).right, tab_right);
9331                tester.pump_and_settle();
9332
9333                let view = tester.get_center(only::<TabBarView>(tester));
9334                tester.fling_from(view, Offset::new(100.0, 0.0), 5000.0, 2);
9335                tester.pump_by(Duration::from_millis(50));
9336                assert_eq!(tab_rect(tester).left, tab_left);
9337                assert_eq!(tab_rect(tester).right, tab_right);
9338                tester.pump_and_settle();
9339
9340                assert_eq!(controller.index(&tester.cell.borrow()), 0);
9341                expect(tester, &find::text("TAB"), finds_one_widget());
9342                expect(tester, &find::text("PAGE"), finds_one_widget());
9343            });
9344        }
9345
9346        // 'can tap on indicator at very bottom of TabBar to switch tabs'.
9347        #[test]
9348        fn a_tap_on_the_indicator_at_the_bottom_of_a_tab_switches_to_it() {
9349            test_widgets(|tester| {
9350                let controller = new_controller(tester, 2);
9351                let theme = theme(tester, None, None);
9352                tester.pump_widget(boilerplate(
9353                    theme,
9354                    TextDirection::Ltr,
9355                    bar_over_view(
9356                        TabBar::new([
9357                            Tab::new().text("TAB1").into_widget(),
9358                            Tab::new().text("TAB2").into_widget(),
9359                        ])
9360                        .controller(controller.clone())
9361                        .indicator_weight(30.0),
9362                        TabBarView::new([
9363                            Text::new("PAGE1").into_widget(),
9364                            Text::new("PAGE2").into_widget(),
9365                        ])
9366                        .controller(controller.clone()),
9367                    ),
9368                ));
9369
9370                assert_eq!(controller.index(&tester.cell.borrow()), 0);
9371
9372                let bottom_right =
9373                    tester.get_rect(only::<TabBar>(tester)).bottom_right() - Offset::new(1.0, 1.0);
9374                let mut gesture = TestPointer::touch(1);
9375                tester.down(&mut gesture, bottom_right);
9376                tester.up(&gesture);
9377                tester.pump_and_settle();
9378
9379                assert_eq!(controller.index(&tester.cell.borrow()), 1);
9380            });
9381        }
9382
9383        // 'can be notified of TabBar onTap behavior'.
9384        #[test]
9385        fn on_tap_reports_the_tapped_tab_even_when_the_index_does_not_change() {
9386            test_widgets(|tester| {
9387                let tab_index = Rc::new(Cell::new(-1_i64));
9388                let tabs = ["A", "B", "C"];
9389                let controller = {
9390                    let mut app = tester.cell.borrow_mut();
9391                    TabController::new(&mut app, 2, None, tabs.len(), TestVSync)
9392                };
9393                let build_frame = |tester: &WidgetTester| {
9394                    let theme = theme(tester, None, None);
9395                    let tab_index = Rc::clone(&tab_index);
9396                    boilerplate(
9397                        theme,
9398                        TextDirection::Ltr,
9399                        TabBar::new(tabs.iter().map(|tab| Tab::new().text(*tab).into_widget()))
9400                            .controller(controller.clone())
9401                            .on_tap(move |_app, index| tab_index.set(index as i64)),
9402                    )
9403                };
9404                let index = |tester: &WidgetTester| controller.index(&tester.cell.borrow());
9405                let previous_index =
9406                    |tester: &WidgetTester| controller.previous_index(&tester.cell.borrow());
9407
9408                let frame = build_frame(tester);
9409                tester.pump_widget(frame);
9410                expect(tester, &find::text("A"), finds_one_widget());
9411                expect(tester, &find::text("B"), finds_one_widget());
9412                expect(tester, &find::text("C"), finds_one_widget());
9413                assert_eq!(index(tester), 2);
9414                assert_eq!(tab_index.get(), -1); // no tap so far so tabIndex should reflect that
9415
9416                // Verify whether the [onTap] notification works when the [TabBar] animates.
9417                let frame = build_frame(tester);
9418                tester.pump_widget(frame);
9419                let b = text(tester, "B");
9420                tap(tester, b);
9421                tester.pump();
9422                assert!(controller.index_is_changing(&tester.cell.borrow()));
9423                tester.pump_and_settle();
9424                assert_eq!(index(tester), 1);
9425                assert_eq!(previous_index(tester), 2);
9426                assert!(!controller.index_is_changing(&tester.cell.borrow()));
9427                assert_eq!(tab_index.get(), index(tester) as i64);
9428
9429                tab_index.set(-1);
9430
9431                let frame = build_frame(tester);
9432                tester.pump_widget(frame);
9433                let c = text(tester, "C");
9434                tap(tester, c);
9435                tester.pump();
9436                tester.pump_and_settle();
9437                assert_eq!(index(tester), 2);
9438                assert_eq!(previous_index(tester), 1);
9439                assert_eq!(tab_index.get(), index(tester) as i64);
9440
9441                tab_index.set(-1);
9442
9443                let frame = build_frame(tester);
9444                tester.pump_widget(frame);
9445                let a = text(tester, "A");
9446                tap(tester, a);
9447                tester.pump();
9448                tester.pump_and_settle();
9449                assert_eq!(index(tester), 0);
9450                assert_eq!(previous_index(tester), 2);
9451                assert_eq!(tab_index.get(), index(tester) as i64);
9452
9453                tab_index.set(-1);
9454
9455                // Verify whether [onTap] is called even when the [TabController] does
9456                // not change.
9457                let current_controller_index = index(tester);
9458                let frame = build_frame(tester);
9459                tester.pump_widget(frame);
9460                let a = text(tester, "A");
9461                tap(tester, a);
9462                tester.pump();
9463                tester.pump_and_settle();
9464                assert_eq!(index(tester), current_controller_index); // controller has not changed
9465                assert_eq!(tab_index.get(), 0);
9466            });
9467        }
9468
9469        /// The message of the panic `tab.into_widget()` raises.
9470        fn tab_constructor_panic(tab: Tab) -> String {
9471            let result = catch_unwind(AssertUnwindSafe(move || {
9472                let _ = tab.into_widget();
9473            }));
9474            panic_message(result.expect_err("the constructor assert fires"))
9475        }
9476
9477        // 'illegal constructor combinations'.
9478        #[test]
9479        fn a_tab_without_content_or_with_both_text_and_child_panics() {
9480            tab_constructor_panic(Tab::new());
9481            tab_constructor_panic(
9482                Tab::new()
9483                    .icon(waft_widgets::Container::new())
9484                    .text("foo")
9485                    .child(waft_widgets::Container::new()),
9486            );
9487            tab_constructor_panic(Tab::new().text("foo").child(waft_widgets::Container::new()));
9488        }
9489
9490        // 'Tab throws clear error when both text and child are set'.
9491        #[test]
9492        fn a_tab_with_both_text_and_child_says_to_give_one() {
9493            let message = tab_constructor_panic(Tab::new().text("Hi").child(Text::new("World")));
9494            assert!(
9495                message.contains("Provide either text or child, not both, when creating a Tab."),
9496                "{message}"
9497            );
9498        }
9499
9500        // 'Tabs changes mouse cursor when a tab is hovered'.
9501        #[test]
9502        fn a_hovered_tab_shows_the_tab_bars_mouse_cursor_or_a_click_cursor() {
9503            use waft_services::{MouseCursorRef, SystemMouseCursors};
9504            test_widgets(|tester| {
9505                let build = |tester: &WidgetTester, mouse_cursor: Option<MouseCursorRef>| {
9506                    let theme = theme(tester, None, None);
9507                    let mut tab_bar =
9508                        TabBar::new(["A", "B"].map(|tab| Tab::new().text(tab).into_widget()));
9509                    if let Some(mouse_cursor) = mouse_cursor {
9510                        tab_bar = tab_bar.mouse_cursor(mouse_cursor);
9511                    }
9512                    material_app(
9513                        theme,
9514                        DefaultTabController::new(
9515                            2,
9516                            Scaffold::new().body(
9517                                waft_widgets::MouseRegion::new()
9518                                    .cursor(SystemMouseCursors::FORBIDDEN.into())
9519                                    .child(tab_bar),
9520                            ),
9521                        )
9522                        .into_widget(),
9523                    )
9524                };
9525                let frame = build(tester, Some(SystemMouseCursors::TEXT.into()));
9526                tester.pump_widget(frame);
9527
9528                let mut mouse = TestPointer::mouse(1, 0);
9529                let first_tab = find::by_type::<Tab>().evaluate(tester)[0];
9530                let center = tester.get_center(first_tab);
9531                tester.add_pointer(&mut mouse, center);
9532                tester.pump();
9533
9534                let text_cursor: MouseCursorRef = SystemMouseCursors::TEXT.into();
9535                assert!(*tester.active_cursor(1) == *text_cursor);
9536
9537                // Test default cursor
9538                let frame = build(tester, None);
9539                tester.pump_widget(frame);
9540                let click: MouseCursorRef = SystemMouseCursors::CLICK.into();
9541                assert!(*tester.active_cursor(1) == *click);
9542            });
9543        }
9544
9545        /// The two-tab tab bar of the controller-change cases.
9546        fn left_right_tab_bar(tester: &WidgetTester, controller: Ref<TabController>) -> WidgetRef {
9547            let theme = theme(tester, Some(false), None);
9548            boilerplate(
9549                theme,
9550                TextDirection::Ltr,
9551                top_left(
9552                    TabBar::new([
9553                        Tab::new().text("LEFT").into_widget(),
9554                        Tab::new().text("RIGHT").into_widget(),
9555                    ])
9556                    .controller(controller),
9557                ),
9558            )
9559        }
9560
9561        // 'TabController changes'.
9562        #[test]
9563        fn a_tab_bar_given_a_new_controller_follows_the_new_one() {
9564            test_widgets(|tester| {
9565                let controller1 = new_controller(tester, 2);
9566                let controller2 = new_controller(tester, 2);
9567
9568                let frame = left_right_tab_bar(tester, controller1.clone());
9569                tester.pump_widget(frame);
9570                let frame = left_right_tab_bar(tester, controller2.clone());
9571                tester.pump_widget(frame);
9572                assert_eq!(controller1.index(&tester.cell.borrow()), 0);
9573                assert_eq!(controller2.index(&tester.cell.borrow()), 0);
9574
9575                const INDICATOR_WEIGHT: f64 = 2.0;
9576                let tab_bar_box = first_render_box::<TabBar>(tester);
9577                assert_eq!(tab_bar_height(tester), 48.0); // 48 = _kTabHeight(46) + indicatorWeight(2.0)
9578
9579                const INDICATOR_Y: f64 = 48.0 - INDICATOR_WEIGHT / 2.0;
9580                assert!(paints_line(
9581                    tester,
9582                    tab_bar_box,
9583                    None,
9584                    INDICATOR_WEIGHT,
9585                    Offset::new(INDICATOR_WEIGHT / 2.0, INDICATOR_Y),
9586                    Offset::new(400.0 - INDICATOR_WEIGHT / 2.0, INDICATOR_Y), // 400 = screen_width / 2
9587                ));
9588
9589                let right = text(tester, "RIGHT");
9590                tap(tester, right);
9591                tester.pump_and_settle();
9592                assert_eq!(controller1.index(&tester.cell.borrow()), 0);
9593                assert_eq!(controller2.index(&tester.cell.borrow()), 1);
9594
9595                // Verify that the TabBar's _IndicatorPainter is now listening to
9596                // tabController2.
9597                assert!(paints_line(
9598                    tester,
9599                    tab_bar_box,
9600                    None,
9601                    INDICATOR_WEIGHT,
9602                    Offset::new(400.0 + INDICATOR_WEIGHT / 2.0, INDICATOR_Y),
9603                    Offset::new(800.0 - INDICATOR_WEIGHT / 2.0, INDICATOR_Y),
9604                ));
9605            });
9606        }
9607
9608        // 'TabController changes while flinging'.
9609        #[test]
9610        fn a_controller_replaced_while_flinging_is_followed_by_the_next_fling() {
9611            test_widgets(|tester| {
9612                let build_frame = |tester: &WidgetTester, controller: Ref<TabController>| {
9613                    let theme = {
9614                        let app = tester.cell.borrow();
9615                        ThemeData::builder()
9616                            .platform(TargetPlatform::IOS)
9617                            .build(&app)
9618                    };
9619                    let length = controller.length(&tester.cell.borrow());
9620                    let mut tabs = vec![
9621                        Tab::new().text("A").into_widget(),
9622                        Tab::new().text("B").into_widget(),
9623                    ];
9624                    let mut children = vec![
9625                        Center::new().child(Text::new("CHILD A")).into_widget(),
9626                        Center::new().child(Text::new("CHILD B")).into_widget(),
9627                    ];
9628                    if length == 3 {
9629                        tabs.push(Tab::new().text("C").into_widget());
9630                        children.push(Center::new().child(Text::new("CHILD C")).into_widget());
9631                    }
9632                    material_app(
9633                        theme,
9634                        Scaffold::new()
9635                            .app_bar(waft_widgets::PreferredSizeWidgetRef::new(
9636                                AppBar::new().title(Text::new("tabs")).bottom(
9637                                    waft_widgets::PreferredSizeWidgetRef::new(
9638                                        TabBar::new(tabs).controller(controller.clone()),
9639                                    ),
9640                                ),
9641                            ))
9642                            .body(TabBarView::new(children).controller(controller.clone()))
9643                            .into_widget(),
9644                    )
9645                };
9646
9647                let controller1 = new_controller(tester, 2);
9648                let controller2 = new_controller(tester, 3);
9649                assert_eq!(controller1.index(&tester.cell.borrow()), 0);
9650                assert_eq!(controller2.index(&tester.cell.borrow()), 0);
9651
9652                let frame = build_frame(tester, controller1.clone());
9653                tester.pump_widget(frame);
9654                let fling_start = tester.get_center(text(tester, "CHILD A"));
9655                tester.fling_from(fling_start, Offset::new(-200.0, 0.0), 10000.0, 1);
9656                tester.pump_by(Duration::from_millis(10)); // start the fling animation
9657
9658                tester.pump_by(Duration::from_millis(10));
9659
9660                let frame = build_frame(tester, controller2.clone()); // replace controller
9661                tester.pump_widget(frame);
9662                tester.fling_from(fling_start, Offset::new(-200.0, 0.0), 10000.0, 2);
9663                tester.pump_and_settle(); // finish the fling animation
9664
9665                assert_eq!(controller1.index(&tester.cell.borrow()), 0);
9666                assert_eq!(controller2.index(&tester.cell.borrow()), 1);
9667            });
9668        }
9669
9670        // 'TabController changes with different initialIndex'.
9671        #[test]
9672        fn a_new_controller_with_the_last_tab_selected_scrolls_it_into_view() {
9673            test_widgets(|tester| {
9674                let last_tab_key = GlobalKey::new();
9675                let build_frame = |tester: &WidgetTester, length: usize| {
9676                    let controller = {
9677                        let mut app = tester.cell.borrow_mut();
9678                        TabController::new(&mut app, length - 1, None, length, TestVSync)
9679                    };
9680                    let theme = theme(tester, None, None);
9681                    let tabs = (0..length).map(|index| {
9682                        let mut tab = Tab::new().text(format!("Tab {index}"));
9683                        if index == length - 1 {
9684                            tab = tab.key(last_tab_key.clone().into());
9685                        }
9686                        SizedBox::new().width(100.0).child(tab).into_widget()
9687                    });
9688                    let frame = boilerplate(
9689                        theme,
9690                        TextDirection::Ltr,
9691                        TabBar::new(tabs)
9692                            .label_padding(EdgeInsetsGeometry::ZERO)
9693                            .controller(controller.clone())
9694                            .is_scrollable(true),
9695                    );
9696                    (controller, frame)
9697                };
9698
9699                let (controller, frame) = build_frame(tester, 10);
9700                tester.pump_widget(frame);
9701                assert_eq!(controller.index(&tester.cell.borrow()), 9);
9702                assert_eq!(tester.get_center(&last_tab_key).dx(), 750.0);
9703
9704                // Rebuild with a new controller with more tabs and last tab selected.
9705                // Last tab should be visible and on the right of the window.
9706                let (controller, frame) = build_frame(tester, 15);
9707                tester.pump_widget(frame);
9708                assert_eq!(controller.index(&tester.cell.borrow()), 14);
9709                assert_eq!(tester.get_center(&last_tab_key).dx(), 750.0);
9710            });
9711        }
9712
9713        /// `tabs_utils.dart`'s `TabBarTestScrollPhysics`.
9714        #[derive(Debug, Default)]
9715        struct TabBarTestScrollPhysics {
9716            parent: Option<ScrollPhysicsRef>,
9717        }
9718
9719        impl ScrollPhysics for TabBarTestScrollPhysics {
9720            fn as_any(&self) -> &dyn std::any::Any {
9721                self
9722            }
9723
9724            fn parent(&self) -> Option<&ScrollPhysicsRef> {
9725                self.parent.as_ref()
9726            }
9727
9728            fn apply_to(&self, ancestor: Option<ScrollPhysicsRef>) -> ScrollPhysicsRef {
9729                Rc::new(TabBarTestScrollPhysics {
9730                    parent: waft_widgets::ScrollPhysicsBase::build_parent(self, ancestor),
9731                })
9732            }
9733
9734            fn apply_physics_to_user_offset(
9735                &self,
9736                _position: &dyn waft_widgets::ScrollMetrics,
9737                offset: f64,
9738            ) -> f64 {
9739                if offset == 10.0 { 20.0 } else { offset }
9740            }
9741
9742            fn spring(&self) -> waft_physics::SpringDescription {
9743                waft_physics::SpringDescription::with_damping_ratio_value(0.5, 500.0, 1.1)
9744            }
9745        }
9746
9747        // 'DefaultTabController changes does not recreate PageController'.
9748        #[test]
9749        fn a_default_tab_controller_with_a_new_length_keeps_the_page_controller() {
9750            test_widgets(|tester| {
9751                let build_frame = |tester: &WidgetTester, length: usize| {
9752                    let theme = theme(tester, None, None);
9753                    boilerplate(
9754                        theme,
9755                        TextDirection::Ltr,
9756                        DefaultTabController::new(
9757                            length,
9758                            TabBarView::new((0..length).map(|index| {
9759                                Center::new()
9760                                    .child(Text::new(format!("Page {index}")))
9761                                    .into_widget()
9762                            }))
9763                            .physics(Rc::new(TabBarTestScrollPhysics::default())),
9764                        )
9765                        .initial_index(length - 1),
9766                    )
9767                };
9768                let page_controller = |tester: &WidgetTester| {
9769                    tester.widget(only::<PageView>(tester), |page_view: &PageView| {
9770                        page_view
9771                            .controller
9772                            .clone()
9773                            .expect("a page view's controller")
9774                    })
9775                };
9776
9777                let frame = build_frame(tester, 15);
9778                tester.pump_widget(frame);
9779                let page_controller1 = page_controller(tester);
9780                let tab_controller = default_controller_of(tester, text(tester, "Page 14"));
9781                assert_eq!(tab_controller.index(&tester.cell.borrow()), 14);
9782                assert_eq!(page_controller1.page(&tester.cell.borrow()), Some(14.0));
9783
9784                // Rebuild with a new default tab controller with more tabs.
9785                let frame = build_frame(tester, 10);
9786                tester.pump_widget(frame);
9787                let page_controller2 = page_controller(tester);
9788                let tab_controller = default_controller_of(tester, text(tester, "Page 9"));
9789                assert_eq!(tab_controller.index(&tester.cell.borrow()), 9);
9790                assert_eq!(page_controller2.page(&tester.cell.borrow()), Some(9.0));
9791
9792                assert_eq!(page_controller1, page_controller2);
9793            });
9794        }
9795
9796        // 'Do not throw when switching between a scrollable TabBar and a non-scrollable TabBar'.
9797        #[test]
9798        fn switching_between_a_scrollable_and_a_fixed_tab_bar_does_not_panic() {
9799            test_widgets(|tester| {
9800                let controller1 = new_controller(tester, 2);
9801                let controller2 = new_controller(tester, 2);
9802                let build_frame = |tester: &WidgetTester, controller, is_scrollable| {
9803                    let theme = theme(tester, None, None);
9804                    boilerplate(
9805                        theme,
9806                        TextDirection::Ltr,
9807                        top_left(
9808                            TabBar::new([
9809                                Tab::new().text("LEFT").into_widget(),
9810                                Tab::new().text("RIGHT").into_widget(),
9811                            ])
9812                            .controller(controller)
9813                            .is_scrollable(is_scrollable),
9814                        ),
9815                    )
9816                };
9817
9818                // Show both controllers once.
9819                let frame = build_frame(tester, controller1.clone(), false);
9820                tester.pump_widget(frame);
9821                let frame = build_frame(tester, controller2.clone(), true);
9822                tester.pump_widget(frame);
9823
9824                // Switch back to the first controller.
9825                let frame = build_frame(tester, controller1, false);
9826                tester.pump_widget(frame);
9827
9828                // Switch back to the second controller.
9829                let frame = build_frame(tester, controller2, true);
9830                tester.pump_widget(frame);
9831            });
9832        }
9833
9834        // 'Default tab indicator color is white in M2 and surfaceVariant in M3'.
9835        #[test]
9836        fn the_default_indicator_line_is_white_in_material2_and_outline_variant_in_material3() {
9837            for material3 in [true, false] {
9838                test_widgets(|tester| {
9839                    let theme = {
9840                        let app = tester.cell.borrow();
9841                        ThemeData::builder()
9842                            .platform(TargetPlatform::Android)
9843                            .use_material3(material3)
9844                            .build(&app)
9845                    };
9846                    let frame = build_left_right_app(
9847                        tester,
9848                        vec!["LEFT", "RIGHT"],
9849                        "LEFT",
9850                        true,
9851                        Some(theme.clone()),
9852                    );
9853                    tester.pump_widget(frame);
9854                    let tab_bar_box = first_render_box::<TabBar>(tester);
9855                    let color = if material3 {
9856                        theme.color_scheme.outline_variant()
9857                    } else {
9858                        Colors::WHITE
9859                    };
9860                    let lines = deep_lines(tester, tab_bar_box.as_object());
9861                    assert!(
9862                        lines
9863                            .iter()
9864                            .any(|line| line.color.to_argb32() == color.to_argb32()),
9865                        "{lines:?}"
9866                    );
9867                });
9868            }
9869        }
9870
9871        // 'Tab indicator color should not be adjusted when disable [automaticIndicatorColorAdjustment]'.
9872        #[test]
9873        fn the_indicator_color_is_not_adjusted_without_automatic_adjustment() {
9874            test_widgets(|tester| {
9875                // Dart's theme is Material 3, the default, so only its Material 3 colour is
9876                // checked: in Material 2 the default indicator is white already
9877                // (`TabsDefaultsM2`), adjusted or not.
9878                let theme = {
9879                    let app = tester.cell.borrow();
9880                    ThemeData::builder()
9881                        .platform(TargetPlatform::Android)
9882                        .build(&app)
9883                };
9884                let frame = build_left_right_app(
9885                    tester,
9886                    vec!["LEFT", "RIGHT"],
9887                    "LEFT",
9888                    false,
9889                    Some(theme.clone()),
9890                );
9891                tester.pump_widget(frame);
9892                let tab_bar_box = first_render_box::<TabBar>(tester);
9893                let color = theme.color_scheme.outline_variant();
9894                let lines = deep_lines(tester, tab_bar_box.as_object());
9895                assert!(
9896                    lines
9897                        .iter()
9898                        .any(|line| line.color.to_argb32() == color.to_argb32()),
9899                    "{lines:?}"
9900                );
9901            });
9902        }
9903
9904        /// Records the haptic feedback the platform is asked for.
9905        #[derive(Default)]
9906        struct FeedbackTester {
9907            haptics: RefCell<Vec<waft_embedder::HapticFeedbackType>>,
9908        }
9909
9910        impl waft_embedder::Haptics for FeedbackTester {
9911            fn feedback(&self, kind: waft_embedder::HapticFeedbackType) {
9912                self.haptics.borrow_mut().push(kind);
9913            }
9914        }
9915
9916        /// A tester whose platform records haptic feedback into the returned tester.
9917        fn feedback_tester() -> (WidgetTester, Rc<FeedbackTester>) {
9918            let feedback = Rc::new(FeedbackTester::default());
9919            let platform = waft_test::TestPlatform::new()
9920                .on(TargetPlatform::Android)
9921                .with_haptics(Rc::clone(&feedback) as Rc<dyn waft_embedder::Haptics>);
9922            let tester = WidgetTester::with_platform(platform);
9923            (tester, feedback)
9924        }
9925
9926        // 'Tab feedback is enabled (default)'.
9927        //
9928        // The click system sound waits with `SystemSound`, so its count is not checked, as in
9929        // ink_well.rs's feedback cases.
9930        #[test]
9931        fn tab_feedback_is_enabled_by_default() {
9932            test_widgets(|_| {
9933                let (mut tester, feedback) = feedback_tester();
9934                let tester = &mut tester;
9935                let theme = theme(tester, None, None);
9936                tester.pump_widget(boilerplate(
9937                    theme,
9938                    TextDirection::Ltr,
9939                    DefaultTabController::new(1, TabBar::new([Tab::new().text("A").into_widget()])),
9940                ));
9941                let ink_well = only::<InkWell>(tester);
9942                tap(tester, ink_well);
9943                tester.pump_by(Duration::from_secs(1));
9944                assert_eq!(feedback.haptics.borrow().len(), 0);
9945
9946                tap(tester, ink_well);
9947                tester.pump_by(Duration::from_secs(1));
9948                assert_eq!(feedback.haptics.borrow().len(), 0);
9949            });
9950        }
9951
9952        // 'Tab feedback is disabled'.
9953        #[test]
9954        fn tab_feedback_can_be_disabled() {
9955            test_widgets(|_| {
9956                let (mut tester, feedback) = feedback_tester();
9957                let tester = &mut tester;
9958                let theme = theme(tester, None, None);
9959                tester.pump_widget(boilerplate(
9960                    theme,
9961                    TextDirection::Ltr,
9962                    DefaultTabController::new(
9963                        1,
9964                        TabBar::new([Tab::new().text("A").into_widget()]).enable_feedback(false),
9965                    ),
9966                ));
9967                let ink_well = only::<InkWell>(tester);
9968                tap(tester, ink_well);
9969                tester.pump_by(Duration::from_secs(1));
9970                assert_eq!(feedback.haptics.borrow().len(), 0);
9971
9972                let center = tester.get_center(ink_well);
9973                tester.long_press_at(center, 1);
9974                tester.pump_by(Duration::from_secs(1));
9975                assert_eq!(feedback.haptics.borrow().len(), 0);
9976            });
9977        }
9978
9979        /// Dart's `WidgetStateProperty.resolveWith` overlay of the overlay color cases.
9980        fn hover_pressed_overlay(pressed: Color) -> WidgetStatePropertyRef<Option<Color>> {
9981            <dyn WidgetStateProperty<Option<Color>>>::resolve_with(move |states| {
9982                if states.contains(&WidgetState::Hovered) {
9983                    return Some(Color::new(0xff00ff00));
9984                }
9985                if states.contains(&WidgetState::Pressed) {
9986                    return Some(pressed);
9987                }
9988                Some(Color::new(0xffbadbad)) // Shouldn't happen.
9989            })
9990        }
9991
9992        fn ink_features_painted(tester: &WidgetTester) -> Vec<Op> {
9993            let ink_features = tester.first::<crate::material::RenderInkFeatures>();
9994            tester.painted_ops_deep(ink_features.as_object())
9995        }
9996
9997        // "Tab's ink well changes color on hover with Tab overlayColor".
9998        #[test]
9999        fn a_hovered_tab_paints_the_overlay_colors_hovered_color() {
10000            test_widgets(|tester| {
10001                let theme = theme(tester, None, None);
10002                tester.pump_widget(boilerplate(
10003                    theme,
10004                    TextDirection::Ltr,
10005                    DefaultTabController::new(
10006                        1,
10007                        TabBar::new([Tab::new().text("A").into_widget()])
10008                            .overlay_color(hover_pressed_overlay(Color::new(0xf00fffff))),
10009                    ),
10010                ));
10011                let mut mouse = TestPointer::mouse(1, 0);
10012                tester.add_pointer(&mut mouse, Offset::ZERO);
10013                let center = tester.get_center(only::<Tab>(tester));
10014                tester.move_to(&mut mouse, center, false);
10015                tester.pump_and_settle();
10016                let painted = ink_features_painted(tester);
10017                assert_paints(
10018                    &painted,
10019                    &[PaintCall::rect_at(
10020                        Rect::from_ltrb(0.0, 276.0, 800.0, 324.0),
10021                        Some(Color::new(0xff00ff00)),
10022                    )],
10023                );
10024            });
10025        }
10026
10027        /// The two skipping cases' app: a 300x200 scaffold, top left, with a tab bar and a view.
10028        fn skipping_app(
10029            tester: &WidgetTester,
10030            controller: Ref<TabController>,
10031            tabs: &[&str],
10032            children: Vec<WidgetRef>,
10033        ) -> WidgetRef {
10034            let theme = theme(tester, None, None);
10035            material_app(
10036                theme,
10037                Align::new()
10038                    .alignment(AlignmentGeometry::TOP_LEFT)
10039                    .child(
10040                        SizedBox::new().width(300.0).height(200.0).child(
10041                            Scaffold::new()
10042                                .app_bar(waft_widgets::PreferredSizeWidgetRef::new(
10043                                    AppBar::new().title(Text::new("tabs")).bottom(
10044                                        waft_widgets::PreferredSizeWidgetRef::new(
10045                                            TabBar::new(
10046                                                tabs.iter()
10047                                                    .map(|tab| Tab::new().text(*tab).into_widget()),
10048                                            )
10049                                            .controller(controller.clone()),
10050                                        ),
10051                                    ),
10052                                ))
10053                                .body(TabBarView::new(children).controller(controller)),
10054                        ),
10055                    )
10056                    .into_widget(),
10057            )
10058        }
10059
10060        // 'Skipping tabs with global key does not crash'.
10061        #[test]
10062        fn skipping_to_a_far_tab_whose_pages_have_global_keys_does_not_panic() {
10063            test_widgets(|tester| {
10064                let tabs = ["Tab1", "Tab2", "Tab3", "Tab4"];
10065                let controller = new_controller(tester, tabs.len());
10066                let children = ["1", "2", "3", "4"]
10067                    .map(|page| Text::new(page).key(GlobalKey::new().into()).into_widget())
10068                    .to_vec();
10069                let frame = skipping_app(tester, controller.clone(), &tabs, children);
10070                tester.pump_widget(frame);
10071                expect(tester, &find::text("1"), finds_one_widget());
10072                expect(tester, &find::text("4"), finds_nothing());
10073                let tab4 = text(tester, "Tab4");
10074                tap(tester, tab4);
10075                tester.pump_and_settle();
10076                assert_eq!(controller.index(&tester.cell.borrow()), 3);
10077                expect(tester, &find::text("4"), finds_one_widget());
10078                expect(tester, &find::text("1"), finds_nothing());
10079            });
10080        }
10081
10082        /// tabs_utils' `TabAlwaysKeepAliveWidget`: a page that always asks to be kept alive.
10083        #[derive(Debug)]
10084        struct TabAlwaysKeepAliveWidget {
10085            key: Option<KeyRef>,
10086        }
10087
10088        impl TabAlwaysKeepAliveWidget {
10089            const TEXT: &str = "AlwaysKeepAlive";
10090        }
10091
10092        impl StatefulWidget for TabAlwaysKeepAliveWidget {
10093            type State = TabAlwaysKeepAliveWidgetState;
10094
10095            fn key(&self) -> Option<&KeyRef> {
10096                self.key.as_ref()
10097            }
10098
10099            fn create_state(&self) -> TabAlwaysKeepAliveWidgetState {
10100                TabAlwaysKeepAliveWidgetState {
10101                    state: StateData::new(),
10102                    keep_alive: waft_widgets::AutomaticKeepAliveClientMixinData::default(),
10103                }
10104            }
10105        }
10106
10107        struct TabAlwaysKeepAliveWidgetState {
10108            state: StateData<TabAlwaysKeepAliveWidget>,
10109            keep_alive: waft_widgets::AutomaticKeepAliveClientMixinData,
10110        }
10111
10112        impl waft_widgets::AutomaticKeepAliveClientMixin for TabAlwaysKeepAliveWidgetState {
10113            fn automatic_keep_alive_client_data(
10114                self: Handle<Self>,
10115                app: &App,
10116            ) -> &waft_widgets::AutomaticKeepAliveClientMixinData {
10117                &app.get(self).keep_alive
10118            }
10119
10120            fn automatic_keep_alive_client_data_mut(
10121                self: Handle<Self>,
10122                app: &mut App,
10123            ) -> &mut waft_widgets::AutomaticKeepAliveClientMixinData {
10124                &mut app.get_mut(self).keep_alive
10125            }
10126
10127            fn want_keep_alive(self: Handle<Self>, _app: &App) -> bool {
10128                true
10129            }
10130        }
10131
10132        impl State for TabAlwaysKeepAliveWidgetState {
10133            type Widget = TabAlwaysKeepAliveWidget;
10134            waft_widgets::state_accessors!();
10135
10136            fn init_state(self: Handle<Self>, app: &mut App) {
10137                waft_widgets::AutomaticKeepAliveClientMixin::init_state(self, app);
10138            }
10139
10140            fn deactivate(self: Handle<Self>, app: &mut App) {
10141                waft_widgets::AutomaticKeepAliveClientMixin::deactivate(self, app);
10142            }
10143
10144            fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
10145                waft_widgets::AutomaticKeepAliveClientMixin::build(self, app);
10146                Text::new(TabAlwaysKeepAliveWidget::TEXT).into_widget()
10147            }
10148        }
10149
10150        // 'Skipping tabs with a KeepAlive child works'.
10151        #[test]
10152        fn skipping_past_a_kept_alive_page_keeps_it() {
10153            test_widgets(|tester| {
10154                // Regression test for https://github.com/flutter/flutter/issues/11895
10155                let tabs = ["Tab1", "Tab2", "Tab3", "Tab4", "Tab5"];
10156                let controller = new_controller(tester, tabs.len());
10157                let children = vec![
10158                    TabAlwaysKeepAliveWidget {
10159                        key: Some(waft_foundation::UniqueKey::new().into()),
10160                    }
10161                    .into_widget(),
10162                    Text::new("2").into_widget(),
10163                    Text::new("3").into_widget(),
10164                    Text::new("4").into_widget(),
10165                    Text::new("5").into_widget(),
10166                ];
10167                let frame = skipping_app(tester, controller.clone(), &tabs, children);
10168                tester.pump_widget(frame);
10169                assert_eq!(
10170                    find::text(TabAlwaysKeepAliveWidget::TEXT)
10171                        .evaluate(tester)
10172                        .len(),
10173                    1
10174                );
10175                expect(tester, &find::text("4"), finds_nothing());
10176                let tab4 = text(tester, "Tab4");
10177                tap(tester, tab4);
10178                tester.pump_and_settle();
10179                tester.pump();
10180                assert_eq!(controller.index(&tester.cell.borrow()), 3);
10181                expect(
10182                    tester,
10183                    &find::text(TabAlwaysKeepAliveWidget::TEXT).skip_offstage(false),
10184                    finds_one_widget(),
10185                );
10186                expect(tester, &find::text("4"), finds_one_widget());
10187            });
10188        }
10189
10190        // 'tabbar does not scroll when viewport dimensions initially change from zero to non-zero'.
10191        #[test]
10192        fn a_scrollable_tab_bar_whose_viewport_grows_from_zero_does_not_animate() {
10193            test_widgets(|tester| {
10194                let tabs = ["NEW MEXICO", "GABBA", "HEY"];
10195                let controller = new_controller(tester, tabs.len());
10196                let build_test_widget = |tester: &WidgetTester, width: f64, height: f64| {
10197                    let theme = theme(tester, None, None);
10198                    material_app(
10199                        theme,
10200                        Center::new()
10201                            .child(
10202                                SizedBox::new().height(height).width(width).child(
10203                                    Scaffold::new()
10204                                        .app_bar(waft_widgets::PreferredSizeWidgetRef::new(
10205                                            AppBar::new().title(Text::new("AppBarBug")).bottom(
10206                                                waft_widgets::PreferredSizeWidgetRef::new(
10207                                                    waft_widgets::PreferredSize::new(
10208                                                        Size::from_height(30.0),
10209                                                        Padding::new(
10210                                                            EdgeInsetsGeometry::symmetric(
10211                                                                0.0, 15.0,
10212                                                            ),
10213                                                        )
10214                                                        .child(
10215                                                            Align::new()
10216                                                                .alignment(
10217                                                                    AlignmentGeometry::CENTER,
10218                                                                )
10219                                                                .child(
10220                                                                    TabBar::new(tabs.map(|tab| {
10221                                                                        Tab::new()
10222                                                                            .text(tab)
10223                                                                            .into_widget()
10224                                                                    }))
10225                                                                    .controller(controller.clone())
10226                                                                    .is_scrollable(true),
10227                                                                ),
10228                                                        ),
10229                                                    ),
10230                                                ),
10231                                            ),
10232                                        ))
10233                                        .body(Center::new().child(Text::new("Hello World"))),
10234                                ),
10235                            )
10236                            .into_widget(),
10237                    )
10238                };
10239
10240                let frame = build_test_widget(tester, 0.0, 0.0);
10241                tester.pump_widget(frame);
10242
10243                let frame = build_test_widget(tester, 300.0, 400.0);
10244                tester.pump_widget(frame);
10245
10246                assert!(!tester.has_running_animations());
10247                assert_eq!(tester.pump_and_settle(), 1); // no more frames are scheduled.
10248            });
10249        }
10250
10251        // 'Number of tabs can be updated dynamically'.
10252        #[test]
10253        fn the_number_of_tabs_can_change_and_the_selection_follows() {
10254            test_widgets(|tester| {
10255                let key = GlobalKey::new();
10256                let build_tabs = |tester: &WidgetTester, tabs: &[&str]| {
10257                    let theme = theme(tester, None, None);
10258                    boilerplate(
10259                        theme,
10260                        TextDirection::Ltr,
10261                        DefaultTabController::new(
10262                            tabs.len(),
10263                            TabBar::new(tabs.iter().map(|tab| Tab::new().text(*tab).into_widget())),
10264                        )
10265                        .key(key.clone().into()),
10266                    )
10267                };
10268                let controller_state = |tester: &WidgetTester| {
10269                    let controller = default_controller_of(tester, text(tester, "A"));
10270                    let app = tester.cell.borrow();
10271                    (
10272                        controller.previous_index(&app),
10273                        controller.index(&app),
10274                        controller.length(&app),
10275                    )
10276                };
10277
10278                let frame = build_tabs(tester, &["A", "B", "C"]);
10279                tester.pump_widget(frame);
10280                let b = text(tester, "B");
10281                tap(tester, b);
10282                tester.pump();
10283                assert_eq!(controller_state(tester), (0, 1, 3));
10284
10285                let frame = build_tabs(tester, &["A", "B"]);
10286                tester.pump_widget(frame);
10287                assert_eq!(controller_state(tester), (0, 1, 2));
10288
10289                let frame = build_tabs(tester, &["A"]);
10290                tester.pump_widget(frame);
10291                assert_eq!(controller_state(tester), (1, 0, 1));
10292
10293                let frame = build_tabs(tester, &["A", "B"]);
10294                tester.pump_widget(frame);
10295                assert_eq!(controller_state(tester), (1, 0, 2));
10296            });
10297        }
10298    }
10299
10300    mod label_colors_lengths_and_alignments {
10301        //! tabs_test.dart cases, part d: from 'TabBar with one tab has correct color' through
10302        //! 'Material3 - Scrollable TabBar without a divider does not expand to full width'.
10303        use waft_embedder::valo::Op;
10304        use waft_rendering::testing::{PaintCall, paints};
10305
10306        use std::cell::{Cell, RefCell};
10307        use std::panic::{AssertUnwindSafe, catch_unwind};
10308
10309        use waft_widgets::{PreferredSizeWidgetRef, StatefulBuilder, WidgetStateColor};
10310
10311        use super::*;
10312        use crate::icon_button::IconButton;
10313        use crate::icons::Icons;
10314        use crate::test_support::PaintInspection;
10315        use crate::text_button::TextButton;
10316        use waft_widgets::testing::TestVSync;
10317
10318        /// Dart's `createTabController(length:, vsync: const TestVSync())`.
10319        fn create_tab_controller(tester: &WidgetTester, length: usize) -> Ref<TabController> {
10320            let mut app = tester.cell.borrow_mut();
10321            TabController::new(&mut app, 0, None, length, TestVSync)
10322        }
10323
10324        /// Dart's `IconTheme.of(tester.element(find.text(text))).color`.
10325        fn icon_color(tester: &WidgetTester, label: &str) -> Option<Color> {
10326            let element = text(tester, label);
10327            let mut app = tester.cell.borrow_mut();
10328            IconTheme::of(&mut app, element)
10329                .color
10330                .as_ref()
10331                .map(AnyColor::color)
10332        }
10333
10334        /// Dart's `tester.renderObject<RenderParagraph>(find.text(text)).text.style!`.
10335        fn paragraph_style(tester: &WidgetTester, label: &str) -> TextStyle {
10336            let render = tester.render_box_of(text(tester, label));
10337            let app = tester.cell.borrow();
10338            let paragraph = render
10339                .as_object()
10340                .downcast::<waft_rendering::RenderParagraph>(&app)
10341                .expect("a Text renders a paragraph");
10342            paragraph
10343                .text(&app)
10344                .style()
10345                .cloned()
10346                .expect("the paragraph's text has a style")
10347        }
10348
10349        fn style_color(style: &TextStyle) -> Option<Color> {
10350            style.color.as_ref().map(AnyColor::color)
10351        }
10352
10353        /// The panic message of `panic`.
10354        fn panic_message(panic: Box<dyn Any + Send>) -> String {
10355            panic
10356                .downcast_ref::<String>()
10357                .cloned()
10358                .or_else(|| {
10359                    panic
10360                        .downcast_ref::<&str>()
10361                        .map(|message| message.to_string())
10362                })
10363                .unwrap_or_default()
10364        }
10365
10366        /// Dart's `tester.pumpWidget(widget)` followed by `tester.takeException()`: the message of
10367        /// the panic the frame raised, if any.
10368        fn pump_and_take_exception(tester: &mut WidgetTester, widget: WidgetRef) -> Option<String> {
10369            catch_unwind(AssertUnwindSafe(|| tester.pump_widget(widget)))
10370                .err()
10371                .map(panic_message)
10372        }
10373
10374        /// Dart's `find.byKey(key)` tapped at its centre.
10375        fn tap_key(tester: &mut WidgetTester, key: &GlobalKey) {
10376            let center = tester.get_center(key);
10377            tester.tap_at(center, 1);
10378        }
10379
10380        /// Dart's `find.widgetWithIcon(Tab, icon)`.
10381        fn tab_with_icon(tester: &WidgetTester, icon: &waft_widgets::IconData) -> AnyElement {
10382            let icon = tester.element(find::by_icon(icon).first());
10383            tester.ancestor_of_type::<Tab>(icon)
10384        }
10385
10386        /// Dart's `find.widgetWithText(W, text).first`: the nearest `W` above the text.
10387        fn nearest_with_text<W: 'static>(tester: &WidgetTester, label: &str) -> AnyElement {
10388            tester.element(find::ancestor(find::text(label), find::by_type::<W>()).first())
10389        }
10390
10391        /// The `PageController` of the only `PageView`: Dart's
10392        /// `tester.widget<PageView>(find.byType(PageView)).controller!`.
10393        fn page_controller(tester: &WidgetTester) -> Ref<PageController> {
10394            tester.widget(only::<PageView>(tester), |page_view: &PageView| {
10395                page_view
10396                    .controller
10397                    .clone()
10398                    .expect("a tab bar view's page view has a controller")
10399            })
10400        }
10401
10402        /// `tabs_utils.dart`'s `TabBody`: logs its state's `init` and `dispose`.
10403        #[derive(Debug)]
10404        struct TabBody {
10405            index: usize,
10406            log: Rc<RefCell<Vec<String>>>,
10407        }
10408
10409        impl StatefulWidget for TabBody {
10410            type State = TabBodyState;
10411
10412            fn create_state(&self) -> TabBodyState {
10413                TabBodyState {
10414                    state: StateData::new(),
10415                }
10416            }
10417        }
10418
10419        struct TabBodyState {
10420            state: StateData<TabBody>,
10421        }
10422
10423        impl State for TabBodyState {
10424            type Widget = TabBody;
10425            waft_widgets::state_accessors!();
10426
10427            fn init_state(self: Handle<Self>, app: &mut App) {
10428                let widget = self.widget(app);
10429                widget
10430                    .log
10431                    .borrow_mut()
10432                    .push(format!("init: {}", widget.index));
10433            }
10434
10435            fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &TabBody) {
10436                assert_eq!(old_widget.index, self.widget(app).index);
10437            }
10438
10439            fn dispose(self: Handle<Self>, app: &mut App) {
10440                let widget = self.widget(app);
10441                widget
10442                    .log
10443                    .borrow_mut()
10444                    .push(format!("dispose: {}", widget.index));
10445            }
10446
10447            fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
10448                Center::new()
10449                    .child(Text::new(format!("{}", self.widget(app).index)))
10450                    .into_widget()
10451            }
10452        }
10453
10454        /// Dart's `Scaffold(appBar: AppBar(bottom: tab_bar, ..), body: body)`.
10455        fn scaffold_with_tab_bar(
10456            app_bar: AppBar,
10457            tab_bar: TabBar,
10458            body: Option<WidgetRef>,
10459        ) -> WidgetRef {
10460            let mut scaffold = Scaffold::new().app_bar(PreferredSizeWidgetRef::new(
10461                app_bar.bottom(PreferredSizeWidgetRef::new(tab_bar)),
10462            ));
10463            if let Some(body) = body {
10464                scaffold = scaffold.body(body);
10465            }
10466            scaffold.into_widget()
10467        }
10468
10469        // Regression test for https://github.com/flutter/flutter/issues/15008.
10470        // 'TabBar with one tab has correct color'.
10471        #[test]
10472        fn a_tab_bar_with_one_tab_gives_it_the_selected_color() {
10473            test_widgets(|tester| {
10474                const SELECTED_TAB_COLOR: Color = Color::new(0x00000001);
10475                const UNSELECTED_TAB_COLOR: Color = Color::new(0x00000002);
10476
10477                let theme = theme(tester, None, None);
10478                tester.pump_widget(boilerplate(
10479                    theme,
10480                    TextDirection::Ltr,
10481                    DefaultTabController::new(
10482                        1,
10483                        TabBar::new([Tab::new().text("A").into_widget()])
10484                            .label_color(SELECTED_TAB_COLOR)
10485                            .unselected_label_color(UNSELECTED_TAB_COLOR),
10486                    ),
10487                ));
10488
10489                assert_eq!(icon_color(tester, "A"), Some(SELECTED_TAB_COLOR));
10490            });
10491        }
10492
10493        /// Dart's `WidgetStateColor.resolveWith` answering `selected` when selected, else
10494        /// `unselected`.
10495        fn selected_state_color(selected: Color, unselected: Color) -> WidgetStateColor {
10496            WidgetStateColor::resolve_with(move |states| {
10497                if states.contains(&WidgetState::Selected) {
10498                    return selected;
10499                }
10500                unselected
10501            })
10502        }
10503
10504        // 'TabBar.labelColor resolves material states'.
10505        #[test]
10506        fn a_widget_state_label_color_resolves_per_tab_selection() {
10507            test_widgets(|tester| {
10508                const TAB1: &str = "Tab 1";
10509                const TAB2: &str = "Tab 2";
10510                const SELECTED_COLOR: Color = Color::new(0xff00ff00);
10511                const UNSELECTED_COLOR: Color = Color::new(0xffff0000);
10512                let label_color = selected_state_color(SELECTED_COLOR, UNSELECTED_COLOR);
10513
10514                // Test labelColor correctly resolves material states.
10515                let theme = theme(tester, None, None);
10516                tester.pump_widget(boilerplate(
10517                    theme,
10518                    TextDirection::Ltr,
10519                    DefaultTabController::new(
10520                        2,
10521                        TabBar::new([Text::new(TAB1).into_widget(), Text::new(TAB2).into_widget()])
10522                            .label_color(label_color),
10523                    ),
10524                ));
10525
10526                assert_eq!(icon_color(tester, TAB1), Some(SELECTED_COLOR));
10527                assert_eq!(icon_color(tester, TAB2), Some(UNSELECTED_COLOR));
10528                assert_eq!(
10529                    style_color(&paragraph_style(tester, TAB1)),
10530                    Some(SELECTED_COLOR)
10531                );
10532                assert_eq!(
10533                    style_color(&paragraph_style(tester, TAB2)),
10534                    Some(UNSELECTED_COLOR)
10535                );
10536            });
10537        }
10538
10539        // 'labelColor & unselectedLabelColor override material state labelColor'.
10540        #[test]
10541        fn plain_label_colors_replace_a_widget_state_label_color() {
10542            test_widgets(|tester| {
10543                const TAB1: &str = "Tab 1";
10544                const TAB2: &str = "Tab 2";
10545                const SELECTED_STATE_COLOR: Color = Color::new(0xff00ff00);
10546                const UNSELECTED_STATE_COLOR: Color = Color::new(0xffff0000);
10547                const SELECTED_COLOR: Color = Color::new(0xff00ffff);
10548                const UNSELECTED_COLOR: Color = Color::new(0xffff12ff);
10549
10550                let build_tab_bar = |tester: &WidgetTester, state_color: bool| {
10551                    let mut tab_bar =
10552                        TabBar::new([Text::new(TAB1).into_widget(), Text::new(TAB2).into_widget()]);
10553                    if state_color {
10554                        tab_bar = tab_bar.label_color(selected_state_color(
10555                            SELECTED_STATE_COLOR,
10556                            UNSELECTED_STATE_COLOR,
10557                        ));
10558                    } else {
10559                        tab_bar = tab_bar
10560                            .label_color(SELECTED_COLOR)
10561                            .unselected_label_color(UNSELECTED_COLOR);
10562                    }
10563                    boilerplate(
10564                        theme(tester, None, None),
10565                        TextDirection::Ltr,
10566                        DefaultTabController::new(2, tab_bar),
10567                    )
10568                };
10569
10570                // Test material state label color.
10571                let frame = build_tab_bar(tester, true);
10572                tester.pump_widget(frame);
10573
10574                assert_eq!(icon_color(tester, TAB1), Some(SELECTED_STATE_COLOR));
10575                assert_eq!(icon_color(tester, TAB2), Some(UNSELECTED_STATE_COLOR));
10576                assert_eq!(
10577                    style_color(&paragraph_style(tester, TAB1)),
10578                    Some(SELECTED_STATE_COLOR)
10579                );
10580                assert_eq!(
10581                    style_color(&paragraph_style(tester, TAB2)),
10582                    Some(UNSELECTED_STATE_COLOR)
10583                );
10584
10585                // Test labelColor & unselectedLabelColor override material state labelColor.
10586                let frame = build_tab_bar(tester, false);
10587                tester.pump_widget(frame);
10588
10589                assert_eq!(icon_color(tester, TAB1), Some(SELECTED_COLOR));
10590                assert_eq!(icon_color(tester, TAB2), Some(UNSELECTED_COLOR));
10591                assert_eq!(
10592                    style_color(&paragraph_style(tester, TAB1)),
10593                    Some(SELECTED_COLOR)
10594                );
10595                assert_eq!(
10596                    style_color(&paragraph_style(tester, TAB2)),
10597                    Some(UNSELECTED_COLOR)
10598                );
10599            });
10600        }
10601
10602        // Regression test for https://github.com/flutter/flutter/issues/32428
10603        // 'Replacing the tabController after disposing the old one'.
10604        #[test]
10605        fn a_tab_bar_takes_a_new_controller_after_the_old_one_is_disposed() {
10606            test_widgets(|tester| {
10607                let controller = Rc::new(RefCell::new(create_tab_controller(tester, 2)));
10608
10609                let theme = theme(tester, None, None);
10610                let shown = Rc::clone(&controller);
10611                tester.pump_widget(material_app(
10612                    theme,
10613                    StatefulBuilder::new(move |app, _context, set_state| {
10614                        let current = shown.borrow().clone();
10615                        let length = current.length(app);
10616                        let replaced = Rc::clone(&shown);
10617                        let change = TextButton::new(
10618                            Some(Listener::new(move |app| {
10619                                let replaced = Rc::clone(&replaced);
10620                                set_state(app, &mut move |app| {
10621                                    replaced.borrow().dispose(app);
10622                                    *replaced.borrow_mut() =
10623                                        TabController::new(app, 0, None, 3, TestVSync);
10624                                });
10625                            })),
10626                            Some(Text::new("Change TabController length")),
10627                        );
10628                        scaffold_with_tab_bar(
10629                            AppBar::new().actions(vec![change.into_widget()]),
10630                            TabBar::new(
10631                                (0..length).map(|index| {
10632                                    Tab::new().text(format!("Tab{index}")).into_widget()
10633                                }),
10634                            )
10635                            .controller(current.clone()),
10636                            Some(
10637                                TabBarView::new((0..length).map(|index| {
10638                                    Center::new()
10639                                        .child(Text::new(format!("Tab {index}")))
10640                                        .into_widget()
10641                                }))
10642                                .controller(current.clone())
10643                                .into_widget(),
10644                            ),
10645                        )
10646                    })
10647                    .into_widget(),
10648                ));
10649
10650                {
10651                    let app = tester.cell.borrow();
10652                    assert_eq!(controller.borrow().index(&app), 0);
10653                    assert_eq!(controller.borrow().length(&app), 2);
10654                }
10655                expect(tester, &find::text("Tab0"), finds_one_widget());
10656                expect(tester, &find::text("Tab1"), finds_one_widget());
10657                expect(tester, &find::text("Tab2"), finds_nothing());
10658
10659                let button = text(tester, "Change TabController length");
10660                tap(tester, button);
10661                tester.pump_and_settle();
10662                {
10663                    let app = tester.cell.borrow();
10664                    assert_eq!(controller.borrow().index(&app), 0);
10665                    assert_eq!(controller.borrow().length(&app), 3);
10666                }
10667                expect(tester, &find::text("Tab0"), finds_one_widget());
10668                expect(tester, &find::text("Tab1"), finds_one_widget());
10669                expect(tester, &find::text("Tab2"), finds_one_widget());
10670            });
10671        }
10672
10673        /// The app of 'DefaultTabController should allow for a length of zero' and of 'Do not crash if
10674        /// the controller and TabBarView are updated at different phases(build and layout) of the same
10675        /// frame': Dart's `BottomAppBar` is not ported, so its `Row` of buttons is the scaffold's
10676        /// bottom navigation bar itself; the cases read neither its size nor its colour.
10677        fn zero_length_app(
10678            tester: &WidgetTester,
10679            add_key: GlobalKey,
10680            delete_key: GlobalKey,
10681            body_in_layout_builder: bool,
10682        ) -> WidgetRef {
10683            let tab_text_content: Rc<RefCell<Vec<String>>> = Rc::new(RefCell::new(Vec::new()));
10684            let theme = theme(tester, None, None);
10685            material_app(
10686                theme,
10687                StatefulBuilder::new(move |_app, _context, set_state| {
10688                    let contents = tab_text_content.borrow().clone();
10689                    let mut app_bar = AppBar::new().title(Text::new("Default TabBar Preview"));
10690                    if !contents.is_empty() {
10691                        app_bar = app_bar.bottom(PreferredSizeWidgetRef::new(
10692                            TabBar::new(
10693                                contents
10694                                    .iter()
10695                                    .map(|content| Tab::new().text(content.clone()).into_widget()),
10696                            )
10697                            .is_scrollable(true),
10698                        ));
10699                    }
10700                    let body_contents = contents.clone();
10701                    let build_body = move || {
10702                        if body_contents.is_empty() {
10703                            Center::new().child(Text::new("No tabs")).into_widget()
10704                        } else {
10705                            TabBarView::new(body_contents.iter().map(|content| {
10706                                Tab::new().text(format!("{content}'s view")).into_widget()
10707                            }))
10708                            .into_widget()
10709                        }
10710                    };
10711                    let body = if body_in_layout_builder {
10712                        waft_widgets::LayoutBuilder::new(move |_app, _context, _constraints| {
10713                            build_body()
10714                        })
10715                        .into_widget()
10716                    } else {
10717                        build_body()
10718                    };
10719                    let added = Rc::clone(&tab_text_content);
10720                    let add_state = set_state.clone();
10721                    let add = IconButton::new(
10722                        Some(Listener::new(move |app| {
10723                            let added = Rc::clone(&added);
10724                            add_state(app, &mut move |_app| {
10725                                let mut contents = added.borrow().clone();
10726                                let next = format!("Tab {}", contents.len() + 1);
10727                                contents.push(next);
10728                                *added.borrow_mut() = contents;
10729                            });
10730                        })),
10731                        waft_widgets::Icon::new(Some(Icons::add())),
10732                    )
10733                    .key(add_key.clone().into());
10734                    let deleted = Rc::clone(&tab_text_content);
10735                    let delete_state = set_state.clone();
10736                    let delete = IconButton::new(
10737                        Some(Listener::new(move |app| {
10738                            let deleted = Rc::clone(&deleted);
10739                            delete_state(app, &mut move |_app| {
10740                                let mut contents = deleted.borrow().clone();
10741                                contents.pop();
10742                                *deleted.borrow_mut() = contents;
10743                            });
10744                        })),
10745                        waft_widgets::Icon::new(Some(Icons::delete())),
10746                    )
10747                    .key(delete_key.clone().into());
10748                    DefaultTabController::new(
10749                        contents.len(),
10750                        Scaffold::new()
10751                            .app_bar(PreferredSizeWidgetRef::new(app_bar))
10752                            .body(body)
10753                            .bottom_navigation_bar(
10754                                Row::new()
10755                                    .main_axis_alignment(MainAxisAlignment::SpaceBetween)
10756                                    .children([add.into_widget(), delete.into_widget()]),
10757                            ),
10758                    )
10759                    .into_widget()
10760                })
10761                .into_widget(),
10762            )
10763        }
10764
10765        // Regression test for https://github.com/flutter/flutter/issues/20292.
10766        // 'DefaultTabController should allow for a length of zero'.
10767        #[test]
10768        fn a_default_tab_controller_can_have_no_tabs() {
10769            test_widgets(|tester| {
10770                let add_key = GlobalKey::new();
10771                let delete_key = GlobalKey::new();
10772                let app = zero_length_app(tester, add_key.clone(), delete_key.clone(), false);
10773                tester.pump_widget(app);
10774
10775                // Initializes with zero tabs properly
10776                expect(tester, &find::text("No tabs"), finds_one_widget());
10777                tap_key(tester, &add_key);
10778                tester.pump_and_settle();
10779                expect(tester, &find::text("Tab 1"), finds_one_widget());
10780                expect(tester, &find::text("Tab 1's view"), finds_one_widget());
10781
10782                // Dynamically updates to zero tabs properly
10783                tap_key(tester, &delete_key);
10784                tester.pump_and_settle();
10785                expect(tester, &find::text("No tabs"), finds_one_widget());
10786            });
10787        }
10788
10789        /// The app of the two 'add tab' / 'remove tab' cases: an `AppBar` whose bottom is a 40 high
10790        /// `PreferredSize` around an `Expanded` `TabBar` of `titles`, with `controller` when given
10791        /// and under a `DefaultTabController` otherwise.
10792        fn add_remove_app(
10793            tester: &WidgetTester,
10794            titles: Rc<RefCell<Vec<String>>>,
10795            controller: Option<Rc<RefCell<Ref<TabController>>>>,
10796            add_key: GlobalKey,
10797            remove_key: GlobalKey,
10798        ) -> WidgetRef {
10799            let theme = theme(tester, None, None);
10800            material_app(
10801                theme,
10802                StatefulBuilder::new(move |_app, _context, set_state| {
10803                    let current_titles = titles.borrow().clone();
10804                    let added = Rc::clone(&titles);
10805                    let added_controller = controller.clone();
10806                    let add_state = set_state.clone();
10807                    let add = TextButton::new(
10808                        Some(Listener::new(move |app| {
10809                            let added = Rc::clone(&added);
10810                            let added_controller = added_controller.clone();
10811                            add_state(app, &mut move |app| {
10812                                let next = format!("Tab {}", added.borrow().len() + 1);
10813                                added.borrow_mut().push(next);
10814                                if let Some(controller) = &added_controller {
10815                                    let length = added.borrow().len();
10816                                    *controller.borrow_mut() =
10817                                        TabController::new(app, 0, None, length, TestVSync);
10818                                }
10819                            });
10820                        })),
10821                        Some(Text::new("Add tab")),
10822                    )
10823                    .key(add_key.clone().into());
10824                    let removed = Rc::clone(&titles);
10825                    let removed_controller = controller.clone();
10826                    let remove_state = set_state.clone();
10827                    let remove = TextButton::new(
10828                        Some(Listener::new(move |app| {
10829                            let removed = Rc::clone(&removed);
10830                            let removed_controller = removed_controller.clone();
10831                            remove_state(app, &mut move |app| {
10832                                removed.borrow_mut().pop();
10833                                if let Some(controller) = &removed_controller {
10834                                    let length = removed.borrow().len();
10835                                    *controller.borrow_mut() =
10836                                        TabController::new(app, 0, None, length, TestVSync);
10837                                }
10838                            });
10839                        })),
10840                        Some(Text::new("Remove tab")),
10841                    )
10842                    .key(remove_key.clone().into());
10843                    let mut tab_bar = TabBar::new(
10844                        current_titles
10845                            .iter()
10846                            .map(|title| Tab::new().text(title.clone()).into_widget()),
10847                    );
10848                    if let Some(controller) = &controller {
10849                        tab_bar = tab_bar.controller(controller.borrow().clone());
10850                    }
10851                    let scaffold = Scaffold::new().app_bar(PreferredSizeWidgetRef::new(
10852                        AppBar::new()
10853                            .actions(vec![add.into_widget(), remove.into_widget()])
10854                            .bottom(PreferredSizeWidgetRef::new(
10855                                waft_widgets::PreferredSize::new(
10856                                    Size::from_height(40.0),
10857                                    Expanded::new(tab_bar),
10858                                ),
10859                            )),
10860                    ));
10861                    match controller {
10862                        Some(_) => scaffold.into_widget(),
10863                        None => {
10864                            DefaultTabController::new(current_titles.len(), scaffold).into_widget()
10865                        }
10866                    }
10867                })
10868                .into_widget(),
10869            )
10870        }
10871
10872        // Regression test for https://github.com/flutter/flutter/issues/94504.
10873        // 'DefaultTabController should allow dynamic length of tabs'.
10874        #[test]
10875        fn a_default_tab_controller_follows_a_changing_number_of_tabs() {
10876            test_widgets(|tester| {
10877                let add_key = GlobalKey::new();
10878                let remove_key = GlobalKey::new();
10879                let titles = Rc::new(RefCell::new(Vec::new()));
10880                let app = add_remove_app(tester, titles, None, add_key.clone(), remove_key.clone());
10881                tester.pump_widget(app);
10882
10883                expect(tester, &find::text("Tab 1"), finds_nothing());
10884                expect(tester, &find::text("Tab 2"), finds_nothing());
10885
10886                tap_key(tester, &add_key); // +1
10887                tester.pump_and_settle();
10888                expect(tester, &find::text("Tab 1"), finds_one_widget());
10889                expect(tester, &find::text("Tab 2"), finds_nothing());
10890
10891                tap_key(tester, &add_key); // +2
10892                tester.pump_and_settle();
10893                expect(tester, &find::text("Tab 1"), finds_one_widget());
10894                expect(tester, &find::text("Tab 2"), finds_one_widget());
10895
10896                tap_key(tester, &remove_key); // -2
10897                tap_key(tester, &remove_key); // -1
10898                tester.pump_and_settle();
10899                expect(tester, &find::text("Tab 1"), finds_nothing());
10900                expect(tester, &find::text("Tab 2"), finds_nothing());
10901            });
10902        }
10903
10904        // Regression test for https://github.com/flutter/flutter/issues/68962.
10905        // 'TabBar - updating to and from zero tabs'.
10906        #[test]
10907        fn a_tab_bar_goes_to_and_from_no_tabs_with_new_controllers() {
10908            test_widgets(|tester| {
10909                let add_key = GlobalKey::new();
10910                let remove_key = GlobalKey::new();
10911                let titles = Rc::new(RefCell::new(Vec::new()));
10912                let controller = Rc::new(RefCell::new(create_tab_controller(tester, 0)));
10913                let app = add_remove_app(
10914                    tester,
10915                    titles,
10916                    Some(controller),
10917                    add_key.clone(),
10918                    remove_key.clone(),
10919                );
10920                tester.pump_widget(app);
10921
10922                expect(tester, &find::text("Tab 1"), finds_nothing());
10923                expect(tester, &find::text("Add tab"), finds_one_widget());
10924                tap_key(tester, &add_key);
10925                tester.pump_and_settle();
10926                expect(tester, &find::text("Tab 1"), finds_one_widget());
10927
10928                tap_key(tester, &remove_key);
10929                tester.pump_and_settle();
10930                expect(tester, &find::text("Tab 1"), finds_nothing());
10931            });
10932        }
10933
10934        // 'TabBar expands vertically to accommodate the Icon and child Text() pair the same amount it
10935        // would expand for Icon and text pair.'
10936        #[test]
10937        fn an_icon_with_a_text_child_tab_bar_is_as_tall_as_an_icon_with_text_one() {
10938            let tab_bar_with_text = TabBar::new([Tab::new()
10939                .icon(waft_widgets::Icon::new(Some(Icons::notifications())))
10940                .text("Test")
10941                .into_widget()]);
10942            let tab_bar_with_text_child = TabBar::new([Tab::new()
10943                .icon(waft_widgets::Icon::new(Some(Icons::notifications())))
10944                .child(Text::new("Test"))
10945                .into_widget()]);
10946
10947            assert_eq!(
10948                tab_bar_with_text.preferred_size(),
10949                tab_bar_with_text_child.preferred_size()
10950            );
10951        }
10952
10953        /// The left edge of the indicator `render` paints in `indicator_color`, as `tabs_utils.dart`'s
10954        /// `TabIndicatorRecordingCanvas` records it: the line's rect inflated by half the default
10955        /// indicator weight. Painted with `app`, so a listener that runs inside a frame can read it.
10956        fn indicator_left(app: &mut App, render: AnyRenderObject, indicator_color: Color) -> f64 {
10957            use waft_embedder::valo::{Op, PaintStyle as ValoPaintStyle};
10958            use waft_rendering::ContainerLayer;
10959            const INDICATOR_WEIGHT: f64 = 2.0;
10960            let layer = waft_rendering::OffsetLayer::new(app, Offset::ZERO);
10961            let container = layer.as_container_layer();
10962            let bounds = render.paint_bounds(app);
10963            let mut context = PaintingContext::new(container, bounds);
10964            context.paint_child(app, render, Offset::ZERO);
10965            context.stop_recording_if_needed(app);
10966            let mut left = None;
10967            let mut child = container.first_child(app);
10968            while let Some(current) = child {
10969                if let Some(picture) = app
10970                    .handle::<waft_rendering::PictureLayer>(current.id())
10971                    .and_then(|picture| picture.picture(app))
10972                {
10973                    for op in waft_embedder::flattened_ops(picture) {
10974                        if let Op::DrawPath { path, paint, .. } = op
10975                            && matches!(paint.style, ValoPaintStyle::Stroke(_))
10976                            && path.elements().count() == 2
10977                            && super::argb32(paint.color) == indicator_color.to_argb32()
10978                        {
10979                            left = Some(f64::from(path.bounds().x) - INDICATOR_WEIGHT / 2.0);
10980                        }
10981                    }
10982                }
10983                child = current.next_sibling(app);
10984            }
10985            left.expect("the indicator line was painted")
10986        }
10987
10988        // 'Setting TabController index should make TabBar indicator immediately pop into the
10989        // position'. Dart's `TabControllerFrame` makes the controller with its state as the vsync;
10990        // here it is made with `TestVSync`, which ticks the same frames.
10991        #[test]
10992        fn setting_the_index_moves_the_indicator_at_once() {
10993            test_widgets(|tester| {
10994                const INDICATOR_COLOR: Color = Color::new(0xFFFF0000);
10995                let tab_controller = create_tab_controller(tester, 3);
10996                let tabs = || ["A", "B", "C"].map(|text| Tab::new().text(text).into_widget());
10997
10998                let theme = theme(tester, Some(false), None);
10999                tester.pump_widget(material_app(
11000                    theme,
11001                    scaffold_with_tab_bar(
11002                        AppBar::new(),
11003                        TabBar::new(tabs())
11004                            .controller(tab_controller.clone())
11005                            .indicator_color(INDICATOR_COLOR),
11006                        Some(
11007                            TabBarView::new(
11008                                ["A", "B", "C"]
11009                                    .map(|text| Center::new().child(Text::new(text)).into_widget()),
11010                            )
11011                            .controller(tab_controller.clone())
11012                            .into_widget(),
11013                        ),
11014                    ),
11015                ));
11016
11017                let tab_bar = tester.render_box_of(only::<TabBar>(tester)).as_object();
11018                let expected_indicator_left = Rc::new(Cell::new(indicator_left(
11019                    &mut tester.cell.borrow_mut(),
11020                    tab_bar,
11021                    INDICATOR_COLOR,
11022                )));
11023
11024                let page_controller = page_controller(tester);
11025                let expected = Rc::clone(&expected_indicator_left);
11026                // Whenever TabBarView scrolls due to changing TabController's index,
11027                // check if indicator stays idle in its expectedIndicatorLeft
11028                let page_controller_listener = Listener::new(move |app| {
11029                    assert_eq!(
11030                        indicator_left(app, tab_bar, INDICATOR_COLOR),
11031                        expected.get()
11032                    );
11033                });
11034
11035                // Moving from index 0 to 2 (distanced tabs)
11036                {
11037                    let mut app = tester.cell.borrow_mut();
11038                    tab_controller.set_index(&mut app, 2);
11039                    expected_indicator_left.set(indicator_left(&mut app, tab_bar, INDICATOR_COLOR));
11040                    Listenable::add_listener(
11041                        &page_controller,
11042                        &mut app,
11043                        page_controller_listener.clone(),
11044                    );
11045                }
11046                tester.pump_and_settle();
11047
11048                // Moving from index 2 to 1 (neighboring tabs)
11049                {
11050                    let mut app = tester.cell.borrow_mut();
11051                    tab_controller.set_index(&mut app, 1);
11052                    expected_indicator_left.set(indicator_left(&mut app, tab_bar, INDICATOR_COLOR));
11053                }
11054                tester.pump_and_settle();
11055                let mut app = tester.cell.borrow_mut();
11056                Listenable::remove_listener(&page_controller, &mut app, &page_controller_listener);
11057            });
11058        }
11059
11060        // Regression test for https://github.com/flutter/flutter/issues/57708
11061        // 'Setting BouncingScrollPhysics on TabBarView does not include ClampingScrollPhysics'.
11062        #[test]
11063        fn bouncing_physics_on_a_tab_bar_view_leave_out_clamping_physics() {
11064            test_widgets(|tester| {
11065                let theme = theme(tester, None, None);
11066                tester.pump_widget(material_app(
11067                    theme,
11068                    DefaultTabController::new(
11069                        10,
11070                        Scaffold::new().body(
11071                            TabBarView::new((0..10).map(|i| {
11072                                Center::new()
11073                                    .child(Text::new(format!("index {i}")))
11074                                    .into_widget()
11075                            }))
11076                            .physics(Rc::new(waft_widgets::BouncingScrollPhysics::new())),
11077                        ),
11078                    )
11079                    .into_widget(),
11080                ));
11081
11082                let physics = tester.widget(only::<PageView>(tester), |page_view: &PageView| {
11083                    page_view
11084                        .physics
11085                        .clone()
11086                        .expect("a tab bar view gives its page view physics")
11087                });
11088                let mut physics = Some(physics);
11089                while let Some(current) = physics {
11090                    assert!(
11091                        !current.as_any().is::<ClampingScrollPhysics>(),
11092                        "{current:?}"
11093                    );
11094                    physics = current.parent().cloned();
11095                }
11096            });
11097        }
11098
11099        // 'TabController.offset changes reflect labelColor'.
11100        #[test]
11101        fn the_controller_offset_lerps_the_label_colors() {
11102            test_widgets(|tester| {
11103                let controller = create_tab_controller(tester, 2);
11104                let first_color: Rc<Cell<Option<Color>>> = Rc::new(Cell::new(None));
11105                let second_color: Rc<Cell<Option<Color>>> = Rc::new(Cell::new(None));
11106
11107                let build_tab_bar = |tester: &WidgetTester, state_color: bool| {
11108                    let first = Rc::clone(&first_color);
11109                    let second = Rc::clone(&second_color);
11110                    let mut tab_bar = TabBar::new([
11111                        waft_widgets::Builder::new(move |app, context| {
11112                            first.set(style_color(&DefaultTextStyle::of(app, context).style));
11113                            Text::new("First").into_widget()
11114                        })
11115                        .into_widget(),
11116                        waft_widgets::Builder::new(move |app, context| {
11117                            second.set(style_color(&DefaultTextStyle::of(app, context).style));
11118                            Text::new("Second").into_widget()
11119                        })
11120                        .into_widget(),
11121                    ])
11122                    .controller(controller.clone())
11123                    .unselected_label_color(Colors::BLACK);
11124                    tab_bar = if state_color {
11125                        // this is a third color to also test if unselectedLabelColor
11126                        // is ignored when labelColor is WidgetStateColor
11127                        tab_bar
11128                            .label_color(selected_state_color(Colors::WHITE, Colors::TRANSPARENT))
11129                    } else {
11130                        tab_bar.label_color(Colors::WHITE)
11131                    };
11132                    boilerplate(theme(tester, None, None), TextDirection::Ltr, tab_bar)
11133                };
11134
11135                let test_label_color =
11136                    |tester: &mut WidgetTester, selected_color: Color, unselected_color: Color| {
11137                        let lerp = |a: Color, b: Color, t: f64| Color::lerp(Some(a), Some(b), t);
11138                        assert_eq!(first_color.get(), Some(selected_color));
11139                        assert_eq!(second_color.get(), Some(unselected_color));
11140
11141                        controller.set_offset(&mut tester.cell.borrow_mut(), 0.6);
11142                        tester.pump();
11143
11144                        assert_eq!(
11145                            first_color.get(),
11146                            lerp(selected_color, unselected_color, 0.6)
11147                        );
11148                        assert_eq!(
11149                            second_color.get(),
11150                            lerp(unselected_color, selected_color, 0.6)
11151                        );
11152
11153                        controller.set_index(&mut tester.cell.borrow_mut(), 1);
11154                        tester.pump();
11155
11156                        assert_eq!(first_color.get(), Some(unselected_color));
11157                        assert_eq!(second_color.get(), Some(selected_color));
11158
11159                        controller.set_offset(&mut tester.cell.borrow_mut(), 0.6);
11160                        tester.pump();
11161
11162                        assert_eq!(first_color.get(), Some(unselected_color));
11163                        assert_eq!(second_color.get(), Some(selected_color));
11164
11165                        controller.set_offset(&mut tester.cell.borrow_mut(), -0.6);
11166                        tester.pump();
11167
11168                        assert_eq!(
11169                            first_color.get(),
11170                            lerp(selected_color, unselected_color, 0.4)
11171                        );
11172                        assert_eq!(
11173                            second_color.get(),
11174                            lerp(unselected_color, selected_color, 0.4)
11175                        );
11176                    };
11177
11178                let frame = build_tab_bar(tester, false);
11179                tester.pump_widget(frame);
11180                test_label_color(tester, Colors::WHITE, Colors::BLACK);
11181
11182                // reset
11183                controller.set_index(&mut tester.cell.borrow_mut(), 0);
11184                tester.pump();
11185
11186                let frame = build_tab_bar(tester, true);
11187                tester.pump_widget(frame);
11188                test_label_color(tester, Colors::WHITE, Colors::TRANSPARENT);
11189            });
11190        }
11191
11192        // 'No crash on dispose'.
11193        #[test]
11194        fn tapping_a_tab_while_its_view_disposes_pages_does_not_panic() {
11195            test_widgets(|tester| {
11196                let theme = theme(tester, None, None);
11197                let icon = |icon: waft_widgets::IconData| {
11198                    waft_widgets::Icon::new(Some(icon)).into_widget()
11199                };
11200                tester.pump_widget(material_app(
11201                    theme,
11202                    DefaultTabController::new(
11203                        3,
11204                        scaffold_with_tab_bar(
11205                            AppBar::new().title(Text::new("Tabs Demo")),
11206                            TabBar::new([
11207                                Tab::new().icon(icon(Icons::directions_car())).into_widget(),
11208                                Tab::new()
11209                                    .icon(icon(Icons::directions_transit()))
11210                                    .into_widget(),
11211                                Tab::new()
11212                                    .icon(icon(Icons::directions_bike()))
11213                                    .into_widget(),
11214                            ]),
11215                            Some(
11216                                TabBarView::new([
11217                                    icon(Icons::directions_car()),
11218                                    icon(Icons::directions_transit()),
11219                                    icon(Icons::directions_bike()),
11220                                ])
11221                                .into_widget(),
11222                            ),
11223                        ),
11224                    )
11225                    .into_widget(),
11226                ));
11227                let bike = tester.element(find::by_icon(&Icons::directions_bike()).first());
11228                // No crash on dispose.
11229                let tapped = catch_unwind(AssertUnwindSafe(|| tap(tester, bike)));
11230                assert!(tapped.is_ok());
11231            });
11232        }
11233
11234        // "TabController's animation value should be in sync with TabBarView's scroll value when user
11235        // interrupts ballistic scroll".
11236        #[test]
11237        fn the_controller_animation_follows_the_page_when_a_touch_interrupts_a_ballistic_scroll() {
11238            test_widgets(|tester| {
11239                let tab_controller = create_tab_controller(tester, 3);
11240
11241                tester.pump_widget(
11242                    Directionality::new(
11243                        TextDirection::Ltr,
11244                        SizedBox::expand().child(
11245                            Center::new().child(
11246                                SizedBox::square(Some(400.0)).child(
11247                                    TabBarView::new(["0", "1", "2"].map(|text| {
11248                                        Center::new().child(Text::new(text)).into_widget()
11249                                    }))
11250                                    .controller(tab_controller.clone()),
11251                                ),
11252                            ),
11253                        ),
11254                    )
11255                    .into_widget(),
11256                );
11257
11258                let page_controller = page_controller(tester);
11259                {
11260                    let app = tester.cell.borrow();
11261                    let position = page_controller.position(&app);
11262                    assert_eq!(tab_controller.index(&app), 0);
11263                    assert_eq!(position.pixels(&app), 0.0);
11264                }
11265
11266                page_controller.jump_to(&mut tester.cell.borrow_mut(), 300.0);
11267                tester.pump();
11268                let animation_value = |tester: &WidgetTester| {
11269                    let app = tester.cell.borrow();
11270                    tab_controller
11271                        .animation(&app)
11272                        .expect("a live controller has an animation")
11273                        .value(&app)
11274                };
11275                assert_eq!(
11276                    Some(animation_value(tester)),
11277                    page_controller.page(&tester.cell.borrow())
11278                );
11279
11280                // Touch TabBarView while ballistic scrolling is happening and
11281                // check if tabController's animation value properly follows page value.
11282                let center = tester.get_center(only::<PageView>(tester));
11283                let mut gesture = TestPointer::touch(1);
11284                tester.down(&mut gesture, center);
11285                tester.pump();
11286                assert_eq!(
11287                    Some(animation_value(tester)),
11288                    page_controller.page(&tester.cell.borrow())
11289                );
11290
11291                // Finish gesture to release resources.
11292                tester.up(&gesture);
11293                tester.pump_and_settle();
11294            });
11295        }
11296
11297        // Regression test for https://github.com/flutter/flutter/issues/14316.
11298        // 'Does not instantiate intermediate tabs during animation'.
11299        #[test]
11300        fn skipping_to_a_distant_tab_builds_no_page_in_between() {
11301            test_widgets(|tester| {
11302                let log = Rc::new(RefCell::new(Vec::new()));
11303                let theme = theme(tester, None, None);
11304                tester.pump_widget(material_app(
11305                    theme,
11306                    DefaultTabController::new(
11307                        5,
11308                        scaffold_with_tab_bar(
11309                            AppBar::new().title(Text::new("Tabs Test")),
11310                            TabBar::new(
11311                                ["car", "transit", "bike", "boat", "bus"]
11312                                    .map(|text| Tab::new().text(text).into_widget()),
11313                            ),
11314                            Some(
11315                                TabBarView::new((0..5).map(|index| {
11316                                    TabBody {
11317                                        index,
11318                                        log: Rc::clone(&log),
11319                                    }
11320                                    .into_widget()
11321                                }))
11322                                .into_widget(),
11323                            ),
11324                        ),
11325                    )
11326                    .into_widget(),
11327                ));
11328
11329                expect(tester, &find::text("0"), finds_one_widget());
11330                expect(tester, &find::text("3"), finds_nothing());
11331                assert_eq!(*log.borrow(), vec!["init: 0"]);
11332
11333                let boat = text(tester, "boat");
11334                tap(tester, boat);
11335                tester.pump_and_settle();
11336
11337                expect(tester, &find::text("0"), finds_nothing());
11338                expect(tester, &find::text("3"), finds_one_widget());
11339
11340                // No other tab got instantiated during the animation.
11341                assert_eq!(*log.borrow(), vec!["init: 0", "init: 3", "dispose: 0"]);
11342            });
11343        }
11344
11345        // This is a regression test for the issue brought up here
11346        // https://github.com/flutter/flutter/issues/79226
11347        // "TabController's animation value should be updated when TabController's index >= tabs's
11348        // length".
11349        #[test]
11350        fn removing_the_selected_last_tab_moves_the_animation_to_the_new_last_tab() {
11351            test_widgets(|tester| {
11352                let tabs = Rc::new(RefCell::new(vec!["A", "B", "C"]));
11353                let theme = theme(tester, None, None);
11354                tester.pump_widget(material_app(
11355                    theme,
11356                    StatefulBuilder::new(move |_app, _context, set_state| {
11357                        let current = tabs.borrow().clone();
11358                        let removed = Rc::clone(&tabs);
11359                        let remove = TextButton::new(
11360                            Some(Listener::new(move |app| {
11361                                let removed = Rc::clone(&removed);
11362                                set_state(app, &mut move |_app| {
11363                                    removed.borrow_mut().pop();
11364                                });
11365                            })),
11366                            Some(Text::new("Remove Last Tab")),
11367                        );
11368                        DefaultTabController::new(
11369                            current.len(),
11370                            scaffold_with_tab_bar(
11371                                AppBar::new().actions(vec![remove.into_widget()]),
11372                                TabBar::new(
11373                                    current
11374                                        .iter()
11375                                        .map(|tab| Tab::new().text(*tab).into_widget()),
11376                                ),
11377                                Some(
11378                                    TabBarView::new(current.iter().map(|tab| {
11379                                        Tab::new().text(format!("Tab child {tab}")).into_widget()
11380                                    }))
11381                                    .into_widget(),
11382                                ),
11383                            ),
11384                        )
11385                        .into_widget()
11386                    })
11387                    .into_widget(),
11388                ));
11389
11390                let get_controller =
11391                    |tester: &WidgetTester| default_controller_of(tester, text(tester, "B"));
11392                let controller = get_controller(tester);
11393
11394                controller.animate_to(
11395                    &mut tester.cell.borrow_mut(),
11396                    2,
11397                    Some(Duration::from_millis(200)),
11398                    Some(Curves::linear()),
11399                );
11400                tester.pump();
11401                tester.pump_by(Duration::from_millis(300));
11402
11403                let controller = get_controller(tester);
11404                {
11405                    let app = tester.cell.borrow();
11406                    assert_eq!(controller.index(&app), 2);
11407                    assert_eq!(controller.animation(&app).expect("live").value(&app), 2.0);
11408                }
11409
11410                let remove = text(tester, "Remove Last Tab");
11411                tap(tester, remove);
11412                tester.pump_and_settle();
11413
11414                let controller = get_controller(tester);
11415                let app = tester.cell.borrow();
11416                assert_eq!(controller.index(&app), 1);
11417                assert_eq!(controller.animation(&app).expect("live").value(&app), 1.0);
11418            });
11419        }
11420
11421        // 'Tab preferredSize gives correct value'.
11422        #[test]
11423        fn a_tab_prefers_46_high_or_72_with_an_icon_and_text() {
11424            test_widgets(|tester| {
11425                let theme = theme(tester, None, None);
11426                tester.pump_widget(material_app(
11427                    theme,
11428                    Material::new()
11429                        .child(
11430                            Row::new().children([
11431                                Tab::new()
11432                                    .icon(waft_widgets::Icon::new(Some(Icons::message())))
11433                                    .into_widget(),
11434                                Tab::new().text("Two").into_widget(),
11435                                Tab::new()
11436                                    .text("Three")
11437                                    .icon(waft_widgets::Icon::new(Some(Icons::chat())))
11438                                    .into_widget(),
11439                            ]),
11440                        )
11441                        .into_widget(),
11442                ));
11443
11444                let preferred = |element: AnyElement| {
11445                    tester.widget(element, |tab: &Tab| tab.preferred_size().size())
11446                };
11447                assert_eq!(
11448                    preferred(tab_with_icon(tester, &Icons::message())),
11449                    Size::from_height(46.0)
11450                );
11451                assert_eq!(
11452                    preferred(nearest_with_text::<Tab>(tester, "Two")),
11453                    Size::from_height(46.0)
11454                );
11455                assert_eq!(
11456                    preferred(nearest_with_text::<Tab>(tester, "Three")),
11457                    Size::from_height(72.0)
11458                );
11459            });
11460        }
11461
11462        /// The `TabBar` above the tab labelled `label`: Dart's
11463        /// `tester.widget<TabBar>(find.widgetWithText(TabBar, label)).preferredSize`.
11464        fn tab_bar_preferred_size(tester: &WidgetTester, label: &str) -> Size {
11465            tester.widget(
11466                nearest_with_text::<TabBar>(tester, label),
11467                |tab_bar: &TabBar| tab_bar.preferred_size().size(),
11468            )
11469        }
11470
11471        // 'TabBar preferredSize gives correct value when there are both icon and text in tabs'.
11472        #[test]
11473        fn a_tab_bar_with_an_icon_and_text_tab_prefers_74_high() {
11474            test_widgets(|tester| {
11475                let theme = theme(tester, None, None);
11476                tester.pump_widget(material_app(
11477                    theme,
11478                    DefaultTabController::new(
11479                        5,
11480                        scaffold_with_tab_bar(
11481                            AppBar::new().title(Text::new("Tabs Test")),
11482                            TabBar::new([
11483                                Tab::new().text("car").into_widget(),
11484                                Tab::new().text("transit").into_widget(),
11485                                Tab::new().text("bike").into_widget(),
11486                                Tab::new()
11487                                    .text("boat")
11488                                    .icon(waft_widgets::Icon::new(Some(Icons::message())))
11489                                    .into_widget(),
11490                                Tab::new().text("bus").into_widget(),
11491                            ]),
11492                            None,
11493                        ),
11494                    )
11495                    .into_widget(),
11496                ));
11497
11498                assert_eq!(
11499                    tab_bar_preferred_size(tester, "car"),
11500                    Size::from_height(74.0)
11501                );
11502            });
11503        }
11504
11505        // 'TabBar preferredSize gives correct value when there is only icon or text in tabs'.
11506        #[test]
11507        fn a_tab_bar_of_icon_or_text_tabs_prefers_48_high() {
11508            test_widgets(|tester| {
11509                let theme = theme(tester, None, None);
11510                tester.pump_widget(material_app(
11511                    theme,
11512                    DefaultTabController::new(
11513                        5,
11514                        scaffold_with_tab_bar(
11515                            AppBar::new().title(Text::new("Tabs Test")),
11516                            TabBar::new([
11517                                Tab::new().text("car").into_widget(),
11518                                Tab::new()
11519                                    .icon(waft_widgets::Icon::new(Some(Icons::message())))
11520                                    .into_widget(),
11521                                Tab::new().text("bike").into_widget(),
11522                                Tab::new()
11523                                    .icon(waft_widgets::Icon::new(Some(Icons::chat())))
11524                                    .into_widget(),
11525                                Tab::new().text("bus").into_widget(),
11526                            ]),
11527                            None,
11528                        ),
11529                    )
11530                    .into_widget(),
11531                ));
11532
11533                assert_eq!(
11534                    tab_bar_preferred_size(tester, "car"),
11535                    Size::from_height(48.0)
11536                );
11537            });
11538        }
11539
11540        /// The three uniform padding cases: a tab bar of an icon and text tab and two text tabs in
11541        /// an app bar, with `label_padding` when given, under `theme`; answers the label padding of
11542        /// each tab, the nearest `Padding` above its text.
11543        fn uniform_paddings(
11544            tester: &mut WidgetTester,
11545            theme: ThemeData,
11546            label_padding: Option<EdgeInsetsGeometry>,
11547        ) -> [EdgeInsetsGeometry; 3] {
11548            let controller = create_tab_controller(tester, 3);
11549            let mut tab_bar = TabBar::new([
11550                Tab::new()
11551                    .text("Tab 1")
11552                    .icon(waft_widgets::Icon::new(Some(Icons::plus_one())))
11553                    .into_widget(),
11554                Tab::new().text("Tab 2").into_widget(),
11555                Tab::new().text("Tab 3").into_widget(),
11556            ])
11557            .controller(controller);
11558            if let Some(label_padding) = label_padding {
11559                tab_bar = tab_bar.label_padding(label_padding);
11560            }
11561            tester.pump_widget(material_app(
11562                theme,
11563                scaffold_with_tab_bar(AppBar::new(), tab_bar, None),
11564            ));
11565            ["Tab 1", "Tab 2", "Tab 3"].map(|label| {
11566                tester.widget(
11567                    nearest_with_text::<Padding>(tester, label),
11568                    |padding: &Padding| padding.padding,
11569                )
11570            })
11571        }
11572
11573        // 'Tabs are given uniform padding in case of few tabs having both text and icon'.
11574        #[test]
11575        fn text_tabs_beside_an_icon_and_text_tab_get_vertical_padding() {
11576            test_widgets(|tester| {
11577                let expected_padding_adjusted = EdgeInsetsGeometry::symmetric(13.0, 16.0);
11578                let expected_padding_default = EdgeInsetsGeometry::symmetric(0.0, 16.0);
11579
11580                let theme = theme(tester, None, None);
11581                let [tab_one, tab_two, tab_three] = uniform_paddings(tester, theme, None);
11582
11583                assert_eq!(tab_one, expected_padding_default);
11584                assert_eq!(tab_two, expected_padding_adjusted);
11585                assert_eq!(tab_three, expected_padding_adjusted);
11586            });
11587        }
11588
11589        // 'Tabs are given uniform padding when labelPadding is given'.
11590        #[test]
11591        fn text_tabs_beside_an_icon_and_text_tab_add_vertical_padding_to_the_label_padding() {
11592            test_widgets(|tester| {
11593                let label_padding = EdgeInsetsGeometry::symmetric(10.0, 20.0);
11594                let expected_padding_adjusted = EdgeInsetsGeometry::symmetric(23.0, 20.0);
11595                let expected_padding_default = EdgeInsetsGeometry::symmetric(10.0, 20.0);
11596
11597                let theme = theme(tester, None, None);
11598                let [tab_one, tab_two, tab_three] =
11599                    uniform_paddings(tester, theme, Some(label_padding));
11600
11601                assert_eq!(tab_one, expected_padding_default);
11602                assert_eq!(tab_two, expected_padding_adjusted);
11603                assert_eq!(tab_three, expected_padding_adjusted);
11604            });
11605        }
11606
11607        // 'Tabs are given uniform padding TabBarTheme.labelPadding is given'.
11608        #[test]
11609        fn text_tabs_beside_an_icon_and_text_tab_add_vertical_padding_to_the_theme_label_padding() {
11610            test_widgets(|tester| {
11611                let label_padding = EdgeInsetsGeometry::symmetric(15.0, 20.0);
11612                let expected_padding_adjusted = EdgeInsetsGeometry::symmetric(28.0, 20.0);
11613                let expected_padding_default = EdgeInsetsGeometry::symmetric(15.0, 20.0);
11614
11615                let theme = theme(
11616                    tester,
11617                    None,
11618                    Some(TabBarThemeData::new().label_padding(label_padding)),
11619                );
11620                let [tab_one, tab_two, tab_three] = uniform_paddings(tester, theme, None);
11621
11622                assert_eq!(tab_one, expected_padding_default);
11623                assert_eq!(tab_two, expected_padding_adjusted);
11624                assert_eq!(tab_three, expected_padding_adjusted);
11625            });
11626        }
11627
11628        // 'Change tab bar height'.
11629        #[test]
11630        fn every_kind_of_tab_takes_the_height_it_is_given() {
11631            test_widgets(|tester| {
11632                let theme = theme(tester, Some(false), None);
11633                let style = TextStyle::new().font_size(25.0);
11634                tester.pump_widget(material_app(
11635                    theme,
11636                    DefaultTabController::new(
11637                        4,
11638                        scaffold_with_tab_bar(
11639                            AppBar::new(),
11640                            TabBar::new([
11641                                Tab::new()
11642                                    .icon(waft_widgets::Icon::new(Some(Icons::check())).size(40.0))
11643                                    .height(85.0)
11644                                    .child(Text::new("1 - OK").style(style.clone()))
11645                                    .into_widget(), // icon and child
11646                                Tab::new()
11647                                    .height(85.0)
11648                                    .child(Text::new("2 - OK").style(style.clone()))
11649                                    .into_widget(), // child
11650                                Tab::new()
11651                                    .icon(waft_widgets::Icon::new(Some(Icons::done())).size(40.0))
11652                                    .height(85.0)
11653                                    .into_widget(), // icon
11654                                Tab::new().text("4 - OK").height(85.0).into_widget(), // text
11655                            ]),
11656                            None,
11657                        ),
11658                    )
11659                    .into_widget(),
11660                ));
11661                let first_tab = tab_with_icon(tester, &Icons::check());
11662                let sec_tab = nearest_with_text::<Tab>(tester, "2 - OK");
11663                let third_tab = tab_with_icon(tester, &Icons::done());
11664                let fourth_tab = nearest_with_text::<Tab>(tester, "4 - OK");
11665                assert_eq!(
11666                    tester.widget(first_tab, |tab: &Tab| tab.preferred_size().size().height()),
11667                    85.0
11668                );
11669                for tab in [first_tab, sec_tab, third_tab, fourth_tab] {
11670                    assert_eq!(tester.widget(tab, |tab: &Tab| tab.height), Some(85.0));
11671                }
11672            });
11673        }
11674
11675        // 'Change tab bar height 2'.
11676        #[test]
11677        fn an_icon_and_text_tab_takes_the_height_it_is_given() {
11678            test_widgets(|tester| {
11679                let theme = theme(tester, None, None);
11680                tester.pump_widget(material_app(
11681                    theme,
11682                    DefaultTabController::new(
11683                        1,
11684                        scaffold_with_tab_bar(
11685                            AppBar::new(),
11686                            TabBar::new([Tab::new()
11687                                .icon(waft_widgets::Icon::new(Some(Icons::check())).size(40.0))
11688                                .text("1 - OK")
11689                                .height(85.0)
11690                                .into_widget()]), // icon and text
11691                            None,
11692                        ),
11693                    )
11694                    .into_widget(),
11695                ));
11696                let first_tab = tab_with_icon(tester, &Icons::check());
11697                assert_eq!(tester.widget(first_tab, |tab: &Tab| tab.height), Some(85.0));
11698            });
11699        }
11700
11701        /// The two controller-swap cases' `buildFrame`: a column of a tab bar and a tab bar view of
11702        /// `controller`, with a third tab when `show_last`.
11703        fn controller_swap_frame(
11704            tester: &WidgetTester,
11705            controller: Ref<TabController>,
11706            show_last: bool,
11707        ) -> WidgetRef {
11708            let mut tabs = vec![
11709                Tab::new().text("one").into_widget(),
11710                Tab::new().text("two").into_widget(),
11711            ];
11712            let mut pages = vec![
11713                Text::new("PAGE1").into_widget(),
11714                Text::new("PAGE2").into_widget(),
11715            ];
11716            if show_last {
11717                tabs.push(Tab::new().text("three").into_widget());
11718                pages.push(Text::new("PAGE3").into_widget());
11719            }
11720            boilerplate(
11721                theme(tester, None, None),
11722                TextDirection::Ltr,
11723                Column::new().children([
11724                    TabBar::new(tabs)
11725                        .controller(controller.clone())
11726                        .into_widget(),
11727                    waft_widgets::Flexible::new(TabBarView::new(pages).controller(controller))
11728                        .into_widget(),
11729                ]),
11730            )
11731        }
11732
11733        // This is a regression test for https://github.com/flutter/flutter/issues/93237
11734        // 'Change the TabController should make both TabBar and TabBarView return to the initial
11735        // index.'
11736        #[test]
11737        fn a_new_controller_returns_the_tab_bar_and_its_view_to_the_new_index() {
11738            test_widgets(|tester| {
11739                let controller1 = create_tab_controller(tester, 3);
11740                let controller2 = create_tab_controller(tester, 2);
11741                let controller3 = create_tab_controller(tester, 3);
11742
11743                let frame = controller_swap_frame(tester, controller1.clone(), true);
11744                tester.pump_widget(frame);
11745                let page_controller = page_controller(tester);
11746                let three = text(tester, "three");
11747                tap(tester, three);
11748                tester.pump_and_settle();
11749                {
11750                    let app = tester.cell.borrow();
11751                    assert_eq!(controller1.index(&app), 2);
11752                    assert_eq!(page_controller.page(&app), Some(2.0));
11753                }
11754
11755                // Change TabController from 3 items to 2.
11756                let frame = controller_swap_frame(tester, controller2.clone(), false);
11757                tester.pump_widget(frame);
11758                tester.pump_and_settle();
11759                {
11760                    let app = tester.cell.borrow();
11761                    assert_eq!(controller2.index(&app), 0);
11762                    assert_eq!(page_controller.page(&app), Some(0.0));
11763                }
11764
11765                // Change TabController from 2 items to 3.
11766                let frame = controller_swap_frame(tester, controller3.clone(), true);
11767                tester.pump_widget(frame);
11768                tester.pump_and_settle();
11769                {
11770                    let app = tester.cell.borrow();
11771                    assert_eq!(controller3.index(&app), 0);
11772                    assert_eq!(page_controller.page(&app), Some(0.0));
11773                }
11774
11775                let three = text(tester, "three");
11776                tap(tester, three);
11777                tester.pump_and_settle();
11778
11779                let app = tester.cell.borrow();
11780                assert_eq!(controller3.index(&app), 2);
11781                assert_eq!(page_controller.page(&app), Some(2.0));
11782            });
11783        }
11784
11785        // This is a regression test for https://github.com/flutter/flutter/issues/97441
11786        // 'Do not crash when the new TabController.index is longer than the old length.'
11787        #[test]
11788        fn going_back_to_a_controller_whose_index_the_other_lacked_does_not_panic() {
11789            test_widgets(|tester| {
11790                let controller1 = create_tab_controller(tester, 3);
11791                let controller2 = create_tab_controller(tester, 2);
11792
11793                let frame = controller_swap_frame(tester, controller1.clone(), true);
11794                tester.pump_widget(frame);
11795                let three = text(tester, "three");
11796                tap(tester, three);
11797                tester.pump_and_settle();
11798                {
11799                    let page_controller = page_controller(tester);
11800                    let app = tester.cell.borrow();
11801                    assert_eq!(controller1.index(&app), 2);
11802                    assert_eq!(page_controller.page(&app), Some(2.0));
11803                }
11804
11805                // Change TabController from controller1 to controller2.
11806                let frame = controller_swap_frame(tester, controller2.clone(), false);
11807                tester.pump_widget(frame);
11808                tester.pump_and_settle();
11809                {
11810                    let page_controller = page_controller(tester);
11811                    let app = tester.cell.borrow();
11812                    assert_eq!(controller2.index(&app), 0);
11813                    assert_eq!(page_controller.page(&app), Some(0.0));
11814                }
11815
11816                // Change TabController back to 'controller1' whose index is 2.
11817                let frame = controller_swap_frame(tester, controller1.clone(), true);
11818                tester.pump_widget(frame);
11819                tester.pump_and_settle();
11820                let page_controller = page_controller(tester);
11821                let app = tester.cell.borrow();
11822                assert_eq!(controller1.index(&app), 2);
11823                assert_eq!(page_controller.page(&app), Some(2.0));
11824            });
11825        }
11826
11827        /// The splash factory and overlay colour of the only `InkWell`.
11828        fn ink_well_splash_and_overlay(
11829            tester: &WidgetTester,
11830        ) -> (
11831            Option<InteractiveInkFeatureFactoryRef>,
11832            Option<WidgetStatePropertyRef<Option<Color>>>,
11833        ) {
11834            tester.widget(only::<InkWell>(tester), |ink_well: &InkWell| {
11835                (
11836                    ink_well.ink_response.splash_factory.clone(),
11837                    ink_well.ink_response.overlay_color.clone(),
11838                )
11839            })
11840        }
11841
11842        // 'TabBar InkWell splashFactory and overlayColor'.
11843        #[test]
11844        fn the_tab_ink_wells_take_the_splash_factory_and_overlay_color() {
11845            test_widgets(|tester| {
11846                let splash_factory = crate::no_splash::NoSplash::splash_factory();
11847                let overlay_color: WidgetStatePropertyRef<Option<Color>> =
11848                    <dyn WidgetStateProperty<Option<Color>>>::resolve_with(|_states| {
11849                        Some(Colors::TRANSPARENT)
11850                    });
11851                let green_tab = || {
11852                    waft_widgets::Container::new()
11853                        .width(100.0)
11854                        .height(100.0)
11855                        .color(Colors::GREEN.primary())
11856                        .into_widget()
11857                };
11858
11859                // TabBarTheme splashFactory and overlayColor
11860                let theme_with_tab_bar = theme(
11861                    tester,
11862                    None,
11863                    Some(
11864                        TabBarThemeData::new()
11865                            .splash_factory(Rc::clone(&splash_factory))
11866                            .overlay_color(Rc::clone(&overlay_color)),
11867                    ),
11868                );
11869                tester.pump_widget(material_app(
11870                    theme_with_tab_bar,
11871                    DefaultTabController::new(
11872                        1,
11873                        scaffold_with_tab_bar(AppBar::new(), TabBar::new([green_tab()]), None),
11874                    )
11875                    .into_widget(),
11876                ));
11877
11878                let (splash, overlay) = ink_well_splash_and_overlay(tester);
11879                assert!(Rc::ptr_eq(
11880                    &splash.expect("a splash factory"),
11881                    &splash_factory
11882                ));
11883                assert!(Rc::ptr_eq(
11884                    &overlay.expect("an overlay color"),
11885                    &overlay_color
11886                ));
11887
11888                // TabBar splashFactory and overlayColor
11889                let default_theme = theme(tester, None, None);
11890                tester.pump_widget(material_app(
11891                    default_theme,
11892                    DefaultTabController::new(
11893                        1,
11894                        scaffold_with_tab_bar(
11895                            AppBar::new(),
11896                            TabBar::new([green_tab()])
11897                                .splash_factory(Rc::clone(&splash_factory))
11898                                .overlay_color(Rc::clone(&overlay_color)),
11899                            None,
11900                        ),
11901                    )
11902                    .into_widget(),
11903                ));
11904                tester.pump_and_settle(); // theme animation
11905                let (splash, overlay) = ink_well_splash_and_overlay(tester);
11906                assert!(Rc::ptr_eq(
11907                    &splash.expect("a splash factory"),
11908                    &splash_factory
11909                ));
11910                assert!(Rc::ptr_eq(
11911                    &overlay.expect("an overlay color"),
11912                    &overlay_color
11913                ));
11914            });
11915        }
11916
11917        // 'splashBorderRadius is passed to InkWell.borderRadius'.
11918        #[test]
11919        fn the_splash_border_radius_rounds_the_tab_hover_highlight() {
11920            test_widgets(|tester| {
11921                const HOVER_COLOR: Color = Color::new(0xfff44336);
11922                const RADIUS: f64 = 20.0;
11923                let theme = theme(tester, None, None);
11924                tester.pump_widget(boilerplate(
11925                    theme,
11926                    TextDirection::Ltr,
11927                    DefaultTabController::new(
11928                        1,
11929                        TabBar::new([Tab::new().child(Text::new("")).into_widget()])
11930                            .overlay_color(<dyn WidgetStateProperty<Option<Color>>>::resolve_with(
11931                                |states| {
11932                                    if states.contains(&WidgetState::Hovered) {
11933                                        return Some(HOVER_COLOR);
11934                                    }
11935                                    Some(Colors::BLACK54)
11936                                },
11937                            ))
11938                            .splash_border_radius(BorderRadius::all(
11939                                waft_embedder::Radius::circular(RADIUS),
11940                            )),
11941                    ),
11942                ));
11943                tester.pump_and_settle();
11944                let mut gesture = TestPointer::mouse(1, 0);
11945                let center = tester.get_center(only::<Tab>(tester));
11946                tester.add_pointer(&mut gesture, Offset::ZERO);
11947                tester.move_to(&mut gesture, center, false);
11948                tester.pump_and_settle();
11949                let object = tester.first::<crate::material::RenderInkFeatures>();
11950                let ink_well_rect = tester.get_rect(only::<InkWell>(tester));
11951                waft_rendering::testing::assert_paints(
11952                    &tester.painted_ops(object.as_object()),
11953                    &[waft_rendering::testing::PaintCall::rrect_at(
11954                        waft_embedder::RRect::from_rect_and_radius(
11955                            ink_well_rect,
11956                            waft_embedder::Radius::circular(RADIUS),
11957                        ),
11958                        Some(HOVER_COLOR),
11959                    )],
11960                );
11961            });
11962        }
11963
11964        // Regression test for https://github.com/flutter/flutter/issues/154484.
11965        // 'No crash if TabBar build called before didUpdateWidget with SliverAppBar'.
11966        #[test]
11967        fn a_sliver_app_bar_tab_bar_gaining_its_first_tab_does_not_panic() {
11968            test_widgets(|tester| {
11969                let tabs: Rc<RefCell<Vec<String>>> = Rc::new(RefCell::new(Vec::new()));
11970                let theme = theme(tester, None, None);
11971                tester.pump_widget(material_app(
11972                    theme,
11973                    StatefulBuilder::new(move |_app, _context, set_state| {
11974                        let current = tabs.borrow().clone();
11975                        let added = Rc::clone(&tabs);
11976                        let add = TextButton::new(
11977                            Some(Listener::new(move |app| {
11978                                let added = Rc::clone(&added);
11979                                set_state(app, &mut move |_app| {
11980                                    let next = format!("Tab {}", added.borrow().len() + 1);
11981                                    added.borrow_mut().push(next);
11982                                });
11983                            })),
11984                            Some(Text::new("Add Tab")),
11985                        );
11986                        DefaultTabController::new(
11987                            current.len(),
11988                            Scaffold::new().body(
11989                                waft_widgets::CustomScrollView::new().slivers([
11990                                    crate::app_bar::SliverAppBar::new()
11991                                        .actions(vec![add.into_widget()])
11992                                        .bottom(PreferredSizeWidgetRef::new(TabBar::new(
11993                                            current.iter().map(|tab| {
11994                                                Tab::new().text(tab.clone()).into_widget()
11995                                            }),
11996                                        )))
11997                                        .into_widget(),
11998                                ]),
11999                            ),
12000                        )
12001                        .into_widget()
12002                    })
12003                    .into_widget(),
12004                ));
12005
12006                // Initializes with zero tabs.
12007                expect(tester, &find::text("Tab 1"), finds_nothing());
12008                expect(tester, &find::text("Tab 2"), finds_nothing());
12009
12010                // No crash after tabs added.
12011                let add = text(tester, "Add Tab");
12012                let added = catch_unwind(AssertUnwindSafe(|| {
12013                    tap(tester, add);
12014                    tester.pump_and_settle();
12015                }));
12016                assert!(added.is_ok());
12017                expect(tester, &find::text("Tab 1"), finds_one_widget());
12018                expect(tester, &find::text("Tab 2"), finds_nothing());
12019            });
12020        }
12021
12022        // Regression test for https://github.com/flutter/flutter/issues/104994.
12023        // 'Do not crash if the controller and TabBarView are updated at different phases(build and
12024        // layout) of the same frame'.
12025        #[test]
12026        fn a_tab_bar_view_built_in_layout_follows_a_controller_built_earlier_in_the_frame() {
12027            test_widgets(|tester| {
12028                let add_key = GlobalKey::new();
12029                let delete_key = GlobalKey::new();
12030                let app = zero_length_app(tester, add_key.clone(), delete_key.clone(), true);
12031                tester.pump_widget(app);
12032
12033                // Initializes with zero tabs properly
12034                expect(tester, &find::text("No tabs"), finds_one_widget());
12035                tap_key(tester, &add_key);
12036                tester.pump_and_settle();
12037                expect(tester, &find::text("Tab 1"), finds_one_widget());
12038                expect(tester, &find::text("Tab 1's view"), finds_one_widget());
12039
12040                // Dynamically updates to zero tabs properly
12041                tap_key(tester, &delete_key);
12042                tester.pump_and_settle();
12043                expect(tester, &find::text("No tabs"), finds_one_widget());
12044            });
12045        }
12046
12047        /// A green 100 square, the tab of the two length-mismatch cases.
12048        fn green_square() -> WidgetRef {
12049            waft_widgets::Container::new()
12050                .width(100.0)
12051                .height(100.0)
12052                .color(Colors::GREEN.primary())
12053                .into_widget()
12054        }
12055
12056        // "Throw if the controller's length mismatch the tabs count".
12057        #[test]
12058        fn a_controller_longer_than_the_tabs_panics() {
12059            test_widgets(|tester| {
12060                let theme = theme(tester, None, None);
12061                let exception = pump_and_take_exception(
12062                    tester,
12063                    material_app(
12064                        theme,
12065                        DefaultTabController::new(
12066                            2,
12067                            scaffold_with_tab_bar(
12068                                AppBar::new(),
12069                                TabBar::new([green_square()]),
12070                                None,
12071                            ),
12072                        )
12073                        .into_widget(),
12074                    ),
12075                );
12076                let exception = exception.expect("the length check fails");
12077                assert!(
12078                    exception.contains("does not match the number of tabs"),
12079                    "{exception}"
12080                );
12081            });
12082        }
12083
12084        // "Throw if the controller's length mismatch the TabBarView‘s children count".
12085        #[test]
12086        fn a_tab_bar_view_with_more_children_than_the_controller_panics() {
12087            test_widgets(|tester| {
12088                let theme = theme(tester, None, None);
12089                let icon = |icon: waft_widgets::IconData| {
12090                    waft_widgets::Icon::new(Some(icon)).into_widget()
12091                };
12092                let exception = pump_and_take_exception(
12093                    tester,
12094                    material_app(
12095                        theme,
12096                        DefaultTabController::new(
12097                            1,
12098                            scaffold_with_tab_bar(
12099                                AppBar::new(),
12100                                TabBar::new([green_square()]),
12101                                Some(
12102                                    TabBarView::new([
12103                                        icon(Icons::directions_car()),
12104                                        icon(Icons::directions_transit()),
12105                                        icon(Icons::directions_bike()),
12106                                    ])
12107                                    .into_widget(),
12108                                ),
12109                            ),
12110                        )
12111                        .into_widget(),
12112                    ),
12113                );
12114                let exception = exception.expect("the length check fails");
12115                assert!(
12116                    exception.contains("does not match the number of children"),
12117                    "{exception}"
12118                );
12119            });
12120        }
12121
12122        fn paints_rect_of(ops: &[Op], color: Color) -> bool {
12123            paints(ops, &[PaintCall::rect(Some(color))]).is_ok()
12124        }
12125
12126        fn ink_features_painted(tester: &WidgetTester) -> Vec<Op> {
12127            let ink_features = tester.first::<crate::material::RenderInkFeatures>();
12128            tester.painted_ops_deep(ink_features.as_object())
12129        }
12130
12131        #[allow(deprecated)]
12132        fn with_opacity(color: Color, opacity: f64) -> Color {
12133            color.with_opacity(opacity)
12134        }
12135
12136        // 'Tab has correct selected/unselected hover color'.
12137        #[test]
12138        fn an_unselected_and_a_selected_tab_hover_in_different_colors() {
12139            test_widgets(|tester| {
12140                tester.set_highlight_strategy(
12141                    waft_widgets::FocusHighlightStrategy::AlwaysTraditional,
12142                );
12143                let theme = theme(tester, None, None);
12144                let mut frame = Frame::new(vec!["A", "B", "C"], "C");
12145                frame.use_material3 = Some(theme.use_material3);
12146                let frame = frame.build(tester);
12147                tester.pump_widget(frame);
12148
12149                tester.pump_and_settle();
12150                let unselected = with_opacity(theme.color_scheme.on_surface(), 0.08);
12151                let selected = with_opacity(theme.color_scheme.primary(), 0.08);
12152                assert!(!paints_rect_of(&ink_features_painted(tester), unselected));
12153                assert!(!paints_rect_of(&ink_features_painted(tester), selected));
12154
12155                // Start hovering unselected tab.
12156                let mut gesture = TestPointer::mouse(1, 0);
12157                tester.add_pointer(&mut gesture, Offset::ZERO);
12158                let first = find::by_type::<Tab>().evaluate(tester)[0];
12159                let first_center = tester.get_center(first);
12160                tester.move_to(&mut gesture, first_center, false);
12161                tester.pump_and_settle();
12162                assert!(paints_rect_of(&ink_features_painted(tester), unselected));
12163
12164                // Start hovering selected tab.
12165                let last = *find::by_type::<Tab>()
12166                    .evaluate(tester)
12167                    .last()
12168                    .expect("tabs");
12169                let last_center = tester.get_center(last);
12170                tester.move_to(&mut gesture, last_center, false);
12171                tester.pump_and_settle();
12172                assert!(paints_rect_of(&ink_features_painted(tester), selected));
12173            });
12174        }
12175
12176        /// Whether the primary focus is a node that has it: Dart's
12177        /// `tester.binding.focusManager.primaryFocus?.hasPrimaryFocus`.
12178        fn primary_focus_has_primary_focus(tester: &WidgetTester) -> bool {
12179            let mut app = tester.cell.borrow_mut();
12180            let manager = waft_widgets::FocusManager::instance(&mut app);
12181            manager
12182                .primary_focus(&app)
12183                .is_some_and(|node| node.has_primary_focus(&app))
12184        }
12185
12186        // 'Tab has correct selected/unselected focus color'.
12187        #[test]
12188        fn an_unselected_and_a_selected_tab_focus_in_different_colors() {
12189            test_widgets(|tester| {
12190                tester.set_highlight_strategy(
12191                    waft_widgets::FocusHighlightStrategy::AlwaysTraditional,
12192                );
12193                let theme = theme(tester, None, None);
12194                let mut frame = Frame::new(vec!["A", "B", "C"], "B");
12195                frame.use_material3 = Some(theme.use_material3);
12196                let frame = frame.build(tester);
12197                tester.pump_widget(material_app(theme.clone(), frame));
12198
12199                tester.pump_and_settle();
12200                let unselected = with_opacity(theme.color_scheme.on_surface(), 0.1);
12201                let selected = with_opacity(theme.color_scheme.primary(), 0.1);
12202                assert!(!paints_rect_of(&ink_features_painted(tester), unselected));
12203                assert!(!paints_rect_of(&ink_features_painted(tester), selected));
12204
12205                tester.send_key_event(
12206                    waft_services::PhysicalKeyboardKey::TAB,
12207                    waft_services::LogicalKeyboardKey::TAB,
12208                );
12209                tester.pump_and_settle();
12210                assert!(primary_focus_has_primary_focus(tester));
12211                assert!(paints_rect_of(&ink_features_painted(tester), unselected));
12212
12213                tester.send_key_event(
12214                    waft_services::PhysicalKeyboardKey::TAB,
12215                    waft_services::LogicalKeyboardKey::TAB,
12216                );
12217                tester.pump_and_settle();
12218                assert!(primary_focus_has_primary_focus(tester));
12219                assert!(paints_rect_of(&ink_features_painted(tester), selected));
12220            });
12221        }
12222
12223        // 'Tab has correct selected/unselected pressed color'.
12224        #[test]
12225        fn pressing_an_unselected_or_a_selected_tab_highlights_in_the_primary_color() {
12226            test_widgets(|tester| {
12227                let theme = theme(tester, None, None);
12228                let mut frame = Frame::new(vec!["A", "B", "C"], "B");
12229                frame.use_material3 = Some(theme.use_material3);
12230                let frame = frame.build(tester);
12231                tester.pump_widget(material_app(theme.clone(), frame));
12232
12233                tester.pump_and_settle();
12234                let pressed = with_opacity(theme.color_scheme.primary(), 0.1);
12235                assert!(!paints_rect_of(&ink_features_painted(tester), pressed));
12236
12237                // Press unselected tab.
12238                let mut gesture = TestPointer::touch(1);
12239                let a = tester.get_center(text(tester, "A"));
12240                tester.down(&mut gesture, a);
12241                tester.pump_and_settle(); // Let the press highlight animation finish.
12242                assert!(paints_rect_of(&ink_features_painted(tester), pressed));
12243
12244                // Release pressed gesture.
12245                tester.up(&gesture);
12246                tester.pump_and_settle();
12247
12248                // Press selected tab.
12249                let mut gesture = TestPointer::touch(2);
12250                let b = tester.get_center(text(tester, "B"));
12251                tester.down(&mut gesture, b);
12252                tester.pump_and_settle(); // Let the press highlight animation finish.
12253                assert!(paints_rect_of(&ink_features_painted(tester), pressed));
12254            });
12255        }
12256
12257        /// Dart's `moreOrLessEquals` epsilon, 1e-10, at the precision of the f32 transforms
12258        /// `local_to_global` goes through: a tab's global left comes back within 1e-6 of Dart's.
12259        const F32_EPSILON: f64 = 1e-4;
12260
12261        /// Dart's `expect(a, equals(b))` on a global coordinate, to the precision of
12262        /// [`F32_EPSILON`].
12263        fn assert_f32_eq(a: f64, b: f64) {
12264            assert!(close(a, b, F32_EPSILON), "{a} != {b}");
12265        }
12266
12267        /// The rects of the first and the last `Tab`.
12268        fn first_and_last_tab_rects(tester: &WidgetTester) -> (Rect, Rect) {
12269            let tabs = find::by_type::<Tab>().evaluate(tester);
12270            (
12271                tester.get_rect(tabs[0]),
12272                tester.get_rect(*tabs.last().expect("tabs")),
12273            )
12274        }
12275
12276        // 'Material3 - Default TabAlignment'.
12277        #[test]
12278        fn material3_tabs_fill_a_fixed_tab_bar_and_start_offset_in_a_scrollable_one() {
12279            test_widgets(|tester| {
12280                const TAB_START_OFFSET: f64 = 52.0;
12281                let padding = K_TAB_LABEL_PADDING;
12282
12283                // Test default TabAlignment when isScrollable is false.
12284                let frame = Frame::new(vec!["A", "B"], "B").build(tester);
12285                tester.pump_widget(frame);
12286
12287                let tab_bar = tester.get_rect(only::<TabBar>(tester));
12288                let (tab_one_rect, tab_two_rect) = first_and_last_tab_rects(tester);
12289
12290                // Tabs should fill the width of the TabBar.
12291                let tab_one_left = ((tab_bar.width() / 2.0) - tab_one_rect.width()) / 2.0;
12292                assert!(
12293                    close(tab_one_rect.left, tab_one_left, F32_EPSILON),
12294                    "{} {}",
12295                    tab_one_rect.left,
12296                    tab_one_left
12297                );
12298                let tab_two_right =
12299                    tab_bar.width() - ((tab_bar.width() / 2.0) - tab_two_rect.width()) / 2.0;
12300                assert!(
12301                    close(tab_two_rect.right, tab_two_right, F32_EPSILON),
12302                    "{} {}",
12303                    tab_two_rect.right,
12304                    tab_two_right
12305                );
12306
12307                // Test default TabAlignment when isScrollable is true.
12308                let mut frame = Frame::new(vec!["A", "B"], "B");
12309                frame.is_scrollable = true;
12310                let frame = frame.build(tester);
12311                tester.pump_widget(frame);
12312
12313                let (tab_one_rect, tab_two_rect) = first_and_last_tab_rects(tester);
12314
12315                // Tabs should be aligned to the start of the TabBar.
12316                let tab_one_left = padding.left + TAB_START_OFFSET;
12317                assert!(
12318                    close(tab_one_rect.left, tab_one_left, F32_EPSILON),
12319                    "{} {}",
12320                    tab_one_rect.left,
12321                    tab_one_left
12322                );
12323                let tab_two_right = padding.horizontal()
12324                    + TAB_START_OFFSET
12325                    + tab_one_rect.width()
12326                    + padding.left
12327                    + tab_two_rect.width();
12328                assert!(
12329                    close(tab_two_rect.right, tab_two_right, F32_EPSILON),
12330                    "{} {}",
12331                    tab_two_rect.right,
12332                    tab_two_right
12333                );
12334            });
12335        }
12336
12337        /// A `buildFrame` of tabs A and B on B with `tab_alignment`, scrollable when `is_scrollable`,
12338        /// inside a `MaterialApp` of the default theme; answers the panic its frame raised.
12339        fn alignment_exception(
12340            tester: &mut WidgetTester,
12341            tab_alignment: TabAlignment,
12342            is_scrollable: bool,
12343        ) -> Option<String> {
12344            let theme = theme(tester, None, None);
12345            let mut frame = Frame::new(vec!["A", "B"], "B");
12346            frame.tab_alignment = Some(tab_alignment);
12347            frame.is_scrollable = is_scrollable;
12348            let frame = frame.build(tester);
12349            pump_and_take_exception(tester, material_app(theme, frame))
12350        }
12351
12352        // 'TabAlignment.fill only supports non-scrollable tab bar'.
12353        #[test]
12354        fn fill_alignment_panics_on_a_scrollable_tab_bar() {
12355            test_widgets(|tester| {
12356                // Test TabAlignment.fill with non-scrollable tab bar.
12357                assert_eq!(alignment_exception(tester, TabAlignment::Fill, false), None);
12358
12359                // Test TabAlignment.fill with scrollable tab bar.
12360                let mut fresh = WidgetTester::on(waft_embedder::TargetPlatform::Android);
12361                let tester = &mut fresh;
12362                let exception = alignment_exception(tester, TabAlignment::Fill, true)
12363                    .expect("the alignment assert fails");
12364                assert!(
12365                    exception.contains("is only valid for non-scrollable tab bars"),
12366                    "{exception}"
12367                );
12368            });
12369        }
12370
12371        // 'TabAlignment.start & TabAlignment.startOffset only supports scrollable tab bar'.
12372        #[test]
12373        fn start_alignments_panic_on_a_fixed_tab_bar() {
12374            test_widgets(|tester| {
12375                for alignment in [TabAlignment::Start, TabAlignment::StartOffset] {
12376                    // Test the alignment with scrollable tab bar.
12377                    assert_eq!(alignment_exception(tester, alignment, true), None);
12378
12379                    // Test the alignment with non-scrollable tab bar.
12380                    let mut fresh = WidgetTester::on(waft_embedder::TargetPlatform::Android);
12381                    let tester = &mut fresh;
12382                    let exception = alignment_exception(tester, alignment, false)
12383                        .expect("the alignment assert fails");
12384                    assert!(
12385                        exception.contains("is only valid for scrollable tab bars"),
12386                        "{exception}"
12387                    );
12388                }
12389            });
12390        }
12391
12392        /// A `buildFrame` of tabs A and B on B.
12393        fn alignment_frame(
12394            tester: &WidgetTester,
12395            is_scrollable: bool,
12396            tab_alignment: Option<TabAlignment>,
12397            text_direction: TextDirection,
12398        ) -> WidgetRef {
12399            let mut frame = Frame::new(vec!["A", "B"], "B");
12400            frame.is_scrollable = is_scrollable;
12401            frame.tab_alignment = tab_alignment;
12402            frame.text_direction = text_direction;
12403            frame.build(tester)
12404        }
12405
12406        // 'Material3 - TabAlignment updates tabs alignment (non-scrollable TabBar)'.
12407        #[test]
12408        fn material3_center_alignment_packs_the_tabs_of_a_fixed_tab_bar() {
12409            test_widgets(|tester| {
12410                let padding = K_TAB_LABEL_PADDING;
12411
12412                // Test TabAlignment.fill (default) when isScrollable is false.
12413                let frame = alignment_frame(tester, false, None, TextDirection::Ltr);
12414                tester.pump_widget(frame);
12415
12416                const AVAILABLE_WIDTH: f64 = 800.0;
12417                let (tab_one_rect, tab_two_rect) = first_and_last_tab_rects(tester);
12418
12419                // By defaults tabs should fill the width of the TabBar.
12420                let tab_one_left = ((AVAILABLE_WIDTH / 2.0) - tab_one_rect.width()) / 2.0;
12421                assert!(close(tab_one_rect.left, tab_one_left, F32_EPSILON));
12422                let tab_two_right =
12423                    AVAILABLE_WIDTH - ((AVAILABLE_WIDTH / 2.0) - tab_two_rect.width()) / 2.0;
12424                assert!(close(tab_two_rect.right, tab_two_right, F32_EPSILON));
12425
12426                // Test TabAlignment.center when isScrollable is false.
12427                let frame = alignment_frame(
12428                    tester,
12429                    false,
12430                    Some(TabAlignment::Center),
12431                    TextDirection::Ltr,
12432                );
12433                tester.pump_widget(frame);
12434                tester.pump_and_settle();
12435
12436                let (tab_one_rect, tab_two_rect) = first_and_last_tab_rects(tester);
12437
12438                // Tabs should not fill the width of the TabBar.
12439                let tab_one_left = padding.left;
12440                assert!(close(tab_one_rect.left, tab_one_left, F32_EPSILON));
12441                let tab_two_right = padding.horizontal()
12442                    + tab_one_rect.width()
12443                    + padding.left
12444                    + tab_two_rect.width();
12445                assert!(close(tab_two_rect.right, tab_two_right, F32_EPSILON));
12446            });
12447        }
12448
12449        // 'Material3 - TabAlignment updates tabs alignment (scrollable TabBar)'.
12450        #[test]
12451        fn material3_alignments_place_the_tabs_of_a_scrollable_tab_bar() {
12452            test_widgets(|tester| {
12453                const TAB_START_OFFSET: f64 = 52.0;
12454                let padding = K_TAB_LABEL_PADDING;
12455
12456                // Test TabAlignment.startOffset (default) when isScrollable is true.
12457                let frame = alignment_frame(tester, true, None, TextDirection::Ltr);
12458                tester.pump_widget(frame);
12459
12460                let tab_bar = tester.get_rect(only::<TabBar>(tester));
12461                let (tab_one_rect, tab_two_rect) = first_and_last_tab_rects(tester);
12462
12463                // By default tabs should be aligned to the start of the TabBar with
12464                // an horizontal offset of 52.0 pixels.
12465                let tab_one_left = padding.left + TAB_START_OFFSET;
12466                assert_f32_eq(tab_one_rect.left, tab_one_left);
12467                let tab_two_right = TAB_START_OFFSET
12468                    + padding.horizontal()
12469                    + tab_one_rect.width()
12470                    + padding.left
12471                    + tab_two_rect.width();
12472                assert_f32_eq(tab_two_rect.right, tab_two_right);
12473
12474                // Test TabAlignment.start when isScrollable is true.
12475                let frame =
12476                    alignment_frame(tester, true, Some(TabAlignment::Start), TextDirection::Ltr);
12477                tester.pump_widget(frame);
12478                tester.pump_and_settle();
12479
12480                let (tab_one_rect, tab_two_rect) = first_and_last_tab_rects(tester);
12481
12482                // Tabs should be aligned to the start of the TabBar.
12483                let tab_one_left = padding.left;
12484                assert_f32_eq(tab_one_rect.left, tab_one_left);
12485                let tab_two_right = padding.horizontal()
12486                    + tab_one_rect.width()
12487                    + padding.left
12488                    + tab_two_rect.width();
12489                assert_f32_eq(tab_two_rect.right, tab_two_right);
12490
12491                // Test TabAlignment.center when isScrollable is true.
12492                let frame =
12493                    alignment_frame(tester, true, Some(TabAlignment::Center), TextDirection::Ltr);
12494                tester.pump_widget(frame);
12495                tester.pump_and_settle();
12496
12497                let (tab_one_rect, tab_two_rect) = first_and_last_tab_rects(tester);
12498
12499                // Tabs should be centered in the TabBar.
12500                let tab_one_left = (tab_bar.width() / 2.0) - tab_one_rect.width() - padding.right;
12501                assert_f32_eq(tab_one_rect.left, tab_one_left);
12502                let tab_two_right = (tab_bar.width() / 2.0) + tab_two_rect.width() + padding.left;
12503                assert_f32_eq(tab_two_rect.right, tab_two_right);
12504
12505                // Test TabAlignment.startOffset when isScrollable is true.
12506                let frame = alignment_frame(
12507                    tester,
12508                    true,
12509                    Some(TabAlignment::StartOffset),
12510                    TextDirection::Ltr,
12511                );
12512                tester.pump_widget(frame);
12513                tester.pump_and_settle();
12514
12515                let (tab_one_rect, tab_two_rect) = first_and_last_tab_rects(tester);
12516
12517                // Tabs should be aligned to the start of the TabBar with an
12518                // horizontal offset of 52.0 pixels.
12519                let tab_one_left = padding.left + TAB_START_OFFSET;
12520                assert_f32_eq(tab_one_rect.left, tab_one_left);
12521                let tab_two_right = TAB_START_OFFSET
12522                    + padding.horizontal()
12523                    + tab_one_rect.width()
12524                    + padding.left
12525                    + tab_two_rect.width();
12526                assert_f32_eq(tab_two_rect.right, tab_two_right);
12527            });
12528        }
12529
12530        // 'Material3 - TabAlignment.start & TabAlignment.startOffset respects TextDirection.rtl'.
12531        #[test]
12532        fn material3_start_alignments_start_from_the_right_in_rtl() {
12533            test_widgets(|tester| {
12534                const TAB_START_OFFSET: f64 = 52.0;
12535                let padding = K_TAB_LABEL_PADDING;
12536
12537                // Test TabAlignment.startOffset (default) when isScrollable is true.
12538                let frame = alignment_frame(tester, true, None, TextDirection::Rtl);
12539                tester.pump_widget(frame);
12540
12541                let tab_bar = tester.get_rect(only::<TabBar>(tester));
12542                let (tab_one_rect, tab_two_rect) = first_and_last_tab_rects(tester);
12543
12544                // Tabs should be aligned to the start of the TabBar with an
12545                // horizontal offset of 52.0 pixels.
12546                let tab_one_right = tab_bar.width() - padding.right - TAB_START_OFFSET;
12547                assert_f32_eq(tab_one_rect.right, tab_one_right);
12548                let tab_two_left = tab_bar.width()
12549                    - TAB_START_OFFSET
12550                    - padding.horizontal()
12551                    - tab_one_rect.width()
12552                    - padding.right
12553                    - tab_two_rect.width();
12554                assert_f32_eq(tab_two_rect.left, tab_two_left);
12555
12556                // Test TabAlignment.start when isScrollable is true.
12557                let frame =
12558                    alignment_frame(tester, true, Some(TabAlignment::Start), TextDirection::Rtl);
12559                tester.pump_widget(frame);
12560                tester.pump_and_settle();
12561
12562                let (tab_one_rect, tab_two_rect) = first_and_last_tab_rects(tester);
12563
12564                // Tabs should be aligned to the start of the TabBar.
12565                let tab_one_right = tab_bar.width() - padding.right;
12566                assert_f32_eq(tab_one_rect.right, tab_one_right);
12567                let tab_two_left = tab_bar.width()
12568                    - padding.horizontal()
12569                    - tab_one_rect.width()
12570                    - padding.left
12571                    - tab_two_rect.width();
12572                assert_f32_eq(tab_two_rect.left, tab_two_left);
12573
12574                // Test TabAlignment.startOffset when isScrollable is true.
12575                let frame = alignment_frame(
12576                    tester,
12577                    true,
12578                    Some(TabAlignment::StartOffset),
12579                    TextDirection::Rtl,
12580                );
12581                tester.pump_widget(frame);
12582                tester.pump_and_settle();
12583
12584                let (tab_one_rect, tab_two_rect) = first_and_last_tab_rects(tester);
12585
12586                // Tabs should be aligned to the start of the TabBar with an
12587                // horizontal offset of 52.0 pixels.
12588                let tab_one_right = tab_bar.width() - padding.right - TAB_START_OFFSET;
12589                assert_f32_eq(tab_one_rect.right, tab_one_right);
12590                let tab_two_left = tab_bar.width()
12591                    - TAB_START_OFFSET
12592                    - padding.horizontal()
12593                    - tab_one_rect.width()
12594                    - padding.right
12595                    - tab_two_rect.width();
12596                assert_f32_eq(tab_two_rect.left, tab_two_left);
12597            });
12598        }
12599
12600        // 'Material3 - TabBar inherits the dividerColor of TabBarTheme'.
12601        #[test]
12602        fn material3_the_indicator_painter_takes_the_theme_divider_color() {
12603            test_widgets(|tester| {
12604                let divider_color = Colors::YELLOW.primary();
12605                let theme = theme(
12606                    tester,
12607                    None,
12608                    Some(TabBarThemeData::new().divider_color(divider_color)),
12609                );
12610                let controller = create_tab_controller(tester, 3);
12611                tester.pump_widget(material_app(
12612                    theme,
12613                    scaffold_with_tab_bar(
12614                        AppBar::new(),
12615                        TabBar::new(
12616                            ["Tab 1", "Tab 2", "Tab 3"]
12617                                .map(|text| Tab::new().text(text).into_widget()),
12618                        )
12619                        .controller(controller),
12620                        None,
12621                    ),
12622                ));
12623
12624                // Test painter's divider color.
12625                let paint = *find::by_type::<CustomPaint>()
12626                    .evaluate(tester)
12627                    .last()
12628                    .expect("a CustomPaint");
12629                let painter_divider_color = tester.widget(paint, |paint: &CustomPaint| {
12630                    paint
12631                        .painter
12632                        .as_ref()
12633                        .and_then(|painter| painter.as_any().downcast_ref::<IndicatorPainter>())
12634                        .expect("the last CustomPaint is the indicator's")
12635                        .divider_color
12636                });
12637                assert_eq!(painter_divider_color, Some(divider_color));
12638            });
12639        }
12640
12641        // This is a regression test for https://github.com/flutter/flutter/pull/125974#discussion_r1239089151.
12642        // 'Divider can be constrained'.
12643        #[test]
12644        fn the_divider_of_a_constrained_scrollable_tab_bar_is_as_wide_as_the_tab_bar() {
12645            test_widgets(|tester| {
12646                let divider_color = Colors::YELLOW.primary();
12647                let theme = theme(
12648                    tester,
12649                    None,
12650                    Some(TabBarThemeData::new().divider_color(divider_color)),
12651                );
12652                tester.pump_widget(material_app(
12653                    theme,
12654                    Scaffold::new()
12655                        .body(DefaultTabController::new(
12656                            2,
12657                            Center::new().child(
12658                                waft_widgets::ConstrainedBox::new(
12659                                    BoxConstraints::new().max_width(360.0),
12660                                )
12661                                .child(
12662                                    waft_widgets::ColoredBox::new(Colors::GREY.shade200()).child(
12663                                        TabBar::secondary([
12664                                            Tab::new().text("Test 1").into_widget(),
12665                                            Tab::new().text("Test 2").into_widget(),
12666                                        ])
12667                                        .tab_alignment(TabAlignment::Start)
12668                                        .is_scrollable(true),
12669                                    ),
12670                                ),
12671                            ),
12672                        ))
12673                        .into_widget(),
12674                ));
12675
12676                // Test tab bar width.
12677                assert_eq!(tester.get_size(only::<TabBar>(tester)).width(), 360.0);
12678                // Test divider width.
12679                let divider = find::by_type::<CustomPaint>().evaluate(tester)[1];
12680                assert_eq!(tester.get_size(divider).width(), 360.0);
12681            });
12682        }
12683
12684        // 'TabBar labels use colors from labelStyle & unselectedLabelStyle'.
12685        #[test]
12686        fn labels_take_their_colors_from_the_label_styles() {
12687            test_widgets(|tester| {
12688                const TAB1: &str = "Tab 1";
12689                const TAB2: &str = "Tab 2";
12690                let label_style = TextStyle::new()
12691                    .color(Color::new(0xff0000ff))
12692                    .font_style(waft_embedder::FontStyle::Italic);
12693                let unselected_label_style = TextStyle::new()
12694                    .color(Color::new(0x950000ff))
12695                    .font_style(waft_embedder::FontStyle::Italic);
12696
12697                // Test tab bar with labelStyle & unselectedLabelStyle.
12698                let theme = theme(tester, None, None);
12699                tester.pump_widget(boilerplate(
12700                    theme,
12701                    TextDirection::Ltr,
12702                    DefaultTabController::new(
12703                        2,
12704                        TabBar::new([
12705                            Tab::new().text(TAB1).into_widget(),
12706                            Tab::new().text(TAB2).into_widget(),
12707                        ])
12708                        .label_style(label_style.clone())
12709                        .unselected_label_style(unselected_label_style.clone()),
12710                    ),
12711                ));
12712
12713                let selected_text_style = paragraph_style(tester, TAB1);
12714                let unselected_text_style = paragraph_style(tester, TAB2);
12715
12716                // Selected tab should use the labelStyle color.
12717                assert_eq!(icon_color(tester, TAB1), style_color(&label_style));
12718                assert_eq!(style_color(&selected_text_style), style_color(&label_style));
12719                assert_eq!(selected_text_style.font_style, label_style.font_style);
12720                // Unselected tab should use the unselectedLabelStyle color.
12721                assert_eq!(
12722                    icon_color(tester, TAB2),
12723                    style_color(&unselected_label_style)
12724                );
12725                assert_eq!(
12726                    style_color(&unselected_text_style),
12727                    style_color(&unselected_label_style)
12728                );
12729                assert_eq!(
12730                    unselected_text_style.font_style,
12731                    unselected_label_style.font_style
12732                );
12733            });
12734        }
12735
12736        // 'labelColor & unselectedLabelColor override labelStyle & unselectedLabelStyle colors'.
12737        #[test]
12738        fn label_colors_override_the_label_style_colors() {
12739            test_widgets(|tester| {
12740                const TAB1: &str = "Tab 1";
12741                const TAB2: &str = "Tab 2";
12742                const LABEL_COLOR: Color = Color::new(0xfff00000);
12743                const UNSELECTED_LABEL_COLOR: Color = Color::new(0x95ff0000);
12744                let label_style = TextStyle::new()
12745                    .color(Color::new(0xff0000ff))
12746                    .font_style(waft_embedder::FontStyle::Italic);
12747                let unselected_label_style = TextStyle::new()
12748                    .color(Color::new(0x950000ff))
12749                    .font_style(waft_embedder::FontStyle::Italic);
12750
12751                let build_tab_bar = |tester: &WidgetTester, colors: Option<(Color, Color)>| {
12752                    let mut tab_bar = TabBar::new([
12753                        Tab::new().text(TAB1).into_widget(),
12754                        Tab::new().text(TAB2).into_widget(),
12755                    ])
12756                    .label_style(label_style.clone())
12757                    .unselected_label_style(unselected_label_style.clone());
12758                    if let Some((label_color, unselected_label_color)) = colors {
12759                        tab_bar = tab_bar
12760                            .label_color(label_color)
12761                            .unselected_label_color(unselected_label_color);
12762                    }
12763                    boilerplate(
12764                        theme(tester, None, None),
12765                        TextDirection::Ltr,
12766                        DefaultTabController::new(2, tab_bar),
12767                    )
12768                };
12769
12770                // Test tab bar with labelStyle & unselectedLabelStyle.
12771                let frame = build_tab_bar(tester, None);
12772                tester.pump_widget(frame);
12773
12774                let selected_text_style = paragraph_style(tester, TAB1);
12775                let unselected_text_style = paragraph_style(tester, TAB2);
12776
12777                // Selected tab should use labelStyle color.
12778                assert_eq!(icon_color(tester, TAB1), style_color(&label_style));
12779                assert_eq!(style_color(&selected_text_style), style_color(&label_style));
12780                assert_eq!(selected_text_style.font_style, label_style.font_style);
12781                // Unselected tab should use unselectedLabelStyle color.
12782                assert_eq!(
12783                    icon_color(tester, TAB2),
12784                    style_color(&unselected_label_style)
12785                );
12786                assert_eq!(
12787                    style_color(&unselected_text_style),
12788                    style_color(&unselected_label_style)
12789                );
12790                assert_eq!(
12791                    unselected_text_style.font_style,
12792                    unselected_label_style.font_style
12793                );
12794
12795                // Update tab bar with labelColor & unselectedLabelColor.
12796                let frame = build_tab_bar(tester, Some((LABEL_COLOR, UNSELECTED_LABEL_COLOR)));
12797                tester.pump_widget(frame);
12798                tester.pump_and_settle();
12799
12800                let selected_text_style = paragraph_style(tester, TAB1);
12801                let unselected_text_style = paragraph_style(tester, TAB2);
12802
12803                // Selected tab should use the labelColor.
12804                assert_eq!(icon_color(tester, TAB1), Some(LABEL_COLOR));
12805                assert_eq!(style_color(&selected_text_style), Some(LABEL_COLOR));
12806                assert_eq!(selected_text_style.font_style, label_style.font_style);
12807                // Unselected tab should use the unselectedLabelColor.
12808                assert_eq!(icon_color(tester, TAB2), Some(UNSELECTED_LABEL_COLOR));
12809                assert_eq!(
12810                    style_color(&unselected_text_style),
12811                    Some(UNSELECTED_LABEL_COLOR)
12812                );
12813                assert_eq!(
12814                    unselected_text_style.font_style,
12815                    unselected_label_style.font_style
12816                );
12817            });
12818        }
12819
12820        // This is a regression test for https://github.com/flutter/flutter/issues/140338.
12821        // 'Material3 - Scrollable TabBar without a divider does not expand to full width'.
12822        #[test]
12823        fn material3_a_scrollable_tab_bar_without_a_divider_shrinks_to_its_tabs() {
12824            test_widgets(|tester| {
12825                let build_tab_bar =
12826                    |tester: &WidgetTester,
12827                     divider_height: Option<f64>,
12828                     tab_alignment: TabAlignment| {
12829                        let mut tab_bar = TabBar::new(
12830                            ["Tab 1", "Tab 2", "Tab 3"]
12831                                .map(|text| Tab::new().text(text).into_widget()),
12832                        )
12833                        .tab_alignment(tab_alignment)
12834                        .is_scrollable(true);
12835                        if let Some(divider_height) = divider_height {
12836                            tab_bar = tab_bar.divider_height(divider_height);
12837                        }
12838                        boilerplate(
12839                            theme(tester, None, None),
12840                            TextDirection::Ltr,
12841                            Center::new().child(DefaultTabController::new(3, tab_bar)),
12842                        )
12843                    };
12844                let mut width_with = |divider_height: Option<f64>, tab_alignment: TabAlignment| {
12845                    let frame = build_tab_bar(tester, divider_height, tab_alignment);
12846                    tester.pump_widget(frame);
12847                    tester.get_size(only::<TabBar>(tester)).width()
12848                };
12849
12850                // Test default tab bar width when there is a divider and tabAlignment
12851                // is set to startOffset.
12852                assert_eq!(width_with(None, TabAlignment::Start), 800.0);
12853
12854                // Test default tab bar width when there is a divider and tabAlignment
12855                // is set to start.
12856                assert_eq!(width_with(None, TabAlignment::StartOffset), 800.0);
12857
12858                // Test default tab bar width when there is a divider and tabAlignment
12859                // tabAlignment is set to center.
12860                assert_eq!(width_with(None, TabAlignment::Center), 800.0);
12861
12862                // Test default tab bar width when the divider height is set to 0.0
12863                // and tabAlignment is set to startOffset.
12864                assert_eq!(width_with(Some(0.0), TabAlignment::StartOffset), 359.5);
12865
12866                // Test default tab bar width when the divider height is set to 0.0
12867                // and tabAlignment is set to start.
12868                assert_eq!(width_with(Some(0.0), TabAlignment::Start), 307.5);
12869
12870                // Test default tab bar width when the divider height is set to 0.0
12871                // and tabAlignment is set to center.
12872                assert_eq!(width_with(Some(0.0), TabAlignment::Center), 307.5);
12873            });
12874        }
12875    }
12876
12877    mod material2_and_indicator_animations {
12878        //! tabs_test.dart cases, part e: the 'Material 2' group to the end of the file.
12879
12880        use std::cell::{Cell, RefCell};
12881        use waft_painting::Decoration;
12882
12883        use waft_embedder::{RRect, Radius};
12884        use waft_painting::EdgeInsets;
12885
12886        use waft_widgets::{
12887            AnyElement, Focus, Icon, MediaQueryData, PreferredSizeWidgetRef, UnfocusDisposition,
12888        };
12889
12890        use super::*;
12891        use crate::app_bar::AppBar;
12892        use crate::icons::Icons;
12893        use crate::scaffold::Scaffold;
12894        use crate::test_support::{PaintInspection, material_app};
12895        use crate::theme_data::ThemeData;
12896        use waft_widgets::testing::TestVSync;
12897
12898        /// Dart's `tester.renderObject<RenderParagraph>(find.text(text)).text.style!`.
12899        fn paragraph_style(tester: &WidgetTester, value: &str) -> TextStyle {
12900            let render = tester.render_box_of(text(tester, value));
12901            let app = tester.cell.borrow();
12902            let paragraph = render
12903                .as_object()
12904                .downcast::<waft_rendering::RenderParagraph>(&app)
12905                .expect("a Text renders a paragraph");
12906            paragraph
12907                .text(&app)
12908                .style()
12909                .cloned()
12910                .expect("the paragraph's text has a style")
12911        }
12912
12913        fn paragraph_color(tester: &WidgetTester, value: &str) -> Option<Color> {
12914            paragraph_style(tester, value)
12915                .color
12916                .as_ref()
12917                .map(AnyColor::color)
12918        }
12919
12920        /// Dart's `createTabController(length:, vsync: const TestVSync())`.
12921        fn controller(tester: &WidgetTester, length: usize) -> Ref<TabController> {
12922            let mut app = tester.cell.borrow_mut();
12923            TabController::new(&mut app, 0, None, length, TestVSync)
12924        }
12925
12926        /// Dart's `ThemeData(useMaterial3: false)`.
12927        fn m2(tester: &WidgetTester) -> ThemeData {
12928            theme(tester, Some(false), None)
12929        }
12930
12931        /// The tabs' elements, in order: Dart's `find.byType(Tab)`.
12932        fn tabs_of(tester: &WidgetTester) -> Vec<AnyElement> {
12933            find::by_type::<Tab>().evaluate(tester)
12934        }
12935
12936        /// Dart's `RRect.fromLTRBAndCorners(left, top, right, bottom, topLeft: 3, topRight: 3)`.
12937        fn indicator_rrect(left: f64, top: f64, right: f64, bottom: f64) -> RRect {
12938            RRect::from_ltrb_and_corners(
12939                left,
12940                top,
12941                right,
12942                bottom,
12943                Radius::circular(3.0),
12944                Radius::circular(3.0),
12945                Radius::ZERO,
12946                Radius::ZERO,
12947            )
12948        }
12949
12950        /// The `CustomPaint` that paints the indicator's render object.
12951        ///
12952        /// Dart's `paints` matcher on the tab bar records through the layers a scrollable tab bar's
12953        /// viewport pushes; `WidgetTester::pictures` reads the tab bar's own pictures only, so the
12954        /// cases ask this `CustomPaint`, in whose coordinates Dart's rrects are.
12955        fn indicator_paint(tester: &WidgetTester) -> AnyRenderObject {
12956            let tab_bar = only::<TabBar>(tester);
12957            let indicator_paint = tester
12958                .descendants_of_type::<CustomPaint>(tab_bar)
12959                .into_iter()
12960                .find(|element| {
12961                    tester.widget(*element, |paint: &CustomPaint| {
12962                        paint
12963                            .painter
12964                            .as_ref()
12965                            .is_some_and(|painter| painter.as_any().is::<IndicatorPainter>())
12966                    })
12967                })
12968                .expect("the indicator's CustomPaint");
12969            tester.render_box_of(indicator_paint).as_object()
12970        }
12971
12972        /// Dart's `expect(find.byType(TabBar), paints..rrect(rrect: rrect))`.
12973        fn paints_rrect(tester: &WidgetTester, rrect: RRect) -> bool {
12974            waft_rendering::testing::paints(
12975                &tester.painted_ops(indicator_paint(tester)),
12976                &[waft_rendering::testing::PaintCall::rrect_at(rrect, None)],
12977            )
12978            .is_ok()
12979        }
12980
12981        /// [`paints_rrect`] with the rrect's edges within `epsilon` of what is painted.
12982        fn paints_rrect_within(tester: &WidgetTester, rrect: RRect, epsilon: f64) -> bool {
12983            use waft_embedder::valo::Op;
12984            tester
12985                .painted_ops(indicator_paint(tester))
12986                .into_iter()
12987                .any(|op| match op {
12988                    Op::DrawPath { path, .. } => {
12989                        path.as_round_rect().is_some_and(|(rect, radii)| {
12990                            close(f64::from(rect.x), rrect.left, epsilon)
12991                                && close(f64::from(rect.y), rrect.top, epsilon)
12992                                && close(f64::from(rect.x + rect.width), rrect.right, epsilon)
12993                                && close(f64::from(rect.y + rect.height), rrect.bottom, epsilon)
12994                                && radii == [[3.0, 3.0], [3.0, 3.0], [0.0, 0.0], [0.0, 0.0]]
12995                        })
12996                    }
12997                    _ => false,
12998                })
12999        }
13000
13001        /// Dart's `_accelerateInterpolation`.
13002        fn accelerate_interpolation(fraction: f64) -> f64 {
13003            1.0 - ((fraction * PI) / 2.0).cos()
13004        }
13005
13006        /// Dart's `_decelerateInterpolation`.
13007        fn decelerate_interpolation(fraction: f64) -> f64 {
13008            ((fraction * PI) / 2.0).sin()
13009        }
13010
13011        /// tabs_utils.dart's `tabIndicatorRRectElasticAnimation`.
13012        fn tab_indicator_rrect_elastic_animation(
13013            tab_bar_height: f64,
13014            _current_rect: Rect,
13015            from_rect: Rect,
13016            to_rect: Rect,
13017            progress: f64,
13018        ) -> RRect {
13019            const INDICATOR_WEIGHT: f64 = 3.0;
13020            let left_fraction = accelerate_interpolation(progress);
13021            let right_fraction = decelerate_interpolation(progress);
13022            let lerp = |a: f64, b: f64, t: f64| lerp_double(Some(a), Some(b), t).expect("lerps");
13023
13024            RRect::from_ltrb_and_corners(
13025                lerp(from_rect.left, to_rect.left, left_fraction),
13026                tab_bar_height - INDICATOR_WEIGHT,
13027                lerp(from_rect.right, to_rect.right, right_fraction),
13028                tab_bar_height,
13029                Radius::circular(INDICATOR_WEIGHT),
13030                Radius::circular(INDICATOR_WEIGHT),
13031                Radius::ZERO,
13032                Radius::ZERO,
13033            )
13034        }
13035
13036        /// Dart's `Container(alignment: Alignment.topLeft, child: child)`.
13037        fn top_left<K>(child: impl IntoWidget<K>) -> WidgetRef {
13038            waft_widgets::Container::new()
13039                .alignment(AlignmentGeometry::TOP_LEFT)
13040                .child(child)
13041                .into_widget()
13042        }
13043
13044        /// Dart's `Scaffold(appBar: AppBar(title:, bottom: tab_bar), body:)`.
13045        fn scaffold_with_tab_bar(
13046            title: Option<&str>,
13047            tab_bar: TabBar,
13048            body: Option<WidgetRef>,
13049        ) -> Scaffold {
13050            let mut app_bar = AppBar::new().bottom(PreferredSizeWidgetRef::new(tab_bar));
13051            if let Some(title) = title {
13052                app_bar = app_bar.title(Text::new(title));
13053            }
13054            let mut scaffold = Scaffold::new().app_bar(PreferredSizeWidgetRef::new(app_bar));
13055            if let Some(body) = body {
13056                scaffold = scaffold.body(body);
13057            }
13058            scaffold
13059        }
13060
13061        fn text_tabs(texts: &[&str]) -> Vec<WidgetRef> {
13062            texts
13063                .iter()
13064                .map(|text| Tab::new().text(*text).into_widget())
13065                .collect()
13066        }
13067
13068        // ---- Material 2 ----
13069
13070        // 'TabBar default selected/unselected text style'.
13071        #[test]
13072        fn material2_labels_take_the_primary_text_themes_body_large_and_70_percent_unselected() {
13073            test_widgets(|tester| {
13074                let theme = m2(tester);
13075                let mut frame = Frame::new(vec!["A", "B", "C"], "A");
13076                frame.use_material3 = Some(false);
13077                let frame = frame.build(tester);
13078                tester.pump_widget(frame);
13079                expect(tester, &find::text("A"), finds_one_widget());
13080                expect(tester, &find::text("B"), finds_one_widget());
13081                expect(tester, &find::text("C"), finds_one_widget());
13082
13083                let body_large_color = theme
13084                    .primary_text_theme
13085                    .body_large
13086                    .as_ref()
13087                    .and_then(|style| style.color.as_ref().map(AnyColor::color))
13088                    .expect("a color");
13089
13090                // Test selected label text style.
13091                let selected = paragraph_style(tester, "A");
13092                assert_eq!(selected.font_family.as_deref(), Some("Roboto"));
13093                assert_eq!(selected.font_size, Some(14.0));
13094                assert_eq!(paragraph_color(tester, "A"), Some(body_large_color));
13095
13096                // Test unselected label text style.
13097                let unselected = paragraph_style(tester, "C");
13098                assert_eq!(unselected.font_family.as_deref(), Some("Roboto"));
13099                assert_eq!(unselected.font_size, Some(14.0));
13100                assert_eq!(
13101                    paragraph_color(tester, "C"),
13102                    Some(body_large_color.with_alpha(0xB2)) // 70% alpha,
13103                );
13104            });
13105        }
13106
13107        // 'TabBar default unselectedLabelColor inherits labelColor with 70% opacity'.
13108        #[test]
13109        fn material2_the_unselected_label_color_is_the_label_color_at_70_percent() {
13110            test_widgets(|tester| {
13111                const LABEL_COLOR: Color = Color::new(0xff0000ff);
13112                let mut frame = Frame::new(vec!["A", "B", "C"], "A");
13113                frame.use_material3 = Some(false);
13114                frame.tab_bar_theme = Some(TabBarThemeData::new().label_color(LABEL_COLOR));
13115                let frame = frame.build(tester);
13116                tester.pump_widget(frame);
13117                expect(tester, &find::text("A"), finds_one_widget());
13118                expect(tester, &find::text("B"), finds_one_widget());
13119                expect(tester, &find::text("C"), finds_one_widget());
13120
13121                // Test selected label color.
13122                assert_eq!(paragraph_color(tester, "A"), Some(LABEL_COLOR));
13123
13124                // Test unselected label color.
13125                assert_eq!(
13126                    paragraph_color(tester, "C"),
13127                    Some(LABEL_COLOR.with_alpha(0xB2)) // 70% alpha,
13128                );
13129            });
13130        }
13131
13132        // 'Material2 - Default TabAlignment'.
13133        #[test]
13134        fn material2_tabs_fill_a_fixed_tab_bar_and_start_a_scrollable_one() {
13135            test_widgets(|tester| {
13136                let mut frame = Frame::new(vec!["A", "B"], "B");
13137                frame.use_material3 = Some(false);
13138                let frame = frame.build(tester);
13139                tester.pump_widget(frame);
13140
13141                let tab_bar = tester.get_rect(only::<TabBar>(tester));
13142                let tabs = tabs_of(tester);
13143                let tab_one_rect = tester.get_rect(tabs[0]);
13144                let tab_two_rect = tester.get_rect(tabs[1]);
13145
13146                // Tabs should fill the width of the TabBar.
13147                let tab_one_left = ((tab_bar.width() / 2.0) - tab_one_rect.width()) / 2.0;
13148                assert_eq!(tab_one_rect.left, tab_one_left);
13149                let tab_two_right =
13150                    tab_bar.width() - ((tab_bar.width() / 2.0) - tab_two_rect.width()) / 2.0;
13151                assert_eq!(tab_two_rect.right, tab_two_right);
13152
13153                // Test default TabAlignment when isScrollable is true.
13154                let mut frame = Frame::new(vec!["A", "B"], "B");
13155                frame.use_material3 = Some(false);
13156                frame.is_scrollable = true;
13157                let frame = frame.build(tester);
13158                tester.pump_widget(frame);
13159
13160                let tabs = tabs_of(tester);
13161                let tab_one_rect = tester.get_rect(tabs[0]);
13162                let tab_two_rect = tester.get_rect(tabs[1]);
13163
13164                // Tabs should be aligned to the start of the TabBar.
13165                let padding =
13166                    EdgeInsetsGeometry::from(K_TAB_LABEL_PADDING).resolve(Some(TextDirection::Ltr));
13167                assert_eq!(tab_one_rect.left, padding.left);
13168                let tab_two_right = padding.horizontal()
13169                    + tab_one_rect.width()
13170                    + padding.left
13171                    + tab_two_rect.width();
13172                assert_eq!(tab_two_rect.right, tab_two_right);
13173            });
13174        }
13175
13176        fn material2_default_indicator(secondary: bool) {
13177            test_widgets(|tester| {
13178                let theme = m2(tester);
13179                let controller = controller(tester, 4);
13180                let tabs =
13181                    (0..4).map(|index| Tab::new().text(format!("Tab {index}")).into_widget());
13182                let tab_bar = if secondary {
13183                    TabBar::secondary(tabs)
13184                } else {
13185                    TabBar::new(tabs)
13186                }
13187                .controller(controller);
13188                tester.pump_widget(material_app(
13189                    theme.clone(),
13190                    boilerplate(theme.clone(), TextDirection::Ltr, top_left(tab_bar)),
13191                ));
13192
13193                let tab_bar_box = first_render_box::<TabBar>(tester);
13194                assert_eq!(tab_bar_box.size(&tester.cell.borrow()).height(), 48.0);
13195
13196                const INDICATOR_WEIGHT: f64 = 2.0;
13197                const INDICATOR_Y: f64 = 48.0 - (INDICATOR_WEIGHT / 2.0);
13198                const INDICATOR_LEFT: f64 = INDICATOR_WEIGHT / 2.0;
13199                const INDICATOR_RIGHT: f64 = 200.0 - (INDICATOR_WEIGHT / 2.0);
13200
13201                #[allow(deprecated)]
13202                let indicator_color = theme.indicator_color;
13203                let lines = painted_lines(tester, tab_bar_box.as_object());
13204                assert!(
13205                    lines.iter().any(|line| is_line(
13206                        line,
13207                        indicator_color,
13208                        Some(INDICATOR_WEIGHT),
13209                        Offset::new(INDICATOR_LEFT, INDICATOR_Y),
13210                        Offset::new(INDICATOR_RIGHT, INDICATOR_Y),
13211                    )),
13212                    "{lines:?}"
13213                );
13214            });
13215        }
13216
13217        // 'TabBar default tab indicator (primary)', Material 2.
13218        #[test]
13219        fn material2_the_default_primary_indicator_is_a_tab_wide_line_in_the_indicator_color() {
13220            material2_default_indicator(false);
13221        }
13222
13223        // 'TabBar default tab indicator (secondary)', Material 2.
13224        #[test]
13225        fn material2_the_default_secondary_indicator_is_a_tab_wide_line_in_the_indicator_color() {
13226            material2_default_indicator(true);
13227        }
13228
13229        // 'Material2 - TabBar with padding isScrollable: true'.
13230        #[test]
13231        fn material2_a_scrollable_tab_bar_insets_its_tabs_by_its_padding() {
13232            test_widgets(|tester| {
13233                const INDICATOR_WEIGHT: f64 = 2.0; // default indicator weight
13234                let padding = EdgeInsets::only(3.0, 7.0, 5.0, 3.0);
13235                let keys = [GlobalKey::new(), GlobalKey::new(), GlobalKey::new()];
13236                let tabs = vec![
13237                    SizedBox::new()
13238                        .key(keys[0].clone().into())
13239                        .width(130.0)
13240                        .height(30.0)
13241                        .into_widget(),
13242                    SizedBox::new()
13243                        .key(keys[1].clone().into())
13244                        .width(140.0)
13245                        .height(40.0)
13246                        .into_widget(),
13247                    SizedBox::new()
13248                        .key(keys[2].clone().into())
13249                        .width(150.0)
13250                        .height(50.0)
13251                        .into_widget(),
13252                ];
13253                let controller = controller(tester, tabs.len());
13254                let theme = m2(tester);
13255                tester.pump_widget(boilerplate(
13256                    theme,
13257                    TextDirection::Ltr,
13258                    top_left(
13259                        TabBar::new(tabs)
13260                            .padding(padding)
13261                            .label_padding(EdgeInsetsGeometry::ZERO)
13262                            .is_scrollable(true)
13263                            .controller(controller),
13264                    ),
13265                ));
13266
13267                let tab_bar_box = first_render_box::<TabBar>(tester);
13268                let tab_bar_height = 50.0 + INDICATOR_WEIGHT + padding.top + padding.bottom; // 50 = max tab height
13269                assert_eq!(
13270                    tab_bar_box.size(&tester.cell.borrow()).height(),
13271                    tab_bar_height
13272                );
13273
13274                let key_rect = |tester: &WidgetTester, key: &GlobalKey| {
13275                    tester.get_rect(tester.render_object(key).as_box().expect("a box"))
13276                };
13277
13278                // Tab0 width = 130, height = 30
13279                let mut tab_left = padding.left;
13280                let mut tab_right = tab_left + 130.0;
13281                let mut tab_top =
13282                    (tab_bar_height - INDICATOR_WEIGHT + (padding.top - padding.bottom) - 30.0)
13283                        / 2.0;
13284                let mut tab_bottom = tab_top + 30.0;
13285                assert_eq!(
13286                    key_rect(tester, &keys[0]),
13287                    Rect::from_ltrb(tab_left, tab_top, tab_right, tab_bottom)
13288                );
13289
13290                // Tab1 width = 140, height = 40
13291                tab_left = tab_right;
13292                tab_right = tab_left + 140.0;
13293                tab_top = (tab_bar_height - INDICATOR_WEIGHT + (padding.top - padding.bottom)
13294                    - 40.0)
13295                    / 2.0;
13296                tab_bottom = tab_top + 40.0;
13297                assert_eq!(
13298                    key_rect(tester, &keys[1]),
13299                    Rect::from_ltrb(tab_left, tab_top, tab_right, tab_bottom)
13300                );
13301
13302                // Tab2 width = 150, height = 50
13303                tab_left = tab_right;
13304                tab_right = tab_left + 150.0;
13305                tab_top = (tab_bar_height - INDICATOR_WEIGHT + (padding.top - padding.bottom)
13306                    - 50.0)
13307                    / 2.0;
13308                tab_bottom = tab_top + 50.0;
13309                assert_eq!(
13310                    key_rect(tester, &keys[2]),
13311                    Rect::from_ltrb(tab_left, tab_top, tab_right, tab_bottom)
13312                );
13313
13314                tab_right += padding.right;
13315                assert_eq!(tab_bar_box.size(&tester.cell.borrow()).width(), tab_right);
13316            });
13317        }
13318
13319        // 'Material2 - TabAlignment updates tabs alignment (non-scrollable TabBar)'.
13320        #[test]
13321        fn material2_tab_alignment_center_stops_fixed_tabs_filling_the_tab_bar() {
13322            test_widgets(|tester| {
13323                let theme = m2(tester);
13324
13325                // Test TabAlignment.fill (default) when isScrollable is false.
13326                let frame = Frame::new(vec!["A", "B"], "B").build(tester);
13327                tester.pump_widget(material_app(theme.clone(), frame));
13328
13329                let tab_bar = tester.get_rect(only::<TabBar>(tester));
13330                let tabs = tabs_of(tester);
13331                let tab_one_rect = tester.get_rect(tabs[0]);
13332                let tab_two_rect = tester.get_rect(tabs[1]);
13333
13334                // Within f32: global positions go through valo's f32 matrices (waft-gestures'
13335                // `Matrix4` entry), where Dart's are f64 and compare within 1e-10.
13336                const EPSILON: f64 = 1e-4;
13337
13338                // By default tabs should fill the width of the TabBar.
13339                let tab_one_left = ((tab_bar.width() / 2.0) - tab_one_rect.width()) / 2.0;
13340                assert!(close(tab_one_rect.left, tab_one_left, EPSILON));
13341                let tab_two_right =
13342                    tab_bar.width() - ((tab_bar.width() / 2.0) - tab_two_rect.width()) / 2.0;
13343                assert!(close(tab_two_rect.right, tab_two_right, EPSILON));
13344
13345                // Test TabAlignment.center when isScrollable is false.
13346                let mut frame = Frame::new(vec!["A", "B"], "B");
13347                frame.tab_alignment = Some(TabAlignment::Center);
13348                let frame = frame.build(tester);
13349                tester.pump_widget(material_app(theme, frame));
13350                tester.pump_and_settle();
13351
13352                let tabs = tabs_of(tester);
13353                let tab_one_rect = tester.get_rect(tabs[0]);
13354                let tab_two_rect = tester.get_rect(tabs[1]);
13355
13356                // Tabs should not fill the width of the TabBar.
13357                let padding =
13358                    EdgeInsetsGeometry::from(K_TAB_LABEL_PADDING).resolve(Some(TextDirection::Ltr));
13359                assert!(close(tab_one_rect.left, padding.left, EPSILON));
13360                let tab_two_right = padding.horizontal()
13361                    + tab_one_rect.width()
13362                    + padding.left
13363                    + tab_two_rect.width();
13364                assert!(close(tab_two_rect.right, tab_two_right, EPSILON));
13365            });
13366        }
13367
13368        // ---- after the Material 2 group ----
13369
13370        // 'does not crash if switching to a newly added tab'.
13371        #[test]
13372        fn switching_to_a_newly_added_tab_shows_its_view() {
13373            test_widgets(|tester| {
13374                let build_tabs = |tester: &WidgetTester, tab_count: usize| {
13375                    let theme = theme(tester, None, None);
13376                    boilerplate(
13377                        theme,
13378                        TextDirection::Ltr,
13379                        DefaultTabController::new(
13380                            tab_count,
13381                            scaffold_with_tab_bar(
13382                                Some("Flutter Demo Click Counter"),
13383                                TabBar::new(
13384                                    (0..tab_count)
13385                                        .map(|i| Tab::new().text(format!("Tab {i}")).into_widget()),
13386                                )
13387                                .tab_alignment(TabAlignment::Start)
13388                                .is_scrollable(true),
13389                                Some(
13390                                    TabBarView::new(
13391                                        (0..tab_count)
13392                                            .map(|i| Text::new(format!("View {i}")).into_widget()),
13393                                    )
13394                                    .into_widget(),
13395                                ),
13396                            ),
13397                        ),
13398                    )
13399                };
13400
13401                let widget = build_tabs(tester, 1);
13402                tester.pump_widget(widget);
13403                assert_eq!(tabs_of(tester).len(), 1);
13404
13405                let widget = build_tabs(tester, 2);
13406                tester.pump_widget(widget);
13407                assert_eq!(tabs_of(tester).len(), 2);
13408
13409                let widget = build_tabs(tester, 3);
13410                tester.pump_widget(widget);
13411                assert_eq!(tabs_of(tester).len(), 3);
13412
13413                expect(tester, &find::text("View 0"), finds_one_widget());
13414                expect(tester, &find::text("View 2"), finds_nothing());
13415                let tab_2 = text(tester, "Tab 2");
13416                tap(tester, tab_2);
13417                tester.pump_and_settle();
13418                expect(tester, &find::text("View 0"), finds_nothing());
13419                expect(tester, &find::text("View 2"), finds_one_widget());
13420            });
13421        }
13422
13423        /// tabs_utils.dart's `TestIndicatorDecoration`: each painter it creates records the last
13424        /// configuration it painted with.
13425        #[derive(Clone, Default)]
13426        struct TestIndicatorDecoration {
13427            painters: Rc<RefCell<Vec<LastConfiguration>>>,
13428        }
13429
13430        /// What a `TestIndicatorBoxPainter` last painted with.
13431        type LastConfiguration = Rc<RefCell<Option<ImageConfiguration>>>;
13432
13433        impl fmt::Debug for TestIndicatorDecoration {
13434            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
13435                f.write_str("TestIndicatorDecoration")
13436            }
13437        }
13438
13439        impl Decoration for TestIndicatorDecoration {
13440            fn create_box_painter(
13441                &self,
13442                _on_changed: Option<waft_foundation::VoidCallback>,
13443            ) -> Box<dyn BoxPainter> {
13444                let last_configuration = Rc::new(RefCell::new(None));
13445                self.painters
13446                    .borrow_mut()
13447                    .push(Rc::clone(&last_configuration));
13448                Box::new(TestIndicatorBoxPainter { last_configuration })
13449            }
13450
13451            fn as_any(&self) -> &dyn Any {
13452                self
13453            }
13454        }
13455
13456        /// tabs_utils.dart's `TestIndicatorBoxPainter`.
13457        struct TestIndicatorBoxPainter {
13458            last_configuration: LastConfiguration,
13459        }
13460
13461        impl BoxPainter for TestIndicatorBoxPainter {
13462            fn paint(
13463                &mut self,
13464                _canvas: &mut Canvas,
13465                _offset: Offset,
13466                configuration: &ImageConfiguration,
13467            ) {
13468                *self.last_configuration.borrow_mut() = Some(configuration.clone());
13469            }
13470
13471            fn on_changed(&self) -> Option<&dyn Fn(&mut App)> {
13472                None
13473            }
13474        }
13475
13476        // 'Tab indicator painter image configuration'.
13477        #[test]
13478        fn the_indicator_paints_with_its_size_the_text_direction_and_the_device_pixel_ratio() {
13479            test_widgets(|tester| {
13480                let decoration = TestIndicatorDecoration::default();
13481
13482                let build_tabs =
13483                    |tester: &WidgetTester, text_direction: TextDirection, ratio: f64| {
13484                        let theme = theme(tester, None, None);
13485                        material_app(
13486                            theme,
13487                            MediaQuery::new(
13488                                MediaQueryData::new().device_pixel_ratio(ratio),
13489                                Directionality::new(
13490                                    text_direction,
13491                                    DefaultTabController::new(
13492                                        2,
13493                                        scaffold_with_tab_bar(
13494                                            None,
13495                                            TabBar::new(text_tabs(&["A", "B"]))
13496                                                .indicator(decoration.clone()),
13497                                            None,
13498                                        ),
13499                                    ),
13500                                ),
13501                            )
13502                            .into_widget(),
13503                        )
13504                    };
13505
13506                let widget = build_tabs(tester, TextDirection::Ltr, 1.0);
13507                tester.pump_widget(widget);
13508
13509                let last = |decoration: &TestIndicatorDecoration| {
13510                    decoration
13511                        .painters
13512                        .borrow()
13513                        .last()
13514                        .expect("a painter")
13515                        .borrow()
13516                        .clone()
13517                        .expect("a configuration")
13518                };
13519                let config = last(&decoration);
13520                let size = config.size.expect("a size");
13521                assert!(close(size.width(), 14.1, 0.1), "{size:?}");
13522                assert_eq!(size.height(), 48.0);
13523                assert_eq!(config.text_direction, Some(TextDirection::Ltr));
13524                assert_eq!(config.device_pixel_ratio, Some(1.0));
13525
13526                let widget = build_tabs(tester, TextDirection::Rtl, 2.33);
13527                tester.pump_widget(widget);
13528
13529                let config = last(&decoration);
13530                let size = config.size.expect("a size");
13531                assert!(close(size.width(), 14.1, 0.1), "{size:?}");
13532                assert_eq!(size.height(), 48.0);
13533                assert_eq!(config.text_direction, Some(TextDirection::Rtl));
13534                assert_eq!(config.device_pixel_ratio, Some(2.33));
13535            });
13536        }
13537
13538        // 'TabBar.textScaler overrides tab label text scale, textScaleFactor = noScaling, 1.75, 2.0'.
13539        #[test]
13540        fn the_text_scaler_of_a_tab_bar_overrides_the_ambient_one() {
13541            test_widgets(|tester| {
13542                let build_tabs = |tester: &WidgetTester, text_scaler: TextScaler| {
13543                    let theme = theme(tester, None, None);
13544                    material_app(
13545                        theme,
13546                        MediaQuery::new(
13547                            MediaQueryData::new().text_scaler(TextScaler::linear(3.0)),
13548                            DefaultTabController::new(
13549                                2,
13550                                scaffold_with_tab_bar(
13551                                    None,
13552                                    TabBar::new(text_tabs(&["Tab 1", "Tab 2"]))
13553                                        .text_scaler(text_scaler),
13554                                    None,
13555                                ),
13556                            ),
13557                        )
13558                        .into_widget(),
13559                    )
13560                };
13561
13562                let widget = build_tabs(tester, TextScaler::NO_SCALING);
13563                tester.pump_widget(widget);
13564                assert_eq!(
13565                    tester.get_size(text(tester, "Tab 1")),
13566                    Size::new(70.5, 20.0)
13567                );
13568
13569                let widget = build_tabs(tester, TextScaler::linear(1.75));
13570                tester.pump_widget(widget);
13571                assert_eq!(
13572                    tester.get_size(text(tester, "Tab 1")),
13573                    Size::new(123.0, 35.0)
13574                );
13575
13576                let widget = build_tabs(tester, TextScaler::linear(2.0));
13577                tester.pump_widget(widget);
13578                assert_eq!(
13579                    tester.get_size(text(tester, "Tab 1")),
13580                    Size::new(140.5, 40.0)
13581                );
13582            });
13583        }
13584
13585        /// The pixels of the first `SingleChildScrollView`'s controller.
13586        fn scroll_view_pixels(tester: &WidgetTester) -> f64 {
13587            let scroll_view = only::<SingleChildScrollView>(tester);
13588            let controller = tester.widget(scroll_view, |scroll_view: &SingleChildScrollView| {
13589                scroll_view
13590                    .controller
13591                    .clone()
13592                    .expect("a tab bar hands its scroll view a controller")
13593            });
13594            let app = tester.cell.borrow();
13595            controller.position(&app).pixels(&app)
13596        }
13597
13598        /// Dart's `MaterialApp(home: DefaultTabController(length: 20, initialIndex:, child:
13599        /// Scaffold(appBar: AppBar(bottom: TabBar(isScrollable: true, ..)), body: TabBarView(..))))`.
13600        fn twenty_scrollable_tabs(tester: &WidgetTester, initial_index: usize) -> WidgetRef {
13601            let theme = theme(tester, None, None);
13602            let tabs = (0..20).map(|index| Tab::new().text(format!("Tab {index}")).into_widget());
13603            material_app(
13604                theme,
13605                DefaultTabController::new(
13606                    20,
13607                    scaffold_with_tab_bar(
13608                        None,
13609                        TabBar::new(tabs).is_scrollable(true),
13610                        Some(
13611                            TabBarView::new((0..20).map(|i| {
13612                                Center::new()
13613                                    .child(Text::new(format!("Page {i}")))
13614                                    .into_widget()
13615                            }))
13616                            .into_widget(),
13617                        ),
13618                    ),
13619                )
13620                .initial_index(initial_index)
13621                .into_widget(),
13622            )
13623        }
13624
13625        // 'Scrollable TabBar does not jitter in the middle position'.
13626        #[test]
13627        fn a_scrollable_tab_bar_follows_a_dragged_tab_bar_view_without_jitter_in_the_middle() {
13628            test_widgets(|tester| {
13629                let widget = twenty_scrollable_tabs(tester, 10);
13630                tester.pump_widget(widget);
13631
13632                expect(tester, &find::text("Page 10"), finds_one_widget());
13633                expect(tester, &find::text("Page 11"), finds_nothing());
13634                let pixels = scroll_view_pixels(tester);
13635                assert!(close(pixels, 683.2, 0.1), "{pixels}");
13636
13637                // Drag the TabBarView to the left.
13638                let view = tester.get_center(only::<TabBarView>(tester));
13639                tester.drag_from(view, Offset::new(-800.0, 0.0), 1);
13640                tester.pump();
13641                tester.pump_by(Duration::from_millis(200));
13642
13643                expect(tester, &find::text("Page 10"), finds_nothing());
13644                expect(tester, &find::text("Page 11"), finds_one_widget());
13645                let pixels = scroll_view_pixels(tester);
13646                assert!(close(pixels, 799.8, 0.1), "{pixels}");
13647            });
13648        }
13649
13650        // 'Scrollable TabBar does not jitter when the tab bar reaches the start'.
13651        #[test]
13652        fn a_scrollable_tab_bar_follows_a_dragged_tab_bar_view_without_jitter_at_the_start() {
13653            test_widgets(|tester| {
13654                let widget = twenty_scrollable_tabs(tester, 4);
13655                tester.pump_widget(widget);
13656
13657                expect(tester, &find::text("Page 4"), finds_one_widget());
13658                expect(tester, &find::text("Page 3"), finds_nothing());
13659                let pixels = scroll_view_pixels(tester);
13660                assert!(close(pixels, 61.25, 0.1), "{pixels}");
13661
13662                // Drag the TabBarView to the right.
13663                let start = tester.get_center(text(tester, "Page 4"));
13664                let mut gesture = TestPointer::touch(1);
13665                tester.down(&mut gesture, start);
13666                tester.move_to(&mut gesture, start + Offset::new(600.0, 0.0), true);
13667                tester.up(&gesture);
13668                tester.pump();
13669                tester.pump_by(Duration::from_millis(500));
13670
13671                expect(tester, &find::text("Page 4"), finds_one_widget());
13672                expect(tester, &find::text("Page 3"), finds_one_widget());
13673                let pixels = scroll_view_pixels(tester);
13674                assert!(close(pixels, 0.2, 0.1), "{pixels}");
13675
13676                tester.pump_and_settle();
13677                expect(tester, &find::text("Page 4"), finds_nothing());
13678                expect(tester, &find::text("Page 3"), finds_one_widget());
13679                assert_eq!(scroll_view_pixels(tester), 0.0);
13680            });
13681        }
13682
13683        // 'Scrollable TabBar with transparent divider expands to full width'.
13684        #[test]
13685        fn a_scrollable_tab_bar_with_a_transparent_divider_is_as_wide_as_its_parent() {
13686            test_widgets(|tester| {
13687                for tab_alignment in [
13688                    TabAlignment::StartOffset,
13689                    TabAlignment::Start,
13690                    TabAlignment::Center,
13691                ] {
13692                    let theme = theme(tester, None, None);
13693                    tester.pump_widget(boilerplate(
13694                        theme,
13695                        TextDirection::Ltr,
13696                        Center::new().child(DefaultTabController::new(
13697                            3,
13698                            TabBar::new(text_tabs(&["Tab 1", "Tab 2", "Tab 3"]))
13699                                .divider_color(Colors::TRANSPARENT)
13700                                .tab_alignment(tab_alignment)
13701                                .is_scrollable(true),
13702                        )),
13703                    ));
13704                    assert_eq!(
13705                        tester.get_size(only::<TabBar>(tester)).width(),
13706                        800.0,
13707                        "{tab_alignment:?}"
13708                    );
13709                }
13710            });
13711        }
13712
13713        // 'TabBar.indicatorAnimation can customize tab indicator animation'.
13714        #[test]
13715        fn the_indicator_animation_of_a_tab_bar_moves_the_indicator_linearly_or_elastically() {
13716            test_widgets(|tester| {
13717                const INDICATOR_WIDTH: f64 = 50.0;
13718                let controller = controller(tester, 4);
13719                let build_tab =
13720                    |tester: &WidgetTester, indicator_animation: TabIndicatorAnimation| {
13721                        let theme = theme(tester, None, None);
13722                        let tabs = (0..4).map(|index| {
13723                            Tab::new()
13724                                .key(waft_foundation::ValueKey::new(index).into())
13725                                .child(SizedBox::new().width(INDICATOR_WIDTH))
13726                                .into_widget()
13727                        });
13728                        material_app(
13729                            theme.clone(),
13730                            boilerplate(
13731                                theme,
13732                                TextDirection::Ltr,
13733                                top_left(
13734                                    TabBar::new(tabs)
13735                                        .indicator_animation(indicator_animation)
13736                                        .controller(controller.clone()),
13737                                ),
13738                            ),
13739                        )
13740                    };
13741
13742                // Test tab indicator animation with TabIndicatorAnimation.linear.
13743                let widget = build_tab(tester, TabIndicatorAnimation::Linear);
13744                tester.pump_widget(widget);
13745
13746                // Idle at tab 0.
13747                assert!(paints_rrect(
13748                    tester,
13749                    indicator_rrect(75.0, 45.0, 125.0, 48.0)
13750                ));
13751
13752                // Start moving tab indicator.
13753                controller.set_offset(&mut tester.cell.borrow_mut(), 0.2);
13754                tester.pump();
13755
13756                assert!(paints_rrect(
13757                    tester,
13758                    indicator_rrect(115.0, 45.0, 165.0, 48.0)
13759                ));
13760
13761                // Reset tab controller offset.
13762                controller.set_offset(&mut tester.cell.borrow_mut(), 0.0);
13763
13764                // Test tab indicator animation with TabIndicatorAnimation.elastic.
13765                let widget = build_tab(tester, TabIndicatorAnimation::Elastic);
13766                tester.pump_widget(widget);
13767                tester.pump_and_settle();
13768
13769                let tab_bar_height = first_render_box::<TabBar>(tester)
13770                    .size(&tester.cell.borrow())
13771                    .height();
13772
13773                // Idle at tab 0.
13774                let current_rect = Rect::from_ltrb(75.0, 0.0, 125.0, 48.0);
13775                let from_rect = Rect::from_ltrb(75.0, 0.0, 125.0, 48.0);
13776                let to_rect = Rect::from_ltrb(75.0, 0.0, 125.0, 48.0);
13777                assert!(paints_rrect(
13778                    tester,
13779                    tab_indicator_rrect_elastic_animation(
13780                        tab_bar_height,
13781                        current_rect,
13782                        from_rect,
13783                        to_rect,
13784                        0.0
13785                    )
13786                ));
13787
13788                controller.set_offset(&mut tester.cell.borrow_mut(), 0.2);
13789                tester.pump();
13790                let to_rect = Rect::from_ltrb(275.0, 0.0, 325.0, 48.0);
13791                assert!(paints_rrect(
13792                    tester,
13793                    tab_indicator_rrect_elastic_animation(
13794                        tab_bar_height,
13795                        current_rect,
13796                        from_rect,
13797                        to_rect,
13798                        0.2
13799                    )
13800                ));
13801            });
13802        }
13803
13804        // 'Tabs icon respects ambient icon theme'.
13805        #[test]
13806        fn tab_icons_take_the_ambient_icon_theme_except_the_selected_ones_color() {
13807            test_widgets(|tester| {
13808                let icon_theme = IconThemeData::new()
13809                    .color(Color::new(0xffff0000))
13810                    .size(38.0);
13811                let theme = {
13812                    let app = tester.cell.borrow();
13813                    ThemeData::builder().icon_theme(icon_theme).build(&app)
13814                };
13815                let selected_icon = Icons::ac_unit();
13816                let unselected_icon = Icons::access_alarm();
13817                tester.pump_widget(boilerplate(
13818                    theme.clone(),
13819                    TextDirection::Ltr,
13820                    DefaultTabController::new(
13821                        2,
13822                        TabBar::new([
13823                            Tab::new()
13824                                .icon(Icon::new(Some(selected_icon.clone())))
13825                                .text("Tab 1")
13826                                .into_widget(),
13827                            Tab::new()
13828                                .icon(Icon::new(Some(unselected_icon.clone())))
13829                                .text("Tab 2")
13830                                .into_widget(),
13831                        ]),
13832                    ),
13833                ));
13834
13835                let icon_color = |tester: &WidgetTester, icon| {
13836                    let element = tester.element(find::by_icon(icon).first());
13837                    tester
13838                        .glyph_style(element)
13839                        .color
13840                        .as_ref()
13841                        .map(AnyColor::color)
13842                };
13843
13844                // The iconTheme color isn't applied to the selected icon.
13845                assert_eq!(
13846                    icon_color(tester, &selected_icon),
13847                    Some(theme.color_scheme.primary())
13848                );
13849                // The iconTheme color is applied to the unselected icon.
13850                assert_eq!(
13851                    icon_color(tester, &unselected_icon),
13852                    theme.icon_theme.color.as_ref().map(AnyColor::color)
13853                );
13854
13855                // Both selected and unselected icons should have the iconTheme size.
13856                let size = theme.icon_theme.size.expect("a size");
13857                let selected = tester.element(find::by_icon(&selected_icon).first());
13858                assert_eq!(tester.get_size(selected), Size::new(size, size));
13859                let unselected = tester.element(find::by_icon(&unselected_icon).first());
13860                assert_eq!(tester.get_size(unselected), Size::new(size, size));
13861            });
13862        }
13863
13864        /// The eight tabs of the overflow cases.
13865        const OVERFLOW_TABS: [&str; 8] = [
13866            "Short",
13867            "A Bit Longer Text",
13868            "An Extremely Long Tab Label That Overflows",
13869            "Tiny",
13870            "Moderate Length",
13871            "Just Right",
13872            "Supercalifragilisticexpialidocious",
13873            "Longer Than Usual",
13874        ];
13875
13876        /// The overflow cases' `buildTabBar`, pumped, with its controller.
13877        fn pump_overflow_tab_bar(
13878            tester: &mut WidgetTester,
13879            text_direction: TextDirection,
13880            indicator_animation: TabIndicatorAnimation,
13881            is_scrollable: bool,
13882        ) -> Ref<TabController> {
13883            let controller = controller(tester, OVERFLOW_TABS.len());
13884            let theme = theme(tester, None, None);
13885            tester.pump_widget(boilerplate(
13886                theme,
13887                text_direction,
13888                top_left(
13889                    TabBar::new(text_tabs(&OVERFLOW_TABS))
13890                        .is_scrollable(is_scrollable)
13891                        .indicator_animation(indicator_animation)
13892                        .controller(controller.clone()),
13893                ),
13894            ));
13895            controller
13896        }
13897
13898        /// Dart's `tester.tap(find.byType(Tab).at(index))`.
13899        fn tap_tab(tester: &mut WidgetTester, index: usize) {
13900            let tab = tabs_of(tester)[index];
13901            tap(tester, tab);
13902        }
13903
13904        /// Dart's `tester.tap(find.byType(Tab).last)`.
13905        fn tap_last_tab(tester: &mut WidgetTester) {
13906            let tab = *tabs_of(tester).last().expect("a tab");
13907            tap(tester, tab);
13908        }
13909
13910        fn tab_rect(tester: &WidgetTester, index: usize) -> Rect {
13911            tester.get_rect(tabs_of(tester)[index])
13912        }
13913
13914        /// The cases on a fixed tab bar: the indicator at two points of the animation to tab 2, kept
13915        /// inside the label's trailing edge, then on the label.
13916        fn fixed_overflow_case(
13917            text_direction: TextDirection,
13918            indicator_animation: TabIndicatorAnimation,
13919            steps: [(f64, f64); 2],
13920        ) {
13921            test_widgets(|tester| {
13922                pump_overflow_tab_bar(tester, text_direction, indicator_animation, false);
13923
13924                tap_tab(tester, 2);
13925                tester.pump();
13926                tester.pump_by(Duration::from_millis(100));
13927
13928                let label_rect = tab_rect(tester, 2);
13929                for (step, (indicator_left, indicator_right)) in steps.into_iter().enumerate() {
13930                    if step == 1 {
13931                        tester.pump_by(Duration::from_millis(100));
13932                    }
13933                    assert!(
13934                        paints_rrect(
13935                            tester,
13936                            indicator_rrect(indicator_left, 45.0, indicator_right, 48.0)
13937                        ),
13938                        "step {step}"
13939                    );
13940                    match text_direction {
13941                        TextDirection::Ltr => assert!(indicator_right < label_rect.right),
13942                        TextDirection::Rtl => assert!(indicator_left > label_rect.left),
13943                    }
13944                }
13945
13946                // Let the animation complete.
13947                tester.pump_by(Duration::from_millis(200));
13948
13949                assert!(paints_rrect(
13950                    tester,
13951                    indicator_rrect(label_rect.left, 45.0, label_rect.right, 48.0)
13952                ));
13953            });
13954        }
13955
13956        // 'Elastic Tab animation does not overflow target tab - LTR'.
13957        #[test]
13958        fn the_elastic_indicator_stays_inside_the_target_tab_left_to_right() {
13959            fixed_overflow_case(
13960                TextDirection::Ltr,
13961                TabIndicatorAnimation::Elastic,
13962                [
13963                    (92.50662931979836, 241.31938023664574),
13964                    (192.50227846755732, 282.61484607849377),
13965                ],
13966            );
13967        }
13968
13969        // 'Elastic Tab animation does not overflow target tab - RTL'.
13970        #[test]
13971        fn the_elastic_indicator_stays_inside_the_target_tab_right_to_left() {
13972            fixed_overflow_case(
13973                TextDirection::Rtl,
13974                TabIndicatorAnimation::Elastic,
13975                [
13976                    (558.6806197633543, 707.4933706802017),
13977                    (517.3851539215062, 607.497721532442),
13978                ],
13979            );
13980        }
13981
13982        // 'Linear Tab animation does not overflow target tab - LTR'.
13983        #[test]
13984        fn the_linear_indicator_stays_inside_the_target_tab_left_to_right() {
13985            fixed_overflow_case(
13986                TextDirection::Ltr,
13987                TabIndicatorAnimation::Linear,
13988                [
13989                    (131.26358723640442, 199.26358723640442),
13990                    (201.00625545158982, 269.0062554515898),
13991                ],
13992            );
13993        }
13994
13995        // 'Linear Tab animation does not overflow target tab - RTL'.
13996        #[test]
13997        fn the_linear_indicator_stays_inside_the_target_tab_right_to_left() {
13998            fixed_overflow_case(
13999                TextDirection::Rtl,
14000                TabIndicatorAnimation::Linear,
14001                [
14002                    (600.7364127635956, 668.7364127635956),
14003                    (530.9937445484102, 598.9937445484102),
14004                ],
14005            );
14006        }
14007
14008        /// What a step of a scrollable overflow case checks against the tab's corner.
14009        #[derive(Clone, Copy)]
14010        enum Edge {
14011            /// `indicatorRight < bottomRight.dx`.
14012            RightBeforeBottomRight,
14013            /// `indicatorLeft < bottomRight.dx`.
14014            LeftBeforeBottomRight,
14015            /// `indicatorLeft > bottomLeft.dx`.
14016            LeftAfterBottomLeft,
14017            /// `indicatorLeft > bottomRight.dx`.
14018            LeftAfterBottomRight,
14019        }
14020
14021        /// The cases on a scrollable tab bar: the indicator at three points of the animation to tab
14022        /// 2, each checked against the tab's corner as it then stands.
14023        ///
14024        /// The indicator's edges are compared within 1e-3: they sum the widths of long labels, which
14025        /// Valo measures in `f32`, a few ulps off Dart's `f64` sums at these magnitudes.
14026        fn scrollable_overflow_case(
14027            text_direction: TextDirection,
14028            indicator_animation: TabIndicatorAnimation,
14029            steps: [(f64, f64, Edge); 3],
14030        ) {
14031            test_widgets(|tester| {
14032                pump_overflow_tab_bar(tester, text_direction, indicator_animation, true);
14033
14034                tap_tab(tester, 2);
14035                tester.pump();
14036                tester.pump_by(Duration::from_millis(100));
14037
14038                for (step, (indicator_left, indicator_right, edge)) in steps.into_iter().enumerate()
14039                {
14040                    match step {
14041                        1 => tester.pump_by(Duration::from_millis(100)),
14042                        // Let the animation complete.
14043                        2 => tester.pump_by(Duration::from_millis(200)),
14044                        _ => {}
14045                    }
14046                    let label_rect = tab_rect(tester, 2);
14047                    assert!(
14048                        paints_rrect_within(
14049                            tester,
14050                            indicator_rrect(indicator_left, 45.0, indicator_right, 48.0),
14051                            1e-3
14052                        ),
14053                        "step {step}"
14054                    );
14055                    match edge {
14056                        Edge::RightBeforeBottomRight => assert!(indicator_right < label_rect.right),
14057                        Edge::LeftBeforeBottomRight => assert!(indicator_left < label_rect.right),
14058                        Edge::LeftAfterBottomLeft => assert!(indicator_left > label_rect.left),
14059                        Edge::LeftAfterBottomRight => assert!(indicator_left > label_rect.right),
14060                    }
14061                }
14062            });
14063        }
14064
14065        // 'Elastic Tab animation does not overflow target tab in a scrollable tab bar - LTR'.
14066        #[test]
14067        fn the_elastic_indicator_stays_inside_the_target_tab_of_a_scrollable_tab_bar_left_to_right()
14068        {
14069            scrollable_overflow_case(
14070                TextDirection::Ltr,
14071                TabIndicatorAnimation::Elastic,
14072                [
14073                    (
14074                        159.14390228994424,
14075                        791.2121709715643,
14076                        Edge::RightBeforeBottomRight,
14077                    ),
14078                    (
14079                        346.2357603195887,
14080                        976.195212100479,
14081                        Edge::LeftBeforeBottomRight,
14082                    ),
14083                    (
14084                        390.1999969482422,
14085                        982.4000091552734,
14086                        Edge::LeftBeforeBottomRight,
14087                    ),
14088                ],
14089            );
14090        }
14091
14092        // 'Elastic Tab animation does not overflow target tab in a scrollable tab bar - RTL'.
14093        #[test]
14094        fn the_elastic_indicator_stays_inside_the_target_tab_of_a_scrollable_tab_bar_right_to_left()
14095        {
14096            scrollable_overflow_case(
14097                TextDirection::Rtl,
14098                TabIndicatorAnimation::Elastic,
14099                [
14100                    (
14101                        1495.1878305543146,
14102                        2127.2560992359345,
14103                        Edge::LeftAfterBottomLeft,
14104                    ),
14105                    (
14106                        1310.2047894254,
14107                        1940.1642412062902,
14108                        Edge::LeftAfterBottomLeft,
14109                    ),
14110                    (
14111                        1303.9999923706055,
14112                        1896.2000045776367,
14113                        Edge::LeftAfterBottomLeft,
14114                    ),
14115                ],
14116            );
14117        }
14118
14119        // 'Linear Tab animation does not overflow target tab in a scrollable tab bar - LTR'.
14120        #[test]
14121        fn the_linear_indicator_stays_inside_the_target_tab_of_a_scrollable_tab_bar_left_to_right()
14122        {
14123            scrollable_overflow_case(
14124                TextDirection::Ltr,
14125                TabIndicatorAnimation::Linear,
14126                [
14127                    (
14128                        159.9711660555031,
14129                        453.47531034110943,
14130                        Edge::RightBeforeBottomRight,
14131                    ),
14132                    (
14133                        349.4619934677845,
14134                        888.8090538538061,
14135                        Edge::LeftBeforeBottomRight,
14136                    ),
14137                    (
14138                        390.1999969482422,
14139                        982.4000091552734,
14140                        Edge::LeftBeforeBottomRight,
14141                    ),
14142                ],
14143            );
14144        }
14145
14146        // 'Linear Tab animation does not overflow target tab in a scrollable tab bar - RTL'.
14147        #[test]
14148        fn the_linear_indicator_stays_inside_the_target_tab_of_a_scrollable_tab_bar_right_to_left()
14149        {
14150            scrollable_overflow_case(
14151                TextDirection::Rtl,
14152                TabIndicatorAnimation::Linear,
14153                [
14154                    (
14155                        1832.9246911847695,
14156                        2126.428835470376,
14157                        Edge::LeftAfterBottomRight,
14158                    ),
14159                    (
14160                        1397.590947672073,
14161                        1936.9380080580945,
14162                        Edge::LeftAfterBottomRight,
14163                    ),
14164                    (
14165                        1303.9999923706055,
14166                        1896.2000045776367,
14167                        Edge::LeftAfterBottomRight,
14168                    ),
14169                ],
14170            );
14171        }
14172
14173        /// The skipping cases: tab 2, the last tab, then tab 1, each halfway and then settled on the
14174        /// label.
14175        fn skipping_case(indicator_animation: TabIndicatorAnimation, halfway: [(f64, f64); 3]) {
14176            test_widgets(|tester| {
14177                let controller = controller(tester, 10);
14178                let theme = theme(tester, None, None);
14179                tester.pump_widget(boilerplate(
14180                    theme,
14181                    TextDirection::Ltr,
14182                    top_left(
14183                        TabBar::new(
14184                            (0..10)
14185                                .map(|index| Tab::new().text(format!("Tab {index}")).into_widget()),
14186                        )
14187                        .indicator_animation(indicator_animation)
14188                        .controller(controller),
14189                    ),
14190                ));
14191
14192                for (step, (indicator_left, indicator_right)) in halfway.into_iter().enumerate() {
14193                    let index = match step {
14194                        0 => {
14195                            tap_tab(tester, 2);
14196                            2
14197                        }
14198                        1 => {
14199                            tap_last_tab(tester);
14200                            9
14201                        }
14202                        _ => {
14203                            tap_tab(tester, 1);
14204                            1
14205                        }
14206                    };
14207                    tester.pump();
14208                    tester.pump_by(Duration::from_millis(200));
14209                    assert!(
14210                        paints_rrect(
14211                            tester,
14212                            indicator_rrect(indicator_left, 45.0, indicator_right, 48.0)
14213                        ),
14214                        "step {step}"
14215                    );
14216
14217                    tester.pump_and_settle();
14218                    let label_rect = tab_rect(tester, index);
14219                    assert!(
14220                        paints_rrect(
14221                            tester,
14222                            indicator_rrect(label_rect.left, 45.0, label_rect.right, 48.0)
14223                        ),
14224                        "step {step} settled"
14225                    );
14226                }
14227            });
14228        }
14229
14230        // 'Elastic Tab animation when skipping tabs'.
14231        #[test]
14232        fn the_elastic_indicator_moves_straight_to_a_skipped_to_tab() {
14233            skipping_case(
14234                TabIndicatorAnimation::Elastic,
14235                [
14236                    (157.20182277404584, 222.89187686279502),
14237                    (670.2063797091604, 780.1215690197826),
14238                    (100.43249254881991, 219.19270890381662),
14239                ],
14240            );
14241        }
14242
14243        // 'Linear Tab animation when skipping tabs'.
14244        #[test]
14245        fn the_linear_indicator_moves_straight_to_a_skipped_to_tab() {
14246            skipping_case(
14247                TabIndicatorAnimation::Linear,
14248                [
14249                    (164.00500436127186, 212.00500436127186),
14250                    (694.0175152644515, 742.0175152644515),
14251                    (143.97998255491257, 191.97998255491257),
14252                ],
14253            );
14254        }
14255
14256        /// The `MaterialApp(home: DefaultTabController(length: 3, child: Scaffold(appBar:
14257        /// AppBar(bottom: tab_bar), body: TabBarView(..))))` of the hover and focus cases.
14258        fn three_tab_app(tester: &WidgetTester, tab_bar: TabBar) -> WidgetRef {
14259            let theme = theme(tester, None, None);
14260            material_app(
14261                theme,
14262                DefaultTabController::new(
14263                    3,
14264                    scaffold_with_tab_bar(
14265                        None,
14266                        tab_bar,
14267                        Some(
14268                            TabBarView::new([
14269                                Text::new("Tab 1 View").into_widget(),
14270                                Text::new("Tab 2 View").into_widget(),
14271                                Text::new("Tab 3 View").into_widget(),
14272                            ])
14273                            .into_widget(),
14274                        ),
14275                    ),
14276                )
14277                .into_widget(),
14278            )
14279        }
14280
14281        // 'onHover is triggered when mouse pointer is over a tab'.
14282        #[test]
14283        fn on_hover_reports_a_pointer_entering_and_leaving_each_tab() {
14284            test_widgets(|tester| {
14285                let hover_events: Rc<RefCell<Vec<(bool, usize)>>> = Rc::default();
14286                let tab_bar = |secondary: bool| {
14287                    let events = Rc::clone(&hover_events);
14288                    let tabs = text_tabs(&["Tab 1", "Tab 2", "Tab 3"]);
14289                    if secondary {
14290                        TabBar::secondary(tabs)
14291                    } else {
14292                        TabBar::new(tabs)
14293                    }
14294                    .on_hover(move |_app, value, index| events.borrow_mut().push((value, index)))
14295                };
14296
14297                let widget = three_tab_app(tester, tab_bar(false));
14298                tester.pump_widget(widget);
14299                assert!(hover_events.borrow().is_empty());
14300
14301                // Hover over the first tab.
14302                let mut gesture = TestPointer::mouse(1, 0);
14303                tester.add_pointer(&mut gesture, Offset::ZERO);
14304                let mut expected = Vec::new();
14305                for secondary in [false, true] {
14306                    if secondary {
14307                        hover_events.borrow_mut().clear();
14308                        expected.clear();
14309                        let widget = three_tab_app(tester, tab_bar(true));
14310                        tester.pump_widget(widget);
14311                        assert!(hover_events.borrow().is_empty());
14312                    }
14313                    for (index, label) in ["Tab 1", "Tab 2", "Tab 3"].into_iter().enumerate() {
14314                        let at = tester.get_center(text(tester, label));
14315                        tester.move_to(&mut gesture, at, false);
14316                        tester.pump();
14317                        if index > 0 {
14318                            expected.push((false, index - 1));
14319                        }
14320                        expected.push((true, index));
14321                        assert_eq!(*hover_events.borrow(), expected);
14322                    }
14323                    let at = tester.get_center(only::<TabBarView>(tester));
14324                    tester.move_to(&mut gesture, at, false);
14325                    tester.pump();
14326                    expected.push((false, 2));
14327                    assert_eq!(*hover_events.borrow(), expected);
14328                }
14329            });
14330        }
14331
14332        // 'onFocusChange is triggered when tabs gain and lose focus'.
14333        #[test]
14334        fn on_focus_change_reports_each_tab_gaining_and_losing_focus() {
14335            test_widgets(|tester| {
14336                let focus_events: Rc<RefCell<Vec<(bool, usize)>>> = Rc::default();
14337                let tab_bar = |secondary: bool| {
14338                    let events = Rc::clone(&focus_events);
14339                    let tabs = text_tabs(&["Tab 1", "Tab 2", "Tab 3"]);
14340                    if secondary {
14341                        TabBar::secondary(tabs)
14342                    } else {
14343                        TabBar::new(tabs)
14344                    }
14345                    .on_focus_change(move |_app, value, index| {
14346                        events.borrow_mut().push((value, index))
14347                    })
14348                };
14349
14350                for secondary in [false, true] {
14351                    focus_events.borrow_mut().clear();
14352                    let widget = three_tab_app(tester, tab_bar(secondary));
14353                    tester.pump_widget(widget);
14354                    assert!(focus_events.borrow().is_empty());
14355
14356                    let mut expected = Vec::new();
14357                    let mut node = None;
14358                    for (index, label) in ["Tab 1", "Tab 2", "Tab 3"].into_iter().enumerate() {
14359                        let tab_element = text(tester, label);
14360                        let focus_node = {
14361                            let mut app = tester.cell.borrow_mut();
14362                            Focus::of(&mut app, tab_element, false, false)
14363                        };
14364                        focus_node.request_focus(&mut tester.cell.borrow_mut(), None);
14365                        tester.pump();
14366                        if index > 0 {
14367                            expected.push((false, index - 1));
14368                        }
14369                        expected.push((true, index));
14370                        assert_eq!(*focus_events.borrow(), expected);
14371                        node = Some(focus_node);
14372                    }
14373                    let node = node.expect("the third tab's node");
14374                    assert!(node.has_focus(&tester.cell.borrow_mut()));
14375
14376                    node.unfocus(&mut tester.cell.borrow_mut(), UnfocusDisposition::Scope);
14377                    tester.pump();
14378
14379                    assert!(!node.has_focus(&tester.cell.borrow_mut()));
14380                    expected.push((false, 2));
14381                    assert_eq!(*focus_events.borrow(), expected);
14382                }
14383            });
14384        }
14385
14386        // 'Ink features are painted on inner Material'.
14387        #[test]
14388        fn a_tab_bars_ink_features_are_painted_on_its_own_material() {
14389            test_widgets(|tester| {
14390                use crate::material::{AnyMaterialInkController, RenderInkFeatures};
14391
14392                let theme = theme(tester, None, None);
14393                tester.pump_widget(material_app(
14394                    theme,
14395                    Material::new()
14396                        .child(
14397                            Center::new().child(DefaultTabController::new(
14398                                10,
14399                                TabBar::new(
14400                                    (1..=10)
14401                                        .map(|i| Tab::new().text(format!("Tab {i}")).into_widget()),
14402                                )
14403                                .is_scrollable(true),
14404                            )),
14405                        )
14406                        .into_widget(),
14407                ));
14408
14409                expect(tester, &find::by_type::<Material>(), finds_n_widgets(2));
14410
14411                let tab_bar = only::<TabBar>(tester);
14412                let semantics = *tester
14413                    .descendants_of_type::<Semantics>(tab_bar)
14414                    .first()
14415                    .expect("a Semantics under the TabBar");
14416                let (outer_material, inner_material) = {
14417                    let app = tester.cell.borrow();
14418                    (Material::of(&app, tab_bar), Material::of(&app, semantics))
14419                };
14420                // Material outside the TabBar, and the Material directly wrapping the TabBar.
14421                assert_ne!(outer_material, inner_material);
14422
14423                let ink_features = |tester: &WidgetTester, material: AnyMaterialInkController| {
14424                    let render = tester
14425                        .all::<RenderInkFeatures>()
14426                        .into_iter()
14427                        .find(|render| render.as_object().id() == material.id())
14428                        .expect("the material's render object");
14429                    render
14430                        .debug_ink_features(&tester.cell.borrow())
14431                        .map(|features| features.len())
14432                };
14433                assert_eq!(ink_features(tester, outer_material), None);
14434                assert_eq!(ink_features(tester, inner_material), None);
14435
14436                // Hover over the first tab to trigger the ink highlight.
14437                let mut gesture = TestPointer::mouse(1, 0);
14438                let at = tester.get_center(text(tester, "Tab 1"));
14439                tester.add_pointer(&mut gesture, at);
14440                tester.pump();
14441
14442                // Only the inner Material should have ink features.
14443                assert_eq!(ink_features(tester, outer_material), None);
14444                assert_eq!(ink_features(tester, inner_material), Some(1));
14445            });
14446        }
14447
14448        // 'Tab can have children with other semantics roles'.
14449        #[test]
14450        fn a_tab_child_can_have_its_own_semantics_role() {
14451            test_widgets(|tester| {
14452                let theme = theme(tester, None, None);
14453                tester.pump_widget(material_app(
14454                    theme,
14455                    Material::new()
14456                        .child(
14457                            Center::new().child(DefaultTabController::new(
14458                                1,
14459                                TabBar::new([Tab::new()
14460                                    .child(
14461                                        Semantics::new()
14462                                            .role(SemanticsRole::ListItem)
14463                                            .child(Text::new("A")),
14464                                    )
14465                                    .into_widget()])
14466                                .is_scrollable(true),
14467                            )),
14468                        )
14469                        .into_widget(),
14470                ));
14471                assert_eq!(tabs_of(tester).len(), 1);
14472            });
14473        }
14474
14475        // 'TabPageSelector does not crash at zero area'.
14476        #[test]
14477        fn a_tab_page_selector_animates_at_zero_area() {
14478            test_widgets(|tester| {
14479                tester.view().set_physical_size(Size::ZERO);
14480                let controller = controller(tester, 2);
14481                let theme = theme(tester, None, None);
14482                tester.pump_widget(material_app(
14483                    theme,
14484                    Center::new()
14485                        .child(TabPageSelector::new().controller(controller.clone()))
14486                        .into_widget(),
14487                ));
14488                assert_eq!(tester.get_size(only::<TabPageSelector>(tester)), Size::ZERO);
14489                controller.animate_to(&mut tester.cell.borrow_mut(), 1, None, None);
14490                tester.pump();
14491                tester.pump_and_settle();
14492            });
14493        }
14494
14495        // 'TabBarView does not crash at zero area'.
14496        #[test]
14497        fn a_tab_bar_view_animates_at_zero_area() {
14498            test_widgets(|tester| {
14499                tester.view().set_physical_size(Size::ZERO);
14500                let controller = controller(tester, 2);
14501                let theme = theme(tester, None, None);
14502                tester.pump_widget(material_app(
14503                    theme,
14504                    Center::new()
14505                        .child(
14506                            TabBarView::new([
14507                                Text::new("X").into_widget(),
14508                                Text::new("Y").into_widget(),
14509                            ])
14510                            .controller(controller.clone()),
14511                        )
14512                        .into_widget(),
14513                ));
14514                assert_eq!(tester.get_size(only::<TabBarView>(tester)), Size::ZERO);
14515                controller.animate_to(&mut tester.cell.borrow_mut(), 1, None, None);
14516                tester.pump();
14517                tester.pump_and_settle();
14518            });
14519        }
14520
14521        // 'TabPageSelectorIndicator does not crash at zero area'.
14522        #[test]
14523        fn a_tab_page_selector_indicator_builds_at_zero_area() {
14524            test_widgets(|tester| {
14525                let theme = theme(tester, None, None);
14526                tester.pump_widget(material_app(
14527                    theme,
14528                    Center::new()
14529                        .child(SizedBox::shrink().child(TabPageSelectorIndicator::new(
14530                            Colors::RED.primary(),
14531                            Colors::BLUE.primary(),
14532                            1.0,
14533                        )))
14534                        .into_widget(),
14535                ));
14536                assert_eq!(
14537                    tester.get_size(only::<TabPageSelectorIndicator>(tester)),
14538                    Size::ZERO
14539                );
14540            });
14541        }
14542
14543        // 'DefaultTabController does not crash at zero area'.
14544        #[test]
14545        fn a_default_tab_controller_builds_at_zero_area() {
14546            test_widgets(|tester| {
14547                let theme = theme(tester, None, None);
14548                tester.pump_widget(material_app(
14549                    theme,
14550                    Center::new()
14551                        .child(
14552                            SizedBox::shrink().child(DefaultTabController::new(2, Scaffold::new())),
14553                        )
14554                        .into_widget(),
14555                ));
14556                assert_eq!(
14557                    tester.get_size(only::<DefaultTabController>(tester)),
14558                    Size::ZERO
14559                );
14560            });
14561        }
14562
14563        // 'Tab does not crash at zero area'.
14564        #[test]
14565        fn a_tab_builds_at_zero_area() {
14566            test_widgets(|tester| {
14567                let theme = theme(tester, None, None);
14568                tester.pump_widget(material_app(
14569                    theme,
14570                    Scaffold::new()
14571                        .body(
14572                            Center::new()
14573                                .child(SizedBox::shrink().child(Tab::new().child(Text::new("X")))),
14574                        )
14575                        .into_widget(),
14576                ));
14577                assert_eq!(tester.get_size(only::<Tab>(tester)), Size::ZERO);
14578            });
14579        }
14580
14581        // 'TabBar does not crash at zero area'.
14582        #[test]
14583        fn a_tab_bar_animates_at_zero_area() {
14584            test_widgets(|tester| {
14585                tester.view().set_physical_size(Size::ZERO);
14586                let controller = controller(tester, 2);
14587                let theme = theme(tester, None, None);
14588                tester.pump_widget(material_app(
14589                    theme,
14590                    Center::new()
14591                        .child(
14592                            TabBar::new([
14593                                Text::new("X").into_widget(),
14594                                Text::new("Y").into_widget(),
14595                            ])
14596                            .controller(controller.clone()),
14597                        )
14598                        .into_widget(),
14599                ));
14600                assert_eq!(tester.get_size(only::<TabBar>(tester)), Size::ZERO);
14601                controller.animate_to(&mut tester.cell.borrow_mut(), 1, None, None);
14602                tester.pump();
14603                tester.pump_and_settle();
14604            });
14605        }
14606
14607        /// tabs_utils.dart's `TabBarAsyncImageIndicatorDecoration`: its painters count their paints,
14608        /// and the first paint of each asks for a repaint later, as an image that finishes loading
14609        /// does.
14610        ///
14611        /// Dart's painter calls `onChanged` from `Future.delayed(Duration.zero)`; a `BoxPainter`
14612        /// here paints without the `App`, so it leaves the call in `pending`, and the case makes it
14613        /// where Dart's event queue would, between the frames.
14614        #[derive(Clone, Default)]
14615        struct TabBarAsyncImageIndicatorDecoration {
14616            paint_count: Rc<Cell<usize>>,
14617            pending: Rc<RefCell<Vec<waft_foundation::VoidCallback>>>,
14618        }
14619
14620        impl TabBarAsyncImageIndicatorDecoration {
14621            fn run_pending(&self, app: &mut App) {
14622                let pending = std::mem::take(&mut *self.pending.borrow_mut());
14623                for on_changed in pending {
14624                    on_changed(app);
14625                }
14626            }
14627        }
14628
14629        impl fmt::Debug for TabBarAsyncImageIndicatorDecoration {
14630            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
14631                f.write_str("TabBarAsyncImageIndicatorDecoration")
14632            }
14633        }
14634
14635        impl Decoration for TabBarAsyncImageIndicatorDecoration {
14636            fn create_box_painter(
14637                &self,
14638                on_changed: Option<waft_foundation::VoidCallback>,
14639            ) -> Box<dyn BoxPainter> {
14640                Box::new(TabBarAsyncImageIndicatorBoxPainter {
14641                    on_changed,
14642                    paint_count: Rc::clone(&self.paint_count),
14643                    pending: Rc::clone(&self.pending),
14644                    image_painted: false,
14645                })
14646            }
14647
14648            fn as_any(&self) -> &dyn Any {
14649                self
14650            }
14651        }
14652
14653        /// tabs_utils.dart's `TabBarAsyncImageIndicatorBoxPainter`.
14654        struct TabBarAsyncImageIndicatorBoxPainter {
14655            on_changed: Option<waft_foundation::VoidCallback>,
14656            paint_count: Rc<Cell<usize>>,
14657            pending: Rc<RefCell<Vec<waft_foundation::VoidCallback>>>,
14658            image_painted: bool,
14659        }
14660
14661        impl BoxPainter for TabBarAsyncImageIndicatorBoxPainter {
14662            fn paint(
14663                &mut self,
14664                canvas: &mut Canvas,
14665                offset: Offset,
14666                configuration: &ImageConfiguration,
14667            ) {
14668                self.paint_count.set(self.paint_count.get() + 1);
14669
14670                // Simulate async image loading on first paint.
14671                if !self.image_painted
14672                    && let Some(on_changed) = &self.on_changed
14673                {
14674                    self.image_painted = true;
14675                    self.pending.borrow_mut().push(Rc::clone(on_changed));
14676                }
14677
14678                // Paint a simple rectangle to indicate the indicator was painted.
14679                let size = configuration.size.expect("a size");
14680                canvas.draw_rect(
14681                    Rect::from_ltwh(offset.dx(), size.height() - 2.0, size.width(), 2.0),
14682                    &Paint::from_color(Colors::BLUE.primary().into()),
14683                );
14684            }
14685
14686            fn on_changed(&self) -> Option<&dyn Fn(&mut App)> {
14687                self.on_changed.as_deref()
14688            }
14689        }
14690
14691        // 'TabBar indicator image should be rendered at initialIndex for the first time'.
14692        #[test]
14693        fn an_indicator_whose_image_loads_later_repaints_on_the_initial_tab() {
14694            test_widgets(|tester| {
14695                let decoration = TabBarAsyncImageIndicatorDecoration::default();
14696                let theme = theme(tester, None, None);
14697                tester.pump_widget(material_app(
14698                    theme,
14699                    DefaultTabController::new(
14700                        3,
14701                        scaffold_with_tab_bar(
14702                            None,
14703                            TabBar::new(text_tabs(&["One", "Two", "Three"]))
14704                                .indicator(decoration.clone()),
14705                            Some(
14706                                TabBarView::new(["Page One", "Page Two", "Page Three"].map(
14707                                    |page| Center::new().child(Text::new(page)).into_widget(),
14708                                ))
14709                                .into_widget(),
14710                            ),
14711                        ),
14712                    )
14713                    .into_widget(),
14714                ));
14715
14716                // Initial paint - indicator should be painted once.
14717                assert_eq!(decoration.paint_count.get(), 1);
14718
14719                // Pump with duration to allow the event queue (async image load simulation) to complete.
14720                decoration.run_pending(&mut tester.cell.borrow_mut());
14721                tester.pump_by(Duration::from_millis(1));
14722
14723                // After async image loads, the indicator should be repainted.
14724                // This verifies that the markNeedsPaint callback properly triggers a repaint.
14725                assert!(
14726                    decoration.paint_count.get() > 1,
14727                    "Indicator should be repainted after async image loads"
14728                );
14729
14730                // Verify the indicator repaints when switching tabs.
14731                let initial_paint_count = decoration.paint_count.get();
14732                let two = text(tester, "Two");
14733                tap(tester, two);
14734                tester.pump_and_settle();
14735
14736                assert!(
14737                    decoration.paint_count.get() > initial_paint_count,
14738                    "Indicator should repaint when switching tabs"
14739                );
14740            });
14741        }
14742    }
14743
14744    /// Dart's `_TabLabelBarRenderer` fills no properties of its own; it inherits
14745    /// `RenderFlex.debugFillProperties` and names its children `child 1`, `child 2`, ….
14746    #[test]
14747    fn a_tab_label_bar_fills_the_properties_it_inherits() {
14748        use waft_foundation::{AppCell, DiagnosticPropertiesBuilder, DiagnosticsNode};
14749        use waft_rendering::RenderConstrainedBox;
14750
14751        let cell = AppCell::new();
14752        let mut app = cell.borrow_mut();
14753        let callback: LayoutCallback = Rc::new(|_app, _offsets, _text_direction, _width| {});
14754        let bar = TabLabelBarRenderer::new(
14755            &mut app,
14756            Axis::Horizontal,
14757            MainAxisSize::Max,
14758            MainAxisAlignment::Start,
14759            CrossAxisAlignment::End,
14760            TextDirection::Ltr,
14761            VerticalDirection::Down,
14762            callback,
14763        );
14764        let first = RenderConstrainedBox::new(
14765            &mut app,
14766            waft_rendering::BoxConstraints::tight(waft_embedder::Size::new(10.0, 10.0)),
14767            None,
14768        )
14769        .as_box();
14770        let second = RenderConstrainedBox::new(
14771            &mut app,
14772            waft_rendering::BoxConstraints::tight(waft_embedder::Size::new(10.0, 10.0)),
14773            None,
14774        )
14775        .as_box();
14776        bar.insert(&mut app, first, None);
14777        bar.insert(&mut app, second, None);
14778
14779        let mut properties = DiagnosticPropertiesBuilder::new();
14780        RenderObject::debug_fill_properties(bar, &app, &mut properties);
14781        let names: Vec<&str> = properties
14782            .properties
14783            .iter()
14784            .filter_map(|property| property.name())
14785            .collect();
14786        assert_eq!(
14787            names,
14788            [
14789                "direction",
14790                "mainAxisAlignment",
14791                "mainAxisSize",
14792                "crossAxisAlignment",
14793                "textDirection",
14794                "verticalDirection",
14795                "textBaseline",
14796                "spacing",
14797            ]
14798        );
14799
14800        let node = bar.as_object().to_diagnostics_node(&app, None);
14801        let children: Vec<&str> = node
14802            .children()
14803            .iter()
14804            .filter_map(|child| child.name())
14805            .collect();
14806        assert_eq!(children, ["child 1", "child 2"]);
14807    }
14808}