Skip to main content

waft_material/
carousel.rs

1//! Flutter counterpart: material_ui's `carousel.dart`.
2//!
3//! `CarouselView` and its scrolling machinery: the two slivers with their render objects
4//! (items of a fixed extent that shrink at the edges, and items sized by weights), the
5//! snapping physics, the position that keeps its offset in items, and the controller.
6//!
7//! Dart's render objects read their `constraints` inside the `itemExtentBuilder` they pass to
8//! `RenderSliverFixedExtentBoxAdaptor`. Here the builder takes no `App`, so each render object
9//! hands the adaptor a builder over a snapshot of the constraints it reads; the constraints do
10//! not change during one layout.
11
12#![allow(clippy::too_many_arguments)]
13
14use std::any::Any;
15use std::fmt::{self, Debug};
16use std::rc::Rc;
17use std::time::Duration;
18
19use waft_animation::Curve;
20use waft_embedder::{Clip, Color, clamp_double};
21use waft_foundation::{
22    App, ChangeNotifier, ChangeNotifierData, CompleterFuture, Handle, ListenableObject, Listener,
23    OptionRetained, PRECISION_ERROR_TOLERANCE, Ref, ValueChanged, wait_all,
24};
25use waft_painting::{
26    Axis, AxisDirection, BorderRadiusGeometry, EdgeInsets, RoundedRectangleBorder, ShapeBorderRef,
27};
28use waft_physics::{ScrollSpringSimulation, Simulation, Tolerance};
29use waft_rendering::{
30    AnyRenderBox, ContainerRenderObjectData, ContainerRenderObjectMixin, ItemExtentBuilder,
31    RenderHandle, RenderObjectData, RenderSliver, RenderSliverBoxChildManager, RenderSliverData,
32    RenderSliverFixedExtentBoxAdaptor, RenderSliverFixedExtentBoxAdaptorData,
33    RenderSliverMultiBoxAdaptor, RenderSliverMultiBoxAdaptorData, ScrollCacheExtent,
34    SliverConstraints, SliverGeometry, SliverLayoutDimensions, SliverMultiBoxAdaptorParentData,
35    ViewportOffset, fixed_extent_box_adaptor_leaf, render_sliver_fixed_extent_accessors,
36};
37use waft_widgets::{
38    AnyScrollPosition, BuildContext, FixedScrollMetrics, GestureDetector, IntoWidget, KeyRef,
39    LayoutBuilder, NullableIndexedWidgetBuilder, Padding, RenderObjectWidget,
40    ScrollActivityDelegate, ScrollConfiguration, ScrollContext, ScrollControllerData,
41    ScrollControllerLeaf, ScrollMetrics, ScrollPhysics, ScrollPhysicsBase, ScrollPhysicsRef,
42    ScrollPosition, ScrollPositionBase, ScrollPositionData, ScrollPositionRef,
43    ScrollPositionWithSingleContext, ScrollPositionWithSingleContextData,
44    ScrollPositionWithSingleContextLeaf, SliverChildBuilderDelegate, SliverChildDelegateRef,
45    SliverMultiBoxAdaptorWidget, SliverWithKeepAliveWidget, Stack, StackFit, State, StateData,
46    StatefulWidget, WidgetRef, WidgetState, WidgetStateProperty, WidgetStatePropertyRef,
47    child_manager_of,
48};
49
50use crate::carousel_theme::CarouselViewTheme;
51use crate::colors::Colors;
52use crate::ink_well::InkWell;
53use crate::material::Material;
54use crate::theme::Theme;
55
56/// Signature of the builder `CarouselView.builder` and `CarouselView.weightedBuilder` take: it
57/// answers `None` for an index beyond the last item.
58pub type CarouselItemBuilder = NullableIndexedWidgetBuilder;
59
60/// A Material Design carousel widget.
61///
62/// The [`CarouselView`] presents a scrollable list of items, each of which can dynamically
63/// change size based on the chosen layout.
64///
65/// Material Design 3 introduced 4 carousel layouts:
66///
67///  * Multi-browse and uncontained: [`CarouselView::new`] with an
68///    [`item_extent`](Self::item_extent) — the items have the same maximum extent and shrink to
69///    a smaller one as they reach the edges.
70///  * Hero and center-aligned hero: [`CarouselView::weighted`], whose items' extents follow
71///    the [`flex_weights`](Self::flex_weights).
72///
73/// The [`CarouselView::builder`] and [`CarouselView::weighted_builder`] constructors build their
74/// items lazily; with [`infinite`](Self::infinite) set, the list repeats its items forever.
75///
76/// The properties of the items' `Material` that are `None` come from the
77/// [`CarouselViewTheme`](crate::CarouselViewTheme), and then from the defaults documented on
78/// each field.
79///
80/// See also:
81///
82///  * [`CarouselController`], which controls the scroll position of this widget.
83///  * `PageView`, which is a scrollable list that works page by page.
84pub struct CarouselView {
85    pub key: Option<KeyRef>,
86    /// The amount of space surrounding each carousel item.
87    ///
88    /// Defaults to `EdgeInsets::all(4.0)`.
89    pub padding: Option<EdgeInsets>,
90
91    /// The background color for each carousel item.
92    ///
93    /// Defaults to `ColorScheme::surface`.
94    pub background_color: Option<Color>,
95
96    /// The z-coordinate of each carousel item.
97    ///
98    /// Defaults to 0.0.
99    pub elevation: Option<f64>,
100
101    /// The shape of each carousel item's [`Material`].
102    ///
103    /// Defaults to a `RoundedRectangleBorder` with a circular corner radius of 28.0.
104    pub shape: Option<ShapeBorderRef>,
105
106    /// The clip behavior for each carousel item.
107    ///
108    /// Defaults to [`Clip::AntiAlias`].
109    pub item_clip_behavior: Option<Clip>,
110
111    /// The highlight color to indicate the carousel items are in pressed, hovered or focused
112    /// states.
113    ///
114    /// Defaults to `ColorScheme::onSurface` with opacities of 0.1 (pressed), 0.08 (hovered)
115    /// and 0.1 (focused).
116    pub overlay_color: Option<WidgetStatePropertyRef<Option<Color>>>,
117
118    /// The minimum allowable extent (size) in the main axis for carousel items in the
119    /// viewport.
120    ///
121    /// As the carousel scrolls, the first visible item is pinned and gradually shrinks to
122    /// [`shrink_extent`](Self::shrink_extent) before disappearing.
123    ///
124    /// Defaults to 0.0.
125    pub shrink_extent: f64,
126
127    /// The scroll position snaps to the nearest item when scrolling ends.
128    ///
129    /// Defaults to false.
130    pub item_snapping: bool,
131
132    /// An object that can be used to control the position to which this scroll view is
133    /// scrolled.
134    pub controller: Option<Ref<CarouselController>>,
135
136    /// The [`Axis`] along which the scroll view's offset increases with each item.
137    ///
138    /// Defaults to [`Axis::Horizontal`].
139    pub scroll_direction: Axis,
140
141    /// Whether the carousel list scrolls in the reading direction.
142    ///
143    /// Defaults to false.
144    pub reverse: bool,
145
146    /// Whether the items scroll past the position of the largest weight so that every item
147    /// has a chance to be the largest. Only meaningful for the weighted constructors.
148    ///
149    /// Defaults to true.
150    pub consume_max_weight: bool,
151
152    /// Called when one of the items is tapped, with its index.
153    pub on_tap: Option<ValueChanged<i32>>,
154
155    /// Whether the items show the ink splash and the overlay colors when they are tapped,
156    /// hovered or focused.
157    ///
158    /// Defaults to true.
159    pub enable_splash: bool,
160
161    /// The extent the children are forced to have in the main axis. Set by
162    /// [`CarouselView::new`] and [`CarouselView::builder`].
163    pub item_extent: Option<f64>,
164
165    /// The weights that determine the extent of each item. Set by [`CarouselView::weighted`]
166    /// and [`CarouselView::weighted_builder`].
167    pub flex_weights: Option<Vec<i32>>,
168
169    /// The child widgets for the carousel; empty for the builder constructors.
170    pub children: Vec<WidgetRef>,
171
172    /// Called when the leading item changes while the carousel is scrolled.
173    pub on_index_changed: Option<ValueChanged<i32>>,
174
175    /// The builder of the builder constructors, which build the items lazily.
176    pub item_builder: Option<CarouselItemBuilder>,
177
178    /// The number of items the builder constructors can build; `None` means as many as the
179    /// builder answers.
180    pub item_count: Option<i32>,
181
182    /// Whether the carousel loops its items forever.
183    ///
184    /// Defaults to false.
185    pub infinite: bool,
186}
187
188impl CarouselView {
189    fn base() -> CarouselView {
190        CarouselView {
191            key: None,
192            padding: None,
193            background_color: None,
194            elevation: None,
195            shape: None,
196            item_clip_behavior: None,
197            overlay_color: None,
198            shrink_extent: 0.0,
199            item_snapping: false,
200            controller: None,
201            scroll_direction: Axis::Horizontal,
202            reverse: false,
203            consume_max_weight: true,
204            on_tap: None,
205            enable_splash: true,
206            item_extent: None,
207            flex_weights: None,
208            children: Vec::new(),
209            on_index_changed: None,
210            item_builder: None,
211            item_count: None,
212            infinite: false,
213        }
214    }
215
216    /// Creates a Material Design carousel whose items all have the extent `item_extent`.
217    pub fn new(item_extent: f64, children: Vec<WidgetRef>) -> CarouselView {
218        CarouselView {
219            item_extent: Some(item_extent),
220            children,
221            ..CarouselView::base()
222        }
223    }
224
225    /// Creates a Material Design carousel whose items' extents follow `flex_weights`.
226    ///
227    /// The length of `flex_weights` is how many items fit in the viewport at a time.
228    pub fn weighted(flex_weights: Vec<i32>, children: Vec<WidgetRef>) -> CarouselView {
229        CarouselView {
230            flex_weights: Some(flex_weights),
231            children,
232            ..CarouselView::base()
233        }
234    }
235
236    /// Creates a Material Design carousel that builds its items lazily, each with the extent
237    /// `item_extent`.
238    pub fn builder(item_extent: f64, item_builder: CarouselItemBuilder) -> CarouselView {
239        CarouselView {
240            item_extent: Some(item_extent),
241            item_builder: Some(item_builder),
242            ..CarouselView::base()
243        }
244    }
245
246    /// Creates a Material Design carousel that builds its items lazily, with extents that
247    /// follow `flex_weights`.
248    pub fn weighted_builder(
249        flex_weights: Vec<i32>,
250        item_builder: CarouselItemBuilder,
251    ) -> CarouselView {
252        CarouselView {
253            flex_weights: Some(flex_weights),
254            item_builder: Some(item_builder),
255            ..CarouselView::base()
256        }
257    }
258
259    /// Dart `CarouselView(key:)`.
260    pub fn key(mut self, key: KeyRef) -> CarouselView {
261        self.key = Some(key);
262        self
263    }
264
265    /// Dart `CarouselView(padding:)`.
266    pub fn padding(mut self, padding: EdgeInsets) -> CarouselView {
267        self.padding = Some(padding);
268        self
269    }
270
271    /// Dart `CarouselView(backgroundColor:)`.
272    pub fn background_color(mut self, background_color: Color) -> CarouselView {
273        self.background_color = Some(background_color);
274        self
275    }
276
277    /// Dart `CarouselView(elevation:)`.
278    pub fn elevation(mut self, elevation: f64) -> CarouselView {
279        self.elevation = Some(elevation);
280        self
281    }
282
283    /// Dart `CarouselView(shape:)`.
284    pub fn shape(mut self, shape: impl Into<ShapeBorderRef>) -> CarouselView {
285        self.shape = Some(shape.into());
286        self
287    }
288
289    /// Dart `CarouselView(itemClipBehavior:)`.
290    pub fn item_clip_behavior(mut self, item_clip_behavior: Clip) -> CarouselView {
291        self.item_clip_behavior = Some(item_clip_behavior);
292        self
293    }
294
295    /// Dart `CarouselView(overlayColor:)`.
296    pub fn overlay_color(
297        mut self,
298        overlay_color: WidgetStatePropertyRef<Option<Color>>,
299    ) -> CarouselView {
300        self.overlay_color = Some(overlay_color);
301        self
302    }
303
304    /// Dart `CarouselView(itemSnapping:)`.
305    pub fn item_snapping(mut self, item_snapping: bool) -> CarouselView {
306        self.item_snapping = item_snapping;
307        self
308    }
309
310    /// Dart `CarouselView(shrinkExtent:)`.
311    pub fn shrink_extent(mut self, shrink_extent: f64) -> CarouselView {
312        self.shrink_extent = shrink_extent;
313        self
314    }
315
316    /// Dart `CarouselView(controller:)`.
317    pub fn controller(mut self, controller: Ref<CarouselController>) -> CarouselView {
318        self.controller = Some(controller);
319        self
320    }
321
322    /// Dart `CarouselView(scrollDirection:)`.
323    pub fn scroll_direction(mut self, scroll_direction: Axis) -> CarouselView {
324        self.scroll_direction = scroll_direction;
325        self
326    }
327
328    /// Dart `CarouselView(reverse:)`.
329    pub fn reverse(mut self, reverse: bool) -> CarouselView {
330        self.reverse = reverse;
331        self
332    }
333
334    /// Dart `CarouselView.weighted(consumeMaxWeight:)`.
335    pub fn consume_max_weight(mut self, consume_max_weight: bool) -> CarouselView {
336        self.consume_max_weight = consume_max_weight;
337        self
338    }
339
340    /// Dart `CarouselView(onTap:)`.
341    pub fn on_tap(mut self, on_tap: ValueChanged<i32>) -> CarouselView {
342        self.on_tap = Some(on_tap);
343        self
344    }
345
346    /// Dart `CarouselView(enableSplash:)`.
347    pub fn enable_splash(mut self, enable_splash: bool) -> CarouselView {
348        self.enable_splash = enable_splash;
349        self
350    }
351
352    /// Dart `CarouselView(onIndexChanged:)`.
353    pub fn on_index_changed(mut self, on_index_changed: ValueChanged<i32>) -> CarouselView {
354        self.on_index_changed = Some(on_index_changed);
355        self
356    }
357
358    /// Dart `CarouselView.builder(itemCount:)`.
359    pub fn item_count(mut self, item_count: i32) -> CarouselView {
360        self.item_count = Some(item_count);
361        self
362    }
363
364    /// Dart `CarouselView(infinite:)`.
365    pub fn infinite(mut self, infinite: bool) -> CarouselView {
366        self.infinite = infinite;
367        self
368    }
369}
370
371impl Debug for CarouselView {
372    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
373        f.debug_struct("CarouselView")
374            .field("item_extent", &self.item_extent)
375            .field("flex_weights", &self.flex_weights)
376            .field("children", &self.children.len())
377            .finish_non_exhaustive()
378    }
379}
380
381impl StatefulWidget for CarouselView {
382    type State = CarouselViewState;
383
384    fn key(&self) -> Option<&KeyRef> {
385        self.key.as_ref()
386    }
387
388    fn create_state(&self) -> CarouselViewState {
389        CarouselViewState {
390            state: StateData::new(),
391            item_extent: None,
392            internal_controller: None,
393            last_reported_leading_item: 0,
394        }
395    }
396}
397
398/// Dart's `_CarouselViewState`.
399pub struct CarouselViewState {
400    state: StateData<CarouselView>,
401    item_extent: Option<f64>,
402    internal_controller: Option<Ref<CarouselController>>,
403    last_reported_leading_item: i32,
404}
405
406impl CarouselViewState {
407    fn flex_weights(self: Handle<Self>, app: &App) -> Option<Vec<i32>> {
408        self.widget(app).flex_weights.clone()
409    }
410
411    fn consume_max_weight(self: Handle<Self>, app: &App) -> bool {
412        self.widget(app).consume_max_weight
413    }
414
415    /// Dart's `widget.controller ?? _internalController!`.
416    fn controller(self: Handle<Self>, app: &App) -> Handle<CarouselController> {
417        match self.widget(app).controller.as_ref() {
418            Some(controller) => controller.handle(),
419            None => app
420                .get(self)
421                .internal_controller
422                .handle()
423                .expect("an internal controller exists while the widget has none"),
424        }
425    }
426
427    fn carousel_position(self: Handle<Self>, app: &App) -> Handle<CarouselPosition> {
428        self.controller(app).carousel_position(app)
429    }
430
431    fn handle_scroll(self: Handle<Self>, app: &mut App) {
432        let Some(on_index_changed) = self.widget(app).on_index_changed.clone() else {
433            return;
434        };
435
436        let current_leading_index = self.carousel_position(app).leading_item(app);
437
438        if current_leading_index != app.get(self).last_reported_leading_item {
439            app.get_mut(self).last_reported_leading_item = current_leading_index;
440            on_index_changed(app, current_leading_index);
441        }
442    }
443
444    // For weighted carousel, the initialItem means the index of the item to occupy the first
445    // maximum weight in flexWeights. To get the initial leading item, it should be initialItem -
446    // index of the first max weight in flexWeights. So it might be negative when initialItem
447    // value is small but the first max weight index is large. In that case, the initial leading
448    // item should be 0.
449    fn get_initial_leading_item(self: Handle<Self>, app: &App) -> i32 {
450        let initial_item = self.controller(app).initial_item(app);
451        if let Some(flex_weights) = self.flex_weights(app) {
452            let first_max_weight_index = index_of_max(&flex_weights);
453            return (initial_item - first_max_weight_index).max(0);
454        }
455        initial_item
456    }
457
458    #[allow(deprecated)] // Dart's `withOpacity`.
459    fn build_carousel_item(self: Handle<Self>, app: &mut App, mut index: i32) -> WidgetRef {
460        let widget = self.widget(app);
461        // For infinite scrolling, wrap the index to the actual children range.
462        if widget.infinite && !widget.children.is_empty() {
463            index %= widget.children.len() as i32;
464        }
465        let context = self.context(app);
466        let carousel_theme = CarouselViewTheme::of(app, context);
467        let color_scheme = Theme::of(app, context).color_scheme.clone();
468        let widget = self.widget(app);
469        let effective_padding = widget
470            .padding
471            .or(carousel_theme.padding)
472            .unwrap_or(EdgeInsets::all(4.0));
473        let effective_background_color = widget
474            .background_color
475            .or(carousel_theme.background_color)
476            .unwrap_or(color_scheme.surface());
477        let effective_elevation = widget.elevation.or(carousel_theme.elevation).unwrap_or(0.0);
478        let effective_shape: ShapeBorderRef = widget
479            .shape
480            .clone()
481            .or_else(|| carousel_theme.shape.clone().map(ShapeBorderRef::from))
482            .unwrap_or_else(|| {
483                ShapeBorderRef::new(RoundedRectangleBorder::new(
484                    waft_painting::BorderSide::NONE,
485                    BorderRadiusGeometry::circular(28.0),
486                ))
487            });
488        let effective_item_clip_behavior = widget
489            .item_clip_behavior
490            .or(carousel_theme.item_clip_behavior)
491            .unwrap_or(Clip::AntiAlias);
492        let effective_overlay_color = widget
493            .overlay_color
494            .clone()
495            .or_else(|| carousel_theme.overlay_color.clone())
496            .unwrap_or_else(|| {
497                let on_surface = color_scheme.on_surface();
498                <dyn WidgetStateProperty<Option<Color>>>::resolve_with(move |states| {
499                    if states.contains(&WidgetState::Pressed) {
500                        return Some(on_surface.with_opacity(0.1));
501                    }
502                    if states.contains(&WidgetState::Hovered) {
503                        return Some(on_surface.with_opacity(0.08));
504                    }
505                    if states.contains(&WidgetState::Focused) {
506                        return Some(on_surface.with_opacity(0.1));
507                    }
508                    None
509                })
510            });
511        let enable_splash = widget.enable_splash;
512        let on_tap = widget.on_tap.clone();
513        let mut contents = widget.children[index as usize].clone();
514
515        if enable_splash {
516            let on_tap = on_tap.clone();
517            let ink_well = InkWell::new()
518                .overlay_color(effective_overlay_color)
519                .on_tap(Listener::new(move |app: &mut App| {
520                    if let Some(on_tap) = &on_tap {
521                        on_tap(app, index);
522                    }
523                }));
524            contents = Stack::new()
525                .fit(StackFit::Expand)
526                .children(vec![
527                    contents,
528                    Material::new()
529                        .color(Colors::TRANSPARENT)
530                        .child(ink_well)
531                        .into_widget(),
532                ])
533                .into_widget();
534        } else if let Some(on_tap) = on_tap {
535            contents = GestureDetector::new()
536                .on_tap(Listener::new(move |app: &mut App| on_tap(app, index)))
537                .child(contents)
538                .into_widget();
539        }
540
541        Padding::new(effective_padding)
542            .child(
543                Material::new()
544                    .clip_behavior(effective_item_clip_behavior)
545                    .color(effective_background_color)
546                    .elevation(effective_elevation)
547                    .shape(effective_shape)
548                    .child(contents),
549            )
550            .into_widget()
551    }
552
553    fn build_sliver_carousel(self: Handle<Self>, app: &mut App) -> WidgetRef {
554        let widget = self.widget(app);
555        let infinite = widget.infinite;
556        let item_builder = widget.item_builder.clone();
557        let item_count = widget.item_count;
558        let children_len = widget.children.len() as i32;
559        let shrink_extent = widget.shrink_extent;
560        // Determine the child count and builder based on whether we're using lazy loading
561        let child_count = if infinite {
562            None
563        } else if item_builder.is_some() {
564            item_count
565        } else {
566            Some(children_len)
567        };
568
569        let effective_builder: NullableIndexedWidgetBuilder = match item_builder {
570            Some(item_builder) => match item_count {
571                Some(item_count) if infinite && item_count > 0 => {
572                    Rc::new(move |app: &mut App, context: BuildContext, index: i32| {
573                        item_builder(app, context, index % item_count)
574                    })
575                }
576                _ => item_builder,
577            },
578            None => Rc::new(move |app: &mut App, _context: BuildContext, index: i32| {
579                Some(self.build_carousel_item(app, index))
580            }),
581        };
582        let mut delegate = SliverChildBuilderDelegate::from_builder(effective_builder);
583        if let Some(child_count) = child_count {
584            delegate = delegate.child_count(child_count);
585        }
586        let delegate = delegate.into_delegate();
587
588        if let Some(item_extent) = app.get(self).item_extent {
589            return SliverFixedExtentCarousel {
590                key: None,
591                delegate,
592                item_extent,
593                min_extent: shrink_extent,
594                infinite,
595            }
596            .into_widget();
597        }
598
599        let flex_weights = self.flex_weights(app);
600        debug_assert!(
601            flex_weights
602                .as_ref()
603                .is_some_and(|weights| weights.iter().all(|weight| *weight > 0)),
604            "flexWeights is null or it contains non-positive integers"
605        );
606        SliverWeightedCarousel {
607            key: None,
608            delegate,
609            consume_max_weight: self.consume_max_weight(app),
610            shrink_extent,
611            weights: Rc::new(flex_weights.expect("asserted above")),
612            infinite,
613        }
614        .into_widget()
615    }
616}
617
618/// The index of the first greatest weight.
619fn index_of_max(weights: &[i32]) -> i32 {
620    let max_weight = weights.iter().max().expect("the weights are not empty");
621    weights
622        .iter()
623        .position(|weight| weight == max_weight)
624        .expect("the maximum is in the list") as i32
625}
626
627impl State for CarouselViewState {
628    type Widget = CarouselView;
629    waft_widgets::state_accessors!();
630
631    fn init_state(self: Handle<Self>, app: &mut App) {
632        let item_extent = self.widget(app).item_extent;
633        app.get_mut(self).item_extent = item_extent;
634        if self.widget(app).controller.is_none() {
635            let controller = CarouselController::new(app, 0);
636            app.get_mut(self).internal_controller = Some(controller);
637        }
638        let initial_leading_item = self.get_initial_leading_item(app);
639        app.get_mut(self).last_reported_leading_item = initial_leading_item;
640        let controller = self.controller(app);
641        controller.attach_state(app, self);
642        controller.add_listener(app, Listener::handle_method(self, Self::handle_scroll));
643    }
644
645    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &CarouselView) {
646        let widget = self.widget(app);
647        let new_controller = widget.controller.clone();
648        let controller_changed = widget.controller != old_widget.controller;
649        let flex_weights_changed = widget.flex_weights != old_widget.flex_weights;
650        let item_extent = widget.item_extent;
651        let item_extent_changed = widget.item_extent != old_widget.item_extent;
652        let consume_max_weight_changed = widget.consume_max_weight != old_widget.consume_max_weight;
653        if controller_changed {
654            if let Some(old_controller) = &old_widget.controller {
655                old_controller.handle().detach_state(app, self);
656            }
657            if let Some(new_controller) = new_controller {
658                if let Some(internal_controller) = app.get(self).internal_controller.handle() {
659                    internal_controller.detach_state(app, self);
660                }
661                app.get_mut(self).internal_controller = None;
662                new_controller.handle().attach_state(app, self);
663            } else {
664                // widget.controller == null && oldWidget.controller != null
665                debug_assert!(app.get(self).internal_controller.is_none());
666                let controller = CarouselController::new(app, 0);
667                app.get_mut(self).internal_controller = Some(controller);
668                self.controller(app).attach_state(app, self);
669            }
670        }
671        if flex_weights_changed {
672            let flex_weights = self.flex_weights(app);
673            self.carousel_position(app)
674                .set_flex_weights(app, flex_weights);
675        }
676        if item_extent_changed {
677            app.get_mut(self).item_extent = item_extent;
678            self.carousel_position(app)
679                .set_item_extent(app, item_extent);
680        }
681        if consume_max_weight_changed {
682            let consume_max_weight = self.consume_max_weight(app);
683            self.carousel_position(app)
684                .set_consume_max_weight(app, consume_max_weight);
685        }
686    }
687
688    fn dispose(self: Handle<Self>, app: &mut App) {
689        let controller = self.controller(app);
690        controller.remove_listener(app, &Listener::handle_method(self, Self::handle_scroll));
691        controller.detach_state(app, self);
692        if let Some(internal_controller) = app.get(self).internal_controller.handle() {
693            ScrollControllerLeaf::dispose(internal_controller, app);
694        }
695    }
696
697    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
698        let item_snapping = self.widget(app).item_snapping;
699        let physics: ScrollPhysicsRef = if item_snapping {
700            Rc::new(CarouselScrollPhysics::new())
701        } else {
702            ScrollConfiguration::of(app, context).get_scroll_physics(app, context)
703        };
704        let controller = match self.widget(app).controller.clone() {
705            Some(controller) => controller,
706            None => app
707                .get(self)
708                .internal_controller
709                .clone()
710                .expect("an internal controller exists while the widget has none"),
711        };
712
713        LayoutBuilder::new(move |app: &mut App, _context: BuildContext, constraints| {
714            let widget = self.widget(app);
715            let scroll_direction = widget.scroll_direction;
716            let reverse = widget.reverse;
717            let main_axis_extent = match scroll_direction {
718                Axis::Horizontal => constraints.constraints().max_width,
719                Axis::Vertical => constraints.constraints().max_height,
720            };
721
722            let item_extent = widget
723                .item_extent
724                .map(|item_extent| clamp_double(item_extent, 0.0, main_axis_extent));
725            app.get_mut(self).item_extent = item_extent;
726            waft_widgets::CustomScrollView::new()
727                .scroll_direction(scroll_direction)
728                .reverse(reverse)
729                .controller(controller.clone().into_erased())
730                .physics(Rc::clone(&physics))
731                .clip_behavior(Clip::AntiAlias)
732                .scroll_cache_extent(ScrollCacheExtent::Viewport(0.0))
733                .slivers(vec![self.build_sliver_carousel(app)])
734                .into_widget()
735        })
736        .into_widget()
737    }
738}
739
740// ---------------------------------------------------------------------------------------------
741// _SliverFixedExtentCarousel
742
743/// Dart's `_SliverFixedExtentCarousel`.
744struct SliverFixedExtentCarousel {
745    key: Option<KeyRef>,
746    delegate: SliverChildDelegateRef,
747    item_extent: f64,
748    min_extent: f64,
749    infinite: bool,
750}
751
752impl RenderObjectWidget for SliverFixedExtentCarousel {
753    type RenderObject = RenderSliverFixedExtentCarousel;
754
755    fn key(&self) -> Option<&KeyRef> {
756        self.key.as_ref()
757    }
758
759    fn create_render_object(
760        &self,
761        app: &mut App,
762        context: BuildContext,
763    ) -> waft_rendering::AnyRenderObject {
764        RenderSliverFixedExtentCarousel::new(
765            app,
766            child_manager_of::<SliverFixedExtentCarousel>(app, context),
767            self.min_extent,
768            self.item_extent,
769            self.infinite,
770        )
771        .as_object()
772    }
773
774    fn update_render_object(
775        &self,
776        app: &mut App,
777        _context: BuildContext,
778        render_object: RenderHandle<RenderSliverFixedExtentCarousel>,
779    ) {
780        render_object.set_max_extent(app, self.item_extent);
781        render_object.set_min_extent(app, self.min_extent);
782        render_object.set_infinite(app, self.infinite);
783    }
784}
785
786impl SliverWithKeepAliveWidget for SliverFixedExtentCarousel {}
787
788impl SliverMultiBoxAdaptorWidget for SliverFixedExtentCarousel {
789    fn delegate(&self) -> &SliverChildDelegateRef {
790        &self.delegate
791    }
792}
793
794impl Debug for SliverFixedExtentCarousel {
795    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
796        f.debug_struct("_SliverFixedExtentCarousel")
797            .field("item_extent", &self.item_extent)
798            .field("min_extent", &self.min_extent)
799            .field("infinite", &self.infinite)
800            .finish_non_exhaustive()
801    }
802}
803
804/// What `_RenderSliverFixedExtentCarousel` reads of its constraints, taken when the adaptor asks
805/// for the item extent builder.
806#[derive(Clone, Copy)]
807struct FixedCarouselExtents {
808    scroll_offset: f64,
809    remaining_paint_extent: f64,
810    max_extent: f64,
811    min_extent: f64,
812}
813
814impl FixedCarouselExtents {
815    fn of(
816        constraints: SliverConstraints,
817        max_extent: f64,
818        min_extent: f64,
819    ) -> FixedCarouselExtents {
820        FixedCarouselExtents {
821            scroll_offset: constraints.scroll_offset,
822            remaining_paint_extent: constraints.remaining_paint_extent,
823            max_extent,
824            min_extent,
825        }
826    }
827
828    // This implements the [itemExtentBuilder] callback.
829    fn build_item_extent(&self, index: i32) -> f64 {
830        if self.max_extent == 0.0 {
831            return self.max_extent;
832        }
833
834        let first_visible_index = (self.scroll_offset / self.max_extent).floor() as i32;
835
836        // Calculate how many items have been completely scroll off screen.
837        let offscreen_items = (self.scroll_offset / self.max_extent).floor();
838
839        // If an item is partially off screen and partially on screen,
840        // `constraints.scrollOffset` must be greater than
841        // `offscreenItems * maxExtent`, so the difference between these two is how
842        // much the current first visible item is off screen.
843        let offscreen_extent = self.scroll_offset - offscreen_items * self.max_extent;
844
845        // If there is not enough space to place the last visible item but the remaining
846        // space is larger than `minExtent`, the extent for last item should be at
847        // least the remaining extent to ensure a smooth size transition.
848        let effective_min_extent =
849            dart_modulo(self.remaining_paint_extent, self.max_extent).max(self.min_extent);
850
851        // Two special cases are the first and last visible items. Other items' extent
852        // should all return `maxExtent`.
853        if index == first_visible_index {
854            let effective_extent = self.max_extent - offscreen_extent;
855            return effective_extent.max(effective_min_extent);
856        }
857
858        let scroll_offset_for_last_index = self.scroll_offset + self.remaining_paint_extent;
859        if index == self.max_child_index_for_scroll_offset(scroll_offset_for_last_index) {
860            return clamp_double(
861                scroll_offset_for_last_index - self.max_extent * f64::from(index),
862                effective_min_extent,
863                self.max_extent,
864            );
865        }
866
867        self.max_extent
868    }
869
870    fn index_to_layout_offset(&self, index: i32) -> f64 {
871        if self.max_extent == 0.0 {
872            return self.max_extent;
873        }
874
875        let first_visible_index = (self.scroll_offset / self.max_extent).floor() as i32;
876
877        // If there is not enough space to place the last visible item but the remaining
878        // space is larger than `minExtent`, the extent for last item should be at
879        // least the remaining extent to make sure a smooth size transition.
880        let effective_min_extent =
881            dart_modulo(self.remaining_paint_extent, self.max_extent).max(self.min_extent);
882        if index == first_visible_index {
883            let first_visible_item_extent = self.build_item_extent(index);
884
885            // If the first item is collapsed to be less than `effectiveMinExtent`,
886            // then it should stop changing its size and should start to scroll off screen.
887            if first_visible_item_extent <= effective_min_extent {
888                return self.max_extent * f64::from(index) - effective_min_extent + self.max_extent;
889            }
890            return self.scroll_offset;
891        }
892        self.max_extent * f64::from(index)
893    }
894
895    fn min_child_index_for_scroll_offset(&self, scroll_offset: f64) -> i32 {
896        if self.max_extent == 0.0 {
897            return 0;
898        }
899
900        let first_visible_index = (scroll_offset / self.max_extent).floor() as i32;
901        first_visible_index.max(0)
902    }
903
904    fn max_child_index_for_scroll_offset(&self, scroll_offset: f64) -> i32 {
905        if self.max_extent > 0.0 {
906            let actual = scroll_offset / self.max_extent - 1.0;
907            let round = actual.round();
908            if (actual * self.max_extent - round * self.max_extent).abs()
909                < PRECISION_ERROR_TOLERANCE
910            {
911                return (round as i32).max(0);
912            }
913            return (actual.ceil() as i32).max(0);
914        }
915        0
916    }
917}
918
919/// Dart's `%` on doubles, the Euclidean modulo: never negative.
920fn dart_modulo(dividend: f64, divisor: f64) -> f64 {
921    let result = dividend.rem_euclid(divisor);
922    if result == 0.0 { 0.0 } else { result }
923}
924
925/// Dart's `_RenderSliverFixedExtentCarousel`.
926struct RenderSliverFixedExtentCarousel {
927    render_object: RenderObjectData,
928    render_sliver: RenderSliverData,
929    container: ContainerRenderObjectData<AnyRenderBox>,
930    adaptor: RenderSliverMultiBoxAdaptorData,
931    fixed_extent: RenderSliverFixedExtentBoxAdaptorData,
932    max_extent: f64,
933    min_extent: f64,
934    infinite: bool,
935}
936
937impl RenderSliverFixedExtentCarousel {
938    fn new(
939        app: &mut App,
940        child_manager: Rc<dyn RenderSliverBoxChildManager>,
941        min_extent: f64,
942        max_extent: f64,
943        infinite: bool,
944    ) -> RenderHandle<RenderSliverFixedExtentCarousel> {
945        RenderHandle::new_sliver(
946            app,
947            RenderSliverFixedExtentCarousel {
948                render_object: RenderObjectData::new(),
949                render_sliver: RenderSliverData::new(),
950                container: ContainerRenderObjectData::new(),
951                adaptor: RenderSliverMultiBoxAdaptorData::new(child_manager),
952                fixed_extent: RenderSliverFixedExtentBoxAdaptorData::new(),
953                max_extent,
954                min_extent,
955                infinite,
956            },
957        )
958    }
959
960    fn set_max_extent(self: RenderHandle<Self>, app: &mut App, value: f64) {
961        if self.get(app).max_extent == value {
962            return;
963        }
964        self.get_mut(app).max_extent = value;
965        self.mark_needs_layout(app);
966    }
967
968    fn set_min_extent(self: RenderHandle<Self>, app: &mut App, value: f64) {
969        if self.get(app).min_extent == value {
970            return;
971        }
972        self.get_mut(app).min_extent = value;
973        self.mark_needs_layout(app);
974    }
975
976    fn set_infinite(self: RenderHandle<Self>, app: &mut App, value: bool) {
977        if self.get(app).infinite == value {
978            return;
979        }
980        self.get_mut(app).infinite = value;
981        self.mark_needs_layout(app);
982    }
983
984    fn extents(self: RenderHandle<Self>, app: &App) -> FixedCarouselExtents {
985        let this = self.get(app);
986        FixedCarouselExtents::of(self.constraints(app), this.max_extent, this.min_extent)
987    }
988}
989
990impl RenderSliverFixedExtentBoxAdaptor for RenderSliverFixedExtentCarousel {
991    render_sliver_fixed_extent_accessors!();
992
993    fn item_extent(self: RenderHandle<Self>, _app: &App) -> Option<f64> {
994        None
995    }
996
997    fn item_extent_builder(self: RenderHandle<Self>, app: &App) -> Option<ItemExtentBuilder> {
998        let extents = self.extents(app);
999        Some(Rc::new(
1000            move |index: i32, _dimensions: SliverLayoutDimensions| {
1001                Some(extents.build_item_extent(index))
1002            },
1003        ))
1004    }
1005
1006    fn index_to_layout_offset(self: RenderHandle<Self>, app: &App, index: i32) -> f64 {
1007        self.extents(app).index_to_layout_offset(index)
1008    }
1009
1010    fn get_min_child_index_for_scroll_offset(
1011        self: RenderHandle<Self>,
1012        app: &App,
1013        scroll_offset: f64,
1014    ) -> i32 {
1015        self.extents(app)
1016            .min_child_index_for_scroll_offset(scroll_offset)
1017    }
1018
1019    fn get_max_child_index_for_scroll_offset(
1020        self: RenderHandle<Self>,
1021        app: &App,
1022        scroll_offset: f64,
1023    ) -> i32 {
1024        self.extents(app)
1025            .max_child_index_for_scroll_offset(scroll_offset)
1026    }
1027}
1028
1029fixed_extent_box_adaptor_leaf!(RenderSliverFixedExtentCarousel);
1030
1031// ---------------------------------------------------------------------------------------------
1032// _SliverWeightedCarousel
1033
1034/// Dart's `_SliverWeightedCarousel`.
1035struct SliverWeightedCarousel {
1036    key: Option<KeyRef>,
1037    delegate: SliverChildDelegateRef,
1038    // Determine whether extra scroll offset should be calculate so that every
1039    // item have a chance to scroll to the maximum extent.
1040    //
1041    // This is useful when the leading/trailing items have smaller weights, such
1042    // as [1, 7], and [3, 2, 1].
1043    consume_max_weight: bool,
1044    // The starting extent for items when they gradually show on/off screen.
1045    //
1046    // This is useful to avoid a hairline shape. This value should also smaller
1047    // than the last item extent to make sure a smooth transition. So in calculation,
1048    // this is limited to [0, weight for the last visible item].
1049    shrink_extent: f64,
1050    // The layout arrangement.
1051    //
1052    // When items are laying out, each item will be arranged based on the order of
1053    // the weights and the extent is based on the corresponding weight out of the
1054    // sum of weights. The length of weights means how many items we can put in the
1055    // view at a time.
1056    weights: Rc<Vec<i32>>,
1057    // Whether the carousel should loop infinitely.
1058    infinite: bool,
1059}
1060
1061impl RenderObjectWidget for SliverWeightedCarousel {
1062    type RenderObject = RenderSliverWeightedCarousel;
1063
1064    fn key(&self) -> Option<&KeyRef> {
1065        self.key.as_ref()
1066    }
1067
1068    fn create_render_object(
1069        &self,
1070        app: &mut App,
1071        context: BuildContext,
1072    ) -> waft_rendering::AnyRenderObject {
1073        RenderSliverWeightedCarousel::new(
1074            app,
1075            child_manager_of::<SliverWeightedCarousel>(app, context),
1076            self.consume_max_weight,
1077            self.shrink_extent,
1078            Rc::clone(&self.weights),
1079            self.infinite,
1080        )
1081        .as_object()
1082    }
1083
1084    fn update_render_object(
1085        &self,
1086        app: &mut App,
1087        _context: BuildContext,
1088        render_object: RenderHandle<RenderSliverWeightedCarousel>,
1089    ) {
1090        render_object.set_consume_max_weight(app, self.consume_max_weight);
1091        render_object.set_shrink_extent(app, self.shrink_extent);
1092        render_object.set_weights(app, Rc::clone(&self.weights));
1093        render_object.set_infinite(app, self.infinite);
1094    }
1095}
1096
1097impl SliverWithKeepAliveWidget for SliverWeightedCarousel {}
1098
1099impl SliverMultiBoxAdaptorWidget for SliverWeightedCarousel {
1100    fn delegate(&self) -> &SliverChildDelegateRef {
1101        &self.delegate
1102    }
1103}
1104
1105impl Debug for SliverWeightedCarousel {
1106    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1107        f.debug_struct("_SliverWeightedCarousel")
1108            .field("weights", &self.weights)
1109            .field("consume_max_weight", &self.consume_max_weight)
1110            .field("shrink_extent", &self.shrink_extent)
1111            .field("infinite", &self.infinite)
1112            .finish_non_exhaustive()
1113    }
1114}
1115
1116/// What `_RenderSliverWeightedCarousel` reads of its constraints and fields, taken when the
1117/// adaptor asks for the item extent builder.
1118#[derive(Clone)]
1119struct WeightedCarouselExtents {
1120    scroll_offset: f64,
1121    remaining_paint_extent: f64,
1122    viewport_main_axis_extent: f64,
1123    consume_max_weight: bool,
1124    shrink_extent: f64,
1125    weights: Rc<Vec<i32>>,
1126    infinite: bool,
1127    child_count: Option<i32>,
1128}
1129
1130impl WeightedCarouselExtents {
1131    fn max_weight(&self) -> i32 {
1132        *self
1133            .weights
1134            .iter()
1135            .max()
1136            .expect("the weights are not empty")
1137    }
1138
1139    fn min_weight(&self) -> i32 {
1140        *self
1141            .weights
1142            .iter()
1143            .min()
1144            .expect("the weights are not empty")
1145    }
1146
1147    // To ge the extent unit based on the viewport extent and the sum of weights.
1148    fn extent_unit(&self) -> f64 {
1149        self.viewport_main_axis_extent / f64::from(self.weights.iter().sum::<i32>())
1150    }
1151
1152    fn first_child_extent(&self) -> f64 {
1153        f64::from(self.weights[0]) * self.extent_unit()
1154    }
1155
1156    fn max_child_extent(&self) -> f64 {
1157        f64::from(self.max_weight()) * self.extent_unit()
1158    }
1159
1160    fn min_child_extent(&self) -> f64 {
1161        f64::from(self.min_weight()) * self.extent_unit()
1162    }
1163
1164    // The shrink extent for first and last visible items should be no larger
1165    // than [minChildExtent] to ensure a smooth transition.
1166    fn effective_shrink_extent(&self) -> f64 {
1167        clamp_double(self.shrink_extent, 0.0, self.min_child_extent())
1168    }
1169
1170    // The scroll offset in whole first-child extents, rounded the way the position rounds items.
1171    fn scroll_in_first_children(&self) -> i32 {
1172        let actual = self.scroll_offset / self.first_child_extent();
1173        let round = actual.round();
1174        if (actual - round).abs() < PRECISION_ERROR_TOLERANCE {
1175            round as i32
1176        } else {
1177            actual.floor() as i32
1178        }
1179    }
1180
1181    // The index of the first visible item. The returned value can be negative when
1182    // the leading items with smaller weights need to be fully expanded. For example,
1183    // assuming a weights [1, 7, 1], when item 0 is expanding to the maximum size
1184    // (with weight 7), we leave some space before item 0 assuming there is another
1185    // item -1 as the first visible item.
1186    fn first_visible_item_index(&self) -> i32 {
1187        // If constraints.viewportMainAxisExtent is 0, firstChildExtent will be 0 and cause
1188        // division error.
1189        if self.viewport_main_axis_extent == 0.0 {
1190            return 0;
1191        }
1192        let max_weight = self.max_weight();
1193        let mut smaller_weight_count = 0;
1194        for weight in self.weights.iter() {
1195            if *weight == max_weight {
1196                break;
1197            }
1198            smaller_weight_count += 1;
1199        }
1200
1201        let index = self.scroll_in_first_children();
1202        if self.consume_max_weight {
1203            index - smaller_weight_count
1204        } else {
1205            index
1206        }
1207    }
1208
1209    // This value indicates the scrolling progress of items following the first
1210    // item. It informs them how much the first item has moved off-screen,
1211    // enabling them to adjust their sizes (grow or shrink) accordingly.
1212    fn first_visible_item_offscreen_extent(&self) -> f64 {
1213        // If constraints.viewportMainAxisExtent is 0, firstChildExtent will be 0 and cause
1214        // division error.
1215        if self.viewport_main_axis_extent == 0.0 {
1216            return 0.0;
1217        }
1218        self.scroll_offset - f64::from(self.scroll_in_first_children()) * self.first_child_extent()
1219    }
1220
1221    // Given the off-screen extent for the first visible item, we can know the
1222    // on-screen extent for the first visible item.
1223    fn distance_to_leading_edge(&self) -> f64 {
1224        self.first_child_extent() - self.first_visible_item_offscreen_extent()
1225    }
1226
1227    // This is to implement the itemExtentBuilder callback to return each item extent
1228    // while scrolling.
1229    //
1230    // The given `index` is compared with `_firstVisibleItemIndex` to know how
1231    // many items are placed before the current one in the view.
1232    fn build_item_extent(&self, index: i32) -> f64 {
1233        // If constraints.viewportMainAxisExtent is 0, firstChildExtent will be 0 and cause
1234        // division error.
1235        if self.viewport_main_axis_extent == 0.0 {
1236            return 0.0;
1237        }
1238
1239        let first_visible_item_index = self.first_visible_item_index();
1240        if index == first_visible_item_index {
1241            return self
1242                .distance_to_leading_edge()
1243                .max(self.effective_shrink_extent());
1244        }
1245        // Calculate the extents of items located within the range defined by the
1246        // weights array relative to the first visible item. This allows us to
1247        // precisely determine each item's extent based on its initial extent
1248        // (calculated from the weights) and the scrolling progress (the off-screen
1249        // portion of the first item).
1250        if index > first_visible_item_index
1251            && index - first_visible_item_index < self.weights.len() as i32
1252        {
1253            debug_assert!(index - first_visible_item_index < self.weights.len() as i32);
1254            let curr_index_on_weight_list = (index - first_visible_item_index) as usize;
1255            let curr_weight = self.weights[curr_index_on_weight_list];
1256            let initial_extent = self.extent_unit() * f64::from(curr_weight); // initial extent
1257            let progress = self.first_visible_item_offscreen_extent() / self.first_child_extent();
1258
1259            let prev_weight = self.weights[curr_index_on_weight_list - 1];
1260            let final_increase =
1261                f64::from(prev_weight - curr_weight) / f64::from(self.max_weight());
1262            return initial_extent + final_increase * progress * self.max_child_extent();
1263        }
1264        // Calculate the extents of items located beyond the range defined by the
1265        // weights array relative to the first visible item. During scrolling transition,
1266        // it is possible that the number of visible items is larger than the length
1267        // of `weights`. The extra item extent should be calculated here to fill
1268        // the remaining space.
1269        if index > first_visible_item_index
1270            && index - first_visible_item_index + 1 > self.weights.len() as i32
1271        {
1272            let mut visible_items_total_extent = self.distance_to_leading_edge();
1273            for i in (first_visible_item_index + 1)..index {
1274                visible_items_total_extent += self.build_item_extent(i);
1275            }
1276            return (self.remaining_paint_extent - visible_items_total_extent)
1277                .max(self.effective_shrink_extent());
1278        }
1279        self.min_child_extent().max(self.effective_shrink_extent())
1280    }
1281
1282    // Given an index, this method returns the layout offset for the item. The `index`
1283    // is firstly compared to `_firstVisibleItemIndex` and compute the distance
1284    // between them, then compute all the current extents for items that are located
1285    // in front.
1286    fn index_to_layout_offset(&self, index: i32) -> f64 {
1287        let first_visible_item_index = self.first_visible_item_index();
1288        if index == first_visible_item_index {
1289            if self.distance_to_leading_edge() <= self.effective_shrink_extent() {
1290                return self.scroll_offset - self.effective_shrink_extent()
1291                    + self.distance_to_leading_edge();
1292            }
1293            return self.scroll_offset;
1294        }
1295        let mut visible_items_total_extent = self.distance_to_leading_edge();
1296        for i in (first_visible_item_index + 1)..index {
1297            visible_items_total_extent += self.build_item_extent(i);
1298        }
1299        self.scroll_offset + visible_items_total_extent
1300    }
1301
1302    fn max_child_index_for_scroll_offset(&self) -> i32 {
1303        let child_count = self.child_count;
1304
1305        // For infinite scrolling, calculate how many items fit in the viewport
1306        if self.infinite && child_count.is_none() {
1307            let mut visible_items_total_extent = self.distance_to_leading_edge();
1308            let mut index = self.first_visible_item_index() + 1;
1309            // Calculate upper bound based on viewport extent and minimum possible item extent.
1310            // In worst case, all items would be at minimum extent i.e. minChildExtent.
1311            let safe_min_extent = self.min_child_extent().max(1.0);
1312            let estimated_upper_bound = self.first_visible_item_index()
1313                + (self.viewport_main_axis_extent / safe_min_extent).ceil() as i32;
1314            while visible_items_total_extent < self.viewport_main_axis_extent
1315                && index < estimated_upper_bound
1316            {
1317                visible_items_total_extent += self.build_item_extent(index);
1318                if visible_items_total_extent >= self.viewport_main_axis_extent {
1319                    return index;
1320                }
1321                index += 1;
1322            }
1323            return index;
1324        }
1325
1326        if let Some(child_count) = child_count {
1327            let mut visible_items_total_extent = self.distance_to_leading_edge();
1328            for i in (self.first_visible_item_index() + 1)..child_count {
1329                visible_items_total_extent += self.build_item_extent(i);
1330                if visible_items_total_extent >= self.viewport_main_axis_extent {
1331                    return i;
1332                }
1333            }
1334        }
1335        child_count.unwrap_or(0)
1336    }
1337}
1338
1339/// Dart's `_RenderSliverWeightedCarousel`: a sliver that places its box children in a linear
1340/// array and constrains them to have the corresponding weight which is determined by its
1341/// weights.
1342struct RenderSliverWeightedCarousel {
1343    render_object: RenderObjectData,
1344    render_sliver: RenderSliverData,
1345    container: ContainerRenderObjectData<AnyRenderBox>,
1346    adaptor: RenderSliverMultiBoxAdaptorData,
1347    fixed_extent: RenderSliverFixedExtentBoxAdaptorData,
1348    consume_max_weight: bool,
1349    shrink_extent: f64,
1350    weights: Rc<Vec<i32>>,
1351    infinite: bool,
1352}
1353
1354impl RenderSliverWeightedCarousel {
1355    fn new(
1356        app: &mut App,
1357        child_manager: Rc<dyn RenderSliverBoxChildManager>,
1358        consume_max_weight: bool,
1359        shrink_extent: f64,
1360        weights: Rc<Vec<i32>>,
1361        infinite: bool,
1362    ) -> RenderHandle<RenderSliverWeightedCarousel> {
1363        RenderHandle::new_sliver(
1364            app,
1365            RenderSliverWeightedCarousel {
1366                render_object: RenderObjectData::new(),
1367                render_sliver: RenderSliverData::new(),
1368                container: ContainerRenderObjectData::new(),
1369                adaptor: RenderSliverMultiBoxAdaptorData::new(child_manager),
1370                fixed_extent: RenderSliverFixedExtentBoxAdaptorData::new(),
1371                consume_max_weight,
1372                shrink_extent,
1373                weights,
1374                infinite,
1375            },
1376        )
1377    }
1378
1379    fn set_consume_max_weight(self: RenderHandle<Self>, app: &mut App, value: bool) {
1380        if self.get(app).consume_max_weight == value {
1381            return;
1382        }
1383        self.get_mut(app).consume_max_weight = value;
1384        self.mark_needs_layout(app);
1385    }
1386
1387    fn set_shrink_extent(self: RenderHandle<Self>, app: &mut App, value: f64) {
1388        if self.get(app).shrink_extent == value {
1389            return;
1390        }
1391        self.get_mut(app).shrink_extent = value;
1392        self.mark_needs_layout(app);
1393    }
1394
1395    fn set_weights(self: RenderHandle<Self>, app: &mut App, value: Rc<Vec<i32>>) {
1396        if *self.get(app).weights == *value {
1397            return;
1398        }
1399        self.get_mut(app).weights = value;
1400        self.mark_needs_layout(app);
1401    }
1402
1403    fn set_infinite(self: RenderHandle<Self>, app: &mut App, value: bool) {
1404        if self.get(app).infinite == value {
1405            return;
1406        }
1407        self.get_mut(app).infinite = value;
1408        self.mark_needs_layout(app);
1409    }
1410
1411    fn extents(self: RenderHandle<Self>, app: &App) -> WeightedCarouselExtents {
1412        let this = self.get(app);
1413        let constraints = self.constraints(app);
1414        WeightedCarouselExtents {
1415            scroll_offset: constraints.scroll_offset,
1416            remaining_paint_extent: constraints.remaining_paint_extent,
1417            viewport_main_axis_extent: constraints.viewport_main_axis_extent,
1418            consume_max_weight: this.consume_max_weight,
1419            shrink_extent: this.shrink_extent,
1420            weights: Rc::clone(&this.weights),
1421            infinite: this.infinite,
1422            child_count: self.child_manager(app).estimated_child_count(app),
1423        }
1424    }
1425}
1426
1427impl RenderSliverFixedExtentBoxAdaptor for RenderSliverWeightedCarousel {
1428    render_sliver_fixed_extent_accessors!();
1429
1430    fn item_extent(self: RenderHandle<Self>, _app: &App) -> Option<f64> {
1431        None
1432    }
1433
1434    fn item_extent_builder(self: RenderHandle<Self>, app: &App) -> Option<ItemExtentBuilder> {
1435        let extents = self.extents(app);
1436        Some(Rc::new(
1437            move |index: i32, _dimensions: SliverLayoutDimensions| {
1438                Some(extents.build_item_extent(index))
1439            },
1440        ))
1441    }
1442
1443    fn index_to_layout_offset(self: RenderHandle<Self>, app: &App, index: i32) -> f64 {
1444        self.extents(app).index_to_layout_offset(index)
1445    }
1446
1447    fn get_min_child_index_for_scroll_offset(
1448        self: RenderHandle<Self>,
1449        app: &App,
1450        _scroll_offset: f64,
1451    ) -> i32 {
1452        self.extents(app).first_visible_item_index().max(0)
1453    }
1454
1455    fn get_max_child_index_for_scroll_offset(
1456        self: RenderHandle<Self>,
1457        app: &App,
1458        _scroll_offset: f64,
1459    ) -> i32 {
1460        self.extents(app).max_child_index_for_scroll_offset()
1461    }
1462
1463    fn compute_max_scroll_offset(
1464        self: RenderHandle<Self>,
1465        app: &mut App,
1466        _constraints: SliverConstraints,
1467    ) -> f64 {
1468        if self.get(app).infinite {
1469            return f64::INFINITY;
1470        }
1471        let child_count = self.child_manager(app).child_count(app);
1472        f64::from(child_count) * self.extents(app).max_child_extent()
1473    }
1474
1475    // This method is mostly the same as its parent class [RenderSliverFixedExtentList].
1476    // The difference is when we allow some space before the leading items or after
1477    // the trailing items with smaller weights, we leave extra scroll offset.
1478    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
1479        let constraints = self.constraints(app);
1480        let child_manager = self.child_manager(app);
1481        child_manager.did_start_layout(app);
1482        child_manager.set_did_underflow(app, false);
1483
1484        let scroll_offset = constraints.scroll_offset + constraints.cache_origin;
1485        debug_assert!(scroll_offset >= 0.0);
1486        let remaining_extent = constraints.remaining_cache_extent;
1487        debug_assert!(remaining_extent >= 0.0);
1488        let target_end_scroll_offset = scroll_offset + remaining_extent;
1489
1490        let first_index = self.get_min_child_index_for_scroll_offset(app, scroll_offset);
1491        let target_last_index = target_end_scroll_offset
1492            .is_finite()
1493            .then(|| self.get_max_child_index_for_scroll_offset(app, target_end_scroll_offset));
1494
1495        if self.first_child(app).is_some() {
1496            let leading_garbage = self.calculate_leading_garbage(app, first_index);
1497            let trailing_garbage = match target_last_index {
1498                Some(last_index) => self.calculate_trailing_garbage(app, last_index),
1499                None => 0,
1500            };
1501            self.collect_garbage(app, leading_garbage, trailing_garbage);
1502        } else {
1503            self.collect_garbage(app, 0, 0);
1504        }
1505
1506        if self.first_child(app).is_none() {
1507            let layout_offset = self.index_to_layout_offset(app, first_index);
1508            if !self.add_initial_child(app, first_index, layout_offset) {
1509                // There are either no children, or we are past the end of all our children.
1510                let max = if first_index <= 0 {
1511                    0.0
1512                } else {
1513                    self.compute_max_scroll_offset(app, constraints)
1514                };
1515                self.set_geometry(
1516                    app,
1517                    SliverGeometry::builder()
1518                        .scroll_extent(max)
1519                        .max_paint_extent(max)
1520                        .build(),
1521                );
1522                child_manager.did_finish_layout(app);
1523                return;
1524            }
1525        }
1526
1527        let mut trailing_child_with_layout: Option<AnyRenderBox> = None;
1528
1529        let first_child = self.first_child(app).expect("added above");
1530        let mut index = self.index_of(app, first_child) - 1;
1531        while index >= first_index {
1532            let child_constraints = self.child_constraints(app, index);
1533            let Some(child) = self.insert_and_layout_leading_child(app, child_constraints, false)
1534            else {
1535                // Items before the previously first child are no longer present. Reset the
1536                // scroll offset to offset all items prior and up to the missing item. Let the
1537                // parent re-lay-out everything.
1538                let correction = self.index_to_layout_offset(app, index);
1539                self.set_geometry(
1540                    app,
1541                    SliverGeometry::builder()
1542                        .scroll_offset_correction(correction)
1543                        .build(),
1544                );
1545                return;
1546            };
1547            let layout_offset = self.index_to_layout_offset(app, index);
1548            let child_parent_data = child
1549                .as_object()
1550                .parent_data_of_mut::<SliverMultiBoxAdaptorParentData>(app);
1551            child_parent_data.set_layout_offset(Some(layout_offset));
1552            debug_assert_eq!(child_parent_data.index, Some(index));
1553            trailing_child_with_layout.get_or_insert(child);
1554            index -= 1;
1555        }
1556
1557        if trailing_child_with_layout.is_none() {
1558            let first_child = self.first_child(app).expect("the child list is not empty");
1559            let child_constraints = self.child_constraints(app, self.index_of(app, first_child));
1560            first_child.layout(app, child_constraints, false);
1561            let layout_offset = self.index_to_layout_offset(app, first_index);
1562            first_child
1563                .as_object()
1564                .parent_data_of_mut::<SliverMultiBoxAdaptorParentData>(app)
1565                .set_layout_offset(Some(layout_offset));
1566            trailing_child_with_layout = Some(first_child);
1567        }
1568
1569        // From the last item to the firstly encountered max item
1570        let extents = self.extents(app);
1571        let mut extra_layout_offset = 0.0;
1572        if extents.consume_max_weight {
1573            let max_weight = extents.max_weight();
1574            for weight in extents.weights.iter().rev() {
1575                if *weight == max_weight {
1576                    break;
1577                }
1578                extra_layout_offset += f64::from(*weight) * extents.extent_unit();
1579            }
1580        }
1581
1582        let mut estimated_max_scroll_offset = f64::INFINITY;
1583        // Layout visible items after the first visible item.
1584        let mut index = self.index_of(app, trailing_child_with_layout.expect("set above")) + 1;
1585        while target_last_index.is_none_or(|last_index| index <= last_index) {
1586            let after = trailing_child_with_layout.expect("set above");
1587            let mut child = self.child_after(app, after);
1588            if child.is_none_or(|current| self.index_of(app, current) != index) {
1589                let child_constraints = self.child_constraints(app, index);
1590                child = self.insert_and_layout_child(app, child_constraints, Some(after), false);
1591                if child.is_none() {
1592                    // We have run out of children.
1593                    estimated_max_scroll_offset =
1594                        self.index_to_layout_offset(app, index) + extra_layout_offset;
1595                    break;
1596                }
1597            } else {
1598                let child_constraints = self.child_constraints(app, index);
1599                child
1600                    .expect("checked")
1601                    .layout(app, child_constraints, false);
1602            }
1603            let child = child.expect("set above");
1604            trailing_child_with_layout = Some(child);
1605            debug_assert_eq!(
1606                child
1607                    .as_object()
1608                    .parent_data_of::<SliverMultiBoxAdaptorParentData>(app)
1609                    .index,
1610                Some(index)
1611            );
1612            let layout_offset = self.index_to_layout_offset(app, index);
1613            child
1614                .as_object()
1615                .parent_data_of_mut::<SliverMultiBoxAdaptorParentData>(app)
1616                .set_layout_offset(Some(layout_offset));
1617            index += 1;
1618        }
1619
1620        let last_child = self.last_child(app).expect("the child list is not empty");
1621        let last_index = self.index_of(app, last_child);
1622        let leading_scroll_offset = self.index_to_layout_offset(app, first_index);
1623        let infinite = self.get(app).infinite;
1624        let trailing_scroll_offset;
1625
1626        if !infinite && last_index + 1 == child_manager.child_count(app) {
1627            let mut trailing = self.index_to_layout_offset(app, last_index);
1628
1629            trailing += (f64::from(*extents.weights.last().expect("not empty"))
1630                * extents.extent_unit())
1631            .max(extents.build_item_extent(last_index));
1632            trailing += extra_layout_offset;
1633            estimated_max_scroll_offset = trailing;
1634            trailing_scroll_offset = trailing;
1635        } else {
1636            trailing_scroll_offset = self.index_to_layout_offset(app, last_index + 1);
1637        }
1638
1639        debug_assert!(self.debug_assert_child_list_is_non_empty_and_contiguous(app));
1640        debug_assert_eq!(
1641            self.index_of(app, self.first_child(app).expect("not empty")),
1642            first_index
1643        );
1644        debug_assert!(target_last_index.is_none_or(|target| last_index <= target));
1645
1646        estimated_max_scroll_offset =
1647            estimated_max_scroll_offset.min(self.estimate_max_scroll_offset(
1648                app,
1649                constraints,
1650                Some(first_index),
1651                Some(last_index),
1652                Some(leading_scroll_offset),
1653                Some(trailing_scroll_offset),
1654            ));
1655
1656        let from = if extents.consume_max_weight {
1657            0.0
1658        } else {
1659            leading_scroll_offset
1660        };
1661        let paint_extent =
1662            self.calculate_paint_offset(app, constraints, from, trailing_scroll_offset);
1663        let cache_extent =
1664            self.calculate_cache_offset(app, constraints, from, trailing_scroll_offset);
1665
1666        let target_end_scroll_offset_for_paint =
1667            constraints.scroll_offset + constraints.remaining_paint_extent;
1668        let target_last_index_for_paint =
1669            target_end_scroll_offset_for_paint.is_finite().then(|| {
1670                self.get_max_child_index_for_scroll_offset(app, target_end_scroll_offset_for_paint)
1671            });
1672
1673        self.set_geometry(
1674            app,
1675            SliverGeometry::builder()
1676                .scroll_extent(estimated_max_scroll_offset)
1677                .paint_extent(paint_extent)
1678                .cache_extent(cache_extent)
1679                .max_paint_extent(estimated_max_scroll_offset)
1680                // Conservative to avoid flickering away the clip during scroll.
1681                .has_visual_overflow(
1682                    target_last_index_for_paint.is_some_and(|target| last_index >= target)
1683                        || constraints.scroll_offset > 0.0,
1684                )
1685                .build(),
1686        );
1687
1688        // We may have started the layout while scrolled to the end, which would not expose a new
1689        // child.
1690        if estimated_max_scroll_offset == trailing_scroll_offset {
1691            child_manager.set_did_underflow(app, true);
1692        }
1693        child_manager.did_finish_layout(app);
1694    }
1695}
1696
1697fixed_extent_box_adaptor_leaf!(RenderSliverWeightedCarousel);
1698
1699// ---------------------------------------------------------------------------------------------
1700// CarouselScrollPhysics
1701
1702/// Scroll physics used by a [`CarouselView`].
1703///
1704/// These physics cause the carousel to snap to item boundaries.
1705///
1706/// See also:
1707///
1708///  * [`ScrollPhysics`], the base trait which defines the API for scrolling physics.
1709///  * `PageScrollPhysics`, scroll physics used by a `PageView`.
1710#[derive(Default)]
1711pub struct CarouselScrollPhysics {
1712    /// See [`ScrollPhysics::parent`].
1713    pub parent: Option<ScrollPhysicsRef>,
1714}
1715
1716impl CarouselScrollPhysics {
1717    /// Creates physics for a [`CarouselView`].
1718    pub fn new() -> CarouselScrollPhysics {
1719        CarouselScrollPhysics::default()
1720    }
1721
1722    /// Dart `CarouselScrollPhysics(parent:)`.
1723    pub fn with_parent(mut self, parent: ScrollPhysicsRef) -> CarouselScrollPhysics {
1724        self.parent = Some(parent);
1725        self
1726    }
1727
1728    fn get_target_pixels(
1729        &self,
1730        position: &CarouselMetrics,
1731        tolerance: Tolerance,
1732        velocity: f64,
1733    ) -> f64 {
1734        let fraction = match position.item_extent {
1735            Some(item_extent) => item_extent / position.viewport_dimension(),
1736            None => {
1737                let flex_weights = position
1738                    .flex_weights
1739                    .as_ref()
1740                    .expect("a carousel position has an item extent or flex weights");
1741                f64::from(flex_weights[0]) / f64::from(flex_weights.iter().sum::<i32>())
1742            }
1743        };
1744
1745        let item_width = position.viewport_dimension() * fraction;
1746
1747        let actual = position.pixels().max(0.0) / item_width;
1748        let round = actual.round();
1749        let mut item = if (actual - round).abs() < PRECISION_ERROR_TOLERANCE {
1750            round
1751        } else {
1752            actual
1753        };
1754        if velocity < -tolerance.velocity {
1755            item -= 0.5;
1756        } else if velocity > tolerance.velocity {
1757            item += 0.5;
1758        }
1759        item.round() * item_width
1760    }
1761}
1762
1763impl ScrollPhysics for CarouselScrollPhysics {
1764    fn as_any(&self) -> &dyn Any {
1765        self
1766    }
1767
1768    fn parent(&self) -> Option<&ScrollPhysicsRef> {
1769        self.parent.as_ref()
1770    }
1771
1772    fn apply_to(&self, ancestor: Option<ScrollPhysicsRef>) -> ScrollPhysicsRef {
1773        Rc::new(CarouselScrollPhysics {
1774            parent: ScrollPhysicsBase::build_parent(self, ancestor),
1775        })
1776    }
1777
1778    fn create_ballistic_simulation(
1779        &self,
1780        position: &dyn ScrollMetrics,
1781        velocity: f64,
1782    ) -> Option<Box<dyn Simulation>> {
1783        let metrics = position.as_any().downcast_ref::<CarouselMetrics>().expect(
1784            "CarouselScrollPhysics can only be used with Scrollables that uses the \
1785                 CarouselController",
1786        );
1787        if (velocity <= 0.0 && metrics.pixels() <= metrics.min_scroll_extent())
1788            || (velocity >= 0.0 && metrics.pixels() >= metrics.max_scroll_extent())
1789        {
1790            return ScrollPhysicsBase::create_ballistic_simulation(self, metrics, velocity);
1791        }
1792
1793        let tolerance = self.tolerance_for(metrics);
1794        let target = self.get_target_pixels(metrics, tolerance, velocity);
1795        if target != metrics.pixels() {
1796            return Some(Box::new(ScrollSpringSimulation::new(
1797                self.spring(),
1798                metrics.pixels(),
1799                target,
1800                velocity,
1801                tolerance,
1802            )));
1803        }
1804        None
1805    }
1806
1807    fn allow_implicit_scrolling(&self) -> bool {
1808        true
1809    }
1810}
1811
1812impl Debug for CarouselScrollPhysics {
1813    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1814        match &self.parent {
1815            None => write!(f, "CarouselScrollPhysics"),
1816            Some(parent) => write!(f, "CarouselScrollPhysics -> {parent:?}"),
1817        }
1818    }
1819}
1820
1821// ---------------------------------------------------------------------------------------------
1822// _CarouselMetrics
1823
1824/// Dart's `_CarouselMetrics`: the snapshot a carousel's position hands the physics, which
1825/// answers Dart's `position is _CarouselPosition`.
1826#[derive(Clone)]
1827struct CarouselMetrics {
1828    fixed: FixedScrollMetrics,
1829    item_extent: Option<f64>,
1830    flex_weights: Option<Vec<i32>>,
1831    /// Dart's `consumeMaxWeight`, which the physics do not read.
1832    #[allow(dead_code)]
1833    consume_max_weight: Option<bool>,
1834}
1835
1836impl ScrollMetrics for CarouselMetrics {
1837    fn as_any(&self) -> &dyn Any {
1838        self
1839    }
1840
1841    fn min_scroll_extent(&self) -> f64 {
1842        self.fixed.min_scroll_extent()
1843    }
1844
1845    fn max_scroll_extent(&self) -> f64 {
1846        self.fixed.max_scroll_extent()
1847    }
1848
1849    fn has_content_dimensions(&self) -> bool {
1850        self.fixed.has_content_dimensions()
1851    }
1852
1853    fn pixels(&self) -> f64 {
1854        self.fixed.pixels()
1855    }
1856
1857    fn has_pixels(&self) -> bool {
1858        self.fixed.has_pixels()
1859    }
1860
1861    fn viewport_dimension(&self) -> f64 {
1862        self.fixed.viewport_dimension()
1863    }
1864
1865    fn has_viewport_dimension(&self) -> bool {
1866        self.fixed.has_viewport_dimension()
1867    }
1868
1869    fn axis_direction(&self) -> AxisDirection {
1870        self.fixed.axis_direction()
1871    }
1872
1873    fn device_pixel_ratio(&self) -> f64 {
1874        self.fixed.device_pixel_ratio()
1875    }
1876}
1877
1878impl Debug for CarouselMetrics {
1879    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1880        write!(
1881            f,
1882            "CarouselMetrics({:.1}..[{:.1}]..{:.1})",
1883            self.extent_before(),
1884            self.extent_inside(),
1885            self.extent_after()
1886        )
1887    }
1888}
1889
1890// ---------------------------------------------------------------------------------------------
1891// _CarouselPosition
1892
1893/// Dart's `_CarouselPosition`: a [`ScrollPositionWithSingleContextLeaf`] that keeps its offset in
1894/// items.
1895struct CarouselPosition {
1896    change_notifier: ChangeNotifierData,
1897    scroll_position: ScrollPositionData,
1898    single_context: ScrollPositionWithSingleContextData,
1899    item_to_show_on_startup: f64,
1900    item_count: Option<i32>,
1901    infinite: bool,
1902    // When the viewport has a zero-size, the item can not
1903    // be retrieved by `getItemFromPixels`, so we need to cache the item
1904    // for use when resizing the viewport to non-zero next time.
1905    cached_item: Option<f64>,
1906    consume_max_weight: bool,
1907    item_extent: Option<f64>,
1908    flex_weights: Option<Vec<i32>>,
1909}
1910
1911impl CarouselPosition {
1912    fn new(
1913        app: &mut App,
1914        physics: ScrollPhysicsRef,
1915        context: Rc<dyn ScrollContext>,
1916        initial_item: i32,
1917        item_extent: Option<f64>,
1918        flex_weights: Option<Vec<i32>>,
1919        consume_max_weight: bool,
1920        infinite: bool,
1921        item_count: Option<i32>,
1922        old_position: Option<AnyScrollPosition>,
1923    ) -> Ref<CarouselPosition> {
1924        debug_assert!(
1925            (flex_weights.is_some() && item_extent.is_none())
1926                || (flex_weights.is_none() && item_extent.is_some())
1927        );
1928        let scroll_position = ScrollPositionData::new(app, physics, context, true, None);
1929        let this = app.create(CarouselPosition {
1930            change_notifier: ChangeNotifierData::new(),
1931            scroll_position,
1932            single_context: ScrollPositionWithSingleContextData::new(),
1933            item_to_show_on_startup: f64::from(initial_item),
1934            item_count,
1935            infinite,
1936            cached_item: None,
1937            consume_max_weight,
1938            item_extent,
1939            flex_weights,
1940        });
1941        ScrollPositionWithSingleContext::init(this.handle(), app, None, old_position);
1942        this
1943    }
1944
1945    fn set_item_count(self: Handle<Self>, app: &mut App, value: Option<i32>) {
1946        if app.get(self).item_count == value {
1947            return;
1948        }
1949        app.get_mut(self).item_count = value;
1950    }
1951
1952    fn set_infinite(self: Handle<Self>, app: &mut App, value: bool) {
1953        if app.get(self).infinite == value {
1954            return;
1955        }
1956        app.get_mut(self).infinite = value;
1957    }
1958
1959    fn set_consume_max_weight(self: Handle<Self>, app: &mut App, value: bool) {
1960        if app.get(self).consume_max_weight == value {
1961            return;
1962        }
1963        if self.has_pixels(app) && app.get(self).flex_weights.is_some() {
1964            let flex_weights = app.get(self).flex_weights.clone();
1965            let leading_item = self.update_leading_item(app, flex_weights.as_deref(), value);
1966            let item_extent = app.get(self).item_extent;
1967            let new_pixel =
1968                self.get_pixels_from_item(app, leading_item, flex_weights.as_deref(), item_extent);
1969            self.force_pixels(app, new_pixel);
1970        }
1971        app.get_mut(self).consume_max_weight = value;
1972    }
1973
1974    fn set_item_extent(self: Handle<Self>, app: &mut App, value: Option<f64>) {
1975        if app.get(self).item_extent == value {
1976            return;
1977        }
1978        if self.has_pixels(app)
1979            && app.get(self).item_extent.is_some()
1980            && self.viewport_dimension(app) != 0.0
1981        {
1982            let leading_item =
1983                self.get_item_from_pixels(app, self.pixels(app), self.viewport_dimension(app));
1984            let flex_weights = app.get(self).flex_weights.clone();
1985            let new_pixel =
1986                self.get_pixels_from_item(app, leading_item, flex_weights.as_deref(), value);
1987            self.force_pixels(app, new_pixel);
1988        }
1989        app.get_mut(self).item_extent = value;
1990    }
1991
1992    fn set_flex_weights(self: Handle<Self>, app: &mut App, value: Option<Vec<i32>>) {
1993        if app.get(self).flex_weights == value {
1994            return;
1995        }
1996        let old_weights = app.get(self).flex_weights.clone();
1997        if self.has_pixels(app) && old_weights.is_some() {
1998            let consume_max_weight = app.get(self).consume_max_weight;
1999            let leading_item = self.update_leading_item(app, value.as_deref(), consume_max_weight);
2000            let item_extent = app.get(self).item_extent;
2001            let new_pixel =
2002                self.get_pixels_from_item(app, leading_item, value.as_deref(), item_extent);
2003            self.force_pixels(app, new_pixel);
2004        }
2005        app.get_mut(self).flex_weights = value;
2006    }
2007
2008    // The index of the leading item in the carousel.
2009    // `getItemFromPixels` may return a fractional value (e.g., 0.6 when mid-scroll).
2010    // Use `toInt()` to truncate the fractional part, ensuring the leading item
2011    // only advances after fully crossing the next item's boundary.
2012    fn leading_item(self: Handle<Self>, app: &App) -> i32 {
2013        let mut leading_item =
2014            self.get_item_from_pixels(app, self.pixels(app), self.viewport_dimension(app)) as i32;
2015        let this = app.get(self);
2016        // When `consumeMaxWeight` is true, there is some reserved space before
2017        // item 0 so that item 0 can be expanded to occupy the maximum
2018        // weight while scrolling. The way how consumeMaxWeight works is that we assume
2019        // there are some "invisible" items before the first visible item. Therefore,
2020        // to calculate the correct visible leading item, we need to offset the leading
2021        // item by the index of the maximum weight.
2022        //
2023        // The subtraction may cause negative number for leading item. In this case,
2024        // constrain the leading item to 0.
2025        if this.consume_max_weight
2026            && let Some(flex_weights) = &this.flex_weights
2027        {
2028            leading_item = (leading_item - index_of_max(flex_weights)).max(0);
2029        }
2030        // For infinite scrolling, wrap the index to the range [0, itemCount - 1].
2031        if this.infinite
2032            && let Some(item_count) = this.item_count
2033            && item_count > 0
2034        {
2035            leading_item %= item_count;
2036        }
2037        leading_item
2038    }
2039
2040    fn update_leading_item(
2041        self: Handle<Self>,
2042        app: &App,
2043        new_flex_weights: Option<&[i32]>,
2044        new_consume_max_weight: bool,
2045    ) -> f64 {
2046        let this = app.get(self);
2047        let max_item;
2048        if self.has_pixels(app)
2049            && let Some(flex_weights) = &this.flex_weights
2050        {
2051            let leading_item =
2052                self.get_item_from_pixels(app, self.pixels(app), self.viewport_dimension(app));
2053            max_item = if this.consume_max_weight {
2054                leading_item
2055            } else {
2056                leading_item + f64::from(index_of_max(flex_weights))
2057            };
2058        } else {
2059            if !new_consume_max_weight {
2060                return this.item_to_show_on_startup;
2061            }
2062            max_item = this.item_to_show_on_startup;
2063        }
2064        if let Some(new_flex_weights) = new_flex_weights
2065            && !new_consume_max_weight
2066        {
2067            let max_weight = new_flex_weights.iter().max().expect("not empty");
2068            let mut smaller_weights = 0;
2069            for weight in new_flex_weights {
2070                if weight == max_weight {
2071                    break;
2072                }
2073                smaller_weights += 1;
2074            }
2075            return max_item - f64::from(smaller_weights);
2076        }
2077        max_item
2078    }
2079
2080    fn get_item_from_pixels(
2081        self: Handle<Self>,
2082        app: &App,
2083        pixels: f64,
2084        viewport_dimension: f64,
2085    ) -> f64 {
2086        debug_assert!(viewport_dimension > 0.0);
2087        let this = app.get(self);
2088        let fraction = match this.item_extent {
2089            Some(item_extent) => item_extent / viewport_dimension,
2090            None => {
2091                // If itemExtent is null, flexWeights cannot be null.
2092                let flex_weights = this
2093                    .flex_weights
2094                    .as_ref()
2095                    .expect("a carousel position has an item extent or flex weights");
2096                f64::from(flex_weights[0]) / f64::from(flex_weights.iter().sum::<i32>())
2097            }
2098        };
2099
2100        let actual = pixels.max(0.0) / (viewport_dimension * fraction);
2101        let round = actual.round();
2102        if (actual - round).abs() < PRECISION_ERROR_TOLERANCE {
2103            return round;
2104        }
2105        actual
2106    }
2107
2108    fn get_pixels_from_item(
2109        self: Handle<Self>,
2110        app: &App,
2111        item: f64,
2112        flex_weights: Option<&[i32]>,
2113        item_extent: Option<f64>,
2114    ) -> f64 {
2115        let viewport_dimension = self.viewport_dimension(app);
2116        if viewport_dimension == 0.0 {
2117            return 0.0;
2118        }
2119        let fraction = match item_extent {
2120            Some(item_extent) => item_extent / viewport_dimension,
2121            None => {
2122                // If itemExtent is null, flexWeights cannot be null.
2123                let flex_weights =
2124                    flex_weights.expect("a carousel position has an item extent or flex weights");
2125                f64::from(flex_weights[0]) / f64::from(flex_weights.iter().sum::<i32>())
2126            }
2127        };
2128
2129        item * viewport_dimension * fraction
2130    }
2131
2132    fn get_cycle_length_in_pixels(self: Handle<Self>, app: &App) -> f64 {
2133        let this = app.get(self);
2134        let Some(item_count) = this.item_count else {
2135            return 0.0;
2136        };
2137        if item_count <= 0
2138            || !self.has_viewport_dimension(app)
2139            || self.viewport_dimension(app) == 0.0
2140        {
2141            return 0.0;
2142        }
2143        let viewport_dimension = self.viewport_dimension(app);
2144        let fraction = if let Some(item_extent) = this.item_extent {
2145            item_extent / viewport_dimension
2146        } else if let Some(flex_weights) = &this.flex_weights {
2147            f64::from(flex_weights[0]) / f64::from(flex_weights.iter().sum::<i32>())
2148        } else {
2149            return 0.0;
2150        };
2151        f64::from(item_count) * viewport_dimension * fraction
2152    }
2153}
2154
2155impl ChangeNotifier for CarouselPosition {
2156    fn change_notifier_data(&self) -> &ChangeNotifierData {
2157        &self.change_notifier
2158    }
2159
2160    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
2161        &mut self.change_notifier
2162    }
2163}
2164
2165impl ViewportOffset for CarouselPosition {
2166    fn pixels(self: Handle<Self>, app: &App) -> f64 {
2167        ScrollPositionBase::pixels(self, app)
2168    }
2169
2170    fn has_pixels(self: Handle<Self>, app: &App) -> bool {
2171        ScrollPositionBase::has_pixels(self, app)
2172    }
2173
2174    fn apply_viewport_dimension(
2175        self: Handle<Self>,
2176        app: &mut App,
2177        viewport_dimension: f64,
2178    ) -> bool {
2179        let old_viewport_dimensions = self
2180            .has_viewport_dimension(app)
2181            .then(|| self.viewport_dimension(app));
2182        if Some(viewport_dimension) == old_viewport_dimensions {
2183            return true;
2184        }
2185        let result = ScrollPositionBase::apply_viewport_dimension(self, app, viewport_dimension);
2186        let old_pixels = self.has_pixels(app).then(|| self.pixels(app));
2187        let flex_weights = app.get(self).flex_weights.clone();
2188        let item = match old_pixels {
2189            None => {
2190                let consume_max_weight = app.get(self).consume_max_weight;
2191                self.update_leading_item(app, flex_weights.as_deref(), consume_max_weight)
2192            }
2193            // If resize from zero, we should use the _cachedItem to recover the state.
2194            Some(_) if old_viewport_dimensions == Some(0.0) => app
2195                .get(self)
2196                .cached_item
2197                .expect("a position resized from zero cached its item"),
2198            Some(old_pixels) => self.get_item_from_pixels(
2199                app,
2200                old_pixels,
2201                old_viewport_dimensions.unwrap_or(viewport_dimension),
2202            ),
2203        };
2204        let item_extent = app.get(self).item_extent;
2205        let new_pixels = self.get_pixels_from_item(app, item, flex_weights.as_deref(), item_extent);
2206        // If the viewportDimension is zero, cache the item
2207        // in case the viewport is resized to be non-zero.
2208        app.get_mut(self).cached_item = (viewport_dimension == 0.0).then_some(item);
2209
2210        if Some(new_pixels) != old_pixels {
2211            self.correct_pixels(app, new_pixels);
2212            return false;
2213        }
2214        result
2215    }
2216
2217    fn apply_content_dimensions(
2218        self: Handle<Self>,
2219        app: &mut App,
2220        min_scroll_extent: f64,
2221        max_scroll_extent: f64,
2222    ) -> bool {
2223        // For infinite scrolling, dynamically add cycles when approaching the boundary.
2224        // This eliminates the need for a large hardcoded starting offset.
2225        let infinite = app.get(self).infinite;
2226        if infinite && self.has_pixels(app) {
2227            let cycle_length = self.get_cycle_length_in_pixels(app);
2228            let pixels = self.pixels(app);
2229            if cycle_length > 0.0 && pixels < cycle_length {
2230                // When scroll position drops below one cycle, add cycles to maintain buffer.
2231                // This allows seamless backward scrolling without hitting the boundary.
2232                let cycles_to_add = ((cycle_length - pixels) / cycle_length).ceil();
2233                self.correct_pixels(app, pixels + cycles_to_add * cycle_length);
2234                // Indicate position was corrected and layout should rerun.
2235                return false;
2236            }
2237        }
2238        ScrollPositionBase::apply_content_dimensions(
2239            self,
2240            app,
2241            if infinite { 0.0 } else { min_scroll_extent },
2242            max_scroll_extent,
2243        )
2244    }
2245
2246    fn correct_by(self: Handle<Self>, app: &mut App, correction: f64) {
2247        ScrollPositionBase::correct_by(self, app, correction);
2248    }
2249
2250    fn jump_to(self: Handle<Self>, app: &mut App, value: f64) {
2251        ScrollPositionWithSingleContextLeaf::jump_to(self, app, value);
2252    }
2253
2254    fn animate_to(
2255        self: Handle<Self>,
2256        app: &mut App,
2257        to: f64,
2258        duration: Duration,
2259        curve: Rc<dyn Curve>,
2260    ) -> CompleterFuture<()> {
2261        ScrollPositionWithSingleContextLeaf::animate_to(self, app, to, duration, curve)
2262    }
2263
2264    fn move_to(
2265        self: Handle<Self>,
2266        app: &mut App,
2267        to: f64,
2268        duration: Option<Duration>,
2269        curve: Option<Rc<dyn Curve>>,
2270        clamp: Option<bool>,
2271    ) -> CompleterFuture<()> {
2272        ScrollPositionBase::move_to(self, app, to, duration, curve, clamp)
2273    }
2274
2275    fn user_scroll_direction(self: Handle<Self>, app: &App) -> waft_rendering::ScrollDirection {
2276        ScrollPositionWithSingleContextLeaf::user_scroll_direction(self, app)
2277    }
2278
2279    fn allow_implicit_scrolling(self: Handle<Self>, app: &App) -> bool {
2280        ScrollPositionBase::allow_implicit_scrolling(self, app)
2281    }
2282}
2283
2284impl ScrollPosition for CarouselPosition {
2285    waft_widgets::scroll_position_with_single_context_overrides!();
2286
2287    fn copy_with(self: Handle<Self>, app: &App) -> Rc<dyn ScrollMetrics> {
2288        let has_content_dimensions = self.has_content_dimensions(app);
2289        let this = app.get(self);
2290        Rc::new(CarouselMetrics {
2291            fixed: FixedScrollMetrics::new(
2292                has_content_dimensions.then(|| self.min_scroll_extent(app)),
2293                has_content_dimensions.then(|| self.max_scroll_extent(app)),
2294                self.has_pixels(app).then(|| self.pixels(app)),
2295                self.has_viewport_dimension(app)
2296                    .then(|| self.viewport_dimension(app)),
2297                ScrollPosition::axis_direction(self, app),
2298                self.device_pixel_ratio(app),
2299            ),
2300            item_extent: this.item_extent,
2301            flex_weights: this.flex_weights.clone(),
2302            consume_max_weight: Some(this.consume_max_weight),
2303        })
2304    }
2305}
2306
2307impl ScrollActivityDelegate for CarouselPosition {
2308    waft_widgets::scroll_position_with_single_context_delegate_overrides!();
2309}
2310
2311impl ScrollPositionWithSingleContextLeaf for CarouselPosition {
2312    waft_widgets::scroll_position_with_single_context_accessors!();
2313
2314    fn absorb(self: Handle<Self>, app: &mut App, other: AnyScrollPosition) {
2315        ScrollPositionWithSingleContext::absorb(self, app, other);
2316
2317        let Some(other) = other.downcast::<CarouselPosition>(app) else {
2318            return;
2319        };
2320
2321        let (cached_item, item_extent) = {
2322            let other = app.get(other);
2323            (other.cached_item, other.item_extent)
2324        };
2325        let this = app.get_mut(self);
2326        this.cached_item = cached_item;
2327        this.item_extent = item_extent;
2328    }
2329}
2330
2331// ---------------------------------------------------------------------------------------------
2332// CarouselController
2333
2334/// A controller for [`CarouselView`].
2335///
2336/// Using a carousel controller helps to show the first visible item on the carousel list.
2337pub struct CarouselController {
2338    change_notifier: ChangeNotifierData,
2339    scroll_controller: ScrollControllerData,
2340    /// The item that will be the leading item when the carousel is first built.
2341    ///
2342    /// For a weighted carousel, it is the item that occupies the first maximum weight.
2343    initial_item: i32,
2344    carousel_state: Option<Handle<CarouselViewState>>,
2345}
2346
2347impl CarouselController {
2348    /// Creates a carousel controller.
2349    pub fn new(app: &mut App, initial_item: i32) -> Ref<CarouselController> {
2350        app.create(CarouselController {
2351            change_notifier: ChangeNotifierData::new(),
2352            scroll_controller: ScrollControllerData::new(0.0, true, None, None, None),
2353            initial_item,
2354            carousel_state: None,
2355        })
2356    }
2357
2358    /// The item that will be the leading item when the carousel is first built.
2359    pub fn initial_item(self: Handle<Self>, app: &App) -> i32 {
2360        app.get(self).initial_item
2361    }
2362
2363    /// The index of the current leading item of the controlled [`CarouselView`].
2364    ///
2365    /// Reading it panics before a [`CarouselView`] is built with this controller, and while
2366    /// several carousels are attached to it.
2367    pub fn leading_item(self: Handle<Self>, app: &App) -> i32 {
2368        let positions = self.positions(app);
2369        debug_assert!(
2370            !positions.is_empty(),
2371            "CarouselController.leadingItem cannot be accessed before a CarouselView is built \
2372             with it."
2373        );
2374        debug_assert!(
2375            positions.len() == 1,
2376            "CarouselController.leadingItem cannot be read when multiple CarouselViews are \
2377             attached to the same controller."
2378        );
2379        self.carousel_position(app).leading_item(app)
2380    }
2381
2382    /// Dart's `this.position as _CarouselPosition`.
2383    fn carousel_position(self: Handle<Self>, app: &App) -> Handle<CarouselPosition> {
2384        self.position(app)
2385            .downcast::<CarouselPosition>(app)
2386            .expect("a CarouselController creates the positions of the CarouselViews it controls")
2387    }
2388
2389    fn attach_state(self: Handle<Self>, app: &mut App, anchor: Handle<CarouselViewState>) {
2390        app.get_mut(self).carousel_state = Some(anchor);
2391    }
2392
2393    fn detach_state(self: Handle<Self>, app: &mut App, anchor: Handle<CarouselViewState>) {
2394        if app.get(self).carousel_state == Some(anchor) {
2395            app.get_mut(self).carousel_state = None;
2396        }
2397    }
2398
2399    /// Animates the controlled carousel so that the item at `index` is the leading item (or, for
2400    /// a weighted carousel with `consume_max_weight` unset, the one with the largest weight).
2401    ///
2402    /// The returned future resolves when the animation completes; it resolves at once without a
2403    /// controlled carousel. Dart's defaults are a duration of 300 milliseconds and `Curves.ease`.
2404    pub fn animate_to_item(
2405        self: Handle<Self>,
2406        app: &mut App,
2407        index: i32,
2408        duration: Duration,
2409        curve: Rc<dyn Curve>,
2410    ) -> CompleterFuture<()> {
2411        let Some(carousel_state) = app.get(self).carousel_state else {
2412            return CompleterFuture::ready(());
2413        };
2414        if !self.has_clients(app) {
2415            return CompleterFuture::ready(());
2416        }
2417
2418        let has_flex_weights = carousel_state
2419            .flex_weights(app)
2420            .is_some_and(|weights| !weights.is_empty());
2421        let widget = carousel_state.widget(app);
2422        let index = if widget.item_builder.is_some() {
2423            match widget.item_count {
2424                Some(item_count) => index.clamp(0, item_count - 1),
2425                None => 0,
2426            }
2427        } else {
2428            index.clamp(0, widget.children.len() as i32 - 1)
2429        };
2430
2431        let futures: Vec<CompleterFuture<()>> = self
2432            .positions(app)
2433            .into_iter()
2434            .map(|position| {
2435                let position = position
2436                    .downcast::<CarouselPosition>(app)
2437                    .expect("a CarouselController's positions are carousel positions");
2438                let target = self.get_target_offset(app, position, index, has_flex_weights);
2439                ViewportOffset::animate_to(position, app, target, duration, Rc::clone(&curve))
2440            })
2441            .collect();
2442        CompleterFuture::spawn(app, async move {
2443            wait_all(futures).await;
2444        })
2445    }
2446
2447    fn get_target_offset(
2448        self: Handle<Self>,
2449        app: &App,
2450        position: Handle<CarouselPosition>,
2451        index: i32,
2452        has_flex_weights: bool,
2453    ) -> f64 {
2454        let carousel_state = app.get(self).carousel_state.expect("checked by the caller");
2455        if !has_flex_weights {
2456            let target_in_first_cycle = f64::from(index)
2457                * app
2458                    .get(carousel_state)
2459                    .item_extent
2460                    .expect("a carousel without weights has an item extent");
2461            if !carousel_state.widget(app).infinite {
2462                return target_in_first_cycle;
2463            }
2464            return self.adjust_for_infinite_cycle(app, position, target_in_first_cycle);
2465        }
2466
2467        let weights = carousel_state
2468            .flex_weights(app)
2469            .expect("has_flex_weights was checked");
2470        let total_weight: i32 = weights.iter().sum();
2471        let dimension = position.viewport_dimension(app);
2472
2473        let max_weight_index = index_of_max(&weights);
2474        let mut leading_index = if carousel_state.consume_max_weight(app) {
2475            index
2476        } else {
2477            index - max_weight_index
2478        };
2479        let widget = carousel_state.widget(app);
2480        if widget.item_builder.is_some() {
2481            leading_index = match widget.item_count {
2482                Some(item_count) => leading_index.clamp(0, item_count - 1),
2483                None => 0,
2484            };
2485        } else {
2486            let item_count = widget.children.len() as i32;
2487            leading_index = leading_index.clamp(0, item_count - 1);
2488        }
2489
2490        let target_in_first_cycle = dimension
2491            * (f64::from(weights[0]) / f64::from(total_weight))
2492            * f64::from(leading_index);
2493        if !widget.infinite {
2494            return target_in_first_cycle;
2495        }
2496        self.adjust_for_infinite_cycle(app, position, target_in_first_cycle)
2497    }
2498
2499    fn adjust_for_infinite_cycle(
2500        self: Handle<Self>,
2501        app: &App,
2502        position: Handle<CarouselPosition>,
2503        target_in_first_cycle: f64,
2504    ) -> f64 {
2505        let cycle_length = position.get_cycle_length_in_pixels(app);
2506        if cycle_length <= 0.0 {
2507            return target_in_first_cycle;
2508        }
2509        let current_pixels = position.pixels(app);
2510        // Determine which cycle the current position is in.
2511        let current_cycle_start = (current_pixels / cycle_length).floor() * cycle_length;
2512        // Candidate target in the same cycle as the current position.
2513        let same_cycle_target = current_cycle_start + target_in_first_cycle;
2514
2515        // Always scroll forward: pick the first target at or ahead of current position.
2516        if same_cycle_target >= current_pixels {
2517            return same_cycle_target;
2518        }
2519        same_cycle_target + cycle_length
2520    }
2521
2522    fn get_item_count(self: Handle<Self>, app: &App) -> Option<i32> {
2523        let carousel_state = app.get(self).carousel_state?;
2524        let widget = carousel_state.widget(app);
2525        if widget.item_builder.is_some() {
2526            return widget.item_count;
2527        }
2528        Some(widget.children.len() as i32)
2529    }
2530}
2531
2532impl ChangeNotifier for CarouselController {
2533    fn change_notifier_data(&self) -> &ChangeNotifierData {
2534        &self.change_notifier
2535    }
2536
2537    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
2538        &mut self.change_notifier
2539    }
2540}
2541
2542impl ScrollControllerLeaf for CarouselController {
2543    waft_widgets::scroll_controller_accessors!();
2544
2545    fn create_scroll_position(
2546        self: Handle<Self>,
2547        app: &mut App,
2548        physics: ScrollPhysicsRef,
2549        context: Rc<dyn ScrollContext>,
2550        old_position: Option<AnyScrollPosition>,
2551    ) -> ScrollPositionRef {
2552        let carousel_state = app
2553            .get(self)
2554            .carousel_state
2555            .expect("a CarouselController creates positions for an attached CarouselView");
2556        let initial_item = app.get(self).initial_item;
2557        let item_extent = app.get(carousel_state).item_extent;
2558        let consume_max_weight = carousel_state.consume_max_weight(app);
2559        let flex_weights = carousel_state.flex_weights(app);
2560        let infinite = carousel_state.widget(app).infinite;
2561        let item_count = self.get_item_count(app);
2562        CarouselPosition::new(
2563            app,
2564            physics,
2565            context,
2566            initial_item,
2567            item_extent,
2568            flex_weights,
2569            consume_max_weight,
2570            infinite,
2571            item_count,
2572            old_position,
2573        )
2574        .into_erased()
2575    }
2576
2577    fn attach(self: Handle<Self>, app: &mut App, position: ScrollPositionRef) {
2578        let attached = position.handle();
2579        waft_widgets::ScrollController::attach(self.as_controller(), app, position);
2580        let carousel_position = attached
2581            .downcast::<CarouselPosition>(app)
2582            .expect("a CarouselController attaches the positions it creates");
2583        let carousel_state = app
2584            .get(self)
2585            .carousel_state
2586            .expect("a CarouselController attaches positions of an attached CarouselView");
2587        let flex_weights = carousel_state.flex_weights(app);
2588        let item_extent = app.get(carousel_state).item_extent;
2589        let consume_max_weight = carousel_state.consume_max_weight(app);
2590        let infinite = carousel_state.widget(app).infinite;
2591        let item_count = self.get_item_count(app);
2592        carousel_position.set_flex_weights(app, flex_weights);
2593        carousel_position.set_item_extent(app, item_extent);
2594        carousel_position.set_consume_max_weight(app, consume_max_weight);
2595        carousel_position.set_infinite(app, infinite);
2596        carousel_position.set_item_count(app, item_count);
2597    }
2598}
2599
2600#[cfg(test)]
2601mod tests {
2602    use std::cell::{Cell, RefCell};
2603
2604    use waft_animation::Curves;
2605    use waft_embedder::Size;
2606    use waft_embedder::{Offset, Rect};
2607    use waft_painting::{BorderRadiusGeometry, BorderSide, StadiumBorder};
2608    use waft_rendering::RenderBox;
2609    use waft_rendering::testing::{PaintCall, paints};
2610    use waft_widgets::testing::{
2611        Finder, TestPointer, WidgetTester, expect, find, finds_nothing, finds_one_widget,
2612        test_widgets,
2613    };
2614    use waft_widgets::{
2615        Center, Padding, ScrollBehaviorRef, ScrollConfiguration, SizedBox, Text, WidgetStates,
2616    };
2617
2618    use super::*;
2619    use crate::scaffold::Scaffold;
2620    use crate::test_support::{PaintInspection, material_app};
2621    use crate::theme_data::ThemeData;
2622
2623    fn text_items(count: i32) -> Vec<WidgetRef> {
2624        (0..count)
2625            .map(|index| {
2626                Center::new()
2627                    .child(Text::new(format!("Item {index}")))
2628                    .into_widget()
2629            })
2630            .collect()
2631    }
2632
2633    fn pump_carousel(tester: &mut WidgetTester, carousel: CarouselView) {
2634        let theme = ThemeData::builder().build(&tester.cell.borrow());
2635        tester.pump_widget(material_app(
2636            theme,
2637            Scaffold::new().body(carousel).into_widget(),
2638        ));
2639    }
2640
2641    /// What the first `_RenderInkFeatures` paints with its subtree: Dart's `paints` on it.
2642    fn ink_painted_ops(tester: &WidgetTester) -> Vec<waft_embedder::valo::Op> {
2643        tester.painted_ops_deep(
2644            tester
2645                .first::<crate::material::RenderInkFeatures>()
2646                .as_object(),
2647        )
2648    }
2649
2650    /// Dart's `getItem`.
2651    fn get_item(index: i32) -> Finder {
2652        find::descendant(
2653            find::by_type::<CarouselView>(),
2654            find::ancestor(
2655                find::text(&format!("Item {index}")),
2656                find::by_type::<Padding>(),
2657            ),
2658        )
2659    }
2660
2661    fn assert_item_rect(tester: &WidgetTester, index: i32, expected: Rect) {
2662        assert_eq!(tester.get_rect(get_item(index)), expected);
2663    }
2664
2665    fn expect_items(tester: &WidgetTester, present: &[i32], absent: &[i32]) {
2666        for index in present {
2667            expect(tester, &get_item(*index), finds_one_widget());
2668        }
2669        for index in absent {
2670            expect(tester, &get_item(*index), finds_nothing());
2671        }
2672    }
2673
2674    #[test]
2675    fn carousel_view_defaults() {
2676        test_widgets(|tester| {
2677            pump_carousel(tester, CarouselView::new(200.0, text_items(10)));
2678            let theme = ThemeData::builder().build(&tester.cell.borrow());
2679
2680            let material = find::descendant(
2681                find::by_type::<CarouselView>(),
2682                find::by_type::<crate::material::Material>(),
2683            )
2684            .first();
2685            tester.widget(material, |material: &crate::material::Material| {
2686                assert_eq!(material.clip_behavior, Clip::AntiAlias);
2687                assert_eq!(material.color, Some(theme.color_scheme.surface()));
2688                assert_eq!(material.elevation, 0.0);
2689                assert_eq!(
2690                    material.shape,
2691                    Some(ShapeBorderRef::new(RoundedRectangleBorder::new(
2692                        BorderSide::NONE,
2693                        BorderRadiusGeometry::circular(28.0)
2694                    )))
2695                );
2696            });
2697        });
2698    }
2699
2700    #[test]
2701    fn carousel_view_items_customization() {
2702        test_widgets(|tester| {
2703            let key = waft_widgets::GlobalKey::new();
2704            let mut children = text_items(10);
2705            children[0] = Center::new()
2706                .key(key.clone().into())
2707                .child(Center::new().child(Text::new("Item 0")))
2708                .into_widget();
2709            let overlay_color = <dyn WidgetStateProperty<Option<Color>>>::resolve_with(|states| {
2710                if states.contains(&WidgetState::Pressed) {
2711                    return Some(Colors::YELLOW.primary());
2712                }
2713                if states.contains(&WidgetState::Hovered) {
2714                    return Some(Colors::RED.primary());
2715                }
2716                if states.contains(&WidgetState::Focused) {
2717                    return Some(Colors::PURPLE.primary());
2718                }
2719                None
2720            });
2721            pump_carousel(
2722                tester,
2723                CarouselView::new(200.0, children)
2724                    .padding(EdgeInsets::all(20.0))
2725                    .background_color(Colors::AMBER.primary())
2726                    .elevation(10.0)
2727                    .shape(StadiumBorder::new(BorderSide::NONE))
2728                    .overlay_color(overlay_color),
2729            );
2730
2731            let carousel_view_material = find::descendant(
2732                find::by_type::<CarouselView>(),
2733                find::by_type::<crate::material::Material>(),
2734            )
2735            .first();
2736            // Padding is 20 on both side.
2737            assert_eq!(
2738                tester.get_size(carousel_view_material.clone()).width(),
2739                200.0 - 20.0 - 20.0
2740            );
2741            tester.widget(
2742                carousel_view_material.clone(),
2743                |material: &crate::material::Material| {
2744                    assert_eq!(material.color, Some(Colors::AMBER.primary()));
2745                    assert_eq!(material.elevation, 10.0);
2746                    assert_eq!(
2747                        material.shape,
2748                        Some(ShapeBorderRef::new(StadiumBorder::new(BorderSide::NONE)))
2749                    );
2750                },
2751            );
2752
2753            // On hovered.
2754            let mut mouse = TestPointer::mouse(1, waft_gestures::K_PRIMARY_MOUSE_BUTTON);
2755            let center = tester.get_center(&key);
2756            tester.add_pointer(&mut mouse, Offset::ZERO);
2757            tester.move_to(&mut mouse, center, false);
2758            tester.pump_and_settle();
2759            assert!(
2760                paints(
2761                    &ink_painted_ops(tester),
2762                    &[PaintCall::rect(Some(Colors::RED.primary()))]
2763                )
2764                .is_ok()
2765            );
2766
2767            // On pressed.
2768            tester.pump_and_settle();
2769            tester.down(&mut mouse, center);
2770            tester.pump_and_settle();
2771            for op in ink_painted_ops(tester) {
2772                eprintln!("DBG {op:?}");
2773            }
2774            assert!(
2775                paints(
2776                    &ink_painted_ops(tester),
2777                    &[
2778                        PaintCall::rect(None),
2779                        PaintCall::rect(Some(Colors::YELLOW.primary()))
2780                    ]
2781                )
2782                .is_ok()
2783            );
2784
2785            tester.pump_and_settle();
2786            tester.up(&mouse);
2787            tester.remove_pointer(&mouse);
2788
2789            // On focused.
2790            let overlay_color = tester.widget(
2791                find::descendant(carousel_view_material, find::by_type::<InkWell>()),
2792                |ink_well: &InkWell| ink_well.ink_response.overlay_color.clone(),
2793            );
2794            assert_eq!(
2795                overlay_color
2796                    .expect("an overlay color")
2797                    .resolve(&WidgetStates::from([WidgetState::Focused])),
2798                Some(Colors::PURPLE.primary())
2799            );
2800        });
2801    }
2802
2803    #[test]
2804    fn carousel_view_respects_on_tap() {
2805        test_widgets(|tester| {
2806            let tap_index = Rc::new(Cell::new(0));
2807            pump_carousel(
2808                tester,
2809                CarouselView::new(50.0, text_items(10)).on_tap({
2810                    let tap_index = Rc::clone(&tap_index);
2811                    Rc::new(move |_app, index| tap_index.set(index))
2812                }),
2813            );
2814
2815            tester.tap(find::ancestor(find::text("Item 1"), find::by_type::<Stack>()).first());
2816            tester.pump();
2817            assert_eq!(tap_index.get(), 1);
2818
2819            tester.tap(find::ancestor(find::text("Item 2"), find::by_type::<Stack>()).first());
2820            tester.pump();
2821            assert_eq!(tap_index.get(), 2);
2822        });
2823    }
2824
2825    #[test]
2826    fn carousel_view_layout_uncontained_layout() {
2827        test_widgets(|tester| {
2828            pump_carousel(tester, CarouselView::new(250.0, text_items(10)));
2829
2830            expect(tester, &find::text("Item 0"), finds_one_widget());
2831            assert_item_rect(tester, 0, Rect::from_ltrb(0.0, 0.0, 250.0, 600.0));
2832            expect(tester, &find::text("Item 1"), finds_one_widget());
2833            assert_item_rect(tester, 1, Rect::from_ltrb(250.0, 0.0, 500.0, 600.0));
2834            expect(tester, &find::text("Item 2"), finds_one_widget());
2835            assert_item_rect(tester, 2, Rect::from_ltrb(500.0, 0.0, 750.0, 600.0));
2836            expect(tester, &find::text("Item 3"), finds_one_widget());
2837            assert_item_rect(tester, 3, Rect::from_ltrb(750.0, 0.0, 800.0, 600.0));
2838            expect(tester, &find::text("Item 4"), finds_nothing());
2839        });
2840    }
2841
2842    #[test]
2843    fn carousel_view_weighted_layout() {
2844        test_widgets(|tester| {
2845            pump_carousel(
2846                tester,
2847                CarouselView::weighted(vec![4, 3, 2, 1], text_items(10)),
2848            );
2849
2850            // Item widths are 4/10, 3/10, 2/10 and 1/10 of the viewport.
2851            assert_item_rect(tester, 0, Rect::from_ltrb(0.0, 0.0, 320.0, 600.0));
2852            assert_item_rect(tester, 1, Rect::from_ltrb(320.0, 0.0, 560.0, 600.0));
2853            assert_item_rect(tester, 2, Rect::from_ltrb(560.0, 0.0, 720.0, 600.0));
2854            assert_item_rect(tester, 3, Rect::from_ltrb(720.0, 0.0, 800.0, 600.0));
2855            expect(tester, &find::text("Item 4"), finds_nothing());
2856
2857            // Test shorter weight list.
2858            pump_carousel(tester, CarouselView::weighted(vec![7, 1], text_items(10)));
2859            tester.pump_and_settle();
2860
2861            // Item widths are 7/8 and 1/8 of the viewport.
2862            assert_item_rect(tester, 0, Rect::from_ltrb(0.0, 0.0, 700.0, 600.0));
2863            assert_item_rect(tester, 1, Rect::from_ltrb(700.0, 0.0, 800.0, 600.0));
2864            expect(tester, &find::text("Item 2"), finds_nothing());
2865        });
2866    }
2867
2868    #[test]
2869    fn carousel_controller_initial_item() {
2870        test_widgets(|tester| {
2871            let controller = CarouselController::new(&mut tester.cell.borrow_mut(), 5);
2872            pump_carousel(
2873                tester,
2874                CarouselView::new(400.0, text_items(10)).controller(controller),
2875            );
2876
2877            assert_item_rect(tester, 5, Rect::from_ltrb(0.0, 0.0, 400.0, 600.0));
2878            assert_item_rect(tester, 6, Rect::from_ltrb(400.0, 0.0, 800.0, 600.0));
2879            expect_items(tester, &[5, 6], &[4, 7]);
2880        });
2881    }
2882
2883    #[test]
2884    fn carousel_view_weighted_respects_carousel_controller_initial_item() {
2885        test_widgets(|tester| {
2886            let controller = CarouselController::new(&mut tester.cell.borrow_mut(), 5);
2887            pump_carousel(
2888                tester,
2889                CarouselView::weighted(vec![7, 1], text_items(10)).controller(controller),
2890            );
2891
2892            assert_item_rect(tester, 5, Rect::from_ltrb(0.0, 0.0, 700.0, 600.0));
2893            assert_item_rect(tester, 6, Rect::from_ltrb(700.0, 0.0, 800.0, 600.0));
2894            expect_items(tester, &[5, 6], &[4, 7]);
2895        });
2896    }
2897
2898    #[test]
2899    fn the_initial_item_should_be_the_first_item_with_expanded_size() {
2900        test_widgets(|tester| {
2901            let controller = CarouselController::new(&mut tester.cell.borrow_mut(), 5);
2902            pump_carousel(
2903                tester,
2904                CarouselView::weighted(vec![1, 8, 1], text_items(10)).controller(controller),
2905            );
2906
2907            // Item 5 should have be the expanded item.
2908            assert_item_rect(tester, 5, Rect::from_ltrb(80.0, 0.0, 720.0, 600.0));
2909            assert_item_rect(tester, 6, Rect::from_ltrb(720.0, 0.0, 800.0, 600.0));
2910            assert_item_rect(tester, 4, Rect::from_ltrb(0.0, 0.0, 80.0, 600.0));
2911            expect_items(tester, &[4, 5, 6], &[7]);
2912        });
2913    }
2914
2915    #[test]
2916    fn carousel_view_respects_item_snapping() {
2917        test_widgets(|tester| {
2918            pump_carousel(
2919                tester,
2920                CarouselView::new(300.0, text_items(10)).item_snapping(true),
2921            );
2922            let check_original_expectations = |tester: &WidgetTester| {
2923                expect_items(tester, &[0, 1, 2], &[3]);
2924            };
2925
2926            check_original_expectations(tester);
2927
2928            // Snap back to the original item.
2929            tester.drag(get_item(0), Offset::new(-150.0, 0.0));
2930            tester.pump_and_settle();
2931            check_original_expectations(tester);
2932
2933            // Snap back to the original item.
2934            tester.drag(get_item(0), Offset::new(100.0, 0.0));
2935            tester.pump_and_settle();
2936            check_original_expectations(tester);
2937
2938            // Snap to the next item.
2939            tester.drag(get_item(0), Offset::new(-200.0, 0.0));
2940            tester.pump_and_settle();
2941            expect_items(tester, &[1, 2, 3], &[0]);
2942        });
2943    }
2944
2945    #[test]
2946    fn carousel_view_weighted_respects_item_snapping() {
2947        test_widgets(|tester| {
2948            pump_carousel(
2949                tester,
2950                CarouselView::weighted(vec![1, 7], text_items(10))
2951                    .item_snapping(true)
2952                    .consume_max_weight(false),
2953            );
2954            let check_original_expectations = |tester: &WidgetTester| {
2955                expect_items(tester, &[0, 1], &[2]);
2956            };
2957
2958            check_original_expectations(tester);
2959
2960            // Snap back to the original item.
2961            tester.drag(get_item(0), Offset::new(-20.0, 0.0));
2962            tester.pump_and_settle();
2963            check_original_expectations(tester);
2964
2965            // Snap back to the original item.
2966            tester.drag(get_item(0), Offset::new(50.0, 0.0));
2967            tester.pump_and_settle();
2968            check_original_expectations(tester);
2969
2970            // Snap to the next item.
2971            tester.drag(get_item(0), Offset::new(-70.0, 0.0));
2972            tester.pump_and_settle();
2973            expect_items(tester, &[1, 2], &[0, 3]);
2974        });
2975    }
2976
2977    #[test]
2978    fn carousel_view_respects_item_snapping_when_fling() {
2979        test_widgets(|tester| {
2980            pump_carousel(
2981                tester,
2982                CarouselView::new(300.0, text_items(10)).item_snapping(true),
2983            );
2984
2985            // Show item 0, 1, and 2.
2986            expect_items(tester, &[0, 1, 2], &[3]);
2987
2988            // Snap to the next item. Show item 1, 2 and 3.
2989            tester.fling(get_item(0), Offset::new(-100.0, 0.0), 800.0);
2990            tester.pump_and_settle();
2991            expect_items(tester, &[1, 2, 3], &[0, 4]);
2992
2993            // Snap to the next item. Show item 2, 3 and 4.
2994            tester.fling(get_item(1), Offset::new(-100.0, 0.0), 800.0);
2995            tester.pump_and_settle();
2996            expect_items(tester, &[2, 3, 4], &[0, 1, 5]);
2997
2998            // Fling back to the previous item. Show item 1, 2 and 3.
2999            tester.fling(get_item(2), Offset::new(100.0, 0.0), 800.0);
3000            tester.pump_and_settle();
3001            expect_items(tester, &[1, 2, 3], &[4]);
3002        });
3003    }
3004
3005    #[test]
3006    fn carousel_view_respects_reverse() {
3007        test_widgets(|tester| {
3008            pump_carousel(
3009                tester,
3010                CarouselView::new(200.0, text_items(10)).reverse(true),
3011            );
3012            tester.pump_and_settle();
3013
3014            // Item 0 should be placed on the end of the screen.
3015            assert_item_rect(tester, 0, Rect::from_ltrb(600.0, 0.0, 800.0, 600.0));
3016            // Item 1 should be placed before item 0.
3017            assert_item_rect(tester, 1, Rect::from_ltrb(400.0, 0.0, 600.0, 600.0));
3018            assert_item_rect(tester, 2, Rect::from_ltrb(200.0, 0.0, 400.0, 600.0));
3019            assert_item_rect(tester, 3, Rect::from_ltrb(0.0, 0.0, 200.0, 600.0));
3020        });
3021    }
3022
3023    #[test]
3024    fn carousel_view_weighted_respects_reverse() {
3025        test_widgets(|tester| {
3026            pump_carousel(
3027                tester,
3028                CarouselView::weighted(vec![4, 3, 2, 1], text_items(10)).reverse(true),
3029            );
3030            tester.pump_and_settle();
3031
3032            let item0_width = 80.0 * 4.0;
3033            let item1_width = 80.0 * 3.0;
3034            let item2_width = 80.0 * 2.0;
3035            assert_item_rect(
3036                tester,
3037                0,
3038                Rect::from_ltrb(800.0 - item0_width, 0.0, 800.0, 600.0),
3039            );
3040            assert_item_rect(
3041                tester,
3042                1,
3043                Rect::from_ltrb(
3044                    800.0 - item0_width - item1_width,
3045                    0.0,
3046                    800.0 - item0_width,
3047                    600.0,
3048                ),
3049            );
3050            assert_item_rect(
3051                tester,
3052                2,
3053                Rect::from_ltrb(
3054                    800.0 - item0_width - item1_width - item2_width,
3055                    0.0,
3056                    800.0 - item0_width - item1_width,
3057                    600.0,
3058                ),
3059            );
3060            assert_item_rect(
3061                tester,
3062                3,
3063                Rect::from_ltrb(
3064                    0.0,
3065                    0.0,
3066                    800.0 - item0_width - item1_width - item2_width,
3067                    600.0,
3068                ),
3069            );
3070        });
3071    }
3072
3073    #[test]
3074    fn carousel_view_weighted_respects_consume_max_weight() {
3075        test_widgets(|tester| {
3076            pump_carousel(
3077                tester,
3078                CarouselView::weighted(vec![1, 2, 4, 2, 1], text_items(10)).item_snapping(true),
3079            );
3080
3081            assert_item_rect(tester, 0, Rect::from_ltrb(240.0, 0.0, 560.0, 600.0));
3082
3083            for _ in 0..7 {
3084                tester.drag(find::by_type::<CarouselView>(), Offset::new(-80.0, 0.0));
3085                tester.pump_and_settle();
3086            }
3087            expect(tester, &get_item(9), finds_one_widget());
3088            assert_item_rect(tester, 9, Rect::from_ltrb(720.0, 0.0, 800.0, 600.0));
3089
3090            for _ in 0..2 {
3091                tester.drag(find::by_type::<CarouselView>(), Offset::new(-80.0, 0.0));
3092                tester.pump_and_settle();
3093            }
3094            expect(tester, &get_item(9), finds_one_widget());
3095            assert_item_rect(tester, 9, Rect::from_ltrb(240.0, 0.0, 560.0, 600.0));
3096        });
3097    }
3098
3099    #[test]
3100    fn the_initial_item_stays_when_the_flex_weights_is_updated() {
3101        test_widgets(|tester| {
3102            let controller = CarouselController::new(&mut tester.cell.borrow_mut(), 3);
3103            let build_carousel = |tester: &mut WidgetTester, flex_weights: Vec<i32>| {
3104                pump_carousel(
3105                    tester,
3106                    CarouselView::weighted(flex_weights, text_items(20))
3107                        .controller(controller.clone())
3108                        .item_snapping(true),
3109                );
3110            };
3111
3112            build_carousel(tester, vec![1, 1, 6, 1, 1]);
3113            tester.pump_and_settle();
3114            expect(tester, &find::text("Item 0"), finds_nothing());
3115            for index in 1..=5 {
3116                expect(
3117                    tester,
3118                    &find::text(&format!("Item {index}")),
3119                    finds_one_widget(),
3120                );
3121            }
3122            let rect3 = tester.get_rect(get_item(3));
3123            assert_eq!(rect3.center().dx(), 400.0);
3124            assert_eq!(rect3.center().dy(), 300.0);
3125            expect(tester, &find::text("Item 6"), finds_nothing());
3126
3127            build_carousel(tester, vec![7, 1]);
3128            tester.pump_and_settle();
3129            expect(tester, &find::text("Item 2"), finds_nothing());
3130            expect(tester, &find::text("Item 3"), finds_one_widget());
3131            expect(tester, &find::text("Item 4"), finds_one_widget());
3132            expect(tester, &find::text("Item 5"), finds_nothing());
3133            assert_item_rect(tester, 3, Rect::from_ltrb(0.0, 0.0, 700.0, 600.0));
3134            assert_item_rect(tester, 4, Rect::from_ltrb(700.0, 0.0, 800.0, 600.0));
3135        });
3136    }
3137
3138    #[test]
3139    fn the_initial_item_stays_when_the_item_extent_is_updated() {
3140        test_widgets(|tester| {
3141            let controller = CarouselController::new(&mut tester.cell.borrow_mut(), 3);
3142            let build_carousel = |tester: &mut WidgetTester, item_extent: f64| {
3143                pump_carousel(
3144                    tester,
3145                    CarouselView::new(item_extent, text_items(20))
3146                        .controller(controller.clone())
3147                        .item_snapping(true),
3148                );
3149            };
3150
3151            for item_extent in [234.0, 400.0, 100.0] {
3152                build_carousel(tester, item_extent);
3153                tester.pump_and_settle();
3154                let bottom_right = tester.get_rect(get_item(3)).bottom_right();
3155                assert_eq!(bottom_right.dx(), item_extent);
3156                assert_eq!(bottom_right.dy(), 600.0);
3157            }
3158        });
3159    }
3160
3161    #[test]
3162    fn carousel_view_on_tap_is_clickable() {
3163        test_widgets(|tester| {
3164            let tapped_index = Rc::new(Cell::new(-1));
3165            pump_carousel(
3166                tester,
3167                CarouselView::new(350.0, text_items(3)).on_tap({
3168                    let tapped_index = Rc::clone(&tapped_index);
3169                    Rc::new(move |_app, index| tapped_index.set(index))
3170                }),
3171            );
3172            tester.pump_and_settle();
3173
3174            tester.tap(find::text("Item 1"));
3175            tester.pump_and_settle();
3176            assert_eq!(tapped_index.get(), 1);
3177
3178            tester.tap(find::text("Item 2"));
3179            tester.pump_and_settle();
3180            assert_eq!(tapped_index.get(), 2);
3181        });
3182    }
3183
3184    #[test]
3185    fn carousel_view_with_enable_splash_false_children_are_directly_interactive() {
3186        test_widgets(|tester| {
3187            let button_pressed = Rc::new(Cell::new(false));
3188            let children = (0..3)
3189                .map(|index| {
3190                    let button_pressed = Rc::clone(&button_pressed);
3191                    Center::new()
3192                        .child(crate::elevated_button::ElevatedButton::new(
3193                            Some(Listener::new(move |_app| button_pressed.set(true))),
3194                            Some(Text::new(format!("Button {index}"))),
3195                        ))
3196                        .into_widget()
3197                })
3198                .collect();
3199            pump_carousel(
3200                tester,
3201                CarouselView::new(350.0, children).enable_splash(false),
3202            );
3203            tester.pump_and_settle();
3204
3205            tester.tap(find::text("Button 1"));
3206            assert!(button_pressed.get());
3207        });
3208    }
3209
3210    #[test]
3211    fn carousel_view_with_enable_splash_true_children_are_not_directly_interactive() {
3212        test_widgets(|tester| {
3213            let button_pressed = Rc::new(Cell::new(false));
3214            let children = (0..3)
3215                .map(|index| {
3216                    let button_pressed = Rc::clone(&button_pressed);
3217                    Center::new()
3218                        .child(crate::elevated_button::ElevatedButton::new(
3219                            Some(Listener::new(move |_app| button_pressed.set(true))),
3220                            Some(Text::new(format!("Button {index}"))),
3221                        ))
3222                        .into_widget()
3223                })
3224                .collect();
3225            pump_carousel(tester, CarouselView::new(350.0, children));
3226            tester.pump_and_settle();
3227
3228            tester.tap_at(tester.get_center(find::text("Button 1")), 1);
3229            assert!(!button_pressed.get());
3230        });
3231    }
3232
3233    #[test]
3234    fn carousel_view_does_not_crash_if_item_extent_is_zero() {
3235        test_widgets(|tester| {
3236            pump_carousel(
3237                tester,
3238                CarouselView::new(
3239                    0.0,
3240                    vec![
3241                        waft_widgets::Container::new()
3242                            .color(Colors::RED.primary())
3243                            .width(100.0)
3244                            .height(100.0)
3245                            .into_widget(),
3246                    ],
3247                ),
3248            );
3249        });
3250    }
3251
3252    #[test]
3253    fn carousel_view_builder_creates_items_lazily() {
3254        test_widgets(|tester| {
3255            let built_items = Rc::new(RefCell::new(Vec::<i32>::new()));
3256            let item_builder: CarouselItemBuilder = {
3257                let built_items = Rc::clone(&built_items);
3258                Rc::new(move |_app, _context, index| {
3259                    built_items.borrow_mut().push(index);
3260                    Some(
3261                        Center::new()
3262                            .child(Text::new(format!("Item {index}")))
3263                            .into_widget(),
3264                    )
3265                })
3266            };
3267            pump_carousel(
3268                tester,
3269                CarouselView::builder(300.0, item_builder).item_count(1000),
3270            );
3271
3272            // Only visible items should be built initially.
3273            assert!(built_items.borrow().len() < 10);
3274            assert!(built_items.borrow().contains(&0));
3275            assert!(built_items.borrow().contains(&1));
3276
3277            // Scroll to a far item.
3278            tester.drag(find::by_type::<CarouselView>(), Offset::new(-2000.0, 0.0));
3279            tester.pump_and_settle();
3280
3281            // Clear built items to see what's built after scrolling.
3282            built_items.borrow_mut().clear();
3283
3284            // Force rebuild by scrolling a bit more.
3285            tester.drag(find::by_type::<CarouselView>(), Offset::new(-300.0, 0.0));
3286            tester.pump();
3287
3288            // Should have built new items, not the initial ones.
3289            assert!(!built_items.borrow().is_empty());
3290            assert!(built_items.borrow().iter().all(|index| *index > 3));
3291        });
3292    }
3293
3294    /// Dart's `runCarouselTest`: `animateToItem` to the middle item and back to the first.
3295    fn run_carousel_test(
3296        flex_weights: Vec<i32>,
3297        consume_max_weight: bool,
3298        number_of_children: i32,
3299        scroll_direction: Axis,
3300        reverse: bool,
3301    ) {
3302        test_widgets(move |tester| {
3303            let controller = CarouselController::new(&mut tester.cell.borrow_mut(), 0);
3304            let carousel = if flex_weights.is_empty() {
3305                CarouselView::new(300.0, text_items(number_of_children))
3306            } else {
3307                CarouselView::weighted(flex_weights.clone(), text_items(number_of_children))
3308                    .consume_max_weight(consume_max_weight)
3309            };
3310            pump_carousel(
3311                tester,
3312                carousel
3313                    .scroll_direction(scroll_direction)
3314                    .reverse(reverse)
3315                    .controller(controller.clone())
3316                    .item_snapping(true),
3317            );
3318
3319            // The index of the middle item, reversed for a reversed list.
3320            let middle_index = if reverse {
3321                number_of_children - 1 - (f64::from(number_of_children) / 2.0).round() as i32
3322            } else {
3323                (f64::from(number_of_children) / 2.0).round() as i32
3324            };
3325            let animate = |tester: &mut WidgetTester, index: i32| {
3326                drop(controller.handle().animate_to_item(
3327                    &mut tester.cell.borrow_mut(),
3328                    index,
3329                    Duration::from_millis(100),
3330                    Curves::ease_in_out(),
3331                ));
3332            };
3333            animate(tester, middle_index);
3334            tester.pump_and_settle();
3335
3336            // Verify that the middle item is visible.
3337            expect(
3338                tester,
3339                &find::text(&format!("Item {middle_index}")),
3340                finds_one_widget(),
3341            );
3342
3343            // Scroll to the first item.
3344            animate(tester, 0);
3345            tester.pump_and_settle();
3346
3347            // Verify that the first item is visible.
3348            expect(tester, &find::text("Item 0"), finds_one_widget());
3349        });
3350    }
3351
3352    #[test]
3353    fn carousel_controller_animate_to_item_weighted_horizontal_not_reversed() {
3354        run_carousel_test(vec![7, 1], true, 20, Axis::Horizontal, false);
3355    }
3356
3357    #[test]
3358    fn carousel_controller_animate_to_item_weighted_horizontal_reversed() {
3359        run_carousel_test(vec![7, 1], true, 20, Axis::Horizontal, true);
3360    }
3361
3362    #[test]
3363    fn carousel_controller_animate_to_item_weighted_vertical_not_reversed() {
3364        run_carousel_test(vec![7, 1], true, 20, Axis::Vertical, false);
3365    }
3366
3367    #[test]
3368    fn carousel_controller_animate_to_item_weighted_vertical_reversed() {
3369        run_carousel_test(vec![7, 1], true, 20, Axis::Vertical, true);
3370    }
3371
3372    #[test]
3373    fn carousel_controller_animate_to_item_weighted_not_consuming_max_weight() {
3374        run_carousel_test(vec![1, 7], false, 20, Axis::Horizontal, false);
3375    }
3376
3377    #[test]
3378    fn carousel_controller_animate_to_item_not_weighted() {
3379        run_carousel_test(Vec::new(), true, 20, Axis::Horizontal, false);
3380    }
3381
3382    #[test]
3383    fn carousel_view_on_index_changed_reports_the_leading_item_after_animation() {
3384        test_widgets(|tester| {
3385            let controller = CarouselController::new(&mut tester.cell.borrow_mut(), 0);
3386            let leading_index = Rc::new(Cell::new(0));
3387            pump_carousel(
3388                tester,
3389                CarouselView::new(300.0, text_items(6))
3390                    .controller(controller.clone())
3391                    .on_index_changed({
3392                        let leading_index = Rc::clone(&leading_index);
3393                        Rc::new(move |_app, index| leading_index.set(index))
3394                    }),
3395            );
3396            tester.pump_and_settle();
3397
3398            drop(controller.handle().animate_to_item(
3399                &mut tester.cell.borrow_mut(),
3400                3,
3401                Duration::from_millis(100),
3402                Curves::ease_in_out(),
3403            ));
3404            tester.pump_and_settle();
3405            assert_eq!(leading_index.get(), 3);
3406            assert_eq!(controller.handle().leading_item(&tester.cell.borrow()), 3);
3407        });
3408    }
3409
3410    #[test]
3411    fn carousel_view_infinite_animate_to_item_beyond_the_item_count() {
3412        test_widgets(|tester| {
3413            let controller = CarouselController::new(&mut tester.cell.borrow_mut(), 0);
3414            pump_carousel(
3415                tester,
3416                CarouselView::new(200.0, text_items(3))
3417                    .infinite(true)
3418                    .controller(controller.clone()),
3419            );
3420
3421            // Verify animating to an index beyond the array length.
3422            drop(controller.handle().animate_to_item(
3423                &mut tester.cell.borrow_mut(),
3424                5,
3425                Duration::from_millis(300),
3426                Curves::ease(),
3427            ));
3428            tester.pump_and_settle();
3429
3430            // Should show last item 2 times based on size.
3431            assert!(find::text_containing("Item 2").evaluate(tester).len() >= 2);
3432        });
3433    }
3434
3435    #[test]
3436    fn carousel_view_infinite_scrolling() {
3437        test_widgets(|tester| {
3438            pump_carousel(
3439                tester,
3440                CarouselView::new(200.0, text_items(3)).infinite(true),
3441            );
3442
3443            // Initial state: viewport is 800 wide, each item is 200 wide.
3444            // Visible items: Item 0 at [0-200], Item 1 at [200-400], Item 2 at [400-600],
3445            // Item 0 at [600-800] (wraps)
3446            expect(
3447                tester,
3448                &find::text("Item 0"),
3449                waft_widgets::testing::finds_n_widgets(2),
3450            );
3451            expect(tester, &find::text("Item 1"), finds_one_widget());
3452            expect(tester, &find::text("Item 2"), finds_one_widget());
3453            assert_eq!(
3454                tester.get_rect(get_item(0).first()),
3455                Rect::from_ltrb(0.0, 0.0, 200.0, 600.0)
3456            );
3457            assert_eq!(
3458                tester.get_rect(get_item(1).first()),
3459                Rect::from_ltrb(200.0, 0.0, 400.0, 600.0)
3460            );
3461            assert_eq!(
3462                tester.get_rect(get_item(2).first()),
3463                Rect::from_ltrb(400.0, 0.0, 600.0, 600.0)
3464            );
3465
3466            // Scroll forward by 400 pixels (dragging left).
3467            tester.drag(find::by_type::<CarouselView>(), Offset::new(-400.0, 0.0));
3468            tester.pump_and_settle();
3469
3470            // Visible items: Item 2 at [0-200], Item 0 at [200-400], Item 1 at [400-600],
3471            // Item 2 at [600-800].
3472            expect(tester, &find::text("Item 0"), finds_one_widget());
3473            expect(tester, &find::text("Item 1"), finds_one_widget());
3474            expect(
3475                tester,
3476                &find::text("Item 2"),
3477                waft_widgets::testing::finds_n_widgets(2),
3478            );
3479            assert_eq!(
3480                tester.get_rect(get_item(2).first()),
3481                Rect::from_ltrb(0.0, 0.0, 200.0, 600.0)
3482            );
3483            assert_eq!(
3484                tester.get_rect(get_item(0).first()),
3485                Rect::from_ltrb(200.0, 0.0, 400.0, 600.0)
3486            );
3487            assert_eq!(
3488                tester.get_rect(get_item(1).first()),
3489                Rect::from_ltrb(400.0, 0.0, 600.0, 600.0)
3490            );
3491        });
3492    }
3493
3494    #[test]
3495    fn carousel_view_item_clip_behavior_defaults_to_anti_alias() {
3496        test_widgets(|tester| {
3497            pump_carousel(tester, CarouselView::new(300.0, text_items(3)));
3498            let material = find::descendant(
3499                find::by_type::<CarouselView>(),
3500                find::by_type::<crate::material::Material>(),
3501            )
3502            .first();
3503            tester.widget(material, |material: &crate::material::Material| {
3504                assert_eq!(material.clip_behavior, Clip::AntiAlias);
3505            });
3506        });
3507    }
3508
3509    #[test]
3510    fn carousel_view_item_clip_behavior_respects_custom_item_clip_behavior() {
3511        test_widgets(|tester| {
3512            pump_carousel(
3513                tester,
3514                CarouselView::new(300.0, text_items(3)).item_clip_behavior(Clip::HardEdge),
3515            );
3516            let material = find::descendant(
3517                find::by_type::<CarouselView>(),
3518                find::by_type::<crate::material::Material>(),
3519            )
3520            .first();
3521            tester.widget(material, |material: &crate::material::Material| {
3522                assert_eq!(material.clip_behavior, Clip::HardEdge);
3523            });
3524        });
3525    }
3526
3527    /// Dart's `tester.drag(finder, offset, kind: PointerDeviceKind.trackpad)`: a pan-zoom gesture
3528    /// whose pan is the whole `offset`, with no touch slop taken off it.
3529    fn trackpad_drag(tester: &mut WidgetTester, target: Finder, offset: Offset) {
3530        use waft_embedder::{PointerChange, PointerData, PointerDataPacket, PointerDeviceKind};
3531        let start = tester.get_center(target);
3532        let pointer = tester.next_pointer();
3533        let ratio = tester.device_pixel_ratio();
3534        let send = |tester: &mut WidgetTester, change: PointerChange, pan: Offset| {
3535            {
3536                let mut app = tester.cell.borrow_mut();
3537                waft_gestures::GestureBinding::instance(&mut app).handle_pointer_data_packet(
3538                    &mut app,
3539                    PointerDataPacket::new(vec![PointerData {
3540                        change,
3541                        kind: PointerDeviceKind::Trackpad,
3542                        time_stamp: Duration::ZERO,
3543                        device: pointer,
3544                        pointer_identifier: pointer,
3545                        physical_x: start.dx() * ratio,
3546                        physical_y: start.dy() * ratio,
3547                        pan_x: pan.dx() * ratio,
3548                        pan_y: pan.dy() * ratio,
3549                        pan_delta_x: pan.dx() * ratio,
3550                        pan_delta_y: pan.dy() * ratio,
3551                        scale: 1.0,
3552                        ..PointerData::default()
3553                    }]),
3554                );
3555                app.drain_microtasks();
3556            }
3557            tester.cell.checkpoint();
3558        };
3559        send(tester, PointerChange::PanZoomStart, Offset::ZERO);
3560        send(tester, PointerChange::PanZoomUpdate, offset);
3561        send(tester, PointerChange::PanZoomEnd, offset);
3562    }
3563
3564    #[test]
3565    fn carousel_view_respects_scrolling_direction_vertical() {
3566        test_widgets(|tester| {
3567            pump_carousel(
3568                tester,
3569                CarouselView::new(200.0, text_items(10))
3570                    .padding(EdgeInsets::ZERO)
3571                    .scroll_direction(Axis::Vertical),
3572            );
3573            tester.pump_and_settle();
3574
3575            expect_items(tester, &[0, 1, 2], &[3]);
3576            assert_item_rect(tester, 0, Rect::from_ltrb(0.0, 0.0, 800.0, 200.0));
3577
3578            trackpad_drag(
3579                tester,
3580                find::by_type::<CarouselView>(),
3581                Offset::new(0.0, -200.0),
3582            );
3583            tester.pump_and_settle();
3584            expect_items(tester, &[3], &[0]);
3585        });
3586    }
3587
3588    #[test]
3589    fn carousel_view_weighted_respects_scrolling_direction_vertical() {
3590        test_widgets(|tester| {
3591            pump_carousel(
3592                tester,
3593                CarouselView::weighted(vec![3, 2, 1], text_items(10))
3594                    .padding(EdgeInsets::ZERO)
3595                    .scroll_direction(Axis::Vertical),
3596            );
3597            tester.pump_and_settle();
3598
3599            expect_items(tester, &[0, 1, 2], &[3]);
3600            assert_item_rect(tester, 0, Rect::from_ltrb(0.0, 0.0, 800.0, 300.0));
3601
3602            trackpad_drag(
3603                tester,
3604                find::by_type::<CarouselView>(),
3605                Offset::new(0.0, -300.0),
3606            );
3607            tester.pump_and_settle();
3608            expect_items(tester, &[3], &[0]);
3609        });
3610    }
3611
3612    #[test]
3613    fn carousel_view_weighted_respects_scrolling_direction_vertical_and_item_snapping() {
3614        test_widgets(|tester| {
3615            pump_carousel(
3616                tester,
3617                CarouselView::weighted(vec![3, 2, 1], text_items(10))
3618                    .item_snapping(true)
3619                    .scroll_direction(Axis::Vertical),
3620            );
3621            tester.pump_and_settle();
3622
3623            expect_items(tester, &[0, 1, 2], &[3]);
3624            assert_item_rect(tester, 0, Rect::from_ltrb(0.0, 0.0, 800.0, 300.0));
3625
3626            // Less than half of the leading item: it goes back to its position.
3627            trackpad_drag(
3628                tester,
3629                find::by_type::<CarouselView>(),
3630                Offset::new(0.0, -149.0),
3631            );
3632            tester.pump_and_settle();
3633            expect_items(tester, &[0, 1, 2], &[3]);
3634
3635            // More than half of it: it keeps scrolling and is gone when the animation ends.
3636            trackpad_drag(
3637                tester,
3638                find::by_type::<CarouselView>(),
3639                Offset::new(0.0, -151.0),
3640            );
3641            tester.pump_and_settle();
3642            expect_items(tester, &[3], &[0]);
3643        });
3644    }
3645
3646    #[test]
3647    fn carousel_view_weighted_respects_reverse_and_vertical_scroll_direction() {
3648        test_widgets(|tester| {
3649            pump_carousel(
3650                tester,
3651                CarouselView::weighted(vec![4, 3, 2, 1], text_items(10))
3652                    .reverse(true)
3653                    .scroll_direction(Axis::Vertical),
3654            );
3655            tester.pump_and_settle();
3656
3657            let item0_height = 60.0 * 4.0;
3658            let item1_height = 60.0 * 3.0;
3659            let item2_height = 60.0 * 2.0;
3660            expect_items(tester, &[0, 1, 2, 3], &[]);
3661            assert_item_rect(
3662                tester,
3663                0,
3664                Rect::from_ltrb(0.0, 600.0 - item0_height, 800.0, 600.0),
3665            );
3666            assert_item_rect(
3667                tester,
3668                1,
3669                Rect::from_ltrb(
3670                    0.0,
3671                    600.0 - item0_height - item1_height,
3672                    800.0,
3673                    600.0 - item0_height,
3674                ),
3675            );
3676            assert_item_rect(
3677                tester,
3678                2,
3679                Rect::from_ltrb(
3680                    0.0,
3681                    600.0 - item0_height - item1_height - item2_height,
3682                    800.0,
3683                    600.0 - item0_height - item1_height,
3684                ),
3685            );
3686            assert_item_rect(
3687                tester,
3688                3,
3689                Rect::from_ltrb(
3690                    0.0,
3691                    0.0,
3692                    800.0,
3693                    600.0 - item0_height - item1_height - item2_height,
3694                ),
3695            );
3696        });
3697    }
3698
3699    #[test]
3700    fn carousel_view_weighted_respects_reverse_vertical_scroll_direction_and_item_snapping() {
3701        test_widgets(|tester| {
3702            pump_carousel(
3703                tester,
3704                CarouselView::weighted(vec![4, 3, 2, 1], text_items(10))
3705                    .reverse(true)
3706                    .scroll_direction(Axis::Vertical)
3707                    .item_snapping(true),
3708            );
3709            tester.pump_and_settle();
3710
3711            expect_items(tester, &[0, 1, 2, 3], &[4]);
3712            assert_item_rect(tester, 0, Rect::from_ltrb(0.0, 360.0, 800.0, 600.0));
3713
3714            trackpad_drag(
3715                tester,
3716                find::by_type::<CarouselView>(),
3717                Offset::new(0.0, 240.0 / 2.0 - 1.0),
3718            );
3719            tester.pump_and_settle();
3720            expect_items(tester, &[0, 1, 2, 3], &[4]);
3721
3722            trackpad_drag(
3723                tester,
3724                find::by_type::<CarouselView>(),
3725                Offset::new(0.0, 240.0 / 2.0 + 1.0),
3726            );
3727            tester.pump_and_settle();
3728            expect_items(tester, &[4], &[0]);
3729        });
3730    }
3731
3732    #[test]
3733    fn carousel_view_respects_shrink_extent() {
3734        test_widgets(|tester| {
3735            pump_carousel(
3736                tester,
3737                CarouselView::new(350.0, text_items(10)).shrink_extent(300.0),
3738            );
3739            tester.pump_and_settle();
3740
3741            assert_item_rect(tester, 0, Rect::from_ltrb(0.0, 0.0, 350.0, 600.0));
3742            assert_item_rect(tester, 1, Rect::from_ltrb(350.0, 0.0, 700.0, 600.0));
3743            // The extent of item 2 is 300, and only 100 is on screen.
3744            assert_item_rect(tester, 2, Rect::from_ltrb(700.0, 0.0, 1000.0, 600.0));
3745
3746            trackpad_drag(
3747                tester,
3748                find::by_type::<CarouselView>(),
3749                Offset::new(-50.0, 0.0),
3750            );
3751            tester.pump();
3752            // Item 0 is pinned and changes size from 350 to 300.
3753            assert_item_rect(tester, 0, Rect::from_ltrb(0.0, 0.0, 300.0, 600.0));
3754            // Dragging on, the extent of item 0 stays 300 and part of it leaves the screen.
3755            trackpad_drag(
3756                tester,
3757                find::by_type::<CarouselView>(),
3758                Offset::new(-50.0, 0.0),
3759            );
3760            tester.pump();
3761            assert_item_rect(tester, 0, Rect::from_ltrb(-50.0, 0.0, 250.0, 600.0));
3762        });
3763    }
3764
3765    #[test]
3766    fn while_scrolling_one_extra_item_shows_at_the_end_of_the_screen_during_items_transition() {
3767        test_widgets(|tester| {
3768            pump_carousel(
3769                tester,
3770                CarouselView::weighted(vec![1, 2, 4, 2, 1], text_items(10))
3771                    .consume_max_weight(false),
3772            );
3773            tester.pump_and_settle();
3774
3775            expect_items(tester, &[0, 1, 2, 3, 4], &[]);
3776
3777            // Dragging the first item to the middle: the progress of its size change is 50%,
3778            // and its original width is 80.
3779            trackpad_drag(tester, get_item(0), Offset::new(-40.0, 0.0));
3780            tester.pump();
3781            let width =
3782                |tester: &WidgetTester, index: i32| tester.get_rect(get_item(index)).width();
3783            assert_eq!(width(tester, 0), 40.0);
3784            assert_eq!(width(tester, 1), 160.0 - 0.5 * (160.0 - 80.0));
3785            assert_eq!(width(tester, 2), 320.0 - 0.5 * (320.0 - 160.0));
3786            assert_eq!(width(tester, 3), 160.0 + 0.5 * (320.0 - 160.0));
3787            assert_eq!(width(tester, 4), 80.0 + 0.5 * (160.0 - 80.0));
3788
3789            let sum: f64 = (0..5).map(|index| width(tester, index)).sum();
3790            assert!(sum < 800.0);
3791            let difference = 800.0 - sum;
3792
3793            // One more item shows to fill the rest of the viewport.
3794            expect_items(tester, &[5], &[]);
3795            assert_eq!(width(tester, 5), difference);
3796        });
3797    }
3798
3799    fn texts_of(count: i32) -> Vec<WidgetRef> {
3800        (0..count)
3801            .map(|index| Text::new(format!("Item {index}")).into_widget())
3802            .collect()
3803    }
3804
3805    fn scrollable_state(tester: &WidgetTester) -> Handle<waft_widgets::ScrollableState> {
3806        let scrollable = tester.element(find::by_type::<waft_widgets::Scrollable>());
3807        scrollable
3808            .state_handle::<waft_widgets::ScrollableState>(&tester.cell.borrow())
3809            .expect("a Scrollable element holds a ScrollableState")
3810    }
3811
3812    fn found_n(tester: &WidgetTester, text: &str, count: usize) {
3813        expect(
3814            tester,
3815            &find::text(text),
3816            waft_widgets::testing::finds_n_widgets(count),
3817        );
3818    }
3819
3820    fn animate_to(
3821        tester: &mut WidgetTester,
3822        controller: &Ref<CarouselController>,
3823        item: i32,
3824        milliseconds: u64,
3825    ) {
3826        drop(controller.handle().animate_to_item(
3827            &mut tester.cell.borrow_mut(),
3828            item,
3829            Duration::from_millis(milliseconds),
3830            Curves::linear(),
3831        ));
3832        tester.pump_and_settle();
3833    }
3834
3835    fn leading_item(tester: &WidgetTester, controller: &Ref<CarouselController>) -> i32 {
3836        controller.handle().leading_item(&tester.cell.borrow())
3837    }
3838
3839    fn offset(tester: &WidgetTester, controller: &Ref<CarouselController>) -> f64 {
3840        controller.handle().offset(&tester.cell.borrow())
3841    }
3842
3843    /// Dart's `buildCarousel` of the `onIndexChanged` group.
3844    fn index_carousel(
3845        weighted: Option<Vec<i32>>,
3846        reverse: bool,
3847        item_snapping: bool,
3848        item_count: i32,
3849        controller: &Ref<CarouselController>,
3850        leading_index: &Rc<Cell<i32>>,
3851    ) -> CarouselView {
3852        let carousel = match weighted {
3853            Some(weights) => CarouselView::weighted(weights, texts_of(item_count)),
3854            None => CarouselView::new(300.0, texts_of(item_count)),
3855        };
3856        let leading_index = Rc::clone(leading_index);
3857        carousel
3858            .reverse(reverse)
3859            .item_snapping(item_snapping)
3860            .controller(controller.clone())
3861            .on_index_changed(Rc::new(move |_app, index| leading_index.set(index)))
3862    }
3863
3864    #[test]
3865    fn carousel_view_shows_the_correct_item_after_animation() {
3866        test_widgets(|tester| {
3867            let controller = CarouselController::new(&mut tester.cell.borrow_mut(), 0);
3868            let leading_index = Rc::new(Cell::new(0));
3869            pump_carousel(
3870                tester,
3871                index_carousel(None, false, false, 6, &controller, &leading_index),
3872            );
3873            tester.pump_and_settle();
3874
3875            animate_to(tester, &controller, 3, 200);
3876            assert_eq!(leading_item(tester, &controller), 3);
3877            assert_eq!(leading_index.get(), 3);
3878
3879            animate_to(tester, &controller, 1, 200);
3880            assert_eq!(leading_item(tester, &controller), 1);
3881            assert_eq!(leading_index.get(), 1);
3882        });
3883    }
3884
3885    #[test]
3886    fn carousel_view_weighted_shows_the_correct_item_after_animation_with_symmetric_flex_weights() {
3887        test_widgets(|tester| {
3888            let controller = CarouselController::new(&mut tester.cell.borrow_mut(), 0);
3889            let leading_index = Rc::new(Cell::new(0));
3890            pump_carousel(
3891                tester,
3892                index_carousel(
3893                    Some(vec![2, 5, 2]),
3894                    false,
3895                    false,
3896                    6,
3897                    &controller,
3898                    &leading_index,
3899                ),
3900            );
3901            tester.pump_and_settle();
3902
3903            // Item 4 goes to the first position with the max weight (5), so item 3 leads.
3904            animate_to(tester, &controller, 4, 200);
3905            assert_eq!(leading_item(tester, &controller), 3);
3906            assert_eq!(leading_index.get(), 3);
3907            expect(tester, &find::text("Item 3"), finds_one_widget());
3908        });
3909    }
3910
3911    #[test]
3912    fn carousel_view_weighted_shows_the_correct_item_after_animation_with_asymmetric_flex_weights()
3913    {
3914        test_widgets(|tester| {
3915            let controller = CarouselController::new(&mut tester.cell.borrow_mut(), 0);
3916            let leading_index = Rc::new(Cell::new(0));
3917            pump_carousel(
3918                tester,
3919                index_carousel(
3920                    Some(vec![1, 2, 3, 4]),
3921                    false,
3922                    false,
3923                    6,
3924                    &controller,
3925                    &leading_index,
3926                ),
3927            );
3928            tester.pump_and_settle();
3929
3930            animate_to(tester, &controller, 2, 200);
3931            assert_eq!(leading_item(tester, &controller), 0);
3932            assert_eq!(leading_index.get(), 0);
3933        });
3934    }
3935
3936    #[test]
3937    fn carousel_view_shows_the_correct_item_after_dragging() {
3938        test_widgets(|tester| {
3939            let controller = CarouselController::new(&mut tester.cell.borrow_mut(), 0);
3940            let leading_index = Rc::new(Cell::new(0));
3941            pump_carousel(
3942                tester,
3943                index_carousel(
3944                    Some(vec![2, 5, 2]),
3945                    false,
3946                    true,
3947                    5,
3948                    &controller,
3949                    &leading_index,
3950                ),
3951            );
3952            tester.pump_and_settle();
3953
3954            tester.drag(find::by_type::<CarouselView>(), Offset::new(-300.0, 0.0));
3955            tester.pump_and_settle();
3956            assert_eq!(leading_item(tester, &controller), 1);
3957            assert_eq!(leading_index.get(), 1);
3958        });
3959    }
3960
3961    #[test]
3962    fn carousel_view_with_reverse_reports_the_correct_leading_item_after_animation() {
3963        test_widgets(|tester| {
3964            let controller = CarouselController::new(&mut tester.cell.borrow_mut(), 0);
3965            let leading_index = Rc::new(Cell::new(0));
3966            pump_carousel(
3967                tester,
3968                index_carousel(None, true, false, 6, &controller, &leading_index),
3969            );
3970            tester.pump_and_settle();
3971
3972            animate_to(tester, &controller, 2, 200);
3973            assert_eq!(leading_item(tester, &controller), 2);
3974            assert_eq!(leading_index.get(), 2);
3975        });
3976    }
3977
3978    #[test]
3979    fn carousel_view_weighted_with_reverse_reports_the_correct_leading_item_after_drag() {
3980        test_widgets(|tester| {
3981            let controller = CarouselController::new(&mut tester.cell.borrow_mut(), 0);
3982            let leading_index = Rc::new(Cell::new(0));
3983            pump_carousel(
3984                tester,
3985                index_carousel(
3986                    Some(vec![2, 5, 2]),
3987                    true,
3988                    true,
3989                    5,
3990                    &controller,
3991                    &leading_index,
3992                ),
3993            );
3994            tester.pump_and_settle();
3995
3996            tester.drag(find::by_type::<CarouselView>(), Offset::new(300.0, 0.0));
3997            tester.pump_and_settle();
3998            assert_eq!(leading_item(tester, &controller), 1);
3999            assert_eq!(leading_index.get(), 1);
4000        });
4001    }
4002
4003    #[test]
4004    fn carousel_view_infinite_scrolling_supports_bidirectional_scrolling() {
4005        test_widgets(|tester| {
4006            pump_carousel(
4007                tester,
4008                CarouselView::new(200.0, text_items(3)).infinite(true),
4009            );
4010
4011            found_n(tester, "Item 0", 2);
4012            found_n(tester, "Item 1", 1);
4013            found_n(tester, "Item 2", 1);
4014            let initial_item0_left = tester.get_rect(get_item(0).first()).left;
4015
4016            tester.drag(find::by_type::<CarouselView>(), Offset::new(200.0, 0.0));
4017            tester.pump_and_settle();
4018
4019            // After scrolling backward, item 2 appears twice.
4020            found_n(tester, "Item 2", 2);
4021            found_n(tester, "Item 0", 1);
4022            found_n(tester, "Item 1", 1);
4023            let after_item2_left = tester.get_rect(get_item(2).first()).left;
4024            waft_widgets::testing::assert_more_or_less_equals_within(
4025                after_item2_left,
4026                initial_item0_left,
4027                10.0,
4028            );
4029
4030            tester.drag(find::by_type::<CarouselView>(), Offset::new(-200.0, 0.0));
4031            tester.pump_and_settle();
4032            found_n(tester, "Item 0", 2);
4033            found_n(tester, "Item 1", 1);
4034            found_n(tester, "Item 2", 1);
4035        });
4036    }
4037
4038    #[test]
4039    fn carousel_view_weighted_infinite_scrolling() {
4040        test_widgets(|tester| {
4041            pump_carousel(
4042                tester,
4043                CarouselView::weighted(vec![1, 2, 1], text_items(3)).infinite(true),
4044            );
4045
4046            found_n(tester, "Item 0", 1);
4047            found_n(tester, "Item 1", 1);
4048            // Item 2 wraps to fill the padding area.
4049            found_n(tester, "Item 2", 1);
4050            assert_eq!(
4051                tester.get_rect(get_item(2).first()),
4052                Rect::from_ltrb(0.0, 0.0, 200.0, 600.0)
4053            );
4054            assert_eq!(
4055                tester.get_rect(get_item(0).first()),
4056                Rect::from_ltrb(200.0, 0.0, 600.0, 600.0)
4057            );
4058            assert_eq!(
4059                tester.get_rect(get_item(1).first()),
4060                Rect::from_ltrb(600.0, 0.0, 800.0, 600.0)
4061            );
4062
4063            tester.drag(find::by_type::<CarouselView>(), Offset::new(-400.0, 0.0));
4064            tester.pump_and_settle();
4065            found_n(tester, "Item 1", 1);
4066            found_n(tester, "Item 2", 1);
4067        });
4068    }
4069
4070    #[test]
4071    fn carousel_view_weighted_with_hero_layout_and_infinite_scrolling() {
4072        test_widgets(|tester| {
4073            pump_carousel(
4074                tester,
4075                CarouselView::weighted(vec![1, 7, 1], text_items(6)).infinite(true),
4076            );
4077
4078            found_n(tester, "Item 0", 1);
4079            found_n(tester, "Item 1", 1);
4080            expect(tester, &find::text("Item 2"), finds_nothing());
4081            let rect0 = tester.get_rect(get_item(0).first());
4082            waft_widgets::testing::assert_more_or_less_equals_within(rect0.left, 800.0 / 9.0, 0.1);
4083            waft_widgets::testing::assert_more_or_less_equals_within(
4084                rect0.width(),
4085                800.0 * 7.0 / 9.0,
4086                0.1,
4087            );
4088
4089            tester.drag(find::by_type::<CarouselView>(), Offset::new(-622.0, 0.0));
4090            tester.pump_and_settle();
4091            found_n(tester, "Item 1", 1);
4092            found_n(tester, "Item 2", 1);
4093
4094            tester.drag(find::by_type::<CarouselView>(), Offset::new(622.0, 0.0));
4095            tester.pump_and_settle();
4096            found_n(tester, "Item 0", 1);
4097            found_n(tester, "Item 1", 1);
4098
4099            tester.drag(find::by_type::<CarouselView>(), Offset::new(200.0, 0.0));
4100            tester.pump_and_settle();
4101            found_n(tester, "Item 5", 1);
4102        });
4103    }
4104
4105    #[test]
4106    fn carousel_view_weighted_with_multi_browse_layout_and_infinite_scrolling() {
4107        test_widgets(|tester| {
4108            pump_carousel(
4109                tester,
4110                CarouselView::weighted(vec![1, 2, 3, 2, 1], text_items(10))
4111                    .infinite(true)
4112                    .consume_max_weight(false),
4113            );
4114
4115            found_n(tester, "Item 0", 1);
4116            found_n(tester, "Item 1", 1);
4117            found_n(tester, "Item 2", 1);
4118
4119            tester.drag(find::by_type::<CarouselView>(), Offset::new(-89.0, 0.0));
4120            tester.pump_and_settle();
4121            found_n(tester, "Item 1", 1);
4122            found_n(tester, "Item 2", 1);
4123            found_n(tester, "Item 3", 1);
4124
4125            tester.drag(find::by_type::<CarouselView>(), Offset::new(200.0, 0.0));
4126            tester.pump_and_settle();
4127            found_n(tester, "Item 0", 1);
4128        });
4129    }
4130
4131    #[test]
4132    fn carousel_view_infinite_leading_item_wraps_correctly_when_scrolling_forwards() {
4133        test_widgets(|tester| {
4134            let controller = CarouselController::new(&mut tester.cell.borrow_mut(), 0);
4135            let reported = Rc::new(RefCell::new(Vec::new()));
4136            pump_carousel(
4137                tester,
4138                CarouselView::new(200.0, text_items(5))
4139                    .item_snapping(true)
4140                    .infinite(true)
4141                    .controller(controller.clone())
4142                    .on_index_changed({
4143                        let reported = Rc::clone(&reported);
4144                        Rc::new(move |_app, index| reported.borrow_mut().push(index))
4145                    }),
4146            );
4147
4148            let initial_item = leading_item(tester, &controller);
4149            for i in 1..=7 {
4150                tester.drag(find::by_type::<CarouselView>(), Offset::new(-200.0, 0.0));
4151                tester.pump_and_settle();
4152                assert_eq!(leading_item(tester, &controller), (initial_item + i) % 5);
4153            }
4154
4155            assert!(reported.borrow().len() >= 7);
4156            assert!(
4157                reported
4158                    .borrow()
4159                    .iter()
4160                    .all(|index| (0..=4).contains(index))
4161            );
4162        });
4163    }
4164
4165    #[test]
4166    fn carousel_view_infinite_leading_item_wraps_correctly_when_scrolling_backwards() {
4167        test_widgets(|tester| {
4168            let controller = CarouselController::new(&mut tester.cell.borrow_mut(), 0);
4169            let reported = Rc::new(RefCell::new(Vec::new()));
4170            pump_carousel(
4171                tester,
4172                CarouselView::new(200.0, text_items(5))
4173                    .item_snapping(true)
4174                    .infinite(true)
4175                    .controller(controller.clone())
4176                    .on_index_changed({
4177                        let reported = Rc::clone(&reported);
4178                        Rc::new(move |_app, index| reported.borrow_mut().push(index))
4179                    }),
4180            );
4181
4182            let initial_item = leading_item(tester, &controller);
4183            for i in 1..=7 {
4184                tester.drag(find::by_type::<CarouselView>(), Offset::new(200.0, 0.0));
4185                tester.pump_and_settle();
4186                let expected = ((initial_item - i) % 5 + 5) % 5;
4187                assert_eq!(leading_item(tester, &controller), expected);
4188            }
4189
4190            assert!(reported.borrow().len() >= 7);
4191            assert!(
4192                reported
4193                    .borrow()
4194                    .iter()
4195                    .all(|index| (0..=4).contains(index))
4196            );
4197        });
4198    }
4199
4200    #[test]
4201    fn carousel_view_infinite_animate_to_item_scrolls_forward_to_next_item() {
4202        test_widgets(|tester| {
4203            let controller = CarouselController::new(&mut tester.cell.borrow_mut(), 0);
4204            pump_carousel(
4205                tester,
4206                CarouselView::new(200.0, text_items(5))
4207                    .item_snapping(true)
4208                    .infinite(true)
4209                    .controller(controller.clone()),
4210            );
4211
4212            let initial_offset = offset(tester, &controller);
4213            let initial_item = leading_item(tester, &controller);
4214            animate_to(tester, &controller, initial_item + 1, 200);
4215            assert_eq!(leading_item(tester, &controller), (initial_item + 1) % 5);
4216            assert!(offset(tester, &controller) > initial_offset);
4217        });
4218    }
4219
4220    #[test]
4221    fn carousel_view_weighted_infinite_animate_to_item_scrolls_forward_to_next_item() {
4222        test_widgets(|tester| {
4223            let controller = CarouselController::new(&mut tester.cell.borrow_mut(), 0);
4224            pump_carousel(
4225                tester,
4226                CarouselView::weighted(vec![1, 7, 1], text_items(5))
4227                    .item_snapping(true)
4228                    .infinite(true)
4229                    .controller(controller.clone()),
4230            );
4231
4232            let initial_offset = offset(tester, &controller);
4233            animate_to(tester, &controller, 1, 200);
4234            assert!(offset(tester, &controller) > initial_offset);
4235            found_n(tester, "Item 1", 1);
4236        });
4237    }
4238
4239    #[test]
4240    fn carousel_view_infinite_animate_to_item_scrolls_forward_even_to_item_just_behind() {
4241        test_widgets(|tester| {
4242            let controller = CarouselController::new(&mut tester.cell.borrow_mut(), 0);
4243            pump_carousel(
4244                tester,
4245                CarouselView::new(200.0, text_items(5))
4246                    .item_snapping(true)
4247                    .infinite(true)
4248                    .controller(controller.clone()),
4249            );
4250
4251            animate_to(tester, &controller, 2, 200);
4252            assert_eq!(leading_item(tester, &controller), 2);
4253            let offset_at_item2 = offset(tester, &controller);
4254
4255            animate_to(tester, &controller, 1, 200);
4256            assert_eq!(leading_item(tester, &controller), 1);
4257            assert!(offset(tester, &controller) > offset_at_item2);
4258        });
4259    }
4260
4261    #[test]
4262    fn carousel_view_weighted_infinite_animate_to_item_scrolls_forward_even_to_item_just_behind() {
4263        test_widgets(|tester| {
4264            let controller = CarouselController::new(&mut tester.cell.borrow_mut(), 0);
4265            pump_carousel(
4266                tester,
4267                CarouselView::weighted(vec![1, 7, 1], text_items(5))
4268                    .item_snapping(true)
4269                    .infinite(true)
4270                    .controller(controller.clone()),
4271            );
4272
4273            animate_to(tester, &controller, 2, 200);
4274            let offset_at_item2 = offset(tester, &controller);
4275
4276            animate_to(tester, &controller, 1, 200);
4277            assert!(offset(tester, &controller) > offset_at_item2);
4278            found_n(tester, "Item 1", 1);
4279        });
4280    }
4281
4282    fn rtl_carousel(reverse: bool) -> CarouselView {
4283        let item = |index: i32| {
4284            Center::new()
4285                .key(waft_foundation::ValueKey::new(index).into())
4286                .child(Text::new(format!("Item {index}")))
4287                .into_widget()
4288        };
4289        CarouselView::new(600.0, vec![item(0), item(1)]).reverse(reverse)
4290    }
4291
4292    fn pump_rtl_carousel(tester: &mut WidgetTester, reverse: bool) {
4293        let theme = ThemeData::builder().build(&tester.cell.borrow());
4294        tester.pump_widget(material_app(
4295            theme,
4296            waft_widgets::Directionality::new(
4297                waft_painting::TextDirection::Rtl,
4298                Scaffold::new().body(rtl_carousel(reverse)),
4299            )
4300            .into_widget(),
4301        ));
4302        tester.pump_and_settle();
4303    }
4304
4305    #[test]
4306    fn scrolls_correctly_in_rtl() {
4307        test_widgets(|tester| {
4308            pump_rtl_carousel(tester, false);
4309            let item0 = find::by_key(waft_foundation::ValueKey::new(0));
4310            let before = tester.get_center(item0.clone()).dx();
4311
4312            tester.drag(find::by_type::<CarouselView>(), Offset::new(500.0, 0.0));
4313            tester.pump_and_settle();
4314
4315            let after = tester.get_center(item0).dx();
4316            assert!(after > before);
4317            let axis_direction = scrollable_state(tester).axis_direction(&tester.cell.borrow());
4318            assert_eq!(axis_direction, AxisDirection::Left);
4319        });
4320    }
4321
4322    #[test]
4323    fn scrolls_correctly_in_rtl_with_reverse() {
4324        test_widgets(|tester| {
4325            pump_rtl_carousel(tester, true);
4326            let item0 = find::by_key(waft_foundation::ValueKey::new(0));
4327            let before = tester.get_center(item0.clone()).dx();
4328
4329            tester.drag(find::by_type::<CarouselView>(), Offset::new(-500.0, 0.0));
4330            tester.pump_and_settle();
4331
4332            let after = tester.get_center(item0).dx();
4333            assert!(after < before);
4334            let axis_direction = scrollable_state(tester).axis_direction(&tester.cell.borrow());
4335            assert_eq!(axis_direction, AxisDirection::Right);
4336        });
4337    }
4338
4339    #[test]
4340    fn snaps_back_to_item_boundary_after_partial_scroll() {
4341        test_widgets(|tester| {
4342            pump_carousel(
4343                tester,
4344                CarouselView::new(
4345                    600.0,
4346                    vec![
4347                        SizedBox::new().width(600.0).height(600.0).into_widget(),
4348                        SizedBox::new().width(600.0).height(600.0).into_widget(),
4349                    ],
4350                )
4351                .item_snapping(true),
4352            );
4353
4354            tester.drag(find::by_type::<CarouselView>(), Offset::new(-100.0, 0.0));
4355            tester.pump_and_settle();
4356
4357            let position = scrollable_state(tester).position(&tester.cell.borrow());
4358            assert_eq!(position.pixels(&tester.cell.borrow()), 0.0);
4359        });
4360    }
4361
4362    #[test]
4363    fn carousel_view_weighted_does_not_crash_at_finite_trailing_scroll_offset() {
4364        test_widgets(|tester| {
4365            let controller = CarouselController::new(&mut tester.cell.borrow_mut(), 0);
4366            tester.set_surface_size(Some(waft_embedder::Size::new(750.0, 1000.0)));
4367            pump_carousel(
4368                tester,
4369                CarouselView::weighted(vec![1, 7], text_items(5)).controller(controller.clone()),
4370            );
4371
4372            controller
4373                .handle()
4374                .jump_to(&mut tester.cell.borrow_mut(), 461.5);
4375            tester.pump();
4376            tester.set_surface_size(None);
4377        });
4378    }
4379
4380    #[test]
4381    fn carousel_controller_animate_to_item_weighted_horizontal_reversed_one_to_seven() {
4382        run_carousel_test(vec![1, 7], true, 20, Axis::Horizontal, true);
4383    }
4384
4385    #[test]
4386    fn carousel_controller_animate_to_item_weighted_vertical_not_reversed_one_to_seven() {
4387        run_carousel_test(vec![1, 7], false, 20, Axis::Vertical, false);
4388    }
4389
4390    #[test]
4391    fn carousel_controller_animate_to_item_weighted_vertical_reversed_not_consuming_max_weight() {
4392        run_carousel_test(vec![1, 7], false, 20, Axis::Vertical, true);
4393    }
4394
4395    #[test]
4396    fn carousel_controller_animate_to_item_weighted_vertical_reversed_one_to_seven() {
4397        run_carousel_test(vec![1, 7], true, 20, Axis::Vertical, true);
4398    }
4399
4400    #[test]
4401    fn carousel_controller_animate_to_item_horizontal_reversed() {
4402        run_carousel_test(Vec::new(), true, 10, Axis::Horizontal, true);
4403    }
4404
4405    #[test]
4406    fn carousel_controller_animate_to_item_vertical_not_reversed() {
4407        run_carousel_test(Vec::new(), true, 10, Axis::Vertical, false);
4408    }
4409
4410    #[test]
4411    fn carousel_controller_animate_to_item_vertical_reversed() {
4412        run_carousel_test(Vec::new(), true, 10, Axis::Vertical, true);
4413    }
4414
4415    #[test]
4416    fn carousel_view_positions_items_correctly() {
4417        test_widgets(|tester| {
4418            let number_of_children = 5;
4419            let controller = CarouselController::new(&mut tester.cell.borrow_mut(), 0);
4420            pump_carousel(
4421                tester,
4422                CarouselView::weighted(vec![2, 3, 1], text_items(number_of_children))
4423                    .controller(controller.clone())
4424                    .item_snapping(true),
4425            );
4426            tester.pump_and_settle();
4427
4428            let carousel_rect = tester.get_rect(find::by_type::<CarouselView>());
4429            for i in 0..number_of_children {
4430                drop(controller.handle().animate_to_item(
4431                    &mut tester.cell.borrow_mut(),
4432                    i,
4433                    Duration::from_millis(300),
4434                    Curves::ease_in_out(),
4435                ));
4436                tester.pump_and_settle();
4437
4438                expect(
4439                    tester,
4440                    &find::text(&format!("Item {i}")),
4441                    finds_one_widget(),
4442                );
4443                let item_rect = tester.get_rect(find::text(&format!("Item {i}")));
4444                assert!(item_rect.left >= carousel_rect.left);
4445                assert!(item_rect.right <= carousel_rect.right);
4446            }
4447        });
4448    }
4449
4450    #[test]
4451    fn carousel_view_infinite_animate_to_item_wraps_to_the_item_behind() {
4452        test_widgets(|tester| {
4453            let controller = CarouselController::new(&mut tester.cell.borrow_mut(), 0);
4454            pump_carousel(
4455                tester,
4456                CarouselView::new(200.0, text_items(3))
4457                    .infinite(true)
4458                    .controller(controller.clone()),
4459            );
4460
4461            drop(controller.handle().animate_to_item(
4462                &mut tester.cell.borrow_mut(),
4463                5,
4464                Duration::from_millis(300),
4465                Curves::ease(),
4466            ));
4467            tester.pump_and_settle();
4468
4469            expect(
4470                tester,
4471                &find::text_containing("Item 2"),
4472                waft_widgets::testing::finds_at_least_n_widgets(2),
4473            );
4474        });
4475    }
4476
4477    #[test]
4478    fn carousel_view_weighted_builder_creates_items_lazily_with_flex_weights() {
4479        test_widgets(|tester| {
4480            let built_items = Rc::new(RefCell::new(Vec::<i32>::new()));
4481            let item_builder: CarouselItemBuilder = {
4482                let built_items = Rc::clone(&built_items);
4483                Rc::new(move |_app, _context, index| {
4484                    built_items.borrow_mut().push(index);
4485                    Some(
4486                        Center::new()
4487                            .child(Text::new(format!("Item {index}")))
4488                            .into_widget(),
4489                    )
4490                })
4491            };
4492            pump_carousel(
4493                tester,
4494                CarouselView::weighted_builder(vec![2, 3, 1], item_builder).item_count(1000),
4495            );
4496
4497            assert!(built_items.borrow().len() < 10);
4498            assert!(built_items.borrow().contains(&0));
4499            assert!(built_items.borrow().contains(&1));
4500
4501            tester.drag(find::by_type::<CarouselView>(), Offset::new(-2000.0, 0.0));
4502            tester.pump_and_settle();
4503            built_items.borrow_mut().clear();
4504
4505            tester.drag(find::by_type::<CarouselView>(), Offset::new(-300.0, 0.0));
4506            tester.pump();
4507            assert!(!built_items.borrow().is_empty());
4508            assert!(built_items.borrow().iter().all(|index| *index > 3));
4509        });
4510    }
4511
4512    fn sized_item() -> WidgetRef {
4513        SizedBox::expand()
4514            .key(waft_foundation::ValueKey::new("item").into())
4515            .into_widget()
4516    }
4517
4518    #[test]
4519    fn item_extent_can_be_set_to_infinity() {
4520        test_widgets(|tester| {
4521            pump_carousel(tester, CarouselView::new(f64::INFINITY, vec![sized_item()]));
4522
4523            let size = tester.get_size(find::by_key(waft_foundation::ValueKey::new("item")));
4524            // The default horizontal padding is 4 on each side.
4525            assert_eq!(size.width(), 800.0 - 8.0);
4526        });
4527    }
4528
4529    fn pump_in_zero_width_parent(tester: &mut WidgetTester, carousel: CarouselView) {
4530        let theme = ThemeData::builder().build(&tester.cell.borrow());
4531        tester.pump_widget(material_app(
4532            theme,
4533            Scaffold::new()
4534                .body(SizedBox::new().width(0.0).child(carousel))
4535                .into_widget(),
4536        ));
4537    }
4538
4539    // Dart's `expect(tester.takeException(), isNull)` in the five cases below: a panic fails
4540    // the test.
4541    #[test]
4542    fn does_not_crash_when_parent_size_is_zero() {
4543        test_widgets(|tester| {
4544            pump_in_zero_width_parent(tester, CarouselView::new(40.0, vec![sized_item()]));
4545        });
4546    }
4547
4548    #[test]
4549    fn does_not_crash_when_initial_viewport_dimension_is_zero_and_item_extent_is_fixed() {
4550        test_widgets(|tester| {
4551            tester.set_surface_size(Some(Size::new(0.0, 0.0)));
4552            pump_carousel(tester, CarouselView::new(60.0, vec![sized_item()]));
4553            tester.set_surface_size(None);
4554        });
4555    }
4556
4557    #[test]
4558    fn does_not_crash_when_initial_viewport_dimension_is_zero_and_item_extent_is_infinite() {
4559        test_widgets(|tester| {
4560            tester.set_surface_size(Some(Size::new(0.0, 0.0)));
4561            pump_carousel(tester, CarouselView::new(f64::INFINITY, vec![sized_item()]));
4562            tester.set_surface_size(None);
4563        });
4564    }
4565
4566    #[test]
4567    fn carousel_view_weighted_does_not_crash_when_parent_size_is_zero() {
4568        test_widgets(|tester| {
4569            pump_in_zero_width_parent(
4570                tester,
4571                CarouselView::weighted(vec![1, 2], vec![sized_item(), sized_item()]),
4572            );
4573        });
4574    }
4575
4576    #[test]
4577    fn carousel_view_weighted_does_not_crash_when_initial_viewport_dimension_is_zero() {
4578        test_widgets(|tester| {
4579            tester.set_surface_size(Some(Size::new(0.0, 0.0)));
4580            pump_carousel(
4581                tester,
4582                CarouselView::weighted(vec![1, 2], vec![sized_item(), sized_item()]),
4583            );
4584            tester.set_surface_size(None);
4585        });
4586    }
4587
4588    #[test]
4589    fn item_extent_is_applied_when_viewport_dimension_is_updated() {
4590        test_widgets(|tester| {
4591            let item_extent = 60.0;
4592            for (index, size) in [Size::new(0.0, 0.0), Size::new(500.0, 400.0)]
4593                .into_iter()
4594                .enumerate()
4595            {
4596                tester.set_surface_size(Some(size));
4597                let behavior = ScrollBehaviorRef::new(
4598                    ScrollBehaviorRef::new(waft_widgets::PlainScrollBehavior)
4599                        .copy_with()
4600                        .scrollbars(index % 2 == 0),
4601                );
4602                let theme = ThemeData::builder().build(&tester.cell.borrow());
4603                tester.pump_widget(material_app(
4604                    theme,
4605                    Scaffold::new()
4606                        .body(Center::new().child(ScrollConfiguration::new(
4607                            behavior,
4608                            CarouselView::new(item_extent, vec![sized_item()]),
4609                        )))
4610                        .into_widget(),
4611                ));
4612            }
4613
4614            let size = tester.get_size(find::by_key(waft_foundation::ValueKey::new("item")));
4615            assert_eq!(size.width(), item_extent - 8.0);
4616            tester.set_surface_size(None);
4617        });
4618    }
4619
4620    #[test]
4621    fn carousel_view_weighted_weights_are_applied_when_viewport_dimension_is_updated() {
4622        test_widgets(|tester| {
4623            let controller = CarouselController::new(&mut tester.cell.borrow_mut(), 1);
4624            let (first_weight, second_weight) = (2, 3);
4625            let surface_width = 500.0;
4626            for (index, size) in [Size::new(0.0, 0.0), Size::new(surface_width, 400.0)]
4627                .into_iter()
4628                .enumerate()
4629            {
4630                tester.set_surface_size(Some(size));
4631                let behavior = ScrollBehaviorRef::new(
4632                    ScrollBehaviorRef::new(waft_widgets::PlainScrollBehavior)
4633                        .copy_with()
4634                        .scrollbars(index % 2 == 0),
4635                );
4636                let theme = ThemeData::builder().build(&tester.cell.borrow());
4637                tester.pump_widget(material_app(
4638                    theme,
4639                    Scaffold::new()
4640                        .body(
4641                            Center::new().child(ScrollConfiguration::new(
4642                                behavior,
4643                                CarouselView::weighted(
4644                                    vec![first_weight, second_weight],
4645                                    text_items(20),
4646                                )
4647                                .controller(controller.clone()),
4648                            )),
4649                        )
4650                        .into_widget(),
4651                ));
4652            }
4653
4654            let total_weight = f64::from(first_weight + second_weight);
4655            expect(tester, &find::text("Item 0"), finds_one_widget());
4656            expect(tester, &find::text("Item 1"), finds_one_widget());
4657            assert_eq!(
4658                tester.get_rect(get_item(0)).width(),
4659                surface_width * f64::from(first_weight) / total_weight
4660            );
4661            assert_eq!(
4662                tester.get_rect(get_item(1)).width(),
4663                surface_width * f64::from(second_weight) / total_weight
4664            );
4665            tester.set_surface_size(None);
4666        });
4667    }
4668
4669    #[test]
4670    fn the_shrink_extent_should_keep_the_same_when_the_item_is_tapped() {
4671        test_widgets(|tester| {
4672            let theme = ThemeData::builder().build(&tester.cell.borrow());
4673            tester.pump_widget(material_app(
4674                theme,
4675                Scaffold::new()
4676                    .body(
4677                        Center::new().child(
4678                            waft_widgets::ConstrainedBox::new(waft_rendering::BoxConstraints {
4679                                max_height: 200.0,
4680                                ..waft_rendering::BoxConstraints::new()
4681                            })
4682                            .child(
4683                                CarouselView::new(330.0, text_items(20))
4684                                    .on_tap(Rc::new(|_app, _index| {})),
4685                            ),
4686                        ),
4687                    )
4688                    .into_widget(),
4689            ));
4690            tester.pump_and_settle();
4691
4692            assert_eq!(tester.get_rect(get_item(0)).width(), 330.0);
4693
4694            tester.tap(find::ancestor(
4695                find::text("Item 1"),
4696                find::by_type::<waft_widgets::Stack>(),
4697            ));
4698            tester.pump_and_settle();
4699
4700            assert_eq!(tester.get_rect(get_item(0)).width(), 330.0);
4701            assert_eq!(tester.get_rect(get_item(1)).width(), 330.0);
4702            // Item 2 shrinks: its width is 800 - 330 - 330.
4703            assert_eq!(tester.get_rect(get_item(2)).width(), 140.0);
4704        });
4705    }
4706}