ailloli_ui_widgets/layout/
scroll_view.rs

1//! Single-child clipped scrolling, virtualization hints, follow-end, and bars.
2
3use std::cell::Cell;
4
5use ailloli_ui_core::event::{Event, PointerEvent};
6use ailloli_ui_core::geometry::{Constraints, Rect, Size};
7use ailloli_ui_core::scroll::{
8    ScrollAxes, ScrollBehavior, ScrollMetrics, ScrollState, ScrollbarAxis, ScrollbarGeometry,
9    ScrollbarGeometrySpec,
10};
11use ailloli_ui_core::style::FlexItemStyle;
12use ailloli_ui_core::{Color, Offset};
13use ailloli_ui_runtime::component::reactive::with_untracked_reads;
14use ailloli_ui_runtime::component::{ComponentNode, Context, IntoView, Signal, View, Widget};
15use ailloli_ui_runtime::input::EventCtx;
16use ailloli_ui_runtime::layout::LayoutEngine;
17use ailloli_ui_runtime::layout::{
18    ChildLayout, LayoutChild, LayoutCtx, LayoutResult, VirtualViewport,
19};
20use ailloli_ui_runtime::scene::PaintCtx;
21use ailloli_ui_runtime::{DrawCmd, DrawRRect, Invalidation};
22
23use crate::scrollbar::{thumb_color_for_state, ScrollbarInteraction};
24use crate::transactional_layout::TransactionalLayoutPending;
25
26/// Visual style for [`ScrollView`] scrollbars.
27///
28/// All dimensions are logical pixels. The default is a six-pixel bar inset by
29/// three pixels with a minimum 24-pixel thumb. Custom values are not normalized
30/// globally; unusable track geometry simply suppresses that scrollbar.
31///
32/// # Examples
33///
34/// ```
35/// use ailloli_ui_widgets::layout::ScrollbarStyle;
36/// let style = ScrollbarStyle::default();
37/// assert_eq!(style.thickness, 6.0);
38/// assert_eq!(style.min_thumb_len, 24.0);
39/// ```
40#[derive(Debug, Clone, Copy, PartialEq)]
41pub struct ScrollbarStyle {
42    /// Scrollbar track fill.
43    pub track_color: Color,
44    /// Scrollbar thumb fill.
45    pub thumb_color: Color,
46    /// Track/thumb cross-axis thickness in logical pixels.
47    pub thickness: f32,
48    /// Minimum main-axis thumb length in logical pixels, capped to the track.
49    pub min_thumb_len: f32,
50    /// Distance from viewport edges in logical pixels.
51    pub inset: f32,
52    /// Track and thumb corner radius in logical pixels.
53    pub radius: f32,
54}
55
56/// Supplies the standard neutral scrollbar palette and geometry.
57impl Default for ScrollbarStyle {
58    fn default() -> Self {
59        Self {
60            track_color: Color::rgba(148, 163, 184, 0.16),
61            thumb_color: Color::rgba(148, 163, 184, 0.56),
62            thickness: 6.0,
63            min_thumb_len: 24.0,
64            inset: 3.0,
65            radius: 3.0,
66        }
67    }
68}
69
70/// Single-child viewport for content larger than its visible bounds.
71///
72/// The default scrolls vertically, begins at zero, shows scrollbars, maps one
73/// wheel line to 48 logical pixels, and does not follow the content end. The
74/// content is clipped and receives a virtual viewport hint containing the
75/// current offset. Visible bars support thumb drag and centered track clicks;
76/// wheel events bubble when the viewport is already at its requested limit.
77///
78/// # Examples
79///
80/// ```
81/// use ailloli_ui_widgets::{layout::ScrollView, text::Text};
82/// let scroll: ScrollView<()> = ScrollView::vertical().child(Text::new("content"));
83/// let _ = scroll;
84/// ```
85pub struct ScrollView<A = ()> {
86    /// Axes on which content may exceed the viewport and scroll.
87    axes: ScrollAxes,
88    /// Initial content offset in logical pixels.
89    initial_offset: Offset,
90    /// Wheel scaling and axis-filtering policy.
91    behavior: ScrollBehavior,
92    /// Whether content growth should remain pinned to its end edge.
93    follow_end: bool,
94    /// Whether overflow paints visual scrollbars.
95    scrollbars: bool,
96    /// Scrollbar colors and logical-pixel geometry.
97    scrollbar_style: ScrollbarStyle,
98    /// Optional sole content child.
99    child: Option<View<A>>,
100}
101
102/// Creates the same vertical viewport as [`ScrollView::new`].
103impl<A: 'static> Default for ScrollView<A> {
104    fn default() -> Self {
105        Self::new()
106    }
107}
108
109impl<A: 'static> ScrollView<A> {
110    /// Creates a vertical viewport.
111    ///
112    /// # Examples
113    ///
114    /// ```
115    /// use ailloli_ui_widgets::layout::ScrollView;
116    /// let scroll: ScrollView<()> = ScrollView::new();
117    /// let _ = scroll;
118    /// ```
119    pub fn new() -> Self {
120        Self::vertical()
121    }
122
123    /// Creates a vertical-only viewport.
124    ///
125    /// Horizontal initial/wheel offsets are filtered to zero.
126    ///
127    /// # Examples
128    ///
129    /// ```
130    /// use ailloli_ui_widgets::layout::ScrollView;
131    /// let scroll: ScrollView<()> = ScrollView::vertical();
132    /// let _ = scroll;
133    /// ```
134    pub fn vertical() -> Self {
135        Self {
136            axes: ScrollAxes::VERTICAL,
137            initial_offset: Offset::default(),
138            behavior: ScrollBehavior::new(ScrollAxes::VERTICAL),
139            follow_end: false,
140            scrollbars: true,
141            scrollbar_style: ScrollbarStyle::default(),
142            child: None,
143        }
144    }
145
146    /// Creates a horizontal-only viewport.
147    ///
148    /// Vertical initial/wheel offsets are filtered to zero.
149    ///
150    /// # Examples
151    ///
152    /// ```
153    /// use ailloli_ui_widgets::layout::ScrollView;
154    /// let scroll: ScrollView<()> = ScrollView::horizontal();
155    /// let _ = scroll;
156    /// ```
157    pub fn horizontal() -> Self {
158        Self {
159            axes: ScrollAxes::HORIZONTAL,
160            initial_offset: Offset::default(),
161            behavior: ScrollBehavior::new(ScrollAxes::HORIZONTAL),
162            follow_end: false,
163            scrollbars: true,
164            scrollbar_style: ScrollbarStyle::default(),
165            child: None,
166        }
167    }
168
169    /// Creates a viewport scrollable on both axes.
170    ///
171    /// # Examples
172    ///
173    /// ```
174    /// use ailloli_ui_widgets::layout::ScrollView;
175    /// let scroll: ScrollView<()> = ScrollView::both();
176    /// let _ = scroll;
177    /// ```
178    pub fn both() -> Self {
179        Self {
180            axes: ScrollAxes::BOTH,
181            initial_offset: Offset::default(),
182            behavior: ScrollBehavior::new(ScrollAxes::BOTH),
183            follow_end: false,
184            scrollbars: true,
185            scrollbar_style: ScrollbarStyle::default(),
186            child: None,
187        }
188    }
189
190    /// Sets the initial non-persisted logical-pixel content offset.
191    ///
192    /// Disabled axes are filtered to zero. The first bounded layout clamps the
193    /// retained state to content limits.
194    ///
195    /// # Examples
196    ///
197    /// ```
198    /// use ailloli_ui_core::Offset;
199    /// use ailloli_ui_widgets::layout::ScrollView;
200    /// let scroll: ScrollView<()> = ScrollView::both().initial_offset(Offset::new(10.0, 20.0));
201    /// let _ = scroll;
202    /// ```
203    pub fn initial_offset(mut self, offset: Offset) -> Self {
204        self.initial_offset = self.axes.filter_offset(offset);
205        self
206    }
207
208    /// Sets a non-negative initial vertical offset in logical pixels.
209    ///
210    /// Negative and `NaN` inputs become zero via floating-point `max`.
211    ///
212    /// # Examples
213    ///
214    /// ```
215    /// use ailloli_ui_widgets::layout::ScrollView;
216    /// let scroll: ScrollView<()> = ScrollView::vertical().initial_scroll_y(120.0);
217    /// let _ = scroll;
218    /// ```
219    pub fn initial_scroll_y(self, scroll_y: f32) -> Self {
220        self.initial_offset(Offset::new(0.0, scroll_y.max(0.0)))
221    }
222
223    /// Legacy builder kept for old tests/apps where this value represented child paint offset.
224    ///
225    /// The legacy value is negated: `-40.0` becomes a retained y offset of
226    /// `40.0`, while positive and `NaN` values become zero. Prefer
227    /// [`Self::initial_scroll_y`] for new code.
228    ///
229    /// # Examples
230    ///
231    /// ```
232    /// use ailloli_ui_widgets::layout::ScrollView;
233    /// let legacy: ScrollView<()> = ScrollView::vertical().scroll_y(-40.0);
234    /// let _ = legacy;
235    /// ```
236    pub fn scroll_y(mut self, scroll_y: f32) -> Self {
237        self.initial_offset.y = (-scroll_y).max(0.0);
238        self
239    }
240
241    /// Sets logical pixels represented by one wheel line.
242    ///
243    /// Values are clamped to at least one; `NaN` and negative infinity become
244    /// one, while positive infinity remains infinite.
245    ///
246    /// # Examples
247    ///
248    /// ```
249    /// use ailloli_ui_widgets::layout::ScrollView;
250    /// let scroll: ScrollView<()> = ScrollView::vertical().wheel_line_px(24.0);
251    /// let _ = scroll;
252    /// ```
253    pub fn wheel_line_px(mut self, line_px: f32) -> Self {
254        self.behavior = self.behavior.with_line_px(line_px);
255        self
256    }
257
258    /// Enables or disables sticky scrolling at the enabled-axis end.
259    ///
260    /// When enabled, content growth follows the end until a manual wheel scroll
261    /// moves farther than one logical pixel away. Reaching the end reactivates it.
262    ///
263    /// # Examples
264    ///
265    /// ```
266    /// use ailloli_ui_widgets::layout::ScrollView;
267    /// let log: ScrollView<()> = ScrollView::vertical().follow_end(true);
268    /// let _ = log;
269    /// ```
270    pub fn follow_end(mut self, enabled: bool) -> Self {
271        self.follow_end = enabled;
272        self
273    }
274
275    /// Shows or hides interactive overflow scrollbars.
276    ///
277    /// Hidden bars expose no pointer hit regions; wheel scrolling and clipping
278    /// remain active.
279    ///
280    /// # Examples
281    ///
282    /// ```
283    /// use ailloli_ui_widgets::layout::ScrollView;
284    /// let scroll: ScrollView<()> = ScrollView::vertical().scrollbars(false);
285    /// let _ = scroll;
286    /// ```
287    pub fn scrollbars(mut self, enabled: bool) -> Self {
288        self.scrollbars = enabled;
289        self
290    }
291
292    /// Replaces scrollbar colors and geometry.
293    ///
294    /// # Examples
295    ///
296    /// ```
297    /// use ailloli_ui_widgets::layout::{ScrollbarStyle, ScrollView};
298    /// let style = ScrollbarStyle { thickness: 8.0, ..Default::default() };
299    /// let scroll: ScrollView<()> = ScrollView::vertical().scrollbar_style(style);
300    /// let _ = scroll;
301    /// ```
302    pub fn scrollbar_style(mut self, style: ScrollbarStyle) -> Self {
303        self.scrollbar_style = style;
304        self
305    }
306
307    /// Sets the single scroll content child, replacing any previous child.
308    ///
309    /// # Examples
310    ///
311    /// ```
312    /// use ailloli_ui_widgets::{layout::ScrollView, text::Text};
313    /// let scroll: ScrollView<()> = ScrollView::vertical().child(Text::new("content"));
314    /// let _ = scroll;
315    /// ```
316    pub fn child(mut self, child: impl IntoView<A>) -> Self {
317        self.child = Some(child.into_view());
318        self
319    }
320}
321
322/// Retained builder snapshot used to allocate scroll/follow signals.
323struct ScrollViewComponent<A> {
324    /// Axes on which content may scroll.
325    axes: ScrollAxes,
326    /// Initial retained content offset in logical pixels.
327    initial_offset: Offset,
328    /// Wheel scaling and axis-filtering policy.
329    behavior: ScrollBehavior,
330    /// Whether content growth should remain pinned to its end edge.
331    follow_end: bool,
332    /// Whether overflow paints visual scrollbars.
333    scrollbars: bool,
334    /// Scrollbar colors and logical-pixel geometry.
335    scrollbar_style: ScrollbarStyle,
336    /// Optional sole content child.
337    child: Option<View<A>>,
338}
339
340/// Builds the viewport widget and preserves its optional content child.
341impl<A: 'static> ComponentNode<A> for ScrollViewComponent<A> {
342    fn build(&self, context: &mut Context<A>) -> View<A> {
343        let state = context.signal_with_invalidation(
344            ScrollState::with_offset(self.initial_offset),
345            Invalidation::Paint,
346        );
347        let follow_end_active =
348            context.signal_with_invalidation(self.follow_end, Invalidation::Paint);
349        let scrollbar_interaction =
350            context.signal_with_invalidation(ScrollbarInteraction::default(), Invalidation::Paint);
351        let mut children = Vec::new();
352        if let Some(child) = self.child.clone() {
353            children.push(child);
354        }
355
356        View::node(
357            ScrollViewWidget {
358                axes: self.axes,
359                state,
360                behavior: self.behavior,
361                follow_end: self.follow_end,
362                follow_end_active,
363                scrollbars: self.scrollbars,
364                scrollbar_style: self.scrollbar_style,
365                scrollbar_interaction,
366                pending_layout: Cell::new(None),
367            },
368            children,
369        )
370    }
371}
372
373/// Stateful retained viewport implementation.
374struct ScrollViewWidget {
375    /// Axes on which content may scroll.
376    axes: ScrollAxes,
377    /// Retained content offset in logical pixels.
378    state: Signal<ScrollState>,
379    /// Wheel scaling and axis-filtering policy.
380    behavior: ScrollBehavior,
381    /// Whether end-following is enabled for this viewport.
382    follow_end: bool,
383    /// Whether the viewport currently remains attached to the content end.
384    follow_end_active: Signal<bool>,
385    /// Whether overflow paints visual scrollbars.
386    scrollbars: bool,
387    /// Scrollbar colors and logical-pixel geometry.
388    scrollbar_style: ScrollbarStyle,
389    /// Retained hover and captured scrollbar gesture.
390    scrollbar_interaction: Signal<ScrollbarInteraction>,
391    /// Geometry-derived state owned by one exact authoritative attempt.
392    pending_layout: Cell<Option<TransactionalLayoutPending<PendingScrollViewLayout>>>,
393}
394
395/// State published only by the successful attempt that computed it.
396#[derive(Clone, Copy)]
397struct PendingScrollViewLayout {
398    /// Final authoritative clamp.
399    state: Option<ScrollState>,
400    /// Final authoritative follow-end transition.
401    follow_end_active: Option<bool>,
402    /// Geometry-dependent gesture cleanup.
403    scrollbar_interaction: Option<ScrollbarInteraction>,
404}
405
406/// Implements bounded/unbounded layout passes, clipping, bars, and wheel input.
407impl<A: 'static> Widget<A> for ScrollViewWidget {
408    fn debug_name(&self) -> &'static str {
409        "ScrollView"
410    }
411
412    fn layout(
413        &self,
414        engine: &mut LayoutEngine<'_, A>,
415        ctx: &mut LayoutCtx<'_>,
416        children: &mut [LayoutChild],
417        constraints: Constraints,
418    ) -> LayoutResult {
419        let mut child_layouts = Vec::new();
420        // `state` is owned by this exact retained widget. Its pre-clamp value is
421        // administrative because only the final authoritative pass may publish
422        // the geometry-dependent clamp in `layout_committed`.
423        let mut state = with_untracked_reads(|| self.state.read());
424        let mut next_follow_end_active = None;
425        let mut persist_state = false;
426        let constraints_max = constraints.max_size();
427        let mut size = finite_or_zero_size(constraints_max);
428
429        if let Some(child) = children.first_mut() {
430            let child_constraints = self.child_constraints(constraints_max);
431            let viewport_hint_size = finite_or_zero_size(constraints_max);
432            let previous_viewport = ctx.replace_virtual_viewport(Some(VirtualViewport::new(
433                Rect::new(
434                    state.offset.x,
435                    state.offset.y,
436                    viewport_hint_size.w,
437                    viewport_hint_size.h,
438                ),
439                0.0,
440            )));
441            let mut r = child.layout(engine, ctx, child_constraints);
442            ctx.replace_virtual_viewport(previous_viewport);
443            size = viewport_size(constraints_max, r.size);
444            if self.has_bounded_scroll_viewport(constraints_max) {
445                let metrics = ScrollMetrics::new(size, r.size);
446                let (next_state, next_follow) = self.sync_scroll_state_for_layout(state, metrics);
447                if !same_offset(state.offset, next_state.offset) {
448                    let previous_viewport =
449                        ctx.replace_virtual_viewport(Some(VirtualViewport::new(
450                            Rect::new(next_state.offset.x, next_state.offset.y, size.w, size.h),
451                            0.0,
452                        )));
453                    r = child.layout(engine, ctx, child_constraints);
454                    ctx.replace_virtual_viewport(previous_viewport);
455                }
456                state = next_state;
457                next_follow_end_active = next_follow;
458                persist_state = true;
459            } else {
460                // Flex containers probe growing children with an unbounded
461                // main axis before assigning their final slot. That probe is
462                // not a real viewport: clamping here would erase a retained
463                // deep scroll offset and then expose every virtualized row to
464                // layout. Keep the persistent state untouched and render the
465                // intrinsic probe from the origin; the following bounded pass
466                // applies and clamps the real offset.
467                state = ScrollState::new();
468            }
469            child_layouts.push(ChildLayout {
470                offset: Offset::new(-state.offset.x, -state.offset.y),
471                size: r.size,
472                paint_bounds: Rect::new(0.0, 0.0, r.size.w, r.size.h),
473                visual_bounds: r.visual_bounds,
474            });
475        }
476        let viewport = Rect::new(0.0, 0.0, size.w, size.h);
477
478        let scrollbar_geometries = if self.scrollbars {
479            let metrics = child_layouts
480                .first()
481                .map(|child| ScrollMetrics::new(size, child.size));
482            metrics
483                .map(|metrics| {
484                    scrollbars_for(viewport, metrics, state, self.axes, self.scrollbar_style)
485                })
486                .unwrap_or_default()
487        } else {
488            Vec::new()
489        };
490        // Reconciliation can clear a gesture against authoritative geometry.
491        // Its context-owned Paint invalidator is the static ownership edge;
492        // observing the pre-reconcile value would supersede this layout when
493        // the cleanup writes the new value below.
494        let mut interaction = with_untracked_reads(|| self.scrollbar_interaction.read());
495        let interaction_changed = interaction.reconcile(ctx.layout_pass(), &scrollbar_geometries);
496        if ctx.layout_pass().is_committed() {
497            let retained_state = with_untracked_reads(|| self.state.read());
498            self.pending_layout.set(TransactionalLayoutPending::new(
499                ctx,
500                PendingScrollViewLayout {
501                    state: (persist_state && !same_offset(retained_state.offset, state.offset))
502                        .then_some(state),
503                    follow_end_active: next_follow_end_active,
504                    scrollbar_interaction: interaction_changed.then_some(interaction),
505                },
506            ));
507        }
508
509        LayoutResult {
510            size,
511            children: child_layouts,
512            paint_bounds: viewport,
513            visual_bounds: viewport,
514            overlay_hit_bounds: scrollbar_geometries
515                .iter()
516                .map(|geometry| geometry.hit_track)
517                .collect(),
518            clip: Some(ailloli_ui_core::ClipShape::Rect(viewport)),
519            is_window_root_clip: false,
520            artifact: None,
521        }
522    }
523
524    fn layout_committed(&self, ctx: &mut LayoutCtx<'_>, _bounds: Rect, _layout: &LayoutResult) {
525        let Some(pending) = self
526            .pending_layout
527            .take()
528            .and_then(|pending| pending.into_committed(ctx))
529        else {
530            return;
531        };
532        if let Some(state) = pending.state {
533            self.state.set(state);
534        }
535        if let Some(active) = pending.follow_end_active {
536            self.follow_end_active.set(active);
537        }
538        if let Some(interaction) = pending.scrollbar_interaction {
539            self.scrollbar_interaction.set(interaction);
540        }
541    }
542
543    fn paint(&self, _ctx: &mut PaintCtx<'_>, _bounds: Rect, _layout: &LayoutResult) {}
544
545    fn paint_overlay(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, layout: &LayoutResult) {
546        if !self.scrollbars {
547            return;
548        }
549        let Some(child) = layout.children.first() else {
550            return;
551        };
552
553        let metrics = ScrollMetrics::new(layout.size, child.size);
554        let state = self.state.read();
555        let geometries = scrollbars_for(bounds, metrics, state, self.axes, self.scrollbar_style);
556        paint_scrollbars(
557            ctx,
558            &geometries,
559            self.scrollbar_style,
560            self.scrollbar_interaction.read(),
561        );
562    }
563
564    fn event(&self, ctx: &mut EventCtx<A>, event: &Event, bounds: Rect, layout: &LayoutResult) {
565        let Some(child) = layout.children.first() else {
566            return;
567        };
568
569        let metrics = ScrollMetrics::new(layout.size, child.size);
570        if self.scrollbars {
571            let geometries = scrollbars_for(
572                bounds,
573                metrics,
574                self.state.read(),
575                self.axes,
576                self.scrollbar_style,
577            );
578            let mut interaction = self.scrollbar_interaction.read();
579            let response = interaction.handle_event(ctx, event, &geometries);
580            if response.state_changed {
581                self.scrollbar_interaction.set(interaction);
582            }
583            let mut scrolled = false;
584            if let Some((axis, target)) = response.scroll_to {
585                let state = self.state.read();
586                let target = match axis {
587                    ScrollbarAxis::Horizontal => Offset::new(target, state.offset.y),
588                    ScrollbarAxis::Vertical => Offset::new(state.offset.x, target),
589                };
590                let outcome = state.scroll_to(target, metrics, self.axes);
591                if outcome.changed {
592                    self.state.set(outcome.state());
593                    self.sync_follow_end_after_manual_scroll(outcome.after, outcome.max_offset);
594                    scrolled = true;
595                }
596            }
597            if response.repaint || scrolled {
598                if scrolled {
599                    ctx.request_layout();
600                } else {
601                    ctx.request_repaint();
602                }
603            }
604            if response.consumed {
605                ctx.stop_propagation();
606                return;
607            }
608        }
609
610        if let Event::Pointer(PointerEvent::Wheel {
611            delta, modifiers, ..
612        }) = event
613        {
614            let state = self.state.read();
615            let outcome = state.scroll_by(
616                self.behavior.wheel_delta_with_modifiers(*delta, *modifiers),
617                metrics,
618                self.axes,
619            );
620            if outcome.changed {
621                self.state.set(outcome.state());
622                self.sync_follow_end_after_manual_scroll(outcome.after, outcome.max_offset);
623                ctx.request_layout();
624                ctx.stop_propagation();
625            }
626        }
627    }
628}
629
630/// Converts the builder into a component with default flex-shrink weight one.
631impl<A: 'static> IntoView<A> for ScrollView<A> {
632    fn into_view(self) -> View<A> {
633        View::component(ScrollViewComponent {
634            axes: self.axes,
635            initial_offset: self.initial_offset,
636            behavior: self.behavior,
637            follow_end: self.follow_end,
638            scrollbars: self.scrollbars,
639            scrollbar_style: self.scrollbar_style,
640            child: self.child,
641        })
642        // A scroll container is a viewport, not an intrinsically-sized list.
643        // Let a flex parent shrink its probe result into the assigned slot;
644        // callers can still opt out explicitly with `.flex_shrink(0.0)`.
645        .with_flex_item(FlexItemStyle::new().flex_shrink(1.0))
646    }
647}
648
649/// Scroll-state synchronization, follow-end policy, and child constraints.
650impl ScrollViewWidget {
651    /// Returns whether every enabled scroll axis has a finite viewport extent.
652    fn has_bounded_scroll_viewport(&self, viewport: Size) -> bool {
653        (!self.axes.horizontal || viewport.w.is_finite())
654            && (!self.axes.vertical || viewport.h.is_finite())
655    }
656
657    /// Clamps offset and applies the retained follow-end policy during layout.
658    fn sync_scroll_state_for_layout(
659        &self,
660        state: ScrollState,
661        metrics: ScrollMetrics,
662    ) -> (ScrollState, Option<bool>) {
663        if !self.follow_end {
664            let clamped = state.clamp_to(metrics, self.axes);
665            return (clamped.state(), None);
666        }
667
668        let max_offset = self.axes.filter_offset(metrics.max_offset());
669        let follow_active = with_untracked_reads(|| self.follow_end_active.read());
670        let mut next_follow_active = follow_active;
671        let target = if follow_active {
672            ScrollState::with_offset(max_offset)
673        } else {
674            let clamped = state.clamp_to(metrics, self.axes).state();
675            if offset_at_end(clamped.offset, max_offset, self.axes) {
676                next_follow_active = true;
677            }
678            clamped
679        };
680        (
681            target,
682            (next_follow_active != follow_active).then_some(next_follow_active),
683        )
684    }
685
686    /// Updates end-following after a wheel or other manual offset change.
687    fn sync_follow_end_after_manual_scroll(&self, offset: Offset, max_offset: Offset) {
688        if !self.follow_end {
689            return;
690        }
691        self.set_follow_end_active(offset_at_end(offset, max_offset, self.axes));
692    }
693
694    /// Writes the follow-end flag only when its value changes.
695    fn set_follow_end_active(&self, active: bool) {
696        if with_untracked_reads(|| self.follow_end_active.read()) != active {
697            self.follow_end_active.set(active);
698        }
699    }
700
701    /// Makes enabled axes unbounded while preserving the viewport on other axes.
702    fn child_constraints(&self, viewport: Size) -> Constraints {
703        Constraints::loose(
704            if self.axes.horizontal {
705                f32::INFINITY
706            } else {
707                viewport.w
708            },
709            if self.axes.vertical {
710                f32::INFINITY
711            } else {
712                viewport.h
713            },
714        )
715    }
716}
717
718/// Maximum logical-pixel distance considered to be at the scroll end.
719const FOLLOW_END_EPSILON: f32 = 1.0;
720
721/// Tests enabled axes against their maximum offsets within the end epsilon.
722fn offset_at_end(offset: Offset, max_offset: Offset, axes: ScrollAxes) -> bool {
723    (!axes.horizontal || offset.x >= max_offset.x - FOLLOW_END_EPSILON)
724        && (!axes.vertical || offset.y >= max_offset.y - FOLLOW_END_EPSILON)
725}
726
727/// Compares offsets with a strict 0.001 logical-pixel per-axis tolerance.
728fn same_offset(a: Offset, b: Offset) -> bool {
729    (a.x - b.x).abs() < 0.001 && (a.y - b.y).abs() < 0.001
730}
731
732/// Replaces each non-finite extent with zero independently.
733fn finite_or_zero_size(size: Size) -> Size {
734    Size::new(
735        if size.w.is_finite() { size.w } else { 0.0 },
736        if size.h.is_finite() { size.h } else { 0.0 },
737    )
738}
739
740/// Uses finite maximum constraints or falls back to content extent per axis.
741fn viewport_size(constraints_max: Size, content: Size) -> Size {
742    Size::new(
743        finite_or_content(constraints_max.w, content.w),
744        finite_or_content(constraints_max.h, content.h),
745    )
746}
747
748/// Selects a finite maximum or the corresponding content extent.
749fn finite_or_content(max: f32, content: f32) -> f32 {
750    if max.is_finite() {
751        max
752    } else {
753        content
754    }
755}
756
757/// Paints bars only for enabled axes with more than 0.5 pixels of overflow.
758fn paint_scrollbars(
759    ctx: &mut PaintCtx<'_>,
760    geometries: &[ScrollbarGeometry],
761    style: ScrollbarStyle,
762    interaction: ScrollbarInteraction,
763) {
764    for geometry in geometries.iter().copied() {
765        push_scrollbar(ctx, geometry, style, interaction);
766    }
767}
768
769/// Appends track then thumb rounded-rectangle commands.
770fn push_scrollbar(
771    ctx: &mut PaintCtx<'_>,
772    geometry: ScrollbarGeometry,
773    style: ScrollbarStyle,
774    interaction: ScrollbarInteraction,
775) {
776    ctx.push(DrawCmd::RRect(DrawRRect {
777        rect: geometry.track,
778        radius: style.radius,
779        color: style.track_color,
780    }));
781    ctx.push(DrawCmd::RRect(DrawRRect {
782        rect: geometry.thumb,
783        radius: style.radius,
784        color: thumb_color_for_state(
785            style.thumb_color,
786            interaction.visual_state(geometry.axis, ctx.is_hovered()),
787        ),
788    }));
789}
790
791/// Resolves every enabled overflowing axis with shared Core geometry.
792fn scrollbars_for(
793    bounds: Rect,
794    metrics: ScrollMetrics,
795    state: ScrollState,
796    axes: ScrollAxes,
797    style: ScrollbarStyle,
798) -> Vec<ScrollbarGeometry> {
799    let max = metrics.max_offset();
800    let show_horizontal = axes.horizontal && max.x > 0.5;
801    let show_vertical = axes.vertical && max.y > 0.5;
802    let reserve = style.thickness + style.inset;
803    let mut geometries = Vec::with_capacity(2);
804    if show_vertical {
805        let spec = ScrollbarGeometrySpec::new(ScrollbarAxis::Vertical, bounds, metrics, state)
806            .with_paint_metrics(style.thickness, style.min_thumb_len, style.inset)
807            .with_end_reserve(if show_horizontal { reserve } else { 0.0 });
808        if let Some(geometry) = spec.resolve() {
809            geometries.push(geometry);
810        }
811    }
812    if show_horizontal {
813        let spec = ScrollbarGeometrySpec::new(ScrollbarAxis::Horizontal, bounds, metrics, state)
814            .with_paint_metrics(style.thickness, style.min_thumb_len, style.inset)
815            .with_end_reserve(if show_vertical { reserve } else { 0.0 });
816        if let Some(geometry) = spec.resolve() {
817            geometries.push(geometry);
818        }
819    }
820    geometries
821}