Skip to main content

kui_core/runtime/
scrolling.rs

1//! Retained scroll offsets: the outside API (`reveal`, `set_scroll`, the
2//! geometry a virtual list reads) and the after-layout nudges that keep a
3//! caret or a revealed node in view. The wheel and the scrollbars move the
4//! same offsets from `dispatch`.
5
6use super::*;
7
8impl Core {
9    /// Sets one axis of a container's scroll offset, keeping the other
10    /// where it stands — mid-leg, the drawn place and not the target, so
11    /// a thumb dragged on one axis does not jump the other to where an
12    /// eased leg was going.
13    pub(crate) fn set_scroll_axis(&mut self, key: Key, axis: ScrollAxis, value: f32) {
14        let mut off = self.scroll.standing(key);
15        match axis {
16            ScrollAxis::X => off.x = value,
17            ScrollAxis::Y => off.y = value,
18        }
19        self.scroll.set(key, off);
20    }
21
22    // -- Scrolling ------------------------------------------------------
23    // Scroll offsets are retained per node key, clamped to the overflow the
24    // last layout found. The wheel, the scrollbars, Tab and the caret all
25    // move them from inside; these three are the same moves from outside,
26    // so "scroll to the selected row", "jump to the top" and "restore the
27    // position I saved" need no layout arithmetic in the app.
28
29    /// Scrolls the nearest scrolling ancestor of `key` so the node is
30    /// inside it — what Tab does to the control it lands on, asked for by
31    /// name. Already-visible nodes stay put.
32    ///
33    /// The request resolves at the next `finish_frame`, against the frame
34    /// that one lays out — the frame being built if this is called from a
35    /// view, the one after it if from an event handler (a frame is
36    /// requested, so one comes). That is what lets a view reveal a row it
37    /// is declaring for the first time. If that frame does not declare
38    /// `key`, or nothing above it scrolls, it is a no-op — the request is
39    /// spent, not held for the frame that might. Two reveals before one
40    /// frame into the *same* container are contradictory, so the last one
41    /// wins there; reveals into different containers — a tab strip and
42    /// the pane list under it — are not, and each lands.
43    ///
44    /// Traced, the ask is `"reveal"` at the caller's line.
45    #[track_caller]
46    pub fn reveal(&mut self, key: Key) {
47        self.pending_reveal.push(key);
48        self.owe_frame("reveal");
49    }
50
51    /// [`Self::reveal`] by the label a node declares, resolved when the
52    /// frame finishes — against the frame being built, or the next one
53    /// when none is — so a view may name a row it is declaring right now,
54    /// or one the frame after declares. A label that frame
55    /// does not declare raises `label-without-node` and moves nothing.
56    #[track_caller]
57    pub fn reveal_label(&mut self, label: &str) {
58        self.pending_reveal_labels
59            .push((label.to_string(), self.origin));
60        self.owe_frame("reveal_label");
61    }
62
63    /// [`Self::set_scroll`] by label, resolved like [`Self::reveal_label`]
64    /// but before layout, so the frame that resolves it lays out at the
65    /// offset.
66    #[track_caller]
67    pub fn set_scroll_label(&mut self, label: &str, offset: Vec2) {
68        self.pending_scroll_labels
69            .push((label.to_string(), self.origin, offset));
70        if !self.building {
71            self.owe_frame("set_scroll_label");
72        }
73    }
74
75    /// A deferred label, found as the origin that asked would find it
76    /// (`find_label` answers per origin), in this frame alone.
77    fn find_label_as(&mut self, label: &str, origin: crate::tree::OriginId) -> Option<Key> {
78        let at = std::mem::replace(&mut self.origin, origin);
79        let key = self.find_label(label, false);
80        self.origin = at;
81        key
82    }
83
84    /// Before layout: the `set_scroll_label` asks, as `set_scroll`s.
85    pub(crate) fn resolve_scroll_labels(&mut self) {
86        for (label, origin, offset) in std::mem::take(&mut self.pending_scroll_labels) {
87            match self.find_label_as(&label, origin) {
88                Some(key) => self.scroll.set_smooth(key, offset),
89                None => self
90                    .diag
91                    .raise(crate::diag::label_without_node("set_scroll", &label)),
92            }
93        }
94    }
95
96    /// The retained scroll offset of the container `key`, as the last
97    /// layout clamped it (positive = content moved up / left) — the
98    /// target: while a container with a `transition` eases to it the
99    /// content is drawn short of it, where [`Self::scroll_geometry`]
100    /// says. Zero for a node that never scrolled, and for one that is not
101    /// a container at all — the store keeps offsets, not membership.
102    pub fn scroll_offset(&self, key: Key) -> Vec2 {
103        let v = self.scroll.offset(key);
104        self.note_read(|| replay::Read::Scroll(key, v));
105        v
106    }
107
108    /// Everything the last layout resolved for the container `key`: its own
109    /// box, its content size, and the clamped offset — `None` for a key no
110    /// layout has ever resolved as a scroll container. While an eased
111    /// leg runs the offset is where the content is drawn rather than
112    /// the target, sampled at the clock the coming frame reads, so a view
113    /// slices the rows that frame shows.
114    ///
115    /// This is what makes a long list affordable. The core culls glyphs by
116    /// viewport but builds every child a view declares, so ten thousand rows
117    /// cost ten thousand rows; with the offset and the container's height a
118    /// view can declare only the rows that can be seen and two spacers, and
119    /// pay for a screenful. `widgets::uniform_list` is that, done.
120    ///
121    /// Read during a build, it describes the frame before — the tree it came
122    /// from is already cleared. That is one frame of lag on the size, so the
123    /// frame after a resize slices to the old height; a row or two of
124    /// overscan covers it, which is what the widget does. The rect is the
125    /// same one an `on_layout` on that node would post, without the round
126    /// trip through the app's model, and without firing every time an
127    /// enclosing container scrolls the whole list past.
128    pub fn scroll_geometry(&self, key: Key) -> Option<crate::scroll::ScrollGeometry> {
129        let shift = self.dt_shift();
130        let g = self.scroll.geometry(key).map(|mut g| {
131            g.rect.x -= shift.x;
132            g.rect.y -= shift.y;
133            g
134        });
135        self.note_read(|| replay::Read::ScrollGeom(key, g));
136        g
137    }
138
139    /// The rect the last frame laid `key` out at, in logical viewport px —
140    /// for a node that declared `on_layout`, whose rect the core keeps for
141    /// the event's edge trigger anyway. The query
142    /// shape of the `layout` event: the same numbers, read during the next
143    /// build with no event, no tag and no model field. `None` for a key
144    /// that did not declare `on_layout` last frame; read during a build it
145    /// describes the previous frame, like [`Self::scroll_geometry`].
146    pub fn layout_of(&self, key: Key) -> Option<Rect> {
147        let r = self.layout_of_raw(key);
148        self.note_read(|| replay::Read::Layout(key, r));
149        r
150    }
151
152    pub(crate) fn layout_of_raw(&self, key: Key) -> Option<Rect> {
153        let shift = self.dt_shift();
154        // "Last frame" is the one before this build while a build is on,
155        // and the one just finished between two — `frame_no` has already
156        // moved on in the first case and not in the second.
157        let last = self.frame_no - u64::from(self.building);
158        self.layouts
159            .get(&key)
160            .filter(|(_, seen)| *seen == last)
161            .map(|(r, _)| Rect::new(r.x - shift.x, r.y - shift.y, r.w, r.h))
162    }
163
164    /// Sets the container `key`'s retained offset, the way the wheel would.
165    /// Takes effect at the next layout, which clamps it to that frame's
166    /// overflow: `Vec2::ZERO` is "jump to the top", and a large value is
167    /// "jump to the end" without knowing the content height. Writing an
168    /// offset for a key that never scrolls is harmless; it just never
169    /// reads back. Between two frames the write asks for the frame that
170    /// lands it; from inside a view it asks for nothing, because the
171    /// frame being built is that frame — the positions pass reads the
172    /// store after the view has run — and a view writing every frame
173    /// would otherwise be a window that never idles (the devtools' events
174    /// list and `widgets::list` both write this way).
175    #[track_caller]
176    pub fn set_scroll(&mut self, key: Key, offset: Vec2) {
177        // Programmatic, so a container with a `transition` eases into it
178        // (F80); the wheel and the thumb go through `scroll_by` and
179        // `set_scroll_axis`, which do not.
180        self.scroll.set_smooth(key, offset);
181        if !self.building {
182            self.owe_frame("set_scroll");
183        }
184    }
185
186    /// Moves `key`'s scroll state by the content that moved under it:
187    /// `drawn` for where the content is drawn (and an eased leg's start),
188    /// `target` for the retained offset. No ease is asked or ended, and no
189    /// frame is asked for: it is a correction to the frame about to be
190    /// laid out — the rows above the window were measured and came out
191    /// another height — so it belongs to that frame, whoever calls it. A
192    /// variable-height list's anchor: `widgets::list` from its view,
193    /// the Node and Lua ports from theirs, just before the tree they
194    /// return is laid out.
195    pub fn shift_scroll(&mut self, key: Key, drawn: Vec2, target: Vec2) {
196        self.scroll.shift(key, drawn, target);
197    }
198
199    /// After layout: if the focused edit's caret moved this frame, nudge the
200    /// nearest scrollable ancestor so the caret stays visible, then re-run
201    /// the positions pass with the adjusted offset (positions is the only
202    /// pass scroll offsets feed into, so nothing else needs recomputing).
203    pub(crate) fn scroll_caret_into_view(&mut self) {
204        let Some(key) = self.edit.caret_moved else {
205            return;
206        };
207        // Not under a held pointer drag: the caret is where the pointer
208        // is, past the edge or not, and what moves the scroller then is
209        // the drag's own rate (ADR 0029, decision 2) — a reveal there
210        // would jump it by the whole distance past, every frame. The move
211        // stays noted, so the release reveals where the caret landed;
212        // a field still scrolls its own text below, at once.
213        let held = self.edit.dragging.is_some_and(|(k, _)| k == key);
214        if !held {
215            self.edit.caret_moved = None;
216        }
217        if self.edit.focused() != Some(key) {
218            return;
219        }
220        let Some(i) =
221            (0..self.tree.len()).find(|&i| self.tree.content[i] == NodeContent::Edit(key))
222        else {
223            return;
224        };
225        let pad = self.tree.specs[i].layout.padding;
226        // A single-line field scrolls its own text, and the box it does
227        // that in is final now that layout has run — so settle its offset
228        // before asking where the caret is. Without this the ancestor
229        // scrolls to reveal a caret the field is about to bring into view
230        // itself (F41); emission recomputes the same number.
231        let inner_w = (self.tree.size[i].w - pad.x()).max(0.0) * self.scale;
232        self.edit_with_fonts(|edit, fs| edit.line_offset(key, inner_w, fs));
233        if held {
234            return;
235        }
236        let Some((_, caret)) = self.stock_caret_viewport_rect(key) else {
237            return;
238        };
239        self.scroll_rect_into_view(i, caret, true);
240    }
241
242    /// After layout: resolves a pending `reveal(key)` against the frame
243    /// just laid out, then forgets it either way — a key this frame did
244    /// not declare is a no-op, not a request that waits for the frame that
245    /// declares it. Like the caret, the positions pass re-runs, so this
246    /// frame already draws the node in view.
247    pub(crate) fn apply_pending_reveal(&mut self) {
248        for (label, origin) in std::mem::take(&mut self.pending_reveal_labels) {
249            match self.find_label_as(&label, origin) {
250                Some(key) => self.pending_reveal.push(key),
251                None => self
252                    .diag
253                    .raise(crate::diag::label_without_node("reveal", &label)),
254            }
255        }
256        let asks = std::mem::take(&mut self.pending_reveal);
257        if asks.is_empty() {
258            return;
259        }
260        // Each ask by the container it would move — its nearest
261        // scrolling ancestor, which is the only one a reveal nudges —
262        // the last ask per container kept, in the order asked.
263        let mut kept: Vec<(u32, usize)> = Vec::new();
264        for key in asks {
265            let Some(i) = (0..self.tree.len()).find(|&i| self.tree.keys[i] == key) else {
266                continue;
267            };
268            let mut a = self.tree.parent[i];
269            while a != NIL {
270                let spec = self.tree.specs[a as usize].layout;
271                if spec.scroll_x || spec.scroll_y {
272                    break;
273                }
274                a = self.tree.parent[a as usize];
275            }
276            if a == NIL {
277                continue;
278            }
279            kept.retain(|(c, _)| *c != a);
280            kept.push((a, i));
281        }
282        for (_, i) in kept {
283            let rect = Rect::from_pos_size(self.tree.pos[i], self.tree.size[i]);
284            self.scroll_rect_into_view_smooth(i, rect, true);
285        }
286    }
287
288    /// Nudges the nearest scrolling ancestor of node `i` so `rect`
289    /// (viewport coordinates) is inside it. With `relayout`, re-runs the
290    /// positions pass so this frame already shows the new offset
291    /// (positions is the only pass scroll offsets feed into); without it
292    /// the next frame does.
293    pub(crate) fn scroll_rect_into_view(&mut self, i: usize, rect: Rect, relayout: bool) {
294        self.scroll_rect_into_view_from(i, rect, relayout, false);
295    }
296
297    /// The same, easing the nudge on a container that declares a
298    /// `transition`: what `reveal` asks for, where a caret nudge
299    /// and a focus move take the content there at once.
300    pub(crate) fn scroll_rect_into_view_smooth(&mut self, i: usize, rect: Rect, relayout: bool) {
301        self.scroll_rect_into_view_from(i, rect, relayout, true);
302    }
303
304    fn scroll_rect_into_view_from(&mut self, i: usize, rect: Rect, relayout: bool, smooth: bool) {
305        // Slack so the target isn't glued to the container edge.
306        const MARGIN: f32 = 4.0;
307        let mut a = self.tree.parent[i];
308        while a != NIL {
309            let spec = self.tree.specs[a as usize].layout;
310            if spec.scroll_x || spec.scroll_y {
311                let view =
312                    Rect::from_pos_size(self.tree.pos[a as usize], self.tree.size[a as usize]);
313                let mut delta = Vec2::ZERO;
314                if spec.scroll_y {
315                    if rect.y < view.y + MARGIN {
316                        delta.y = rect.y - (view.y + MARGIN);
317                    } else if rect.y + rect.h > view.y + view.h - MARGIN {
318                        delta.y = rect.y + rect.h - (view.y + view.h - MARGIN);
319                    }
320                }
321                if spec.scroll_x {
322                    if rect.x < view.x + MARGIN {
323                        delta.x = rect.x - (view.x + MARGIN);
324                    } else if rect.x + rect.w > view.x + view.w - MARGIN {
325                        delta.x = rect.x + rect.w - (view.x + view.w - MARGIN);
326                    }
327                }
328                if delta.x != 0.0 || delta.y != 0.0 {
329                    let key = self.tree.keys[a as usize];
330                    if smooth {
331                        self.scroll.scroll_by_smooth(key, delta);
332                    } else {
333                        self.scroll.scroll_by(key, delta);
334                    }
335                    if relayout {
336                        layout::reposition(
337                            &mut self.tree,
338                            &mut self.scroll,
339                            self.viewport,
340                            self.scale,
341                        );
342                    }
343                }
344                return;
345            }
346            a = self.tree.parent[a as usize];
347        }
348    }
349}