Skip to main content

waft_rendering/
sliver_persistent_header.rs

1//! Flutter counterpart: `rendering/sliver_persistent_header.dart`.
2//!
3//! Semantics wait; see `PORTING.md`.
4
5use std::rc::Rc;
6use std::time::Duration;
7
8use waft_animation::{
9    Animatable, AnimationController, AnimationStatus, Curve, CurveTween, Curves, Tween,
10};
11use waft_embedder::{Matrix4, Offset, Rect, clamp_double};
12use waft_foundation::{
13    App, AsyncCallback, DiagnosticPropertiesBuilder, DoubleProperty, Handle, HandleId,
14    ListenableObject, Listener,
15};
16use waft_painting::{Axis, AxisDirection, transform_rect};
17use waft_scheduler::{Ticker, TickerCallback, TickerProvider, TickerProviderObject};
18
19use crate::box_::{AnyRenderBox, BoxHitTestResult};
20use crate::object::{
21    AnyRenderObject, RenderHandle, RenderObjectBase, RenderObjectWithChildMixin, resolve,
22};
23use crate::painting_context::PaintingContext;
24use crate::sliver::{
25    RenderSliver, RenderSliverHelpers, SliverGeometry, SliverHitTestResult,
26    apply_growth_direction_to_axis_direction, calculate_cache_offset,
27};
28use crate::viewport_offset::ScrollDirection;
29use waft_animation::AnimationRef;
30use waft_animation::Drive;
31use waft_foundation::OptionRetained;
32use waft_foundation::Ref;
33
34/// Trims the specified edges of the given `Rect`, so that they do not exceed the given values.
35///
36/// Flutter's private `_trim`; the omitted Dart defaults are the unbounded edges.
37fn trim(original: Option<Rect>, top: f64, right: f64, bottom: f64, left: f64) -> Option<Rect> {
38    original.map(|rect| rect.intersect(Rect::from_ltrb(left, top, right, bottom)))
39}
40
41/// An erased [`TickerProvider`] a render object can hold as a field, compared by identity.
42///
43/// Dart's `TickerProvider? vsync` field.
44///
45/// Two refs are equal when they erase the same arena object, as Dart compares the provider
46/// object itself; a widget that erases its state on every build must not look like a new vsync.
47#[derive(Clone)]
48pub struct TickerProviderRef {
49    id: HandleId,
50    provider: Rc<dyn TickerProvider>,
51}
52
53impl TickerProviderRef {
54    /// Erases an arena object that vends tickers.
55    pub fn new<T: TickerProviderObject>(provider: Handle<T>) -> TickerProviderRef {
56        TickerProviderRef {
57            id: provider.id(),
58            provider: Rc::new(provider),
59        }
60    }
61}
62
63impl TickerProvider for TickerProviderRef {
64    fn create_ticker(&self, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
65        self.provider.create_ticker(app, on_tick)
66    }
67}
68
69impl PartialEq for TickerProviderRef {
70    fn eq(&self, other: &TickerProviderRef) -> bool {
71        self.id == other.id
72    }
73}
74
75impl std::fmt::Debug for TickerProviderRef {
76    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
77        f.write_str("TickerProviderRef")
78    }
79}
80
81/// Specifies how a stretched header is to trigger a callback.
82#[derive(Clone)]
83pub struct OverScrollHeaderStretchConfiguration {
84    /// The offset of overscroll required to trigger the
85    /// [`on_stretch_trigger`](Self::on_stretch_trigger).
86    pub stretch_trigger_offset: f64,
87
88    /// The callback function to be executed when a user over-scrolls to the offset specified
89    /// by [`stretch_trigger_offset`](Self::stretch_trigger_offset).
90    pub on_stretch_trigger: Option<AsyncCallback>,
91}
92
93impl OverScrollHeaderStretchConfiguration {
94    /// Creates an object that specifies how a stretched header may activate an
95    /// [`AsyncCallback`].
96    ///
97    /// Dart's default `stretch_trigger_offset` is 100.0.
98    pub fn new() -> OverScrollHeaderStretchConfiguration {
99        OverScrollHeaderStretchConfiguration {
100            stretch_trigger_offset: 100.0,
101            on_stretch_trigger: None,
102        }
103    }
104
105    /// Sets [`stretch_trigger_offset`](Self::stretch_trigger_offset).
106    pub fn stretch_trigger_offset(mut self, value: f64) -> OverScrollHeaderStretchConfiguration {
107        self.stretch_trigger_offset = value;
108        self
109    }
110
111    /// Sets [`on_stretch_trigger`](Self::on_stretch_trigger).
112    pub fn on_stretch_trigger(
113        mut self,
114        value: AsyncCallback,
115    ) -> OverScrollHeaderStretchConfiguration {
116        self.on_stretch_trigger = Some(value);
117        self
118    }
119}
120
121impl Default for OverScrollHeaderStretchConfiguration {
122    fn default() -> OverScrollHeaderStretchConfiguration {
123        OverScrollHeaderStretchConfiguration::new()
124    }
125}
126
127/// Specifies how a pinned header or a floating header should react to
128/// [`crate::RenderObject::show_on_screen`] calls.
129#[derive(Clone, Copy, Debug, PartialEq)]
130pub struct PersistentHeaderShowOnScreenConfiguration {
131    /// The smallest the floating header can expand to in the main axis direction, in response to a
132    /// [`crate::RenderObject::show_on_screen`] call, in addition to its
133    /// [`RenderSliverPersistentHeader::min_extent`].
134    ///
135    /// When a floating persistent header is told to show a [`Rect`] on screen, it may expand
136    /// itself to accommodate the rect. The minimum extent that is allowed for such expansion is
137    /// either the header's `min_extent` or this value, whichever is larger.
138    ///
139    /// Defaults to negative infinity, and must be less than or equal to
140    /// [`max_show_on_screen_extent`](Self::max_show_on_screen_extent). Has no effect unless the
141    /// persistent header is a floating header.
142    pub min_show_on_screen_extent: f64,
143
144    /// The biggest the floating header can expand to in the main axis direction, in response to a
145    /// [`crate::RenderObject::show_on_screen`] call, in addition to its
146    /// [`RenderSliverPersistentHeader::max_extent`].
147    ///
148    /// Defaults to infinity, and must be greater than or equal to
149    /// [`min_show_on_screen_extent`](Self::min_show_on_screen_extent). Has no effect unless the
150    /// persistent header is a floating header.
151    pub max_show_on_screen_extent: f64,
152}
153
154impl PersistentHeaderShowOnScreenConfiguration {
155    /// Creates an object that specifies how a pinned or floating persistent header should behave
156    /// in response to [`crate::RenderObject::show_on_screen`] calls.
157    pub const fn new() -> PersistentHeaderShowOnScreenConfiguration {
158        PersistentHeaderShowOnScreenConfiguration {
159            min_show_on_screen_extent: f64::NEG_INFINITY,
160            max_show_on_screen_extent: f64::INFINITY,
161        }
162    }
163
164    /// Sets [`min_show_on_screen_extent`](Self::min_show_on_screen_extent).
165    pub fn min_show_on_screen_extent(
166        mut self,
167        value: f64,
168    ) -> PersistentHeaderShowOnScreenConfiguration {
169        self.min_show_on_screen_extent = value;
170        debug_assert!(self.min_show_on_screen_extent <= self.max_show_on_screen_extent);
171        self
172    }
173
174    /// Sets [`max_show_on_screen_extent`](Self::max_show_on_screen_extent).
175    pub fn max_show_on_screen_extent(
176        mut self,
177        value: f64,
178    ) -> PersistentHeaderShowOnScreenConfiguration {
179        self.max_show_on_screen_extent = value;
180        debug_assert!(self.min_show_on_screen_extent <= self.max_show_on_screen_extent);
181        self
182    }
183}
184
185impl Default for PersistentHeaderShowOnScreenConfiguration {
186    fn default() -> PersistentHeaderShowOnScreenConfiguration {
187        PersistentHeaderShowOnScreenConfiguration::new()
188    }
189}
190
191/// Specifies how a floating header is to be "snapped" (animated) into or out of view.
192#[derive(Clone)]
193pub struct FloatingHeaderSnapConfiguration {
194    /// The snap animation curve.
195    pub curve: Rc<dyn Curve>,
196
197    /// The snap animation's duration.
198    pub duration: Duration,
199}
200
201impl FloatingHeaderSnapConfiguration {
202    /// Creates an object that specifies how a floating header is to be snapped into or out of
203    /// view.
204    ///
205    /// Dart's defaults: [`Curves::ease`] and 300 milliseconds.
206    pub fn new() -> FloatingHeaderSnapConfiguration {
207        FloatingHeaderSnapConfiguration {
208            curve: Curves::ease(),
209            duration: Duration::from_millis(300),
210        }
211    }
212
213    /// Sets [`curve`](Self::curve).
214    pub fn curve(mut self, value: Rc<dyn Curve>) -> FloatingHeaderSnapConfiguration {
215        self.curve = value;
216        self
217    }
218
219    /// Sets [`duration`](Self::duration).
220    pub fn duration(mut self, value: Duration) -> FloatingHeaderSnapConfiguration {
221        self.duration = value;
222        self
223    }
224}
225
226impl Default for FloatingHeaderSnapConfiguration {
227    fn default() -> FloatingHeaderSnapConfiguration {
228        FloatingHeaderSnapConfiguration::new()
229    }
230}
231
232/// Flutter's `RenderSliverPersistentHeader` fields.
233pub struct RenderSliverPersistentHeaderData {
234    last_stretch_offset: f64,
235    needs_update_child: bool,
236    last_shrink_offset: f64,
237    last_overlaps_content: bool,
238    /// Defines the parameters used to execute a callback when a stretching header over-scrolls.
239    ///
240    /// If this is `None` then the callback is not triggered.
241    pub stretch_configuration: Option<OverScrollHeaderStretchConfiguration>,
242}
243
244impl RenderSliverPersistentHeaderData {
245    /// Creates the state of a persistent header that has not been laid out.
246    pub fn new(
247        stretch_configuration: Option<OverScrollHeaderStretchConfiguration>,
248    ) -> RenderSliverPersistentHeaderData {
249        RenderSliverPersistentHeaderData {
250            last_stretch_offset: 0.0,
251            needs_update_child: true,
252            last_shrink_offset: 0.0,
253            last_overlaps_content: false,
254            stretch_configuration,
255        }
256    }
257}
258
259/// Implements [`RenderSliverPersistentHeader`] field accessors for a `header` field.
260#[macro_export]
261macro_rules! render_sliver_persistent_header_accessors {
262    () => {
263        fn header_data(
264            self: $crate::RenderHandle<Self>,
265            app: &::waft_foundation::App,
266        ) -> &$crate::RenderSliverPersistentHeaderData {
267            &self.get(app).header
268        }
269        fn header_data_mut(
270            self: $crate::RenderHandle<Self>,
271            app: &mut ::waft_foundation::App,
272        ) -> &mut $crate::RenderSliverPersistentHeaderData {
273            &mut self.get_mut(app).header
274        }
275    };
276}
277
278/// A sliver that has a box child which scrolls normally, except that when it hits the leading
279/// edge (typically the top) of the viewport, it shrinks to a minimum size
280/// ([`min_extent`](Self::min_extent)).
281///
282/// This trait primarily provides helpers for managing the child, in particular:
283///
284///  * [`layout_child`](Self::layout_child), which applies min and max extents and a scroll offset
285///    to lay out the child. This is normally called from `perform_layout`.
286///  * [`child_extent`](Self::child_extent), to convert the child's box layout dimensions to the
287///    sliver geometry model.
288///  * hit testing, painting, and other details of the sliver protocol.
289///
290/// Implementors must implement `perform_layout`, [`min_extent`](Self::min_extent) and
291/// [`max_extent`](Self::max_extent), and typically also will implement
292/// [`update_child`](Self::update_child).
293pub trait RenderSliverPersistentHeader:
294    RenderSliver + RenderObjectWithChildMixin<ChildType = AnyRenderBox> + RenderSliverHelpers
295{
296    /// Mixin field access.
297    fn header_data(self: RenderHandle<Self>, app: &App) -> &RenderSliverPersistentHeaderData;
298
299    /// See [`header_data`](Self::header_data).
300    fn header_data_mut(
301        self: RenderHandle<Self>,
302        app: &mut App,
303    ) -> &mut RenderSliverPersistentHeaderData;
304
305    /// The biggest that this render object can become, in the main axis direction.
306    ///
307    /// This value should not be based on the child. If it changes, call `mark_needs_layout`.
308    fn max_extent(self: RenderHandle<Self>, app: &App) -> f64;
309
310    /// The smallest that this render object can become, in the main axis direction.
311    ///
312    /// If this is based on the intrinsic dimensions of the child, the child should be measured
313    /// during [`update_child`](Self::update_child) and the value cached and returned here.
314    fn min_extent(self: RenderHandle<Self>, app: &App) -> f64;
315
316    /// The dimension of the child in the main axis.
317    fn child_extent(self: RenderHandle<Self>, app: &App) -> f64 {
318        let Some(child) = self.child(app) else {
319            return 0.0;
320        };
321        debug_assert!(child.has_size(app));
322        match self.constraints(app).axis() {
323            Axis::Vertical => child.size(app).height(),
324            Axis::Horizontal => child.size(app).width(),
325        }
326    }
327
328    /// Dart's `debugFillProperties`: the maximum extent and the child's position.
329    ///
330    /// Dart computes both lazily; this reads them when the property is added, which a dump does
331    /// before it prints, as Dart's lazy properties do when their level is read.
332    fn debug_fill_properties(
333        self: RenderHandle<Self>,
334        app: &App,
335        properties: &mut DiagnosticPropertiesBuilder,
336    ) {
337        properties.add(DoubleProperty::new("maxExtent", self.max_extent(app)));
338        let child = self
339            .child(app)
340            .expect("a persistent header positioned its child");
341        properties.add(DoubleProperty::new(
342            "child position",
343            self.child_main_axis_position(app, child.as_object()),
344        ));
345    }
346
347    /// The most recent `shrink_offset` passed to [`update_child`](Self::update_child).
348    fn last_shrink_offset(self: RenderHandle<Self>, app: &App) -> f64 {
349        self.header_data(app).last_shrink_offset
350    }
351
352    /// The most recent `overlaps_content` passed to [`update_child`](Self::update_child).
353    fn last_overlaps_content(self: RenderHandle<Self>, app: &App) -> bool {
354        self.header_data(app).last_overlaps_content
355    }
356
357    /// Defines the parameters used to execute a callback when a stretching header over-scrolls.
358    fn stretch_configuration(
359        self: RenderHandle<Self>,
360        app: &App,
361    ) -> Option<OverScrollHeaderStretchConfiguration> {
362        self.header_data(app).stretch_configuration.clone()
363    }
364
365    /// Sets [`stretch_configuration`](Self::stretch_configuration).
366    fn set_stretch_configuration(
367        self: RenderHandle<Self>,
368        app: &mut App,
369        value: Option<OverScrollHeaderStretchConfiguration>,
370    ) {
371        self.header_data_mut(app).stretch_configuration = value;
372    }
373
374    /// Update the child render object if necessary.
375    ///
376    /// Called before the first layout, any time `mark_needs_layout` is called, and any time the
377    /// scroll offset changes. The `shrink_offset` is the difference between the
378    /// [`max_extent`](Self::max_extent) and the current size. Zero means the header is fully
379    /// expanded, any greater number up to `max_extent` means that the header has been scrolled by
380    /// that much. The `overlaps_content` argument is true if the sliver's leading edge is beyond
381    /// its normal place in the viewport contents.
382    ///
383    /// When this method is called by [`layout_child`](Self::layout_child), the child can be set,
384    /// mutated, or replaced. Any time this method would mutate the child, call `mark_needs_layout`.
385    fn update_child(
386        self: RenderHandle<Self>,
387        app: &mut App,
388        shrink_offset: f64,
389        overlaps_content: bool,
390    ) {
391        let _ = (self, app, shrink_offset, overlaps_content);
392    }
393
394    /// The body of Flutter's `markNeedsLayout` override, run before the inherited body.
395    ///
396    /// This is automatically called whenever the child's intrinsic dimensions change, at which
397    /// point we should remeasure them during the next layout.
398    fn mark_needs_layout(self: RenderHandle<Self>, app: &mut App) {
399        self.header_data_mut(app).needs_update_child = true;
400        RenderSliver::mark_needs_layout(self, app);
401    }
402
403    /// Lays out the child.
404    ///
405    /// This is called by `perform_layout`. It applies the given `scroll_offset` (which need not
406    /// match the offset given by the constraints) and the `max_extent` (which need not match the
407    /// value returned by [`max_extent`](Self::max_extent)).
408    ///
409    /// The `overlaps_content` argument is passed to [`update_child`](Self::update_child).
410    fn layout_child(
411        self: RenderHandle<Self>,
412        app: &mut App,
413        scroll_offset: f64,
414        max_extent: f64,
415        overlaps_content: bool,
416    ) {
417        let shrink_offset = scroll_offset.min(max_extent);
418        let header = self.header_data(app);
419        if header.needs_update_child
420            || header.last_shrink_offset != shrink_offset
421            || header.last_overlaps_content != overlaps_content
422        {
423            self.as_object().invoke_layout_callback(app, |app| {
424                self.update_child(app, shrink_offset, overlaps_content);
425            });
426            let header = self.header_data_mut(app);
427            header.last_shrink_offset = shrink_offset;
428            header.last_overlaps_content = overlaps_content;
429            header.needs_update_child = false;
430        }
431        debug_assert!(
432            self.min_extent(app) <= max_extent,
433            "the max_extent for this persistent header is less than its min_extent"
434        );
435        let constraints = self.constraints(app);
436        let stretch_configuration = self.stretch_configuration(app);
437        let mut stretch_offset = 0.0;
438        if stretch_configuration.is_some() && constraints.scroll_offset == 0.0 {
439            stretch_offset += constraints.overlap.abs();
440        }
441
442        if let Some(child) = self.child(app) {
443            let min_extent = self.min_extent(app);
444            let child_constraints = constraints.as_box_constraints(
445                0.0,
446                min_extent.max(max_extent - shrink_offset) + stretch_offset,
447                None,
448            );
449            child.layout(app, child_constraints, true);
450        }
451
452        if let Some(configuration) = &stretch_configuration
453            && let Some(on_stretch_trigger) = configuration.on_stretch_trigger.clone()
454            && stretch_offset >= configuration.stretch_trigger_offset
455            && self.header_data(app).last_stretch_offset <= configuration.stretch_trigger_offset
456        {
457            // The future the trigger hands back is not awaited, as Dart's is not.
458            drop(on_stretch_trigger(app));
459        }
460        self.header_data_mut(app).last_stretch_offset = stretch_offset;
461    }
462
463    /// The body of Flutter's `hitTestChildren` override.
464    fn hit_test_children(
465        self: RenderHandle<Self>,
466        app: &mut App,
467        result: &mut SliverHitTestResult<'_>,
468        main_axis_position: f64,
469        cross_axis_position: f64,
470    ) -> bool {
471        debug_assert!(self.geometry(app).hit_test_extent > 0.0);
472        let Some(child) = self.child(app) else {
473            return false;
474        };
475        self.hit_test_box_child(
476            app,
477            &mut BoxHitTestResult::wrap(result),
478            child,
479            main_axis_position,
480            cross_axis_position,
481        )
482    }
483
484    /// The body of Flutter's `applyPaintTransform` override.
485    fn apply_paint_transform(
486        self: RenderHandle<Self>,
487        app: &App,
488        child: AnyRenderObject,
489        transform: &mut Matrix4,
490    ) {
491        debug_assert_eq!(Some(child), self.child(app).map(AnyRenderBox::as_object));
492        let child = child.as_box().expect("the child is a box");
493        self.apply_paint_transform_for_box_child(app, child, transform);
494    }
495
496    /// The body of Flutter's `paint` override.
497    fn paint(
498        self: RenderHandle<Self>,
499        app: &mut App,
500        context: &mut PaintingContext,
501        offset: Offset,
502    ) {
503        let Some(child) = self.child(app) else {
504            return;
505        };
506        if !self.geometry(app).visible {
507            return;
508        }
509        let constraints = self.constraints(app);
510        let paint_extent = self.geometry(app).paint_extent;
511        let child_position = RenderSliver::child_main_axis_position(self, app, child.as_object());
512        let child_extent = self.child_extent(app);
513        let offset = offset
514            + match apply_growth_direction_to_axis_direction(
515                constraints.axis_direction,
516                constraints.growth_direction,
517            ) {
518                AxisDirection::Up => Offset::new(0.0, paint_extent - child_position - child_extent),
519                AxisDirection::Left => {
520                    Offset::new(paint_extent - child_position - child_extent, 0.0)
521                }
522                AxisDirection::Right => Offset::new(child_position, 0.0),
523                AxisDirection::Down => Offset::new(0.0, child_position),
524            };
525        context.paint_child(app, child.as_object(), offset);
526    }
527}
528
529/// Flutter's `RenderSliverScrollingPersistentHeader` field.
530#[derive(Debug, Default)]
531pub struct RenderSliverScrollingPersistentHeaderData {
532    // Distance from our leading edge to the child's leading edge, in the axis direction.
533    // Negative if we're scrolled off the top.
534    child_position: Option<f64>,
535}
536
537impl RenderSliverScrollingPersistentHeaderData {
538    /// Creates the state of a scrolling persistent header that has not been laid out.
539    pub const fn new() -> RenderSliverScrollingPersistentHeaderData {
540        RenderSliverScrollingPersistentHeaderData {
541            child_position: None,
542        }
543    }
544}
545
546/// A sliver with a box child which scrolls normally, except that when it hits the leading edge
547/// (typically the top) of the viewport, it shrinks to a minimum size before continuing to scroll.
548///
549/// This sliver makes no effort to avoid overlapping other content.
550pub trait RenderSliverScrollingPersistentHeader: RenderSliverPersistentHeader {
551    /// Mixin field access.
552    fn scrolling_data(
553        self: RenderHandle<Self>,
554        app: &App,
555    ) -> &RenderSliverScrollingPersistentHeaderData;
556
557    /// See [`scrolling_data`](Self::scrolling_data).
558    fn scrolling_data_mut(
559        self: RenderHandle<Self>,
560        app: &mut App,
561    ) -> &mut RenderSliverScrollingPersistentHeaderData;
562
563    /// Updates the geometry, and returns the new value for
564    /// [`RenderSliver::child_main_axis_position`].
565    fn update_geometry(self: RenderHandle<Self>, app: &mut App) -> f64 {
566        let constraints = self.constraints(app);
567        let mut stretch_offset = 0.0;
568        if self.stretch_configuration(app).is_some() {
569            stretch_offset += constraints.overlap.abs();
570        }
571        let max_extent = self.max_extent(app);
572        let paint_extent = max_extent - constraints.scroll_offset;
573        let cache_extent = calculate_cache_offset(constraints, 0.0, max_extent);
574
575        self.set_geometry(
576            app,
577            SliverGeometry::builder()
578                .scroll_extent(max_extent)
579                .paint_origin(constraints.overlap.min(0.0))
580                .paint_extent(clamp_double(
581                    paint_extent,
582                    0.0,
583                    constraints.remaining_paint_extent,
584                ))
585                .cache_extent(cache_extent)
586                .max_paint_extent(max_extent + stretch_offset)
587                // Conservatively say we do have overflow to avoid complexity.
588                .has_visual_overflow(true)
589                .build(),
590        );
591        if stretch_offset > 0.0 {
592            0.0
593        } else {
594            (paint_extent - self.child_extent(app)).min(0.0)
595        }
596    }
597
598    /// The body of Flutter's `performLayout` override.
599    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
600        let scroll_offset = self.constraints(app).scroll_offset;
601        let max_extent = self.max_extent(app);
602        self.layout_child(app, scroll_offset, max_extent, false);
603        let child_position = self.update_geometry(app);
604        self.scrolling_data_mut(app).child_position = Some(child_position);
605    }
606
607    /// The body of Flutter's `childMainAxisPosition` override.
608    fn child_main_axis_position(
609        self: RenderHandle<Self>,
610        app: &App,
611        child: AnyRenderObject,
612    ) -> f64 {
613        debug_assert_eq!(Some(child), self.child(app).map(AnyRenderBox::as_object));
614        self.scrolling_data(app)
615            .child_position
616            .expect("the header has been laid out")
617    }
618}
619
620/// Flutter's `RenderSliverPinnedPersistentHeader` field.
621#[derive(Clone, Copy, Debug)]
622pub struct RenderSliverPinnedPersistentHeaderData {
623    /// Specifies the persistent header's behavior when `show_on_screen` is called.
624    ///
625    /// If set to `None`, the persistent header will delegate the `show_on_screen` call to its
626    /// parent render object.
627    pub show_on_screen_configuration: Option<PersistentHeaderShowOnScreenConfiguration>,
628}
629
630impl RenderSliverPinnedPersistentHeaderData {
631    /// Creates the state of a pinned persistent header.
632    pub const fn new() -> RenderSliverPinnedPersistentHeaderData {
633        RenderSliverPinnedPersistentHeaderData {
634            show_on_screen_configuration: Some(PersistentHeaderShowOnScreenConfiguration::new()),
635        }
636    }
637}
638
639impl Default for RenderSliverPinnedPersistentHeaderData {
640    fn default() -> RenderSliverPinnedPersistentHeaderData {
641        RenderSliverPinnedPersistentHeaderData::new()
642    }
643}
644
645/// A sliver with a box child which never scrolls off the viewport in the positive scroll
646/// direction, and which first scrolls on at a full size but then shrinks as the viewport continues
647/// to scroll.
648///
649/// This sliver avoids overlapping other earlier slivers where possible.
650pub trait RenderSliverPinnedPersistentHeader: RenderSliverPersistentHeader {
651    /// Mixin field access.
652    fn pinned_data(self: RenderHandle<Self>, app: &App) -> &RenderSliverPinnedPersistentHeaderData;
653
654    /// See [`pinned_data`](Self::pinned_data).
655    fn pinned_data_mut(
656        self: RenderHandle<Self>,
657        app: &mut App,
658    ) -> &mut RenderSliverPinnedPersistentHeaderData;
659
660    /// The body of Flutter's `performLayout` override.
661    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
662        let constraints = self.constraints(app);
663        let max_extent = self.max_extent(app);
664        let overlaps_content = constraints.overlap > 0.0;
665        self.layout_child(app, constraints.scroll_offset, max_extent, overlaps_content);
666        let effective_remaining_paint_extent =
667            (constraints.remaining_paint_extent - constraints.overlap).max(0.0);
668        let layout_extent = clamp_double(
669            max_extent - constraints.scroll_offset,
670            0.0,
671            effective_remaining_paint_extent,
672        );
673        let stretch_offset = if self.stretch_configuration(app).is_some() {
674            constraints.overlap.abs()
675        } else {
676            0.0
677        };
678        let child_extent = self.child_extent(app);
679        let min_extent = self.min_extent(app);
680        self.set_geometry(
681            app,
682            SliverGeometry::builder()
683                .scroll_extent(max_extent)
684                .paint_origin(constraints.overlap)
685                .paint_extent(child_extent.min(effective_remaining_paint_extent))
686                .layout_extent(layout_extent)
687                .max_paint_extent(max_extent + stretch_offset)
688                .max_scroll_obstruction_extent(min_extent)
689                .cache_extent(if layout_extent > 0.0 {
690                    -constraints.cache_origin + layout_extent
691                } else {
692                    layout_extent
693                })
694                // Conservatively say we do have overflow to avoid complexity.
695                .has_visual_overflow(true)
696                .build(),
697        );
698    }
699
700    /// The body of Flutter's `childMainAxisPosition` override.
701    fn child_main_axis_position(
702        self: RenderHandle<Self>,
703        _app: &App,
704        _child: AnyRenderObject,
705    ) -> f64 {
706        let _ = self;
707        0.0
708    }
709
710    /// The body of Flutter's `showOnScreen` override.
711    fn show_on_screen(
712        self: RenderHandle<Self>,
713        app: &mut App,
714        descendant: Option<AnyRenderObject>,
715        rect: Option<Rect>,
716        duration: Duration,
717        curve: Rc<dyn Curve>,
718    ) {
719        let local_bounds = match descendant {
720            Some(descendant) => Some(transform_rect(
721                &descendant.get_transform_to(app, Some(self.as_object())),
722                rect.unwrap_or_else(|| descendant.paint_bounds(app)),
723            )),
724            None => rect,
725        };
726
727        let constraints = self.constraints(app);
728        let child_extent = self.child_extent(app);
729        let new_rect = match apply_growth_direction_to_axis_direction(
730            constraints.axis_direction,
731            constraints.growth_direction,
732        ) {
733            AxisDirection::Up => trim(
734                local_bounds,
735                f64::NEG_INFINITY,
736                f64::INFINITY,
737                child_extent,
738                f64::NEG_INFINITY,
739            ),
740            AxisDirection::Left => trim(
741                local_bounds,
742                f64::NEG_INFINITY,
743                child_extent,
744                f64::INFINITY,
745                f64::NEG_INFINITY,
746            ),
747            AxisDirection::Right => trim(
748                local_bounds,
749                f64::NEG_INFINITY,
750                f64::INFINITY,
751                f64::INFINITY,
752                0.0,
753            ),
754            AxisDirection::Down => trim(
755                local_bounds,
756                0.0,
757                f64::INFINITY,
758                f64::INFINITY,
759                f64::NEG_INFINITY,
760            ),
761        };
762
763        RenderObjectBase::show_on_screen(
764            self,
765            app,
766            Some(self.as_object()),
767            new_rect,
768            duration,
769            curve,
770        );
771    }
772}
773
774/// Flutter's `RenderSliverFloatingPersistentHeader` fields.
775pub struct RenderSliverFloatingPersistentHeaderData {
776    controller: Option<Ref<AnimationController>>,
777    animation: Option<AnimationRef<f64>>,
778    last_actual_scroll_offset: Option<f64>,
779    effective_scroll_offset: Option<f64>,
780    // Important for pointer scrolling, which does not have the same concept of a hold and release
781    // scroll movement, like dragging. This keeps track of the last ScrollDirection when scrolling
782    // started.
783    last_started_scroll_direction: Option<ScrollDirection>,
784    // Distance from our leading edge to the child's leading edge, in the axis direction.
785    // Negative if we're scrolled off the top.
786    child_position: Option<f64>,
787    vsync: Option<TickerProviderRef>,
788    /// Defines the parameters used to snap (animate) the floating header in and out of view.
789    ///
790    /// If this is `None` then the floating header does not snap.
791    pub snap_configuration: Option<FloatingHeaderSnapConfiguration>,
792    /// Specifies the persistent header's behavior when `show_on_screen` is called.
793    ///
794    /// If set to `None`, the persistent header will delegate the `show_on_screen` call to its
795    /// parent render object.
796    pub show_on_screen_configuration: Option<PersistentHeaderShowOnScreenConfiguration>,
797}
798
799impl RenderSliverFloatingPersistentHeaderData {
800    /// Creates the state of a floating persistent header that has not been laid out.
801    pub fn new(
802        vsync: Option<TickerProviderRef>,
803        snap_configuration: Option<FloatingHeaderSnapConfiguration>,
804        show_on_screen_configuration: Option<PersistentHeaderShowOnScreenConfiguration>,
805    ) -> RenderSliverFloatingPersistentHeaderData {
806        RenderSliverFloatingPersistentHeaderData {
807            controller: None,
808            animation: None,
809            last_actual_scroll_offset: None,
810            effective_scroll_offset: None,
811            last_started_scroll_direction: None,
812            child_position: None,
813            vsync,
814            snap_configuration,
815            show_on_screen_configuration,
816        }
817    }
818}
819
820/// A sliver with a box child which shrinks and scrolls like a
821/// [`RenderSliverScrollingPersistentHeader`], but immediately comes back when the user scrolls in
822/// the reverse direction.
823///
824/// See also:
825///
826///  * [`RenderSliverFloatingPinnedPersistentHeader`], which is similar but sticks to the start of
827///    the viewport rather than scrolling off.
828pub trait RenderSliverFloatingPersistentHeader: RenderSliverPersistentHeader {
829    /// Mixin field access.
830    fn floating_data(
831        self: RenderHandle<Self>,
832        app: &App,
833    ) -> &RenderSliverFloatingPersistentHeaderData;
834
835    /// See [`floating_data`](Self::floating_data).
836    fn floating_data_mut(
837        self: RenderHandle<Self>,
838        app: &mut App,
839    ) -> &mut RenderSliverFloatingPersistentHeaderData;
840
841    /// Dart's `debugFillProperties`: the persistent header's lines, then the effective scroll
842    /// offset.
843    fn debug_fill_properties(
844        self: RenderHandle<Self>,
845        app: &App,
846        properties: &mut DiagnosticPropertiesBuilder,
847    ) {
848        RenderSliverPersistentHeader::debug_fill_properties(self, app, properties);
849        properties.add(DoubleProperty::new(
850            "effective scroll offset",
851            self.effective_scroll_offset(app),
852        ));
853    }
854
855    /// The body of Flutter's `detach` override: disposes the snap animation controller, which is
856    /// lazily recreated if we are reattached.
857    fn did_detach(self: RenderHandle<Self>, app: &mut App) {
858        if let Some(controller) = self.floating_data(app).controller.handle() {
859            controller.dispose(app);
860        }
861        self.floating_data_mut(app).controller = None;
862    }
863
864    /// A [`TickerProvider`] to use when animating the scroll position.
865    fn vsync(self: RenderHandle<Self>, app: &App) -> Option<TickerProviderRef> {
866        self.floating_data(app).vsync.clone()
867    }
868
869    /// Sets [`vsync`](Self::vsync).
870    fn set_vsync(self: RenderHandle<Self>, app: &mut App, value: Option<TickerProviderRef>) {
871        if value == self.floating_data(app).vsync {
872            return;
873        }
874        self.floating_data_mut(app).vsync = value.clone();
875        match value {
876            None => {
877                if let Some(controller) = self.floating_data(app).controller.handle() {
878                    controller.dispose(app);
879                }
880                self.floating_data_mut(app).controller = None;
881            }
882            Some(vsync) => {
883                if let Some(controller) = self.floating_data(app).controller.handle() {
884                    controller.resync(app, vsync);
885                }
886            }
887        }
888    }
889
890    /// Defines the parameters used to snap (animate) the floating header in and out of view.
891    fn snap_configuration(
892        self: RenderHandle<Self>,
893        app: &App,
894    ) -> Option<FloatingHeaderSnapConfiguration> {
895        self.floating_data(app).snap_configuration.clone()
896    }
897
898    /// Sets [`snap_configuration`](Self::snap_configuration).
899    fn set_snap_configuration(
900        self: RenderHandle<Self>,
901        app: &mut App,
902        value: Option<FloatingHeaderSnapConfiguration>,
903    ) {
904        self.floating_data_mut(app).snap_configuration = value;
905    }
906
907    /// Specifies the persistent header's behavior when `show_on_screen` is called.
908    fn show_on_screen_configuration(
909        self: RenderHandle<Self>,
910        app: &App,
911    ) -> Option<PersistentHeaderShowOnScreenConfiguration> {
912        self.floating_data(app).show_on_screen_configuration
913    }
914
915    /// Sets [`show_on_screen_configuration`](Self::show_on_screen_configuration).
916    fn set_show_on_screen_configuration(
917        self: RenderHandle<Self>,
918        app: &mut App,
919        value: Option<PersistentHeaderShowOnScreenConfiguration>,
920    ) {
921        self.floating_data_mut(app).show_on_screen_configuration = value;
922    }
923
924    /// Flutter's `_effectiveScrollOffset`, the offset the header is laid out at.
925    fn effective_scroll_offset(self: RenderHandle<Self>, app: &App) -> Option<f64> {
926        self.floating_data(app).effective_scroll_offset
927    }
928
929    /// Updates the geometry, and returns the new value for
930    /// [`RenderSliver::child_main_axis_position`].
931    fn update_geometry(self: RenderHandle<Self>, app: &mut App) -> f64 {
932        let constraints = self.constraints(app);
933        let mut stretch_offset = 0.0;
934        if self.stretch_configuration(app).is_some() {
935            stretch_offset += constraints.overlap.abs();
936        }
937        let max_extent = self.max_extent(app);
938        let paint_extent = max_extent
939            - self
940                .effective_scroll_offset(app)
941                .expect("perform_layout sets the effective scroll offset");
942        let layout_extent = max_extent - constraints.scroll_offset;
943        self.set_geometry(
944            app,
945            SliverGeometry::builder()
946                .scroll_extent(max_extent)
947                .paint_origin(constraints.overlap.min(0.0))
948                .paint_extent(clamp_double(
949                    paint_extent,
950                    0.0,
951                    constraints.remaining_paint_extent,
952                ))
953                .layout_extent(clamp_double(
954                    layout_extent,
955                    0.0,
956                    constraints.remaining_paint_extent,
957                ))
958                .max_paint_extent(max_extent + stretch_offset)
959                // Conservatively say we do have overflow to avoid complexity.
960                .has_visual_overflow(true)
961                .build(),
962        );
963        if stretch_offset > 0.0 {
964            0.0
965        } else {
966            (paint_extent - self.child_extent(app)).min(0.0)
967        }
968    }
969
970    /// Flutter's `_updateAnimation`.
971    fn update_animation(
972        self: RenderHandle<Self>,
973        app: &mut App,
974        duration: Duration,
975        end_value: f64,
976        curve: Rc<dyn Curve>,
977    ) {
978        let vsync = self
979            .vsync(app)
980            .expect("vsync must be set if the floating header changes size animatedly");
981        let controller = match self.floating_data(app).controller.clone() {
982            Some(controller) => controller,
983            None => {
984                let controller = AnimationController::new(
985                    app,
986                    None,
987                    Some(duration),
988                    None,
989                    0.0,
990                    1.0,
991                    waft_animation::AnimationBehavior::Normal,
992                    vsync,
993                );
994                self.floating_data_mut(app).controller = Some(controller.clone());
995                controller.add_listener(
996                    app,
997                    Listener::handle_method(self.handle(), snap_tick::<Self>),
998                );
999                controller
1000            }
1001        };
1002        let begin = self.effective_scroll_offset(app);
1003        let tween = Tween::new(app, begin, Some(end_value));
1004        let curve_tween = CurveTween::new(app, curve);
1005        let animation = controller.drive(app, tween.chain(curve_tween));
1006        self.floating_data_mut(app).animation = Some(animation);
1007    }
1008
1009    /// Update the last known scroll direction when scrolling began.
1010    fn update_scroll_start_direction(
1011        self: RenderHandle<Self>,
1012        app: &mut App,
1013        direction: ScrollDirection,
1014    ) {
1015        self.floating_data_mut(app).last_started_scroll_direction = Some(direction);
1016    }
1017
1018    /// If the header isn't already fully exposed, then scroll it into view.
1019    fn maybe_start_snap_animation(
1020        self: RenderHandle<Self>,
1021        app: &mut App,
1022        direction: ScrollDirection,
1023    ) {
1024        let Some(snap) = self.snap_configuration(app) else {
1025            return;
1026        };
1027        let effective_scroll_offset = self
1028            .effective_scroll_offset(app)
1029            .expect("the header has been laid out");
1030        let max_extent = self.max_extent(app);
1031        if direction == ScrollDirection::Forward && effective_scroll_offset <= 0.0 {
1032            return;
1033        }
1034        if direction == ScrollDirection::Reverse && effective_scroll_offset >= max_extent {
1035            return;
1036        }
1037
1038        let end_value = if direction == ScrollDirection::Forward {
1039            0.0
1040        } else {
1041            max_extent
1042        };
1043        self.update_animation(app, snap.duration, end_value, Rc::clone(&snap.curve));
1044        if let Some(controller) = self.floating_data(app).controller.handle() {
1045            controller.forward(app, Some(0.0));
1046        }
1047    }
1048
1049    /// If a header snap animation or a `show_on_screen` expand animation is underway then stop it.
1050    fn maybe_stop_snap_animation(
1051        self: RenderHandle<Self>,
1052        app: &mut App,
1053        _direction: ScrollDirection,
1054    ) {
1055        if let Some(controller) = self.floating_data(app).controller.handle() {
1056            controller.stop(app, false);
1057        }
1058    }
1059
1060    /// The body of Flutter's `performLayout` override.
1061    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
1062        let constraints = self.constraints(app);
1063        let max_extent = self.max_extent(app);
1064        let data = self.floating_data(app);
1065        let last_actual_scroll_offset = data.last_actual_scroll_offset;
1066        let effective_scroll_offset = data.effective_scroll_offset;
1067        let last_started_scroll_direction = data.last_started_scroll_direction;
1068        // We've laid out at least once to get an initial position, and either we are scrolling
1069        // back, so should reveal, or some part of it is visible, so should shrink or reveal as
1070        // appropriate.
1071        let new_effective_scroll_offset = match last_actual_scroll_offset {
1072            Some(last_actual_scroll_offset)
1073                if constraints.scroll_offset < last_actual_scroll_offset
1074                    || effective_scroll_offset.is_some_and(|offset| offset < max_extent) =>
1075            {
1076                let mut delta = last_actual_scroll_offset - constraints.scroll_offset;
1077                let mut effective_scroll_offset =
1078                    effective_scroll_offset.expect("laid out at least once");
1079                let allow_floating_expansion = constraints.user_scroll_direction
1080                    == ScrollDirection::Forward
1081                    || last_started_scroll_direction == Some(ScrollDirection::Forward);
1082                if allow_floating_expansion {
1083                    if effective_scroll_offset > max_extent {
1084                        // We're scrolled off-screen, but should reveal, so pretend we're just at
1085                        // the limit.
1086                        effective_scroll_offset = max_extent;
1087                    }
1088                } else if delta > 0.0 {
1089                    // Disallow the expansion. (But allow shrinking, i.e. delta < 0.0 is fine.)
1090                    delta = 0.0;
1091                }
1092                clamp_double(
1093                    effective_scroll_offset - delta,
1094                    0.0,
1095                    constraints.scroll_offset,
1096                )
1097            }
1098            _ => constraints.scroll_offset,
1099        };
1100        self.floating_data_mut(app).effective_scroll_offset = Some(new_effective_scroll_offset);
1101        let overlaps_content = new_effective_scroll_offset < constraints.scroll_offset;
1102
1103        self.layout_child(
1104            app,
1105            new_effective_scroll_offset,
1106            max_extent,
1107            overlaps_content,
1108        );
1109        let child_position = self.update_geometry(app);
1110        let data = self.floating_data_mut(app);
1111        data.child_position = Some(child_position);
1112        data.last_actual_scroll_offset = Some(constraints.scroll_offset);
1113    }
1114
1115    /// The body of Flutter's `showOnScreen` override.
1116    fn show_on_screen(
1117        self: RenderHandle<Self>,
1118        app: &mut App,
1119        descendant: Option<AnyRenderObject>,
1120        rect: Option<Rect>,
1121        duration: Duration,
1122        curve: Rc<dyn Curve>,
1123    ) {
1124        let Some(show_on_screen) = self.show_on_screen_configuration(app) else {
1125            return RenderObjectBase::show_on_screen(self, app, descendant, rect, duration, curve);
1126        };
1127
1128        let child = self.child(app);
1129        debug_assert!(child.is_some() || descendant.is_none());
1130        // We prefer the child's coordinate space (instead of the sliver's) because it's easier for
1131        // us to convert the target rect into target extents: when the sliver is sitting above the
1132        // leading edge (not possible with pinned headers), the leading edge of the sliver and the
1133        // leading edge of the child will not be aligned. The only exception is when the child is
1134        // `None` (and thus `descendant` is `None`).
1135        let child_bounds = match descendant {
1136            Some(descendant) => Some(transform_rect(
1137                &descendant.get_transform_to(app, child.map(AnyRenderBox::as_object)),
1138                rect.unwrap_or_else(|| descendant.paint_bounds(app)),
1139            )),
1140            None => rect,
1141        };
1142
1143        let constraints = self.constraints(app);
1144        let child_extent = self.child_extent(app);
1145        let (mut target_extent, target_rect) = match apply_growth_direction_to_axis_direction(
1146            constraints.axis_direction,
1147            constraints.growth_direction,
1148        ) {
1149            AxisDirection::Up => (
1150                child_extent - child_bounds.map_or(0.0, |bounds| bounds.top),
1151                trim(
1152                    child_bounds,
1153                    f64::NEG_INFINITY,
1154                    f64::INFINITY,
1155                    child_extent,
1156                    f64::NEG_INFINITY,
1157                ),
1158            ),
1159            AxisDirection::Right => (
1160                child_bounds.map_or(child_extent, |bounds| bounds.right),
1161                trim(
1162                    child_bounds,
1163                    f64::NEG_INFINITY,
1164                    f64::INFINITY,
1165                    f64::INFINITY,
1166                    0.0,
1167                ),
1168            ),
1169            AxisDirection::Down => (
1170                child_bounds.map_or(child_extent, |bounds| bounds.bottom),
1171                trim(
1172                    child_bounds,
1173                    0.0,
1174                    f64::INFINITY,
1175                    f64::INFINITY,
1176                    f64::NEG_INFINITY,
1177                ),
1178            ),
1179            AxisDirection::Left => (
1180                child_extent - child_bounds.map_or(0.0, |bounds| bounds.left),
1181                trim(
1182                    child_bounds,
1183                    f64::NEG_INFINITY,
1184                    child_extent,
1185                    f64::INFINITY,
1186                    f64::NEG_INFINITY,
1187                ),
1188            ),
1189        };
1190
1191        // A stretch header can have a bigger child extent than max extent.
1192        let max_extent = self.max_extent(app);
1193        let effective_max_extent = child_extent.max(max_extent);
1194
1195        target_extent = clamp_double(
1196            clamp_double(
1197                target_extent,
1198                show_on_screen.min_show_on_screen_extent,
1199                show_on_screen.max_show_on_screen_extent,
1200            ),
1201            // Clamp the value back to the valid range after applying additional constraints.
1202            // Contracting is not allowed.
1203            child_extent,
1204            effective_max_extent,
1205        );
1206
1207        // Expands the header if needed, with animation.
1208        let controller_status = self
1209            .floating_data(app)
1210            .controller
1211            .handle()
1212            .map(|controller| controller.status(app));
1213        if target_extent > child_extent && controller_status != Some(AnimationStatus::Forward) {
1214            let target_scroll_offset = max_extent - target_extent;
1215            debug_assert!(
1216                self.vsync(app).is_some(),
1217                "vsync must be set if the floating header changes size animatedly"
1218            );
1219            self.update_animation(app, duration, target_scroll_offset, Rc::clone(&curve));
1220            if let Some(controller) = self.floating_data(app).controller.handle() {
1221                controller.forward(app, Some(0.0));
1222            }
1223        }
1224
1225        let descendant = match descendant {
1226            None => Some(self.as_object()),
1227            Some(_) => child.map(AnyRenderBox::as_object),
1228        };
1229        RenderObjectBase::show_on_screen(self, app, descendant, target_rect, duration, curve);
1230    }
1231
1232    /// The body of Flutter's `childMainAxisPosition` override.
1233    fn child_main_axis_position(
1234        self: RenderHandle<Self>,
1235        app: &App,
1236        child: AnyRenderObject,
1237    ) -> f64 {
1238        debug_assert_eq!(Some(child), self.child(app).map(AnyRenderBox::as_object));
1239        self.floating_data(app).child_position.unwrap_or(0.0)
1240    }
1241
1242    /// The type-erased `RenderSliverFloatingPersistentHeader` handle. Free: the vtable is a
1243    /// `const`, and the id is copied.
1244    fn as_floating_persistent_header(
1245        self: RenderHandle<Self>,
1246    ) -> AnyRenderSliverFloatingPersistentHeader {
1247        AnyRenderSliverFloatingPersistentHeader {
1248            id: self.id(),
1249            vtable: const { &RenderSliverFloatingPersistentHeaderVTable::of::<Self>() },
1250        }
1251    }
1252}
1253
1254/// The vtable of an erased [`AnyRenderSliverFloatingPersistentHeader`].
1255struct RenderSliverFloatingPersistentHeaderVTable {
1256    update_scroll_start_direction: fn(&mut App, HandleId, ScrollDirection),
1257    maybe_start_snap_animation: fn(&mut App, HandleId, ScrollDirection),
1258    maybe_stop_snap_animation: fn(&mut App, HandleId, ScrollDirection),
1259}
1260
1261impl RenderSliverFloatingPersistentHeaderVTable {
1262    const fn of<T: RenderSliverFloatingPersistentHeader>()
1263    -> RenderSliverFloatingPersistentHeaderVTable {
1264        RenderSliverFloatingPersistentHeaderVTable {
1265            update_scroll_start_direction: |app, id, direction| {
1266                T::update_scroll_start_direction(resolve(id), app, direction)
1267            },
1268            maybe_start_snap_animation: |app, id, direction| {
1269                T::maybe_start_snap_animation(resolve(id), app, direction)
1270            },
1271            maybe_stop_snap_animation: |app, id, direction| {
1272                T::maybe_stop_snap_animation(resolve(id), app, direction)
1273            },
1274        }
1275    }
1276}
1277
1278/// Erased [`RenderSliverFloatingPersistentHeader`]: what Dart's
1279/// `findAncestorRenderObjectOfType<RenderSliverFloatingPersistentHeader>()` hands back.
1280#[derive(Clone, Copy)]
1281pub struct AnyRenderSliverFloatingPersistentHeader {
1282    id: HandleId,
1283    vtable: &'static RenderSliverFloatingPersistentHeaderVTable,
1284}
1285
1286impl AnyRenderSliverFloatingPersistentHeader {
1287    /// See [`RenderSliverFloatingPersistentHeader::update_scroll_start_direction`].
1288    pub fn update_scroll_start_direction(self, app: &mut App, direction: ScrollDirection) {
1289        (self.vtable.update_scroll_start_direction)(app, self.id, direction)
1290    }
1291
1292    /// See [`RenderSliverFloatingPersistentHeader::maybe_start_snap_animation`].
1293    pub fn maybe_start_snap_animation(self, app: &mut App, direction: ScrollDirection) {
1294        (self.vtable.maybe_start_snap_animation)(app, self.id, direction)
1295    }
1296
1297    /// See [`RenderSliverFloatingPersistentHeader::maybe_stop_snap_animation`].
1298    pub fn maybe_stop_snap_animation(self, app: &mut App, direction: ScrollDirection) {
1299        (self.vtable.maybe_stop_snap_animation)(app, self.id, direction)
1300    }
1301}
1302
1303impl PartialEq for AnyRenderSliverFloatingPersistentHeader {
1304    fn eq(&self, other: &AnyRenderSliverFloatingPersistentHeader) -> bool {
1305        self.id == other.id
1306    }
1307}
1308
1309impl Eq for AnyRenderSliverFloatingPersistentHeader {}
1310
1311/// The snap animation's listener: Dart's closure inside `_updateAnimation`.
1312fn snap_tick<T: RenderSliverFloatingPersistentHeader>(this: Handle<T>, app: &mut App) {
1313    let this = RenderHandle::from_handle(this);
1314    let Some(animation) = this.floating_data(app).animation.handle() else {
1315        return;
1316    };
1317    let value = animation.value(app);
1318    if this.effective_scroll_offset(app) == Some(value) {
1319        return;
1320    }
1321    this.floating_data_mut(app).effective_scroll_offset = Some(value);
1322    RenderSliverPersistentHeader::mark_needs_layout(this, app);
1323}
1324
1325/// A sliver with a box child which shrinks and then remains pinned to the start of the viewport
1326/// like a [`RenderSliverPinnedPersistentHeader`], but immediately grows when the user scrolls in
1327/// the reverse direction.
1328///
1329/// See also:
1330///
1331///  * [`RenderSliverFloatingPersistentHeader`], which is similar but scrolls off the top rather
1332///    than sticking to it.
1333pub trait RenderSliverFloatingPinnedPersistentHeader: RenderSliverFloatingPersistentHeader {
1334    /// The body of Flutter's `updateGeometry` override.
1335    fn update_geometry(self: RenderHandle<Self>, app: &mut App) -> f64 {
1336        let constraints = self.constraints(app);
1337        let min_extent = self.min_extent(app);
1338        let min_allowed_extent = if constraints.remaining_paint_extent > min_extent {
1339            min_extent
1340        } else {
1341            constraints.remaining_paint_extent
1342        };
1343        let max_extent = self.max_extent(app);
1344        let paint_extent = max_extent
1345            - self
1346                .effective_scroll_offset(app)
1347                .expect("perform_layout sets the effective scroll offset");
1348        let clamped_paint_extent = clamp_double(
1349            paint_extent,
1350            min_allowed_extent,
1351            constraints.remaining_paint_extent,
1352        );
1353        let layout_extent = max_extent - constraints.scroll_offset;
1354        let stretch_offset = if self.stretch_configuration(app).is_some() {
1355            constraints.overlap.abs()
1356        } else {
1357            0.0
1358        };
1359        self.set_geometry(
1360            app,
1361            SliverGeometry::builder()
1362                .scroll_extent(max_extent)
1363                .paint_origin(constraints.overlap.min(0.0))
1364                .paint_extent(clamped_paint_extent)
1365                .layout_extent(clamp_double(layout_extent, 0.0, clamped_paint_extent))
1366                .max_paint_extent(max_extent + stretch_offset)
1367                .max_scroll_obstruction_extent(min_extent)
1368                // Conservatively say we do have overflow to avoid complexity.
1369                .has_visual_overflow(true)
1370                .build(),
1371        );
1372        0.0
1373    }
1374}
1375
1376#[cfg(test)]
1377mod tests {
1378    use std::cell::Cell;
1379    use waft_foundation::Ref;
1380
1381    use waft_embedder::Size;
1382    use waft_foundation::{AppCell, Task};
1383
1384    use super::*;
1385    use crate::object::{RenderObject, RenderObjectData, RenderObjectWithChildData};
1386    use crate::sliver::{AnyRenderSliver, RenderSliverData};
1387    use crate::sliver_multi_box_adaptor::test_support::hit_testable_box;
1388    use crate::sliver_multi_box_adaptor::viewport_test_support::ScrollHarness;
1389
1390    /// The shape every persistent header leaf in this test shares: a min and a max extent, and a
1391    /// box child of the header's current extent.
1392    macro_rules! persistent_header_leaf {
1393        ($leaf:ident, $extra:ident, $perform_layout:path, $child_position:path) => {
1394            struct $leaf {
1395                render_object: RenderObjectData,
1396                render_sliver: RenderSliverData,
1397                child: RenderObjectWithChildData<AnyRenderBox>,
1398                header: RenderSliverPersistentHeaderData,
1399                extra: $extra,
1400                min_extent: f64,
1401                max_extent: f64,
1402            }
1403
1404            impl RenderObjectWithChildMixin for $leaf {
1405                type ChildType = AnyRenderBox;
1406
1407                fn child_data(
1408                    self: RenderHandle<Self>,
1409                    app: &App,
1410                ) -> &RenderObjectWithChildData<AnyRenderBox> {
1411                    &self.get(app).child
1412                }
1413
1414                fn child_data_mut(
1415                    self: RenderHandle<Self>,
1416                    app: &mut App,
1417                ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
1418                    &mut self.get_mut(app).child
1419                }
1420            }
1421
1422            impl RenderSliverHelpers for $leaf {}
1423
1424            impl RenderSliverPersistentHeader for $leaf {
1425                crate::render_sliver_persistent_header_accessors!();
1426
1427                fn max_extent(self: RenderHandle<Self>, app: &App) -> f64 {
1428                    self.get(app).max_extent
1429                }
1430
1431                fn min_extent(self: RenderHandle<Self>, app: &App) -> f64 {
1432                    self.get(app).min_extent
1433                }
1434            }
1435
1436            impl RenderObject for $leaf {
1437                crate::render_object_accessors!();
1438
1439                fn visit_children(
1440                    self: RenderHandle<Self>,
1441                    app: &App,
1442                    visitor: &mut dyn FnMut(AnyRenderObject),
1443                ) {
1444                    if let Some(child) = self.child(app) {
1445                        visitor(child.as_object());
1446                    }
1447                }
1448
1449                fn apply_paint_transform(
1450                    self: RenderHandle<Self>,
1451                    app: &App,
1452                    child: AnyRenderObject,
1453                    transform: &mut Matrix4,
1454                ) {
1455                    RenderSliverPersistentHeader::apply_paint_transform(self, app, child, transform)
1456                }
1457
1458                fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
1459                    $perform_layout(self, app)
1460                }
1461
1462                fn paint(
1463                    self: RenderHandle<Self>,
1464                    app: &mut App,
1465                    context: &mut PaintingContext,
1466                    offset: Offset,
1467                ) {
1468                    RenderSliverPersistentHeader::paint(self, app, context, offset)
1469                }
1470
1471                fn debug_fill_properties(
1472                    self: RenderHandle<Self>,
1473                    app: &App,
1474                    properties: &mut DiagnosticPropertiesBuilder,
1475                ) {
1476                    RenderSliverPersistentHeader::debug_fill_properties(self, app, properties)
1477                }
1478            }
1479
1480            impl RenderSliver for $leaf {
1481                crate::render_sliver_accessors!();
1482
1483                fn hit_test_children(
1484                    self: RenderHandle<Self>,
1485                    app: &mut App,
1486                    result: &mut SliverHitTestResult<'_>,
1487                    main_axis_position: f64,
1488                    cross_axis_position: f64,
1489                ) -> bool {
1490                    RenderSliverPersistentHeader::hit_test_children(
1491                        self,
1492                        app,
1493                        result,
1494                        main_axis_position,
1495                        cross_axis_position,
1496                    )
1497                }
1498
1499                fn child_main_axis_position(
1500                    self: RenderHandle<Self>,
1501                    app: &App,
1502                    child: AnyRenderObject,
1503                ) -> f64 {
1504                    $child_position(self, app, child)
1505                }
1506            }
1507        };
1508    }
1509
1510    type ScrollingExtra = RenderSliverScrollingPersistentHeaderData;
1511    type PinnedExtra = RenderSliverPinnedPersistentHeaderData;
1512
1513    persistent_header_leaf!(
1514        TestScrollingHeader,
1515        ScrollingExtra,
1516        RenderSliverScrollingPersistentHeader::perform_layout,
1517        RenderSliverScrollingPersistentHeader::child_main_axis_position
1518    );
1519
1520    impl RenderSliverScrollingPersistentHeader for TestScrollingHeader {
1521        fn scrolling_data(
1522            self: RenderHandle<Self>,
1523            app: &App,
1524        ) -> &RenderSliverScrollingPersistentHeaderData {
1525            &self.get(app).extra
1526        }
1527
1528        fn scrolling_data_mut(
1529            self: RenderHandle<Self>,
1530            app: &mut App,
1531        ) -> &mut RenderSliverScrollingPersistentHeaderData {
1532            &mut self.get_mut(app).extra
1533        }
1534    }
1535
1536    persistent_header_leaf!(
1537        TestPinnedHeader,
1538        PinnedExtra,
1539        RenderSliverPinnedPersistentHeader::perform_layout,
1540        RenderSliverPinnedPersistentHeader::child_main_axis_position
1541    );
1542
1543    impl RenderSliverPinnedPersistentHeader for TestPinnedHeader {
1544        fn pinned_data(
1545            self: RenderHandle<Self>,
1546            app: &App,
1547        ) -> &RenderSliverPinnedPersistentHeaderData {
1548            &self.get(app).extra
1549        }
1550
1551        fn pinned_data_mut(
1552            self: RenderHandle<Self>,
1553            app: &mut App,
1554        ) -> &mut RenderSliverPinnedPersistentHeaderData {
1555            &mut self.get_mut(app).extra
1556        }
1557    }
1558
1559    fn scrolling_header(
1560        app: &mut App,
1561        min_extent: f64,
1562        max_extent: f64,
1563    ) -> RenderHandle<TestScrollingHeader> {
1564        let child = hit_testable_box(app, max_extent);
1565        let header = RenderHandle::new_sliver(
1566            app,
1567            TestScrollingHeader {
1568                render_object: RenderObjectData::new(),
1569                render_sliver: RenderSliverData::new(),
1570                child: RenderObjectWithChildData::new(),
1571                header: RenderSliverPersistentHeaderData::new(None),
1572                extra: RenderSliverScrollingPersistentHeaderData::new(),
1573                min_extent,
1574                max_extent,
1575            },
1576        );
1577        header.set_child(app, Some(child));
1578        header
1579    }
1580
1581    fn pinned_header(
1582        app: &mut App,
1583        min_extent: f64,
1584        max_extent: f64,
1585    ) -> RenderHandle<TestPinnedHeader> {
1586        let child = hit_testable_box(app, max_extent);
1587        let header = RenderHandle::new_sliver(
1588            app,
1589            TestPinnedHeader {
1590                render_object: RenderObjectData::new(),
1591                render_sliver: RenderSliverData::new(),
1592                child: RenderObjectWithChildData::new(),
1593                header: RenderSliverPersistentHeaderData::new(None),
1594                extra: RenderSliverPinnedPersistentHeaderData::new(),
1595                min_extent,
1596                max_extent,
1597            },
1598        );
1599        header.set_child(app, Some(child));
1600        header
1601    }
1602
1603    /// A header's `layout_child` runs inside a layout callback, so layout has to go through the
1604    /// owner's layout phase.
1605    fn lay_out(app: &mut App, sliver: AnyRenderSliver, scroll_offset: f64) -> ScrollHarness {
1606        let harness = ScrollHarness::new(app, sliver, Size::new(200.0, 400.0));
1607        harness.scroll_to(app, scroll_offset);
1608        harness
1609    }
1610
1611    /// `sliver_persistent_header_test.dart`: a scrolling header shrinks its paint extent as it
1612    /// scrolls off, keeping its full scroll extent.
1613    #[test]
1614    fn a_scrolling_header_shrinks_as_it_scrolls_off() {
1615        let cell = AppCell::new();
1616        let mut app = cell.borrow_mut();
1617        let header = scrolling_header(&mut app, 40.0, 120.0);
1618        lay_out(&mut app, header.as_sliver(), 50.0);
1619
1620        let geometry = header.geometry(&app);
1621        assert_eq!(geometry.scroll_extent, 120.0);
1622        assert_eq!(geometry.paint_extent, 70.0);
1623        assert_eq!(geometry.max_scroll_obstruction_extent, 0.0);
1624        // The child shrinks to what is left of the maximum extent, floored at the minimum.
1625        assert_eq!(header.child_extent(&app), 70.0);
1626        assert_eq!(header.last_shrink_offset(&app), 50.0);
1627        let child = header.child(&app).expect("has a child");
1628        assert_eq!(
1629            RenderSliver::child_main_axis_position(header, &app, child.as_object()),
1630            0.0
1631        );
1632    }
1633
1634    /// `sliver_persistent_header.dart`'s `RenderSliverPersistentHeader.debugFillProperties`: the
1635    /// maximum extent and the child's position.
1636    #[test]
1637    fn a_scrolling_header_dump_shows_its_max_extent_and_child_position() {
1638        let cell = AppCell::new();
1639        let mut app = cell.borrow_mut();
1640        let header = scrolling_header(&mut app, 40.0, 120.0);
1641        lay_out(&mut app, header.as_sliver(), 50.0);
1642
1643        let dump = header
1644            .as_object()
1645            .to_string_deep_with(&app, waft_foundation::DiagnosticLevel::Info);
1646        assert!(dump.contains("maxExtent: 120.0"), "{dump}");
1647        assert!(dump.contains("child position: 0.0"), "{dump}");
1648    }
1649
1650    /// A pinned header stays at the leading edge and reports its minimum extent as the scroll
1651    /// obstruction.
1652    #[test]
1653    fn a_pinned_header_stays_at_the_leading_edge() {
1654        let cell = AppCell::new();
1655        let mut app = cell.borrow_mut();
1656        let header = pinned_header(&mut app, 40.0, 120.0);
1657        lay_out(&mut app, header.as_sliver(), 100.0);
1658
1659        let geometry = header.geometry(&app);
1660        assert_eq!(geometry.scroll_extent, 120.0);
1661        assert_eq!(geometry.max_scroll_obstruction_extent, 40.0);
1662        // Shrunk to the minimum extent, still painting at the leading edge.
1663        assert_eq!(header.child_extent(&app), 40.0);
1664        assert_eq!(geometry.paint_extent, 40.0);
1665        assert_eq!(geometry.layout_extent, 20.0);
1666        let child = header.child(&app).expect("has a child");
1667        assert_eq!(
1668            RenderSliver::child_main_axis_position(header, &app, child.as_object()),
1669            0.0
1670        );
1671    }
1672
1673    /// An unscrolled pinned header is at its maximum extent.
1674    #[test]
1675    fn an_unscrolled_pinned_header_is_at_its_maximum_extent() {
1676        let cell = AppCell::new();
1677        let mut app = cell.borrow_mut();
1678        let header = pinned_header(&mut app, 40.0, 120.0);
1679        lay_out(&mut app, header.as_sliver(), 0.0);
1680
1681        let geometry = header.geometry(&app);
1682        assert_eq!(geometry.paint_extent, 120.0);
1683        assert_eq!(geometry.layout_extent, 120.0);
1684        assert_eq!(header.last_shrink_offset(&app), 0.0);
1685        assert!(!header.last_overlaps_content(&app));
1686    }
1687
1688    /// `layout_child` re-runs `update_child` only when the shrink offset or overlap changes.
1689    #[test]
1690    fn layout_child_reports_the_shrink_offset() {
1691        let cell = AppCell::new();
1692        let mut app = cell.borrow_mut();
1693        let header = scrolling_header(&mut app, 40.0, 120.0);
1694        lay_out(&mut app, header.as_sliver(), 80.0);
1695
1696        assert_eq!(header.last_shrink_offset(&app), 80.0);
1697        // The child is laid out with the remaining extent, floored at the minimum extent.
1698        assert_eq!(header.child_extent(&app), 40.0);
1699    }
1700
1701    /// The stretch trigger fires once as the overscroll crosses the trigger offset, and again
1702    /// only after the header has come back under it.
1703    #[test]
1704    fn the_stretch_trigger_fires_once_per_crossing() {
1705        let cell = AppCell::new();
1706        let mut app = cell.borrow_mut();
1707        let triggered = Rc::new(Cell::new(0));
1708        let counter = Rc::clone(&triggered);
1709        let configuration =
1710            OverScrollHeaderStretchConfiguration::new().on_stretch_trigger(Rc::new(move |_app| {
1711                counter.set(counter.get() + 1);
1712                Task::ready(())
1713            }));
1714        let header = scrolling_header(&mut app, 40.0, 120.0);
1715        header.set_stretch_configuration(&mut app, Some(configuration));
1716        let harness = lay_out(&mut app, header.as_sliver(), 0.0);
1717        assert_eq!(triggered.get(), 0);
1718
1719        harness.scroll_to(&mut app, -120.0);
1720        assert_eq!(triggered.get(), 1);
1721        harness.scroll_to(&mut app, -130.0);
1722        assert_eq!(triggered.get(), 1, "already past the trigger offset");
1723
1724        harness.scroll_to(&mut app, 0.0);
1725        harness.scroll_to(&mut app, -100.0);
1726        assert_eq!(triggered.get(), 2);
1727    }
1728
1729    /// The show-on-screen configuration defaults to the full unbounded range.
1730    #[test]
1731    fn the_show_on_screen_configuration_defaults_to_unbounded() {
1732        let configuration = PersistentHeaderShowOnScreenConfiguration::new();
1733        assert_eq!(configuration.min_show_on_screen_extent, f64::NEG_INFINITY);
1734        assert_eq!(configuration.max_show_on_screen_extent, f64::INFINITY);
1735        let snap = FloatingHeaderSnapConfiguration::new();
1736        assert_eq!(snap.duration, Duration::from_millis(300));
1737    }
1738
1739    /// A vsync that vends plain tickers.
1740    struct Vsync;
1741
1742    impl TickerProviderObject for Vsync {
1743        fn create_ticker(
1744            self: Handle<Self>,
1745            app: &mut App,
1746            on_tick: TickerCallback,
1747        ) -> Ref<Ticker> {
1748            Ticker::new(app, on_tick, None)
1749        }
1750    }
1751
1752    #[test]
1753    fn two_ticker_provider_refs_are_equal_when_they_erase_the_same_provider() {
1754        let cell = AppCell::new();
1755        let mut app = cell.borrow_mut();
1756        let vsync = app.create(Vsync);
1757        let other_vsync = app.create(Vsync);
1758
1759        assert!(TickerProviderRef::new(vsync.handle()) == TickerProviderRef::new(vsync.handle()));
1760        assert!(
1761            TickerProviderRef::new(vsync.handle()) != TickerProviderRef::new(other_vsync.handle())
1762        );
1763    }
1764}