Keep the current History step in view, with the scrollbar always shown

The History list opens at the newest step and scrolls the current step
into view when the history changes (a new step, undo, redo or a jump);
a tool, camera or selection change leaves a list the user scrolled where
it is. Rows are laid out only while visible. The list's scrollbar is a
solid 8 px bar in the theme's colours, shown even when the list fits.

Part of #890.
This commit is contained in:
Rebornim committed 2026-11-28 19:41:36 +00:00
1 parent 178e2d1928
commit 7f9ee780a2
4 files changed
+216 -10

No files matched your search

+53
View File
@@ -11,6 +11,59 @@ mod log_channel;
pub use log_channel::LogChannel;
/// The width of the History and Log lists' scrollbars
const LIST_SCROLLBAR_WIDTH: f32 = 8.0;
const LIST_SCROLLBAR_RADIUS: u8 = 3;
/// The air between a list's scrollbar and the list's edge, and between the rows and the scrollbar
const LIST_SCROLLBAR_OUTER_MARGIN: f32 = 2.0;
const LIST_SCROLLBAR_INNER_MARGIN: f32 = 1.0;
/// A newly focused row of a list scrolls in with a neighbour on each side: only shown rows are laid out, so Tab needs the next one there
pub(crate) fn reveal_focused_row(ui: &Ui, response: &egui::Response, row: egui::Rect) {
if response.gained_focus() {
// The shown width, so the list never moves sideways
let around = egui::Rect::from_x_y_ranges(ui.clip_rect().x_range(), row.y_range()).expand2(egui::vec2(0.0, row.height()));
ui.scroll_to_rect_animation(around, None, egui::style::ScrollAnimation::none());
}
}
/// Show `total_rows` rows of `row_height` in `area` under a solid, always shown, themed scrollbar
pub(crate) fn panel_rows<R>(
ui: &mut Ui,
area: egui::ScrollArea,
row_height: f32,
total_rows: usize,
add_rows: impl FnOnce(&mut Ui, std::ops::Range<usize>) -> R,
) -> egui::scroll_area::ScrollAreaOutput<R> {
let tokens = Tokens::get(ui.ctx());
let row_visuals = ui.visuals().clone();
ui.scope(|ui| {
ui.spacing_mut().item_spacing.y = 0.0;
ui.spacing_mut().scroll = egui::style::ScrollStyle {
bar_width: LIST_SCROLLBAR_WIDTH,
bar_outer_margin: LIST_SCROLLBAR_OUTER_MARGIN,
bar_inner_margin: LIST_SCROLLBAR_INNER_MARGIN,
..egui::style::ScrollStyle::solid()
};
let visuals = ui.visuals_mut();
visuals.extreme_bg_color = tokens.field;
// The thumb stands 3:1 or more off its track in every theme, brighter under the pointer
visuals.widgets.inactive.bg_fill = tokens.text_dim;
visuals.widgets.hovered.bg_fill = tokens.text;
visuals.widgets.active.bg_fill = tokens.text;
for widget in [&mut visuals.widgets.inactive, &mut visuals.widgets.hovered, &mut visuals.widgets.active] {
widget.corner_radius = egui::CornerRadius::same(LIST_SCROLLBAR_RADIUS);
}
area.scroll_bar_visibility(egui::scroll_area::ScrollBarVisibility::AlwaysVisible).show_rows(ui, row_height, total_rows, |ui, rows| {
*ui.visuals_mut() = row_visuals;
add_rows(ui, rows)
})
})
.inner
}
/// The entries a tab lists, as indices into the session log
fn listed(app: &TextureCraftApp, channel: LogChannel) -> Vec<usize> {
app.session.log.iter().enumerate().filter(|(_, entry)| channel_of(entry) == channel).map(|(index, _)| index).collect()
+4
View File
@@ -744,6 +744,9 @@ pub struct UiState {
/// Identity of the log that owns the selected rows.
#[serde(skip)]
pub log_id: u64,
/// The History panel's last shown container and steps (done, undone, newest name): a change scrolls to the current step
#[serde(skip)]
pub history_shown: Option<(egui::Id, usize, usize, Option<String>)>,
}
pub(crate) const MAX_RECENT_PROJECTS: u16 = 100;
@@ -912,6 +915,7 @@ impl Default for UiState {
log_selection: Default::default(),
log_anchor: None,
log_id: 0,
history_shown: None,
}
}
}
+31 -6
View File
@@ -260,15 +260,28 @@ pub(crate) fn history(app: &mut TextureCraftApp, ui: &mut Ui) {
let tokens = Tokens::get(ui.ctx());
let (done, undone) = (app.session.history_labels(), app.session.redo_labels());
let done_count = done.len() as i64;
let rows = std::iter::once((tr("Project opened").to_owned(), tokens.text_dim))
.chain(done.iter().map(|label| (tr_history(label), tokens.text)))
.chain(undone.iter().map(|label| (trf("{action} (undone)", &[("action", &tr_history(label))]), tokens.text_dim)));
let total_rows = 1 + done.len() + undone.len();
// Only new steps or a new container (with its own scroll) bring the current one into view; a tool change keeps the user's scroll
let shown = Some((ui.make_persistent_id("history"), done.len(), undone.len(), done.last().cloned()));
let follow = app.ui.history_shown != shown;
app.ui.history_shown = shown;
// A click on a step goes back (or forward) to it: steps to undo, or to redo when negative
let mut jump = 0i64;
egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| {
ui.spacing_mut().item_spacing.y = 0.0;
for (row, (name, color)) in rows.enumerate() {
let area = egui::ScrollArea::vertical().id_salt("history").auto_shrink([false, false]);
crate::log_panel::panel_rows(ui, area, HISTORY_ROW_HEIGHT, total_rows, |ui, range| {
if follow {
let top = ui.max_rect().top() + (done.len() as f32 - range.start as f32) * HISTORY_ROW_HEIGHT;
let current = egui::Rect::from_x_y_ranges(ui.max_rect().x_range(), top..=top + HISTORY_ROW_HEIGHT);
ui.scroll_to_rect_animation(current, None, egui::style::ScrollAnimation::none());
}
// Only the shown rows are translated
for row in range {
let Some((name, color)) = history_row_name(&done, &undone, row, &tokens) else { continue };
// Each row is the state after that many steps
let steps = done_count - row as i64;
if history_row(ui, &tokens, &name, color, steps == 0).on_hover_text(tr("Return to this step")).clicked() {
@@ -289,10 +302,22 @@ pub(crate) fn history(app: &mut TextureCraftApp, ui: &mut Ui) {
}
}
/// The name and colour of History row `row`: the opened project, then the done steps, then the undone ones
fn history_row_name(done: &[String], undone: &[String], row: usize, tokens: &Tokens) -> Option<(String, egui::Color32)> {
let Some(step) = row.checked_sub(1) else { return Some((tr("Project opened").to_owned(), tokens.text_dim)) };
if let Some(label) = done.get(step) {
return Some((tr_history(label), tokens.text));
}
let label = undone.get(step - done.len())?;
Some((trf("{action} (undone)", &[("action", &tr_history(label))]), tokens.text_dim))
}
/// One History row across the panel: a band under the pointer, the current step outlined
fn history_row(ui: &mut Ui, tokens: &Tokens, name: &str, color: egui::Color32, current: bool) -> egui::Response {
let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), HISTORY_ROW_HEIGHT), egui::Sense::click());
response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, current, name));
crate::log_panel::reveal_focused_row(ui, &response, rect);
if !ui.is_rect_visible(rect) {
return response;
}
+128 -4
View File
@@ -1,7 +1,7 @@
//! A click on a step of the History panel goes back or forward to it.
//! The History panel: a click on a step goes back or forward to it, the current step is marked and kept in view
use egui::accesskit::Toggled;
use egui::{Key, Modifiers};
use egui::{Event, Key, Modifiers, vec2};
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable};
use serde_json::json;
@@ -27,13 +27,16 @@ fn press(harness: &mut Harness<'_, TextureCraftApp>, key: Key) {
harness.run_steps(3);
}
/// The rows the panel shows as the current step: name and top edge
/// The History rows shown as the current step: name and top edge
fn current_rows(harness: &Harness<'_, TextureCraftApp>) -> Vec<(String, f32)> {
let session = &harness.state().session;
let undone = session.redo_labels().into_iter().map(|label| format!("{label} (undone)"));
let names: Vec<String> = session.history_labels().into_iter().chain(undone).chain(["Project opened".to_owned()]).collect();
harness
.get_all_by_role(egui::accesskit::Role::Button)
.filter(|node| node.accesskit_node().toggled() == Some(Toggled::True))
.filter_map(|node| Some((node.accesskit_node().label()?, node.rect().top())))
.filter(|(name, _)| name.contains("Rename layer") || name == "Project opened")
.filter(|(name, _)| names.contains(name))
.collect()
}
@@ -233,3 +236,124 @@ fn only_the_current_step_is_marked_selected() {
harness.run_steps(3);
assert!(harness.state().session.redo_labels().is_empty());
}
/// Enough steps that the History cannot show them all at once
const STEPS_PAST_THE_PANEL: usize = 100;
/// A session `steps` renames long, so its History list is taller than the panel
fn long_session(steps: usize) -> Session {
let mut session = texturecraft_engine::sample_session(256, 64).unwrap();
for step in 0..steps {
execute(&mut session, "layer.rename", &json!({"name": format!("Step {step}")})).unwrap();
}
session
}
/// Whether the current step's row named `name` is on screen
fn current_shown(harness: &Harness<'_, TextureCraftApp>, name: &str) -> bool {
let screen = harness.ctx.content_rect();
current_rows(harness).iter().any(|(row, top)| row == name && screen.y_range().contains(*top))
}
/// Scroll the History list back to its first rows with the mouse wheel
fn scroll_to_top(harness: &mut Harness<'_, TextureCraftApp>) {
// Exactly one row is the current step; its top finds the row under the wheel
let (_, top) = current_rows(harness)[0];
let over = harness.get_all_by_label("Rename layer").find(|node| node.rect().top() == top).unwrap().rect().center();
harness.hover_at(over);
harness.event(Event::MouseWheel {
unit: egui::MouseWheelUnit::Point,
delta: vec2(0.0, 100_000.0),
phase: egui::TouchPhase::Move,
source: egui::MouseWheelSource::Wheel,
modifiers: Modifiers::NONE,
});
harness.run_steps(12);
}
/// A History list longer than the panel opens at its newest step, not at "Project opened"
#[test]
fn a_long_history_shows_the_newest_step() {
let harness = history_harness(long_session(STEPS_PAST_THE_PANEL));
assert!(current_shown(&harness, "Rename layer"));
assert!(harness.query_by_label("Project opened").is_none_or(|row| !harness.ctx.content_rect().y_range().contains(row.rect().top())));
}
/// A list the user scrolled up stays there when a tool changes but the history doesn't
#[test]
fn scrolling_up_is_not_pulled_back() {
let mut harness = history_harness(long_session(STEPS_PAST_THE_PANEL));
scroll_to_top(&mut harness);
assert!(!current_shown(&harness, "Rename layer"));
execute(&mut harness.state_mut().session, "tool.select", &json!({"tool": "path"})).unwrap();
harness.run_steps(4);
assert!(!current_shown(&harness, "Rename layer"));
}
/// Once the history is full, a new step keeps the step count; its new name still brings it into view
#[test]
fn the_newest_step_shows_past_the_history_cap() {
let steps = texturecraft_engine::session::MAX_HISTORY + 60;
let mut harness = history_harness(long_session(steps));
let capped = harness.state().session.history_labels().len();
assert!(capped < steps, "the history is full");
scroll_to_top(&mut harness);
assert!(!current_shown(&harness, "Rename layer"));
execute(&mut harness.state_mut().session, "layer.add.paint", &json!({})).unwrap();
harness.run_steps(4);
let newest = harness.state().session.history_labels().last().cloned().unwrap();
assert_eq!(harness.state().session.history_labels().len(), capped);
assert!(current_shown(&harness, &newest));
}
/// A History list that moves to another container (rail popup to floating window) still shows the current step
#[test]
fn an_undocked_history_shows_the_newest_step() {
let session = long_session(STEPS_PAST_THE_PANEL);
let mut harness = Harness::builder()
.with_size(egui::vec2(1600.0, 960.0))
.with_context_setup(texturecraft_ui_egui::framework::install_headless)
.build_eframe(|context| TextureCraftApp::new(context, session));
harness.run_steps(4);
let icon = harness.get_all_by_role(egui::accesskit::Role::Button).find(|button| {
let label = button.accesskit_node().label().unwrap_or_default();
label == "History" || label.starts_with("History (")
});
icon.expect("the History icon on the rail").click();
harness.run_steps(4);
assert!(current_shown(&harness, "Rename layer"));
harness.get_by_label("Undock").click();
harness.run_steps(4);
assert!(current_shown(&harness, "Rename layer"));
}
/// Shift+Tab walks from the current step up to the first row, past the rows on screen when the panel opened
#[test]
fn the_keyboard_reaches_rows_scrolled_out_of_view() {
let mut harness = history_harness(long_session(STEPS_PAST_THE_PANEL));
let (_, top) = current_rows(&harness)[0];
harness.get_all_by_label("Rename layer").find(|node| node.rect().top() == top).unwrap().focus();
harness.run_steps(2);
let first_row_focused = |harness: &Harness<'_, TextureCraftApp>| {
let screen = harness.ctx.content_rect();
harness.query_by_label("Project opened").is_some_and(|row| row.accesskit_node().is_focused() && screen.y_range().contains(row.rect().top()))
};
// One press per step is enough to reach the first row
for _ in 0..harness.state().session.history_labels().len() + 1 {
if first_row_focused(&harness) {
break;
}
harness.key_press_modifiers(Modifiers::SHIFT, Key::Tab);
harness.run_steps(2);
}
assert!(first_row_focused(&harness));
}