Skip to main content

waft_widgets/widgets/
sliver_persistent_header.rs

1//! Flutter counterpart: `widgets/sliver_persistent_header.dart`.
2
3use std::any::{Any, TypeId};
4use std::fmt::{self, Debug};
5use std::panic::Location;
6use std::rc::Rc;
7use std::time::Duration;
8
9use waft_animation::Curve;
10use waft_embedder::{Matrix4, Offset, Rect};
11use waft_foundation::{
12    App, DiagnosticPropertiesBuilder, DiagnosticsProperty, Handle, IterableProperty,
13    ListenableObject, Listener, OptionRetained,
14};
15use waft_rendering::{
16    AnyRenderBox, AnyRenderObject, AnyRenderSliverFloatingPersistentHeader,
17    FloatingHeaderSnapConfiguration, OverScrollHeaderStretchConfiguration, PaintingContext,
18    PersistentHeaderShowOnScreenConfiguration, RenderHandle, RenderObject, RenderObjectData,
19    RenderObjectWithChildData, RenderObjectWithChildMixin, RenderSliver, RenderSliverData,
20    RenderSliverFloatingPersistentHeader, RenderSliverFloatingPersistentHeaderData,
21    RenderSliverFloatingPinnedPersistentHeader, RenderSliverHelpers, RenderSliverPersistentHeader,
22    RenderSliverPersistentHeaderData, RenderSliverPinnedPersistentHeader,
23    RenderSliverPinnedPersistentHeaderData, RenderSliverScrollingPersistentHeader,
24    RenderSliverScrollingPersistentHeaderData, SliverHitTestResult, TickerProviderRef,
25};
26
27use crate::framework::{
28    AnyElement, BuildContext, CreationLocation, Element, ElementData, IntoWidget, KeyRef,
29    RenderObjectElement, RenderObjectElementData, RenderObjectElementWidget, RenderObjectWidget,
30    Slot, State, StateData, StatefulWidget, StatelessWidget, Widget, WidgetKind, WidgetRef,
31    downcast_widget, short_type_name,
32};
33use crate::widgets::scroll_position::ScrollPositionRef;
34use crate::widgets::scrollable::Scrollable;
35
36// ---------------------------------------------------------------------------------------------
37// SliverPersistentHeaderDelegate
38
39/// Delegate for configuring a [`SliverPersistentHeader`].
40pub trait SliverPersistentHeaderDelegate: Debug + 'static {
41    /// The widget to place inside the [`SliverPersistentHeader`].
42    ///
43    /// The `context` is the [`BuildContext`] of the sliver.
44    ///
45    /// The `shrink_offset` is a distance from [`max_extent`](Self::max_extent) towards
46    /// [`min_extent`](Self::min_extent) representing the current amount by which the sliver has
47    /// been shrunk. When the shrink offset is zero, the contents will be rendered with a
48    /// dimension of `max_extent` in the main axis. When it equals the difference between
49    /// `max_extent` and `min_extent` (a positive number), the contents will be rendered with a
50    /// dimension of `min_extent` in the main axis. The shrink offset will always be a positive
51    /// number in that range.
52    ///
53    /// The `overlaps_content` argument is true if subsequent slivers (if any) will be rendered
54    /// beneath this one, and false if the sliver will not have any contents below it. Typically
55    /// this is used to decide whether to draw a shadow to simulate the sliver being above the
56    /// contents below it.
57    fn build(
58        &self,
59        app: &mut App,
60        context: BuildContext,
61        shrink_offset: f64,
62        overlaps_content: bool,
63    ) -> WidgetRef;
64
65    /// The smallest size to allow the header to reach, when it shrinks at the start of the
66    /// viewport.
67    ///
68    /// This must return a value equal to or less than [`max_extent`](Self::max_extent).
69    ///
70    /// This value should not change over the lifetime of the delegate. It should be based
71    /// entirely on the constructor arguments passed to the delegate. See
72    /// [`should_rebuild`](Self::should_rebuild), which must return true if a new delegate would
73    /// return a different value.
74    fn min_extent(&self) -> f64;
75
76    /// The size of the header when it is not shrinking at the top of the viewport.
77    ///
78    /// This must return a value equal to or greater than [`min_extent`](Self::min_extent).
79    fn max_extent(&self) -> f64;
80
81    /// A `TickerProvider` to use when animating the header's size changes.
82    ///
83    /// Must not be `None` if the persistent header is a floating header, and
84    /// [`snap_configuration`](Self::snap_configuration) or
85    /// [`show_on_screen_configuration`](Self::show_on_screen_configuration) is not `None`.
86    fn vsync(&self) -> Option<TickerProviderRef> {
87        None
88    }
89
90    /// Specifies how floating headers should animate in and out of view.
91    ///
92    /// If the value of this property is `None`, then floating headers will not animate into
93    /// place.
94    ///
95    /// This is only used for floating headers (those with [`SliverPersistentHeader::floating`]
96    /// set to true).
97    fn snap_configuration(&self) -> Option<FloatingHeaderSnapConfiguration> {
98        None
99    }
100
101    /// Specifies a callback and offset for execution.
102    ///
103    /// If the value of this property is `None`, then the callback will not be triggered.
104    ///
105    /// This is only used for stretching headers.
106    fn stretch_configuration(&self) -> Option<OverScrollHeaderStretchConfiguration> {
107        None
108    }
109
110    /// Specifies how floating headers and pinned headers should behave in response to
111    /// `RenderObject::show_on_screen` calls.
112    fn show_on_screen_configuration(&self) -> Option<PersistentHeaderShowOnScreenConfiguration> {
113        None
114    }
115
116    /// Whether this delegate is meaningfully different from the old delegate.
117    ///
118    /// If this returns false, then the header might not be rebuilt, even though the instance of
119    /// the delegate changed.
120    ///
121    /// This must return true if `old_delegate` and this object would return different values for
122    /// [`min_extent`](Self::min_extent), [`max_extent`](Self::max_extent),
123    /// [`snap_configuration`](Self::snap_configuration), or would return a meaningfully different
124    /// widget tree from [`build`](Self::build) for the same arguments.
125    ///
126    /// Dart's `covariant SliverPersistentHeaderDelegate oldDelegate`: the caller has already
127    /// compared [`delegate_type`](Self::delegate_type), so the argument downcasts through
128    /// [`as_any`](Self::as_any).
129    fn should_rebuild(&self, old_delegate: &dyn SliverPersistentHeaderDelegate) -> bool;
130
131    /// The concrete delegate, for Dart's `oldDelegate as Foo`.
132    fn as_any(&self) -> &dyn Any;
133
134    /// The concrete delegate's type, Dart's `runtimeType`.
135    fn delegate_type(&self) -> TypeId {
136        self.as_any().type_id()
137    }
138}
139
140/// A shared [`SliverPersistentHeaderDelegate`].
141pub type SliverPersistentHeaderDelegateRef = Rc<dyn SliverPersistentHeaderDelegate>;
142
143// ---------------------------------------------------------------------------------------------
144// SliverPersistentHeader
145
146/// A sliver whose size varies when the sliver is scrolled to the edge of the viewport opposite
147/// the sliver's `GrowthDirection`.
148///
149/// In the normal case of a `CustomScrollView` with no centered sliver, this sliver will vary its
150/// size when scrolled to the leading edge of the viewport.
151///
152/// This is the layout primitive that `SliverAppBar` uses for its shrinking/growing effect.
153///
154/// _To learn more about slivers, see `CustomScrollView::slivers`._
155#[derive(Debug)]
156pub struct SliverPersistentHeader {
157    pub key: Option<KeyRef>,
158    /// Configuration for the sliver's layout.
159    ///
160    /// The delegate provides the following information:
161    ///
162    ///  * The minimum and maximum dimensions of the sliver.
163    ///  * The builder for generating the widgets of the sliver.
164    ///  * The instructions for snapping the scroll offset, if [`floating`](Self::floating) is
165    ///    true.
166    pub delegate: SliverPersistentHeaderDelegateRef,
167    /// Whether to stick the header to the start of the viewport once it has reached its minimum
168    /// size.
169    ///
170    /// If this is false, the header will continue scrolling off the screen after it has shrunk to
171    /// its minimum extent.
172    pub pinned: bool,
173    /// Whether the header should immediately grow again if the user reverses scroll direction.
174    ///
175    /// If this is false, the header only grows again once the user reaches the part of the
176    /// viewport that contains the sliver.
177    ///
178    /// The delegate's `SliverPersistentHeaderDelegate::snap_configuration` is ignored unless
179    /// this is true.
180    pub floating: bool,
181}
182
183impl SliverPersistentHeader {
184    /// Creates a sliver that varies its size when it is scrolled to the start of a viewport.
185    pub fn new(delegate: SliverPersistentHeaderDelegateRef) -> SliverPersistentHeader {
186        SliverPersistentHeader {
187            key: None,
188            delegate,
189            pinned: false,
190            floating: false,
191        }
192    }
193
194    /// Dart `SliverPersistentHeader(key:)`.
195    pub fn key(mut self, key: KeyRef) -> SliverPersistentHeader {
196        self.key = Some(key);
197        self
198    }
199
200    /// Dart `SliverPersistentHeader(pinned:)`.
201    pub fn pinned(mut self, pinned: bool) -> SliverPersistentHeader {
202        self.pinned = pinned;
203        self
204    }
205
206    /// Dart `SliverPersistentHeader(floating:)`.
207    pub fn floating(mut self, floating: bool) -> SliverPersistentHeader {
208        self.floating = floating;
209        self
210    }
211}
212
213impl StatelessWidget for SliverPersistentHeader {
214    fn key(&self) -> Option<&KeyRef> {
215        self.key.as_ref()
216    }
217
218    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
219        properties.add(DiagnosticsProperty::<String>::new(
220            "delegate",
221            Some(format!("{:?}", self.delegate)),
222        ));
223        let mut flags: Vec<String> = Vec::new();
224        if self.pinned {
225            flags.push("pinned".to_string());
226        }
227        if self.floating {
228            flags.push("floating".to_string());
229        }
230        if flags.is_empty() {
231            flags.push("normal".to_string());
232        }
233        properties.add(IterableProperty::<String>::new("mode", flags));
234    }
235
236    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
237        let delegate = Rc::clone(&self.delegate);
238        match (self.floating, self.pinned) {
239            (true, true) => header_widget(SliverFloatingPinnedPersistentHeader { delegate }),
240            (false, true) => header_widget(SliverPinnedPersistentHeader { delegate }),
241            (true, false) => header_widget(SliverFloatingPersistentHeader { delegate }),
242            (false, false) => header_widget(SliverScrollingPersistentHeader { delegate }),
243        }
244    }
245}
246
247// ---------------------------------------------------------------------------------------------
248// The four private render object widgets
249
250/// Flutter's `_SliverPersistentHeaderRenderObjectWidget`.
251trait SliverPersistentHeaderRenderObjectWidget: RenderObjectWidget + Sized
252where
253    Self::RenderObject: RenderSliverPersistentHeaderForWidgets,
254{
255    /// The delegate that lays this header out and builds its child.
256    fn delegate(&self) -> &SliverPersistentHeaderDelegateRef;
257
258    /// Whether this header floats, in which case its child is wrapped in a [`FloatingHeader`].
259    ///
260    /// Dart's `floating` field, which the two floating widgets pass as `super(floating: true)`.
261    fn floating(&self) -> bool {
262        false
263    }
264}
265
266/// The erased form of a [`SliverPersistentHeaderRenderObjectWidget`], which is private in Dart
267/// and so has no [`IntoWidget`] kind of its own.
268struct SliverPersistentHeaderRenderObject<W: SliverPersistentHeaderRenderObjectWidget>(
269    W,
270    CreationLocation,
271)
272where
273    W::RenderObject: RenderSliverPersistentHeaderForWidgets;
274
275/// Dart's `_SliverScrollingPersistentHeader(delegate: ..)` as a tree node.
276#[cfg_attr(debug_assertions, track_caller)]
277fn header_widget<W: SliverPersistentHeaderRenderObjectWidget>(widget: W) -> WidgetRef
278where
279    W::RenderObject: RenderSliverPersistentHeaderForWidgets,
280{
281    Rc::new(SliverPersistentHeaderRenderObject(
282        widget,
283        CreationLocation::of_caller(),
284    ))
285}
286
287impl<W: SliverPersistentHeaderRenderObjectWidget> Widget for SliverPersistentHeaderRenderObject<W>
288where
289    W::RenderObject: RenderSliverPersistentHeaderForWidgets,
290{
291    fn key(&self) -> Option<&KeyRef> {
292        RenderObjectWidget::key(&self.0)
293    }
294
295    fn creation_location(&self) -> Option<&'static Location<'static>> {
296        self.1.location()
297    }
298
299    fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement {
300        SliverPersistentHeaderElement::<W>::new(app, this).as_element()
301    }
302
303    fn as_any(&self) -> &dyn Any {
304        &self.0
305    }
306
307    fn widget_type(&self) -> TypeId {
308        TypeId::of::<W>()
309    }
310
311    fn type_name(&self) -> &'static str {
312        short_type_name::<W>()
313    }
314
315    fn kind(&self) -> WidgetKind {
316        WidgetKind::Other
317    }
318}
319
320impl<W: SliverPersistentHeaderRenderObjectWidget> Debug for SliverPersistentHeaderRenderObject<W>
321where
322    W::RenderObject: RenderSliverPersistentHeaderForWidgets,
323{
324    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
325        self.0.fmt(f)
326    }
327}
328
329/// Flutter's `_SliverScrollingPersistentHeader`.
330#[derive(Debug)]
331struct SliverScrollingPersistentHeader {
332    delegate: SliverPersistentHeaderDelegateRef,
333}
334
335impl RenderObjectWidget for SliverScrollingPersistentHeader {
336    type RenderObject = RenderSliverScrollingPersistentHeaderForWidgets;
337
338    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
339        RenderSliverScrollingPersistentHeaderForWidgets::new(
340            app,
341            self.delegate.stretch_configuration(),
342        )
343        .as_object()
344    }
345
346    fn update_render_object(
347        &self,
348        app: &mut App,
349        _context: BuildContext,
350        render_object: RenderHandle<RenderSliverScrollingPersistentHeaderForWidgets>,
351    ) {
352        render_object.set_stretch_configuration(app, self.delegate.stretch_configuration());
353    }
354}
355
356impl SliverPersistentHeaderRenderObjectWidget for SliverScrollingPersistentHeader {
357    fn delegate(&self) -> &SliverPersistentHeaderDelegateRef {
358        &self.delegate
359    }
360}
361
362/// Flutter's `_SliverPinnedPersistentHeader`.
363#[derive(Debug)]
364struct SliverPinnedPersistentHeader {
365    delegate: SliverPersistentHeaderDelegateRef,
366}
367
368impl RenderObjectWidget for SliverPinnedPersistentHeader {
369    type RenderObject = RenderSliverPinnedPersistentHeaderForWidgets;
370
371    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
372        RenderSliverPinnedPersistentHeaderForWidgets::new(
373            app,
374            self.delegate.stretch_configuration(),
375            self.delegate.show_on_screen_configuration(),
376        )
377        .as_object()
378    }
379
380    fn update_render_object(
381        &self,
382        app: &mut App,
383        _context: BuildContext,
384        render_object: RenderHandle<RenderSliverPinnedPersistentHeaderForWidgets>,
385    ) {
386        render_object.set_stretch_configuration(app, self.delegate.stretch_configuration());
387        render_object
388            .pinned_data_mut(app)
389            .show_on_screen_configuration = self.delegate.show_on_screen_configuration();
390    }
391}
392
393impl SliverPersistentHeaderRenderObjectWidget for SliverPinnedPersistentHeader {
394    fn delegate(&self) -> &SliverPersistentHeaderDelegateRef {
395        &self.delegate
396    }
397}
398
399/// Flutter's `_SliverFloatingPersistentHeader`.
400#[derive(Debug)]
401struct SliverFloatingPersistentHeader {
402    delegate: SliverPersistentHeaderDelegateRef,
403}
404
405impl RenderObjectWidget for SliverFloatingPersistentHeader {
406    type RenderObject = RenderSliverFloatingPersistentHeaderForWidgets;
407
408    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
409        RenderSliverFloatingPersistentHeaderForWidgets::new(
410            app,
411            self.delegate.vsync(),
412            self.delegate.snap_configuration(),
413            self.delegate.stretch_configuration(),
414            self.delegate.show_on_screen_configuration(),
415        )
416        .as_object()
417    }
418
419    fn update_render_object(
420        &self,
421        app: &mut App,
422        _context: BuildContext,
423        render_object: RenderHandle<RenderSliverFloatingPersistentHeaderForWidgets>,
424    ) {
425        render_object.set_vsync(app, self.delegate.vsync());
426        render_object.set_snap_configuration(app, self.delegate.snap_configuration());
427        render_object.set_stretch_configuration(app, self.delegate.stretch_configuration());
428        render_object
429            .set_show_on_screen_configuration(app, self.delegate.show_on_screen_configuration());
430    }
431}
432
433impl SliverPersistentHeaderRenderObjectWidget for SliverFloatingPersistentHeader {
434    fn delegate(&self) -> &SliverPersistentHeaderDelegateRef {
435        &self.delegate
436    }
437
438    fn floating(&self) -> bool {
439        true
440    }
441}
442
443/// Flutter's `_SliverFloatingPinnedPersistentHeader`.
444#[derive(Debug)]
445struct SliverFloatingPinnedPersistentHeader {
446    delegate: SliverPersistentHeaderDelegateRef,
447}
448
449impl RenderObjectWidget for SliverFloatingPinnedPersistentHeader {
450    type RenderObject = RenderSliverFloatingPinnedPersistentHeaderForWidgets;
451
452    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
453        RenderSliverFloatingPinnedPersistentHeaderForWidgets::new(
454            app,
455            self.delegate.vsync(),
456            self.delegate.snap_configuration(),
457            self.delegate.stretch_configuration(),
458            self.delegate.show_on_screen_configuration(),
459        )
460        .as_object()
461    }
462
463    fn update_render_object(
464        &self,
465        app: &mut App,
466        _context: BuildContext,
467        render_object: RenderHandle<RenderSliverFloatingPinnedPersistentHeaderForWidgets>,
468    ) {
469        render_object.set_vsync(app, self.delegate.vsync());
470        render_object.set_snap_configuration(app, self.delegate.snap_configuration());
471        render_object.set_stretch_configuration(app, self.delegate.stretch_configuration());
472        render_object
473            .set_show_on_screen_configuration(app, self.delegate.show_on_screen_configuration());
474    }
475}
476
477impl SliverPersistentHeaderRenderObjectWidget for SliverFloatingPinnedPersistentHeader {
478    fn delegate(&self) -> &SliverPersistentHeaderDelegateRef {
479        &self.delegate
480    }
481
482    fn floating(&self) -> bool {
483        true
484    }
485}
486
487// ---------------------------------------------------------------------------------------------
488// _FloatingHeader
489
490/// Flutter's `_FloatingHeader`.
491#[derive(Debug)]
492struct FloatingHeader {
493    child: WidgetRef,
494}
495
496impl FloatingHeader {
497    #[cfg_attr(debug_assertions, track_caller)]
498    fn new<K>(child: impl IntoWidget<K>) -> FloatingHeader {
499        FloatingHeader {
500            child: child.into_widget(),
501        }
502    }
503}
504
505impl StatefulWidget for FloatingHeader {
506    type State = FloatingHeaderState;
507
508    fn create_state(&self) -> FloatingHeaderState {
509        FloatingHeaderState {
510            state: StateData::new(),
511            position: None,
512        }
513    }
514}
515
516/// A wrapper for the widget created by [`SliverPersistentHeaderElement`] that starts and stops
517/// the floating app bar's snap-into-view or snap-out-of-view animation. It also informs the float
518/// when pointer scrolling by updating the last known `ScrollDirection` when scrolling began.
519struct FloatingHeaderState {
520    state: StateData<FloatingHeader>,
521    position: Option<ScrollPositionRef>,
522}
523
524impl FloatingHeaderState {
525    /// Dart's `_headerRenderer`: the enclosing floating header render object, found through
526    /// `RenderObject::interface`, which answers Dart's
527    /// `findAncestorRenderObjectOfType<RenderSliverFloatingPersistentHeader>()`.
528    fn header_renderer(
529        self: Handle<Self>,
530        app: &App,
531    ) -> Option<AnyRenderSliverFloatingPersistentHeader> {
532        let mut ancestor = self.context(app).parent(app);
533        while let Some(current) = ancestor {
534            if current.is_render_object_element()
535                && let Some(render_object) = current.render_object(app)
536                && let Some(header) =
537                    render_object.interface::<AnyRenderSliverFloatingPersistentHeader>()
538            {
539                return Some(header);
540            }
541            ancestor = current.parent(app);
542        }
543        None
544    }
545
546    /// Dart's `_isScrollingListener`.
547    fn is_scrolling_listener(self: Handle<Self>, app: &mut App) {
548        let position = app
549            .get(self)
550            .position
551            .handle()
552            .expect("the listener is only registered while a position is held");
553
554        // When a scroll stops, then maybe snap the app bar into view.
555        // Similarly, when a scroll starts, then maybe stop the snap animation.
556        // Update the scrolling direction as well for pointer scrolling updates.
557        let header = self.header_renderer(app);
558        let direction = position.user_scroll_direction(app);
559        if *app.get(position.is_scrolling_notifier(app)).value() {
560            if let Some(header) = header {
561                header.update_scroll_start_direction(app, direction);
562                // Only SliverAppBars support snapping, headers will not snap.
563                header.maybe_stop_snap_animation(app, direction);
564            }
565        } else if let Some(header) = header {
566            // Only SliverAppBars support snapping, headers will not snap.
567            header.maybe_start_snap_animation(app, direction);
568        }
569    }
570
571    /// The tear-off Dart passes to `isScrollingNotifier.addListener` and `removeListener`.
572    fn is_scrolling_listener_tear_off(self: Handle<Self>) -> Listener {
573        Listener::handle_method(self, Self::is_scrolling_listener)
574    }
575}
576
577impl State for FloatingHeaderState {
578    type Widget = FloatingHeader;
579    crate::state_accessors!();
580
581    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
582        if let Some(position) = app.get(self).position.handle() {
583            position
584                .is_scrolling_notifier(app)
585                .remove_listener(app, &self.is_scrolling_listener_tear_off());
586        }
587        let context = self.context(app);
588        let position =
589            Scrollable::maybe_of(app, context, None).map(|state| state.kept_position(app));
590        app.get_mut(self).position = position.clone();
591        if let Some(position) = position {
592            position
593                .is_scrolling_notifier(app)
594                .add_listener(app, self.is_scrolling_listener_tear_off());
595        }
596    }
597
598    fn dispose(self: Handle<Self>, app: &mut App) {
599        if let Some(position) = app.get(self).position.handle() {
600            position
601                .is_scrolling_notifier(app)
602                .remove_listener(app, &self.is_scrolling_listener_tear_off());
603        }
604    }
605
606    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
607        self.widget(app).child.clone()
608    }
609}
610
611impl Debug for FloatingHeaderState {
612    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
613        f.debug_struct("FloatingHeaderState")
614            .field("position", &self.position)
615            .finish()
616    }
617}
618
619// ---------------------------------------------------------------------------------------------
620// _SliverPersistentHeaderElement
621
622/// Flutter's `_SliverPersistentHeaderElement`: builds the delegate's child during layout.
623struct SliverPersistentHeaderElement<W: SliverPersistentHeaderRenderObjectWidget>
624where
625    W::RenderObject: RenderSliverPersistentHeaderForWidgets,
626{
627    element: ElementData,
628    render_object_element: RenderObjectElementData,
629    floating: bool,
630    child: Option<AnyElement>,
631    marker: std::marker::PhantomData<fn() -> W>,
632}
633
634impl<W: SliverPersistentHeaderRenderObjectWidget> SliverPersistentHeaderElement<W>
635where
636    W::RenderObject: RenderSliverPersistentHeaderForWidgets,
637{
638    fn new(app: &mut App, widget: WidgetRef) -> Handle<SliverPersistentHeaderElement<W>> {
639        let floating = downcast_widget::<W>(&*widget)
640            .expect("a header element is created from its own widget")
641            .floating();
642        app.create(SliverPersistentHeaderElement::<W> {
643            element: ElementData::new(widget),
644            render_object_element: RenderObjectElementData::default(),
645            floating,
646            child: None,
647            marker: std::marker::PhantomData,
648        })
649        .into_tree_node(app)
650    }
651
652    fn header(self: Handle<Self>, app: &App) -> RenderHandle<W::RenderObject> {
653        self.typed_render_object(app)
654    }
655
656    /// Flutter's `_updateChild`.
657    fn update_child(
658        self: Handle<Self>,
659        app: &mut App,
660        delegate: SliverPersistentHeaderDelegateRef,
661        shrink_offset: f64,
662        overlaps_content: bool,
663    ) {
664        let new_widget = delegate.build(app, self.as_element(), shrink_offset, overlaps_content);
665        let new_widget = if app.get(self).floating {
666            FloatingHeader::new(new_widget).into_widget()
667        } else {
668            new_widget
669        };
670        let child = app.get(self).child;
671        let child = self
672            .as_element()
673            .update_child(app, child, Some(new_widget), None);
674        app.get_mut(self).child = child;
675    }
676
677    /// Flutter's `_build`, run from the render object's layout callback.
678    fn build(self: Handle<Self>, app: &mut App, shrink_offset: f64, overlaps_content: bool) {
679        let owner = self
680            .as_element()
681            .owner(app)
682            .expect("a mounted element has an owner");
683        owner.build_scope(
684            app,
685            self.as_element(),
686            Some(Box::new(move |app| {
687                let delegate = Rc::clone(Self::widget_of(self.as_element().widget(app)).delegate());
688                self.update_child(app, delegate, shrink_offset, overlaps_content);
689            })),
690        );
691    }
692
693    /// The element as its render object's `_element` field.
694    fn as_header_element(self: Handle<Self>) -> SliverPersistentHeaderElementRef {
695        SliverPersistentHeaderElementRef(Rc::new(self))
696    }
697}
698
699impl<W: SliverPersistentHeaderRenderObjectWidget> RenderObjectElementWidget
700    for SliverPersistentHeaderElement<W>
701where
702    W::RenderObject: RenderSliverPersistentHeaderForWidgets,
703{
704    type Widget = W;
705
706    fn widget_of(widget: &WidgetRef) -> &W {
707        downcast_widget::<W>(&**widget)
708            .expect("a SliverPersistentHeaderElement holds its header widget")
709    }
710}
711
712impl<W: SliverPersistentHeaderRenderObjectWidget> RenderObjectElement
713    for SliverPersistentHeaderElement<W>
714where
715    W::RenderObject: RenderSliverPersistentHeaderForWidgets,
716{
717    fn render_object_element_data(self: Handle<Self>, app: &App) -> &RenderObjectElementData {
718        &app.get(self).render_object_element
719    }
720
721    fn render_object_element_data_mut(
722        self: Handle<Self>,
723        app: &mut App,
724    ) -> &mut RenderObjectElementData {
725        &mut app.get_mut(self).render_object_element
726    }
727}
728
729impl<W: SliverPersistentHeaderRenderObjectWidget> Element for SliverPersistentHeaderElement<W>
730where
731    W::RenderObject: RenderSliverPersistentHeaderForWidgets,
732{
733    crate::element_accessors!();
734
735    const IS_RENDER_OBJECT_ELEMENT: bool = true;
736
737    fn render_object(self: Handle<Self>, app: &App) -> Option<AnyRenderObject> {
738        self.render_object_element_data(app).render_object()
739    }
740
741    fn render_object_attaching_child(self: Handle<Self>, _app: &App) -> Option<AnyElement> {
742        None
743    }
744
745    fn debug_doing_build(self: Handle<Self>, app: &App) -> bool {
746        self.render_object_element_data(app).debug_doing_build()
747    }
748
749    fn mount(
750        self: Handle<Self>,
751        app: &mut App,
752        parent: Option<AnyElement>,
753        new_slot: Option<Slot>,
754    ) {
755        RenderObjectElement::mount(self, app, parent, new_slot);
756        let element = self.as_header_element();
757        self.header(app).set_element(app, Some(element));
758    }
759
760    fn unmount(self: Handle<Self>, app: &mut App) {
761        self.header(app).set_element(app, None);
762        RenderObjectElement::unmount(self, app);
763    }
764
765    fn update(self: Handle<Self>, app: &mut App, new_widget: WidgetRef) {
766        let old_widget = self.as_element().widget(app).clone();
767        RenderObjectElement::update(self, app, new_widget.clone());
768        let new_delegate = Rc::clone(Self::widget_of(&new_widget).delegate());
769        let old_delegate = Rc::clone(Self::widget_of(&old_widget).delegate());
770        if !Rc::ptr_eq(&new_delegate, &old_delegate)
771            && (new_delegate.delegate_type() != old_delegate.delegate_type()
772                || new_delegate.should_rebuild(&*old_delegate))
773        {
774            let render_object = self.header(app);
775            let shrink_offset = render_object.last_shrink_offset(app);
776            let overlaps_content = render_object.last_overlaps_content(app);
777            self.update_child(app, new_delegate, shrink_offset, overlaps_content);
778            render_object.trigger_rebuild(app);
779        }
780    }
781
782    fn perform_rebuild(self: Handle<Self>, app: &mut App) {
783        RenderObjectElement::perform_rebuild(self, app);
784        self.header(app).trigger_rebuild(app);
785    }
786
787    fn forget_child(self: Handle<Self>, app: &mut App, child: AnyElement) {
788        debug_assert!(app.get(self).child == Some(child));
789        app.get_mut(self).child = None;
790    }
791
792    fn visit_children(self: Handle<Self>, app: &App, visitor: &mut dyn FnMut(AnyElement)) {
793        if let Some(child) = app.get(self).child {
794            visitor(child);
795        }
796    }
797
798    fn deactivate(self: Handle<Self>, app: &mut App) {
799        RenderObjectElement::deactivate(self, app);
800    }
801
802    fn update_parent_data(self: Handle<Self>, app: &mut App, parent_data_element: AnyElement) {
803        RenderObjectElement::update_parent_data(self, app, parent_data_element);
804    }
805
806    fn update_slot(self: Handle<Self>, app: &mut App, new_slot: Option<Slot>) {
807        RenderObjectElement::update_slot(self, app, new_slot);
808    }
809
810    fn attach_render_object(self: Handle<Self>, app: &mut App, new_slot: Option<Slot>) {
811        RenderObjectElement::attach_render_object(self, app, new_slot);
812    }
813
814    fn detach_render_object(self: Handle<Self>, app: &mut App) {
815        RenderObjectElement::detach_render_object(self, app);
816    }
817
818    fn insert_render_object_child(
819        self: Handle<Self>,
820        app: &mut App,
821        child: AnyRenderObject,
822        _slot: Option<Slot>,
823    ) {
824        let render_object = self.header(app);
825        render_object.set_child(app, Some(child.as_box().expect("a header child is a box")));
826    }
827
828    fn move_render_object_child(
829        self: Handle<Self>,
830        _app: &mut App,
831        _child: AnyRenderObject,
832        _old_slot: Option<Slot>,
833        _new_slot: Option<Slot>,
834    ) {
835        debug_assert!(false, "a persistent header has one child");
836    }
837
838    fn remove_render_object_child(
839        self: Handle<Self>,
840        app: &mut App,
841        _child: AnyRenderObject,
842        _slot: Option<Slot>,
843    ) {
844        self.header(app).set_child(app, None);
845    }
846}
847
848// ---------------------------------------------------------------------------------------------
849// _RenderSliverPersistentHeaderForWidgetsMixin
850
851/// The element behind a header render object, erased: Dart's `_element` field.
852///
853/// A `Handle<SliverPersistentHeaderElement<W>>` cannot be held by a render object that does not
854/// know `W`, so the mixin holds this `Rc` over the two members it calls.
855#[derive(Clone)]
856pub struct SliverPersistentHeaderElementRef(Rc<dyn ErasedHeaderElement>);
857
858impl PartialEq for SliverPersistentHeaderElementRef {
859    fn eq(&self, other: &SliverPersistentHeaderElementRef) -> bool {
860        Rc::ptr_eq(&self.0, &other.0)
861    }
862}
863
864impl Debug for SliverPersistentHeaderElementRef {
865    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
866        f.write_str("SliverPersistentHeaderElementRef")
867    }
868}
869
870/// The object side of [`SliverPersistentHeaderElementRef`].
871trait ErasedHeaderElement {
872    /// The delegate of the widget this element holds.
873    fn delegate(&self, app: &App) -> SliverPersistentHeaderDelegateRef;
874
875    /// `_SliverPersistentHeaderElement._build`.
876    fn build(&self, app: &mut App, shrink_offset: f64, overlaps_content: bool);
877}
878
879impl<W: SliverPersistentHeaderRenderObjectWidget> ErasedHeaderElement
880    for Handle<SliverPersistentHeaderElement<W>>
881where
882    W::RenderObject: RenderSliverPersistentHeaderForWidgets,
883{
884    fn delegate(&self, app: &App) -> SliverPersistentHeaderDelegateRef {
885        Rc::clone(
886            SliverPersistentHeaderElement::<W>::widget_of(self.as_element().widget(app)).delegate(),
887        )
888    }
889
890    fn build(&self, app: &mut App, shrink_offset: f64, overlaps_content: bool) {
891        SliverPersistentHeaderElement::<W>::build(*self, app, shrink_offset, overlaps_content);
892    }
893}
894
895/// Flutter's `_RenderSliverPersistentHeaderForWidgetsMixin` field.
896#[derive(Default)]
897pub struct RenderSliverPersistentHeaderForWidgetsData {
898    element: Option<SliverPersistentHeaderElementRef>,
899}
900
901impl RenderSliverPersistentHeaderForWidgetsData {
902    /// Creates the state of a header whose element has not mounted yet.
903    pub fn new() -> RenderSliverPersistentHeaderForWidgetsData {
904        RenderSliverPersistentHeaderForWidgetsData { element: None }
905    }
906}
907
908/// Flutter's `_RenderSliverPersistentHeaderForWidgetsMixin`: a persistent header whose extents
909/// and child come from a [`SliverPersistentHeaderDelegate`].
910pub trait RenderSliverPersistentHeaderForWidgets: RenderSliverPersistentHeader {
911    /// Mixin field access.
912    fn for_widgets_data(
913        self: RenderHandle<Self>,
914        app: &App,
915    ) -> &RenderSliverPersistentHeaderForWidgetsData;
916
917    /// See [`for_widgets_data`](Self::for_widgets_data).
918    fn for_widgets_data_mut(
919        self: RenderHandle<Self>,
920        app: &mut App,
921    ) -> &mut RenderSliverPersistentHeaderForWidgetsData;
922
923    /// Sets Dart's `_element`; the element does this at mount and clears it at unmount.
924    fn set_element(
925        self: RenderHandle<Self>,
926        app: &mut App,
927        element: Option<SliverPersistentHeaderElementRef>,
928    ) {
929        self.for_widgets_data_mut(app).element = element;
930    }
931
932    /// The delegate of the widget the element holds.
933    fn delegate(self: RenderHandle<Self>, app: &App) -> SliverPersistentHeaderDelegateRef {
934        self.for_widgets_data(app)
935            .element
936            .as_ref()
937            .expect("the element is set at mount")
938            .0
939            .delegate(app)
940    }
941
942    /// The body of Flutter's `minExtent` override.
943    fn min_extent(self: RenderHandle<Self>, app: &App) -> f64 {
944        self.delegate(app).min_extent()
945    }
946
947    /// The body of Flutter's `maxExtent` override.
948    fn max_extent(self: RenderHandle<Self>, app: &App) -> f64 {
949        self.delegate(app).max_extent()
950    }
951
952    /// The body of Flutter's `updateChild` override.
953    fn update_child(
954        self: RenderHandle<Self>,
955        app: &mut App,
956        shrink_offset: f64,
957        overlaps_content: bool,
958    ) {
959        let element = self
960            .for_widgets_data(app)
961            .element
962            .clone()
963            .expect("the element is set at mount");
964        element.0.build(app, shrink_offset, overlaps_content);
965    }
966
967    /// Flutter's `triggerRebuild`.
968    fn trigger_rebuild(self: RenderHandle<Self>, app: &mut App) {
969        RenderSliverPersistentHeader::mark_needs_layout(self, app);
970    }
971}
972
973/// The `RenderObjectWithChildMixin`, `RenderSliverHelpers`, `RenderSliverPersistentHeader` and
974/// `RenderSliverPersistentHeaderForWidgets` halves every header leaf writes the same way.
975macro_rules! header_for_widgets_leaf {
976    ($leaf:ident) => {
977        impl RenderObjectWithChildMixin for $leaf {
978            type ChildType = AnyRenderBox;
979
980            fn child_data(
981                self: RenderHandle<Self>,
982                app: &App,
983            ) -> &RenderObjectWithChildData<AnyRenderBox> {
984                &self.get(app).child
985            }
986
987            fn child_data_mut(
988                self: RenderHandle<Self>,
989                app: &mut App,
990            ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
991                &mut self.get_mut(app).child
992            }
993        }
994
995        impl RenderSliverHelpers for $leaf {}
996
997        impl RenderSliverPersistentHeader for $leaf {
998            waft_rendering::render_sliver_persistent_header_accessors!();
999
1000            fn max_extent(self: RenderHandle<Self>, app: &App) -> f64 {
1001                RenderSliverPersistentHeaderForWidgets::max_extent(self, app)
1002            }
1003
1004            fn min_extent(self: RenderHandle<Self>, app: &App) -> f64 {
1005                RenderSliverPersistentHeaderForWidgets::min_extent(self, app)
1006            }
1007
1008            fn update_child(
1009                self: RenderHandle<Self>,
1010                app: &mut App,
1011                shrink_offset: f64,
1012                overlaps_content: bool,
1013            ) {
1014                RenderSliverPersistentHeaderForWidgets::update_child(
1015                    self,
1016                    app,
1017                    shrink_offset,
1018                    overlaps_content,
1019                );
1020            }
1021        }
1022
1023        impl RenderSliverPersistentHeaderForWidgets for $leaf {
1024            fn for_widgets_data(
1025                self: RenderHandle<Self>,
1026                app: &App,
1027            ) -> &RenderSliverPersistentHeaderForWidgetsData {
1028                &self.get(app).for_widgets
1029            }
1030
1031            fn for_widgets_data_mut(
1032                self: RenderHandle<Self>,
1033                app: &mut App,
1034            ) -> &mut RenderSliverPersistentHeaderForWidgetsData {
1035                &mut self.get_mut(app).for_widgets
1036            }
1037        }
1038    };
1039}
1040
1041/// The `RenderObject` and `RenderSliver` halves shared by every header leaf: the persistent
1042/// header bodies and its properties, plus the `perform_layout` and `child_main_axis_position` of
1043/// the variant.
1044macro_rules! header_protocol {
1045    ($leaf:ident, $debug:path, $perform_layout:path, $child_position:path $(, $extra:item)*) => {
1046        impl RenderObject for $leaf {
1047            waft_rendering::render_object_accessors!();
1048
1049            fn visit_children(
1050                self: RenderHandle<Self>,
1051                app: &App,
1052                visitor: &mut dyn FnMut(AnyRenderObject),
1053            ) {
1054                if let Some(child) = self.child(app) {
1055                    visitor(child.as_object());
1056                }
1057            }
1058
1059            fn apply_paint_transform(
1060                self: RenderHandle<Self>,
1061                app: &App,
1062                child: AnyRenderObject,
1063                transform: &mut Matrix4,
1064            ) {
1065                RenderSliverPersistentHeader::apply_paint_transform(self, app, child, transform);
1066            }
1067
1068            fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
1069                $perform_layout(self, app)
1070            }
1071
1072            fn paint(
1073                self: RenderHandle<Self>,
1074                app: &mut App,
1075                context: &mut PaintingContext,
1076                offset: Offset,
1077            ) {
1078                RenderSliverPersistentHeader::paint(self, app, context, offset);
1079            }
1080
1081            fn debug_fill_properties(
1082                self: RenderHandle<Self>,
1083                app: &App,
1084                properties: &mut waft_foundation::DiagnosticPropertiesBuilder,
1085            ) {
1086                $debug(self, app, properties)
1087            }
1088
1089            $($extra)*
1090        }
1091
1092        impl RenderSliver for $leaf {
1093            waft_rendering::render_sliver_accessors!();
1094
1095            fn hit_test_children(
1096                self: RenderHandle<Self>,
1097                app: &mut App,
1098                result: &mut SliverHitTestResult<'_>,
1099                main_axis_position: f64,
1100                cross_axis_position: f64,
1101            ) -> bool {
1102                RenderSliverPersistentHeader::hit_test_children(
1103                    self,
1104                    app,
1105                    result,
1106                    main_axis_position,
1107                    cross_axis_position,
1108                )
1109            }
1110
1111            fn child_main_axis_position(
1112                self: RenderHandle<Self>,
1113                app: &App,
1114                child: AnyRenderObject,
1115            ) -> f64 {
1116                $child_position(self, app, child)
1117            }
1118        }
1119    };
1120}
1121
1122/// Flutter's `_RenderSliverScrollingPersistentHeaderForWidgets`.
1123pub struct RenderSliverScrollingPersistentHeaderForWidgets {
1124    render_object: RenderObjectData,
1125    render_sliver: RenderSliverData,
1126    child: RenderObjectWithChildData<AnyRenderBox>,
1127    header: RenderSliverPersistentHeaderData,
1128    scrolling: RenderSliverScrollingPersistentHeaderData,
1129    for_widgets: RenderSliverPersistentHeaderForWidgetsData,
1130}
1131
1132impl RenderSliverScrollingPersistentHeaderForWidgets {
1133    /// Creates a scrolling persistent header whose extents come from a delegate.
1134    pub fn new(
1135        app: &mut App,
1136        stretch_configuration: Option<OverScrollHeaderStretchConfiguration>,
1137    ) -> RenderHandle<RenderSliverScrollingPersistentHeaderForWidgets> {
1138        RenderHandle::new_sliver(
1139            app,
1140            RenderSliverScrollingPersistentHeaderForWidgets {
1141                render_object: RenderObjectData::new(),
1142                render_sliver: RenderSliverData::new(),
1143                child: RenderObjectWithChildData::new(),
1144                header: RenderSliverPersistentHeaderData::new(stretch_configuration),
1145                scrolling: RenderSliverScrollingPersistentHeaderData::new(),
1146                for_widgets: RenderSliverPersistentHeaderForWidgetsData::new(),
1147            },
1148        )
1149    }
1150}
1151
1152header_for_widgets_leaf!(RenderSliverScrollingPersistentHeaderForWidgets);
1153
1154impl RenderSliverScrollingPersistentHeader for RenderSliverScrollingPersistentHeaderForWidgets {
1155    fn scrolling_data(
1156        self: RenderHandle<Self>,
1157        app: &App,
1158    ) -> &RenderSliverScrollingPersistentHeaderData {
1159        &self.get(app).scrolling
1160    }
1161
1162    fn scrolling_data_mut(
1163        self: RenderHandle<Self>,
1164        app: &mut App,
1165    ) -> &mut RenderSliverScrollingPersistentHeaderData {
1166        &mut self.get_mut(app).scrolling
1167    }
1168}
1169
1170header_protocol!(
1171    RenderSliverScrollingPersistentHeaderForWidgets,
1172    RenderSliverPersistentHeader::debug_fill_properties,
1173    RenderSliverScrollingPersistentHeader::perform_layout,
1174    RenderSliverScrollingPersistentHeader::child_main_axis_position
1175);
1176
1177/// Flutter's `_RenderSliverPinnedPersistentHeaderForWidgets`.
1178pub struct RenderSliverPinnedPersistentHeaderForWidgets {
1179    render_object: RenderObjectData,
1180    render_sliver: RenderSliverData,
1181    child: RenderObjectWithChildData<AnyRenderBox>,
1182    header: RenderSliverPersistentHeaderData,
1183    pinned: RenderSliverPinnedPersistentHeaderData,
1184    for_widgets: RenderSliverPersistentHeaderForWidgetsData,
1185}
1186
1187impl RenderSliverPinnedPersistentHeaderForWidgets {
1188    /// Creates a pinned persistent header whose extents come from a delegate.
1189    pub fn new(
1190        app: &mut App,
1191        stretch_configuration: Option<OverScrollHeaderStretchConfiguration>,
1192        show_on_screen_configuration: Option<PersistentHeaderShowOnScreenConfiguration>,
1193    ) -> RenderHandle<RenderSliverPinnedPersistentHeaderForWidgets> {
1194        RenderHandle::new_sliver(
1195            app,
1196            RenderSliverPinnedPersistentHeaderForWidgets {
1197                render_object: RenderObjectData::new(),
1198                render_sliver: RenderSliverData::new(),
1199                child: RenderObjectWithChildData::new(),
1200                header: RenderSliverPersistentHeaderData::new(stretch_configuration),
1201                pinned: RenderSliverPinnedPersistentHeaderData {
1202                    show_on_screen_configuration,
1203                },
1204                for_widgets: RenderSliverPersistentHeaderForWidgetsData::new(),
1205            },
1206        )
1207    }
1208}
1209
1210header_for_widgets_leaf!(RenderSliverPinnedPersistentHeaderForWidgets);
1211
1212impl RenderSliverPinnedPersistentHeader for RenderSliverPinnedPersistentHeaderForWidgets {
1213    fn pinned_data(self: RenderHandle<Self>, app: &App) -> &RenderSliverPinnedPersistentHeaderData {
1214        &self.get(app).pinned
1215    }
1216
1217    fn pinned_data_mut(
1218        self: RenderHandle<Self>,
1219        app: &mut App,
1220    ) -> &mut RenderSliverPinnedPersistentHeaderData {
1221        &mut self.get_mut(app).pinned
1222    }
1223}
1224
1225header_protocol!(
1226    RenderSliverPinnedPersistentHeaderForWidgets,
1227    RenderSliverPersistentHeader::debug_fill_properties,
1228    RenderSliverPinnedPersistentHeader::perform_layout,
1229    RenderSliverPinnedPersistentHeader::child_main_axis_position,
1230    fn show_on_screen(
1231        self: RenderHandle<Self>,
1232        app: &mut App,
1233        descendant: Option<AnyRenderObject>,
1234        rect: Option<Rect>,
1235        duration: Duration,
1236        curve: Rc<dyn Curve>,
1237    ) {
1238        RenderSliverPinnedPersistentHeader::show_on_screen(
1239            self, app, descendant, rect, duration, curve,
1240        );
1241    }
1242);
1243
1244/// Flutter's `_RenderSliverFloatingPersistentHeaderForWidgets`.
1245pub struct RenderSliverFloatingPersistentHeaderForWidgets {
1246    render_object: RenderObjectData,
1247    render_sliver: RenderSliverData,
1248    child: RenderObjectWithChildData<AnyRenderBox>,
1249    header: RenderSliverPersistentHeaderData,
1250    floating: RenderSliverFloatingPersistentHeaderData,
1251    for_widgets: RenderSliverPersistentHeaderForWidgetsData,
1252}
1253
1254impl RenderSliverFloatingPersistentHeaderForWidgets {
1255    /// Creates a floating persistent header whose extents come from a delegate.
1256    pub fn new(
1257        app: &mut App,
1258        vsync: Option<TickerProviderRef>,
1259        snap_configuration: Option<FloatingHeaderSnapConfiguration>,
1260        stretch_configuration: Option<OverScrollHeaderStretchConfiguration>,
1261        show_on_screen_configuration: Option<PersistentHeaderShowOnScreenConfiguration>,
1262    ) -> RenderHandle<RenderSliverFloatingPersistentHeaderForWidgets> {
1263        RenderHandle::new_sliver(
1264            app,
1265            RenderSliverFloatingPersistentHeaderForWidgets {
1266                render_object: RenderObjectData::new(),
1267                render_sliver: RenderSliverData::new(),
1268                child: RenderObjectWithChildData::new(),
1269                header: RenderSliverPersistentHeaderData::new(stretch_configuration),
1270                floating: RenderSliverFloatingPersistentHeaderData::new(
1271                    vsync,
1272                    snap_configuration,
1273                    show_on_screen_configuration,
1274                ),
1275                for_widgets: RenderSliverPersistentHeaderForWidgetsData::new(),
1276            },
1277        )
1278    }
1279}
1280
1281header_for_widgets_leaf!(RenderSliverFloatingPersistentHeaderForWidgets);
1282
1283impl RenderSliverFloatingPersistentHeader for RenderSliverFloatingPersistentHeaderForWidgets {
1284    fn floating_data(
1285        self: RenderHandle<Self>,
1286        app: &App,
1287    ) -> &RenderSliverFloatingPersistentHeaderData {
1288        &self.get(app).floating
1289    }
1290
1291    fn floating_data_mut(
1292        self: RenderHandle<Self>,
1293        app: &mut App,
1294    ) -> &mut RenderSliverFloatingPersistentHeaderData {
1295        &mut self.get_mut(app).floating
1296    }
1297}
1298
1299header_protocol!(
1300    RenderSliverFloatingPersistentHeaderForWidgets,
1301    RenderSliverFloatingPersistentHeader::debug_fill_properties,
1302    RenderSliverFloatingPersistentHeader::perform_layout,
1303    RenderSliverFloatingPersistentHeader::child_main_axis_position,
1304    fn did_detach(self: RenderHandle<Self>, app: &mut App) {
1305        RenderSliverFloatingPersistentHeader::did_detach(self, app);
1306        if let Some(child) = self.child(app) {
1307            child.as_object().detach(app);
1308        }
1309    },
1310    fn show_on_screen(
1311        self: RenderHandle<Self>,
1312        app: &mut App,
1313        descendant: Option<AnyRenderObject>,
1314        rect: Option<Rect>,
1315        duration: Duration,
1316        curve: Rc<dyn Curve>,
1317    ) {
1318        RenderSliverFloatingPersistentHeader::show_on_screen(
1319            self, app, descendant, rect, duration, curve,
1320        );
1321    },
1322    fn interface(self: RenderHandle<Self>, id: TypeId) -> Option<Box<dyn Any>> {
1323        (id == TypeId::of::<AnyRenderSliverFloatingPersistentHeader>())
1324            .then(|| Box::new(self.as_floating_persistent_header()) as Box<dyn Any>)
1325    }
1326);
1327
1328/// Flutter's `_RenderSliverFloatingPinnedPersistentHeaderForWidgets`.
1329pub struct RenderSliverFloatingPinnedPersistentHeaderForWidgets {
1330    render_object: RenderObjectData,
1331    render_sliver: RenderSliverData,
1332    child: RenderObjectWithChildData<AnyRenderBox>,
1333    header: RenderSliverPersistentHeaderData,
1334    floating: RenderSliverFloatingPersistentHeaderData,
1335    for_widgets: RenderSliverPersistentHeaderForWidgetsData,
1336}
1337
1338impl RenderSliverFloatingPinnedPersistentHeaderForWidgets {
1339    /// Creates a floating pinned persistent header whose extents come from a delegate.
1340    pub fn new(
1341        app: &mut App,
1342        vsync: Option<TickerProviderRef>,
1343        snap_configuration: Option<FloatingHeaderSnapConfiguration>,
1344        stretch_configuration: Option<OverScrollHeaderStretchConfiguration>,
1345        show_on_screen_configuration: Option<PersistentHeaderShowOnScreenConfiguration>,
1346    ) -> RenderHandle<RenderSliverFloatingPinnedPersistentHeaderForWidgets> {
1347        RenderHandle::new_sliver(
1348            app,
1349            RenderSliverFloatingPinnedPersistentHeaderForWidgets {
1350                render_object: RenderObjectData::new(),
1351                render_sliver: RenderSliverData::new(),
1352                child: RenderObjectWithChildData::new(),
1353                header: RenderSliverPersistentHeaderData::new(stretch_configuration),
1354                floating: RenderSliverFloatingPersistentHeaderData::new(
1355                    vsync,
1356                    snap_configuration,
1357                    show_on_screen_configuration,
1358                ),
1359                for_widgets: RenderSliverPersistentHeaderForWidgetsData::new(),
1360            },
1361        )
1362    }
1363}
1364
1365header_for_widgets_leaf!(RenderSliverFloatingPinnedPersistentHeaderForWidgets);
1366
1367impl RenderSliverFloatingPersistentHeader for RenderSliverFloatingPinnedPersistentHeaderForWidgets {
1368    fn floating_data(
1369        self: RenderHandle<Self>,
1370        app: &App,
1371    ) -> &RenderSliverFloatingPersistentHeaderData {
1372        &self.get(app).floating
1373    }
1374
1375    fn floating_data_mut(
1376        self: RenderHandle<Self>,
1377        app: &mut App,
1378    ) -> &mut RenderSliverFloatingPersistentHeaderData {
1379        &mut self.get_mut(app).floating
1380    }
1381
1382    fn update_geometry(self: RenderHandle<Self>, app: &mut App) -> f64 {
1383        RenderSliverFloatingPinnedPersistentHeader::update_geometry(self, app)
1384    }
1385}
1386
1387impl RenderSliverFloatingPinnedPersistentHeader
1388    for RenderSliverFloatingPinnedPersistentHeaderForWidgets
1389{
1390}
1391
1392header_protocol!(
1393    RenderSliverFloatingPinnedPersistentHeaderForWidgets,
1394    RenderSliverFloatingPersistentHeader::debug_fill_properties,
1395    RenderSliverFloatingPersistentHeader::perform_layout,
1396    RenderSliverFloatingPersistentHeader::child_main_axis_position,
1397    fn did_detach(self: RenderHandle<Self>, app: &mut App) {
1398        RenderSliverFloatingPersistentHeader::did_detach(self, app);
1399        if let Some(child) = self.child(app) {
1400            child.as_object().detach(app);
1401        }
1402    },
1403    fn show_on_screen(
1404        self: RenderHandle<Self>,
1405        app: &mut App,
1406        descendant: Option<AnyRenderObject>,
1407        rect: Option<Rect>,
1408        duration: Duration,
1409        curve: Rc<dyn Curve>,
1410    ) {
1411        RenderSliverFloatingPersistentHeader::show_on_screen(
1412            self, app, descendant, rect, duration, curve,
1413        );
1414    },
1415    fn interface(self: RenderHandle<Self>, id: TypeId) -> Option<Box<dyn Any>> {
1416        (id == TypeId::of::<AnyRenderSliverFloatingPersistentHeader>())
1417            .then(|| Box::new(self.as_floating_persistent_header()) as Box<dyn Any>)
1418    }
1419);
1420
1421#[cfg(test)]
1422mod tests {
1423    use std::cell::RefCell;
1424    use waft_foundation::AppCell;
1425    use waft_foundation::Ref;
1426
1427    use waft_embedder::TextDirection;
1428    use waft_rendering::{
1429        ContainerRenderObjectMixin, FixedViewportOffset, RenderBox, RenderViewport,
1430        ScrollCacheExtent, ViewportOffset,
1431    };
1432
1433    use super::*;
1434    use crate::framework::IntoWidget;
1435    use crate::test_harness::Harness;
1436    use crate::widgets::basic::{Directionality, SizedBox, SliverToBoxAdapter};
1437    use crate::widgets::viewport::Viewport;
1438
1439    /// The shrink offsets the delegate was asked to build for, in order.
1440    type ShrinkOffsets = Rc<RefCell<Vec<f64>>>;
1441
1442    #[derive(Debug)]
1443    struct TestHeaderDelegate {
1444        min_extent: f64,
1445        max_extent: f64,
1446        shrink_offsets: ShrinkOffsets,
1447    }
1448
1449    impl SliverPersistentHeaderDelegate for TestHeaderDelegate {
1450        fn build(
1451            &self,
1452            _app: &mut App,
1453            _context: BuildContext,
1454            shrink_offset: f64,
1455            _overlaps_content: bool,
1456        ) -> WidgetRef {
1457            self.shrink_offsets.borrow_mut().push(shrink_offset);
1458            SizedBox::expand().into_widget()
1459        }
1460
1461        fn min_extent(&self) -> f64 {
1462            self.min_extent
1463        }
1464
1465        fn max_extent(&self) -> f64 {
1466            self.max_extent
1467        }
1468
1469        fn should_rebuild(&self, _old_delegate: &dyn SliverPersistentHeaderDelegate) -> bool {
1470            true
1471        }
1472
1473        fn as_any(&self) -> &dyn Any {
1474            self
1475        }
1476    }
1477
1478    fn header_tree(
1479        offset: &Ref<FixedViewportOffset>,
1480        shrink_offsets: &ShrinkOffsets,
1481        pinned: bool,
1482        floating: bool,
1483    ) -> WidgetRef {
1484        let delegate = Rc::new(TestHeaderDelegate {
1485            min_extent: 40.0,
1486            max_extent: 120.0,
1487            shrink_offsets: Rc::clone(shrink_offsets),
1488        }) as SliverPersistentHeaderDelegateRef;
1489        Directionality::new(
1490            TextDirection::Ltr,
1491            Viewport::new(offset.erase())
1492                .scroll_cache_extent(ScrollCacheExtent::Pixels(0.0))
1493                .slivers(vec![
1494                    SliverPersistentHeader::new(delegate)
1495                        .pinned(pinned)
1496                        .floating(floating)
1497                        .into_widget(),
1498                    SliverToBoxAdapter::new()
1499                        .child(SizedBox::new().height(1000.0))
1500                        .into_widget(),
1501                ]),
1502        )
1503        .into_widget()
1504    }
1505
1506    fn viewport_of(harness: &Harness, app: &App) -> RenderHandle<RenderViewport> {
1507        harness
1508            .render_root(app)
1509            .child(app)
1510            .expect("a child")
1511            .as_object()
1512            .downcast::<RenderViewport>(app)
1513            .expect("a RenderViewport")
1514    }
1515
1516    fn scroll_to(
1517        harness: &Harness,
1518        app: &mut App,
1519        offset: Handle<FixedViewportOffset>,
1520        pixels: f64,
1521    ) {
1522        let current = offset.pixels(app);
1523        offset.correct_by(app, pixels - current);
1524        viewport_of(harness, app).mark_needs_layout(app);
1525        harness.pump(app);
1526    }
1527
1528    /// A pinned header stays at the leading edge, shrinking to its minimum extent as it is
1529    /// scrolled, and rebuilds its child at each shrink offset.
1530    #[test]
1531    fn a_pinned_header_shrinks_to_its_minimum_extent_and_stays() {
1532        let cell = AppCell::new();
1533        let mut app = cell.borrow_mut();
1534        let offset = FixedViewportOffset::zero(&mut app);
1535        let shrink_offsets: ShrinkOffsets = Rc::default();
1536        let harness = Harness::mount(&mut app, header_tree(&offset, &shrink_offsets, true, false));
1537        harness.pump(&mut app);
1538
1539        let header = viewport_of(&harness, &app)
1540            .first_child(&app)
1541            .expect("the header");
1542        assert_eq!(header.geometry(&app).paint_extent, 120.0);
1543        assert_eq!(header.geometry(&app).layout_extent, 120.0);
1544        assert_eq!(header.geometry(&app).max_scroll_obstruction_extent, 40.0);
1545        assert_eq!(*shrink_offsets.borrow(), vec![0.0]);
1546
1547        scroll_to(&harness, &mut app, offset.handle(), 100.0);
1548
1549        // Shrunk to the minimum extent, still painting at the leading edge.
1550        assert_eq!(header.geometry(&app).paint_extent, 40.0);
1551        assert_eq!(header.geometry(&app).layout_extent, 20.0);
1552        assert_eq!(*shrink_offsets.borrow(), vec![0.0, 100.0]);
1553    }
1554
1555    /// A floating header scrolls off as it shrinks: its paint extent falls with the scroll
1556    /// offset and it reports no scroll obstruction.
1557    #[test]
1558    fn a_floating_header_scrolls_off_as_it_shrinks() {
1559        let cell = AppCell::new();
1560        let mut app = cell.borrow_mut();
1561        let offset = FixedViewportOffset::zero(&mut app);
1562        let shrink_offsets: ShrinkOffsets = Rc::default();
1563        let harness = Harness::mount(&mut app, header_tree(&offset, &shrink_offsets, false, true));
1564        harness.pump(&mut app);
1565
1566        let header = viewport_of(&harness, &app)
1567            .first_child(&app)
1568            .expect("the header");
1569        assert_eq!(header.geometry(&app).scroll_extent, 120.0);
1570        assert_eq!(header.geometry(&app).paint_extent, 120.0);
1571        assert_eq!(*shrink_offsets.borrow(), vec![0.0]);
1572
1573        scroll_to(&harness, &mut app, offset.handle(), 100.0);
1574
1575        assert_eq!(header.geometry(&app).paint_extent, 20.0);
1576        assert_eq!(header.geometry(&app).max_scroll_obstruction_extent, 0.0);
1577        assert_eq!(*shrink_offsets.borrow(), vec![0.0, 100.0]);
1578    }
1579}