arc-flow-core 0.2.0

Framework-free graph model for arc-flow: nodes, typed ports, edges, reversible ops, history, validation, edge geometry and spatial index.
Documentation
//! 撤销 / 重做栈:只存逆操作,不存快照(相较 gpui-flow 的整图快照,内存与图规模无关)。

use crate::graph::{Graph, GraphError};
use crate::op::GraphOp;

/// 默认最多保留的撤销步数。
pub const DEFAULT_HISTORY_LIMIT: usize = 200;

#[derive(Clone, Debug)]
struct Entry {
    label: &'static str,
    inverse: GraphOp,
    /// 相同 key 的连续提交合并为一步(例如键盘微移、连续改名)。
    merge_key: Option<u64>,
}

#[derive(Clone, Debug)]
pub struct History {
    undo: Vec<Entry>,
    redo: Vec<Entry>,
    limit: usize,
    sealed: bool,
}

impl Default for History {
    fn default() -> Self {
        Self::new(DEFAULT_HISTORY_LIMIT)
    }
}

impl History {
    pub fn new(limit: usize) -> Self {
        Self {
            undo: Vec::new(),
            redo: Vec::new(),
            limit: limit.max(1),
            sealed: true,
        }
    }

    /// 应用并记录一步。
    pub fn commit(
        &mut self,
        g: &mut Graph,
        op: GraphOp,
        label: &'static str,
    ) -> Result<(), GraphError> {
        self.commit_inner(g, op, label, None)
    }

    /// 应用并与上一步合并(若上一步 key 相同且未被 [`Self::seal`])。
    pub fn commit_merged(
        &mut self,
        g: &mut Graph,
        op: GraphOp,
        label: &'static str,
        key: u64,
    ) -> Result<(), GraphError> {
        self.commit_inner(g, op, label, Some(key))
    }

    fn commit_inner(
        &mut self,
        g: &mut Graph,
        op: GraphOp,
        label: &'static str,
        key: Option<u64>,
    ) -> Result<(), GraphError> {
        if op.is_empty() {
            return Ok(());
        }
        let inverse = g.apply(op)?;
        self.record(inverse, label, key);
        Ok(())
    }

    /// 记录一个已经应用过的修改(例如拖拽过程中逐帧直接改坐标,松手时只记一次)。
    pub fn record(&mut self, inverse: GraphOp, label: &'static str, key: Option<u64>) {
        self.redo.clear();
        if let (Some(k), false, Some(top)) = (key, self.sealed, self.undo.last_mut())
            && top.merge_key == Some(k)
        {
            // 新逆操作先执行、旧逆操作后执行,才能回到合并前的状态。
            let older = std::mem::replace(&mut top.inverse, GraphOp::Batch(Vec::new()));
            top.inverse = GraphOp::Batch(vec![inverse, older]);
            return;
        }
        self.undo.push(Entry {
            label,
            inverse,
            merge_key: key,
        });
        if self.undo.len() > self.limit {
            self.undo.remove(0);
        }
        self.sealed = key.is_none();
    }

    /// 结束当前合并窗口(例如键盘微移后失焦)。
    pub fn seal(&mut self) {
        self.sealed = true;
    }

    pub fn can_undo(&self) -> bool {
        !self.undo.is_empty()
    }

    pub fn can_redo(&self) -> bool {
        !self.redo.is_empty()
    }

    pub fn undo_label(&self) -> Option<&'static str> {
        self.undo.last().map(|e| e.label)
    }

    pub fn redo_label(&self) -> Option<&'static str> {
        self.redo.last().map(|e| e.label)
    }

    pub fn undo(&mut self, g: &mut Graph) -> Result<Option<&'static str>, GraphError> {
        let Some(entry) = self.undo.pop() else {
            return Ok(None);
        };
        let redo = g.apply(entry.inverse)?;
        self.redo.push(Entry {
            label: entry.label,
            inverse: redo,
            merge_key: None,
        });
        self.sealed = true;
        Ok(Some(entry.label))
    }

    pub fn redo(&mut self, g: &mut Graph) -> Result<Option<&'static str>, GraphError> {
        let Some(entry) = self.redo.pop() else {
            return Ok(None);
        };
        let undo = g.apply(entry.inverse)?;
        self.undo.push(Entry {
            label: entry.label,
            inverse: undo,
            merge_key: None,
        });
        self.sealed = true;
        Ok(Some(entry.label))
    }

    pub fn clear(&mut self) {
        self.undo.clear();
        self.redo.clear();
        self.sealed = true;
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::geometry::{Size2, Vec2};

    #[test]
    fn undo_redo_cycle() {
        let mut g = Graph::new();
        let (a, _, _) = g.add_node_with("a", Vec2::ZERO, Size2::new(10.0, 10.0), 0, 0);
        let mut h = History::default();
        let start = g.to_json();
        h.commit(
            &mut g,
            GraphOp::MoveNodes {
                moves: vec![(a, Vec2::new(5.0, 0.0))],
            },
            "move",
        )
        .unwrap();
        let moved = g.to_json();
        assert_eq!(h.undo(&mut g).unwrap(), Some("move"));
        assert_eq!(g.to_json(), start);
        assert_eq!(h.redo(&mut g).unwrap(), Some("move"));
        assert_eq!(g.to_json(), moved);
    }

    #[test]
    fn merged_nudges_undo_in_one_step() {
        let mut g = Graph::new();
        let (a, _, _) = g.add_node_with("a", Vec2::ZERO, Size2::new(10.0, 10.0), 0, 0);
        let mut h = History::default();
        for i in 1..=5 {
            let op = GraphOp::MoveNodes {
                moves: vec![(a, Vec2::new(i as f32, 0.0))],
            };
            h.commit_merged(&mut g, op, "nudge", 7).unwrap();
        }
        assert_eq!(g.node(a).unwrap().pos.x, 5.0);
        h.undo(&mut g).unwrap();
        assert_eq!(g.node(a).unwrap().pos.x, 0.0);
        assert!(!h.can_undo());
        h.redo(&mut g).unwrap();
        assert_eq!(g.node(a).unwrap().pos.x, 5.0);
    }

    #[test]
    fn new_commit_clears_redo_and_limit_applies() {
        let mut g = Graph::new();
        let (a, _, _) = g.add_node_with("a", Vec2::ZERO, Size2::new(10.0, 10.0), 0, 0);
        let mut h = History::new(3);
        for i in 0..5 {
            let op = GraphOp::MoveNodes {
                moves: vec![(a, Vec2::new(i as f32, 0.0))],
            };
            h.commit(&mut g, op, "move").unwrap();
        }
        let mut n = 0;
        while h.undo(&mut g).unwrap().is_some() {
            n += 1;
        }
        assert_eq!(n, 3);
        h.commit(
            &mut g,
            GraphOp::ResizeNode {
                id: a,
                size: Size2::new(1.0, 1.0),
            },
            "resize",
        )
        .unwrap();
        assert!(!h.can_redo());
    }
}