Skip to main content

egui_kit/extract/
scroll.rs

1//! [`Scroll`]: a scroll area whose position the router manages like a browser.
2
3use core::cell::Cell;
4
5use egui::Ui;
6
7use super::FromView;
8use crate::page::{Frame, ViewContext};
9
10/// The scroll position of a page.
11#[derive(Debug, Default)]
12pub(crate) struct PageScroll {
13    /// Applied once, on the first frame of the page.
14    pub(crate) restore: Cell<Option<f32>>,
15    pub(crate) offset: Cell<f32>,
16}
17
18/// The page's scroll area, an extractor: new pages start at the top (unless navigated to with
19/// [`GotoOptions::no_scroll`](crate::GotoOptions::no_scroll)), and back/forward restores where
20/// the user was.
21///
22/// ```no_run
23/// # use egui_kit::extract::Scroll;
24/// fn view(ui: &mut egui::Ui, scroll: Scroll) {
25///     scroll.show(ui, |ui| {
26///         for i in 0..100 {
27///             ui.label(format!("Row {i}"));
28///         }
29///     });
30/// }
31/// ```
32#[derive(Clone, Copy)]
33pub struct Scroll<'f> {
34    pub(crate) frame: &'f Frame<'f>,
35}
36
37impl<S: 'static, D> FromView<S, D> for Scroll<'_> {
38    type Item<'f> = Scroll<'f>;
39
40    fn from_view<'f>(cx: &'f ViewContext<'_, S>) -> Scroll<'f> {
41        Scroll { frame: cx.frame() }
42    }
43}
44
45impl Scroll<'_> {
46    /// Shows a vertical [`egui::ScrollArea`] with the page's content. Use it at most once per page.
47    pub fn show<R>(&self, ui: &mut Ui, add_contents: impl FnOnce(&mut Ui) -> R) -> R {
48        let frame = self.frame;
49        let mut area = egui::ScrollArea::vertical()
50            .id_salt(("egui_kit_page_scroll", frame.page_id))
51            .auto_shrink(false);
52        // An outgoing page is drawn in a different `Ui`, so it keeps its position explicitly.
53        let offset = if frame.outgoing {
54            Some(frame.scroll.offset.get())
55        } else {
56            frame.scroll.restore.take()
57        };
58        if let Some(offset) = offset {
59            area = area.vertical_scroll_offset(offset);
60        }
61        let output = area.show(ui, add_contents);
62        if !frame.outgoing {
63            frame.scroll.offset.set(output.state.offset.y);
64        }
65        output.inner
66    }
67}