Skip to main content

xrack_layout/
scroll_bar.rs

1use crate::{LayoutContext, LayoutNode, Point, Rect, ScrollLayout, TextMeasurer};
2use std::collections::BTreeMap;
3use xrack_runtime::{LayoutDirection, Node, Orientation, ScrollBarPolicy, ScrollBarRange, Value};
4
5/// An overlay scroll bar whose track and thumb use the viewport's logical pixels.
6#[derive(Clone, Copy, Debug, PartialEq)]
7pub struct ScrollBarGeometry {
8    pub orientation: Orientation,
9    pub track: Rect,
10    pub thumb: Rect,
11    pub scroll: ScrollLayout,
12    pub page: f32,
13    pub step: f32,
14    reversed: bool,
15}
16
17#[derive(Clone, Debug, PartialEq)]
18pub(crate) struct AttachedScrollBar {
19    pub target: Vec<usize>,
20    pub geometry: ScrollBarGeometry,
21}
22
23/// Resolve handles after laying out both the control and its viewport.
24pub(crate) fn attach(scene: &Node, layout: &mut LayoutNode, text: &mut impl TextMeasurer) {
25    fn index<'a>(
26        node: &'a Node,
27        item: &LayoutNode,
28        path: &mut Vec<usize>,
29        viewports: &mut BTreeMap<usize, Vec<usize>>,
30        controls: &mut Vec<(&'a Node, Vec<usize>)>,
31    ) {
32        if !item.visible || !node.group_content_enabled() {
33            return;
34        }
35        if let Some(handle) = &node.viewport_handle {
36            viewports.insert(handle.identity(), path.clone());
37        }
38        if node.scroll_target.is_some() {
39            controls.push((node, path.clone()));
40        }
41        for (index_in_parent, child, child_layout) in item.children_in_scene_order(node) {
42            path.push(index_in_parent);
43            index(child, child_layout, path, viewports, controls);
44            path.pop();
45        }
46    }
47
48    let mut viewports = BTreeMap::new();
49    let mut controls = Vec::new();
50    index(
51        scene,
52        layout,
53        &mut Vec::new(),
54        &mut viewports,
55        &mut controls,
56    );
57    let window = layout.bounds;
58    let offsets = BTreeMap::new();
59    for (node, path) in controls {
60        let Some((attached, enabled)) = resolve_attachment(node, &path, layout, &viewports) else {
61            continue;
62        };
63        let geometry = attached.geometry;
64        let Some(item) = path
65            .iter()
66            .try_fold(&mut *layout, |item, &index| item.child_at_mut(index))
67        else {
68            continue;
69        };
70        item.enabled &= enabled;
71        item.attached_scroll_bar = Some(Box::new(attached));
72        if !node.has_scroll_parts() {
73            continue;
74        }
75        let mut context = LayoutContext {
76            text,
77            layout_direction: item.direction_override,
78            offsets: &offsets,
79            input: None,
80            path,
81            row_key: node.routing_row_key(),
82            anchor: None,
83            resolved_list_scroll: None,
84            row_layouts: None,
85            ancestor_shapes: item.ancestor_shapes.clone(),
86            space: item.space.clone(),
87            viewport: window,
88        };
89        // The two visual parts are placed after resolving the viewport and use
90        // exactly the rectangles used for dragging and track paging.
91        for (index, part) in node.children.iter().enumerate() {
92            let bounds = match part.kind {
93                "ScrollTrack" => geometry.track,
94                "ScrollThumb" => geometry.thumb,
95                _ => continue,
96            };
97            context.path.push(index);
98            item.children[index] = context.place(
99                part,
100                bounds,
101                item.clip.intersect(bounds),
102                true,
103                item.enabled,
104                None,
105            );
106            context.path.pop();
107        }
108    }
109}
110
111fn resolve_attachment(
112    node: &Node,
113    path: &[usize],
114    layout: &LayoutNode,
115    viewports: &BTreeMap<usize, Vec<usize>>,
116) -> Option<(AttachedScrollBar, bool)> {
117    let target = viewports.get(&node.scroll_target.as_ref()?.identity())?;
118    if layout.overlays.as_ref().is_some_and(|overlays| {
119        overlays
120            .modal
121            .iter()
122            .any(|modal| path.starts_with(modal) != target.starts_with(modal))
123    }) {
124        return None;
125    }
126    let viewport = layout.at_path(target)?;
127    let axis = node.orientation();
128    let scroll = viewport.scroll_on(axis)?;
129    let page = span(viewport.scroll_viewport(axis), axis);
130    if page <= 0.0 || !shows_bar(control_policy(node), scroll) {
131        return None;
132    }
133    let item = layout.at_path(path)?;
134    let mut geometry = ScrollBarGeometry::new(
135        axis,
136        item.bounds,
137        page,
138        scroll,
139        minimum_size(node),
140        viewport.scroll_axis_reversed(axis),
141    )?;
142    geometry.step =
143        ScrollBarGeometry::viewport_step(page, scroll.max_offset, node.number("step-size"));
144    Some((
145        AttachedScrollBar {
146            target: target.clone(),
147            geometry,
148        },
149        viewport.enabled,
150    ))
151}
152
153fn control_policy(node: &Node) -> ScrollBarPolicy {
154    match node.properties.get("policy") {
155        Some(Value::ScrollBarPolicy(policy)) => *policy,
156        _ => ScrollBarPolicy::AsNeeded,
157    }
158}
159
160fn minimum_size(node: &Node) -> Option<f32> {
161    node.number("minimum-size")
162        .map(|size| size.clamp(0.0, 1.0) as f32)
163}
164
165fn shows_bar(policy: ScrollBarPolicy, scroll: ScrollLayout) -> bool {
166    match policy {
167        ScrollBarPolicy::AsNeeded => scroll.max_offset > 0.0,
168        ScrollBarPolicy::AlwaysOn => true,
169        ScrollBarPolicy::AlwaysOff => false,
170    }
171}
172
173pub(crate) fn standalone_geometry(
174    node: &Node,
175    bounds: Rect,
176    direction: LayoutDirection,
177) -> Option<ScrollBarGeometry> {
178    let range = ScrollBarRange::from_node(node);
179    let scroll = ScrollLayout::new(range.position as f32, range.maximum() as f32);
180    if !shows_bar(control_policy(node), scroll) {
181        return None;
182    }
183    let orientation = node.orientation();
184    let mut geometry = ScrollBarGeometry::new(
185        orientation,
186        bounds,
187        range.size as f32,
188        scroll,
189        minimum_size(node),
190        orientation == Orientation::Horizontal && direction == LayoutDirection::RightToLeft,
191    )?;
192    geometry.step = range.step as f32;
193    Some(geometry)
194}
195
196pub(crate) fn scroll_bar_thickness(bounds: Rect) -> f32 {
197    10.0_f32.min(bounds.width * 0.25).min(bounds.height * 0.25)
198}
199
200impl LayoutNode {
201    pub fn attached_scroll_geometry(&self) -> Option<ScrollBarGeometry> {
202        self.attached_scroll_bar.as_ref().map(|bar| bar.geometry)
203    }
204
205    pub fn scroll_control_geometry(&self, node: &Node) -> Option<ScrollBarGeometry> {
206        if !self.visible || !matches!(node.kind, "ScrollBar" | "ScrollIndicator") {
207            return None;
208        }
209        if node.scroll_target.is_some() {
210            return self.attached_scroll_geometry();
211        }
212        standalone_geometry(node, self.bounds, self.layout_direction)
213    }
214
215    /// Bars share the viewport's offsets and do not change content or header layout.
216    pub fn scroll_bars(&self, node: &Node) -> impl Iterator<Item = ScrollBarGeometry> {
217        if matches!(node.kind, "ScrollBar" | "ScrollIndicator") {
218            return [self.scroll_control_geometry(node), None]
219                .into_iter()
220                .flatten();
221        }
222        if node.kind == "Flickable"
223            || !self.visible
224            || self.scroll.is_none() && self.scroll_on(Orientation::Horizontal).is_none()
225        {
226            return [None; 2].into_iter().flatten();
227        }
228        let viewport = self.scroll_viewport(Orientation::Vertical);
229        if node.kind == "ScrollView" && node.boolean("reserve-scroll-bar-space", false) {
230            let side = (self.bounds.width - viewport.width).max(0.0);
231            let bottom = (self.bounds.height - viewport.height).max(0.0);
232            let mirrored = self.layout_direction == LayoutDirection::RightToLeft;
233            let tracks = [
234                Rect::new(
235                    viewport.x,
236                    viewport.y + viewport.height,
237                    viewport.width,
238                    bottom,
239                ),
240                Rect::new(
241                    if mirrored {
242                        self.bounds.x
243                    } else {
244                        viewport.x + viewport.width
245                    },
246                    viewport.y,
247                    side,
248                    viewport.height,
249                ),
250            ];
251            let bars = [Orientation::Horizontal, Orientation::Vertical].map(|axis| {
252                let index = usize::from(axis == Orientation::Vertical);
253                let track = tracks[index];
254                ScrollBarGeometry::new(
255                    axis,
256                    track,
257                    span(viewport, axis),
258                    self.scroll_on(axis)?,
259                    None,
260                    self.scroll_axis_reversed(axis),
261                )
262            });
263            return bars.into_iter().flatten();
264        }
265        let horizontal_viewport = self.scroll_viewport(Orientation::Horizontal);
266        let horizontal_visible = horizontal_viewport.intersect(self.clip).inset(2.0);
267        let visible = viewport.intersect(self.clip).inset(2.0);
268        let thickness = scroll_bar_thickness(visible);
269        let mirrored = self.layout_direction == LayoutDirection::RightToLeft;
270        let axes = [Orientation::Horizontal, Orientation::Vertical];
271        let scrolls: [_; 2] = std::array::from_fn(|index| {
272            self.scroll_on(axes[index])
273                .filter(|_| {
274                    axes[index] != Orientation::Horizontal || horizontal_visible.width > 0.0
275                })
276                .filter(|&scroll| shows_bar(node.scroll_bar_policy(axes[index]), scroll))
277        });
278        let bars: [_; 2] = std::array::from_fn(|index| {
279            if thickness < 1.0 {
280                return None;
281            }
282            let orientation = axes[index];
283            let scroll = scrolls[index]?;
284            let corner = if scrolls[1 - index].is_some() {
285                thickness
286            } else {
287                0.0
288            };
289            let (track, page) = match orientation {
290                Orientation::Horizontal => (
291                    Rect::new(
292                        horizontal_visible.x + if mirrored { corner } else { 0.0 },
293                        visible.y + visible.height - thickness,
294                        horizontal_visible.width - corner,
295                        thickness,
296                    ),
297                    horizontal_viewport.width,
298                ),
299                Orientation::Vertical => (
300                    Rect::new(
301                        if mirrored {
302                            visible.x
303                        } else {
304                            visible.x + visible.width - thickness
305                        },
306                        visible.y,
307                        thickness,
308                        visible.height - corner,
309                    ),
310                    viewport.height,
311                ),
312            };
313            ScrollBarGeometry::new(
314                orientation,
315                track,
316                page,
317                scroll,
318                None,
319                self.scroll_axis_reversed(orientation),
320            )
321        });
322        bars.into_iter().flatten()
323    }
324}
325
326impl ScrollBarGeometry {
327    pub const STEP: f32 = 28.0;
328
329    pub(crate) fn viewport_step(page: f32, scrollable: f32, configured: Option<f64>) -> f32 {
330        let Some(step) = configured.filter(|step| step.is_finite()) else {
331            return Self::STEP;
332        };
333        let extent = f64::from(page) + f64::from(scrollable);
334        (step.clamp(0.0, 1.0) * extent).min(f64::from(f32::MAX)) as f32
335    }
336
337    fn new(
338        orientation: Orientation,
339        track: Rect,
340        page: f32,
341        scroll: ScrollLayout,
342        minimum_size: Option<f32>,
343        reversed: bool,
344    ) -> Option<Self> {
345        let length = span(track, orientation);
346        if length <= 2.0 || track.width <= 0.0 || track.height <= 0.0 {
347            return None;
348        }
349        let (length, offset) = if scroll.max_offset > 0.0 {
350            let ratio = f64::from(page) / (f64::from(page) + f64::from(scroll.max_offset));
351            let minimum = minimum_size.map_or(20.0_f32.min(length * 0.5), |size| size * length);
352            let thumb_length = (length * ratio as f32)
353                .max(minimum.max(1.0))
354                .min(length - 1.0);
355            let ratio = scroll.offset / scroll.max_offset;
356            (
357                thumb_length,
358                (length - thumb_length) * if reversed { 1.0 - ratio } else { ratio },
359            )
360        } else {
361            (length, 0.0)
362        };
363        let thumb = match orientation {
364            Orientation::Horizontal => Rect::new(track.x + offset, track.y, length, track.height),
365            Orientation::Vertical => Rect::new(track.x, track.y + offset, track.width, length),
366        };
367        Some(Self {
368            orientation,
369            track,
370            thumb,
371            scroll,
372            page,
373            step: Self::STEP,
374            reversed,
375        })
376    }
377
378    /// The thumb's start and length as fractions of the track, in physical order.
379    pub(crate) fn normalized_thumb(self) -> (f64, f64) {
380        let length = f64::from(span(self.track, self.orientation));
381        let position = f64::from(origin(self.thumb, self.orientation))
382            - f64::from(origin(self.track, self.orientation));
383        let size = (f64::from(span(self.thumb, self.orientation)) / length).clamp(0.0, 1.0);
384        ((position / length).clamp(0.0, 1.0 - size), size)
385    }
386
387    #[doc(hidden)]
388    pub fn reversed(self) -> bool {
389        self.reversed
390    }
391
392    pub(crate) fn logical_delta(self, delta: f32) -> f32 {
393        if self.reversed { -delta } else { delta }
394    }
395
396    pub fn scrollable(self) -> bool {
397        self.scroll.max_offset > 0.0
398    }
399
400    pub(crate) fn grab(self, point: Point) -> Option<f32> {
401        self.thumb.contains(point).then(|| {
402            (coordinate(point, self.orientation) - origin(self.thumb, self.orientation))
403                / span(self.thumb, self.orientation)
404        })
405    }
406
407    pub(crate) fn drag_fraction(self, point: Point, grab: f32) -> f64 {
408        let thumb = span(self.thumb, self.orientation);
409        let travel = span(self.track, self.orientation) - thumb;
410        let relative = coordinate(point, self.orientation) - origin(self.track, self.orientation);
411        let fraction = f64::from((relative - grab * thumb) / travel).clamp(0.0, 1.0);
412        if self.reversed {
413            1.0 - fraction
414        } else {
415            fraction
416        }
417    }
418
419    pub(crate) fn page_toward(self, point: Point) -> f32 {
420        let page = if self.page > 0.0 {
421            self.page
422        } else {
423            self.step
424        };
425        let delta = if coordinate(point, self.orientation) < origin(self.thumb, self.orientation) {
426            -page
427        } else {
428            page
429        };
430        (self.scroll.offset + self.logical_delta(delta)).clamp(0.0, self.scroll.max_offset)
431    }
432}
433
434pub(crate) fn snap_fraction(fraction: f64, step: f64) -> f64 {
435    let step = step.clamp(0.0, 1.0);
436    if step <= f64::EPSILON || fraction == 0.0 || fraction == 1.0 {
437        return fraction;
438    }
439    let lower = (fraction / step).floor() * step;
440    let upper = (lower + step).min(1.0);
441    if fraction - lower < upper - fraction {
442        lower
443    } else {
444        upper
445    }
446}
447
448fn coordinate(point: Point, orientation: Orientation) -> f32 {
449    match orientation {
450        Orientation::Horizontal => point.x,
451        Orientation::Vertical => point.y,
452    }
453}
454
455fn origin(rect: Rect, orientation: Orientation) -> f32 {
456    coordinate(
457        Point {
458            x: rect.x,
459            y: rect.y,
460        },
461        orientation,
462    )
463}
464
465fn span(rect: Rect, orientation: Orientation) -> f32 {
466    match orientation {
467        Orientation::Horizontal => rect.width,
468        Orientation::Vertical => rect.height,
469    }
470}