Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add manual scrolling #81

Merged
merged 18 commits into from
Dec 29, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions egui/src/align.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,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,
}
}
Comment on lines +33 to +39
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't know if this is the best place to add this.

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the right place! Maybe could be called simply to_factor

}

impl Default for Align {
Expand Down
35 changes: 34 additions & 1 deletion egui/src/containers/scroll_area.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ pub struct ScrollArea {
max_height: f32,
always_show_scroll: bool,
id_source: Option<Id>,
offset: Option<Vec2>,
}

impl ScrollArea {
Expand All @@ -45,6 +46,7 @@ impl ScrollArea {
max_height,
always_show_scroll: false,
id_source: None,
offset: None,
}
}

Expand All @@ -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 {
Expand All @@ -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.
Expand Down Expand Up @@ -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 {
Expand Down
3 changes: 3 additions & 0 deletions egui/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand All @@ -47,6 +48,7 @@ impl Default for FrameState {
available_rect: Rect::invalid(),
unused_rect: Rect::invalid(),
used_by_panels: Rect::invalid(),
scroll_target: None,
}
}
}
Expand All @@ -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.
Expand Down
6 changes: 3 additions & 3 deletions egui/src/demos/demo_window.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ pub struct DemoWindow {
num_columns: usize,

widgets: Widgets,
scrolls: Scrolls,
colors: ColorWidgets,
layout: LayoutDemo,
tree: Tree,
Expand All @@ -18,6 +19,7 @@ impl Default for DemoWindow {
DemoWindow {
num_columns: 2,

scrolls: Default::default(),
widgets: Default::default(),
colors: Default::default(),
layout: Default::default(),
Expand Down Expand Up @@ -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);
});
lucaspoffo marked this conversation as resolved.
Show resolved Hide resolved
self.scrolls.ui(ui);
});

CollapsingHeader::new("Resize")
Expand Down
3 changes: 2 additions & 1 deletion egui/src/demos/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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.";
Expand Down
87 changes: 87 additions & 0 deletions egui/src/demos/scrolls.rs
Original file line number Diff line number Diff line change
@@ -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));
}
});
}
}
21 changes: 20 additions & 1 deletion egui/src/types.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::{math::Rect, CtxRef, Id, LayerId, Ui};
use crate::{lerp, math::Rect, Align, CtxRef, Id, LayerId, Ui};

// ----------------------------------------------------------------------------

Expand Down Expand Up @@ -159,6 +159,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 {
Expand Down
22 changes: 22 additions & 0 deletions egui/src/ui.rs
Original file line number Diff line number Diff line change
Expand Up @@ -584,6 +584,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());
/// }
/// });
/// ```
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good example 👍

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
Expand Down