From 19b4d87c654f7c502dc61fa1e4fa0bd3914c28cc Mon Sep 17 00:00:00 2001 From: lucaspoffo <35241085+lucaspoffo@users.noreply.github.com> Date: Tue, 29 Dec 2020 08:18:17 -0300 Subject: [PATCH] Add ui.scroll_to_cursor and response.scroll_to_me (#81) Contributed by https://github.com/lucaspoffo --- egui/src/align.rs | 8 +++ egui/src/containers/scroll_area.rs | 35 +++++++++++- egui/src/context.rs | 3 ++ egui/src/demos/demo_window.rs | 6 +-- egui/src/demos/mod.rs | 3 +- egui/src/demos/scrolls.rs | 87 ++++++++++++++++++++++++++++++ egui/src/types.rs | 21 +++++++- egui/src/ui.rs | 22 ++++++++ 8 files changed, 179 insertions(+), 6 deletions(-) create mode 100644 egui/src/demos/scrolls.rs diff --git a/egui/src/align.rs b/egui/src/align.rs index 342a9354..fd54ab8c 100644 --- a/egui/src/align.rs +++ b/egui/src/align.rs @@ -34,6 +34,14 @@ impl Align { pub fn bottom() -> Self { Self::Max } + + pub(crate) fn scroll_center_factor(&self) -> f32 { + match self { + Self::Min => 0.0, + Self::Center => 0.5, + Self::Max => 1.0, + } + } } impl Default for Align { diff --git a/egui/src/containers/scroll_area.rs b/egui/src/containers/scroll_area.rs index d1fd13ac..0fce2c4d 100644 --- a/egui/src/containers/scroll_area.rs +++ b/egui/src/containers/scroll_area.rs @@ -31,6 +31,7 @@ pub struct ScrollArea { max_height: f32, always_show_scroll: bool, id_source: Option, + offset: Option, } impl ScrollArea { @@ -45,6 +46,7 @@ impl ScrollArea { max_height, always_show_scroll: false, id_source: None, + offset: None, } } @@ -60,6 +62,15 @@ impl ScrollArea { self.id_source = Some(Id::new(id_source)); self } + + /// Set the vertical scroll offset position. + /// + /// See also: [`Ui::scroll_to_cursor`](crate::ui::Ui::scroll_to_cursor) and + /// [`Response::scroll_to_me`](crate::types::Response::scroll_to_me) + pub fn scroll_offset(mut self, offset: f32) -> Self { + self.offset = Some(Vec2::new(0.0, offset)); + self + } } struct Prepared { @@ -77,19 +88,24 @@ impl ScrollArea { max_height, always_show_scroll, id_source, + offset, } = self; let ctx = ui.ctx().clone(); let id_source = id_source.unwrap_or_else(|| Id::new("scroll_area")); let id = ui.make_persistent_id(id_source); - let state = ctx + let mut state = ctx .memory() .scroll_areas .get(&id) .cloned() .unwrap_or_default(); + if let Some(offset) = offset { + state.offset = offset; + } + // content: size of contents (generally large; that's why we want scroll bars) // outer: size of scroll area including scroll bar(s) // inner: excluding scroll bar(s). The area we clip the contents to. @@ -155,6 +171,23 @@ impl Prepared { let content_size = content_ui.min_size(); + // We take the scroll target so only this ScrollArea will use it. + let scroll_target = content_ui.ctx().frame_state().scroll_target.take(); + if let Some((scroll_y, align)) = scroll_target { + let center_factor = align.scroll_center_factor(); + + let top = content_ui.min_rect().top(); + let visible_range = top..=top + content_ui.clip_rect().height(); + let offset_y = scroll_y - lerp(visible_range, center_factor); + + let mut spacing = ui.style().spacing.item_spacing.y; + + // Depending on the alignment we need to add or subtract the spacing + spacing *= remap(center_factor, 0.0..=1.0, -1.0..=1.0); + + state.offset.y = offset_y + spacing; + } + let width = if inner_rect.width().is_finite() { inner_rect.width().max(content_size.x) // Expand width to fit content } else { diff --git a/egui/src/context.rs b/egui/src/context.rs index 29f65aad..cdc14661 100644 --- a/egui/src/context.rs +++ b/egui/src/context.rs @@ -38,6 +38,7 @@ pub(crate) struct FrameState { /// How much space is used by panels. used_by_panels: Rect, + pub(crate) scroll_target: Option<(f32, Align)>, // TODO: move some things from `Memory` to here } @@ -47,6 +48,7 @@ impl Default for FrameState { available_rect: Rect::invalid(), unused_rect: Rect::invalid(), used_by_panels: Rect::invalid(), + scroll_target: None, } } } @@ -56,6 +58,7 @@ impl FrameState { self.available_rect = input.screen_rect(); self.unused_rect = input.screen_rect(); self.used_by_panels = Rect::nothing(); + self.scroll_target = None; } /// How much space is still available after panels has been added. diff --git a/egui/src/demos/demo_window.rs b/egui/src/demos/demo_window.rs index 5ab08f5a..da5836ea 100644 --- a/egui/src/demos/demo_window.rs +++ b/egui/src/demos/demo_window.rs @@ -7,6 +7,7 @@ pub struct DemoWindow { num_columns: usize, widgets: Widgets, + scrolls: Scrolls, colors: ColorWidgets, layout: LayoutDemo, tree: Tree, @@ -18,6 +19,7 @@ impl Default for DemoWindow { DemoWindow { num_columns: 2, + scrolls: Default::default(), widgets: Default::default(), colors: Default::default(), layout: Default::default(), @@ -68,9 +70,7 @@ impl DemoWindow { CollapsingHeader::new("Scroll area") .default_open(false) .show(ui, |ui| { - ScrollArea::from_max_height(200.0).show(ui, |ui| { - ui.label(LOREM_IPSUM_LONG); - }); + self.scrolls.ui(ui); }); CollapsingHeader::new("Resize") diff --git a/egui/src/demos/mod.rs b/egui/src/demos/mod.rs index 3febdf53..3d1bd44b 100644 --- a/egui/src/demos/mod.rs +++ b/egui/src/demos/mod.rs @@ -12,6 +12,7 @@ pub mod font_contents_emoji; pub mod font_contents_ubuntu; mod fractal_clock; mod painting; +mod scrolls; mod sliders; mod tests; pub mod toggle_switch; @@ -20,7 +21,7 @@ mod widgets; pub use { app::*, color_test::ColorTest, dancing_strings::DancingStrings, demo_window::DemoWindow, demo_windows::*, drag_and_drop::*, font_book::FontBook, fractal_clock::FractalClock, - painting::Painting, sliders::Sliders, tests::Tests, widgets::Widgets, + painting::Painting, scrolls::Scrolls, sliders::Sliders, tests::Tests, widgets::Widgets, }; pub const LOREM_IPSUM: &str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."; diff --git a/egui/src/demos/scrolls.rs b/egui/src/demos/scrolls.rs new file mode 100644 index 00000000..3451dacb --- /dev/null +++ b/egui/src/demos/scrolls.rs @@ -0,0 +1,87 @@ +use crate::{color::*, demos::LOREM_IPSUM_LONG, *}; + +#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] +#[cfg_attr(feature = "serde", serde(default))] +pub struct Scrolls { + track_item: usize, + tracking: bool, + offset: f32, +} + +impl Default for Scrolls { + fn default() -> Self { + Self { + track_item: 25, + tracking: true, + offset: 0.0, + } + } +} + +impl Scrolls { + pub fn ui(&mut self, ui: &mut Ui) { + ScrollArea::from_max_height(200.0).show(ui, |ui| { + ui.label(LOREM_IPSUM_LONG); + ui.label(LOREM_IPSUM_LONG); + }); + + ui.separator(); + + ui.horizontal(|ui| { + ui.checkbox(&mut self.tracking, "Track") + .on_hover_text("The scroll position will track the selected item"); + ui.add(Slider::usize(&mut self.track_item, 1..=50).text("Track Item")); + }); + let (scroll_offset, _) = ui.horizontal(|ui| { + let scroll_offset = ui.small_button("Scroll Offset").clicked; + ui.add(DragValue::f32(&mut self.offset).speed(1.0).suffix("px")); + scroll_offset + }); + + let scroll_top = ui.button("Scroll to top").clicked; + let scroll_bottom = ui.button("Scroll to bottom").clicked; + if scroll_bottom || scroll_top { + self.tracking = false; + } + + const TITLES: [&str; 3] = ["Top", "Middle", "Bottom"]; + const ALIGNS: [Align; 3] = [Align::Min, Align::Center, Align::Max]; + ui.columns(3, |cols| { + for (i, col) in cols.iter_mut().enumerate() { + col.colored_label(WHITE, TITLES[i]); + let mut scroll_area = ScrollArea::from_max_height(200.0).id_source(i); + if scroll_offset { + self.tracking = false; + scroll_area = scroll_area.scroll_offset(self.offset); + } + + let (current_scroll, max_scroll) = scroll_area.show(col, |ui| { + if scroll_top { + ui.scroll_to_cursor(Align::top()); + } + ui.vertical(|ui| { + for item in 1..=50 { + if self.tracking && item == self.track_item { + let response = ui.colored_label(YELLOW, format!("Item {}", item)); + response.scroll_to_me(ALIGNS[i]); + } else { + ui.label(format!("Item {}", item)); + } + } + }); + + if scroll_bottom { + ui.scroll_to_cursor(Align::bottom()); + } + + let margin = ui.style().visuals.clip_rect_margin; + ( + ui.clip_rect().top() - ui.min_rect().top() + margin, + ui.min_rect().height() - ui.clip_rect().height() + 2.0 * margin, + ) + }); + col.colored_label(WHITE, format!("{:.0}/{:.0}", current_scroll, max_scroll)); + } + }); + } +} diff --git a/egui/src/types.rs b/egui/src/types.rs index 01e3de29..e68ae13e 100644 --- a/egui/src/types.rs +++ b/egui/src/types.rs @@ -1,4 +1,4 @@ -use crate::{math::Rect, CtxRef, Id, LayerId, Ui}; +use crate::{lerp, math::Rect, Align, CtxRef, Id, LayerId, Ui}; // ---------------------------------------------------------------------------- @@ -171,6 +171,25 @@ impl Response { self.ctx .interact_with_hovered(self.layer_id, self.id, self.rect, sense, self.hovered) } + + /// Move the scroll to this UI with the specified alignment. + /// + /// ``` + /// # use egui::Align; + /// # let mut ui = &mut egui::Ui::__test(); + /// egui::ScrollArea::auto_sized().show(ui, |ui| { + /// for i in 0..1000 { + /// let response = ui.button(format!("Button {}", i)); + /// if response.clicked { + /// response.scroll_to_me(Align::Center); + /// } + /// } + /// }); + /// ``` + pub fn scroll_to_me(&self, align: Align) { + let scroll_target = lerp(self.rect.y_range(), align.scroll_center_factor()); + self.ctx.frame_state().scroll_target = Some((scroll_target, align)); + } } impl Response { diff --git a/egui/src/ui.rs b/egui/src/ui.rs index b6c8bba5..3e436e50 100644 --- a/egui/src/ui.rs +++ b/egui/src/ui.rs @@ -598,6 +598,28 @@ impl Ui { let painter = Painter::new(self.ctx().clone(), self.layer_id(), clip_rect); (response, painter) } + + /// Move the scroll to this cursor position with the specified alignment. + /// + /// ``` + /// # use egui::Align; + /// # let mut ui = &mut egui::Ui::__test(); + /// egui::ScrollArea::auto_sized().show(ui, |ui| { + /// let scroll_bottom = ui.button("Scroll to bottom.").clicked; + /// for i in 0..1000 { + /// ui.label(format!("Item {}", i)); + /// } + /// + /// if scroll_bottom { + /// ui.scroll_to_cursor(Align::bottom()); + /// } + /// }); + /// ``` + pub fn scroll_to_cursor(&mut self, align: Align) { + let scroll_y = self.region.cursor.y; + + self.ctx().frame_state().scroll_target = Some((scroll_y, align)); + } } /// # Adding widgets