Skip to main content

uzor_framework/widgets/
scroll.rs

1//! Scroll container over a [`PanelCx`]: wheel routing, trackpad 1:1 + fling,
2//! a draggable / pageable scrollbar, paint.
3//!
4//! ```ignore
5//! let off = scroll_begin(cx, "thread", vp, &mut self.sv, content_h, &st);
6//! // … paint content at y - off, clipped to vp, register its widgets …
7//! scroll_end(cx, "thread", vp, &mut self.sv, &st);
8//! ```
9
10use uzor::input::{Sense, WidgetKind};
11use uzor::{Rect, WidgetId};
12
13use crate::handle::{OverlayCx, PanelCx};
14use crate::types::scroll::{ScrollKey, ScrollStyle, ScrollView};
15use crate::types::spec::Spec;
16
17fn inside(r: Rect, p: (f64, f64)) -> bool {
18    p.0 >= r.x && p.0 < r.x + r.width && p.1 >= r.y && p.1 < r.y + r.height
19}
20
21/// Scroll containers of the window as of the previous frame, innermost (last painted) last:
22/// `(id, viewport, can scroll up, can scroll down)`. A wheel goes to the innermost container
23/// under the pointer that can still move that way and chains outwards at an edge — the DOM's
24/// nested scroll chaining (`overscroll-behavior: auto`).
25///
26/// Keyboard scrolling ([`queue_scroll_key`]) picks its container from the same chain: the
27/// one last clicked in (the browser's "focused" scroller) when it can move that way, else
28/// the innermost hovered one, chaining outwards at an edge. While an overlay has scroll
29/// containers, only those take keys (a modal makes the page under it inert).
30#[derive(Default)]
31struct Chain {
32    t: f64,
33    /// `(id, viewport, can scroll up, can scroll down, painted by an overlay, chains on)`.
34    prev: Vec<Entry>,
35    cur: Vec<Entry>,
36    /// The container last clicked in.
37    active: Option<String>,
38    /// A keyboard step waiting for its container this frame.
39    key: Option<ScrollKey>,
40}
41
42type Entry = (String, Rect, bool, bool, bool, bool);
43
44fn chain_key() -> WidgetId {
45    WidgetId::from("uzor.scroll.chain")
46}
47
48fn chain(states: &mut uzor::app_context::state::StateRegistry, now: f64) -> &mut Chain {
49    let c = states.get_or_insert_with(chain_key(), Chain::default);
50    if c.t != now {
51        c.t = now;
52        c.prev = std::mem::take(&mut c.cur);
53        c.key = None;
54    }
55    c
56}
57
58/// Queue a keyboard scroll step for this frame (call before the frame's `scroll_begin`s,
59/// e.g. at the top of the panel hook, with a key the app did not use otherwise). The
60/// container that takes it glides there; see [`Chain`] for which one.
61pub fn queue_scroll_key<S: Spec>(cx: &mut PanelCx<'_, S>, key: ScrollKey) {
62    let now = cx.time.now.0 * 1000.0;
63    chain(cx.widgets.states, now).key = Some(key);
64    cx.out.request_frame();
65}
66
67/// The container a keyboard step goes to, from the previous frame's chain.
68fn key_owner(c: &Chain, p: Option<(f64, f64)>, key: ScrollKey) -> Option<String> {
69    let up = matches!(key, ScrollKey::LineUp | ScrollKey::PageUp | ScrollKey::Home);
70    let overlay = c.prev.iter().any(|e| e.4);
71    let live: Vec<&Entry> = c.prev.iter().filter(|e| !overlay || e.4).collect();
72    let contains = |o: &Rect, i: &Rect| i.x >= o.x && i.y >= o.y && i.x + i.width <= o.x + o.width && i.y + i.height <= o.y + o.height;
73    // Innermost first: the active container and the ones enclosing it, else those under the pointer.
74    let active = c.active.as_ref().and_then(|a| live.iter().rev().find(|e| &e.0 == a));
75    let mut chain: Vec<&&Entry> = match (active, p) {
76        (Some(a), _) => live.iter().rev().filter(|e| contains(&e.1, &a.1)).collect(),
77        (None, Some(p)) => live.iter().rev().filter(|e| inside(e.1, p)).collect(),
78        (None, None) => Vec::new(),
79    };
80    // Last in line (and alone when nothing is clicked or hovered): the top overlay's
81    // container, else the largest one (the browser's document scroller).
82    let area = |e: &&&Entry| e.1.width * e.1.height;
83    let doc = if overlay { live.iter().last() } else { live.iter().max_by(|a, b| area(a).total_cmp(&area(b))) };
84    if let Some(d) = doc.filter(|d| !chain.iter().any(|e| e.0 == d.0)) {
85        chain.push(d);
86    }
87    for e in chain {
88        if if up { e.2 } else { e.3 } {
89            return Some(e.0.clone());
90        }
91        if !e.5 {
92            return None; // overscroll-behavior: contain
93        }
94    }
95    None
96}
97
98/// Whether container `id` takes a wheel of `dy` at `p` (innermost able one wins; the
99/// innermost one under the pointer when none can move, so edges still settle there).
100fn wheel_owner(c: &Chain, id: &str, p: (f64, f64), dy: f64) -> bool {
101    let under: Vec<&Entry> = c.prev.iter().filter(|e| inside(e.1, p)).collect();
102    if under.is_empty() || !under.iter().any(|e| e.0 == id) {
103        return true; // first frame of this container: no chain yet
104    }
105    // Innermost first: the first that can move takes it; one that contains overscroll keeps it.
106    let able = under.iter().rev().find(|e| (if dy > 0.0 { e.2 } else { e.3 }) || !e.5);
107    match able {
108        Some(e) => e.0 == id,
109        None => under.last().is_some_and(|e| e.0 == id),
110    }
111}
112
113fn ids(id: &str) -> (WidgetId, WidgetId) {
114    (WidgetId::from(format!("{id}:thumb").as_str()), WidgetId::from(format!("{id}:track").as_str()))
115}
116
117macro_rules! scroll_fns {
118    ($cx:ident, $begin:ident, $end:ident, $overlay:expr) => {
119/// Input half: sets the extent, applies this frame's wheel when the pointer is
120/// over `viewport` (and `wheel` is allowed), advances inertia, follows a thumb
121/// drag, pages on a track press. Returns the offset to paint the content at.
122pub fn $begin<S: Spec>(cx: &mut $cx<'_, S>, id: &str, viewport: Rect, sv: &mut ScrollView, content_h: f64, wheel: bool, st: &ScrollStyle) -> f64 {
123    let now = cx.time.now.0 * 1000.0;
124    sv.set_extent(content_h, viewport.height);
125    let (thumb_id, track_id) = ids(id);
126    let track = sv.track(viewport, st);
127    let p = cx.view.pointer();
128    if wheel && p.is_some_and(|p| inside(viewport, p)) {
129        let (_, dy) = cx.view.scroll();
130        let owner = dy == 0.0 || wheel_owner(chain(cx.widgets.states, now), id, p.unwrap_or_default(), dy);
131        if owner && sv.wheel(dy, cx.view.scroll_precise(), now, st) {
132            cx.out.request_frame();
133        }
134    }
135    if let Some(p) = p.filter(|p| inside(viewport, *p) && !cx.view.clicks().is_empty()) {
136        // A click makes the innermost scrollable container under it the keyboard one.
137        let c = chain(cx.widgets.states, now);
138        c.active = c.prev.iter().rev().find(|e| inside(e.1, p) && (e.2 || e.3)).map(|e| e.0.clone()).or(c.active.take());
139    }
140    let c = chain(cx.widgets.states, now);
141    if let Some(k) = c.key {
142        if key_owner(c, p, k).as_deref() == Some(id) {
143            c.key = None;
144            if sv.key(k, true) {
145                cx.out.request_frame();
146            }
147        }
148    }
149    if cx.view.is_pressed(&thumb_id) && !sv.dragging() {
150        if let Some(p) = p {
151            sv.begin_drag(p.1);
152        }
153    }
154    if sv.dragging() {
155        if cx.view.button_down() {
156            if let Some(p) = p {
157                sv.drag_to(p.1, track, st);
158            }
159        } else {
160            sv.end_drag();
161        }
162        cx.out.request_frame();
163    }
164    if cx.view.clicks().iter().any(|(w, _)| *w == track_id) {
165        if let Some(p) = p {
166            sv.page_towards(p.1, track, st);
167        }
168    }
169    if sv.tick(now, st) {
170        cx.out.request_frame();
171    }
172    sv.offset
173}
174
175/// Output half: registers the track and thumb above the content and paints
176/// the thumb (nothing when the content fits).
177pub fn $end<S: Spec>(cx: &mut $cx<'_, S>, id: &str, viewport: Rect, sv: &ScrollView, st: &ScrollStyle) {
178    let now = cx.time.now.0 * 1000.0;
179    chain(cx.widgets.states, now).cur.push((id.to_string(), viewport, sv.can_scroll(1.0), sv.can_scroll(-1.0), $overlay, sv.overscroll.chains()));
180    let track = sv.track(viewport, st);
181    let Some(th) = sv.thumb(track, st) else { return };
182    let (thumb_id, track_id) = ids(id);
183    let layer = cx.widgets.layer.clone();
184    // A slightly wider hit than the painted bar.
185    let grow = |r: Rect| Rect::new(r.x - 4.0, r.y, r.width + 7.0, r.height);
186    // Scrollbars keep the arrow (as the browser's); the thumb captures the pointer on drag.
187    cx.widgets.coord.register_atomic(track_id, WidgetKind::ScrollbarTrack, grow(track), Sense::CLICK, &layer);
188    cx.widgets.coord.register_atomic(thumb_id.clone(), WidgetKind::ScrollbarHandle, grow(th), Sense::CLICK_AND_DRAG, &layer);
189    let hot = sv.dragging() || cx.view.is_hovered(&thumb_id) || cx.view.pointer().is_some_and(|p| inside(grow(track), p));
190    let ctx = &mut *cx.render;
191    ctx.set_fill_color(if hot { st.thumb_hot } else { st.thumb });
192    ctx.begin_path();
193    ctx.rounded_rect(th.x, th.y, th.width, th.height, th.width / 2.0);
194    ctx.fill();
195}
196
197    };
198}
199
200scroll_fns!(PanelCx, scroll_begin, scroll_end, false);
201scroll_fns!(OverlayCx, scroll_begin_overlay, scroll_end_overlay, true);
202
203#[cfg(test)]
204mod tests {
205    use super::*;
206
207    fn e(id: &str, r: Rect, up: bool, down: bool, ov: bool) -> Entry {
208        (id.to_string(), r, up, down, ov, true)
209    }
210
211    #[test]
212    fn key_goes_to_active_then_hovered_and_chains_out() {
213        let page = Rect::new(0.0, 0.0, 1000.0, 800.0);
214        let side = Rect::new(0.0, 0.0, 200.0, 800.0);
215        let inner = Rect::new(300.0, 100.0, 400.0, 300.0);
216        let mut c = Chain { prev: vec![e("page", page, true, true, false), e("side", side, false, true, false), e("inner", inner, true, false, false)], ..Chain::default() };
217        // Hovered, innermost first.
218        assert_eq!(key_owner(&c, Some((50.0, 50.0)), ScrollKey::PageDown).as_deref(), Some("side"));
219        assert_eq!(key_owner(&c, Some((400.0, 200.0)), ScrollKey::LineUp).as_deref(), Some("inner"));
220        // `inner` is at its end: Down chains to the page around it.
221        assert_eq!(key_owner(&c, Some((400.0, 200.0)), ScrollKey::LineDown).as_deref(), Some("page"));
222        // `side` is at its top: Home chains out to the page around it.
223        assert_eq!(key_owner(&c, Some((50.0, 50.0)), ScrollKey::Home).as_deref(), Some("page"));
224        // A container that cannot move hands the key to the document.
225        let mut d = Chain { prev: vec![e("side", side, false, false, false), e("thread", Rect::new(200.0, 0.0, 800.0, 800.0), true, false, false)], ..Chain::default() };
226        d.active = Some("side".into());
227        assert_eq!(key_owner(&d, Some((600.0, 400.0)), ScrollKey::PageUp).as_deref(), Some("thread"));
228        // The clicked container wins over the hovered one.
229        c.active = Some("inner".into());
230        assert_eq!(key_owner(&c, Some((50.0, 50.0)), ScrollKey::End).as_deref(), Some("page"));
231        assert_eq!(key_owner(&c, None, ScrollKey::PageUp).as_deref(), Some("inner"));
232        // Nothing hovered: the largest container (the document).
233        c.active = None;
234        assert_eq!(key_owner(&c, Some((900.0, 900.0)), ScrollKey::PageDown).as_deref(), Some("page"));
235        // An overlay's containers take keys alone.
236        c.prev.push(e("dlg", Rect::new(300.0, 300.0, 300.0, 200.0), true, true, true));
237        assert_eq!(key_owner(&c, Some((50.0, 50.0)), ScrollKey::PageDown).as_deref(), Some("dlg"), "over the scrim: the dialog");
238        assert_eq!(key_owner(&c, Some((400.0, 400.0)), ScrollKey::PageDown).as_deref(), Some("dlg"));
239        c.active = Some("dlg".into());
240        assert_eq!(key_owner(&c, None, ScrollKey::PageDown).as_deref(), Some("dlg"));
241    }
242
243    #[test]
244    fn overscroll_contain_stops_the_chain() {
245        let page = Rect::new(0.0, 0.0, 1000.0, 800.0);
246        let inner = Rect::new(300.0, 100.0, 400.0, 300.0);
247        let mut c = Chain { prev: vec![e("page", page, true, true, false), e("inner", inner, true, false, false)], ..Chain::default() };
248        assert_eq!(key_owner(&c, Some((400.0, 200.0)), ScrollKey::LineDown).as_deref(), Some("page"));
249        assert!(wheel_owner(&c, "page", (400.0, 200.0), -1.0));
250        c.prev[1].5 = false;
251        assert_eq!(key_owner(&c, Some((400.0, 200.0)), ScrollKey::LineDown), None);
252        assert!(!wheel_owner(&c, "page", (400.0, 200.0), -1.0) && wheel_owner(&c, "inner", (400.0, 200.0), -1.0));
253        // What it can take, it still takes.
254        assert_eq!(key_owner(&c, Some((400.0, 200.0)), ScrollKey::LineUp).as_deref(), Some("inner"));
255    }
256}