Skip to main content

mitsuami_core/ui/
scroll.rs

1//! Scroll views and lists: scroll offsets and scrolling into view.
2
3use crate::command::Command;
4use crate::geometry::{Point, Size};
5use crate::widget::{NodeId, RowKey, WidgetKind};
6
7use super::{Inner, Ui};
8
9impl Ui {
10    /// Current scroll offset of a `ScrollView`, `List` or `Table`.
11    pub fn scroll_offset(&self, id: NodeId) -> Option<Point> {
12        let inner = self.inner.borrow();
13        let node = inner.nodes.get(&id)?;
14        node.kind.scrolls().then_some(node.scroll_offset)
15    }
16
17    /// Scrolls a `ScrollView`, `List` or `Table`. A scroll view's offset is
18    /// clamped to its content; a list's or table's isn't, since its rows
19    /// are the platform's: the backend clamps it.
20    pub fn scroll_to(&self, id: NodeId, offset: Point) {
21        {
22            let mut inner = self.inner.borrow_mut();
23            let Some(offset) = inner.clamp_scroll(id, offset) else { return };
24            let node = inner.nodes.get_mut(&id).unwrap();
25            if node.scroll_offset == offset {
26                return;
27            }
28            node.scroll_offset = offset;
29            inner.pending.push(Command::ScrollTo { id, offset });
30        }
31        self.changed();
32    }
33
34    /// Scrolls every enclosing `ScrollView`, `List` and `Table` just enough to show
35    /// the node.
36    pub fn scroll_into_view(&self, id: NodeId) {
37        let mut target = id;
38        loop {
39            let scroll_view = {
40                let inner = self.inner.borrow();
41                let mut current = inner.nodes.get(&target).and_then(|n| n.native_parent);
42                while let Some(ancestor) = current {
43                    if inner.nodes[&ancestor].kind.scrolls() {
44                        break;
45                    }
46                    current = inner.nodes[&ancestor].native_parent;
47                }
48                current
49            };
50            let Some(scroll_view) = scroll_view else { return };
51            // In a list, show the target's row: where rows are is the
52            // platform's business.
53            let row = {
54                let inner = self.inner.borrow();
55                let mut current = Some(target);
56                while let Some(node) = current.and_then(|c| inner.nodes.get(&c)) {
57                    if node.native_parent == Some(scroll_view) {
58                        break;
59                    }
60                    current = node.native_parent;
61                }
62                inner.nodes[&scroll_view].kind.has_rows().then(|| {
63                    current.and_then(|host| {
64                        let props = &inner.nodes[&host].props;
65                        crate::find_prop!(props, Row).or_else(|| crate::find_prop!(props, Cell).map(|cell| cell.row))
66                    })
67                })
68            };
69            if let Some(row) = row {
70                if let Some(row) = row {
71                    self.scroll_to_row(scroll_view, row);
72                }
73                target = scroll_view;
74                continue;
75            }
76            let (Some(rect), Some(viewport)) = (self.window_frame(target), self.viewport(scroll_view)) else {
77                return;
78            };
79            let offset = self.scroll_offset(scroll_view).unwrap_or_default();
80            // The target in content coordinates, and what currently shows.
81            let x = rect.x() - viewport.x() + offset.x;
82            let y = rect.y() - viewport.y() + offset.y;
83            let next = Point::new(
84                fit(x, rect.width(), offset.x, viewport.width()),
85                fit(y, rect.height(), offset.y, viewport.height()),
86            );
87            self.scroll_to(scroll_view, next);
88            target = scroll_view;
89        }
90    }
91
92    /// Scrolls a `List` or `Table` just enough to show a row, mounted or not. The
93    /// platform scrolls and reports it.
94    pub(crate) fn scroll_to_row(&self, id: NodeId, row: RowKey) {
95        {
96            let mut inner = self.inner.borrow_mut();
97            if inner.nodes.get(&id).is_none_or(|n| !n.kind.has_rows()) {
98                return;
99            }
100            inner.pending.push(Command::ScrollToRow { id, row });
101        }
102        self.changed();
103    }
104}
105
106impl Inner {
107    fn clamp_scroll(&self, id: NodeId, offset: Point) -> Option<Point> {
108        let node = self.nodes.get(&id)?;
109        let (axes, content) = match node.kind {
110            WidgetKind::ScrollView => (
111                crate::find_prop!(node.props, ScrollAxes).unwrap_or_default(),
112                node.native_children.first().map_or(Size::ZERO, |c| self.nodes[c].frame.size),
113            ),
114            WidgetKind::List => (crate::ScrollAxes::Vertical, Size::new(node.frame.width(), f32::INFINITY)),
115            // Its columns can be wider than it: the platform clamps.
116            WidgetKind::Table => (crate::ScrollAxes::Both, Size::new(f32::INFINITY, f32::INFINITY)),
117            _ => return None,
118        };
119        let viewport = node.frame.inset(node.viewport_insets).size;
120        let clamp = |v: f32, content: f32, viewport: f32, enabled: bool| {
121            if enabled { v.clamp(0.0, (content - viewport).max(0.0)) } else { 0.0 }
122        };
123        Some(Point::new(
124            clamp(offset.x, content.width, viewport.width, axes.horizontal()),
125            clamp(offset.y, content.height, viewport.height, axes.vertical()),
126        ))
127    }
128}
129
130/// Where to scroll along one axis so `len` at `start` shows, moving as
131/// little as possible from `current` with `visible` in view.
132fn fit(start: f32, len: f32, current: f32, visible: f32) -> f32 {
133    if start < current {
134        start
135    } else if start + len > current + visible {
136        (start + len - visible).min(start)
137    } else {
138        current
139    }
140}