crisol-core 1.3.0

Crisol core: an egui-free data model, themes, metrics, localization, commands, state, and storage.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
//! Transactional undo and redo with a real tree, not a stack.
//!
//! Undo moves to the parent; editing after an undo adds a sibling branch instead of
//! discarding the abandoned one. A group coalesces typing or a drag into one node, and a
//! the History panel in `crisol::app` lets the user jump anywhere.
//!
//! ```
//! use crisol_core::state::history;
//! ```

use std::fmt;

/// A node in the undo tree.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(transparent))]
/// # Example
///
/// ```
/// use crisol_core::state::NodeId;
/// ```
pub struct NodeId(u64);

impl NodeId {
    /// The numeric id, for a journal or a label.
    pub const fn index(self) -> u64 {
        self.0
    }

    /// A node id from its numeric value, for lookups and journal replay.
    pub const fn from_index(index: u64) -> Self {
        Self(index)
    }
}

impl fmt::Display for NodeId {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "{}", self.0)
    }
}

/// One state snapshot in the tree.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
/// # Example
///
/// ```
/// use crisol_core::state::HistoryNode;
/// ```
pub struct HistoryNode<S> {
    /// Stable id.
    pub id: NodeId,
    /// Parent, `None` for the root.
    pub parent: Option<NodeId>,
    /// Children in creation order.
    pub children: Vec<NodeId>,
    /// A short label shown in the History panel.
    pub label: String,
    /// The state at this node.
    pub state: S,
    /// The coalescing group, when this node is still open.
    pub group: Option<u64>,
    /// When the node was recorded, in the application's clock.
    pub timestamp: f64,
}

/// A coalescing group: typing or a drag records one node until the group ends.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(transparent))]
/// # Example
///
/// ```
/// use crisol_core::state::GroupId;
/// ```
pub struct GroupId(u64);

impl GroupId {
    /// The numeric id.
    pub const fn index(self) -> u64 {
        self.0
    }
}

impl fmt::Display for GroupId {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "{}", self.0)
    }
}

/// Why a history operation failed.
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
/// # Example
///
/// ```
/// use crisol_core::state::HistoryError;
/// ```
pub enum HistoryError {
    /// The node id does not exist.
    #[error("unknown history node {0}")]
    UnknownNode(NodeId),
    /// The history is empty.
    #[error("the history is empty")]
    Empty,
    /// A group is already open.
    #[error("group {0} is already open")]
    GroupAlreadyOpen(GroupId),
    /// No group is open.
    #[error("no group is open")]
    NoGroup,
}

/// A tree of state snapshots with a current node.
///
/// ```
/// # use crisol_core::state::History;
/// let mut history = History::new("a".to_owned());
/// history.record("type b", "ab".to_owned());
/// history.record("type c", "abc".to_owned());
/// assert_eq!(history.state(), "abc");
/// history.undo();
/// assert_eq!(history.state(), "ab");
/// history.record("branch", "a!".to_owned());
/// assert_eq!(history.len(), 4, "the abandoned branch is still there");
/// ```
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct History<S> {
    nodes: Vec<HistoryNode<S>>,
    current: NodeId,
    next_id: u64,
    next_group: u64,
    active_group: Option<GroupId>,
    /// The node the last undo came from, so redo returns there even when the parent has
    /// since grown another branch (CORE-DET-05). Transient: not persisted.
    #[cfg_attr(feature = "serde", serde(skip))]
    redo_to: Option<NodeId>,
}

impl<S> History<S> {
    /// A history with one root node.
    pub fn new(initial: S) -> Self {
        Self {
            nodes: vec![HistoryNode {
                id: NodeId(0),
                parent: None,
                children: Vec::new(),
                label: "Initial".to_owned(),
                state: initial,
                group: None,
                timestamp: 0.0,
            }],
            current: NodeId(0),
            next_id: 1,
            next_group: 1,
            active_group: None,
            redo_to: None,
        }
    }

    /// The current node id.
    pub fn current(&self) -> NodeId {
        self.current
    }

    /// The current state.
    // The constructor always inserts the root and nodes are never removed, so these
    // internal ids are valid; the index is not user input.
    #[allow(clippy::indexing_slicing)]
    pub fn state(&self) -> &S {
        &self.nodes[self.current.0 as usize].state
    }

    /// The current node.
    // The constructor always inserts the root and nodes are never removed, so these
    // internal ids are valid; the index is not user input.
    #[allow(clippy::indexing_slicing)]
    pub fn current_node(&self) -> &HistoryNode<S> {
        &self.nodes[self.current.0 as usize]
    }

    /// A node by id.
    pub fn node(&self, id: NodeId) -> Option<&HistoryNode<S>> {
        self.nodes.iter().find(|node| node.id == id)
    }

    /// Every node, in creation order (the root first).
    pub fn nodes(&self) -> &[HistoryNode<S>] {
        &self.nodes
    }

    /// The number of nodes.
    pub fn len(&self) -> usize {
        self.nodes.len()
    }

    /// Whether there is only the root.
    pub fn is_empty(&self) -> bool {
        self.nodes.len() <= 1
    }

    /// Whether an undo is possible.
    // The constructor always inserts the root and nodes are never removed, so these
    // internal ids are valid; the index is not user input.
    #[allow(clippy::indexing_slicing)]
    pub fn can_undo(&self) -> bool {
        self.nodes[self.current.0 as usize].parent.is_some()
    }

    /// Whether a redo is possible.
    // The constructor always inserts the root and nodes are never removed, so these
    // internal ids are valid; the index is not user input.
    #[allow(clippy::indexing_slicing)]
    pub fn can_redo(&self) -> bool {
        !self.nodes[self.current.0 as usize].children.is_empty()
    }

    /// The open coalescing group.
    pub fn group(&self) -> Option<GroupId> {
        self.active_group
    }

    /// Start coalescing. Recording while a group is open updates the current node in
    /// place instead of adding a child.
    ///
    /// # Errors
    /// When a group is already open.
    pub fn begin_group(&mut self, _label: &str) -> Result<GroupId, HistoryError> {
        if let Some(group) = self.active_group {
            return Err(HistoryError::GroupAlreadyOpen(group));
        }
        let group = GroupId(self.next_group);
        self.next_group += 1;
        self.active_group = Some(group);
        Ok(group)
    }

    /// Stop coalescing.
    ///
    /// # Errors
    /// When no group is open.
    pub fn end_group(&mut self) -> Result<(), HistoryError> {
        if self.active_group.take().is_none() {
            return Err(HistoryError::NoGroup);
        }
        Ok(())
    }

    /// The path from the root to the current node.
    pub fn path(&self) -> Vec<NodeId> {
        let mut path = Vec::new();
        let mut node = Some(self.current);
        while let Some(id) = node {
            path.push(id);
            node = self.node(id).and_then(|node| node.parent);
        }
        path.reverse();
        path
    }

    /// Undo one step and return the new state.
    // The constructor always inserts the root and nodes are never removed, so these
    // internal ids are valid; the index is not user input.
    #[allow(clippy::indexing_slicing)]
    pub fn undo(&mut self) -> Option<&S> {
        let parent = self.nodes[self.current.0 as usize].parent?;
        self.redo_to = Some(self.current);
        self.active_group = None;
        self.current = parent;
        Some(self.state())
    }

    /// Redo the most recently created child.
    // The constructor always inserts the root and nodes are never removed, so these
    // internal ids are valid; the index is not user input.
    #[allow(clippy::indexing_slicing)]
    pub fn redo(&mut self) -> Option<&S> {
        let remembered = self
            .redo_to
            .filter(|id| self.nodes[self.current.0 as usize].children.contains(id));
        let child = match remembered {
            Some(id) => id,
            None => *self.nodes[self.current.0 as usize].children.last()?,
        };
        self.redo_to = None;
        self.active_group = None;
        self.current = child;
        Some(self.state())
    }

    /// Jump to a node.
    ///
    /// # Errors
    /// When the node id does not exist.
    pub fn jump_to(&mut self, id: NodeId) -> Result<&S, HistoryError> {
        if self.node(id).is_none() {
            return Err(HistoryError::UnknownNode(id));
        }
        self.redo_to = None;
        self.active_group = None;
        self.current = id;
        Ok(self.state())
    }
}

impl<S: Clone + PartialEq> History<S> {
    /// Record `state` as a child of the current node, or update the current node when a
    /// group is open and already owns it.
    // The constructor always inserts the root and nodes are never removed, so these
    // internal ids are valid; the index is not user input.
    #[allow(clippy::indexing_slicing)]
    pub fn record(&mut self, label: impl Into<String>, state: S) -> NodeId {
        self.redo_to = None;
        let label = label.into();
        if let Some(group) = self.active_group
            && self.current != NodeId(0)
            && self.current_node().group == Some(group.index())
        {
            let node = &mut self.nodes[self.current.0 as usize];
            node.state = state;
            node.label = label;
            return node.id;
        }
        if self.state() == &state {
            return self.current;
        }
        self.record_with_group(label, state, self.active_group.map(GroupId::index), 0.0)
    }

    /// Record a node with an explicit timestamp.
    pub fn record_at(&mut self, label: impl Into<String>, state: S, timestamp: f64) -> NodeId {
        self.record_with_group(label.into(), state, self.active_group.map(GroupId::index), timestamp)
    }

    // The constructor always inserts the root and nodes are never removed, so these
    // internal ids are valid; the index is not user input.
    #[allow(clippy::indexing_slicing)]
    fn record_with_group(&mut self, label: String, state: S, group: Option<u64>, timestamp: f64) -> NodeId {
        let id = NodeId(self.next_id);
        self.next_id += 1;
        self.nodes.push(HistoryNode {
            id,
            parent: Some(self.current),
            children: Vec::new(),
            label,
            state,
            group,
            timestamp,
        });
        self.nodes[self.current.0 as usize].children.push(id);
        self.current = id;
        id
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn undo_and_branch_keep_the_abandoned_path() {
        let mut history = History::new("a".to_owned());
        let second = history.record("b", "ab".to_owned());
        let third = history.record("c", "abc".to_owned());
        assert!(history.can_undo());
        assert!(!history.can_redo());
        history.undo();
        assert_eq!(history.state(), "ab");
        let branch = history.record("!", "a!".to_owned());
        assert_eq!(history.node(third).map(|node| node.label.as_str()), Some("c"));
        assert_eq!(history.node(second).map(|node| node.children.len()), Some(2));
        assert_eq!(history.node(branch).map(|node| node.state.as_str()), Some("a!"));
        assert_eq!(history.len(), 4);
    }

    #[test]
    fn redo_follows_the_last_child_and_jump_time_travels() {
        let mut history = History::new(0);
        history.record("one", 1);
        let two = history.record("two", 2);
        history.undo();
        history.undo();
        assert_eq!(history.state(), &0);
        history.redo();
        assert_eq!(history.state(), &1);
        history.jump_to(two).expect("node exists");
        assert_eq!(history.state(), &2);
        assert!(history.jump_to(NodeId(99)).is_err());
    }

    #[test]
    fn undo_then_redo_returns_to_the_undone_node() {
        let mut history = History::new(0);
        let branch = history.record("a", 1);
        history.undo();
        assert_eq!(history.redo(), Some(&1));
        assert_eq!(history.current(), branch);
    }

    #[test]
    fn a_group_coalesces_typing() {
        let mut history = History::new(String::new());
        history.begin_group("typing").expect("group");
        let first = history.record("t", "t".to_owned());
        let second = history.record("typing", "typing".to_owned());
        assert_eq!(first, second, "the open group updates the same node");
        history.end_group().expect("end");
        history.record("!", "typing!".to_owned());
        assert_eq!(history.len(), 3);
        assert!(history.end_group().is_err());
    }

    #[test]
    fn no_op_records_do_not_add_nodes() {
        let mut history = History::new(1);
        history.record("same", 1);
        assert_eq!(history.len(), 1);
    }

    #[cfg(feature = "serde")]
    #[test]
    fn the_undo_tree_survives_json() {
        let mut history = History::new("a".to_owned());
        history.record("b", "ab".to_owned());
        history.record("c", "abc".to_owned());
        history.undo();
        history.record("!", "a!".to_owned());
        let json = serde_json::to_string(&history).expect("serialize");
        let back: History<String> = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(back.state(), "a!");
        assert_eq!(back.len(), history.len());
        assert_eq!(back.current(), history.current());
    }
}