Skip to main content

twrite_core/
history.rs

1use std::ops::Range;
2
3/// An individual textual modification within a document transaction.
4#[derive(Debug, Clone, PartialEq, Eq)]
5pub struct Edit {
6    /// The byte range in the document before this edit was applied.
7    pub bytes_range: Range<usize>,
8
9    /// The text inserted at [`Self::bytes_range`].
10    pub inserted_text: String,
11
12    /// The text that was present at [`Self::bytes_range`] before the edit.
13    pub deleted_text: String,
14}
15
16/// A group of edits that represents a single undoable operation.
17///
18/// A transaction may contain multiple edits that are undone and redone
19/// together. The cursor positions record the state before and after the
20/// transaction.
21///
22/// # Fields
23///
24/// * `edits` - The edits that make up this transaction.
25/// * `previous_cursor` - The cursor position before the transaction.
26/// * `resulting_cursor` - The cursor position after the transaction.
27#[derive(Debug, Clone, PartialEq, Eq)]
28pub struct Transaction {
29    /// The edits that make up this transaction.
30    pub edits: Vec<Edit>,
31
32    /// The cursor position before the transaction was applied.
33    pub previous_cursor: usize,
34
35    /// The cursor position after the transaction was applied.
36    pub resulting_cursor: usize,
37}
38
39/// Tracks the undo and redo history of a document.
40///
41/// Transactions are stored in the undo stack when they are applied.
42/// When a transaction is undone, it is moved to the redo stack. When
43/// it is redone, it is moved back to the undo stack.
44///
45/// The most recent transaction is stored at the end of each stack.
46///
47/// Adding a new edit after undoing previous edits should clear the
48/// redo stack, as the previous redo history is no longer applicable.
49#[derive(Debug, Default)]
50pub struct History {
51    /// Transactions that can currently be undone.
52    ///
53    /// The most recent transaction is at the end of the vector.
54    pub undo_stack: Vec<Transaction>,
55
56    /// Transactions that can currently be redone.
57    ///
58    /// The most recently undone transaction is at the end of the vector.
59    pub redo_stack: Vec<Transaction>,
60}