day-model 0.7.6

Property observable store.
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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
// Copyright © The Daybrite Project
// SPDX-License-Identifier: MPL-2.0

//! The undo stack: units are turns, inverted; and preview sessions, whose sixty writes cost
//! one record. All headless, against the plain in-memory store (persistence is optional to
//! undo, not the other way around).

use day_macros::Observable;
use day_model::{Keyed, Op, Store, UndoStack};
use day_reactive::Binding;

#[derive(Observable, Clone, Default, PartialEq, Debug)]
pub struct Item {
    #[obs(key)]
    pub id: u32,
    pub name: String,
    pub count: i64,
}

fn store() -> Store<Keyed<Item>> {
    Store::new(Keyed::new(vec![
        Item {
            id: 1,
            name: "one".into(),
            count: 10,
        },
        Item {
            id: 2,
            name: "two".into(),
            count: 20,
        },
    ]))
}

fn stack_over(store: Store<Keyed<Item>>) -> UndoStack {
    let stack = UndoStack::new(100);
    stack.watch(store);
    stack
}

#[test]
fn an_edit_undoes_and_redoes() {
    let store = store();
    let stack = stack_over(store);

    store.elem(1).name().write("renamed".into());
    day_reactive::flush_sync();
    assert!(stack.can_undo().get_untracked());
    assert_eq!(stack.undo_label().get_untracked(), "Name");

    assert!(stack.undo());
    assert_eq!(store.elem(1).name().peek(), "one");
    assert!(stack.can_redo().get_untracked());
    assert!(!stack.can_undo().get_untracked());

    assert!(stack.redo());
    assert_eq!(store.elem(1).name().peek(), "renamed");
    assert!(stack.can_undo().get_untracked());
}

#[test]
fn one_turn_is_one_unit() {
    let store = store();
    let stack = stack_over(store);

    day_reactive::batch(|| {
        store.elem(1).name().write("a".into());
        store.elem(1).count().write(99);
        store.elem(2).name().write("b".into());
    });
    day_reactive::flush_sync();

    assert!(stack.undo(), "one unit holds the whole turn");
    assert_eq!(store.elem(1).name().peek(), "one");
    assert_eq!(store.elem(1).count().peek(), 10);
    assert_eq!(store.elem(2).name().peek(), "two");
    assert!(!stack.can_undo().get_untracked(), "nothing left");
}

#[test]
fn an_undone_delete_comes_back_with_its_data() {
    let store = store();
    let stack = stack_over(store);

    store.restructure("remove", Op::Delete, 1, |v| {
        v.remove(1);
    });
    day_reactive::flush_sync();
    assert!(!store.elem(1).exists());

    assert!(stack.undo());
    assert!(store.elem(1).exists());
    assert_eq!(
        store.elem(1).name().peek(),
        "one",
        "the row's data came back whole"
    );
    assert_eq!(store.elem(1).count().peek(), 10);

    assert!(stack.redo());
    assert!(!store.elem(1).exists());
}

#[test]
fn an_undone_insert_goes_away() {
    let store = store();
    let stack = stack_over(store);

    store.restructure("add", Op::Insert, 7, |v| {
        v.push(Item {
            id: 7,
            name: "seven".into(),
            count: 7,
        });
    });
    day_reactive::flush_sync();
    assert!(store.elem(7).exists());

    assert!(stack.undo());
    assert!(!store.elem(7).exists());
    assert!(stack.redo());
    assert_eq!(store.elem(7).name().peek(), "seven");
}

#[test]
fn a_new_edit_forks_history() {
    let store = store();
    let stack = stack_over(store);

    store.elem(1).name().write("first".into());
    day_reactive::flush_sync();
    stack.undo();
    assert!(stack.can_redo().get_untracked());

    store.elem(1).name().write("second".into());
    day_reactive::flush_sync();
    assert!(!stack.can_redo().get_untracked(), "redo died with the fork");
}

#[test]
fn grouped_changes_are_one_named_unit() {
    let store = store();
    let stack = stack_over(store);

    stack.grouped("rename-everything", || {
        store.elem(1).name().write("x".into());
        day_reactive::flush_sync();
        store.elem(2).name().write("y".into());
        day_reactive::flush_sync();
    });
    assert_eq!(stack.undo_label().get_untracked(), "Rename everything");

    assert!(stack.undo());
    assert_eq!(store.elem(1).name().peek(), "one");
    assert_eq!(store.elem(2).name().peek(), "two");
    assert!(!stack.can_undo().get_untracked());
}

#[test]
fn depth_is_bounded() {
    let store = store();
    let stack = UndoStack::new(3);
    stack.watch(store);

    for i in 0..10 {
        store.elem(1).count().write(i);
        day_reactive::flush_sync();
    }
    let mut undone = 0;
    while stack.undo() {
        undone += 1;
    }
    assert_eq!(undone, 3, "history holds exactly `levels` units");
    assert_eq!(
        store.elem(1).count().peek(),
        6,
        "back three steps, no further"
    );
}

#[test]
fn a_storm_of_previews_is_one_record_and_one_unit() {
    let store = store();
    let stack = stack_over(store);
    let field = store.elem(1).count();

    let ((), changes) = day_model::record_changes(|| {
        for i in 0..60 {
            field.write_preview(i);
        }
    });
    assert_eq!(changes.len(), 0, "sixty previews, zero records");
    assert_eq!(field.peek(), 59, "the store follows live");

    let ((), changes) = day_model::record_changes(|| {
        field.write_commit(50);
    });
    assert_eq!(changes.len(), 1, "one committed record for the gesture");
    assert_eq!(
        changes[0].prior_as::<i64>(),
        Some(&10),
        "prior predates the storm"
    );
    assert_eq!(changes[0].value_as::<i64>(), Some(&50));

    day_reactive::flush_sync();
    assert!(stack.undo());
    assert_eq!(
        field.peek(),
        10,
        "undo restores the pre-drag value in one step"
    );
}

#[test]
fn a_cancelled_session_leaves_nothing() {
    let store = store();
    let stack = stack_over(store);
    let field = store.elem(1).name();

    let s = field.session();
    let ((), changes) = day_model::record_changes(|| {
        s.preview("half-ty".into());
        s.preview("half-typed".into());
        s.cancel();
    });
    assert_eq!(changes.len(), 0);
    assert_eq!(field.peek(), "one", "Escape restores");
    day_reactive::flush_sync();
    assert!(!stack.can_undo().get_untracked(), "no unit either");
}

#[test]
fn preview_wakes_readers_but_not_sinks() {
    let store = store();
    let field = store.elem(1).count();
    let seen = std::rc::Rc::new(std::cell::Cell::new(0));
    let s2 = seen.clone();
    day_reactive::Effect::new(move || {
        let _ = field.read();
        s2.set(s2.get() + 1);
    });
    assert_eq!(seen.get(), 1);

    field.write_preview(77);
    day_reactive::flush_sync();
    assert_eq!(
        seen.get(),
        2,
        "the label tracking the slider follows the drag"
    );
}

#[test]
fn replay_changes_carry_the_author_tag() {
    let store = store();
    let stack = stack_over(store);
    store.elem(1).name().write("tagged".into());
    day_reactive::flush_sync();

    let ((), changes) = day_model::record_changes(|| {
        stack.undo();
    });
    assert!(!changes.is_empty());
    assert!(
        changes.iter().all(|c| c.author == Some("undo")),
        "consumers can tell an undo from the user: {changes:?}"
    );
}

#[test]
fn a_wholesale_rewrite_clears_history() {
    let store = store();
    let stack = stack_over(store);
    store.elem(1).name().write("x".into());
    day_reactive::flush_sync();
    assert!(stack.can_undo().get_untracked());

    store.update("import", |k| {
        *k = Keyed::new(vec![Item {
            id: 9,
            name: "fresh".into(),
            count: 0,
        }]);
    });
    day_reactive::flush_sync();
    assert!(
        !stack.can_undo().get_untracked(),
        "history no longer describes reachable states"
    );
}

#[test]
fn transient_context_rides_the_history() {
    use std::cell::RefCell;
    use std::rc::Rc;

    let store = store();
    let stack = stack_over(store);

    // The app's "selection": a plain value outside the store, snapshotted per unit.
    let selection: Rc<RefCell<Vec<u32>>> = Rc::new(RefCell::new(Vec::new()));
    {
        let cap = selection.clone();
        let res = selection.clone();
        stack.set_transient_context(
            move || Rc::new(cap.borrow().clone()),
            move |ctx| {
                if let Some(sel) = ctx.downcast_ref::<Vec<u32>>() {
                    *res.borrow_mut() = sel.clone();
                }
            },
        );
    }

    // Select 1, edit it; select 2, edit it. The selection changes themselves are no units.
    *selection.borrow_mut() = vec![1];
    store.elem(1).count().write(11);
    day_reactive::flush_sync();
    *selection.borrow_mut() = vec![2];
    store.elem(2).count().write(22);
    day_reactive::flush_sync();

    // Undo lands on the state after item 1's edit, where 1 was selected, not 2.
    assert!(stack.undo());
    assert_eq!(*selection.borrow(), vec![1]);
    assert_eq!(store.elem(2).count().peek(), 20);

    // Redo lands back on item 2's edit, with its selection.
    assert!(stack.redo());
    assert_eq!(*selection.borrow(), vec![2]);
    assert_eq!(store.elem(2).count().peek(), 22);

    // Transient means transient: a selection change after the last unit is not history, so
    // the sealed snapshot wins on the next undo.
    *selection.borrow_mut() = vec![1, 2];
    assert!(stack.undo());
    assert_eq!(*selection.borrow(), vec![1]);

    // Undoing the whole history lands on the base snapshot taken at install: nothing selected.
    assert!(stack.undo());
    assert!(selection.borrow().is_empty());
    assert!(!stack.can_undo().get_untracked());
}

#[test]
fn a_guard_groups_multiple_turns_and_nested_groups() {
    let store = store();
    let stack = stack_over(store);
    let group = stack.begin_group("duplicate");
    store.elem(1).name().write("copy".into());
    day_reactive::flush_sync();
    stack.grouped("move", || {
        store.elem(1).count().write(42);
    });
    day_reactive::flush_sync();
    assert!(!stack.can_undo().get_untracked());
    assert!(
        !stack.undo(),
        "an active gesture cannot be partially undone"
    );
    assert!(!stack.redo());
    drop(group);
    assert_eq!(stack.undo_label().get_untracked(), "Duplicate");
    assert!(stack.undo());
    assert_eq!(store.elem(1).name().peek(), "one");
    assert_eq!(store.elem(1).count().peek(), 10);
    assert!(!stack.can_undo().get_untracked());
    assert!(stack.redo());
    assert_eq!(store.elem(1).name().peek(), "copy");
    assert_eq!(store.elem(1).count().peek(), 42);
}

#[test]
fn an_empty_group_does_not_label_the_next_edit() {
    let store = store();
    let stack = stack_over(store);
    drop(stack.begin_group("duplicate"));
    store.elem(1).name().write("next".into());
    day_reactive::flush_sync();
    assert_ne!(stack.undo_label().get_untracked(), "Duplicate");
}

#[test]
fn a_move_and_a_delete_undo_to_their_original_rows() {
    let store = store();
    store.push(Item {
        id: 3,
        name: "three".into(),
        count: 30,
    });
    let stack = stack_over(store);

    assert!(store.move_row(2, 0));
    day_reactive::flush_sync();
    assert_eq!(store.keys(), vec![3, 1, 2]);
    assert!(stack.undo());
    assert_eq!(store.keys(), vec![1, 2, 3]);
    assert!(stack.redo());
    assert_eq!(store.keys(), vec![3, 1, 2]);

    // A deleted row comes back where it was, not at the end.
    assert!(store.remove(1));
    day_reactive::flush_sync();
    assert_eq!(store.keys(), vec![3, 2]);
    assert!(stack.undo());
    assert_eq!(store.keys(), vec![3, 1, 2]);
    assert_eq!(store.elem(1).name().peek(), "one");
}

/// An app write over an open preview session (a text field's text replaced while typing) ends
/// the session without a record: the app's write records itself, and the next gesture's undo
/// returns to the app's value rather than to the text from before the typing.
#[test]
fn ending_a_preview_session_starts_the_next_from_the_current_value() {
    let store = store();
    let stack = stack_over(store);
    let field = store.elem(1).name();

    field.write_preview("ty".to_string());
    field.write_preview("typed".to_string());
    day_reactive::flush_sync();
    field.write("replacement".to_string());
    field.end_preview();
    day_reactive::flush_sync();

    field.write_preview("next".to_string());
    field.write_commit("next".to_string());
    day_reactive::flush_sync();

    assert!(stack.undo());
    assert_eq!(field.peek(), "replacement");
    assert!(stack.undo());
    assert_eq!(field.peek(), "typed");
    assert!(
        !stack.undo(),
        "the abandoned preview left no record of its own"
    );
}

#[test]
fn ending_without_a_session_does_nothing() {
    let store = store();
    let stack = stack_over(store);
    let field = store.elem(2).count();
    field.end_preview();
    field.write_commit(21);
    day_reactive::flush_sync();
    assert!(stack.undo());
    assert_eq!(field.peek(), 20);
}