Dialog-local undo: FormDialog::history steps the dialog's own value

A FormDialog with history keeps an EditHistory of its value while it is open. Undo and Redo reach it through
Commands::take_step, after a focused text field's own steps. A change becomes a step once no gesture runs in
the body: runtime::edit::watch_gestures says whether a component's gesture ran inside the body call, counted
at the apply step. ParamDialog takes the history prop; the Contour editor and the ParamDialog stories turn it on.
This commit is contained in:
aiongg
2026-11-12 14:32:40 +00:00
parent 7c6c187a45
commit 863aedd7bd
8 changed files with 127 additions and 8 deletions
@@ -124,6 +124,7 @@ impl StackDialog for ContourEditorDialog {
let sampler = self.sampler.clone();
let shown = FormDialog::new(words.editor.clone(), Bind::bound(&mut self.draft))
.outer_gesture(true)
.history(true)
.extra_buttons(extras.iter().map(|(_, label)| FooterButton::new((*label).clone(), DialogRole::Other)))
.shaped(|dialog| dialog.side_buttons(true))
.show(ui, |ui, _, draft| {
@@ -107,6 +107,9 @@ pub(crate) fn apply_values<C: Component>(comp: &mut C, cx: &mut Cx<'_, C>) -> Va
};
let gesture = cx.core.memory.shown::<Gesture<ValueOf<C>>>(slot);
let (running, watched) = (gesture.is_running().then_some(gesture.id), gesture.watched);
if running.is_some() {
crate::runtime::edit::note_running(&cx.core.ctx);
}
if gesture.is_running() {
gesture.emitted = emitted.or(gesture.emitted.take());
gesture.last_given = given_now.or(gesture.last_given.take());
+28 -4
View File
@@ -28,19 +28,43 @@ pub(crate) fn latest(ctx: &Context) -> (u64, Option<CancelReason>) {
pass_state::with::<CancelAll, _>(ctx, |all| (all.serial, all.reason))
}
/// The newest gesture id handed out in this context.
/// The newest gesture id handed out in this context, and how many times a component has reported its gesture running
/// at an apply step.
#[derive(Clone, Copy, Default)]
pub(crate) struct Gestures(GestureId);
pub(crate) struct Gestures {
newest: GestureId,
running: u64,
}
/// A gesture id no gesture of this context has had: ids grow in the order gestures begin, across components and
/// across a component's eviction, as `GestureHost` assumes.
pub fn next_gesture_id(ctx: &Context) -> GestureId {
pass_state::with::<Gestures, _>(ctx, |gestures| {
gestures.0 = gestures.0.next();
gestures.0
gestures.newest = gestures.newest.next();
gestures.newest
})
}
/// Notes that a component's gesture runs after its apply step, for [`watch_gestures`].
pub(crate) fn note_running(ctx: &Context) {
if !crate::runtime::measure::active(ctx) {
pass_state::with::<Gestures, _>(ctx, |gestures| gestures.running += 1);
}
}
/// Runs `body` and says whether a gesture of a component shown inside it was running after the component's apply
/// step: a drag or a typing run under way. A container that records its body's edits as undo steps waits for the
/// gesture to end, so a drag is one step. A measuring run sees none: gestures run in real runs.
pub fn watch_gestures<R>(ctx: &Context, body: impl FnOnce() -> R) -> (R, bool) {
if crate::runtime::measure::active(ctx) {
return (body(), false);
}
let before = pass_state::with::<Gestures, _>(ctx, |gestures| gestures.running);
let out = body();
let after = pass_state::with::<Gestures, _>(ctx, |gestures| gestures.running);
(out, after != before)
}
/// Notes that the component running gesture `id` was evicted: the gesture ends with `CancelReason::Removed`, which the
/// edit hosts read from `FrameOutput::removed_gestures`.
pub(crate) fn note_removed(ctx: &Context, id: GestureId) {
@@ -159,6 +159,9 @@ pub struct ParamDialog<'a> {
/// Whether the dialog holds one outer gesture over its fields, from open to close.
#[prop]
outer_gesture: bool,
/// Whether Cmd/Ctrl+Z and Shift+Cmd/Ctrl+Z step the dialog's own values ([`FormDialog::history`]).
#[prop]
history: bool,
/// Whether the body is one collection that owns the scroll (a browse list): the dialog's own body scroll is off.
#[prop]
collection_body: bool,
@@ -228,6 +231,7 @@ impl<'a> ParamDialog<'a> {
cancel_label: None,
alt_resets: true,
outer_gesture: false,
history: false,
collection_body: false,
reset_to: None,
layout: ParamLayout::default(),
@@ -292,6 +296,7 @@ impl<'a> ParamDialog<'a> {
cancel_label,
alt_resets,
outer_gesture,
history,
collection_body,
reset_to,
layout,
@@ -312,6 +317,7 @@ impl<'a> ParamDialog<'a> {
.ok_enabled(ok_enabled)
.alt_resets(alt_resets)
.outer_gesture(outer_gesture)
.history(history)
.collection_body(collection_body)
.closable(closable)
.answers(answers)
@@ -25,7 +25,7 @@ const LAYOUTS: [(&str, ParamLayout); 2] = [("Beside", ParamLayout::Beside), ("Be
fn blur_story(ui: &mut Ui, data: &mut StoryData, preview: bool, layout: ParamLayout) -> StoryOutput {
let preview = *data.value("preview", preview);
let layout = *data.choice("layout", layout, &LAYOUTS);
let dialog = ParamDialog::new("blur", "Blur", Param::parse_list(SPEC)).opened(Bind::bound(data.value("open", true)));
let dialog = ParamDialog::new("blur", "Blur", Param::parse_list(SPEC)).opened(Bind::bound(data.value("open", true))).history(true);
let dialog = if preview { dialog.preview(picture(ui)).layout(layout) } else { dialog };
dialog.show(ui).into()
}
@@ -5,6 +5,7 @@
use super::dialog::ResetFooter;
use super::host_requests::HostRequests;
use crate::contract::{Bind, BodyCx, Remember as _, ShowContainer as _};
use crate::runtime::commands::Commands as _;
use crate::runtime::requests::HostAnswer;
use crate::dialog::{Dialog, DialogOutput};
@@ -16,7 +17,8 @@ use crate::runtime::words::CommonWords;
use crate::sections::{DialogRole, FooterButton};
use craft_behavior::{EditEvent, Mixed, Value};
use craft_behavior::edit_history::EditHistory;
use craft_behavior::{CancelReason, EditEvent, Mixed, Value};
use egui::{Response, Ui};
@@ -30,6 +32,16 @@ use std::sync::Arc;
#[cfg(feature = "testing")]
mod stories;
/// The dialog's own undo history of its value while it is open: made on the opening pass, stepped by Undo and Redo.
#[derive(Clone)]
struct History<V>(Option<EditHistory<V>>);
impl<V> Default for History<V> {
fn default() -> Self {
History(None)
}
}
/// The values the dialog opened with, taken after the body's first pass.
#[derive(Clone)]
struct Opened<V>(Option<V>);
@@ -115,6 +127,8 @@ type ResetWithFn<'a, V> = Box<dyn Fn(&V, &V) -> V + 'a>;
/// - Keys: Enter is OK unless the body owns it, Escape cancels. Holding Alt turns Cancel into Reset, which restores
/// the value from when the dialog opened (and runs [`on_reset`](FormDialog::on_reset) for what the body keeps).
/// - The body returns whether the value can be accepted; OK is enabled while it can and `ok_enabled` is true.
/// - With [`history`](FormDialog::history), Cmd/Ctrl+Z and Shift+Cmd/Ctrl+Z step the dialog's own value; a drag or a
/// typing run is one step.
#[must_use = "show the dialog with `show`"]
#[derive(crate::contract::Pattern)]
#[pattern(probe(FormDialog<'static, bool>))]
@@ -129,6 +143,7 @@ pub struct FormDialog<'a, V: Value + Default> {
ok_reason: Option<Label>,
alt_resets: bool,
outer_gesture: bool,
history: bool,
collection_body: bool,
closable: bool,
accept_stays_open: bool,
@@ -155,6 +170,7 @@ impl<'a, V: Value + Default> FormDialog<'a, V> {
ok_reason: None,
alt_resets: true,
outer_gesture: false,
history: false,
collection_body: false,
closable: true,
accept_stays_open: false,
@@ -215,6 +231,14 @@ impl<'a, V: Value + Default> FormDialog<'a, V> {
self
}
/// Whether the dialog keeps an undo history of its value while it is open: Undo and Redo step it, after a focused
/// text field's own steps. A change becomes a step once no gesture runs in the body, so a drag or a typing run is
/// one step. Off by default.
pub fn history(mut self, on: bool) -> Self {
self.history = on;
self
}
/// Whether the body is one collection that owns the scroll.
pub fn collection_body(mut self, on: bool) -> Self {
self.collection_body = on;
@@ -292,6 +316,7 @@ impl<'a, V: Value + Default> FormDialog<'a, V> {
ok_reason,
alt_resets,
outer_gesture,
history,
collection_body,
closable,
accept_stays_open,
@@ -379,7 +404,17 @@ impl<'a, V: Value + Default> FormDialog<'a, V> {
_ => V::default(),
};
let mut values = before.clone();
let ok = {
let mut steps = (history && !measuring).then(|| std::mem::take(&mut cx.memory::<History<V>>().0).filter(|_| !first)).flatten();
if history && !measuring {
let can = |steps: &Option<EditHistory<V>>| steps.as_ref().map_or((false, false), |steps| (steps.can_undo(), steps.can_redo()));
while let Some(step) = cx.take_step(can(&steps).0, can(&steps).1) {
if let Some(steps) = steps.as_mut() {
crate::runtime::edit::cancel_all(ui.ctx(), CancelReason::UndoDuringGesture);
steps.step(&mut values, step);
}
}
}
let (ok, running) = {
let mut requests = requests.borrow_mut();
let mut form = FormCx {
cx: &mut *cx,
@@ -387,11 +422,20 @@ impl<'a, V: Value + Default> FormDialog<'a, V> {
answers: if measuring { Vec::new() } else { std::mem::take(&mut answers) },
requests: &mut requests,
};
body(ui, &mut form, &mut values)
let ctx = ui.ctx().clone();
crate::runtime::edit::watch_gestures(&ctx, || body(ui, &mut form, &mut values))
};
if first {
cx.memory::<Opened<V>>().0 = Some(values.clone());
}
if history && !measuring {
let mut steps = steps.unwrap_or_else(|| EditHistory::new(&values));
// A change becomes a step once the gesture that makes it has ended.
if !running {
steps.record(&EditEvent::set(Mixed::Same(before.clone()), values.clone(), name.clone(), None));
}
cx.memory::<History<V>>().0 = Some(steps);
}
let can_accept = ok && ok_enabled;
accepts.set(can_accept);
let edited = cx.memory::<Opened<V>>().0.as_ref().is_some_and(|opened| *opened != values);
@@ -0,0 +1,40 @@
//! `ParamDialog`: the dialog's own undo history.
use craft_ui::contract::{Bind, Role};
use craft_ui::patterns::form_dialogs::{DialogFields, Param, ParamDialog};
use craft_ui::testing::{Fixture, trial};
use egui::{Key, Modifiers, vec2};
use std::cell::RefCell;
use std::rc::Rc;
const SPEC: &str = r#"{"radius":0..100=10,"smooth":bool}"#;
// A slider drag is one step and a check box click another: Undo takes them back one by one, Redo brings the drag
// back.
#[trial]
fn undo_steps_the_dialog_values_and_a_drag_is_one_step() {
let values = Rc::new(RefCell::new(DialogFields::new()));
let shown = values.clone();
let mut fixture = Fixture::new(move |ui| {
ParamDialog::new("blur", "Blur", Param::parse_list(SPEC)).values(Bind::bound(&mut *shown.borrow_mut())).history(true).show(ui);
});
fixture.settle();
let radius = || values.borrow().number("radius");
let smooth = || values.borrow().bool("smooth").unwrap_or(false);
let opened = radius();
let slider = fixture.by_role(Role::SLIDER).into_iter().next().expect("the radius row has a slider");
fixture.drag(&slider, vec2(60.0, 0.0)).settle();
let dragged = radius();
assert_ne!(dragged, opened, "the drag moved the radius");
let check = fixture.by_label("Smooth").expect("the smooth row has a check box");
fixture.click(&check).settle();
assert!(smooth());
fixture.key(Key::Z, Modifiers::COMMAND).settle();
assert_eq!((radius(), smooth()), (dragged, false), "the first Undo takes back the click");
fixture.key(Key::Z, Modifiers::COMMAND).settle();
assert_eq!(radius(), opened, "the second Undo takes back the whole drag");
fixture.key(Key::Z, Modifiers::COMMAND | Modifiers::SHIFT).settle();
assert_eq!(radius(), dragged, "Redo brings the drag back");
}
@@ -1,6 +1,7 @@
//! The form dialogs' own logic: the parameter model, its spec-string parser, the value store, the size model,
//! guide layout and the export file name.
mod dialog;
mod export;
mod params;
mod preview;