Skip to main content

cosmic_applet_avestruz/views/components/
scroll_position.rs

1// SPDX-License-Identifier: MIT
2
3//! How far a scroller is scrolled, kept where it outlives the widget tree,
4//! and the scroller the views' lists are shown in.
5//!
6//! Another view shown in a list's place throws the scroller's own state
7//! away, and so does closing the popup. A [`ScrollPosition`], the first
8//! thing in a scroller, keeps how far it is scrolled in a cell the model
9//! owns; coming back, the view scrolls to where the cell says it was.
10//!
11//! A scroller that is new, as every one is in a popup that just opened,
12//! does that by itself: [`Restoring`], around it, scrolls it to where the
13//! cell says before it is first drawn. Nobody sees its top go by, and no
14//! message has to find a window that may not be there yet.
15//!
16//! It takes no room and draws nothing. What it keeps is how far its own
17//! place is above the top of what is in view, which, for the first thing in
18//! a scroller, is how far the scroller is scrolled.
19//!
20//! Over the row of a long note that shows in full, the same thing keeps
21//! how far the top of that row is scrolled out of view: what the list is
22//! scrolled back by when the note is cut again (see
23//! [`Expanded`](crate::state::Expanded)).
24//!
25//! ```mermaid
26//! sequenceDiagram
27//!     participant model as The model's cell
28//!     participant position as ScrollPosition
29//!     participant scroller as The scroller
30//!     Note over scroller: the reader scrolls
31//!     scroller->>position: drawn, so far above the top of the view
32//!     position->>model: that far
33//!     Note over scroller: the popup closes: the scroller and its state are gone
34//!     Note over scroller: the popup opens: a new scroller, at its top
35//!     model->>scroller: scrolled to where the cell says, before the first frame (Restoring)
36//!     Note over scroller: the reader sees the list where it was
37//! ```
38//!
39//! Why the place has to be kept at all, and what else is kept the same
40//! way, is in [`crate::guide::architecture`].
41
42use std::cell::Cell;
43
44use cosmic::iced::core::layout;
45use cosmic::iced::core::mouse;
46use cosmic::iced::core::overlay;
47use cosmic::iced::core::renderer;
48use cosmic::iced::core::widget::operation::scrollable::{AbsoluteOffset, scroll_to};
49use cosmic::iced::core::widget::tree::{self, Tree};
50use cosmic::iced::core::widget::{Id, Operation};
51use cosmic::iced::core::{Clipboard, Element, Event, Layout, Length, Rectangle, Shell, Size, Vector, Widget};
52use cosmic::iced::widget::scrollable;
53use cosmic::widget::{self, container};
54
55use crate::messages::Message;
56use crate::views::components::{LIST_PADDING_LEFT, LIST_PADDING_RIGHT, LIST_SCROLL_ID};
57
58/// `content`, a view's list and whatever it has above and under it, in the
59/// scroller the views share, which keeps `position` at how far it is
60/// scrolled, and starts out there.
61///
62/// The scroller is as tall as what is in it, up to the room there is for
63/// it: what the popup may be tall (see `popup_max_height`), less whatever
64/// the view puts above it.
65pub fn list_scroller<'a>(
66    position: &'a Cell<f32>,
67    content: impl Into<cosmic::Element<'a, Message>>,
68) -> cosmic::Element<'a, Message> {
69    let content = widget::Column::new().push(ScrollPosition::new(position)).push(content);
70    // Room on the right for the scrollbar, which is drawn over the content.
71    // No `on_scroll`: a list itself says when its end is near, and why the
72    // scrollable isn't asked is in the list's module docs.
73    let scroller = scrollable(container(content).width(Length::Fill).padding([0, LIST_PADDING_RIGHT, 0, LIST_PADDING_LEFT]))
74        .id(LIST_SCROLL_ID.clone())
75        .height(Length::Shrink);
76
77    Restoring::new(position, LIST_SCROLL_ID.clone(), scroller).into()
78}
79
80/// Whether a [`Restoring`] has put its scroller where it was. Widget state:
81/// it starts over with the widget tree, as the scroller's own place does.
82#[derive(Default)]
83struct Restored(bool);
84
85/// `content`, which holds the scroller `scroller`, scrolled to `position`
86/// before it is first drawn. After that the scroller is its user's.
87pub struct Restoring<'a, Message, Theme, Renderer> {
88    position: &'a Cell<f32>,
89    scroller: Id,
90    content: Element<'a, Message, Theme, Renderer>,
91}
92
93impl<'a, Message, Theme, Renderer> Restoring<'a, Message, Theme, Renderer> {
94    pub fn new(position: &'a Cell<f32>, scroller: Id, content: impl Into<Element<'a, Message, Theme, Renderer>>) -> Self {
95        Self { position, scroller, content: content.into() }
96    }
97}
98
99impl<Message, Theme, Renderer: renderer::Renderer> Widget<Message, Theme, Renderer> for Restoring<'_, Message, Theme, Renderer> {
100    fn tag(&self) -> tree::Tag {
101        tree::Tag::of::<Restored>()
102    }
103
104    fn state(&self) -> tree::State {
105        tree::State::new(Restored::default())
106    }
107
108    fn children(&self) -> Vec<Tree> {
109        vec![Tree::new(&self.content)]
110    }
111
112    fn diff(&mut self, tree: &mut Tree) {
113        tree.diff_children(std::slice::from_mut(&mut self.content));
114    }
115
116    fn size(&self) -> Size<Length> {
117        self.content.as_widget().size()
118    }
119
120    fn layout(&mut self, tree: &mut Tree, renderer: &Renderer, limits: &layout::Limits) -> layout::Node {
121        match tree.children.first_mut() {
122            Some(child) => self.content.as_widget_mut().layout(child, renderer, limits),
123            None => layout::Node::new(Size::ZERO),
124        }
125    }
126
127    fn update(
128        &mut self,
129        tree: &mut Tree,
130        event: &Event,
131        layout: Layout<'_>,
132        cursor: mouse::Cursor,
133        renderer: &Renderer,
134        clipboard: &mut dyn Clipboard,
135        shell: &mut Shell<'_, Message>,
136        viewport: &Rectangle,
137    ) {
138        let first_time = !std::mem::replace(&mut tree.state.downcast_mut::<Restored>().0, true);
139        let Some(child) = tree.children.first_mut() else {
140            return;
141        };
142        // Before the content hears of anything: what keeps the place would
143        // otherwise put down where a new scroller starts, which is its top.
144        let place = self.position.get();
145        if first_time && place > 0.0 {
146            let mut to_place = scroll_to::<()>(self.scroller.clone(), AbsoluteOffset { x: None, y: Some(place) });
147            self.content.as_widget_mut().operate(child, layout, renderer, &mut to_place);
148        }
149        self.content.as_widget_mut().update(child, event, layout, cursor, renderer, clipboard, shell, viewport);
150    }
151
152    fn draw(
153        &self,
154        tree: &Tree,
155        renderer: &mut Renderer,
156        theme: &Theme,
157        style: &renderer::Style,
158        layout: Layout<'_>,
159        cursor: mouse::Cursor,
160        viewport: &Rectangle,
161    ) {
162        if let Some(child) = tree.children.first() {
163            self.content.as_widget().draw(child, renderer, theme, style, layout, cursor, viewport);
164        }
165    }
166
167    fn mouse_interaction(
168        &self,
169        tree: &Tree,
170        layout: Layout<'_>,
171        cursor: mouse::Cursor,
172        viewport: &Rectangle,
173        renderer: &Renderer,
174    ) -> mouse::Interaction {
175        match tree.children.first() {
176            Some(child) => self.content.as_widget().mouse_interaction(child, layout, cursor, viewport, renderer),
177            None => mouse::Interaction::None,
178        }
179    }
180
181    fn operate(&mut self, tree: &mut Tree, layout: Layout<'_>, renderer: &Renderer, operation: &mut dyn Operation) {
182        if let Some(child) = tree.children.first_mut() {
183            self.content.as_widget_mut().operate(child, layout, renderer, operation);
184        }
185    }
186
187    fn overlay<'b>(
188        &'b mut self,
189        tree: &'b mut Tree,
190        layout: Layout<'b>,
191        renderer: &Renderer,
192        viewport: &Rectangle,
193        translation: Vector,
194    ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
195        let child = tree.children.first_mut()?;
196        self.content.as_widget_mut().overlay(child, layout, renderer, viewport, translation)
197    }
198}
199
200impl<'a, Message: 'a, Theme: 'a, Renderer: renderer::Renderer + 'a> From<Restoring<'a, Message, Theme, Renderer>>
201    for Element<'a, Message, Theme, Renderer>
202{
203    fn from(restoring: Restoring<'a, Message, Theme, Renderer>) -> Self {
204        Element::new(restoring)
205    }
206}
207
208/// Keeps `position` at how far its own place is above the top of what is
209/// in view: for the first thing in a scroller, how far that is scrolled.
210pub struct ScrollPosition<'a> {
211    position: &'a Cell<f32>,
212}
213
214impl<'a> ScrollPosition<'a> {
215    pub fn new(position: &'a Cell<f32>) -> Self {
216        Self { position }
217    }
218}
219
220impl<Message, Theme, Renderer: renderer::Renderer> Widget<Message, Theme, Renderer> for ScrollPosition<'_> {
221    /// As tall as its content, which is nothing. Not a fixed height of
222    /// zero: a column leaves out a child that says it takes no room.
223    fn size(&self) -> Size<Length> {
224        Size::new(Length::Fill, Length::Shrink)
225    }
226
227    fn layout(&mut self, _tree: &mut Tree, _renderer: &Renderer, limits: &layout::Limits) -> layout::Node {
228        layout::Node::new(Size::new(limits.max().width, 0.0))
229    }
230
231    fn update(
232        &mut self,
233        _tree: &mut Tree,
234        _event: &Event,
235        layout: Layout<'_>,
236        _cursor: mouse::Cursor,
237        _renderer: &Renderer,
238        _clipboard: &mut dyn Clipboard,
239        _shell: &mut Shell<'_, Message>,
240        viewport: &Rectangle,
241    ) {
242        self.position.set((viewport.y - layout.position().y).max(0.0));
243    }
244
245    fn draw(
246        &self,
247        _tree: &Tree,
248        _renderer: &mut Renderer,
249        _theme: &Theme,
250        _style: &renderer::Style,
251        _layout: Layout<'_>,
252        _cursor: mouse::Cursor,
253        _viewport: &Rectangle,
254    ) {
255    }
256}
257
258impl<'a, Message, Theme, Renderer: renderer::Renderer> From<ScrollPosition<'a>> for Element<'a, Message, Theme, Renderer> {
259    fn from(position: ScrollPosition<'a>) -> Self {
260        Element::new(position)
261    }
262}
263
264/// Keeps `place` at how far down what is in a scroller its own place is:
265/// put before a list that is not the first thing in its scroller, how far
266/// the scroller is scrolled when the list's first row is at the top of
267/// what is in view.
268///
269/// It goes by `scrolled`, which the scroller's [`ScrollPosition`] keeps:
270/// what is in view starts that far down what is in the scroller, so the
271/// top of that is known, and how far under it this is. It takes no room
272/// and draws nothing, as a [`ScrollPosition`] does.
273pub struct PlaceInScroller<'a> {
274    scrolled: &'a Cell<f32>,
275    place: &'a Cell<f32>,
276}
277
278impl<'a> PlaceInScroller<'a> {
279    pub fn new(scrolled: &'a Cell<f32>, place: &'a Cell<f32>) -> Self {
280        Self { scrolled, place }
281    }
282}
283
284impl<Message, Theme, Renderer: renderer::Renderer> Widget<Message, Theme, Renderer> for PlaceInScroller<'_> {
285    /// As a [`ScrollPosition`]: as tall as its content, which is nothing.
286    fn size(&self) -> Size<Length> {
287        Size::new(Length::Fill, Length::Shrink)
288    }
289
290    fn layout(&mut self, _tree: &mut Tree, _renderer: &Renderer, limits: &layout::Limits) -> layout::Node {
291        layout::Node::new(Size::new(limits.max().width, 0.0))
292    }
293
294    fn update(
295        &mut self,
296        _tree: &mut Tree,
297        _event: &Event,
298        layout: Layout<'_>,
299        _cursor: mouse::Cursor,
300        _renderer: &Renderer,
301        _clipboard: &mut dyn Clipboard,
302        _shell: &mut Shell<'_, Message>,
303        viewport: &Rectangle,
304    ) {
305        let top = viewport.y - self.scrolled.get();
306        self.place.set((layout.position().y - top).max(0.0));
307    }
308
309    fn draw(
310        &self,
311        _tree: &Tree,
312        _renderer: &mut Renderer,
313        _theme: &Theme,
314        _style: &renderer::Style,
315        _layout: Layout<'_>,
316        _cursor: mouse::Cursor,
317        _viewport: &Rectangle,
318    ) {
319    }
320}
321
322impl<'a, Message, Theme, Renderer: renderer::Renderer> From<PlaceInScroller<'a>> for Element<'a, Message, Theme, Renderer> {
323    fn from(place: PlaceInScroller<'a>) -> Self {
324        Element::new(place)
325    }
326}
327
328#[cfg(test)]
329mod tests {
330    use super::ScrollPosition;
331    use cosmic::iced::core::widget::Tree;
332    use cosmic::iced::core::{Element, Event, Layout, Point, Rectangle, Shell, Size, clipboard, layout, mouse, window};
333    use std::cell::Cell;
334
335    #[test]
336    fn it_takes_no_room_and_keeps_how_far_the_scroller_is_scrolled() {
337        let position = Cell::new(0.0);
338        let mut element: Element<'_, (), (), ()> = ScrollPosition::new(&position).into();
339        assert!(!element.as_widget().size_hint().is_void(), "a column would leave it out");
340        let mut tree = Tree::new(element.as_widget());
341        let limits = layout::Limits::new(Size::ZERO, Size::new(300.0, f32::INFINITY));
342        let node = element.as_widget_mut().layout(&mut tree, &(), &limits);
343        assert_eq!(node.size(), Size::new(300.0, 0.0));
344
345        // The scroller's content starts 40 down the window, and is scrolled
346        // 250: what is in view starts at 290.
347        let node = node.move_to(Point::new(0.0, 40.0));
348        let mut scrolled_to = |y: f32| {
349            let mut messages = Vec::new();
350            element.as_widget_mut().update(
351                &mut tree,
352                &Event::Window(window::Event::RedrawRequested(std::time::Instant::now())),
353                Layout::new(&node),
354                mouse::Cursor::Unavailable,
355                &(),
356                &mut clipboard::Null,
357                &mut Shell::new(&mut messages),
358                &Rectangle::new(Point::new(0.0, 40.0 + y), Size::new(300.0, 500.0)),
359            );
360            position.get()
361        };
362        assert_eq!(scrolled_to(250.0), 250.0);
363        assert_eq!(scrolled_to(0.0), 0.0);
364    }
365
366    #[test]
367    fn what_is_under_something_in_a_scroller_knows_how_far_down_it_is_however_far_that_is_scrolled() {
368        use super::PlaceInScroller;
369
370        let (scrolled, place) = (Cell::new(0.0), Cell::new(0.0));
371        let mut element: Element<'_, (), (), ()> = PlaceInScroller::new(&scrolled, &place).into();
372        assert!(!element.as_widget().size_hint().is_void(), "a column would leave it out");
373        let mut tree = Tree::new(element.as_widget());
374        let limits = layout::Limits::new(Size::ZERO, Size::new(300.0, f32::INFINITY));
375        let node = element.as_widget_mut().layout(&mut tree, &(), &limits);
376        assert_eq!(node.size(), Size::new(300.0, 0.0));
377
378        // The scroller's content starts 40 down the window, and this is
379        // 180 down that, under whatever is above the list.
380        let node = node.move_to(Point::new(0.0, 40.0 + 180.0));
381        let mut scrolled_to = |y: f32| {
382            // As the scroller's `ScrollPosition`, before it, has kept it.
383            scrolled.set(y);
384            let mut messages = Vec::new();
385            element.as_widget_mut().update(
386                &mut tree,
387                &Event::Window(window::Event::RedrawRequested(std::time::Instant::now())),
388                Layout::new(&node),
389                mouse::Cursor::Unavailable,
390                &(),
391                &mut clipboard::Null,
392                &mut Shell::new(&mut messages),
393                &Rectangle::new(Point::new(0.0, 40.0 + y), Size::new(300.0, 500.0)),
394            );
395            place.get()
396        };
397        assert_eq!(scrolled_to(0.0), 180.0);
398        assert_eq!(scrolled_to(120.0), 180.0, "scrolled short of it");
399        assert_eq!(scrolled_to(900.0), 180.0, "scrolled past it");
400    }
401
402    /// One frame of `element` in a window 300 by 500: laid out, and told
403    /// it is about to be drawn, as the runtime does before every frame.
404    fn frame(element: &mut cosmic::Element<'_, crate::messages::Message>, tree: &mut Tree) {
405        let renderer = crate::views::components::testing::renderer();
406        let limits = layout::Limits::new(Size::ZERO, Size::new(300.0, 500.0));
407        let node = element.as_widget_mut().layout(tree, &renderer, &limits);
408        let mut messages = Vec::new();
409        element.as_widget_mut().update(
410            tree,
411            &Event::Window(window::Event::RedrawRequested(std::time::Instant::now())),
412            Layout::new(&node),
413            mouse::Cursor::Unavailable,
414            &renderer,
415            &mut clipboard::Null,
416            &mut Shell::new(&mut messages),
417            &Rectangle::new(Point::ORIGIN, node.size()),
418        );
419    }
420
421    /// Something far taller than the popup, to scroll.
422    fn tall<'a>() -> cosmic::Element<'a, crate::messages::Message> {
423        cosmic::widget::Space::new().width(cosmic::iced::Length::Fill).height(5_000).into()
424    }
425
426    #[test]
427    fn a_new_scroller_starts_where_the_last_one_was_left() {
428        // The popup closed with its list scrolled to 420, and opens again:
429        // a new widget tree, and a scroller that knows of no place.
430        let position = Cell::new(420.0);
431        let mut element = super::list_scroller(&position, tall());
432        let mut tree = Tree::new(element.as_widget());
433
434        frame(&mut element, &mut tree);
435        assert_eq!(position.get(), 420.0, "scrolled there before its first frame, not left at its top");
436
437        // After that it is its user's: what the cell says is what the
438        // scroller does, not the other way about.
439        position.set(100.0);
440        let mut element = super::list_scroller(&position, tall());
441        tree.diff(element.as_widget_mut());
442        frame(&mut element, &mut tree);
443        assert_eq!(position.get(), 420.0);
444    }
445
446    /// How tall a view lays out in a popup that may be `popup` tall: a
447    /// header 40 tall, and under it the scroller, with `content` `content`
448    /// tall in it.
449    fn view_height(content: f32, popup: f32) -> f32 {
450        let position = Cell::new(0.0);
451        let space = |height: f32| cosmic::widget::Space::new().width(cosmic::iced::Length::Fill).height(height);
452        let mut element: cosmic::Element<'_, crate::messages::Message> =
453            cosmic::widget::Column::new().push(space(40.0)).push(super::list_scroller(&position, space(content))).into();
454        let mut tree = Tree::new(element.as_widget());
455        let renderer = crate::views::components::testing::renderer();
456        let limits = layout::Limits::new(Size::ZERO, Size::new(300.0, popup));
457        element.as_widget_mut().layout(&mut tree, &renderer, &limits).size().height
458    }
459
460    #[test]
461    fn a_long_list_makes_the_popup_as_tall_as_it_may_be_and_a_short_one_as_tall_as_itself() {
462        // However tall the popup may be: no height of its own holds the
463        // scroller back from the room there is.
464        for popup in [450.0, 600.0, 952.0, 1_620.0] {
465            assert_eq!(view_height(5_000.0, popup), popup, "a long list fills a popup that may be {popup} tall");
466        }
467        // With little in it, the popup is as tall as its header and that.
468        assert_eq!(view_height(120.0, 952.0), 160.0);
469        assert_eq!(view_height(912.0, 952.0), 952.0, "what just fits is not scrolled");
470    }
471
472    #[test]
473    fn a_new_scroller_that_was_never_scrolled_starts_at_its_top() {
474        let position = Cell::new(0.0);
475        let mut element = super::list_scroller(&position, tall());
476        let mut tree = Tree::new(element.as_widget());
477        frame(&mut element, &mut tree);
478        assert_eq!(position.get(), 0.0);
479    }
480}