Skip to main content

waft_widgets/widgets/
page_view.rs

1//! Flutter counterpart: `widgets/page_view.dart`.
2//!
3//! `PageView`'s diagnostics wait for diagnostics.
4
5#![allow(clippy::too_many_arguments)]
6
7use std::any::Any;
8use std::fmt::{self, Debug};
9use std::rc::Rc;
10use std::time::Duration;
11
12use waft_animation::Curve;
13use waft_embedder::{Clip, clamp_double};
14use waft_foundation::{
15    App, ChangeNotifier, ChangeNotifierData, CompleterFuture, DiagnosticPropertiesBuilder,
16    DiagnosticsProperty, EnumProperty, FlagProperty, Handle, OptionRetained,
17    PRECISION_ERROR_TOLERANCE, ValueChanged,
18};
19use waft_gestures::DragStartBehavior;
20use waft_painting::{Axis, AxisDirection, flip_axis_direction, text_direction_to_axis_direction};
21use waft_physics::{ScrollSpringSimulation, Simulation, Tolerance};
22use waft_rendering::{
23    AnyRenderObject, HitTestBehavior, ScrollCacheExtent, ScrollDirection, ViewportOffset,
24    ViewportOffsetRef,
25};
26
27use crate::framework::{
28    BuildContext, IntoWidget, KeyRef, State, StateData, StatefulWidget, WidgetRef,
29};
30use crate::widgets::basic::Directionality;
31use crate::widgets::notification_listener::NotificationListener;
32use crate::widgets::page_storage::PageStorage;
33use crate::widgets::scroll_activity::ScrollActivityDelegate;
34use crate::widgets::scroll_configuration::{ScrollBehaviorRef, ScrollConfiguration};
35use crate::widgets::scroll_context::ScrollContext;
36use crate::widgets::scroll_controller::{
37    ScrollController, ScrollControllerCallback, ScrollControllerData, ScrollControllerLeaf,
38};
39use crate::widgets::scroll_delegate::{
40    ChildIndexGetter, NullableIndexedWidgetBuilder, SliverChildBuilderDelegate,
41    SliverChildDelegateRef, SliverChildListDelegate,
42};
43use crate::widgets::scroll_metrics::{FixedScrollMetrics, ScrollMetrics};
44use crate::widgets::scroll_notification::{ScrollNotification, ScrollUpdateNotification};
45use crate::widgets::scroll_physics::{ScrollPhysics, ScrollPhysicsBase, ScrollPhysicsRef};
46use crate::widgets::scroll_position::{
47    AnyScrollPosition, ScrollPosition, ScrollPositionAlignmentPolicy, ScrollPositionBase,
48    ScrollPositionData, ScrollPositionRef,
49};
50use crate::widgets::scroll_position_with_single_context::{
51    ScrollPositionWithSingleContext, ScrollPositionWithSingleContextData,
52    ScrollPositionWithSingleContextLeaf,
53};
54use crate::widgets::scrollable::{Scrollable, ViewportBuilder};
55use crate::widgets::sliver_fill::SliverFillViewport;
56use crate::widgets::viewport::Viewport;
57use waft_foundation::Ref;
58
59// ---------------------------------------------------------------------------------------------
60// PageController
61
62/// A controller for [`PageView`].
63///
64/// A page controller lets you manipulate which page is visible in a [`PageView`]. In addition to
65/// being able to control the pixel offset of the content inside the [`PageView`], a
66/// [`PageController`] also lets you control the offset in terms of pages, which are increments
67/// of the viewport size.
68///
69/// See also:
70///
71///  * [`PageView`], which is the widget this object controls.
72pub struct PageController {
73    change_notifier: ChangeNotifierData,
74    scroll_controller: ScrollControllerData,
75    initial_page: i32,
76    keep_page: bool,
77    viewport_fraction: f64,
78}
79
80impl PageController {
81    /// Creates a page controller.
82    ///
83    /// Dart's defaults: `initial_page` 0, `keep_page` true, `viewport_fraction` 1.0, no
84    /// `on_attach` and no `on_detach`; [`PageController::default`] makes that one.
85    pub fn new(
86        app: &mut App,
87        initial_page: i32,
88        keep_page: bool,
89        viewport_fraction: f64,
90        on_attach: Option<ScrollControllerCallback>,
91        on_detach: Option<ScrollControllerCallback>,
92    ) -> Ref<PageController> {
93        debug_assert!(viewport_fraction > 0.0);
94        app.create(PageController {
95            change_notifier: ChangeNotifierData::new(),
96            scroll_controller: ScrollControllerData::new(0.0, true, None, on_attach, on_detach),
97            initial_page,
98            keep_page,
99            viewport_fraction,
100        })
101    }
102
103    /// Dart's `PageController()`, with every argument at its default.
104    pub fn default(app: &mut App) -> Ref<PageController> {
105        PageController::new(app, 0, true, 1.0, None, None)
106    }
107
108    /// The page to show when first creating the [`PageView`].
109    pub fn initial_page(self: Handle<Self>, app: &App) -> i32 {
110        app.get(self).initial_page
111    }
112
113    /// Save the current [`page`](Self::page) with [`PageStorage`] and restore it if this
114    /// controller's scrollable is recreated.
115    ///
116    /// If this property is set to false, the current [`page`](Self::page) is never saved and
117    /// [`initial_page`](Self::initial_page) is always used to initialize the scroll offset. If
118    /// true (the default), the initial page is used the first time the controller's scrollable
119    /// is created, since there's isn't a page to restore yet. Subsequently the saved page is
120    /// restored and [`initial_page`](Self::initial_page) is ignored.
121    ///
122    /// See also:
123    ///
124    ///  * `PageStorageKey`, which should be used when more than one scrollable appears in the
125    ///    same route, to distinguish the [`PageStorage`] locations used to save scroll offsets.
126    pub fn keep_page(self: Handle<Self>, app: &App) -> bool {
127        app.get(self).keep_page
128    }
129
130    /// The fraction of the viewport that each page should occupy.
131    ///
132    /// Defaults to 1.0, which means each page fills the viewport in the scrolling direction.
133    pub fn viewport_fraction(self: Handle<Self>, app: &App) -> f64 {
134        app.get(self).viewport_fraction
135    }
136
137    /// The current page displayed in the controlled [`PageView`].
138    ///
139    /// There are circumstances that this [`PageController`] can't know the current page.
140    /// Reading [`page`](Self::page) will panic in the following cases:
141    ///
142    /// 1. No [`PageView`] is currently using this [`PageController`]. Once a [`PageView`]
143    ///    starts using this [`PageController`], the new [`page`](Self::page) position will be
144    ///    derived:
145    ///
146    ///    * First, based on the attached [`PageView`]'s [`BuildContext`] and the position saved
147    ///      at that context's [`PageStorage`] if [`keep_page`](Self::keep_page) is true.
148    ///    * Second, from the [`PageController`]'s [`initial_page`](Self::initial_page).
149    ///
150    /// 2. More than one [`PageView`] using the same [`PageController`].
151    ///
152    /// The [`has_clients`](ScrollControllerLeaf::has_clients) property can be used to check if a
153    /// [`PageView`] is attached prior to accessing [`page`](Self::page).
154    pub fn page(self: Handle<Self>, app: &App) -> Option<f64> {
155        let positions = self.positions(app);
156        debug_assert!(
157            !positions.is_empty(),
158            "PageController.page cannot be accessed before a PageView is built with it."
159        );
160        debug_assert!(
161            positions.len() == 1,
162            "The page property cannot be read when multiple PageViews are attached to the same \
163             PageController."
164        );
165        self.page_position(app).page(app)
166    }
167
168    /// Dart's `this.position as _PagePosition`.
169    fn page_position(self: Handle<Self>, app: &App) -> Handle<PagePosition> {
170        self.position(app)
171            .downcast::<PagePosition>(app)
172            .expect("a PageController creates the positions of the PageViews it controls")
173    }
174
175    fn debug_check_page_controller_attached(self: Handle<Self>, app: &App) -> bool {
176        let positions = self.positions(app);
177        debug_assert!(
178            !positions.is_empty(),
179            "PageController is not attached to a PageView."
180        );
181        debug_assert!(
182            positions.len() == 1,
183            "Multiple PageViews are attached to the same PageController."
184        );
185        true
186    }
187
188    /// Animates the controlled [`PageView`] from the current page to the given page.
189    ///
190    /// The animation lasts for the given duration and follows the given curve. The returned
191    /// future resolves when the animation completes.
192    pub fn animate_to_page(
193        self: Handle<Self>,
194        app: &mut App,
195        page: i32,
196        duration: Duration,
197        curve: Rc<dyn Curve>,
198    ) -> CompleterFuture<()> {
199        debug_assert!(self.debug_check_page_controller_attached(app));
200        let position = self.page_position(app);
201        if app.get(position).cached_page.is_some() {
202            app.get_mut(position).cached_page = Some(f64::from(page));
203            return CompleterFuture::ready(());
204        }
205
206        if !position.has_viewport_dimension(app) {
207            app.get_mut(position).page_to_use_on_startup = f64::from(page);
208            return CompleterFuture::ready(());
209        }
210
211        let to = position.get_pixels_from_page(app, f64::from(page));
212        ViewportOffset::animate_to(position, app, to, duration, curve)
213    }
214
215    /// Changes which page is displayed in the controlled [`PageView`].
216    ///
217    /// Jumps the page position from its current value to the given value, without animation,
218    /// and without checking if the new value is in range.
219    pub fn jump_to_page(self: Handle<Self>, app: &mut App, page: i32) {
220        debug_assert!(self.debug_check_page_controller_attached(app));
221        let position = self.page_position(app);
222        if app.get(position).cached_page.is_some() {
223            app.get_mut(position).cached_page = Some(f64::from(page));
224            return;
225        }
226
227        if !position.has_viewport_dimension(app) {
228            app.get_mut(position).page_to_use_on_startup = f64::from(page);
229            return;
230        }
231
232        let to = position.get_pixels_from_page(app, f64::from(page));
233        ViewportOffset::jump_to(position, app, to);
234    }
235
236    /// Animates the controlled [`PageView`] to the next page.
237    ///
238    /// The animation lasts for the given duration and follows the given curve. The returned
239    /// future resolves when the animation completes.
240    pub fn next_page(
241        self: Handle<Self>,
242        app: &mut App,
243        duration: Duration,
244        curve: Rc<dyn Curve>,
245    ) -> CompleterFuture<()> {
246        let page = self
247            .page(app)
248            .expect("an attached page view has a page")
249            .round() as i32;
250        self.animate_to_page(app, page + 1, duration, curve)
251    }
252
253    /// Animates the controlled [`PageView`] to the previous page.
254    ///
255    /// The animation lasts for the given duration and follows the given curve. The returned
256    /// future resolves when the animation completes.
257    pub fn previous_page(
258        self: Handle<Self>,
259        app: &mut App,
260        duration: Duration,
261        curve: Rc<dyn Curve>,
262    ) -> CompleterFuture<()> {
263        let page = self
264            .page(app)
265            .expect("an attached page view has a page")
266            .round() as i32;
267        self.animate_to_page(app, page - 1, duration, curve)
268    }
269}
270
271impl ChangeNotifier for PageController {
272    fn change_notifier_data(&self) -> &ChangeNotifierData {
273        &self.change_notifier
274    }
275
276    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
277        &mut self.change_notifier
278    }
279}
280
281impl ScrollControllerLeaf for PageController {
282    crate::scroll_controller_accessors!();
283
284    fn create_scroll_position(
285        self: Handle<Self>,
286        app: &mut App,
287        physics: ScrollPhysicsRef,
288        context: Rc<dyn ScrollContext>,
289        old_position: Option<AnyScrollPosition>,
290    ) -> ScrollPositionRef {
291        let this = app.get(self);
292        let (initial_page, keep_page, viewport_fraction) =
293            (this.initial_page, this.keep_page, this.viewport_fraction);
294        PagePosition::new(
295            app,
296            physics,
297            context,
298            initial_page,
299            keep_page,
300            viewport_fraction,
301            old_position,
302        )
303        .into_erased()
304    }
305
306    fn attach(self: Handle<Self>, app: &mut App, position: ScrollPositionRef) {
307        let attached = position.handle();
308        ScrollController::attach(self.as_controller(), app, position);
309        let page_position = attached
310            .downcast::<PagePosition>(app)
311            .expect("a PageController attaches the positions it creates");
312        let viewport_fraction = app.get(self).viewport_fraction;
313        page_position.set_viewport_fraction(app, viewport_fraction);
314    }
315}
316
317// ---------------------------------------------------------------------------------------------
318// PageMetrics
319
320/// Metrics for a [`PageView`].
321///
322/// The metrics are available on [`ScrollNotification`]s generated from [`PageView`]s.
323#[derive(Clone, Copy)]
324pub struct PageMetrics {
325    fixed: FixedScrollMetrics,
326    viewport_fraction: f64,
327    // Set only on the snapshot a page view's position makes of itself
328    // (`ScrollPosition::copy_with`), which stands for the position where Dart hands the
329    // position itself to the physics: `PageScrollPhysics` answers it as Dart's
330    // `position is _PagePosition`. Every copy drops it, as Dart's copy is no position.
331    position: Option<PagePositionSnapshot>,
332}
333
334/// What a `_PagePosition` answers beyond its [`PageMetrics`] when its snapshot was taken.
335#[derive(Clone, Copy)]
336struct PagePositionSnapshot {
337    cached_page: Option<f64>,
338}
339
340impl PageMetrics {
341    /// Creates an immutable snapshot of values associated with a [`PageView`].
342    pub fn new(
343        min_scroll_extent: Option<f64>,
344        max_scroll_extent: Option<f64>,
345        pixels: Option<f64>,
346        viewport_dimension: Option<f64>,
347        axis_direction: AxisDirection,
348        viewport_fraction: f64,
349        device_pixel_ratio: f64,
350    ) -> PageMetrics {
351        PageMetrics {
352            fixed: FixedScrollMetrics::new(
353                min_scroll_extent,
354                max_scroll_extent,
355                pixels,
356                viewport_dimension,
357                axis_direction,
358                device_pixel_ratio,
359            ),
360            viewport_fraction,
361            position: None,
362        }
363    }
364
365    /// Dart's `PageMetrics.copyWith`; the `with_*` setters on the copy replace its values.
366    pub fn copy_with(&self) -> PageMetrics {
367        PageMetrics {
368            position: None,
369            ..*self
370        }
371    }
372
373    /// Dart `copyWith(minScrollExtent:)`.
374    pub fn with_min_scroll_extent(mut self, min_scroll_extent: f64) -> PageMetrics {
375        self.fixed = self.fixed.with_min_scroll_extent(min_scroll_extent);
376        self
377    }
378
379    /// Dart `copyWith(maxScrollExtent:)`.
380    pub fn with_max_scroll_extent(mut self, max_scroll_extent: f64) -> PageMetrics {
381        self.fixed = self.fixed.with_max_scroll_extent(max_scroll_extent);
382        self
383    }
384
385    /// Dart `copyWith(pixels:)`.
386    pub fn with_pixels(mut self, pixels: f64) -> PageMetrics {
387        self.fixed = self.fixed.with_pixels(pixels);
388        self
389    }
390
391    /// Dart `copyWith(viewportDimension:)`.
392    pub fn with_viewport_dimension(mut self, viewport_dimension: f64) -> PageMetrics {
393        self.fixed = self.fixed.with_viewport_dimension(viewport_dimension);
394        self
395    }
396
397    /// Dart `copyWith(axisDirection:)`.
398    pub fn with_axis_direction(mut self, axis_direction: AxisDirection) -> PageMetrics {
399        self.fixed = self.fixed.with_axis_direction(axis_direction);
400        self
401    }
402
403    /// Dart `copyWith(viewportFraction:)`.
404    pub fn with_viewport_fraction(mut self, viewport_fraction: f64) -> PageMetrics {
405        self.viewport_fraction = viewport_fraction;
406        self
407    }
408
409    /// Dart `copyWith(devicePixelRatio:)`.
410    pub fn with_device_pixel_ratio(mut self, device_pixel_ratio: f64) -> PageMetrics {
411        self.fixed = self.fixed.with_device_pixel_ratio(device_pixel_ratio);
412        self
413    }
414
415    /// The current page displayed in the [`PageView`].
416    pub fn page(&self) -> Option<f64> {
417        Some(
418            clamp_double(
419                self.pixels(),
420                self.min_scroll_extent(),
421                self.max_scroll_extent(),
422            )
423            .max(0.0)
424                / (self.viewport_dimension() * self.viewport_fraction).max(1.0),
425        )
426    }
427
428    /// The fraction of the viewport that each page occupies.
429    ///
430    /// Used to compute [`page`](Self::page) from the current [`pixels`](ScrollMetrics::pixels).
431    pub fn viewport_fraction(&self) -> f64 {
432        self.viewport_fraction
433    }
434
435    /// Dart's `_PagePosition.page`, answered from the position's snapshot.
436    fn position_page(&self, position: PagePositionSnapshot) -> Option<f64> {
437        if !self.has_pixels() {
438            return None;
439        }
440        if self.has_content_dimensions() {
441            Some(position.cached_page.unwrap_or_else(|| {
442                page_from_pixels(
443                    clamp_double(
444                        self.pixels(),
445                        self.min_scroll_extent(),
446                        self.max_scroll_extent(),
447                    ),
448                    self.viewport_dimension(),
449                    self.viewport_fraction,
450                )
451            }))
452        } else {
453            None
454        }
455    }
456
457    /// Dart's `_PagePosition.getPixelsFromPage`, answered from the position's snapshot.
458    fn position_pixels_from_page(&self, page: f64) -> f64 {
459        pixels_from_page(page, self.viewport_dimension(), self.viewport_fraction)
460    }
461}
462
463impl ScrollMetrics for PageMetrics {
464    fn as_any(&self) -> &dyn Any {
465        self
466    }
467
468    fn min_scroll_extent(&self) -> f64 {
469        self.fixed.min_scroll_extent()
470    }
471
472    fn max_scroll_extent(&self) -> f64 {
473        self.fixed.max_scroll_extent()
474    }
475
476    fn has_content_dimensions(&self) -> bool {
477        self.fixed.has_content_dimensions()
478    }
479
480    fn pixels(&self) -> f64 {
481        self.fixed.pixels()
482    }
483
484    fn has_pixels(&self) -> bool {
485        self.fixed.has_pixels()
486    }
487
488    fn viewport_dimension(&self) -> f64 {
489        self.fixed.viewport_dimension()
490    }
491
492    fn has_viewport_dimension(&self) -> bool {
493        self.fixed.has_viewport_dimension()
494    }
495
496    fn axis_direction(&self) -> AxisDirection {
497        self.fixed.axis_direction()
498    }
499
500    fn device_pixel_ratio(&self) -> f64 {
501        self.fixed.device_pixel_ratio()
502    }
503}
504
505impl Debug for PageMetrics {
506    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
507        write!(
508            f,
509            "PageMetrics({:.1}..[{:.1}]..{:.1})",
510            self.extent_before(),
511            self.extent_inside(),
512            self.extent_after()
513        )
514    }
515}
516
517// ---------------------------------------------------------------------------------------------
518// _PagePosition
519
520/// Dart's `_PagePosition`: a [`ScrollPositionWithSingleContextLeaf`] that keeps its offset in
521/// pages of [`viewport_fraction`](Self::viewport_fraction) of the viewport.
522struct PagePosition {
523    change_notifier: ChangeNotifierData,
524    scroll_position: ScrollPositionData,
525    single_context: ScrollPositionWithSingleContextData,
526    page_to_use_on_startup: f64,
527    // When the viewport has a zero-size, the `page` can not
528    // be retrieved by `getPageFromPixels`, so we need to cache the page
529    // for use when resizing the viewport to non-zero next time.
530    cached_page: Option<f64>,
531    viewport_fraction: f64,
532}
533
534impl PagePosition {
535    fn new(
536        app: &mut App,
537        physics: ScrollPhysicsRef,
538        context: Rc<dyn ScrollContext>,
539        initial_page: i32,
540        keep_page: bool,
541        viewport_fraction: f64,
542        old_position: Option<AnyScrollPosition>,
543    ) -> Ref<PagePosition> {
544        debug_assert!(viewport_fraction > 0.0);
545        let scroll_position = ScrollPositionData::new(app, physics, context, keep_page, None);
546        let this = app.create(PagePosition {
547            change_notifier: ChangeNotifierData::new(),
548            scroll_position,
549            single_context: ScrollPositionWithSingleContextData::new(),
550            page_to_use_on_startup: f64::from(initial_page),
551            cached_page: None,
552            viewport_fraction,
553        });
554        ScrollPositionWithSingleContext::init(this.handle(), app, None, old_position);
555        this
556    }
557
558    /// The fraction of the viewport that each page occupies.
559    fn viewport_fraction(self: Handle<Self>, app: &App) -> f64 {
560        app.get(self).viewport_fraction
561    }
562
563    fn set_viewport_fraction(self: Handle<Self>, app: &mut App, value: f64) {
564        if app.get(self).viewport_fraction == value {
565            return;
566        }
567        let old_page = self.page(app);
568        app.get_mut(self).viewport_fraction = value;
569        if let Some(old_page) = old_page {
570            let pixels = self.get_pixels_from_page(app, old_page);
571            self.force_pixels(app, pixels);
572        }
573    }
574
575    /// Dart's `_initialPageOffset`; see [`initial_page_offset`].
576    fn initial_page_offset(self: Handle<Self>, app: &App) -> f64 {
577        initial_page_offset(self.viewport_dimension(app), self.viewport_fraction(app))
578    }
579
580    fn get_page_from_pixels(
581        self: Handle<Self>,
582        app: &App,
583        pixels: f64,
584        viewport_dimension: f64,
585    ) -> f64 {
586        page_from_pixels(pixels, viewport_dimension, self.viewport_fraction(app))
587    }
588
589    fn get_pixels_from_page(self: Handle<Self>, app: &App, page: f64) -> f64 {
590        pixels_from_page(
591            page,
592            self.viewport_dimension(app),
593            self.viewport_fraction(app),
594        )
595    }
596
597    fn page(self: Handle<Self>, app: &App) -> Option<f64> {
598        if !self.has_pixels(app) {
599            return None;
600        }
601        debug_assert!(
602            self.has_content_dimensions(app) || !self.have_dimensions(app),
603            "Page value is only available after content dimensions are established."
604        );
605        if self.has_content_dimensions(app) || self.have_dimensions(app) {
606            Some(app.get(self).cached_page.unwrap_or_else(|| {
607                self.get_page_from_pixels(
608                    app,
609                    clamp_double(
610                        self.pixels(app),
611                        self.min_scroll_extent(app),
612                        self.max_scroll_extent(app),
613                    ),
614                    self.viewport_dimension(app),
615                )
616            }))
617        } else {
618            None
619        }
620    }
621
622    /// The page this position saves, Dart's `_cachedPage ?? getPageFromPixels(pixels,
623    /// viewportDimension)`.
624    fn page_to_save(self: Handle<Self>, app: &App) -> f64 {
625        app.get(self).cached_page.unwrap_or_else(|| {
626            self.get_page_from_pixels(app, self.pixels(app), self.viewport_dimension(app))
627        })
628    }
629}
630
631// The amount of offset that will be added to [minScrollExtent] and subtracted
632// from [maxScrollExtent], such that every page will properly snap to the center
633// of the viewport when viewportFraction is greater than 1.
634//
635// The value is 0 if viewportFraction is less than or equal to 1, larger than 0
636// otherwise.
637fn initial_page_offset(viewport_dimension: f64, viewport_fraction: f64) -> f64 {
638    (viewport_dimension * (viewport_fraction - 1.0) / 2.0).max(0.0)
639}
640
641/// Dart's `_PagePosition.getPageFromPixels`, over the values it reads.
642fn page_from_pixels(pixels: f64, viewport_dimension: f64, viewport_fraction: f64) -> f64 {
643    debug_assert!(viewport_dimension > 0.0);
644    let actual = (pixels - initial_page_offset(viewport_dimension, viewport_fraction)).max(0.0)
645        / (viewport_dimension * viewport_fraction);
646    let round = actual.round();
647    if (actual - round).abs() < PRECISION_ERROR_TOLERANCE {
648        return round;
649    }
650    actual
651}
652
653/// Dart's `_PagePosition.getPixelsFromPage`, over the values it reads.
654fn pixels_from_page(page: f64, viewport_dimension: f64, viewport_fraction: f64) -> f64 {
655    page * viewport_dimension * viewport_fraction
656        + initial_page_offset(viewport_dimension, viewport_fraction)
657}
658
659impl ChangeNotifier for PagePosition {
660    fn change_notifier_data(&self) -> &ChangeNotifierData {
661        &self.change_notifier
662    }
663
664    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
665        &mut self.change_notifier
666    }
667}
668
669impl ViewportOffset for PagePosition {
670    fn pixels(self: Handle<Self>, app: &App) -> f64 {
671        ScrollPositionBase::pixels(self, app)
672    }
673
674    fn has_pixels(self: Handle<Self>, app: &App) -> bool {
675        ScrollPositionBase::has_pixels(self, app)
676    }
677
678    fn apply_viewport_dimension(
679        self: Handle<Self>,
680        app: &mut App,
681        viewport_dimension: f64,
682    ) -> bool {
683        let old_viewport_dimensions = self
684            .has_viewport_dimension(app)
685            .then(|| self.viewport_dimension(app));
686        if Some(viewport_dimension) == old_viewport_dimensions {
687            return true;
688        }
689        let result = ScrollPositionBase::apply_viewport_dimension(self, app, viewport_dimension);
690        let old_pixels = self.has_pixels(app).then(|| self.pixels(app));
691        let page = match old_pixels {
692            None => app.get(self).page_to_use_on_startup,
693            // If resize from zero, we should use the _cachedPage to recover the state.
694            Some(_) if old_viewport_dimensions == Some(0.0) => app
695                .get(self)
696                .cached_page
697                .expect("a position resized from zero cached its page"),
698            Some(old_pixels) => self.get_page_from_pixels(
699                app,
700                old_pixels,
701                old_viewport_dimensions.expect("a position with pixels had a viewport dimension"),
702            ),
703        };
704        let new_pixels = self.get_pixels_from_page(app, page);
705
706        // If the viewportDimension is zero, cache the page
707        // in case the viewport is resized to be non-zero.
708        app.get_mut(self).cached_page = (viewport_dimension == 0.0).then_some(page);
709
710        if Some(new_pixels) != old_pixels {
711            self.correct_pixels(app, new_pixels);
712            return false;
713        }
714        result
715    }
716
717    fn apply_content_dimensions(
718        self: Handle<Self>,
719        app: &mut App,
720        min_scroll_extent: f64,
721        max_scroll_extent: f64,
722    ) -> bool {
723        let initial_page_offset = self.initial_page_offset(app);
724        let new_min_scroll_extent = min_scroll_extent + initial_page_offset;
725        ScrollPositionBase::apply_content_dimensions(
726            self,
727            app,
728            new_min_scroll_extent,
729            new_min_scroll_extent.max(max_scroll_extent - initial_page_offset),
730        )
731    }
732
733    fn correct_by(self: Handle<Self>, app: &mut App, correction: f64) {
734        ScrollPositionBase::correct_by(self, app, correction);
735    }
736
737    fn jump_to(self: Handle<Self>, app: &mut App, value: f64) {
738        ScrollPositionWithSingleContextLeaf::jump_to(self, app, value);
739    }
740
741    fn animate_to(
742        self: Handle<Self>,
743        app: &mut App,
744        to: f64,
745        duration: Duration,
746        curve: Rc<dyn Curve>,
747    ) -> CompleterFuture<()> {
748        ScrollPositionWithSingleContextLeaf::animate_to(self, app, to, duration, curve)
749    }
750
751    fn move_to(
752        self: Handle<Self>,
753        app: &mut App,
754        to: f64,
755        duration: Option<Duration>,
756        curve: Option<Rc<dyn Curve>>,
757        clamp: Option<bool>,
758    ) -> CompleterFuture<()> {
759        ScrollPositionBase::move_to(self, app, to, duration, curve, clamp)
760    }
761
762    fn user_scroll_direction(self: Handle<Self>, app: &App) -> ScrollDirection {
763        ScrollPositionWithSingleContextLeaf::user_scroll_direction(self, app)
764    }
765
766    fn allow_implicit_scrolling(self: Handle<Self>, app: &App) -> bool {
767        ScrollPositionBase::allow_implicit_scrolling(self, app)
768    }
769}
770
771impl ScrollPosition for PagePosition {
772    crate::scroll_position_with_single_context_overrides!();
773
774    fn copy_with(self: Handle<Self>, app: &App) -> Rc<dyn ScrollMetrics> {
775        let has_content_dimensions = self.has_content_dimensions(app);
776        let mut metrics = PageMetrics::new(
777            has_content_dimensions.then(|| self.min_scroll_extent(app)),
778            has_content_dimensions.then(|| self.max_scroll_extent(app)),
779            self.has_pixels(app).then(|| self.pixels(app)),
780            self.has_viewport_dimension(app)
781                .then(|| self.viewport_dimension(app)),
782            ScrollPosition::axis_direction(self, app),
783            self.viewport_fraction(app),
784            self.device_pixel_ratio(app),
785        );
786        metrics.position = Some(PagePositionSnapshot {
787            cached_page: app.get(self).cached_page,
788        });
789        Rc::new(metrics)
790    }
791
792    fn ensure_visible(
793        self: Handle<Self>,
794        app: &mut App,
795        object: AnyRenderObject,
796        alignment: f64,
797        duration: Duration,
798        curve: Rc<dyn Curve>,
799        alignment_policy: ScrollPositionAlignmentPolicy,
800        _target_render_object: Option<AnyRenderObject>,
801    ) -> CompleterFuture<()> {
802        // Since the _PagePosition is intended to cover the available space within
803        // its viewport, stop trying to move the target render object to the center
804        // - otherwise, could end up changing which page is visible and moving the
805        // targetRenderObject out of the viewport.
806        ScrollPositionBase::ensure_visible(
807            self,
808            app,
809            object,
810            alignment,
811            duration,
812            curve,
813            alignment_policy,
814            None,
815        )
816    }
817
818    fn save_scroll_offset(self: Handle<Self>, app: &mut App) {
819        let storage_context = self.context(app).storage_context(app);
820        if let Some(bucket) = PageStorage::maybe_of(app, storage_context) {
821            let page = self.page_to_save(app);
822            bucket.write_state(app, storage_context, Rc::new(page), None);
823        }
824    }
825
826    fn restore_scroll_offset(self: Handle<Self>, app: &mut App) {
827        if !self.has_pixels(app) {
828            let storage_context = self.context(app).storage_context(app);
829            let value = PageStorage::maybe_of(app, storage_context)
830                .and_then(|bucket| bucket.read_state(app, storage_context, None))
831                .and_then(|data| data.downcast_ref::<f64>().copied());
832            if let Some(value) = value {
833                app.get_mut(self).page_to_use_on_startup = value;
834            }
835        }
836    }
837
838    fn save_offset(self: Handle<Self>, app: &mut App) {
839        let page = self.page_to_save(app);
840        self.context(app).save_offset(app, page);
841    }
842
843    fn restore_offset(self: Handle<Self>, app: &mut App, offset: f64, initial_restore: bool) {
844        if initial_restore {
845            app.get_mut(self).page_to_use_on_startup = offset;
846        } else {
847            let pixels = self.get_pixels_from_page(app, offset);
848            ViewportOffset::jump_to(self, app, pixels);
849        }
850    }
851}
852
853impl ScrollActivityDelegate for PagePosition {
854    crate::scroll_position_with_single_context_delegate_overrides!();
855}
856
857impl ScrollPositionWithSingleContextLeaf for PagePosition {
858    crate::scroll_position_with_single_context_accessors!();
859
860    fn absorb(self: Handle<Self>, app: &mut App, other: AnyScrollPosition) {
861        ScrollPositionWithSingleContext::absorb(self, app, other);
862        debug_assert!(app.get(self).cached_page.is_none());
863
864        let Some(other) = other.downcast::<PagePosition>(app) else {
865            return;
866        };
867
868        if let Some(cached_page) = app.get(other).cached_page {
869            app.get_mut(self).cached_page = Some(cached_page);
870        }
871    }
872}
873
874// ---------------------------------------------------------------------------------------------
875// _ForceImplicitScrollPhysics
876
877/// Dart's `_ForceImplicitScrollPhysics`: answers
878/// [`allow_implicit_scrolling`](ScrollPhysics::allow_implicit_scrolling) with its own value.
879struct ForceImplicitScrollPhysics {
880    allow_implicit_scrolling: bool,
881    parent: Option<ScrollPhysicsRef>,
882}
883
884impl ForceImplicitScrollPhysics {
885    fn new(allow_implicit_scrolling: bool) -> ForceImplicitScrollPhysics {
886        ForceImplicitScrollPhysics {
887            allow_implicit_scrolling,
888            parent: None,
889        }
890    }
891}
892
893impl ScrollPhysics for ForceImplicitScrollPhysics {
894    fn as_any(&self) -> &dyn Any {
895        self
896    }
897
898    fn parent(&self) -> Option<&ScrollPhysicsRef> {
899        self.parent.as_ref()
900    }
901
902    fn apply_to(&self, ancestor: Option<ScrollPhysicsRef>) -> ScrollPhysicsRef {
903        Rc::new(ForceImplicitScrollPhysics {
904            allow_implicit_scrolling: self.allow_implicit_scrolling,
905            parent: ScrollPhysicsBase::build_parent(self, ancestor),
906        })
907    }
908
909    fn allow_implicit_scrolling(&self) -> bool {
910        self.allow_implicit_scrolling
911    }
912}
913
914impl Debug for ForceImplicitScrollPhysics {
915    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
916        match &self.parent {
917            None => write!(f, "_ForceImplicitScrollPhysics"),
918            Some(parent) => write!(f, "_ForceImplicitScrollPhysics -> {parent:?}"),
919        }
920    }
921}
922
923// ---------------------------------------------------------------------------------------------
924// PageScrollPhysics
925
926/// Scroll physics used by a [`PageView`].
927///
928/// These physics cause the page view to snap to page boundaries.
929///
930/// See also:
931///
932///  * [`ScrollPhysics`], the base trait which defines the API for scrolling physics.
933///  * [`PageView::physics`], which can override the physics used by a page view.
934#[derive(Default)]
935pub struct PageScrollPhysics {
936    /// See [`ScrollPhysics::parent`].
937    pub parent: Option<ScrollPhysicsRef>,
938}
939
940impl PageScrollPhysics {
941    /// Creates physics for a [`PageView`].
942    pub fn new() -> PageScrollPhysics {
943        PageScrollPhysics::default()
944    }
945
946    /// Dart `PageScrollPhysics(parent:)`.
947    pub fn with_parent(mut self, parent: ScrollPhysicsRef) -> PageScrollPhysics {
948        self.parent = Some(parent);
949        self
950    }
951
952    // The physics are handed a page view's position as the snapshot its `copy_with` makes;
953    // `page_position` is Dart's `position is _PagePosition` on it.
954    fn get_page(&self, position: &dyn ScrollMetrics) -> f64 {
955        if let Some((metrics, snapshot)) = page_position(position) {
956            return metrics
957                .position_page(snapshot)
958                .expect("a page position with dimensions has a page");
959        }
960        position.pixels() / position.viewport_dimension()
961    }
962
963    fn get_pixels(&self, position: &dyn ScrollMetrics, page: f64) -> f64 {
964        if let Some((metrics, _)) = page_position(position) {
965            return metrics.position_pixels_from_page(page);
966        }
967        page * position.viewport_dimension()
968    }
969
970    fn get_target_pixels(
971        &self,
972        position: &dyn ScrollMetrics,
973        tolerance: Tolerance,
974        velocity: f64,
975    ) -> f64 {
976        let mut page = self.get_page(position);
977        if velocity < -tolerance.velocity {
978            page -= 0.5;
979        } else if velocity > tolerance.velocity {
980            page += 0.5;
981        }
982        self.get_pixels(position, page.round())
983    }
984}
985
986/// The page metrics and the position's snapshot when `position` is a page view's position.
987fn page_position(position: &dyn ScrollMetrics) -> Option<(&PageMetrics, PagePositionSnapshot)> {
988    let metrics = position.as_any().downcast_ref::<PageMetrics>()?;
989    metrics.position.map(|snapshot| (metrics, snapshot))
990}
991
992impl ScrollPhysics for PageScrollPhysics {
993    fn as_any(&self) -> &dyn Any {
994        self
995    }
996
997    fn parent(&self) -> Option<&ScrollPhysicsRef> {
998        self.parent.as_ref()
999    }
1000
1001    fn apply_to(&self, ancestor: Option<ScrollPhysicsRef>) -> ScrollPhysicsRef {
1002        Rc::new(PageScrollPhysics {
1003            parent: ScrollPhysicsBase::build_parent(self, ancestor),
1004        })
1005    }
1006
1007    fn create_ballistic_simulation(
1008        &self,
1009        position: &dyn ScrollMetrics,
1010        velocity: f64,
1011    ) -> Option<Box<dyn Simulation>> {
1012        // If we're out of range and not headed back in range, defer to the parent
1013        // ballistics, which should put us back in range at a page boundary.
1014        if (velocity <= 0.0 && position.pixels() <= position.min_scroll_extent())
1015            || (velocity >= 0.0 && position.pixels() >= position.max_scroll_extent())
1016        {
1017            return ScrollPhysicsBase::create_ballistic_simulation(self, position, velocity);
1018        }
1019        let tolerance = self.tolerance_for(position);
1020        let target = self.get_target_pixels(position, tolerance, velocity);
1021        if target != position.pixels() {
1022            return Some(Box::new(ScrollSpringSimulation::new(
1023                self.spring(),
1024                position.pixels(),
1025                target,
1026                velocity,
1027                tolerance,
1028            )));
1029        }
1030        None
1031    }
1032
1033    fn allow_implicit_scrolling(&self) -> bool {
1034        false
1035    }
1036
1037    fn allow_selection_edge_scrolling(&self) -> bool {
1038        false
1039    }
1040}
1041
1042impl Debug for PageScrollPhysics {
1043    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1044        match &self.parent {
1045            None => write!(f, "PageScrollPhysics"),
1046            Some(parent) => write!(f, "PageScrollPhysics -> {parent:?}"),
1047        }
1048    }
1049}
1050
1051// ---------------------------------------------------------------------------------------------
1052// PageView
1053
1054/// A scrollable list that works page by page.
1055///
1056/// Each child of a page view is forced to be the same size as the viewport.
1057///
1058/// You can use a [`PageController`] to control which page is visible in the view. In addition
1059/// to being able to control the pixel offset of the content inside the [`PageView`], a
1060/// [`PageController`] also lets you control the offset in terms of pages, which are increments
1061/// of the viewport size.
1062///
1063/// The [`PageController`] can also be used to control the
1064/// [`PageController::initial_page`], which determines which page is shown when the
1065/// [`PageView`] is first constructed, and the [`PageController::viewport_fraction`], which
1066/// determines the size of the pages as a fraction of the viewport size.
1067///
1068/// ## Persisting the scroll position during a session
1069///
1070/// Scroll views attempt to persist their scroll position using [`PageStorage`]. For a
1071/// [`PageView`], this can be disabled by setting [`PageController::keep_page`] to false on the
1072/// [`controller`](Self::controller). If it is enabled, using a `PageStorageKey` for the
1073/// [`key`](Self::key) of this widget is recommended to help disambiguate different scroll views
1074/// from each other.
1075///
1076/// See also:
1077///
1078///  * [`PageController`], which controls which page is visible in the view.
1079///  * `SingleChildScrollView`, when you need to make a single child scrollable.
1080///  * `ListView`, for a scrollable list of boxes.
1081///  * `GridView`, for a scrollable grid of boxes.
1082///  * [`ScrollNotification`] and [`NotificationListener`], which can be used to watch the
1083///    scroll position without using a `ScrollController`.
1084pub struct PageView {
1085    pub key: Option<KeyRef>,
1086
1087    /// Controls whether the widget's pages will respond to `RenderObject.showOnScreen`, which
1088    /// will allow for implicit accessibility scrolling.
1089    ///
1090    /// With this flag set to false, when accessibility focus reaches the end of the current
1091    /// page and the user attempts to move it to the next element, the focus will traverse to
1092    /// the next widget outside of the page view.
1093    ///
1094    /// With this flag set to true, when accessibility focus reaches the end of the current page
1095    /// and user attempts to move it to the next element, focus will traverse to the next page
1096    /// in the page view.
1097    pub allow_implicit_scrolling: bool,
1098
1099    /// The amount of content to lay out around the visible pages; `None` until given.
1100    ///
1101    /// In [`PageView`], the default uses [`ScrollCacheExtent::Viewport`], where the value
1102    /// represents the number of viewport lengths to cache beyond the visible area.
1103    ///
1104    /// When [`PageController::viewport_fraction`] is 1.0 (the default), this is equivalent to
1105    /// the number of pages. For example, `ScrollCacheExtent::Viewport(2.0)` caches 2 pages
1106    /// before and after the visible page.
1107    ///
1108    /// When [`PageController::viewport_fraction`] is less than 1.0, multiple pages may be
1109    /// visible in a single viewport, so `ScrollCacheExtent::Viewport(1.0)` may cache more than
1110    /// one additional page in each direction.
1111    ///
1112    /// [`ScrollCacheExtent::Pixels`] can also be used to specify the cache extent in logical
1113    /// pixels instead of viewport sizes.
1114    ///
1115    /// If it is given, its value must be consistent with
1116    /// [`allow_implicit_scrolling`](Self::allow_implicit_scrolling): the value must be greater
1117    /// than 0.0 when [`allow_implicit_scrolling`](Self::allow_implicit_scrolling) is true, and
1118    /// must be 0.0 when it is false.
1119    ///
1120    /// Defaults to `ScrollCacheExtent::Viewport(1.0)` if
1121    /// [`allow_implicit_scrolling`](Self::allow_implicit_scrolling) is true, and
1122    /// `ScrollCacheExtent::Viewport(0.0)` if it is false; read it through
1123    /// [`effective_scroll_cache_extent`](Self::effective_scroll_cache_extent).
1124    pub scroll_cache_extent: Option<ScrollCacheExtent>,
1125
1126    /// Restoration ID to save and restore the scroll offset of the scrollable.
1127    pub restoration_id: Option<String>,
1128
1129    /// The [`Axis`] along which the scroll view's offset increases with each page.
1130    ///
1131    /// For the direction in which active scrolling may be occurring, see
1132    /// `ScrollDirection`.
1133    ///
1134    /// Defaults to [`Axis::Horizontal`].
1135    pub scroll_direction: Axis,
1136
1137    /// Whether the page view scrolls in the reading direction.
1138    ///
1139    /// For example, if the reading direction is left-to-right and
1140    /// [`scroll_direction`](Self::scroll_direction) is [`Axis::Horizontal`], then the page view
1141    /// scrolls from left to right when [`reverse`](Self::reverse) is false and from right to
1142    /// left when [`reverse`](Self::reverse) is true.
1143    ///
1144    /// Similarly, if [`scroll_direction`](Self::scroll_direction) is [`Axis::Vertical`], then
1145    /// the page view scrolls from top to bottom when [`reverse`](Self::reverse) is false and
1146    /// from bottom to top when [`reverse`](Self::reverse) is true.
1147    ///
1148    /// Defaults to false.
1149    pub reverse: bool,
1150
1151    /// An object that can be used to control the position to which this page view is scrolled.
1152    pub controller: Option<Ref<PageController>>,
1153
1154    /// How the page view should respond to user input.
1155    ///
1156    /// For example, determines how the page view continues to animate after the user stops
1157    /// dragging the page view.
1158    ///
1159    /// The physics are modified to snap to page boundaries using [`PageScrollPhysics`] prior
1160    /// to being used.
1161    ///
1162    /// If an explicit [`ScrollBehaviorRef`] is provided to
1163    /// [`scroll_behavior`](Self::scroll_behavior), the [`ScrollPhysics`] provided by that
1164    /// behavior will take precedence after [`physics`](Self::physics).
1165    ///
1166    /// Defaults to matching platform conventions.
1167    pub physics: Option<ScrollPhysicsRef>,
1168
1169    /// Set to false to disable page snapping, useful for custom scroll behavior.
1170    ///
1171    /// If the [`pad_ends`](Self::pad_ends) is false and [`PageController::viewport_fraction`] <
1172    /// 1.0, the page will snap to the beginning of the viewport; otherwise, the page will snap
1173    /// to the center of the viewport.
1174    pub page_snapping: bool,
1175
1176    /// Called whenever the page in the center of the viewport changes.
1177    pub on_page_changed: Option<ValueChanged<i32>>,
1178
1179    /// A delegate that provides the children for the [`PageView`].
1180    ///
1181    /// The [`PageView::custom`] constructor lets you specify this delegate explicitly. The
1182    /// [`PageView::new`] and [`PageView::builder`] constructors create a
1183    /// [`children_delegate`](Self::children_delegate) that wraps the given list and builder,
1184    /// respectively.
1185    pub children_delegate: SliverChildDelegateRef,
1186
1187    /// Determines the way that drag start behavior is handled.
1188    pub drag_start_behavior: DragStartBehavior,
1189
1190    /// The content will be clipped (or not) according to this option.
1191    ///
1192    /// Defaults to [`Clip::HardEdge`].
1193    pub clip_behavior: Clip,
1194
1195    /// Defines the behavior of gesture detector used in this [`Scrollable`].
1196    ///
1197    /// Defaults to [`HitTestBehavior::Opaque`].
1198    pub hit_test_behavior: HitTestBehavior,
1199
1200    /// A [`ScrollBehaviorRef`] that will be applied to this widget individually.
1201    ///
1202    /// The scroll behavior of the inherited [`ScrollConfiguration`] will be modified by default
1203    /// to not apply a scrollbar.
1204    pub scroll_behavior: Option<ScrollBehaviorRef>,
1205
1206    /// Whether to add padding to both ends of the list.
1207    ///
1208    /// If this is set to true and [`PageController::viewport_fraction`] < 1.0, padding will be
1209    /// added such that the first and last child slivers will be in the center of the viewport
1210    /// when scrolled all the way to the start or end, respectively.
1211    ///
1212    /// If [`PageController::viewport_fraction`] >= 1.0, this property has no effect.
1213    ///
1214    /// This property defaults to true.
1215    pub pad_ends: bool,
1216}
1217
1218impl Default for PageView {
1219    fn default() -> PageView {
1220        PageView::custom(SliverChildListDelegate::new(Vec::new()).into_delegate())
1221    }
1222}
1223
1224impl PageView {
1225    /// Creates a scrollable list that works page by page from an explicit list of widgets,
1226    /// which the [`children`](Self::children) setter supplies.
1227    ///
1228    /// This constructor is appropriate for page views with a small number of children because
1229    /// constructing the list requires doing work for every child that could possibly be
1230    /// displayed in the page view, instead of just those children that are actually visible.
1231    pub fn new() -> PageView {
1232        PageView::default()
1233    }
1234
1235    /// Creates a scrollable list that works page by page using widgets that are created on
1236    /// demand.
1237    ///
1238    /// This constructor is appropriate for page views with a large (or infinite) number of
1239    /// children because the builder is called only for those children that are actually
1240    /// visible.
1241    ///
1242    /// Providing an [`item_count`](PageViewBuilder::item_count) lets the [`PageView`] compute
1243    /// the maximum scroll extent.
1244    ///
1245    /// The item builder will be called only with indices greater than or equal to zero and less
1246    /// than the item count.
1247    pub fn builder(
1248        item_builder: impl Fn(&mut App, BuildContext, i32) -> Option<WidgetRef> + 'static,
1249    ) -> PageViewBuilder {
1250        PageViewBuilder::new(Rc::new(item_builder))
1251    }
1252
1253    /// Creates a scrollable list that works page by page with a custom child model.
1254    pub fn custom(children_delegate: SliverChildDelegateRef) -> PageView {
1255        PageView {
1256            key: None,
1257            allow_implicit_scrolling: false,
1258            scroll_cache_extent: None,
1259            restoration_id: None,
1260            scroll_direction: Axis::Horizontal,
1261            reverse: false,
1262            controller: None,
1263            physics: None,
1264            page_snapping: true,
1265            on_page_changed: None,
1266            children_delegate,
1267            drag_start_behavior: DragStartBehavior::Start,
1268            clip_behavior: Clip::HardEdge,
1269            hit_test_behavior: HitTestBehavior::Opaque,
1270            scroll_behavior: None,
1271            pad_ends: true,
1272        }
1273    }
1274
1275    /// Dart `PageView(children:)`, which wraps the list in a `SliverChildListDelegate`.
1276    pub fn children(mut self, children: impl IntoIterator<Item = WidgetRef>) -> PageView {
1277        self.children_delegate =
1278            SliverChildListDelegate::new(children.into_iter().collect()).into_delegate();
1279        self
1280    }
1281
1282    /// Dart `PageView(key:)`.
1283    pub fn key(mut self, key: KeyRef) -> PageView {
1284        self.key = Some(key);
1285        self
1286    }
1287
1288    /// Dart `PageView(scrollDirection:)`.
1289    pub fn scroll_direction(mut self, scroll_direction: Axis) -> PageView {
1290        self.scroll_direction = scroll_direction;
1291        self
1292    }
1293
1294    /// Dart `PageView(reverse:)`.
1295    pub fn reverse(mut self, reverse: bool) -> PageView {
1296        self.reverse = reverse;
1297        self
1298    }
1299
1300    /// Dart `PageView(controller:)`.
1301    pub fn controller(mut self, controller: Ref<PageController>) -> PageView {
1302        self.controller = Some(controller);
1303        self
1304    }
1305
1306    /// Dart `PageView(physics:)`.
1307    pub fn physics(mut self, physics: ScrollPhysicsRef) -> PageView {
1308        self.physics = Some(physics);
1309        self
1310    }
1311
1312    /// Dart `PageView(pageSnapping:)`.
1313    pub fn page_snapping(mut self, page_snapping: bool) -> PageView {
1314        self.page_snapping = page_snapping;
1315        self
1316    }
1317
1318    /// Dart `PageView(onPageChanged:)`.
1319    pub fn on_page_changed(
1320        mut self,
1321        on_page_changed: impl Fn(&mut App, i32) + 'static,
1322    ) -> PageView {
1323        self.on_page_changed = Some(Rc::new(on_page_changed));
1324        self
1325    }
1326
1327    /// Dart `PageView(dragStartBehavior:)`.
1328    pub fn drag_start_behavior(mut self, drag_start_behavior: DragStartBehavior) -> PageView {
1329        self.drag_start_behavior = drag_start_behavior;
1330        self
1331    }
1332
1333    /// Dart `PageView(allowImplicitScrolling:)`.
1334    pub fn allow_implicit_scrolling(mut self, allow_implicit_scrolling: bool) -> PageView {
1335        self.allow_implicit_scrolling = allow_implicit_scrolling;
1336        self
1337    }
1338
1339    /// Dart `PageView(scrollCacheExtent:)`.
1340    pub fn scroll_cache_extent(mut self, scroll_cache_extent: ScrollCacheExtent) -> PageView {
1341        self.scroll_cache_extent = Some(scroll_cache_extent);
1342        self
1343    }
1344
1345    /// Dart `PageView(restorationId:)`.
1346    pub fn restoration_id(mut self, restoration_id: impl Into<String>) -> PageView {
1347        self.restoration_id = Some(restoration_id.into());
1348        self
1349    }
1350
1351    /// Dart `PageView(clipBehavior:)`.
1352    pub fn clip_behavior(mut self, clip_behavior: Clip) -> PageView {
1353        self.clip_behavior = clip_behavior;
1354        self
1355    }
1356
1357    /// Dart `PageView(hitTestBehavior:)`.
1358    pub fn hit_test_behavior(mut self, hit_test_behavior: HitTestBehavior) -> PageView {
1359        self.hit_test_behavior = hit_test_behavior;
1360        self
1361    }
1362
1363    /// Dart `PageView(scrollBehavior:)`.
1364    pub fn scroll_behavior(mut self, scroll_behavior: ScrollBehaviorRef) -> PageView {
1365        self.scroll_behavior = Some(scroll_behavior);
1366        self
1367    }
1368
1369    /// Dart `PageView(padEnds:)`.
1370    pub fn pad_ends(mut self, pad_ends: bool) -> PageView {
1371        self.pad_ends = pad_ends;
1372        self
1373    }
1374
1375    /// Dart's `scrollCacheExtent` field, as its constructor fills it.
1376    pub fn effective_scroll_cache_extent(&self) -> ScrollCacheExtent {
1377        self.scroll_cache_extent
1378            .unwrap_or(ScrollCacheExtent::Viewport(
1379                if self.allow_implicit_scrolling {
1380                    1.0
1381                } else {
1382                    0.0
1383                },
1384            ))
1385    }
1386}
1387
1388impl Debug for PageView {
1389    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1390        f.debug_struct("PageView")
1391            .field("scrollDirection", &self.scroll_direction)
1392            .field("reverse", &self.reverse)
1393            .field("controller", &self.controller)
1394            .field("physics", &self.physics)
1395            .field("pageSnapping", &self.page_snapping)
1396            .field("allowImplicitScrolling", &self.allow_implicit_scrolling)
1397            .finish()
1398    }
1399}
1400
1401impl StatefulWidget for PageView {
1402    type State = PageViewState;
1403
1404    fn key(&self) -> Option<&KeyRef> {
1405        self.key.as_ref()
1406    }
1407
1408    fn debug_check_constructor(&self) {
1409        debug_assert!(
1410            self.scroll_cache_extent
1411                .is_none_or(|extent| (extent.value() > 0.0) == self.allow_implicit_scrolling),
1412            "scrollCacheExtent and allowImplicitScrolling must be consistent: scrollCacheExtent \
1413             must be greater than 0.0 when allowImplicitScrolling is true, and must be 0.0 when \
1414             allowImplicitScrolling is false."
1415        );
1416    }
1417
1418    fn create_state(&self) -> PageViewState {
1419        PageViewState {
1420            state: StateData::new(),
1421            last_reported_page: 0,
1422            controller: None,
1423        }
1424    }
1425}
1426
1427/// Dart's `PageView.builder(..)` arguments that go to its delegate; the value converts to the
1428/// [`PageView`].
1429pub struct PageViewBuilder {
1430    delegate: SliverChildBuilderDelegate,
1431}
1432
1433impl PageViewBuilder {
1434    fn new(item_builder: NullableIndexedWidgetBuilder) -> PageViewBuilder {
1435        PageViewBuilder {
1436            delegate: SliverChildBuilderDelegate::from_builder(item_builder),
1437        }
1438    }
1439
1440    /// Dart `itemCount:`.
1441    pub fn item_count(mut self, item_count: i32) -> PageViewBuilder {
1442        self.delegate = self.delegate.child_count(item_count);
1443        self
1444    }
1445
1446    /// Dart `findChildIndexCallback:`.
1447    ///
1448    /// It corresponds to `SliverChildBuilderDelegate::find_child_index_callback`. If `None`, a
1449    /// child widget may not map to its existing render object when the order of children
1450    /// returned from the children builder changes. This may result in state-loss. This
1451    /// callback needs to be implemented if the order of the children may change at a later
1452    /// time.
1453    pub fn find_child_index_callback(mut self, value: ChildIndexGetter) -> PageViewBuilder {
1454        self.delegate = self.delegate.find_child_index_callback(value);
1455        self
1456    }
1457
1458    /// The [`PageView`] this builder describes, whose other arguments its setters take.
1459    pub fn build(self) -> PageView {
1460        PageView::custom(self.delegate.into_delegate())
1461    }
1462}
1463
1464impl IntoWidget<crate::framework::StatefulKind> for PageViewBuilder {
1465    #[cfg_attr(debug_assertions, track_caller)]
1466    fn into_widget(self) -> WidgetRef {
1467        self.build().into_widget()
1468    }
1469}
1470
1471/// The state of a [`PageView`]; Dart's `_PageViewState`.
1472pub struct PageViewState {
1473    state: StateData<PageView>,
1474    last_reported_page: i32,
1475    controller: Option<Ref<PageController>>,
1476}
1477
1478impl PageViewState {
1479    fn controller(self: Handle<Self>, app: &App) -> Handle<PageController> {
1480        app.get(self)
1481            .controller
1482            .handle()
1483            .expect("the controller is set in init_state")
1484    }
1485
1486    fn init_controller(self: Handle<Self>, app: &mut App) {
1487        let controller = match self.widget(app).controller.clone() {
1488            Some(controller) => controller,
1489            None => PageController::default(app),
1490        };
1491        app.get_mut(self).controller = Some(controller);
1492    }
1493
1494    fn get_direction(self: Handle<Self>, app: &mut App, context: BuildContext) -> AxisDirection {
1495        let widget = self.widget(app);
1496        let reverse = widget.reverse;
1497        match widget.scroll_direction {
1498            Axis::Horizontal => {
1499                let text_direction = Directionality::of(app, context);
1500                let axis_direction = text_direction_to_axis_direction(text_direction);
1501                if reverse {
1502                    flip_axis_direction(axis_direction)
1503                } else {
1504                    axis_direction
1505                }
1506            }
1507            Axis::Vertical => {
1508                if reverse {
1509                    AxisDirection::Up
1510                } else {
1511                    AxisDirection::Down
1512                }
1513            }
1514        }
1515    }
1516
1517    /// The `onNotification` of the listener `build` puts above the scrollable.
1518    fn handle_scroll_notification(
1519        self: Handle<Self>,
1520        app: &mut App,
1521        notification: &dyn ScrollNotification,
1522    ) -> bool {
1523        let on_page_changed = self.widget(app).on_page_changed.clone();
1524        if notification.depth() == 0
1525            && let Some(on_page_changed) = on_page_changed
1526            && notification.as_any().is::<ScrollUpdateNotification>()
1527        {
1528            let metrics = notification
1529                .metrics()
1530                .as_any()
1531                .downcast_ref::<PageMetrics>()
1532                .expect("a page view's position reports page metrics");
1533            let current_page = metrics.page().expect("page metrics have a page").round() as i32;
1534            if current_page != app.get(self).last_reported_page {
1535                app.get_mut(self).last_reported_page = current_page;
1536                on_page_changed(app, current_page);
1537            }
1538        }
1539        false
1540    }
1541}
1542
1543impl State for PageViewState {
1544    type Widget = PageView;
1545    crate::state_accessors!();
1546
1547    fn debug_fill_properties(
1548        self: Handle<Self>,
1549        app: &App,
1550        properties: &mut DiagnosticPropertiesBuilder,
1551    ) {
1552        let widget = self.widget(app);
1553        properties.add(EnumProperty::new(
1554            "scrollDirection",
1555            widget.scroll_direction,
1556        ));
1557        properties.add(FlagProperty::new("reverse", Some(widget.reverse)).if_true("reversed"));
1558        properties.add(
1559            DiagnosticsProperty::<String>::new(
1560                "controller",
1561                app.get(self)
1562                    .controller
1563                    .as_ref()
1564                    .map(|controller| controller.to_string(app)),
1565            )
1566            .with_show_name(false),
1567        );
1568        properties.add(
1569            DiagnosticsProperty::<String>::new(
1570                "physics",
1571                widget
1572                    .physics
1573                    .as_ref()
1574                    .map(|physics| format!("{physics:?}")),
1575            )
1576            .with_show_name(false),
1577        );
1578        properties.add(
1579            FlagProperty::new("pageSnapping", Some(widget.page_snapping))
1580                .if_false("snapping disabled"),
1581        );
1582        properties.add(
1583            FlagProperty::new(
1584                "allowImplicitScrolling",
1585                Some(widget.allow_implicit_scrolling),
1586            )
1587            .if_true("allow implicit scrolling"),
1588        );
1589        properties.add(
1590            DiagnosticsProperty::<ScrollCacheExtent>::new(
1591                "scrollCacheExtent",
1592                widget.scroll_cache_extent,
1593            )
1594            .default_value(Some(ScrollCacheExtent::Viewport(
1595                if widget.allow_implicit_scrolling {
1596                    1.0
1597                } else {
1598                    0.0
1599                },
1600            ))),
1601        );
1602    }
1603
1604    fn init_state(self: Handle<Self>, app: &mut App) {
1605        self.init_controller(app);
1606        let initial_page = self.controller(app).initial_page(app);
1607        app.get_mut(self).last_reported_page = initial_page;
1608    }
1609
1610    fn dispose(self: Handle<Self>, app: &mut App) {
1611        if self.widget(app).controller.is_none() {
1612            ScrollControllerLeaf::dispose(self.controller(app), app);
1613        }
1614    }
1615
1616    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &PageView) {
1617        if old_widget.controller != self.widget(app).controller {
1618            if old_widget.controller.is_none() {
1619                ScrollControllerLeaf::dispose(self.controller(app), app);
1620            }
1621            self.init_controller(app);
1622        }
1623    }
1624
1625    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
1626        let axis_direction = self.get_direction(app, context);
1627        let widget = self.widget(app);
1628        let allow_implicit_scrolling = widget.allow_implicit_scrolling;
1629        let page_snapping = widget.page_snapping;
1630        let widget_physics = widget.physics.clone();
1631        let widget_scroll_behavior = widget.scroll_behavior.clone();
1632        let base_physics = widget_physics.or_else(|| {
1633            widget_scroll_behavior
1634                .as_ref()
1635                .map(|behavior| behavior.get_scroll_physics(app, context))
1636        });
1637        let physics =
1638            ForceImplicitScrollPhysics::new(allow_implicit_scrolling).apply_to(if page_snapping {
1639                Some(PageScrollPhysics::new().apply_to(base_physics))
1640            } else {
1641                base_physics
1642            });
1643
1644        let widget = self.widget(app);
1645        let drag_start_behavior = widget.drag_start_behavior;
1646        let restoration_id = widget.restoration_id.clone();
1647        let hit_test_behavior = widget.hit_test_behavior;
1648        let scroll_cache_extent = widget.effective_scroll_cache_extent();
1649        let clip_behavior = widget.clip_behavior;
1650        let children_delegate = Rc::clone(&widget.children_delegate);
1651        let pad_ends = widget.pad_ends;
1652        let scroll_behavior = match widget_scroll_behavior {
1653            Some(scroll_behavior) => scroll_behavior,
1654            None => ScrollBehaviorRef::new(
1655                ScrollConfiguration::of(app, context)
1656                    .copy_with()
1657                    .scrollbars(false),
1658            ),
1659        };
1660        let controller = app
1661            .get(self)
1662            .controller
1663            .clone()
1664            .expect("the controller is set in init_state");
1665        let viewport_fraction = controller.viewport_fraction(app);
1666
1667        let viewport_builder: ViewportBuilder =
1668            Rc::new(move |_app, _context, position: ViewportOffsetRef| {
1669                Viewport::new(position)
1670                    .scroll_cache_extent(scroll_cache_extent)
1671                    .axis_direction(axis_direction)
1672                    .clip_behavior(clip_behavior)
1673                    .slivers(vec![
1674                        SliverFillViewport::new(Rc::clone(&children_delegate))
1675                            .viewport_fraction(viewport_fraction)
1676                            .pad_ends(pad_ends)
1677                            .allow_implicit_scrolling(allow_implicit_scrolling)
1678                            .into_widget(),
1679                    ])
1680                    .into_widget()
1681            });
1682        let mut scrollable = Scrollable::new(viewport_builder)
1683            .drag_start_behavior(drag_start_behavior)
1684            .axis_direction(axis_direction)
1685            .controller(controller.into_erased())
1686            .physics(physics)
1687            .hit_test_behavior(hit_test_behavior)
1688            .scroll_behavior(scroll_behavior);
1689        if let Some(restoration_id) = restoration_id {
1690            scrollable = scrollable.restoration_id(restoration_id);
1691        }
1692
1693        NotificationListener::<dyn ScrollNotification>::new(scrollable)
1694            .on_notification(
1695                move |app: &mut App, notification: &dyn ScrollNotification| {
1696                    self.handle_scroll_notification(app, notification)
1697                },
1698            )
1699            .into_widget()
1700    }
1701}
1702
1703/// The part of `flutter_test`'s `WidgetTester` the page view and sliver fill tests use: an
1704/// 800 x 600 view at pixel ratio 3, a fake clock that a pump advances, and pointers sent straight
1705/// to the gesture binding.
1706#[cfg(test)]
1707mod tests {
1708    use std::cell::{Cell, RefCell};
1709    use std::panic::{AssertUnwindSafe, catch_unwind};
1710    use std::rc::Rc;
1711    use std::time::Duration;
1712
1713    use waft_animation::Curves;
1714    use waft_embedder::{Offset, Size, TextDirection};
1715    use waft_rendering::{RenderHandle, RenderSliver, RenderSliverFillViewport};
1716
1717    use waft_embedder::{Color, TargetPlatform};
1718    use waft_foundation::{Listener, ValueKey};
1719    use waft_rendering::{RenderBox, RenderViewport, RenderViewportBase};
1720
1721    use super::*;
1722    use crate::testing::{
1723        Finder, TargetPlatformVariant, TestPointer, WidgetTester, assert_more_or_less_equals,
1724        expect, find, finds_nothing, finds_one_widget, test_widgets, test_widgets_variant,
1725    };
1726    use crate::widgets::basic::{Builder, Center, Column, Expanded, OverflowBox, SizedBox};
1727    use crate::widgets::container::Container;
1728    use crate::widgets::gesture_detector::GestureDetector;
1729    use crate::widgets::overlay::{Overlay, OverlayEntry};
1730    use crate::widgets::page_storage::{PageStorage, PageStorageBucket, PageStorageKey};
1731    use crate::widgets::scroll_physics::{BouncingScrollPhysics, ClampingScrollPhysics};
1732    use crate::widgets::text::Text;
1733
1734    const K_BLUE: Color = Color::new(0xFF0000FF);
1735    const K_GREEN: Color = Color::new(0xFF00FF00);
1736
1737    /// `states.dart`'s `kStates`.
1738    const K_STATES: [&str; 50] = [
1739        "Alabama",
1740        "Alaska",
1741        "Arizona",
1742        "Arkansas",
1743        "California",
1744        "Colorado",
1745        "Connecticut",
1746        "Delaware",
1747        "Florida",
1748        "Georgia",
1749        "Hawaii",
1750        "Idaho",
1751        "Illinois",
1752        "Indiana",
1753        "Iowa",
1754        "Kansas",
1755        "Kentucky",
1756        "Louisiana",
1757        "Maine",
1758        "Maryland",
1759        "Massachusetts",
1760        "Michigan",
1761        "Minnesota",
1762        "Mississippi",
1763        "Missouri",
1764        "Montana",
1765        "Nebraska",
1766        "Nevada",
1767        "New Hampshire",
1768        "New Jersey",
1769        "New Mexico",
1770        "New York",
1771        "North Carolina",
1772        "North Dakota",
1773        "Ohio",
1774        "Oklahoma",
1775        "Oregon",
1776        "Pennsylvania",
1777        "Rhode Island",
1778        "South Carolina",
1779        "South Dakota",
1780        "Tennessee",
1781        "Texas",
1782        "Utah",
1783        "Vermont",
1784        "Virginia",
1785        "Washington",
1786        "West Virginia",
1787        "Wisconsin",
1788        "Wyoming",
1789    ];
1790
1791    fn index_of(state: &str) -> i32 {
1792        K_STATES
1793            .iter()
1794            .position(|candidate| *candidate == state)
1795            .expect("a state") as i32
1796    }
1797
1798    /// `kStates.map((state) => Text(state))`.
1799    fn states() -> Vec<WidgetRef> {
1800        K_STATES
1801            .iter()
1802            .map(|&state| Text::new(state).into_widget())
1803            .collect()
1804    }
1805
1806    fn ltr<K>(child: impl IntoWidget<K>) -> WidgetRef {
1807        Directionality::new(TextDirection::Ltr, child).into_widget()
1808    }
1809
1810    fn centered<K>(width: f64, height: f64, child: impl IntoWidget<K>) -> WidgetRef {
1811        ltr(Center::new().child(SizedBox::new().width(width).height(height).child(child)))
1812    }
1813
1814    fn fill_viewport(tester: &WidgetTester) -> RenderHandle<RenderSliverFillViewport> {
1815        *tester
1816            .all::<RenderSliverFillViewport>()
1817            .first()
1818            .expect("a mounted page view")
1819    }
1820
1821    fn page(tester: &WidgetTester, controller: Handle<PageController>) -> Option<f64> {
1822        controller.page(&tester.cell.borrow())
1823    }
1824
1825    fn new_controller(
1826        tester: &WidgetTester,
1827        initial_page: i32,
1828        viewport_fraction: f64,
1829    ) -> Ref<PageController> {
1830        PageController::new(
1831            &mut tester.cell.borrow_mut(),
1832            initial_page,
1833            true,
1834            viewport_fraction,
1835            None,
1836            None,
1837        )
1838    }
1839
1840    #[test]
1841    #[should_panic(expected = "PageController.page cannot be accessed before a PageView is built")]
1842    fn a_page_controller_cannot_return_its_page_while_unattached() {
1843        test_widgets(|tester| {
1844            let controller = PageController::default(&mut tester.cell.borrow_mut());
1845            page(tester, controller.handle());
1846        });
1847    }
1848
1849    #[test]
1850    fn a_page_view_drags_and_flings_from_page_to_page() {
1851        test_widgets(|tester| {
1852            let log: Rc<RefCell<Vec<&str>>> = Rc::new(RefCell::new(Vec::new()));
1853            tester.pump_widget(ltr(PageView::new()
1854                .drag_start_behavior(DragStartBehavior::Down)
1855                .children(K_STATES.iter().map(|&state| {
1856                    let log = Rc::clone(&log);
1857                    GestureDetector::new()
1858                        .drag_start_behavior(DragStartBehavior::Down)
1859                        .on_tap(Listener::new(move |_| log.borrow_mut().push(state)))
1860                        .child(
1861                            Container::new()
1862                                .height(200.0)
1863                                .color(K_BLUE)
1864                                .child(Text::new(state)),
1865                        )
1866                        .into_widget()
1867                }))));
1868
1869            tester.tap(find::text("Alabama"));
1870            assert_eq!(*log.borrow(), ["Alabama"]);
1871            log.borrow_mut().clear();
1872
1873            expect(tester, &find::text("Alaska"), finds_nothing());
1874
1875            tester.drag(find::by_type::<PageView>(), Offset::new(-20.0, 0.0));
1876            tester.pump();
1877
1878            expect(tester, &find::text("Alabama"), finds_one_widget());
1879            expect(tester, &find::text("Alaska"), finds_one_widget());
1880            expect(tester, &find::text("Arizona"), finds_nothing());
1881
1882            tester.pump_and_settle();
1883
1884            expect(tester, &find::text("Alabama"), finds_one_widget());
1885            expect(tester, &find::text("Alaska"), finds_nothing());
1886
1887            tester.drag(find::by_type::<PageView>(), Offset::new(-401.0, 0.0));
1888            tester.pump_and_settle();
1889
1890            expect(tester, &find::text("Alabama"), finds_nothing());
1891            expect(tester, &find::text("Alaska"), finds_one_widget());
1892            expect(tester, &find::text("Arizona"), finds_nothing());
1893
1894            tester.tap(find::text("Alaska"));
1895            assert_eq!(*log.borrow(), ["Alaska"]);
1896            log.borrow_mut().clear();
1897
1898            tester.fling(
1899                find::by_type::<PageView>(),
1900                Offset::new(-200.0, 0.0),
1901                1000.0,
1902            );
1903            tester.pump_and_settle();
1904
1905            expect(tester, &find::text("Alabama"), finds_nothing());
1906            expect(tester, &find::text("Alaska"), finds_nothing());
1907            expect(tester, &find::text("Arizona"), finds_one_widget());
1908
1909            tester.fling(find::by_type::<PageView>(), Offset::new(200.0, 0.0), 1000.0);
1910            tester.pump_and_settle();
1911
1912            expect(tester, &find::text("Alabama"), finds_nothing());
1913            expect(tester, &find::text("Alaska"), finds_one_widget());
1914            expect(tester, &find::text("Arizona"), finds_nothing());
1915        });
1916    }
1917
1918    #[test]
1919    fn a_page_controller_steps_to_the_next_and_previous_page_across_a_resize() {
1920        test_widgets(|tester| {
1921            let controller = new_controller(tester, 4, 1.0);
1922            tester.pump_widget(centered(
1923                600.0,
1924                400.0,
1925                PageView::new()
1926                    .controller(controller.clone())
1927                    .children(states()),
1928            ));
1929
1930            expect(tester, &find::text("California"), finds_one_widget());
1931
1932            drop(controller.next_page(
1933                &mut tester.cell.borrow_mut(),
1934                Duration::from_millis(150),
1935                Curves::ease(),
1936            ));
1937            tester.pump_and_settle();
1938
1939            expect(tester, &find::text("Colorado"), finds_one_widget());
1940
1941            tester.pump_widget(centered(
1942                300.0,
1943                400.0,
1944                PageView::new()
1945                    .controller(controller.clone())
1946                    .children(states()),
1947            ));
1948
1949            expect(tester, &find::text("Colorado"), finds_one_widget());
1950
1951            drop(controller.previous_page(
1952                &mut tester.cell.borrow_mut(),
1953                Duration::from_millis(150),
1954                Curves::ease(),
1955            ));
1956            tester.pump_and_settle();
1957
1958            expect(tester, &find::text("California"), finds_one_widget());
1959        });
1960    }
1961
1962    #[test]
1963    fn the_page_is_stable_across_resizes() {
1964        test_widgets(|tester| {
1965            tester.pump_widget(centered(600.0, 400.0, PageView::new().children(states())));
1966
1967            expect(tester, &find::text("Alabama"), finds_one_widget());
1968
1969            tester.drag(find::by_type::<PageView>(), Offset::new(-1250.0, 0.0));
1970            tester.pump_and_settle();
1971
1972            expect(tester, &find::text("Arizona"), finds_one_widget());
1973
1974            tester.pump_widget(centered(250.0, 100.0, PageView::new().children(states())));
1975
1976            expect(tester, &find::text("Arizona"), finds_one_widget());
1977
1978            tester.pump_widget(centered(450.0, 400.0, PageView::new().children(states())));
1979
1980            expect(tester, &find::text("Arizona"), finds_one_widget());
1981        });
1982    }
1983
1984    #[test]
1985    fn next_and_previous_page_resolve_when_their_animation_ends() {
1986        test_widgets(|tester| {
1987            let controller = PageController::default(&mut tester.cell.borrow_mut());
1988            tester.pump_widget(ltr(PageView::new()
1989                .controller(controller.clone())
1990                .children(states())));
1991
1992            let next_page = controller.next_page(
1993                &mut tester.cell.borrow_mut(),
1994                Duration::from_millis(150),
1995                Curves::ease(),
1996            );
1997
1998            assert!(!next_page.is_completed());
1999            tester.pump_by(Duration::from_millis(200));
2000            assert!(!next_page.is_completed());
2001            tester.pump_by(Duration::from_millis(200));
2002            assert!(next_page.is_completed());
2003
2004            let previous_page = controller.previous_page(
2005                &mut tester.cell.borrow_mut(),
2006                Duration::from_millis(150),
2007                Curves::ease(),
2008            );
2009
2010            assert!(!previous_page.is_completed());
2011            tester.pump_by(Duration::from_millis(200));
2012            assert!(!previous_page.is_completed());
2013            tester.pump_by(Duration::from_millis(200));
2014            assert!(previous_page.is_completed());
2015        });
2016    }
2017
2018    #[test]
2019    fn a_page_view_in_a_zero_size_container_builds_its_first_page() {
2020        test_widgets(|tester| {
2021            tester
2022                .pump_widget(ltr(Center::new()
2023                    .child(SizedBox::shrink().child(PageView::new().children(states())))));
2024
2025            expect(
2026                tester,
2027                &find::text("Alabama").skip_offstage(false),
2028                finds_one_widget(),
2029            );
2030
2031            tester.pump_widget(centered(200.0, 200.0, PageView::new().children(states())));
2032
2033            expect(tester, &find::text("Alabama"), finds_one_widget());
2034        });
2035    }
2036
2037    fn sized_page_view(size: Size, controller: &Ref<PageController>) -> WidgetRef {
2038        ltr(Center::new().child(
2039            SizedBox::from_size(Some(size)).child(
2040                PageView::new()
2041                    .controller(controller.clone())
2042                    .on_page_changed(|_, _| {})
2043                    .children(states()),
2044            ),
2045        ))
2046    }
2047
2048    #[test]
2049    fn a_resize_from_a_zero_size_viewport_keeps_the_page() {
2050        test_widgets(|tester| {
2051            let controller = new_controller(tester, 1, 1.0);
2052
2053            // The pageView have a zero viewport, so nothing display.
2054            tester.pump_widget(sized_page_view(Size::ZERO, &controller));
2055            expect(tester, &find::text("Alabama"), finds_nothing());
2056            expect(
2057                tester,
2058                &find::text("Alabama").skip_offstage(false),
2059                finds_one_widget(),
2060            );
2061
2062            // Resize from zero viewport to non-zero, the controller's initialPage 1 will display.
2063            tester.pump_widget(sized_page_view(Size::new(200.0, 200.0), &controller));
2064            expect(tester, &find::text("Alaska"), finds_one_widget());
2065
2066            // Jump to page 'Iowa'.
2067            controller.jump_to_page(&mut tester.cell.borrow_mut(), index_of("Iowa"));
2068            tester.pump();
2069            expect(tester, &find::text("Iowa"), finds_one_widget());
2070
2071            // Resize to zero viewport again, nothing display.
2072            tester.pump_widget(sized_page_view(Size::ZERO, &controller));
2073            expect(tester, &find::text("Iowa"), finds_nothing());
2074
2075            // Resize from zero to non-zero, the pageView should not lose state, so the page 'Iowa'
2076            // show again.
2077            tester.pump_widget(sized_page_view(Size::new(200.0, 200.0), &controller));
2078            expect(tester, &find::text("Iowa"), finds_one_widget());
2079        });
2080    }
2081
2082    #[test]
2083    fn the_controller_changes_the_page_of_a_zero_size_viewport() {
2084        test_widgets(|tester| {
2085            let controller = new_controller(tester, 1, 1.0);
2086
2087            // The pageView have a zero viewport, so nothing display.
2088            tester.pump_widget(sized_page_view(Size::ZERO, &controller));
2089            assert_eq!(tester.get_size(find::by_type::<PageView>()), Size::ZERO);
2090            expect(tester, &find::text("Alabama"), finds_nothing());
2091            expect(
2092                tester,
2093                &find::text("Alabama").skip_offstage(false),
2094                finds_one_widget(),
2095            );
2096
2097            // Change the page through the page controller when zero viewport
2098            drop(controller.animate_to_page(
2099                &mut tester.cell.borrow_mut(),
2100                index_of("Iowa"),
2101                Duration::from_millis(300),
2102                Curves::ease(),
2103            ));
2104            assert_eq!(
2105                page(tester, controller.handle()),
2106                Some(f64::from(index_of("Iowa")))
2107            );
2108
2109            controller.jump_to_page(&mut tester.cell.borrow_mut(), index_of("Illinois"));
2110            assert_eq!(
2111                page(tester, controller.handle()),
2112                Some(f64::from(index_of("Illinois")))
2113            );
2114
2115            // Resize from zero viewport to non-zero, the latest state should not lost.
2116            tester.pump_widget(sized_page_view(Size::new(200.0, 200.0), &controller));
2117            assert_eq!(
2118                page(tester, controller.handle()),
2119                Some(f64::from(index_of("Illinois")))
2120            );
2121            expect(tester, &find::text("Illinois"), finds_one_widget());
2122        });
2123    }
2124
2125    fn logged_page_view(log: &Rc<RefCell<Vec<i32>>>, page_snapping: bool) -> WidgetRef {
2126        let log = Rc::clone(log);
2127        ltr(PageView::new()
2128            .page_snapping(page_snapping)
2129            .on_page_changed(move |_, page| log.borrow_mut().push(page))
2130            .children(states()))
2131    }
2132
2133    #[test]
2134    fn the_page_changes_at_the_halfway_point() {
2135        test_widgets(|tester| {
2136            let log = Rc::new(RefCell::new(Vec::new()));
2137            tester.pump_widget(logged_page_view(&log, true));
2138
2139            assert!(log.borrow().is_empty());
2140
2141            let mut gesture = TestPointer::touch(1);
2142            tester.down(&mut gesture, Offset::new(100.0, 100.0));
2143            // The page view is 800.0 wide, so this move is just short of halfway.
2144            tester.move_by(&mut gesture, Offset::new(-380.0, 0.0), true);
2145
2146            assert!(log.borrow().is_empty());
2147
2148            // We've crossed the halfway mark.
2149            tester.move_by(&mut gesture, Offset::new(-40.0, 0.0), true);
2150
2151            assert_eq!(*log.borrow(), vec![1]);
2152            log.borrow_mut().clear();
2153
2154            // Moving a bit more should not generate redundant notifications.
2155            tester.move_by(&mut gesture, Offset::new(-40.0, 0.0), true);
2156
2157            assert!(log.borrow().is_empty());
2158
2159            for _ in 0..3 {
2160                tester.move_by(&mut gesture, Offset::new(-40.0, 0.0), true);
2161                tester.pump();
2162            }
2163
2164            assert!(log.borrow().is_empty());
2165
2166            tester.up(&gesture);
2167            tester.pump_and_settle();
2168
2169            assert!(log.borrow().is_empty());
2170
2171            expect(tester, &find::text("Alabama"), finds_nothing());
2172            expect(tester, &find::text("Alaska"), finds_one_widget());
2173        });
2174    }
2175
2176    #[test]
2177    fn bouncing_ballistics_settle_back_on_the_first_page_without_overshooting() {
2178        test_widgets(|tester| {
2179            let log = Rc::new(RefCell::new(Vec::new()));
2180            let controller = new_controller(tester, 0, 0.9);
2181            let build = |size: Option<Size>| -> WidgetRef {
2182                let log = Rc::clone(&log);
2183                let page_view = ltr(PageView::new()
2184                    .controller(controller.clone())
2185                    .on_page_changed(move |_, page| log.borrow_mut().push(page))
2186                    .physics(Rc::new(BouncingScrollPhysics::new()))
2187                    .children(states()));
2188                match size {
2189                    Some(size) => OverflowBox::new()
2190                        .min_width(size.width())
2191                        .min_height(size.height())
2192                        .max_width(size.width())
2193                        .max_height(size.height())
2194                        .child(page_view)
2195                        .into_widget(),
2196                    None => page_view,
2197                }
2198            };
2199
2200            tester.pump_widget(build(None));
2201            assert!(log.borrow().is_empty());
2202
2203            // Fling right to move to a non-existent page at the beginning of the
2204            // PageView, and confirm that the PageView settles back on the first page.
2205            tester.fling(find::by_type::<PageView>(), Offset::new(100.0, 0.0), 800.0);
2206            tester.pump_and_settle();
2207            assert!(log.borrow().is_empty());
2208
2209            expect(tester, &find::text("Alabama"), finds_one_widget());
2210            expect(tester, &find::text("Alaska"), finds_one_widget());
2211            expect(tester, &find::text("Arizona"), finds_nothing());
2212
2213            // Try again with a Cupertino "Plus" device size.
2214            tester.pump_widget(build(Some(Size::new(414.0, 736.0))));
2215            assert!(log.borrow().is_empty());
2216
2217            tester.fling(find::by_type::<PageView>(), Offset::new(100.0, 0.0), 800.0);
2218            tester.pump_and_settle();
2219            assert!(log.borrow().is_empty());
2220
2221            expect(tester, &find::text("Alabama"), finds_one_widget());
2222            expect(tester, &find::text("Alaska"), finds_one_widget());
2223            expect(tester, &find::text("Arizona"), finds_nothing());
2224        });
2225    }
2226
2227    /// The viewport fraction tests' `PageView.builder`: a page per label, a `Container` of
2228    /// height 200, blue or green by the index's parity, showing the label.
2229    fn built_page_view(controller: &Ref<PageController>, labels: Vec<String>) -> WidgetRef {
2230        let item_count = labels.len() as i32;
2231        ltr(PageView::builder(move |_, _, index| {
2232            Some(
2233                Container::new()
2234                    .height(200.0)
2235                    .color(if index % 2 == 0 { K_BLUE } else { K_GREEN })
2236                    .child(Text::new(labels[index as usize].clone()))
2237                    .into_widget(),
2238            )
2239        })
2240        .item_count(item_count)
2241        .build()
2242        .controller(controller.clone()))
2243    }
2244
2245    /// `kStates`, as the viewport fraction tests label their pages.
2246    fn state_labels() -> Vec<String> {
2247        K_STATES.iter().map(|state| state.to_string()).collect()
2248    }
2249
2250    /// `index.toString()` for `count` pages.
2251    fn index_labels(count: i32) -> Vec<String> {
2252        (0..count).map(|index| index.to_string()).collect()
2253    }
2254
2255    #[test]
2256    fn pages_fill_their_viewport_fraction() {
2257        test_widgets(|tester| {
2258            let controller = new_controller(tester, 0, 7.0 / 8.0);
2259            tester.pump_widget(built_page_view(&controller, state_labels()));
2260
2261            assert_eq!(
2262                tester.get_top_left(find::text("Alabama")),
2263                Offset::new(50.0, 0.0)
2264            );
2265            assert_eq!(
2266                tester.get_top_left(find::text("Alaska")),
2267                Offset::new(750.0, 0.0)
2268            );
2269
2270            controller.jump_to_page(&mut tester.cell.borrow_mut(), 10);
2271            tester.pump();
2272
2273            assert_eq!(
2274                tester.get_top_left(find::text("Georgia")),
2275                Offset::new(-650.0, 0.0)
2276            );
2277            assert_eq!(
2278                tester.get_top_left(find::text("Hawaii")),
2279                Offset::new(50.0, 0.0)
2280            );
2281            assert_eq!(
2282                tester.get_top_left(find::text("Idaho")),
2283                Offset::new(750.0, 0.0)
2284            );
2285
2286            let controller = new_controller(tester, 0, 39.0 / 40.0);
2287            tester.pump_widget(built_page_view(&controller, state_labels()));
2288
2289            assert_eq!(
2290                tester.get_top_left(find::text("Georgia")),
2291                Offset::new(-770.0, 0.0)
2292            );
2293            assert_eq!(
2294                tester.get_top_left(find::text("Hawaii")),
2295                Offset::new(10.0, 0.0)
2296            );
2297            assert_eq!(
2298                tester.get_top_left(find::text("Idaho")),
2299                Offset::new(790.0, 0.0)
2300            );
2301        });
2302    }
2303
2304    #[test]
2305    fn page_snapping_can_be_disabled_and_reenabled() {
2306        test_widgets(|tester| {
2307            let log = Rc::new(RefCell::new(Vec::new()));
2308            tester.pump_widget(logged_page_view(&log, true));
2309            assert!(log.borrow().is_empty());
2310
2311            // Drag more than halfway to the next page, to confirm the default behavior.
2312            let mut gesture = TestPointer::touch(1);
2313            tester.down(&mut gesture, Offset::new(100.0, 100.0));
2314            // The page view is 800.0 wide, so this move is just beyond halfway.
2315            tester.move_by(&mut gesture, Offset::new(-420.0, 0.0), true);
2316
2317            assert_eq!(*log.borrow(), vec![1]);
2318            log.borrow_mut().clear();
2319
2320            // Release the gesture, confirm that the page settles on the next.
2321            tester.up(&gesture);
2322            tester.pump_and_settle();
2323
2324            expect(tester, &find::text("Alabama"), finds_nothing());
2325            expect(tester, &find::text("Alaska"), finds_one_widget());
2326
2327            // Disable page snapping, and try moving halfway. Confirm it doesn't snap.
2328            tester.pump_widget(logged_page_view(&log, false));
2329            let mut gesture = TestPointer::touch(1);
2330            tester.down(&mut gesture, Offset::new(100.0, 100.0));
2331            // Move just beyond halfway, again.
2332            tester.move_by(&mut gesture, Offset::new(-420.0, 0.0), true);
2333
2334            // Page notifications still get sent.
2335            assert_eq!(*log.borrow(), vec![2]);
2336            log.borrow_mut().clear();
2337
2338            // Release the gesture, confirm that both pages are visible.
2339            tester.up(&gesture);
2340            tester.pump_and_settle();
2341
2342            expect(tester, &find::text("Alabama"), finds_nothing());
2343            expect(tester, &find::text("Alaska"), finds_one_widget());
2344            expect(tester, &find::text("Arizona"), finds_one_widget());
2345            expect(tester, &find::text("Arkansas"), finds_nothing());
2346
2347            // Now re-enable snapping, confirm that we've settled on a page.
2348            tester.pump_widget(logged_page_view(&log, true));
2349            tester.pump_and_settle();
2350
2351            assert!(log.borrow().is_empty());
2352
2353            expect(tester, &find::text("Alaska"), finds_nothing());
2354            expect(tester, &find::text("Arizona"), finds_one_widget());
2355            expect(tester, &find::text("Arkansas"), finds_nothing());
2356        });
2357    }
2358
2359    #[test]
2360    fn a_small_viewport_fraction_shows_several_pages() {
2361        test_widgets(|tester| {
2362            let controller = new_controller(tester, 0, 1.0 / 8.0);
2363            tester.pump_widget(built_page_view(&controller, state_labels()));
2364
2365            assert_eq!(
2366                tester.get_top_left(find::text("Alabama")),
2367                Offset::new(350.0, 0.0)
2368            );
2369            assert_eq!(
2370                tester.get_top_left(find::text("Alaska")),
2371                Offset::new(450.0, 0.0)
2372            );
2373            assert_eq!(
2374                tester.get_top_left(find::text("Arizona")),
2375                Offset::new(550.0, 0.0)
2376            );
2377            assert_eq!(
2378                tester.get_top_left(find::text("Arkansas")),
2379                Offset::new(650.0, 0.0)
2380            );
2381            assert_eq!(
2382                tester.get_top_left(find::text("California")),
2383                Offset::new(750.0, 0.0)
2384            );
2385
2386            controller.jump_to_page(&mut tester.cell.borrow_mut(), 10);
2387            tester.pump();
2388
2389            assert_eq!(
2390                tester.get_top_left(find::text("Connecticut")),
2391                Offset::new(-50.0, 0.0)
2392            );
2393            assert_eq!(
2394                tester.get_top_left(find::text("Delaware")),
2395                Offset::new(50.0, 0.0)
2396            );
2397            assert_eq!(
2398                tester.get_top_left(find::text("Florida")),
2399                Offset::new(150.0, 0.0)
2400            );
2401            assert_eq!(
2402                tester.get_top_left(find::text("Georgia")),
2403                Offset::new(250.0, 0.0)
2404            );
2405            assert_eq!(
2406                tester.get_top_left(find::text("Hawaii")),
2407                Offset::new(350.0, 0.0)
2408            );
2409            assert_eq!(
2410                tester.get_top_left(find::text("Idaho")),
2411                Offset::new(450.0, 0.0)
2412            );
2413            assert_eq!(
2414                tester.get_top_left(find::text("Illinois")),
2415                Offset::new(550.0, 0.0)
2416            );
2417            assert_eq!(
2418                tester.get_top_left(find::text("Indiana")),
2419                Offset::new(650.0, 0.0)
2420            );
2421            assert_eq!(
2422                tester.get_top_left(find::text("Iowa")),
2423                Offset::new(750.0, 0.0)
2424            );
2425        });
2426    }
2427
2428    #[test]
2429    fn a_large_viewport_fraction_centers_pages_wider_than_the_viewport() {
2430        test_widgets(|tester| {
2431            let controller = new_controller(tester, 0, 5.0 / 4.0);
2432            tester.pump_widget(built_page_view(&controller, state_labels()));
2433
2434            assert_eq!(
2435                tester.get_top_left(find::text("Alabama")),
2436                Offset::new(-100.0, 0.0)
2437            );
2438            assert_eq!(
2439                tester.get_bottom_right(find::text("Alabama")),
2440                Offset::new(900.0, 600.0)
2441            );
2442
2443            controller.jump_to_page(&mut tester.cell.borrow_mut(), 10);
2444            tester.pump();
2445
2446            assert_eq!(
2447                tester.get_top_left(find::text("Hawaii")),
2448                Offset::new(-100.0, 0.0)
2449            );
2450        });
2451    }
2452
2453    #[test]
2454    fn a_new_controller_with_a_larger_viewport_fraction_centers_its_page() {
2455        test_widgets(|tester| {
2456            let old_controller = new_controller(tester, 0, 5.0 / 4.0);
2457            tester.pump_widget(built_page_view(&old_controller, state_labels()));
2458
2459            assert_eq!(
2460                tester.get_top_left(find::text("Alabama")),
2461                Offset::new(-100.0, 0.0)
2462            );
2463
2464            let new_controller = new_controller(tester, 0, 4.0);
2465            tester.pump_widget(built_page_view(&new_controller, state_labels()));
2466            new_controller.jump_to_page(&mut tester.cell.borrow_mut(), 10);
2467            tester.pump();
2468
2469            assert_eq!(
2470                tester.get_top_left(find::text("Hawaii")),
2471                Offset::new(-(4.0 - 1.0) * 800.0 / 2.0, 0.0)
2472            );
2473        });
2474    }
2475
2476    #[test]
2477    fn a_large_viewport_fraction_scrolls_to_the_last_page_and_snaps() {
2478        test_widgets(|tester| {
2479            let controller = new_controller(tester, 0, 5.0 / 4.0);
2480            tester.pump_widget(built_page_view(&controller, index_labels(3)));
2481
2482            assert_eq!(
2483                tester.get_center(find::text("0")),
2484                Offset::new(400.0, 300.0)
2485            );
2486
2487            controller.jump_to_page(&mut tester.cell.borrow_mut(), 2);
2488            tester.pump();
2489            tester.pump_and_settle();
2490
2491            assert_eq!(
2492                tester.get_center(find::text("2")),
2493                Offset::new(400.0, 300.0)
2494            );
2495        });
2496    }
2497
2498    /// Not in page_view_test.dart: Dart's `PageScrollPhysics` count a page view's pages in its
2499    /// own pages (`_PagePosition.page`, `getPixelsFromPage`), here through the snapshot its
2500    /// position's `copy_with` makes.
2501    #[test]
2502    fn a_large_viewport_fraction_settles_on_the_page_dragged_past_halfway() {
2503        test_widgets(|tester| {
2504            let controller = new_controller(tester, 0, 5.0 / 4.0);
2505            tester.pump_widget(built_page_view(&controller, index_labels(3)));
2506
2507            // Pages are 1000 wide and start 100 in: 600 dragged is past halfway to page 1, whose
2508            // pixels are 1100, where whole viewports would have counted page 1 at 800.
2509            tester.drag(find::by_type::<PageView>(), Offset::new(-600.0, 0.0));
2510            tester.pump_and_settle();
2511
2512            assert_eq!(page(tester, controller.handle()), Some(1.0));
2513            assert_eq!(
2514                tester.get_center(find::text("1")),
2515                Offset::new(400.0, 300.0)
2516            );
2517        });
2518    }
2519
2520    #[test]
2521    fn the_current_item_remains_centered_on_constraint_change() {
2522        test_widgets(|tester| {
2523            let controller = new_controller(tester, K_STATES.len() as i32 - 1, 0.5);
2524            // Verifies that the last item is centered on screen.
2525            let verify_centered = |tester: &WidgetTester| {
2526                assert_more_or_less_equals(
2527                    tester.get_center(find::text(K_STATES[K_STATES.len() - 1])),
2528                    Offset::new(400.0, 300.0),
2529                );
2530            };
2531
2532            tester.pump_widget(sized_page_view(Size::new(300.0, 300.0), &controller));
2533            tester.pump_and_settle();
2534
2535            verify_centered(tester);
2536
2537            tester.pump_widget(sized_page_view(Size::new(200.0, 300.0), &controller));
2538            tester.pump_and_settle();
2539
2540            verify_centered(tester);
2541        });
2542    }
2543
2544    #[test]
2545    fn a_jump_past_the_last_page_does_not_report_a_page_change() {
2546        test_widgets(|tester| {
2547            let controller = new_controller(tester, K_STATES.len() as i32 - 1, 1.0);
2548            let change_index = Rc::new(Cell::new(0));
2549            let changed = Rc::clone(&change_index);
2550            tester.pump_widget(ltr(PageView::new()
2551                .controller(controller.clone())
2552                .children(states())
2553                .on_page_changed(move |_, page| changed.set(page))));
2554
2555            // try to move beyond max range
2556            controller.jump_to_page(&mut tester.cell.borrow_mut(), K_STATES.len() as i32 * 2);
2557            // change index should be zero, shouldn't fire onPageChanged
2558            assert_eq!(change_index.get(), 0);
2559            tester.pump();
2560            assert_eq!(change_index.get(), 0);
2561        });
2562    }
2563
2564    fn stored_page_view(
2565        bucket: Ref<PageStorageBucket>,
2566        key: &'static str,
2567        controller: Ref<PageController>,
2568    ) -> WidgetRef {
2569        ltr(PageStorage::new(
2570            bucket,
2571            PageView::new()
2572                .key(PageStorageKey::new(key).into_key())
2573                .controller(controller)
2574                .children((0..3).map(|_| SizedBox::expand().into_widget())),
2575        ))
2576    }
2577
2578    /// The message of the assert that reading `controller.page` fails.
2579    fn page_assert_message(tester: &WidgetTester, controller: Handle<PageController>) -> String {
2580        let error = catch_unwind(AssertUnwindSafe(|| page(tester, controller)))
2581            .expect_err("reading the page asserts");
2582        match error.downcast::<&str>() {
2583            Ok(message) => message.to_string(),
2584            Err(error) => *error.downcast::<String>().expect("a panic message"),
2585        }
2586    }
2587
2588    const PAGE_BEFORE_BUILD: &str =
2589        "PageController.page cannot be accessed before a PageView is built with it.";
2590
2591    #[test]
2592    fn a_page_view_restores_its_page_from_page_storage() {
2593        test_widgets(|tester| {
2594            let controller = PageController::default(&mut tester.cell.borrow_mut());
2595            assert_eq!(
2596                page_assert_message(tester, controller.handle()),
2597                PAGE_BEFORE_BUILD
2598            );
2599            let bucket = PageStorageBucket::new(&mut tester.cell.borrow_mut());
2600            tester.pump_widget(stored_page_view(
2601                bucket.clone(),
2602                "PageView",
2603                controller.clone(),
2604            ));
2605            assert_eq!(page(tester, controller.handle()), Some(0.0));
2606            controller.jump_to_page(&mut tester.cell.borrow_mut(), 2);
2607            // Flutter settles in 2 pumps; its second is the semantics update the jump asks for, and
2608            // accessibility is deferred, so this settles in 1.
2609            assert_eq!(tester.pump_and_settle_by(Duration::from_secs(60)), 1);
2610            assert_eq!(page(tester, controller.handle()), Some(2.0));
2611            tester.pump_widget(PageStorage::new(bucket.clone(), SizedBox::new()));
2612            assert_eq!(
2613                page_assert_message(tester, controller.handle()),
2614                PAGE_BEFORE_BUILD
2615            );
2616            tester.pump_widget(stored_page_view(
2617                bucket.clone(),
2618                "PageView",
2619                controller.clone(),
2620            ));
2621            assert_eq!(page(tester, controller.handle()), Some(2.0));
2622
2623            let controller2 =
2624                PageController::new(&mut tester.cell.borrow_mut(), 0, false, 1.0, None, None);
2625            tester.pump_widget(stored_page_view(
2626                bucket,
2627                "Check it again against your list and see consistency!",
2628                controller2.clone(),
2629            ));
2630            assert_eq!(page(tester, controller2.handle()), Some(0.0));
2631        });
2632    }
2633
2634    #[test]
2635    fn page_metrics_report_their_page() {
2636        let page = PageMetrics::new(
2637            Some(100.0),
2638            Some(200.0),
2639            Some(150.0),
2640            Some(25.0),
2641            AxisDirection::Right,
2642            1.0,
2643            3.0,
2644        );
2645        assert_eq!(page.page(), Some(6.0));
2646        let page2 = page.copy_with().with_pixels(page.pixels() - 100.0);
2647        assert_eq!(page2.page(), Some(4.0));
2648    }
2649
2650    #[test]
2651    fn the_page_controller_rounds_away_a_precision_error() {
2652        test_widgets(|tester| {
2653            let controller = PageController::default(&mut tester.cell.borrow_mut());
2654            tester.pump_widget(ltr(PageView::new()
2655                .controller(controller.clone())
2656                .children((0..3).map(|_| SizedBox::expand().into_widget()))));
2657            // Simulate precision error.
2658            let position = controller.position(&tester.cell.borrow());
2659            position.jump_to(&mut tester.cell.borrow_mut(), 799.99999999999);
2660            assert_eq!(page(tester, controller.handle()), Some(1.0));
2661        });
2662    }
2663
2664    #[test]
2665    fn pad_ends_reaches_the_sliver_fill_viewport() {
2666        test_widgets(|tester| {
2667            // PageView() defaults to true.
2668            tester.pump_widget(ltr(PageView::new()));
2669            assert!(tester.widget(
2670                find::by_type::<SliverFillViewport>().skip_offstage(false),
2671                |fill: &SliverFillViewport| fill.pad_ends
2672            ));
2673
2674            // PageView(padEnds: false) is propagated properly.
2675            tester.pump_widget(ltr(PageView::new().pad_ends(false)));
2676            assert!(!tester.widget(
2677                find::by_type::<SliverFillViewport>().skip_offstage(false),
2678                |fill: &SliverFillViewport| fill.pad_ends
2679            ));
2680        });
2681    }
2682
2683    #[test]
2684    fn the_page_controller_hears_its_position_attach_and_detach() {
2685        test_widgets(|tester| {
2686            let attach = Rc::new(Cell::new(0));
2687            let detach = Rc::new(Cell::new(0));
2688            let (attached, detached) = (Rc::clone(&attach), Rc::clone(&detach));
2689            let controller = PageController::new(
2690                &mut tester.cell.borrow_mut(),
2691                0,
2692                true,
2693                1.0,
2694                Some(Rc::new(move |_, _| attached.set(attached.get() + 1))),
2695                Some(Rc::new(move |_, _| detached.set(detached.get() + 1))),
2696            );
2697            tester.pump_widget(ltr(Center::new().child(
2698                PageView::new()
2699                    .controller(controller.clone())
2700                    .physics(
2701                        PageScrollPhysics::new()
2702                            .apply_to(Some(Rc::new(ClampingScrollPhysics::new()))),
2703                    )
2704                    .children((0..3).map(|_| Center::new().into_widget())),
2705            )));
2706            tester.pump_and_settle();
2707
2708            assert_eq!(attach.get(), 1);
2709            assert_eq!(detach.get(), 0);
2710
2711            tester.pump_widget(SizedBox::new());
2712            tester.pump_and_settle();
2713
2714            assert_eq!(attach.get(), 1);
2715            assert_eq!(detach.get(), 1);
2716        });
2717    }
2718
2719    // ---- page_view_test.dart: "PageView handles change of controller" ----
2720
2721    fn keyed_page_view(
2722        key: &crate::framework::GlobalKey,
2723        controller: Option<Ref<PageController>>,
2724    ) -> WidgetRef {
2725        let mut page_view = PageView::new()
2726            .key(key.clone().into())
2727            .children((0..3).map(|i| Center::new().child(Text::new(i.to_string())).into_widget()));
2728        if let Some(controller) = controller {
2729            page_view = page_view.controller(controller.clone());
2730        }
2731        ltr(page_view)
2732    }
2733
2734    /// `testPageViewWithController`: the first page onstage follows the controller's jumps when
2735    /// it controls the page view, and its jumps panic when it does not.
2736    fn check_page_view_with_controller(
2737        tester: &mut WidgetTester,
2738        controller: Ref<PageController>,
2739        controls: bool,
2740    ) {
2741        let current_visible_page = |tester: &WidgetTester| -> i32 {
2742            tester
2743                .widget(find::by_type::<Text>().first(), |text: &Text| {
2744                    text.data.clone()
2745                })
2746                .expect("the page's Text has data")
2747                .parse()
2748                .expect("the page's Text is its index")
2749        };
2750        let initial_page_in_view = current_visible_page(tester);
2751        for i in 0..3 {
2752            if controls {
2753                controller.jump_to_page(&mut tester.cell.borrow_mut(), i);
2754                tester.pump_and_settle();
2755                assert_eq!(current_visible_page(tester), i);
2756            } else {
2757                let jumped = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2758                    controller.jump_to_page(&mut tester.cell.borrow_mut(), i);
2759                }));
2760                assert!(jumped.is_err());
2761                assert_eq!(current_visible_page(tester), initial_page_in_view);
2762            }
2763        }
2764    }
2765
2766    #[test]
2767    fn a_page_view_follows_a_controller_given_after_none() {
2768        test_widgets(|tester| {
2769            let key = crate::framework::GlobalKey::new();
2770            let controller = PageController::default(&mut tester.cell.borrow_mut());
2771            tester.pump_widget(keyed_page_view(&key, None));
2772            tester.pump_widget(keyed_page_view(&key, Some(controller.clone())));
2773            check_page_view_with_controller(tester, controller, true);
2774        });
2775    }
2776
2777    #[test]
2778    fn a_page_view_follows_its_new_controller_and_not_its_old_one() {
2779        test_widgets(|tester| {
2780            let key = crate::framework::GlobalKey::new();
2781            let controller1 = PageController::default(&mut tester.cell.borrow_mut());
2782            let controller2 = PageController::default(&mut tester.cell.borrow_mut());
2783            tester.pump_widget(keyed_page_view(&key, Some(controller1.clone())));
2784            check_page_view_with_controller(tester, controller1.clone(), true);
2785            tester.pump_widget(keyed_page_view(&key, Some(controller2.clone())));
2786            check_page_view_with_controller(tester, controller1, false);
2787            check_page_view_with_controller(tester, controller2, true);
2788        });
2789    }
2790
2791    #[test]
2792    fn a_page_view_leaves_a_controller_taken_away() {
2793        test_widgets(|tester| {
2794            let key = crate::framework::GlobalKey::new();
2795            let controller = PageController::default(&mut tester.cell.borrow_mut());
2796            tester.pump_widget(keyed_page_view(&key, Some(controller.clone())));
2797            check_page_view_with_controller(tester, controller.clone(), true);
2798            tester.pump_widget(keyed_page_view(&key, None));
2799            check_page_view_with_controller(tester, controller, false);
2800        });
2801    }
2802
2803    #[test]
2804    fn a_page_view_without_a_controller_rebuilds_without_one() {
2805        test_widgets(|tester| {
2806            let key = crate::framework::GlobalKey::new();
2807            tester.pump_widget(keyed_page_view(&key, None));
2808            tester.pump_widget(keyed_page_view(&key, None));
2809        });
2810    }
2811
2812    // ---- page_view_test.dart: scrollCacheExtent ----
2813
2814    fn cached_page_view(
2815        controller: Ref<PageController>,
2816        allow_implicit_scrolling: bool,
2817        scroll_cache_extent: Option<ScrollCacheExtent>,
2818    ) -> WidgetRef {
2819        let mut page_view = PageView::new()
2820            .controller(controller.clone())
2821            .allow_implicit_scrolling(allow_implicit_scrolling)
2822            .children((0..3).map(|i| {
2823                SizedBox::new()
2824                    .key(ValueKey::new(i).into())
2825                    .child(Text::new(format!("Page {i}")))
2826                    .into_widget()
2827            }));
2828        if let Some(scroll_cache_extent) = scroll_cache_extent {
2829            page_view = page_view.scroll_cache_extent(scroll_cache_extent);
2830        }
2831        ltr(page_view)
2832    }
2833
2834    /// Dart's `find.text(text, skipOffstage: false)`.
2835    fn built_text(text: &str) -> Finder {
2836        find::text(text).skip_offstage(false)
2837    }
2838
2839    #[test]
2840    fn a_page_view_lays_out_its_scroll_cache_extent() {
2841        test_widgets(|tester| {
2842            let controller = PageController::default(&mut tester.cell.borrow_mut());
2843            tester.pump_widget(cached_page_view(
2844                controller,
2845                true,
2846                Some(ScrollCacheExtent::Viewport(1.0)),
2847            ));
2848
2849            expect(tester, &find::text("Page 0"), finds_one_widget());
2850            expect(tester, &built_text("Page 1"), finds_one_widget());
2851            expect(tester, &built_text("Page 2"), finds_nothing());
2852        });
2853    }
2854
2855    #[test]
2856    fn the_scroll_cache_extent_follows_allow_implicit_scrolling_by_default() {
2857        test_widgets(|tester| {
2858            let controller = PageController::default(&mut tester.cell.borrow_mut());
2859
2860            // Default (allowImplicitScrolling: false) -> scrollCacheExtent: viewport(0.0)
2861            tester.pump_widget(cached_page_view(controller.clone(), false, None));
2862            expect(tester, &built_text("Page 1"), finds_nothing());
2863
2864            // allowImplicitScrolling: true -> scrollCacheExtent: viewport(1.0)
2865            tester.pump_widget(cached_page_view(controller, true, None));
2866            expect(tester, &built_text("Page 1"), finds_one_widget());
2867        });
2868    }
2869
2870    #[test]
2871    fn a_page_view_updates_its_scroll_cache_extent() {
2872        test_widgets(|tester| {
2873            let controller = PageController::default(&mut tester.cell.borrow_mut());
2874
2875            // Start with viewport(1.0)
2876            tester.pump_widget(cached_page_view(
2877                controller.clone(),
2878                true,
2879                Some(ScrollCacheExtent::Viewport(1.0)),
2880            ));
2881            expect(tester, &built_text("Page 1"), finds_one_widget());
2882
2883            // Update to viewport(2.0)
2884            tester.pump_widget(cached_page_view(
2885                controller.clone(),
2886                true,
2887                Some(ScrollCacheExtent::Viewport(2.0)),
2888            ));
2889            expect(tester, &built_text("Page 1"), finds_one_widget());
2890            expect(tester, &built_text("Page 2"), finds_one_widget());
2891
2892            // Update back to viewport(1.0)
2893            tester.pump_widget(cached_page_view(
2894                controller,
2895                true,
2896                Some(ScrollCacheExtent::Viewport(1.0)),
2897            ));
2898            expect(tester, &built_text("Page 1"), finds_one_widget());
2899            expect(tester, &built_text("Page 2"), finds_nothing());
2900        });
2901    }
2902
2903    #[test]
2904    #[should_panic(expected = "scrollCacheExtent and allowImplicitScrolling must be consistent")]
2905    fn a_zero_scroll_cache_extent_with_implicit_scrolling_panics_when_made_a_widget() {
2906        PageView::new()
2907            .allow_implicit_scrolling(true)
2908            .scroll_cache_extent(ScrollCacheExtent::Viewport(0.0))
2909            .children(states())
2910            .into_widget();
2911    }
2912
2913    #[test]
2914    #[should_panic(expected = "scrollCacheExtent and allowImplicitScrolling must be consistent")]
2915    fn a_positive_scroll_cache_extent_without_implicit_scrolling_panics_when_made_a_widget() {
2916        PageView::new()
2917            .scroll_cache_extent(ScrollCacheExtent::Viewport(2.0))
2918            .children(states())
2919            .into_widget();
2920    }
2921
2922    // ---- not in page_view_test.dart: `_getDirection` ----
2923
2924    #[test]
2925    fn a_reversed_page_view_in_a_right_to_left_text_scrolls_to_the_right() {
2926        test_widgets(|tester| {
2927            tester.pump_widget(Directionality::new(
2928                TextDirection::Rtl,
2929                PageView::new().reverse(true).children(states()),
2930            ));
2931            assert_eq!(
2932                fill_viewport(tester)
2933                    .constraints(&tester.cell.borrow())
2934                    .axis_direction,
2935                AxisDirection::Right
2936            );
2937
2938            tester.pump_widget(Directionality::new(
2939                TextDirection::Rtl,
2940                PageView::new().children(states()),
2941            ));
2942            assert_eq!(
2943                fill_viewport(tester)
2944                    .constraints(&tester.cell.borrow())
2945                    .axis_direction,
2946                AxisDirection::Left
2947            );
2948            assert_eq!(
2949                tester.get_top_left(find::text("Alabama")),
2950                Offset::new(0.0, 0.0)
2951            );
2952
2953            tester.pump_widget(ltr(PageView::new()
2954                .scroll_direction(Axis::Vertical)
2955                .reverse(true)
2956                .children(states())));
2957            assert_eq!(
2958                fill_viewport(tester)
2959                    .constraints(&tester.cell.borrow())
2960                    .axis_direction,
2961                AxisDirection::Up
2962            );
2963        });
2964    }
2965    // ---- page_view_test.dart, the rest ----
2966
2967    #[test]
2968    fn a_page_view_builder_asks_its_find_child_index_callback_on_update() {
2969        test_widgets(|tester| {
2970            let finder_called = Rc::new(Cell::new(false));
2971            let page_view = |item_count: i32| {
2972                let finder_called = Rc::clone(&finder_called);
2973                ltr(PageView::builder(|_, _, index| {
2974                    Some(
2975                        SizedBox::new()
2976                            .key(ValueKey::new(index.to_string()).into())
2977                            .height(2000.0)
2978                            .into_widget(),
2979                    )
2980                })
2981                .item_count(item_count)
2982                .find_child_index_callback(Rc::new(move |_| {
2983                    finder_called.set(true);
2984                    None
2985                }))
2986                .build())
2987            };
2988            tester.pump_widget(page_view(7));
2989            assert!(!finder_called.get());
2990
2991            // Trigger update.
2992            tester.pump_widget(page_view(77));
2993            assert!(finder_called.get());
2994        });
2995    }
2996
2997    #[test]
2998    fn a_page_view_does_not_squish_when_overscrolled() {
2999        let variant = TargetPlatformVariant::new([TargetPlatform::IOS, TargetPlatform::MacOS]);
3000        test_widgets_variant(variant, |tester| {
3001            let platform = tester.target_platform();
3002            tester.pump_widget(ltr(PageView::new().children((0..10).map(|i| {
3003                Container::new()
3004                    .key(ValueKey::new(i).into())
3005                    .color(K_BLUE)
3006                    .into_widget()
3007            }))));
3008            let size_of_first =
3009                |tester: &WidgetTester| tester.get_size(find::by_key(ValueKey::new(0)));
3010            let left_of_first =
3011                |tester: &WidgetTester| tester.get_top_left(find::by_key(ValueKey::new(0))).dx();
3012
3013            assert_eq!(left_of_first(tester), 0.0);
3014            assert_eq!(size_of_first(tester), Size::new(800.0, 600.0));
3015
3016            // Going into overscroll.
3017            tester.drag(find::by_type::<PageView>(), Offset::new(100.0, 0.0));
3018            tester.pump();
3019
3020            assert!(left_of_first(tester) > 0.0);
3021            assert_eq!(size_of_first(tester), Size::new(800.0, 600.0));
3022
3023            // Easing overscroll past overscroll limit.
3024            let back = if platform == TargetPlatform::MacOS {
3025                -500.0
3026            } else {
3027                -200.0
3028            };
3029            tester.drag(find::by_type::<PageView>(), Offset::new(back, 0.0));
3030            tester.pump();
3031
3032            assert!(left_of_first(tester) < 0.0);
3033            assert_eq!(size_of_first(tester), Size::new(800.0, 600.0));
3034        });
3035    }
3036
3037    #[test]
3038    fn all_visible_pages_receive_taps() {
3039        test_widgets(|tester| {
3040            let controller = new_controller(tester, 0, 1.0 / 4.0);
3041            let tapped_index = Rc::new(Cell::new(-1));
3042            let tapped = Rc::clone(&tapped_index);
3043            tester.pump_widget(ltr(PageView::builder(move |_, _, index| {
3044                let tapped = Rc::clone(&tapped);
3045                Some(
3046                    GestureDetector::new()
3047                        .on_tap(Listener::new(move |_| tapped.set(index)))
3048                        .child(SizedBox::expand().child(Text::new(index.to_string())))
3049                        .into_widget(),
3050                )
3051            })
3052            .item_count(20)
3053            .build()
3054            .controller(controller.clone())));
3055
3056            // The first 3 items should be visible and tappable.
3057            for index in [0, 1, 2] {
3058                expect(tester, &find::text(&index.to_string()), finds_one_widget());
3059                // The center of page 2's x-coordinate is 800, so we have to manually
3060                // offset it a bit to make sure the tap lands within the screen.
3061                let center =
3062                    tester.get_center(find::text(&index.to_string())) - Offset::new(3.0, 0.0);
3063                let pointer = tester.next_pointer();
3064                tester.tap_at(center, pointer);
3065                assert_eq!(tapped_index.get(), index);
3066            }
3067
3068            controller.jump_to_page(&mut tester.cell.borrow_mut(), 19);
3069            tester.pump();
3070            // The last 3 items should be visible and tappable.
3071            for index in [17, 18, 19] {
3072                expect(tester, &find::text(&index.to_string()), finds_one_widget());
3073                tester.tap(find::text(&index.to_string()));
3074                assert_eq!(tapped_index.get(), index);
3075            }
3076        });
3077    }
3078
3079    #[test]
3080    fn a_page_view_gives_its_viewport_its_clip_behavior() {
3081        test_widgets(|tester| {
3082            let page_view =
3083                || PageView::new().children([SizedBox::new().height(2000.0).into_widget()]);
3084            tester.pump_widget(ltr(page_view()));
3085
3086            // 1st, check that the render object has received the default clip behavior.
3087            let viewport = *tester
3088                .all::<RenderViewport>()
3089                .first()
3090                .expect("a mounted viewport");
3091            assert_eq!(
3092                viewport.clip_behavior(&tester.cell.borrow()),
3093                Clip::HardEdge
3094            );
3095
3096            // 3rd, pump a new widget to check that the render object can update its clip behavior.
3097            tester.pump_widget(ltr(page_view().clip_behavior(Clip::AntiAlias)));
3098            assert_eq!(
3099                viewport.clip_behavior(&tester.cell.borrow()),
3100                Clip::AntiAlias
3101            );
3102        });
3103    }
3104
3105    #[test]
3106    fn a_jump_to_the_last_of_many_narrow_pages_survives_a_precision_error() {
3107        test_widgets(|tester| {
3108            let controller = new_controller(tester, 152, 1.0);
3109            tester.pump_widget(
3110                Center::new().child(
3111                    SizedBox::new()
3112                        .width(392.72727272727275)
3113                        .child(ltr(PageView::builder(|_, _, _| {
3114                            Some(SizedBox::new().into_widget())
3115                        })
3116                        .item_count(366)
3117                        .build()
3118                        .controller(controller.clone()))),
3119                ),
3120            );
3121
3122            controller.jump_to_page(&mut tester.cell.borrow_mut(), 365);
3123            tester.pump();
3124        });
3125    }
3126
3127    fn three_pages() -> impl Iterator<Item = WidgetRef> {
3128        (0..3).map(|_| SizedBox::expand().into_widget())
3129    }
3130
3131    fn two_page_views(controller: &Ref<PageController>) -> WidgetRef {
3132        ltr(Column::new().children([
3133            Expanded::new(
3134                PageView::new()
3135                    .controller(controller.clone())
3136                    .children(three_pages()),
3137            )
3138            .into_widget(),
3139            Expanded::new(
3140                PageView::new()
3141                    .controller(controller.clone())
3142                    .children(three_pages()),
3143            )
3144            .into_widget(),
3145        ]))
3146    }
3147
3148    #[test]
3149    #[should_panic(expected = "Multiple PageViews are attached to the same PageController.")]
3150    fn animate_to_page_asserts_when_its_controller_has_two_page_views() {
3151        test_widgets(|tester| {
3152            let controller = PageController::default(&mut tester.cell.borrow_mut());
3153            tester.pump_widget(two_page_views(&controller));
3154
3155            drop(controller.animate_to_page(
3156                &mut tester.cell.borrow_mut(),
3157                2,
3158                Duration::from_millis(300),
3159                Curves::ease(),
3160            ));
3161        });
3162    }
3163
3164    #[test]
3165    #[should_panic(expected = "Multiple PageViews are attached to the same PageController.")]
3166    fn jump_to_page_asserts_when_its_controller_has_two_page_views() {
3167        test_widgets(|tester| {
3168            let controller = PageController::default(&mut tester.cell.borrow_mut());
3169            tester.pump_widget(two_page_views(&controller));
3170
3171            controller.jump_to_page(&mut tester.cell.borrow_mut(), 2);
3172        });
3173    }
3174
3175    /// The message a call panics with, or `None` if it returns.
3176    fn panic_message(call: impl FnOnce()) -> Option<String> {
3177        let payload = std::panic::catch_unwind(std::panic::AssertUnwindSafe(call)).err()?;
3178        Some(
3179            payload
3180                .downcast_ref::<String>()
3181                .cloned()
3182                .or_else(|| {
3183                    payload
3184                        .downcast_ref::<&str>()
3185                        .map(|message| message.to_string())
3186                })
3187                .unwrap_or_default(),
3188        )
3189    }
3190
3191    fn page_view_with(controller: Option<&Ref<PageController>>) -> WidgetRef {
3192        let mut page_view = PageView::new().children(three_pages());
3193        if let Some(controller) = controller {
3194            page_view = page_view.controller(controller.clone());
3195        }
3196        ltr(page_view)
3197    }
3198
3199    #[test]
3200    fn animate_to_page_asserts_only_while_its_controller_is_unattached() {
3201        test_widgets(|tester| {
3202            let controller = PageController::default(&mut tester.cell.borrow_mut());
3203
3204            // pageController is not attached to PageView
3205            tester.pump_widget(page_view_with(None));
3206            let animate = |tester: &WidgetTester| {
3207                drop(controller.animate_to_page(
3208                    &mut tester.cell.borrow_mut(),
3209                    2,
3210                    Duration::from_millis(300),
3211                    Curves::ease(),
3212                ));
3213            };
3214            assert_eq!(
3215                panic_message(|| animate(tester)).as_deref(),
3216                Some("PageController is not attached to a PageView.")
3217            );
3218
3219            // pageController is attached to PageView
3220            tester.pump_widget(page_view_with(Some(&controller)));
3221            assert_eq!(panic_message(|| animate(tester)), None);
3222        });
3223    }
3224
3225    #[test]
3226    fn jump_to_page_asserts_only_while_its_controller_is_unattached() {
3227        test_widgets(|tester| {
3228            let controller = PageController::default(&mut tester.cell.borrow_mut());
3229
3230            // pageController is not attached to PageView
3231            tester.pump_widget(page_view_with(None));
3232            let jump =
3233                |tester: &WidgetTester| controller.jump_to_page(&mut tester.cell.borrow_mut(), 2);
3234            assert_eq!(
3235                panic_message(|| jump(tester)).as_deref(),
3236                Some("PageController is not attached to a PageView.")
3237            );
3238
3239            // pageController is attached to PageView
3240            tester.pump_widget(page_view_with(Some(&controller)));
3241            assert_eq!(panic_message(|| jump(tester)), None);
3242        });
3243    }
3244
3245    #[test]
3246    fn the_page_is_none_until_the_content_dimensions_are_known() {
3247        test_widgets(|tester| {
3248            let controller = PageController::default(&mut tester.cell.borrow_mut());
3249            let current_page_is_none = Rc::new(Cell::new(None));
3250            let page_view = || {
3251                let current_page_is_none = Rc::clone(&current_page_is_none);
3252                let observed = controller.handle();
3253                ltr(Column::new().children([Expanded::new(
3254                    PageView::new()
3255                        .controller(controller.clone())
3256                        .children([Builder::new(move |app, _| {
3257                            current_page_is_none.set(Some(observed.page(app).is_none()));
3258                            Center::new().into_widget()
3259                        })
3260                        .into_widget()]),
3261                )
3262                .into_widget()]))
3263            };
3264            tester.pump_widget(page_view());
3265            assert_eq!(current_page_is_none.get(), Some(true));
3266
3267            // A rebuild, as the test's `setState` asks for.
3268            tester.pump_widget(page_view());
3269            assert_eq!(current_page_is_none.get(), Some(false));
3270            assert!(page(tester, controller.handle()).is_some());
3271        });
3272    }
3273
3274    /// A page view in an offstage overlay entry that keeps its state, under an opaque one: built
3275    /// and never laid out, as the page of a route under another route is.
3276    fn page_view_before_layout(
3277        tester: &WidgetTester,
3278        controller: Ref<PageController>,
3279    ) -> WidgetRef {
3280        let mut app = tester.cell.borrow_mut();
3281        let below = OverlayEntry::new(
3282            &mut app,
3283            Rc::new(move |_, _| {
3284                PageView::new()
3285                    .controller(controller.clone())
3286                    .children((0..2).map(|_| SizedBox::expand().into_widget()))
3287                    .into_widget()
3288            }),
3289            false,
3290            true,
3291            false,
3292        );
3293        let above = OverlayEntry::new(
3294            &mut app,
3295            Rc::new(|_, _| SizedBox::shrink().into_widget()),
3296            true,
3297            false,
3298            false,
3299        );
3300        ltr(Overlay::new().initial_entries([below, above]))
3301    }
3302
3303    #[test]
3304    fn jump_to_page_before_layout_does_not_panic() {
3305        test_widgets(|tester| {
3306            let controller = PageController::default(&mut tester.cell.borrow_mut());
3307            let page_view = page_view_before_layout(tester, controller.clone());
3308            tester.pump_widget(page_view);
3309            assert!(!viewport_was_laid_out(tester));
3310
3311            controller.jump_to_page(&mut tester.cell.borrow_mut(), 1);
3312        });
3313    }
3314
3315    #[test]
3316    fn animate_to_page_before_layout_does_not_panic() {
3317        test_widgets(|tester| {
3318            let controller = PageController::default(&mut tester.cell.borrow_mut());
3319            let page_view = page_view_before_layout(tester, controller.clone());
3320            tester.pump_widget(page_view);
3321            assert!(!viewport_was_laid_out(tester));
3322
3323            drop(controller.animate_to_page(
3324                &mut tester.cell.borrow_mut(),
3325                1,
3326                Duration::from_millis(50),
3327                Curves::bounce_in(),
3328            ));
3329        });
3330    }
3331
3332    /// Whether the page view's viewport has been laid out: the test's premise is that it has not.
3333    fn viewport_was_laid_out(tester: &WidgetTester) -> bool {
3334        tester
3335            .all::<RenderViewport>()
3336            .first()
3337            .is_some_and(|viewport| viewport.has_size(&tester.cell.borrow()))
3338    }
3339
3340    #[test]
3341    fn show_on_screen_scrolls_a_page_view_that_allows_implicit_scrolling() {
3342        for scroll_cache_extent in [Some(ScrollCacheExtent::Viewport(1.0)), None] {
3343            test_widgets(|tester| {
3344                let controller = PageController::default(&mut tester.cell.borrow_mut());
3345                tester.pump_widget(cached_page_view_of(
3346                    controller.clone(),
3347                    scroll_cache_extent,
3348                    4,
3349                ));
3350
3351                // Page 2 (index 1) is within the implicit cache extent.
3352                let target_finder = find::text("Page 2").skip_offstage(false);
3353                expect(tester, &target_finder, finds_one_widget());
3354                let target = tester.render_object(target_finder);
3355                target.show_on_screen(
3356                    &mut tester.cell.borrow_mut(),
3357                    None,
3358                    None,
3359                    Duration::ZERO,
3360                    Curves::ease(),
3361                );
3362                tester.pump_and_settle();
3363
3364                // Should scroll.
3365                assert_eq!(
3366                    page(tester, controller.handle()),
3367                    Some(1.0),
3368                    "{scroll_cache_extent:?}"
3369                );
3370            });
3371        }
3372    }
3373
3374    fn cached_page_view_of(
3375        controller: Ref<PageController>,
3376        scroll_cache_extent: Option<ScrollCacheExtent>,
3377        page_count: usize,
3378    ) -> WidgetRef {
3379        let mut page_view = PageView::new().controller(controller.clone());
3380        if let Some(scroll_cache_extent) = scroll_cache_extent {
3381            page_view = page_view.scroll_cache_extent(scroll_cache_extent);
3382        }
3383        ltr(page_view
3384            .allow_implicit_scrolling(true)
3385            .children((1..=page_count).map(|i| Text::new(format!("Page {i}")).into_widget())))
3386    }
3387
3388    // ---- not in page_view_test.dart: `PageScrollPhysics` targets ----
3389
3390    /// Pins `PageScrollPhysics` where its whole-viewport pages agree with Dart's
3391    /// `_PagePosition` branch: a viewport fraction of 1.0 and a position in range. The target is
3392    /// where the spring settles.
3393    #[test]
3394    fn page_scroll_physics_settle_on_the_nearest_page_or_the_next_one_flung_to() {
3395        let physics = PageScrollPhysics::new();
3396        let target = |pixels: f64, velocity: f64| {
3397            let metrics = FixedScrollMetrics::new(
3398                Some(0.0),
3399                Some(2400.0),
3400                Some(pixels),
3401                Some(800.0),
3402                AxisDirection::Right,
3403                3.0,
3404            );
3405            physics
3406                .create_ballistic_simulation(&metrics, velocity)
3407                .map(|simulation| simulation.x(10.0).round())
3408        };
3409
3410        // Released short of halfway: back to the page it left.
3411        assert_eq!(target(300.0, 0.0), Some(0.0));
3412        assert_eq!(target(1100.0, 0.0), Some(800.0));
3413        // Released past halfway: on to the next page.
3414        assert_eq!(target(500.0, 0.0), Some(800.0));
3415        // Flung either way: on to the page it was flung towards.
3416        assert_eq!(target(100.0, 1000.0), Some(800.0));
3417        assert_eq!(target(700.0, -1000.0), Some(0.0));
3418        assert_eq!(target(1700.0, -1000.0), Some(1600.0));
3419        // Already on a page: no simulation.
3420        assert_eq!(target(800.0, 0.0), None);
3421
3422        // The same targets through a page view whose position its controller reports in pages.
3423        test_widgets(|tester| {
3424            let controller = PageController::default(&mut tester.cell.borrow_mut());
3425            tester.pump_widget(ltr(PageView::new()
3426                .controller(controller.clone())
3427                .children(states())));
3428            tester.drag(find::by_type::<PageView>(), Offset::new(-300.0, 0.0));
3429            tester.pump_and_settle();
3430            assert_eq!(page(tester, controller.handle()), Some(0.0));
3431            tester.drag(find::by_type::<PageView>(), Offset::new(-500.0, 0.0));
3432            tester.pump_and_settle();
3433            assert_eq!(page(tester, controller.handle()), Some(1.0));
3434            tester.fling(
3435                find::by_type::<PageView>(),
3436                Offset::new(-100.0, 0.0),
3437                1000.0,
3438            );
3439            tester.pump_and_settle();
3440            assert_eq!(page(tester, controller.handle()), Some(2.0));
3441        });
3442    }
3443}