Skip to main content

egui_pop_api/
history_view.rs

1//! The history's projection (ADR 0014): the `History` panel and the
2//! `history.*` commands agents drive it with, brought by
3//! [`HistoryPlugin`].
4//!
5//! <div class="warning">Experimental: may change in any release
6//! (docs/stability.md).</div>
7//!
8//! - **The panel** ([`PANEL_HISTORY`], closed until asked for; [`show`]
9//!   draws it anywhere): the scopes there are, as chips (the one Ctrl+Z
10//!   goes to first), then the chosen scope's steps, oldest first, under
11//!   a "Start" row. The head is the selected row; the steps a redo would
12//!   make again are muted under it. A click on a row jumps there
13//!   (`edit.jump`, vetoable like an undo); a step made by an agent, a
14//!   script or another process says so after its label. When the owner
15//!   supports them: the snapshots above the steps (a click restores
16//!   one), a hover previewing a row, "Undo this step" in a step's
17//!   context menu, and the replaced steps behind a toggle.
18//! - **The commands** (agents and scripts; kept out of the palette,
19//!   where Edit > Undo and Redo already are): `history.list` (every
20//!   scope, whether it is active, where Undo and Redo go and what they
21//!   would do), `history.read` (a scope's steps), `history.undo`,
22//!   `history.redo`, `history.jump`, `history.snapshot`,
23//!   `history.restore`, `history.drop_snapshot` and `history.undo_step`,
24//!   each with `scope` (none: where the keys go), `if_rev` and
25//!   `dry_run`. They run through the same
26//!   steps as the keys, so a hook vetoing an undo vetoes an agent's too,
27//!   and in the interface, not through the host's dispatch (which would
28//!   hold the host, and with it the history owner).
29//!
30//! ```
31//! use egui_pop_api::App;
32//! use egui_pop_api::history_view::HistoryPlugin;
33//! use egui_pop_core::lock;
34//! use egui_pop_model::commands::Origin;
35//! use egui_pop_model::ids::{CommandId, OwnerId};
36//! use egui_pop_model::values::{Change, Descriptor, Set, Value};
37//! use serde_json::json;
38//!
39//! let mut app = App::builder().plugin(HistoryPlugin::default())
40//!     .build(&egui::Context::default()).unwrap();
41//! let store = app.handle().store();
42//! // The agent may write `doc/n`: it may then undo (and dry-run) its steps.
43//! let agent = Origin::Agent("a".into());
44//! let n = Descriptor::int("N", 0, 9, 0).writers(&[agent.writer()]);
45//! lock(&store).declare(&OwnerId::USER, "doc/n", n).unwrap();
46//! lock(&store).set(Set::new("doc/n", Change::To(Value::Int(3)), Origin::User)).unwrap();
47//! let read = app
48//!     .run(&CommandId::from_static("history.read"), json!({ "scope": "app" }), Origin::Agent("a".into()))
49//!     .now().unwrap().unwrap();
50//! let head = read["head"].as_u64().unwrap();
51//! // A dry run says what an undo would take back, and changes nothing.
52//! let dry = app
53//!     .run(
54//!         &CommandId::from_static("history.undo"),
55//!         json!({ "scope": "app", "if_rev": read["rev"], "dry_run": true }),
56//!         Origin::Agent("a".into()),
57//!     )
58//!     .now().unwrap().unwrap();
59//! assert_eq!(dry["steps"][0]["id"].as_u64(), Some(head));
60//! assert_eq!(lock(&store).get("doc/n").unwrap().value, Value::Int(3));
61//! ```
62
63use egui::{RichText, Ui};
64use egui_pop_core::state::Slot;
65use egui_pop_core::strings;
66use egui_pop_core::theme::Tokens;
67use egui_pop_core::ui::UiPop as _;
68use egui_pop_core::widgets;
69use egui_pop_model::commands::{CommandSpec, Origin};
70use egui_pop_model::ids::{CommandId, PanelId, PluginId};
71use egui_pop_model::panels::{Area, PanelSpec};
72use serde_json::{Value as Json, json};
73
74use crate::app::AppHandle;
75use crate::history::{self, At, Line, ScopeId, StepInfo, Walk};
76use crate::host::source_of;
77use crate::steps::Outcome;
78use crate::strings as txt;
79use crate::toasts;
80use crate::{Ctx, Plugin, PluginError};
81
82/// The plugin's id.
83pub const PLUGIN: PluginId = PluginId::from_static("egui_pop.history");
84
85/// The history panel.
86pub const PANEL_HISTORY: PanelId = PanelId::from_static("egui_pop.history");
87
88/// Every scope, whether it is active, where Undo and Redo go.
89pub const CMD_LIST: CommandId = CommandId::from_static("history.list");
90/// A scope's steps.
91pub const CMD_READ: CommandId = CommandId::from_static("history.read");
92/// Undoes in a scope.
93pub const CMD_UNDO: CommandId = CommandId::from_static("history.undo");
94/// Redoes in a scope.
95pub const CMD_REDO: CommandId = CommandId::from_static("history.redo");
96/// Brings a scope to one of its steps.
97pub const CMD_JUMP: CommandId = CommandId::from_static("history.jump");
98/// Takes a snapshot of a scope.
99pub const CMD_SNAPSHOT: CommandId = CommandId::from_static("history.snapshot");
100/// Brings a scope back to one of its snapshots.
101pub const CMD_RESTORE: CommandId = CommandId::from_static("history.restore");
102/// Deletes a snapshot.
103pub const CMD_DROP_SNAPSHOT: CommandId = CommandId::from_static("history.drop_snapshot");
104/// Undoes one step of a scope out of order.
105pub const CMD_UNDO_STEP: CommandId = CommandId::from_static("history.undo_step");
106
107/// The scope the panel shows, once the user picked one.
108const CHOSEN: Slot<ScopeId> = Slot::new("egui_pop.history.scope");
109
110/// Whether the panel shows the steps new steps replaced.
111const SHOW_REPLACED: Slot<bool> = Slot::new("egui_pop.history.replaced");
112
113/// The history panel and the `history.*` commands.
114#[derive(Clone, Debug)]
115pub struct HistoryPlugin {
116    panel: bool,
117}
118
119impl Default for HistoryPlugin {
120    fn default() -> Self {
121        Self { panel: true }
122    }
123}
124
125impl HistoryPlugin {
126    /// Without the panel: the commands only (an application drawing
127    /// [`show`] where it wants).
128    pub fn without_panel(mut self) -> Self {
129        self.panel = false;
130        self
131    }
132}
133
134impl Plugin for HistoryPlugin {
135    fn id(&self) -> PluginId {
136        PLUGIN
137    }
138
139    fn title(&self) -> String {
140        "History".into()
141    }
142
143    fn connect(&mut self, ctx: &mut Ctx<'_>) -> Result<(), PluginError> {
144        let category = "Edit";
145        ctx.command(
146            CommandSpec::new(CMD_LIST, "List the histories", category)
147                .description("Every history (its scope: id, title, whether it is local or durable, its cap), whether it is active in the window, its revision, head and counts, and where Undo and Redo go now with what they would do.")
148                .hidden()
149                .read_only(),
150            |call| Ok(history::snapshot(call.app)),
151        )?
152        .command(
153            CommandSpec::new(CMD_READ, "Read a history", category)
154                .description("A history's steps (`scope`; none: where Undo goes now): `undo`, oldest first, and `redo`, the next one last; each step's id, label and its text in the interface's language, origin, group, place and time; the history's revision and head; its `snapshots`, the `replaced` steps its owner keeps (each with the step it came `after`) and the `features` its owner supports.")
155                .args(json!({ "scope": "app" }))
156                .hidden()
157                .read_only(),
158            |call| {
159                let scope = scope_arg(call.app, call.args, Walk::Undo)?;
160                let line = history::line(call.app, &scope)
161                    .ok_or_else(|| format!("no history `{scope}`"))?;
162                Ok(read(call.app, &scope, &line))
163            },
164        )?
165        .command(
166            CommandSpec::new(CMD_UNDO, "Undo in a history", category)
167                .icon("undo")
168                .description("Undoes the last step of a history (`scope`; none: where Undo goes now), refused unless its revision is still `if_rev`; with `dry_run`, only says what it would undo.")
169                .args(json!({ "scope": "app", "if_rev": null, "dry_run": false }))
170                .hidden(),
171            |call| walk(call.app, call.args, Walk::Undo, call.origin),
172        )?
173        .command(
174            CommandSpec::new(CMD_REDO, "Redo in a history", category)
175                .icon("redo")
176                .description("Redoes the last undone step of a history (`scope`; none: where Redo goes now), refused unless its revision is still `if_rev`; with `dry_run`, only says what it would redo.")
177                .args(json!({ "scope": "app", "if_rev": null, "dry_run": false }))
178                .hidden(),
179            |call| walk(call.app, call.args, Walk::Redo, call.origin),
180        )?
181        .command(
182            CommandSpec::new(CMD_JUMP, "Jump in a history", category)
183                .icon("history")
184                .description("Brings a history (`scope`) to one of its steps (`to`, its id; 0: the start) by undos or redos, all or nothing, refused unless its revision is still `if_rev`; with `dry_run`, only says which steps it would walk.")
185                .args(json!({ "scope": "app", "to": 0, "if_rev": null, "dry_run": false }))
186                .hidden(),
187            |call| {
188                let to = call.args["to"]
189                    .as_u64()
190                    .ok_or_else(|| "`to` is missing: a step's id, or 0".to_string())?;
191                walk(call.app, call.args, Walk::Jump(to), call.origin)
192            },
193        )?
194        .command(
195            CommandSpec::new(CMD_SNAPSHOT, "Take a snapshot", category)
196                .description("Pins a history's current state (`scope`; none: where Undo goes now) under `name` (none: numbered), refused unless its revision is still `if_rev`, or when its owner has no snapshots; with `dry_run`, only says what it would take.")
197                .args(json!({ "scope": "app", "name": "Before the agent", "if_rev": null, "dry_run": false }))
198                .hidden(),
199            |call| {
200                let (scope, if_rev, dry_run) = request_args(call.args)?;
201                let name = match call.args.get("name").and_then(Json::as_str) {
202                    Some(n) => n.to_string(),
203                    None => next_name(call.app, scope.as_ref()),
204                };
205                let snap = history::take_snapshot(
206                    call.app,
207                    scope.as_ref(),
208                    &name,
209                    if_rev,
210                    dry_run,
211                    call.origin,
212                )
213                .map_err(|r| r.reason)?;
214                let mut out = json!({ "snapshot": snap });
215                if dry_run {
216                    out["dry_run"] = json!(true);
217                }
218                Ok(out)
219            },
220        )?
221        .command(
222            CommandSpec::new(CMD_RESTORE, "Restore a snapshot", category)
223                .description("Brings a history (`scope`; none: where Undo goes now) back to one of its snapshots (`snapshot`, its id) as one new step an undo takes back, refused unless its revision is still `if_rev`; with `dry_run`, only says what it would change.")
224                .args(json!({ "scope": "app", "snapshot": 1, "if_rev": null, "dry_run": false }))
225                .hidden(),
226            |call| {
227                let id = id_arg(call.args, "snapshot", "a snapshot's id")?;
228                walk(call.app, call.args, Walk::Restore(id), call.origin)
229            },
230        )?
231        .command(
232            CommandSpec::new(CMD_DROP_SNAPSHOT, "Delete a snapshot", category)
233                .description("Deletes one of a history's snapshots (`scope`; none: where Undo goes now; `snapshot`, its id), refused unless its revision is still `if_rev`; with `dry_run`, only checks it is there.")
234                .args(json!({ "scope": "app", "snapshot": 1, "if_rev": null, "dry_run": false }))
235                .hidden(),
236            |call| {
237                let id = id_arg(call.args, "snapshot", "a snapshot's id")?;
238                let (scope, if_rev, dry_run) = request_args(call.args)?;
239                history::forget_snapshot(call.app, scope.as_ref(), id, if_rev, dry_run, call.origin)
240                    .map_err(|r| r.reason)?;
241                Ok(json!({ "deleted": id, "dry_run": dry_run }))
242            },
243        )?
244        .command(
245            CommandSpec::new(CMD_UNDO_STEP, "Undo one step", category)
246                .description("Undoes one step of a history (`scope`; none: where Undo goes now; `step`, its id) out of order: the newest as an undo does, an older one by a new step putting its values back, refused when a later step changed one of them or when its owner does not allow it, and unless its revision is still `if_rev`; with `dry_run`, only checks it.")
247                .args(json!({ "scope": "app", "step": 3, "if_rev": null, "dry_run": false }))
248                .hidden(),
249            |call| {
250                let id = id_arg(call.args, "step", "a step's id")?;
251                walk(call.app, call.args, Walk::UndoStep(id), call.origin)
252            },
253        )?;
254        if self.panel {
255            ctx.panel(
256                PanelSpec::new(PANEL_HISTORY, "History", Area::EndSide)
257                    .min_size(160.0)
258                    .default_size(240.0)
259                    .icon("history")
260                    .closed(),
261                |ui, app| {
262                    ui.scroll_area(
263                        egui::ScrollArea::vertical().auto_shrink([false, false]),
264                        |ui| show(ui, app),
265                    );
266                },
267            )?;
268        }
269        Ok(())
270    }
271}
272
273/// The `scope` argument, else where the keys go now.
274fn scope_arg(app: &AppHandle, args: &Json, what: Walk) -> Result<ScopeId, String> {
275    match args.get("scope").and_then(Json::as_str) {
276        Some(s) => ScopeId::new(s).map_err(|e| format!("`scope`: {e}")),
277        None => history::target(app, what == Walk::Redo)
278            .map(|t| t.scope())
279            .ok_or_else(|| "no history to read".to_string()),
280    }
281}
282
283/// A request's `scope` (none: where the keys go), `if_rev` and
284/// `dry_run`.
285fn request_args(args: &Json) -> Result<(Option<ScopeId>, Option<u64>, bool), String> {
286    let scope = match args.get("scope").and_then(Json::as_str) {
287        Some(s) => Some(ScopeId::new(s).map_err(|e| format!("`scope`: {e}"))?),
288        None => None,
289    };
290    Ok((
291        scope,
292        args.get("if_rev").and_then(Json::as_u64),
293        args["dry_run"] == true,
294    ))
295}
296
297/// A required id argument.
298fn id_arg(args: &Json, name: &str, what: &str) -> Result<u64, String> {
299    args[name]
300        .as_u64()
301        .ok_or_else(|| format!("`{name}` is missing: {what}"))
302}
303
304/// A new snapshot's name: "Snapshot 3" after two.
305fn next_name(app: &AppHandle, scope: Option<&ScopeId>) -> String {
306    let scope = scope
307        .cloned()
308        .or_else(|| history::target(app, false).map(|t| t.scope()));
309    let n = scope.map_or(0, |s| history::snapshots(app, &s).len()) + 1;
310    strings::tr_with(&app.egui(), &txt::HISTORY_SNAPSHOT_NAME, &[("n", n.into())])
311}
312
313/// An undo, a redo, a jump, a restore or one step undone, asked by a
314/// command.
315fn walk(app: &AppHandle, args: &Json, what: Walk, origin: &Origin) -> Result<Json, String> {
316    let (scope, if_rev, dry_run) = request_args(args)?;
317    match history::ask(app, what, scope.as_ref(), if_rev, dry_run, origin) {
318        Outcome::Done(r) => r,
319        Outcome::Vetoed { by, reason } => Err(format!("vetoed by {by}: {reason}")),
320    }
321}
322
323/// A step with its label in the interface's language.
324fn step_json(ctx: &egui::Context, step: &StepInfo) -> Json {
325    let mut v = json!(step);
326    v["text"] = json!(history::label_text(ctx, &step.label));
327    v
328}
329
330/// What `history.read` answers.
331fn read(app: &AppHandle, scope: &ScopeId, line: &Line) -> Json {
332    let ctx = app.egui();
333    let replaced: Vec<Json> = history::replaced(app, scope)
334        .iter()
335        .map(|r| {
336            let mut v = step_json(&ctx, &r.step);
337            v["after"] = json!(r.after);
338            v
339        })
340        .collect();
341    json!({
342        "scope": scope,
343        "rev": line.rev,
344        "head": line.head_id(),
345        "undo": line.undo.iter().map(|s| step_json(&ctx, s)).collect::<Vec<_>>(),
346        "redo": line.redo.iter().map(|s| step_json(&ctx, s)).collect::<Vec<_>>(),
347        "snapshots": history::snapshots(app, scope),
348        "replaced": replaced,
349        "features": history::features(app, scope),
350    })
351}
352
353/// The scope the panel shows: the one picked, while it is there; else
354/// where Ctrl+Z goes; else the first.
355pub fn shown_scope(app: &AppHandle) -> Option<ScopeId> {
356    let all = history::scopes(app);
357    let ctx = app.egui();
358    CHOSEN
359        .get(&ctx)
360        .filter(|s| all.iter().any(|i| i.id == *s))
361        .or_else(|| history::target(app, false).map(|t| t.scope()))
362        .filter(|s| all.iter().any(|i| i.id == *s))
363        .or_else(|| all.first().map(|s| s.id.clone()))
364}
365
366/// Shows `scope` in the panel from now on.
367pub fn choose(app: &AppHandle, scope: ScopeId) {
368    CHOSEN.set(&app.egui(), scope);
369}
370
371/// What a step's row says: its label, and who made it when it was not
372/// the user.
373pub fn row_text(ctx: &egui::Context, step: &StepInfo) -> String {
374    let label = history::label_text(ctx, &step.label);
375    match step.origin {
376        Origin::User => label,
377        _ => strings::tr_args(
378            ctx,
379            &txt::HISTORY_BY,
380            &[("label", &label), ("origin", &source_of(&step.origin))],
381        ),
382    }
383}
384
385/// What a click or a context menu asks of the panel.
386enum Act {
387    Jump(u64),
388    Restore(u64),
389    Forget(u64),
390    UndoStep(u64),
391    Snapshot,
392}
393
394/// A row's hover: the point it previews, the owner's answer beside the
395/// row's hint.
396fn previewed(
397    response: egui::Response,
398    app: &AppHandle,
399    view: egui::Id,
400    scope: &ScopeId,
401    at: At,
402    hint: &str,
403) -> egui::Response {
404    if !response.hovered() {
405        return response.on_hover_text(hint);
406    }
407    let preview = history::hover_in(app, view, scope, at);
408    let changes = preview.map(|p| p.changes).unwrap_or_default();
409    if changes.is_empty() {
410        return response.on_hover_text(hint);
411    }
412    response.on_hover_ui(|ui| {
413        ui.label(hint);
414        ui.separator();
415        let ctx = ui.ctx().clone();
416        for c in &changes {
417            ui.label(strings::tr_args(
418                &ctx,
419                &txt::HISTORY_PREVIEW_CHANGE,
420                &[("what", &c.what), ("then", &c.then), ("now", &c.now)],
421            ));
422        }
423    })
424}
425
426/// The history panel's content: the scopes as chips when there are
427/// several; the snapshots, when the owner keeps them; then the shown
428/// scope's steps under "Start" (the replaced ones behind a toggle). A
429/// click on a row jumps there (a snapshot's restores it); hovering a row
430/// asks the owner for a preview; a step's context menu undoes that one
431/// step, when the owner allows it.
432pub fn show(ui: &mut Ui, app: &AppHandle) {
433    let view = ui.scope_id();
434    rows(ui, app, view);
435    // After the rows: a preview none of them asked for in this pass ends.
436    history::rows_drawn(app, view);
437}
438
439fn rows(ui: &mut Ui, app: &AppHandle, view: egui::Id) {
440    let ctx = ui.ctx().clone();
441    let all = history::scopes(app);
442    let Some(scope) = shown_scope(app) else {
443        ui.weak(strings::tr(&ctx, &txt::HISTORY_NONE));
444        return;
445    };
446    if all.len() > 1 {
447        ui.horizontal_wrapped(|ui| {
448            for s in &all {
449                if ui
450                    .add(widgets::SelectableRow::new(s.id == scope, s.title.as_str()))
451                    .clicked()
452                {
453                    choose(app, s.id.clone());
454                }
455            }
456        });
457        ui.separator();
458    }
459    let line = history::line(app, &scope).unwrap_or_default();
460    let features = history::features(app, &scope);
461    let snapshots = history::snapshots(app, &scope);
462    let replaced = history::replaced(app, &scope);
463    let muted = Tokens::of(&ctx).text.muted;
464    let hint = strings::tr(&ctx, &txt::HISTORY_JUMP);
465    let mut act = None;
466    if features.snapshots || !snapshots.is_empty() {
467        ui.label(RichText::new(strings::tr(&ctx, &txt::HISTORY_SNAPSHOTS)).strong());
468        let restore_hint = strings::tr(&ctx, &txt::HISTORY_RESTORE_HINT);
469        let pending_hint = format!(
470            "{restore_hint}\n{}",
471            strings::tr(&ctx, &txt::HISTORY_SNAPSHOT_PENDING_HINT)
472        );
473        for snap in &snapshots {
474            // A snapshot its owner keeps only at its next save says so.
475            let (text, hint) = if snap.pending {
476                let name = strings::tr_args(
477                    &ctx,
478                    &txt::HISTORY_SNAPSHOT_PENDING,
479                    &[("name", &snap.name)],
480                );
481                (RichText::new(name).italics(), &pending_hint)
482            } else {
483                (RichText::new(snap.name.as_str()), &restore_hint)
484            };
485            let r = ui.add(widgets::SelectableRow::new(false, text));
486            let r = previewed(r, app, view, &scope, At::Snapshot(snap.id), hint);
487            if r.clicked() {
488                act = Some(Act::Restore(snap.id));
489            }
490            egui_pop_core::pointer::claim::context_menu(&r, |ui| {
491                if ui
492                    .button(strings::tr(&ctx, &txt::HISTORY_RESTORE))
493                    .clicked()
494                {
495                    act = Some(Act::Restore(snap.id));
496                    ui.close();
497                }
498                if ui
499                    .button(strings::tr(&ctx, &txt::HISTORY_DELETE_SNAPSHOT))
500                    .clicked()
501                {
502                    act = Some(Act::Forget(snap.id));
503                    ui.close();
504                }
505            });
506        }
507        if features.snapshots
508            && ui
509                .button(strings::tr(&ctx, &txt::HISTORY_TAKE_SNAPSHOT))
510                .clicked()
511        {
512            act = Some(Act::Snapshot);
513        }
514        ui.separator();
515    }
516    let show_replaced = !replaced.is_empty() && SHOW_REPLACED.get(&ctx).unwrap_or(false);
517    let mut drawn_replaced = vec![false; replaced.len()];
518    // The replaced steps whose line left after `after`, under its row.
519    let mut replaced_after = |ui: &mut Ui, after: Option<u64>, act: &mut Option<Act>| {
520        if !show_replaced {
521            return;
522        }
523        for (i, r) in replaced.iter().enumerate() {
524            if drawn_replaced[i] || after.is_some_and(|a| a != r.after) {
525                continue;
526            }
527            drawn_replaced[i] = true;
528            let label = history::label_text(&ctx, &r.step.label);
529            let text = strings::tr_args(&ctx, &txt::HISTORY_REPLACED, &[("label", &label)]);
530            let text = RichText::new(text).color(muted).italics();
531            let row = ui.add(widgets::SelectableRow::new(false, text));
532            if previewed(row, app, view, &scope, At::Step(r.step.id), &hint).clicked() {
533                *act = Some(Act::Jump(r.step.id));
534            }
535        }
536    };
537    let start = strings::tr(&ctx, &txt::HISTORY_START);
538    let r = ui.add(widgets::SelectableRow::new(
539        line.undo.is_empty(),
540        start.as_str(),
541    ));
542    if previewed(r, app, view, &scope, At::Step(0), &hint).clicked() && !line.undo.is_empty() {
543        act = Some(Act::Jump(0));
544    }
545    replaced_after(ui, Some(0), &mut act);
546    let head = line.head_id();
547    let undo_this = strings::tr(&ctx, &txt::HISTORY_UNDO_THIS);
548    for step in &line.undo {
549        let here = step.id == head;
550        let r = ui.add(widgets::SelectableRow::new(here, row_text(&ctx, step)));
551        let r = previewed(r, app, view, &scope, At::Step(step.id), &hint);
552        if r.clicked() && !here {
553            act = Some(Act::Jump(step.id));
554        }
555        if features.undo_step {
556            egui_pop_core::pointer::claim::context_menu(&r, |ui| {
557                if ui.button(undo_this.as_str()).clicked() {
558                    act = Some(Act::UndoStep(step.id));
559                    ui.close();
560                }
561            });
562        }
563        replaced_after(ui, Some(step.id), &mut act);
564    }
565    for step in line.redo.iter().rev() {
566        let text = RichText::new(row_text(&ctx, step)).color(muted);
567        let r = ui.add(widgets::SelectableRow::new(false, text));
568        if previewed(r, app, view, &scope, At::Step(step.id), &hint).clicked() {
569            act = Some(Act::Jump(step.id));
570        }
571        replaced_after(ui, Some(step.id), &mut act);
572    }
573    // Lines that left from a step no longer shown.
574    replaced_after(ui, None, &mut act);
575    if !replaced.is_empty() {
576        let mut on = SHOW_REPLACED.get(&ctx).unwrap_or(false);
577        if widgets::checkbox(ui, &mut on, strings::tr(&ctx, &txt::HISTORY_SHOW_REPLACED)).changed()
578        {
579            SHOW_REPLACED.set(&ctx, on);
580        }
581    }
582    if let Some(act) = act {
583        run_act(app, &scope, act);
584    }
585}
586
587/// Runs what the panel asked, as the user; a refusal says why in a
588/// toast.
589fn run_act(app: &AppHandle, scope: &ScopeId, act: Act) {
590    history::end_preview(app);
591    let user = Origin::User;
592    let refusal = match act {
593        Act::Jump(to) => outcome_error(history::jump(app, scope, to, &user)),
594        Act::Restore(id) => outcome_error(history::restore(app, scope, id, &user)),
595        Act::UndoStep(id) => outcome_error(history::undo_step(app, scope, id, &user)),
596        Act::Forget(id) => history::forget_snapshot(app, Some(scope), id, None, false, &user)
597            .err()
598            .map(|r| r.reason),
599        Act::Snapshot => {
600            let name = next_name(app, Some(scope));
601            history::take_snapshot(app, Some(scope), &name, None, false, &user)
602                .err()
603                .map(|r| r.reason)
604        }
605    };
606    if let Some(reason) = refusal
607        && let Some(toasts) = app.service(&toasts::TOASTS)
608    {
609        toasts.notify(toasts::Toast::warning(&reason));
610    }
611}
612
613fn outcome_error(outcome: Outcome) -> Option<String> {
614    match outcome {
615        Outcome::Done(Ok(_)) => None,
616        Outcome::Done(Err(e)) => Some(e),
617        Outcome::Vetoed { reason, .. } => Some(reason),
618    }
619}