History panel: add snapshot-safe row context menus and keyboard access

This commit is contained in:
ruchirguitar
2026-11-26 04:54:14 +05:30
parent 016ead2572
commit c766f2f450
7 changed files with 433 additions and 36 deletions
+1 -2
View File
@@ -69,8 +69,7 @@ fn largest_fitting_chroma(l: f64, h: f64, limit: f64) -> f64 {
let y = [lin(0.0), lin(s), lin(2.0 * s), lin(3.0 * s)];
let bounds = [-GAMUT_SLACK / 12.92, ((1.0 + GAMUT_SLACK + 0.055) / 1.055).powf(2.4)];
let mut ends = vec![0.0];
for ch in 0..3 {
let [y0, y1, y2, y3] = [y[0][ch], y[1][ch], y[2][ch], y[3][ch]];
for (((y0, y1), y2), y3) in y[0].into_iter().zip(y[1]).zip(y[2]).zip(y[3]) {
let (d1, d2, d3) = (y1 - y0, y2 - 2.0 * y1 + y0, y3 - 3.0 * y2 + 3.0 * y1 - y0);
let k = [y0, d1 - d2 / 2.0 + d3 / 3.0, d2 / 2.0 - d3 / 2.0, d3 / 6.0];
let p = |t: f64| ((k[3] * t + k[2]) * t + k[1]) * t + k[0];
+1 -1
View File
@@ -248,7 +248,7 @@ impl History {
/// The document at row `row` of the History panel, `now` being the document now: the rows before
/// it are the undo steps, oldest first, and the rows after it the redo steps, nearest first.
pub(crate) fn state<'a>(&'a self, now: &'a Arc<Document>, row: usize) -> Option<&'a Arc<Document>> {
pub fn state<'a>(&'a self, now: &'a Arc<Document>, row: usize) -> Option<&'a Arc<Document>> {
let current = self.undo.len();
match row.cmp(&current) {
std::cmp::Ordering::Less => self.undo.get(row).map(|e| &e.doc),
+393 -23
View File
@@ -1,9 +1,17 @@
//! History panel: the document's states; click one to go back (or forward) to it.
use std::sync::Arc;
use craft::behavior::{IconId, Selection, SelectionChange, keyed};
use craft::keymap::CommandRef;
use craft::ui::menu::PanelRow;
use craft::ui::patterns::panels::{HistoryEvent, HistoryFooter, HistoryKey, HistoryPanel, HistoryRow};
use craft::ui::contract::{Bind, CollectionEvent, Props as _, ScrollAnchor, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, Sizing};
use craft::ui::display::Divider;
use craft::ui::layout_components::Stack;
use craft::ui::list::{List, ListRow, RowInk};
use craft::ui::menu::{Menu, MenuItem, PanelRow};
use craft::ui::patterns::panels::{HistoryKey, HistoryRow};
use craft::ui::runtime::commands::{CommandState, CommandStates};
use craft::ui::sections::{FooterAction, FooterBar};
use egui::Ui;
use serde_json::{Value, json};
@@ -69,34 +77,168 @@ fn rows(app: &VectorcraftApp) -> Vec<HistoryRow> {
.collect()
}
/// Moves the document to state `target`, stopping at the first step that fails.
fn step_to(app: &mut VectorcraftApp, target: usize) {
let Some(current) = app.session.active().map(|st| st.history.undo.len()) else { return };
let s = steps_to(current, target);
let (cmd, n) = if s < 0 { ("edit.undo", -s) } else { ("edit.redo", s) };
for _ in 0..n {
if app.run(cmd, json!({})).is_err() {
break;
}
}
#[derive(Clone)]
struct ContextState {
document: u64,
snapshot: Arc<vectorcraft_doc::Document>,
}
/// The shared collection supplies row focus, keyboard context requests, scrolling and menu
/// dismissal. The app retains the chosen document snapshot and dispatches its history commands.
pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
let Some(undone) = app.session.active().map(|st| st.history.undo.len()) else {
let state_id = ui.scope_id().with("history-context-state");
let document = app.session.active().map(|st| st.uid);
let mut context = ui.ctx().data(|d| d.get_temp::<ContextState>(state_id));
if context.as_ref().is_some_and(|state| document != Some(state.document)) {
craft::ui::runtime::overlay::close_popups(ui.ctx());
context = None;
}
let Some(st) = app.session.active() else {
ui.ctx().data_mut(|d| d.remove::<ContextState>(state_id));
super::empty_state(ui, "history", tl!("No document"), tl!("Open a document to see its history."));
return;
};
let document = st.uid;
let current = st.history.undo.len();
let rows = rows(app);
// A click on a row moves to its state at once, so the current state is the selected one.
let out = HistoryPanel::new(&rows, Some(HistoryKey::State(undone as u64)))
.footer(HistoryFooter::default().new_document(true))
.can_delete(|_| false)
.show(ui);
for event in out.events {
match event {
HistoryEvent::Select(HistoryKey::State(n)) => step_to(app, n as usize),
HistoryEvent::NewDocument => crate::menus::invoke(app, "edit.newDocumentFromState", json!({})),
_ => {}
let mut selected = Selection::single(HistoryKey::State(current as u64));
let mut new_document = false;
let mut target = None;
let mut action = None;
Stack::new()
.fill()
.footer(|ui, _| {
let out = FooterBar::actions([FooterAction::new(IconId::new("new_file"), tl!("Create New Document from Current State"))]).show_footer(ui);
if !ui.is_sizing_pass() {
new_document |= out.picked.is_some();
}
})
.show(ui, |ui, _| {
let list = List::<HistoryKey>::new(tl!("History"))
.id(ui.scope_id().with(("history-rows", document)))
.select(SelectMode::Single)
.arrows_select(false)
.selection(Bind::bound(&mut selected))
.row_menu()
.sizing(Sizing::Fill)
.scroll_anchor(ScrollAnchor::End);
let out = list.show_items(ui, &keyed(&rows, |row: &HistoryRow| row.key), &mut |_, icx| {
let row = &rows[icx.at];
let mut item = ListRow::new(row.label.clone()).cells(icx.cells()).state(icx.row.clone());
if let Some(icon) = row.icon.clone() {
item = item.icon(icon.into());
}
if row.redo {
item = item.ink(RowInk::Dimmed);
}
item
});
let requested = out.events.iter().find_map(|event| match event {
CollectionEvent::ContextMenu(request) => Some(request.key),
_ => None,
});
if let Some(HistoryKey::State(row)) = requested {
context = app
.session
.active()
.and_then(|st| st.history.state(&st.doc, row as usize))
.cloned()
.map(|snapshot| ContextState { document, snapshot });
} else {
for event in &out.events {
if let CollectionEvent::Activate(HistoryKey::State(row)) = event {
target = app.session.active().and_then(|st| st.history.state(&st.doc, *row as usize)).cloned();
}
if let CollectionEvent::Selection { change: SelectionChange::Set(keys), .. } = event
&& let Some(HistoryKey::State(row)) = keys.last()
&& *row as usize != current
{
target = app.session.active().and_then(|st| st.history.state(&st.doc, *row as usize)).cloned();
}
}
}
if let Some(state) = context.as_ref() {
let snapshot = state.snapshot.clone();
let can_step = app.session.active().is_some_and(|st| !Arc::ptr_eq(&snapshot, &st.doc));
let shown = Menu::context(tl!("History"), &out.response).show(ui, |ui, _| {
if MenuItem::new(tl!("New Document from State")).enabled(crate::menus::enabled(app, "edit.newDocumentFromState")).show(ui).ran {
action = Some(("edit.newDocumentFromState", snapshot.clone()));
}
if MenuItem::new(tl!("Step to This State")).enabled(can_step).show(ui).ran {
target = Some(snapshot.clone());
}
Divider::horizontal().show(ui);
if MenuItem::new(tl!("Clear History")).enabled(crate::menus::enabled(app, "edit.clearHistory")).show(ui).ran {
action = Some(("edit.clearHistory", snapshot.clone()));
}
});
if shown.output.closed.is_some() || action.is_some() || target.is_some() {
context = None;
}
}
});
ui.ctx().data_mut(|d| {
if let Some(state) = context {
d.insert_temp(state_id, state);
} else {
d.remove::<ContextState>(state_id);
}
});
if let Some((command, snapshot)) = action {
if command == "edit.newDocumentFromState" {
if let Some(row) = resolve_state(app, snapshot, false) {
crate::menus::invoke(app, command, json!({ "index": row }));
}
} else {
crate::menus::invoke(app, command, json!({}));
}
}
if let Some(target) = target {
step_to_state(app, target);
}
if new_document {
crate::menus::invoke(app, "edit.newDocumentFromState", json!({}));
}
}
/// Keep the clicked snapshot while pending edits settle: they can add or trim history rows.
fn resolve_state(app: &mut VectorcraftApp, target: Arc<vectorcraft_doc::Document>, keep_typing: bool) -> Option<usize> {
let requests = app.session.finish_tool_edit();
let failed = requests.is_err();
crate::canvas::apply_requests(app, requests);
if failed {
return None;
}
if keep_typing && let Err(e) = app.keep_typing() {
app.status(e);
return None;
}
let st = app.session.active()?;
let current = st.history.undo.len();
let row = if Arc::ptr_eq(&st.doc, &target) {
Some(current)
} else {
st.history
.undo
.iter()
.position(|h| Arc::ptr_eq(&h.doc, &target))
.or_else(|| st.history.redo.iter().rev().position(|h| Arc::ptr_eq(&h.doc, &target)).map(|i| current + i + 1))
};
if row.is_none() {
app.status(tl!("That history state is no longer available."));
}
row
}
fn step_to_state(app: &mut VectorcraftApp, target: Arc<vectorcraft_doc::Document>) {
let Some(row) = resolve_state(app, target, true) else { return };
let Some(st) = app.session.active() else { return };
let steps = steps_to(st.history.undo.len(), row);
let (cmd, n) = if steps < 0 { ("edit.undo", -steps) } else { ("edit.redo", steps) };
for _ in 0..n {
if let Err(e) = app.run(cmd, json!({})) {
app.status(e);
break;
}
}
}
@@ -284,4 +426,232 @@ mod tests {
assert!(st.is_dirty(), "the new document is unsaved");
assert!(std::sync::Arc::ptr_eq(&app.session.documents()[0].doc, &source), "the source stays at that state");
}
fn history_harness(app: VectorcraftApp) -> egui_kittest::Harness<'static, VectorcraftApp> {
crate::i18n::set_current(crate::i18n::Lang::EN);
let mut h = egui_kittest::Harness::builder()
.with_size(egui::vec2(260.0, 400.0))
.with_context_setup(crate::testing::install)
.build_ui_state(|ui, app| show(app, ui), app);
h.run_steps(2);
h
}
fn row_menu_harness(app: VectorcraftApp, row: usize) -> egui_kittest::Harness<'static, VectorcraftApp> {
use egui_kittest::kittest::Queryable;
let mut h = history_harness(app);
let pos = h.get_all_by_role(egui::accesskit::Role::ListItem).nth(row).expect("history row").rect().center();
h.event(egui::Event::PointerMoved(pos));
for pressed in [true, false] {
h.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Secondary, pressed, modifiers: Default::default() });
}
h.run_steps(2);
h
}
fn focus_previous_state(h: &mut egui_kittest::Harness<'static, VectorcraftApp>) {
use egui_kittest::kittest::{NodeT, Queryable};
for _ in 0..4 {
h.key_press(egui::Key::Tab);
h.run_steps(1);
if h.get_all_by_role(egui::accesskit::Role::ListItem).nth(2).unwrap().accesskit_node().is_focused() {
break;
}
}
assert!(h.get_all_by_role(egui::accesskit::Role::ListItem).nth(2).unwrap().accesskit_node().is_focused());
h.key_press(egui::Key::ArrowUp);
h.run_steps(2);
assert!(h.get_all_by_role(egui::accesskit::Role::ListItem).nth(1).unwrap().accesskit_node().is_focused());
assert_eq!(depth(h.state()), (2, 0), "moving focus must not step history");
}
#[test]
fn keyboard_activation_steps_to_the_focused_state() {
let mut h = history_harness(app_with_two_rectangles());
focus_previous_state(&mut h);
h.key_press(egui::Key::Enter);
h.run_steps(2);
assert_eq!(depth(h.state()), (1, 1));
assert_eq!(h.state().session.active().unwrap().doc.layers[0].children().unwrap().len(), 1);
}
#[test]
fn switching_documents_dismisses_the_row_menu_without_clearing_either_history() {
use egui_kittest::kittest::Queryable;
let mut app = app_with_two_rectangles();
app.session.execute("edit.undo", &json!({})).unwrap();
app.session.execute("file.new", &json!({"width": 200, "height": 150})).unwrap();
for x in [10, 60] {
app.session.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 20, "height": 20})).unwrap();
}
app.session.execute("edit.undo", &json!({})).unwrap();
app.session.execute("document.activate", &json!({"index": 0})).unwrap();
let mut h = row_menu_harness(app, 1);
h.get_by_label("Clear History");
h.state_mut().session.execute("document.activate", &json!({"index": 1})).unwrap();
h.run_steps(2);
assert!(h.query_by_label("Clear History").is_none(), "the other document must not inherit the popup");
h.state_mut().session.execute("document.activate", &json!({"index": 0})).unwrap();
h.run_steps(2);
assert!(h.query_by_label("Clear History").is_none(), "switching back must not revive the popup");
for st in h.state().session.documents() {
assert_eq!((st.history.undo.len(), st.history.redo.len()), (1, 1));
}
}
#[test]
fn keyboard_opens_dismisses_and_activates_the_focused_rows_menu() {
use egui_kittest::kittest::{NodeT, Queryable};
let app = app_with_two_rectangles();
let source = app.session.active().unwrap().doc.clone();
let wanted = app.session.active().unwrap().history.undo[1].doc.clone();
let mut h = history_harness(app);
focus_previous_state(&mut h);
h.key_press_modifiers(egui::Modifiers::SHIFT, egui::Key::F10);
h.run_steps(2);
assert!(h.get_by_label("New Document from State").accesskit_node().is_focused());
assert_eq!(depth(h.state()), (2, 0), "opening does not step");
h.key_press(egui::Key::Escape);
h.run_steps(2);
assert!(h.query_by_label("New Document from State").is_none());
assert!(h.get_all_by_role(egui::accesskit::Role::ListItem).nth(1).unwrap().accesskit_node().is_focused());
h.key_press_modifiers(egui::Modifiers::SHIFT, egui::Key::F10);
h.run_steps(2);
h.key_press(egui::Key::Enter);
h.run_steps(2);
assert_eq!(h.state().session.documents().len(), 2);
assert_eq!(h.state().session.active().unwrap().doc.layers, wanted.layers);
assert!(Arc::ptr_eq(&h.state().session.documents()[0].doc, &source));
assert_eq!(h.state().session.documents()[0].history.undo.len(), 2);
}
#[test]
fn right_clicking_an_earlier_state_opens_its_menu_without_stepping() {
use egui_kittest::kittest::Queryable;
let h = row_menu_harness(app_with_two_rectangles(), 1);
h.get_by_label("New Document from State");
h.get_by_label("Step to This State");
h.get_by_label("Clear History");
assert_eq!(depth(h.state()), (2, 0));
}
#[test]
fn the_row_menu_makes_a_new_document_from_that_snapshot() {
use egui_kittest::kittest::Queryable;
let mut app = app_with_two_rectangles();
app.session.execute("edit.undo", &json!({})).unwrap();
let snapshot = app.session.active().unwrap().doc.clone();
app.session.execute("edit.redo", &json!({})).unwrap();
let source = app.session.active().unwrap().doc.clone();
let mut h = row_menu_harness(app, 1);
h.get_by_label("New Document from State").click();
h.run_steps(2);
let app = h.state();
assert_eq!(app.session.documents().len(), 2);
assert_eq!(app.session.active_index(), Some(1));
let st = app.session.active().unwrap();
assert_eq!(st.doc.layers, snapshot.layers, "the historic artwork");
assert!(st.is_dirty());
assert_eq!(depth(app), (0, 0));
assert!(std::sync::Arc::ptr_eq(&app.session.documents()[0].doc, &source));
assert_eq!(app.session.documents()[0].history.undo.len(), 2);
}
#[test]
fn the_row_menu_steps_backward_and_forward_to_the_target() {
use egui_kittest::kittest::{NodeT, Queryable};
for (current, target) in [(2, 0), (0, 2), (1, 1)] {
let mut app = app_with_two_rectangles();
for _ in current..2 {
app.session.execute("edit.undo", &json!({})).unwrap();
}
let mut h = row_menu_harness(app, target);
let item = h.get_by_label("Step to This State");
assert_eq!(item.accesskit_node().is_disabled(), current == target);
item.click();
h.run_steps(2);
assert_eq!(depth(h.state()), (target, 2 - target));
assert_eq!(h.state().session.active().unwrap().doc.layers[0].children().unwrap().len(), target);
}
}
#[test]
fn the_row_menu_clears_undo_and_redo_without_changing_art() {
use egui_kittest::kittest::{NodeT, Queryable};
let mut app = app_with_two_rectangles();
app.session.execute("edit.undo", &json!({})).unwrap();
let source = app.session.active().unwrap().doc.clone();
let mut h = row_menu_harness(app, 0);
h.get_by_label("Clear History").click();
h.run_steps(2);
assert_eq!(depth(h.state()), (0, 0));
assert!(std::sync::Arc::ptr_eq(&h.state().session.active().unwrap().doc, &source));
let mut empty = app_with_two_rectangles();
empty.session.execute("edit.clearHistory", &json!({})).unwrap();
let h = row_menu_harness(empty, 0);
assert!(h.get_by_label("Clear History").accesskit_node().is_disabled());
}
#[test]
fn stepping_settles_typing_and_follows_the_snapshot_when_rows_shift() {
use egui_kittest::kittest::Queryable;
for (limit, row) in [(10, 0), (2, 1)] {
let mut app = app_with_two_rectangles();
app.session.active_mut().unwrap().history.limit = limit;
let st = app.session.active().unwrap();
let wanted = st.history.state(&st.doc, row).unwrap().clone();
app.session.begin_interaction("Typing").unwrap();
app.session.preview("object.move", &json!({"dx": 5, "dy": 0})).unwrap();
let mut h = row_menu_harness(app, row);
h.get_by_label("Step to This State").click();
h.run_steps(2);
let st = h.state().session.active().unwrap();
assert_eq!(st.doc.layers, wanted.layers, "limit {limit}, row {row}");
assert!(st.interaction.is_none());
assert_eq!(st.history.undo.len(), 0);
}
}
#[test]
fn copying_a_state_resolves_pending_tool_edits_without_copying_a_neighbor() {
use egui_kittest::kittest::Queryable;
use vectorcraft_tools::{PointerEvent, PointerKind};
for (row, finishes_while_open) in [(0, false), (1, false), (0, true), (1, true)] {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 800, "height": 200})).unwrap();
// A Shape Builder merge over this many segments computes on another thread.
for k in 0..40 {
app.run("shape.rectangle", json!({"x": k * 10, "y": 0, "width": 20, "height": 20})).unwrap();
}
app.run("select.all", json!({})).unwrap();
app.run("tool.select", json!({"tool": "shapeBuilder"})).unwrap();
let st = app.session.active_mut().unwrap();
st.history.limit = 2;
st.history.trim();
let wanted = st.history.state(&st.doc, row).unwrap().clone();
let view = app.view_info();
crate::canvas::dispatch(&mut app, &PointerEvent::new(PointerKind::Move, 15.0, 10.0), view);
app.session.tool_poll(view, true).unwrap();
crate::canvas::dispatch(&mut app, &PointerEvent::new(PointerKind::Down, 15.0, 10.0), view);
crate::canvas::dispatch(&mut app, &PointerEvent::new(PointerKind::Up, 15.0, 10.0), view);
assert!(app.session.tool_waiting());
let mut h = row_menu_harness(app, row);
if finishes_while_open {
let requests = h.state_mut().session.finish_tool_edit();
crate::canvas::apply_requests(h.state_mut(), requests);
h.run_steps(2);
}
h.get_by_label("New Document from State").click();
h.run_steps(2);
let app = h.state();
assert!(!app.session.tool_waiting());
if row == 0 {
assert_eq!(app.session.documents().len(), 1, "the pruned snapshot must not copy its neighbor");
assert_eq!(app.ui.status, "That history state is no longer available.");
} else {
assert_eq!(app.session.active_index(), Some(1));
assert_eq!(app.session.active().unwrap().doc.layers, wanted.layers, "the retained snapshot moved from row 1 to row 0");
}
}
}
}
+11 -2
View File
File diff suppressed because one or more lines are too long
+9 -3
View File
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+7 -2
View File
File diff suppressed because one or more lines are too long