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 self.scroll.offset(key)
104 }
105
106 /// Everything the last layout resolved for the container `key`: its own
107 /// box, its content size, and the clamped offset — `None` for a key no
108 /// layout has ever resolved as a scroll container. While an eased
109 /// leg runs the offset is where the content is drawn rather than
110 /// the target, sampled at the clock the coming frame reads, so a view
111 /// slices the rows that frame shows.
112 ///
113 /// This is what makes a long list affordable. The core culls glyphs by
114 /// viewport but builds every child a view declares, so ten thousand rows
115 /// cost ten thousand rows; with the offset and the container's height a
116 /// view can declare only the rows that can be seen and two spacers, and
117 /// pay for a screenful. `widgets::uniform_list` is that, done.
118 ///
119 /// Read during a build, it describes the frame before — the tree it came
120 /// from is already cleared. That is one frame of lag on the size, so the
121 /// frame after a resize slices to the old height; a row or two of
122 /// overscan covers it, which is what the widget does. The rect is the
123 /// same one an `on_layout` on that node would post, without the round
124 /// trip through the app's model, and without firing every time an
125 /// enclosing container scrolls the whole list past.
126 pub fn scroll_geometry(&self, key: Key) -> Option<crate::scroll::ScrollGeometry> {
127 let shift = self.dt_shift();
128 self.scroll.geometry(key).map(|mut g| {
129 g.rect.x -= shift.x;
130 g.rect.y -= shift.y;
131 g
132 })
133 }
134
135 /// The rect the last frame laid `key` out at, in logical viewport px —
136 /// for a node that declared `on_layout`, whose rect the core keeps for
137 /// the event's edge trigger anyway. The query
138 /// shape of the `layout` event: the same numbers, read during the next
139 /// build with no event, no tag and no model field. `None` for a key
140 /// that did not declare `on_layout` last frame; read during a build it
141 /// describes the previous frame, like [`Self::scroll_geometry`].
142 pub fn layout_of(&self, key: Key) -> Option<Rect> {
143 let shift = self.dt_shift();
144 // "Last frame" is the one before this build while a build is on,
145 // and the one just finished between two — `frame_no` has already
146 // moved on in the first case and not in the second.
147 let last = self.frame_no - u64::from(self.building);
148 self.layouts
149 .get(&key)
150 .filter(|(_, seen)| *seen == last)
151 .map(|(r, _)| Rect::new(r.x - shift.x, r.y - shift.y, r.w, r.h))
152 }
153
154 /// Sets the container `key`'s retained offset, the way the wheel would.
155 /// Takes effect at the next layout, which clamps it to that frame's
156 /// overflow: `Vec2::ZERO` is "jump to the top", and a large value is
157 /// "jump to the end" without knowing the content height. Writing an
158 /// offset for a key that never scrolls is harmless; it just never
159 /// reads back. Between two frames the write asks for the frame that
160 /// lands it; from inside a view it asks for nothing, because the
161 /// frame being built is that frame — the positions pass reads the
162 /// store after the view has run — and a view writing every frame
163 /// would otherwise be a window that never idles (the devtools' events
164 /// list and `widgets::list` both write this way).
165 #[track_caller]
166 pub fn set_scroll(&mut self, key: Key, offset: Vec2) {
167 // Programmatic, so a container with a `transition` eases into it
168 // (F80); the wheel and the thumb go through `scroll_by` and
169 // `set_scroll_axis`, which do not.
170 self.scroll.set_smooth(key, offset);
171 if !self.building {
172 self.owe_frame("set_scroll");
173 }
174 }
175
176 /// Moves `key`'s scroll state by the content that moved under it:
177 /// `drawn` for where the content is drawn (and an eased leg's start),
178 /// `target` for the retained offset. No ease is asked or ended, and no
179 /// frame is asked for: it is a correction to the frame about to be
180 /// laid out — the rows above the window were measured and came out
181 /// another height — so it belongs to that frame, whoever calls it. A
182 /// variable-height list's anchor: `widgets::list` from its view,
183 /// the Node and Lua ports from theirs, just before the tree they
184 /// return is laid out.
185 pub fn shift_scroll(&mut self, key: Key, drawn: Vec2, target: Vec2) {
186 self.scroll.shift(key, drawn, target);
187 }
188
189 /// After layout: if the focused edit's caret moved this frame, nudge the
190 /// nearest scrollable ancestor so the caret stays visible, then re-run
191 /// the positions pass with the adjusted offset (positions is the only
192 /// pass scroll offsets feed into, so nothing else needs recomputing).
193 pub(crate) fn scroll_caret_into_view(&mut self) {
194 let Some(key) = self.edit.caret_moved else {
195 return;
196 };
197 // Not under a held pointer drag: the caret is where the pointer
198 // is, past the edge or not, and what moves the scroller then is
199 // the drag's own rate (ADR 0029, decision 2) — a reveal there
200 // would jump it by the whole distance past, every frame. The move
201 // stays noted, so the release reveals where the caret landed;
202 // a field still scrolls its own text below, at once.
203 let held = self.edit.dragging.is_some_and(|(k, _)| k == key);
204 if !held {
205 self.edit.caret_moved = None;
206 }
207 if self.edit.focused() != Some(key) {
208 return;
209 }
210 let Some(i) =
211 (0..self.tree.len()).find(|&i| self.tree.content[i] == NodeContent::Edit(key))
212 else {
213 return;
214 };
215 let pad = self.tree.specs[i].layout.padding;
216 // A single-line field scrolls its own text, and the box it does
217 // that in is final now that layout has run — so settle its offset
218 // before asking where the caret is. Without this the ancestor
219 // scrolls to reveal a caret the field is about to bring into view
220 // itself (F41); emission recomputes the same number.
221 let inner_w = (self.tree.size[i].w - pad.x()).max(0.0) * self.scale;
222 self.edit_with_fonts(|edit, fs| edit.line_offset(key, inner_w, fs));
223 if held {
224 return;
225 }
226 let Some((_, caret)) = self.stock_caret_viewport_rect(key) else {
227 return;
228 };
229 self.scroll_rect_into_view(i, caret, true);
230 }
231
232 /// After layout: resolves a pending `reveal(key)` against the frame
233 /// just laid out, then forgets it either way — a key this frame did
234 /// not declare is a no-op, not a request that waits for the frame that
235 /// declares it. Like the caret, the positions pass re-runs, so this
236 /// frame already draws the node in view.
237 pub(crate) fn apply_pending_reveal(&mut self) {
238 for (label, origin) in std::mem::take(&mut self.pending_reveal_labels) {
239 match self.find_label_as(&label, origin) {
240 Some(key) => self.pending_reveal.push(key),
241 None => self
242 .diag
243 .raise(crate::diag::label_without_node("reveal", &label)),
244 }
245 }
246 let asks = std::mem::take(&mut self.pending_reveal);
247 if asks.is_empty() {
248 return;
249 }
250 // Each ask by the container it would move — its nearest
251 // scrolling ancestor, which is the only one a reveal nudges —
252 // the last ask per container kept, in the order asked.
253 let mut kept: Vec<(u32, usize)> = Vec::new();
254 for key in asks {
255 let Some(i) = (0..self.tree.len()).find(|&i| self.tree.keys[i] == key) else {
256 continue;
257 };
258 let mut a = self.tree.parent[i];
259 while a != NIL {
260 let spec = self.tree.specs[a as usize].layout;
261 if spec.scroll_x || spec.scroll_y {
262 break;
263 }
264 a = self.tree.parent[a as usize];
265 }
266 if a == NIL {
267 continue;
268 }
269 kept.retain(|(c, _)| *c != a);
270 kept.push((a, i));
271 }
272 for (_, i) in kept {
273 let rect = Rect::from_pos_size(self.tree.pos[i], self.tree.size[i]);
274 self.scroll_rect_into_view_smooth(i, rect, true);
275 }
276 }
277
278 /// Nudges the nearest scrolling ancestor of node `i` so `rect`
279 /// (viewport coordinates) is inside it. With `relayout`, re-runs the
280 /// positions pass so this frame already shows the new offset
281 /// (positions is the only pass scroll offsets feed into); without it
282 /// the next frame does.
283 pub(crate) fn scroll_rect_into_view(&mut self, i: usize, rect: Rect, relayout: bool) {
284 self.scroll_rect_into_view_from(i, rect, relayout, false);
285 }
286
287 /// The same, easing the nudge on a container that declares a
288 /// `transition`: what `reveal` asks for, where a caret nudge
289 /// and a focus move take the content there at once.
290 pub(crate) fn scroll_rect_into_view_smooth(&mut self, i: usize, rect: Rect, relayout: bool) {
291 self.scroll_rect_into_view_from(i, rect, relayout, true);
292 }
293
294 fn scroll_rect_into_view_from(&mut self, i: usize, rect: Rect, relayout: bool, smooth: bool) {
295 // Slack so the target isn't glued to the container edge.
296 const MARGIN: f32 = 4.0;
297 let mut a = self.tree.parent[i];
298 while a != NIL {
299 let spec = self.tree.specs[a as usize].layout;
300 if spec.scroll_x || spec.scroll_y {
301 let view =
302 Rect::from_pos_size(self.tree.pos[a as usize], self.tree.size[a as usize]);
303 let mut delta = Vec2::ZERO;
304 if spec.scroll_y {
305 if rect.y < view.y + MARGIN {
306 delta.y = rect.y - (view.y + MARGIN);
307 } else if rect.y + rect.h > view.y + view.h - MARGIN {
308 delta.y = rect.y + rect.h - (view.y + view.h - MARGIN);
309 }
310 }
311 if spec.scroll_x {
312 if rect.x < view.x + MARGIN {
313 delta.x = rect.x - (view.x + MARGIN);
314 } else if rect.x + rect.w > view.x + view.w - MARGIN {
315 delta.x = rect.x + rect.w - (view.x + view.w - MARGIN);
316 }
317 }
318 if delta.x != 0.0 || delta.y != 0.0 {
319 let key = self.tree.keys[a as usize];
320 if smooth {
321 self.scroll.scroll_by_smooth(key, delta);
322 } else {
323 self.scroll.scroll_by(key, delta);
324 }
325 if relayout {
326 layout::reposition(
327 &mut self.tree,
328 &mut self.scroll,
329 self.viewport,
330 self.scale,
331 );
332 }
333 }
334 return;
335 }
336 a = self.tree.parent[a as usize];
337 }
338 }
339}