oficina / docs Public

Clone
git clone https://amadan.net/oficina/docs

Plain git — no account needed to clone.

Download

Download this file

1use std::collections::HashSet;
2use std::fmt::Formatter;
3use std::ops::{Deref, DerefMut};
4use std::sync::atomic::{AtomicPtr, Ordering};
5use std::sync::Arc;
6
7use crate::block::ItemPtr;
8use crate::branch::{Branch, BranchPtr};
9use crate::iter::TxnIterator;
10use crate::slice::BlockSlice;
11use crate::sync::Clock;
12use crate::transaction::Origin;
13use crate::{DeleteSet, Doc, Observer, ReadTxn, Transact, TransactionAcqError, TransactionMut, ID};
14
15/// Undo manager is a structure used to perform undo/redo operations over the associated shared
16/// type(s).
17///
18/// Undo-/redo-able actions (a.k.a. [StackItem]s) are not equivalent to [TransactionMut]
19/// unit of work, but rather a series of updates batched within specified time intervals
20/// (see: [Options::capture_timeout_millis]) and their corresponding origins
21/// (see: [Doc::transact_mut_with] and [UndoManager::include_origin]).
22///
23/// Individual stack item boundaries can be also specified explicitly by calling [UndoManager::reset],
24/// which denotes the end of the batch.
25///
26/// In order to revert an operation, call [UndoManager::undo], then [UndoManager::redo] to bring it
27/// back.
28///
29/// Users can also subscribe to change notifications observed by undo manager:
30/// - [UndoManager::observe_item_added], which is fired every time a new [StackItem] is created.
31/// - [UndoManager::observe_item_updated], which is fired every time when an existing [StackItem]
32/// had been extended due to new document changes arriving before capture timeout for that stack
33/// item finished.
34/// - [UndoManager::observe_item_popped], which is fired whenever [StackItem] is being from undo
35/// manager as a result of calling either [UndoManager::undo] or [UndoManager::redo] method.
36pub struct UndoManager<M> {
37 state: Arc<Inner<M>>,
38 doc: Doc,
39}
40
41#[cfg(feature = "sync")]
42type UndoFn<M> = Box<dyn Fn(&TransactionMut, &mut Event<M>) + Send + Sync + 'static>;
43
44#[cfg(not(feature = "sync"))]
45type UndoFn<M> = Box<dyn Fn(&TransactionMut, &mut Event<M>) + 'static>;
46
47#[cfg(feature = "sync")]
48pub trait Meta: Default + Send + Sync {}
49#[cfg(feature = "sync")]
50impl<M> Meta for M where M: Default + Send + Sync {}
51
52#[cfg(not(feature = "sync"))]
53pub trait Meta: Default {}
54#[cfg(not(feature = "sync"))]
55impl<M> Meta for M where M: Default {}
56
57struct Inner<M> {
58 scope: HashSet<BranchPtr>,
59 options: Options,
60 undo_stack: UndoStack<M>,
61 redo_stack: UndoStack<M>,
62 undoing: bool,
63 redoing: bool,
64 last_change: u64,
65 observer_added: Observer<UndoFn<M>>,
66 observer_updated: Observer<UndoFn<M>>,
67 observer_popped: Observer<UndoFn<M>>,
68}
69
70impl<M> UndoManager<M>
71where
72 M: Meta + 'static,
73{
74 /// Creates a new instance of the [UndoManager] working in a `scope` of a particular shared
75 /// type and document. While it's possible for undo manager to observe multiple shared types
76 /// (see: [UndoManager::expand_scope]), it can only work with a single document at the same time.
77 #[cfg(not(target_family = "wasm"))]
78 pub fn new<T>(doc: &Doc, scope: &T) -> Self
79 where
80 T: AsRef<Branch>,
81 {
82 Self::with_scope_and_options(doc, scope, Options::default())
83 }
84
85 #[inline]
86 pub fn doc(&self) -> &Doc {
87 &self.doc
88 }
89
90 /// Creates a new instance of the [UndoManager] working in a context of a given document, but
91 /// without any pre-initialize scope. While it's possible for undo manager to observe multiple
92 /// shared types (see: [UndoManager::expand_scope]), it can only work with a single document
93 /// at the same time.
94 pub fn with_options(doc: &Doc, options: Options) -> Self {
95 let mut inner = Arc::new(Inner {
96 scope: HashSet::new(),
97 options,
98 undo_stack: UndoStack::default(),
99 redo_stack: UndoStack::default(),
100 undoing: false,
101 redoing: false,
102 last_change: 0,
103 observer_added: Observer::new(),
104 observer_updated: Observer::new(),
105 observer_popped: Observer::new(),
106 });
107 let origin = Origin::from(Arc::as_ptr(&inner) as usize);
108 let inner_mut = Arc::get_mut(&mut inner).unwrap();
109 inner_mut.options.tracked_origins.insert(origin.clone());
110 let ptr = AtomicPtr::new(inner_mut as *mut Inner<M>);
111
112 doc.observe_destroy_with(origin.clone(), move |txn, _| {
113 let ptr = ptr.load(Ordering::Acquire);
114 let inner = unsafe { ptr.as_mut().unwrap() };
115 Self::handle_destroy(txn, inner)
116 })
117 .unwrap();
118 let ptr = AtomicPtr::new(inner_mut as *mut Inner<M>);
119
120 doc.observe_after_transaction_with(origin, move |txn| {
121 let ptr = ptr.load(Ordering::Acquire);
122 let inner = unsafe { ptr.as_mut().unwrap() };
123 Self::handle_after_transaction(inner, txn);
124 })
125 .unwrap();
126
127 UndoManager {
128 state: inner,
129 doc: doc.clone(),
130 }
131 }
132
133 /// Creates a new instance of the [UndoManager] working in a `scope` of a particular shared
134 /// type and document. While it's possible for undo manager to observe multiple shared types
135 /// (see: [UndoManager::expand_scope]), it can only work with a single document at the same time.
136 pub fn with_scope_and_options<T>(doc: &Doc, scope: &T, options: Options) -> Self
137 where
138 T: AsRef<Branch>,
139 {
140 let mut mgr = Self::with_options(doc, options);
141 mgr.expand_scope(scope);
142 mgr
143 }
144
145 fn should_skip(inner: &Inner<M>, txn: &TransactionMut) -> bool {
146 if let Some(capture_transaction) = &inner.options.capture_transaction {
147 if !capture_transaction(txn) {
148 return true;
149 }
150 }
151 !inner
152 .scope
153 .iter()
154 .any(|parent| txn.changed_parent_types.contains(parent))
155 || !txn
156 .origin()
157 .map(|o| inner.options.tracked_origins.contains(o))
158 .unwrap_or(inner.options.tracked_origins.len() == 1) // tracked origins contain only undo manager itself
159 }
160
161 fn handle_after_transaction(inner: &mut Inner<M>, txn: &mut TransactionMut) {
162 if Self::should_skip(inner, txn) {
163 return;
164 }
165 let undoing = inner.undoing;
166 let redoing = inner.redoing;
167 if undoing {
168 inner.last_change = 0; // next undo should not be appended to last stack item
169 } else if !redoing {
170 // neither undoing nor redoing: delete redoStack
171 let len = inner.redo_stack.len();
172 for item in inner.redo_stack.drain(0..len) {
173 Self::clear_item(&inner.scope, txn, item);
174 }
175 }
176
177 let mut insertions = DeleteSet::new();
178 for (client, &end_clock) in txn.after_state().iter() {
179 let start_clock = txn.before_state.get(client);
180 let diff = end_clock - start_clock;
181 if diff != 0 {
182 insertions.insert(ID::new(*client, start_clock), diff);
183 }
184 }
185 let now = inner.options.timestamp.now();
186 let stack = if undoing {
187 &mut inner.redo_stack
188 } else {
189 &mut inner.undo_stack
190 };
191 let extend = !undoing
192 && !redoing
193 && !stack.is_empty()
194 && inner.last_change > 0
195 && now - inner.last_change < inner.options.capture_timeout_millis;
196
197 if extend {
198 // append change to last stack op
199 if let Some(last_op) = stack.last_mut() {
200 // always true - we checked if stack is empty above
201 last_op.deletions.merge(txn.delete_set.clone());
202 last_op.insertions.merge(insertions);
203 }
204 } else {
205 // create a new stack op
206 let item = StackItem::new(txn.delete_set.clone(), insertions);
207 stack.push(item);
208 }
209
210 if !undoing && !redoing {
211 inner.last_change = now;
212 }
213 // make sure that deleted structs are not gc'd
214 let ds = txn.delete_set.clone();
215 let mut deleted = ds.deleted_blocks();
216 while let Some(slice) = deleted.next(txn) {
217 if let Some(item) = slice.as_item() {
218 if inner.scope.iter().any(|b| b.is_parent_of(Some(item))) {
219 item.keep(true);
220 }
221 }
222 }
223
224 let last_op = stack.last_mut().unwrap();
225 let meta = std::mem::take(&mut last_op.meta);
226 let mut event = if undoing {
227 Event::undo(meta, txn.origin.clone(), txn.changed_parent_types.clone())
228 } else {
229 Event::redo(meta, txn.origin.clone(), txn.changed_parent_types.clone())
230 };
231 if !extend {
232 if inner.observer_added.has_subscribers() {
233 inner.observer_added.trigger(|fun| fun(txn, &mut event));
234 }
235 } else {
236 if inner.observer_updated.has_subscribers() {
237 inner.observer_updated.trigger(|fun| fun(txn, &mut event));
238 }
239 }
240 last_op.meta = event.meta;
241 }
242
243 fn handle_destroy(txn: &TransactionMut, inner: &mut Inner<M>) {
244 let origin = Origin::from(inner as *mut Inner<M> as usize);
245 if inner.options.tracked_origins.remove(&origin) {
246 if let Some(events) = txn.events() {
247 events.destroy_events.unsubscribe(&origin);
248 events.after_transaction_events.unsubscribe(&origin);
249 }
250 }
251 }
252
253 /// Registers a callback function to be called every time a new [StackItem] is created. This
254 /// usually happens when a new update over an tracked shared type happened after capture timeout
255 /// threshold from the previous stack item occurence has been reached or [UndoManager::reset]
256 /// has been called.
257 ///
258 /// Returns a subscription object which - when dropped - will unregister provided callback.
259 #[cfg(feature = "sync")]
260 pub fn observe_item_added<F>(&self, f: F) -> crate::Subscription
261 where
262 F: Fn(&TransactionMut, &mut Event<M>) + Send + Sync + 'static,
263 {
264 self.state.observer_added.subscribe(Box::new(f))
265 }
266
267 /// Registers a callback function to be called every time a new [StackItem] is created. This
268 /// usually happens when a new update over an tracked shared type happened after capture timeout
269 /// threshold from the previous stack item occurence has been reached or [UndoManager::reset]
270 /// has been called.
271 ///
272 /// Returns a subscription object which - when dropped - will unregister provided callback.
273 #[cfg(not(feature = "sync"))]
274 pub fn observe_item_added<F>(&self, f: F) -> crate::Subscription
275 where
276 F: Fn(&TransactionMut, &mut Event<M>) + 'static,
277 {
278 self.state.observer_added.subscribe(Box::new(f))
279 }
280
281 /// Registers a callback function to be called every time a new [StackItem] is created. This
282 /// usually happens when a new update over an tracked shared type happened after capture timeout
283 /// threshold from the previous stack item occurence has been reached or [UndoManager::reset]
284 /// has been called.
285 ///
286 /// Provided `key` is used to identify the origin of the callback. It can be used to unregister
287 /// the callback later on.
288 #[cfg(feature = "sync")]
289 pub fn observe_item_added_with<K, F>(&self, key: K, f: F)
290 where
291 K: Into<Origin>,
292 F: Fn(&TransactionMut, &mut Event<M>) + Send + Sync + 'static,
293 {
294 self.state
295 .observer_added
296 .subscribe_with(key.into(), Box::new(f))
297 }
298
299 /// Registers a callback function to be called every time a new [StackItem] is created. This
300 /// usually happens when a new update over an tracked shared type happened after capture timeout
301 /// threshold from the previous stack item occurence has been reached or [UndoManager::reset]
302 /// has been called.
303 ///
304 /// Provided `key` is used to identify the origin of the callback. It can be used to unregister
305 /// the callback later on.
306 #[cfg(not(feature = "sync"))]
307 pub fn observe_item_added_with<K, F>(&self, key: K, f: F)
308 where
309 K: Into<Origin>,
310 F: Fn(&TransactionMut, &mut Event<M>) + 'static,
311 {
312 self.state
313 .observer_added
314 .subscribe_with(key.into(), Box::new(f))
315 }
316
317 pub fn unobserve_item_added<K>(&self, key: K) -> bool
318 where
319 K: Into<Origin>,
320 {
321 self.state.observer_added.unsubscribe(&key.into())
322 }
323
324 /// Registers a callback function to be called every time an existing [StackItem] has been
325 /// extended as a result of updates from tracked types which happened before a capture timeout
326 /// has passed.
327 ///
328 /// Returns a subscription object which - when dropped - will unregister provided callback.
329 #[cfg(feature = "sync")]
330 pub fn observe_item_updated<F>(&self, f: F) -> crate::Subscription
331 where
332 F: Fn(&TransactionMut, &mut Event<M>) + Send + Sync + 'static,
333 {
334 self.state.observer_updated.subscribe(Box::new(f))
335 }
336
337 /// Registers a callback function to be called every time an existing [StackItem] has been
338 /// extended as a result of updates from tracked types which happened before a capture timeout
339 /// has passed.
340 ///
341 /// Returns a subscription object which - when dropped - will unregister provided callback.
342 #[cfg(not(feature = "sync"))]
343 pub fn observe_item_updated<F>(&self, f: F) -> crate::Subscription
344 where
345 F: Fn(&TransactionMut, &mut Event<M>) + 'static,
346 {
347 self.state.observer_updated.subscribe(Box::new(f))
348 }
349
350 /// Registers a callback function to be called every time an existing [StackItem] has been
351 /// extended as a result of updates from tracked types which happened before a capture timeout
352 /// has passed.
353 ///
354 /// Provided `key` is used to identify the origin of the callback. It can be used to unregister
355 /// the callback later on.
356 #[cfg(feature = "sync")]
357 pub fn observe_item_updated_with<K, F>(&self, key: K, f: F)
358 where
359 K: Into<Origin>,
360 F: Fn(&TransactionMut, &mut Event<M>) + Send + Sync + 'static,
361 {
362 self.state
363 .observer_updated
364 .subscribe_with(key.into(), Box::new(f))
365 }
366
367 /// Registers a callback function to be called every time an existing [StackItem] has been
368 /// extended as a result of updates from tracked types which happened before a capture timeout
369 /// has passed.
370 ///
371 /// Provided `key` is used to identify the origin of the callback. It can be used to unregister
372 /// the callback later on.
373 #[cfg(not(feature = "sync"))]
374 pub fn observe_item_updated_with<K, F>(&self, key: K, f: F)
375 where
376 K: Into<Origin>,
377 F: Fn(&TransactionMut, &mut Event<M>) + 'static,
378 {
379 self.state
380 .observer_updated
381 .subscribe_with(key.into(), Box::new(f))
382 }
383
384 pub fn unobserve_item_updated<K>(&self, key: K) -> bool
385 where
386 K: Into<Origin>,
387 {
388 self.state.observer_updated.unsubscribe(&key.into())
389 }
390
391 /// Registers a callback function to be called every time an existing [StackItem] has been
392 /// removed as a result of [UndoManager::undo] or [UndoManager::redo] method.
393 ///
394 /// Returns a subscription object which - when dropped - will unregister provided callback.
395 #[cfg(feature = "sync")]
396 pub fn observe_item_popped<F>(&self, f: F) -> crate::Subscription
397 where
398 F: Fn(&TransactionMut, &mut Event<M>) + Send + Sync + 'static,
399 {
400 self.state.observer_popped.subscribe(Box::new(f))
401 }
402
403 /// Registers a callback function to be called every time an existing [StackItem] has been
404 /// removed as a result of [UndoManager::undo] or [UndoManager::redo] method.
405 ///
406 /// Returns a subscription object which - when dropped - will unregister provided callback.
407 #[cfg(not(feature = "sync"))]
408 pub fn observe_item_popped<F>(&self, f: F) -> crate::Subscription
409 where
410 F: Fn(&TransactionMut, &mut Event<M>) + 'static,
411 {
412 self.state.observer_popped.subscribe(Box::new(f))
413 }
414
415 /// Registers a callback function to be called every time an existing [StackItem] has been
416 /// removed as a result of [UndoManager::undo] or [UndoManager::redo] method.
417 ///
418 /// Provided `key` is used to identify the origin of the callback. It can be used to unregister
419 /// the callback later on.
420 #[cfg(feature = "sync")]
421 pub fn observe_item_popped_with<K, F>(&self, key: K, f: F)
422 where
423 K: Into<Origin>,
424 F: Fn(&TransactionMut, &mut Event<M>) + Send + Sync + 'static,
425 {
426 self.state
427 .observer_popped
428 .subscribe_with(key.into(), Box::new(f))
429 }
430
431 /// Registers a callback function to be called every time an existing [StackItem] has been
432 /// removed as a result of [UndoManager::undo] or [UndoManager::redo] method.
433 ///
434 /// Provided `key` is used to identify the origin of the callback. It can be used to unregister
435 /// the callback later on.
436 #[cfg(not(feature = "sync"))]
437 pub fn observe_item_popped_with<K, F>(&self, key: K, f: F)
438 where
439 K: Into<Origin>,
440 F: Fn(&TransactionMut, &mut Event<M>) + 'static,
441 {
442 self.state
443 .observer_popped
444 .subscribe_with(key.into(), Box::new(f))
445 }
446
447 pub fn unobserve_item_popped<K>(&self, key: K) -> bool
448 where
449 K: Into<Origin>,
450 {
451 self.state.observer_popped.unsubscribe(&key.into())
452 }
453
454 /// Extends a list of shared types tracked by current undo manager by a given `scope`.
455 pub fn expand_scope<T>(&mut self, scope: &T)
456 where
457 T: AsRef<Branch>,
458 {
459 let ptr = BranchPtr::from(scope.as_ref());
460 let inner = Arc::get_mut(&mut self.state).unwrap();
461 inner.scope.insert(ptr);
462 }
463
464 /// Extends a list of origins tracked by current undo manager by given `origin`. Origin markers
465 /// can be assigned to updates executing in a scope of a particular transaction
466 /// (see: [Doc::transact_mut_with]).
467 pub fn include_origin<O>(&mut self, origin: O)
468 where
469 O: Into<Origin>,
470 {
471 let inner = Arc::get_mut(&mut self.state).unwrap();
472 inner.options.tracked_origins.insert(origin.into());
473 }
474
475 /// Removes an `origin` from the list of origins tracked by a current undo manager.
476 pub fn exclude_origin<O>(&mut self, origin: O)
477 where
478 O: Into<Origin>,
479 {
480 let inner = Arc::get_mut(&mut self.state).unwrap();
481 inner.options.tracked_origins.remove(&origin.into());
482 }
483
484 /// Clears all [StackItem]s stored within current UndoManager, effectively resetting its state.
485 ///
486 /// # Deadlocks
487 ///
488 /// In order to perform its function, this method must guarantee that underlying document store
489 /// is not being modified by another running `TransactionMut`. It does so by acquiring
490 /// a read-only transaction itself. If transaction couldn't be acquired (because another
491 /// read-write transaction is in progress), it will hold current thread until, acquisition is
492 /// available.
493 pub fn clear(&mut self) {
494 let txn = self.doc.transact();
495 let inner = Arc::get_mut(&mut self.state).unwrap();
496
497 let len = inner.undo_stack.len();
498 for item in inner.undo_stack.drain(0..len) {
499 Self::clear_item(&inner.scope, &txn, item);
500 }
501
502 let len = inner.redo_stack.len();
503 for item in inner.redo_stack.drain(0..len) {
504 Self::clear_item(&inner.scope, &txn, item);
505 }
506 }
507
508 fn clear_item<T: ReadTxn>(scope: &HashSet<BranchPtr>, txn: &T, stack_item: StackItem<M>) {
509 let mut deleted = stack_item.deletions.deleted_blocks();
510 while let Some(slice) = deleted.next(txn) {
511 if let Some(item) = slice.as_item() {
512 if scope.iter().any(|b| b.is_parent_of(Some(item))) {
513 item.keep(false);
514 }
515 }
516 }
517 }
518
519 pub fn as_origin(&self) -> Origin {
520 let mgr_ptr: *const Inner<M> = &*self.state;
521 Origin::from(mgr_ptr as usize)
522 }
523
524 /// [UndoManager] merges undo stack items if they were created withing the time gap smaller than
525 /// [Options::capture_timeout_millis]. You can call this method so that the next stack item won't be
526 /// merged.
527 ///
528 /// Example:
529 /// ```rust
530 /// use yrs::{Doc, GetString, Text, Transact, UndoManager};
531 /// let doc = Doc::new();
532 ///
533 /// // without UndoManager::stop
534 /// let txt = doc.get_or_insert_text("no-stop");
535 /// let mut mgr = UndoManager::new(&doc, &txt);
536 /// txt.insert(&mut doc.transact_mut(), 0, "a");
537 /// txt.insert(&mut doc.transact_mut(), 1, "b");
538 /// mgr.undo_blocking();
539 /// txt.get_string(&doc.transact()); // => "" (note that 'ab' was removed)
540 ///
541 /// // with UndoManager::stop
542 /// let txt = doc.get_or_insert_text("with-stop");
543 /// let mut mgr = UndoManager::new(&doc, &txt);
544 /// txt.insert(&mut doc.transact_mut(), 0, "a");
545 /// mgr.reset();
546 /// txt.insert(&mut doc.transact_mut(), 1, "b");
547 /// mgr.undo_blocking();
548 /// txt.get_string(&doc.transact()); // => "a" (note that only 'b' was removed)
549 /// ```
550 pub fn reset(&mut self) {
551 let inner = Arc::get_mut(&mut self.state).unwrap();
552 inner.last_change = 0;
553 }
554
555 /// Are there any undo steps available?
556 pub fn can_undo(&self) -> bool {
557 !self.state.undo_stack.is_empty()
558 }
559
560 /// Returns a list of [StackItem]s stored within current undo manager responsible for performing
561 /// potential undo operations.
562 pub fn undo_stack(&self) -> &[StackItem<M>] {
563 &self.state.undo_stack.0
564 }
565
566 /// Returns a list of [StackItem]s stored within current undo manager responsible for performing
567 /// potential redo operations.
568 pub fn redo_stack(&self) -> &[StackItem<M>] {
569 &self.state.redo_stack.0
570 }
571
572 /// Undo last action tracked by current undo manager. Actions (a.k.a. [StackItem]s) are groups
573 /// of updates performed in a given time range - they also can be separated explicitly by
574 /// calling [UndoManager::reset].
575 ///
576 /// Successful execution returns a boolean value telling if an undo call has performed any changes.
577 ///
578 /// # Deadlocks
579 ///
580 /// This method requires exclusive access to underlying document store. This means that
581 /// no other transaction on that same document can be active while calling this method.
582 /// Otherwise, it may cause a deadlock.
583 ///
584 /// See also: [UndoManager::try_undo] and [UndoManager::undo_blocking].
585 pub async fn undo(&mut self) -> bool {
586 let origin = self.as_origin();
587 let inner = Arc::get_mut(&mut self.state).unwrap();
588 let txn = crate::AsyncTransact::transact_mut_with(&self.doc, origin.clone()).await;
589 Self::undo_inner(inner, txn, origin)
590 }
591
592 /// Undo last action tracked by current undo manager. Actions (a.k.a. [StackItem]s) are groups
593 /// of updates performed in a given time range - they also can be separated explicitly by
594 /// calling [UndoManager::reset].
595 ///
596 /// Successful execution returns a boolean value telling if an undo call has performed any changes.
597 ///
598 /// # Deadlocks
599 ///
600 /// This method requires exclusive access to underlying document store. This means that
601 /// no other transaction on that same document can be active while calling this method.
602 /// Otherwise, it may cause a deadlock.
603 ///
604 /// See also: [UndoManager::try_undo] and [UndoManager::undo].
605 pub fn undo_blocking(&mut self) -> bool {
606 let origin = self.as_origin();
607 let inner = Arc::get_mut(&mut self.state).unwrap();
608 let txn = self.doc.transact_mut_with(origin.clone());
609 Self::undo_inner(inner, txn, origin)
610 }
611
612 /// Undo last action tracked by current undo manager. Actions (a.k.a. [StackItem]s) are groups
613 /// of updates performed in a given time range - they also can be separated explicitly by
614 /// calling [UndoManager::reset].
615 ///
616 /// Successful execution returns a boolean value telling if an undo call has performed any changes.
617 ///
618 /// See also: [UndoManager::undo] and [UndoManager::undo_blocking].
619 ///
620 /// # Errors
621 ///
622 /// This method requires exclusive access to underlying document store. This means that
623 /// no other transaction on that same document can be active while calling this method.
624 /// Otherwise, an error will be returned.
625 pub fn try_undo(&mut self) -> Result<bool, TransactionAcqError> {
626 let origin = self.as_origin();
627 let inner = Arc::get_mut(&mut self.state).unwrap();
628 let txn = self.doc.try_transact_mut_with(origin.clone())?;
629 let changed = Self::undo_inner(inner, txn, origin);
630 Ok(changed)
631 }
632
633 fn undo_inner(inner: &mut Inner<M>, mut txn: TransactionMut, origin: Origin) -> bool {
634 inner.undoing = true;
635 let result = Self::pop(
636 &mut inner.undo_stack,
637 &inner.redo_stack,
638 &mut txn,
639 &inner.scope,
640 );
641 txn.commit();
642 let changed = if let Some(item) = result {
643 let mut e = Event::undo(item.meta, Some(origin), txn.changed_parent_types.clone());
644 if inner.observer_popped.has_subscribers() {
645 inner.observer_popped.trigger(|fun| fun(&txn, &mut e));
646 }
647 true
648 } else {
649 false
650 };
651 inner.undoing = false;
652 changed
653 }
654
655 /// Are there any redo steps available?
656 pub fn can_redo(&self) -> bool {
657 !self.state.redo_stack.is_empty()
658 }
659
660 /// Redo'es last action previously undo'ed by current undo manager. Actions
661 /// (a.k.a. [StackItem]s) are groups of updates performed in a given time range - they also can
662 /// be separated explicitly by calling [UndoManager::reset].
663 ///
664 /// Successful execution returns a boolean value telling if an undo call has performed any changes.
665 ///
666 /// # Deadlocks
667 ///
668 /// This method requires exclusive access to underlying document store. This means that
669 /// no other transaction on that same document can be active while calling this method.
670 /// Otherwise, it may cause a deadlock.
671 ///
672 /// See also: [UndoManager::try_redo] and [UndoManager::redo_blocking].
673 pub async fn redo(&mut self) -> bool {
674 let origin = self.as_origin();
675 let inner = Arc::get_mut(&mut self.state).unwrap();
676 let txn = crate::AsyncTransact::transact_mut_with(&self.doc, origin.clone()).await;
677 let changed = Self::redo_inner(inner, txn, origin);
678 changed
679 }
680
681 /// Redo'es last action previously undo'ed by current undo manager. Actions
682 /// (a.k.a. [StackItem]s) are groups of updates performed in a given time range - they also can
683 /// be separated explicitly by calling [UndoManager::reset].
684 ///
685 /// Successful execution returns a boolean value telling if an undo call has performed any changes.
686 ///
687 /// # Deadlocks
688 ///
689 /// This method requires exclusive access to underlying document store. This means that
690 /// no other transaction on that same document can be active while calling this method.
691 /// Otherwise, it may cause a deadlock.
692 ///
693 /// See also: [UndoManager::try_redo] and [UndoManager::redo_blocking].
694 pub fn redo_blocking(&mut self) -> bool {
695 let origin = self.as_origin();
696 let inner = Arc::get_mut(&mut self.state).unwrap();
697 let txn = self.doc.transact_mut_with(origin.clone());
698 let changed = Self::redo_inner(inner, txn, origin);
699 changed
700 }
701
702 /// Redo'es last action previously undo'ed by current undo manager. Actions
703 /// (a.k.a. [StackItem]s) are groups of updates performed in a given time range - they also can
704 /// be separated explicitly by calling [UndoManager::reset].
705 ///
706 /// Successful execution returns a boolean value telling if an undo call has performed any changes.
707 ///
708 /// # Errors
709 ///
710 /// This method requires exclusive access to underlying document store. This means that
711 /// no other transaction on that same document can be active while calling this method.
712 /// Otherwise, an error will be returned.
713 pub fn try_redo(&mut self) -> Result<bool, TransactionAcqError> {
714 let origin = self.as_origin();
715 let inner = Arc::get_mut(&mut self.state).unwrap();
716 let txn = self.doc.try_transact_mut_with(origin.clone())?;
717 let changed = Self::redo_inner(inner, txn, origin);
718 Ok(changed)
719 }
720
721 fn redo_inner(inner: &mut Inner<M>, mut txn: TransactionMut, origin: Origin) -> bool {
722 inner.redoing = true;
723 let result = Self::pop(
724 &mut inner.redo_stack,
725 &inner.undo_stack,
726 &mut txn,
727 &inner.scope,
728 );
729 txn.commit();
730 let changed = if let Some(item) = result {
731 let mut e = Event::redo(item.meta, Some(origin), txn.changed_parent_types.clone());
732 if inner.observer_popped.has_subscribers() {
733 inner.observer_popped.trigger(|fun| fun(&txn, &mut e));
734 }
735 true
736 } else {
737 false
738 };
739 inner.redoing = false;
740 changed
741 }
742
743 fn pop(
744 stack: &mut UndoStack<M>,
745 other: &UndoStack<M>,
746 txn: &mut TransactionMut,
747 scope: &HashSet<BranchPtr>,
748 ) -> Option<StackItem<M>> {
749 let mut result = None;
750 while let Some(item) = stack.pop() {
751 let mut to_redo = HashSet::<ItemPtr>::new();
752 // Local patch (see PATCHES.md, "Redo order"): redo in the order the
753 // deletions are found, as Yjs iterates its Set in insertion order. The
754 // HashSet alone made the order depend on the process's hash keys.
755 let mut redo_order = Vec::<ItemPtr>::new();
756 let mut to_delete = Vec::<ItemPtr>::new();
757 let mut change_performed = false;
758
759 let deleted: Vec<_> = item.insertions.deleted_blocks().collect(txn);
760 for slice in deleted {
761 if let BlockSlice::Item(slice) = slice {
762 let mut item = txn.store.materialize(slice);
763 if item.redone.is_some() {
764 let slice = txn.store_mut().follow_redone(item.id())?;
765 item = txn.store.materialize(slice);
766 }
767
768 if !item.is_deleted() && scope.iter().any(|b| b.is_parent_of(Some(item))) {
769 to_delete.push(item);
770 }
771 }
772 }
773
774 let mut deleted = item.deletions.deleted_blocks();
775 while let Some(slice) = deleted.next(txn) {
776 if let BlockSlice::Item(slice) = slice {
777 let ptr = txn.store.materialize(slice);
778 if scope.iter().any(|b| b.is_parent_of(Some(ptr)))
779 && !item.insertions.is_deleted(ptr.id())
780 // Never redo structs in stackItem.insertions because they were created and deleted in the same capture interval.
781 {
782 if to_redo.insert(ptr) {
783 redo_order.push(ptr);
784 }
785 }
786 }
787 }
788
789 for &ptr in redo_order.iter() {
790 let mut ptr = ptr;
791 change_performed |= ptr
792 .redo(txn, &to_redo, &item.insertions, stack, other)
793 .is_some();
794 }
795
796 // We want to delete in reverse order so that children are deleted before
797 // parents, so we have more information available when items are filtered.
798 for &item in to_delete.iter().rev() {
799 // if self.options.delete_filter(item) {
800 txn.delete(item);
801 change_performed = true;
802 }
803
804 if change_performed {
805 result = Some(item);
806 break;
807 }
808 }
809 result
810 }
811}
812
813impl<M: std::fmt::Debug> std::fmt::Debug for UndoManager<M> {
814 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
815 let mut s = f.debug_struct("UndoManager");
816 let state = &self.state;
817 s.field("scope", &state.scope);
818 s.field("tracked_origins", &state.options.tracked_origins);
819 if !state.undo_stack.is_empty() {
820 s.field("undo", &state.undo_stack);
821 }
822 if !state.redo_stack.is_empty() {
823 s.field("redo", &state.redo_stack);
824 }
825 s.finish()
826 }
827}
828
829impl<M> Drop for UndoManager<M> {
830 fn drop(&mut self) {
831 let origin = Origin::from(Arc::as_ptr(&self.state) as usize);
832 self.doc.unobserve_destroy(origin.clone()).unwrap();
833 self.doc.unobserve_after_transaction(origin).unwrap();
834 }
835}
836
837#[repr(transparent)]
838#[derive(Debug, Clone, Eq, PartialEq, Default)]
839pub(crate) struct UndoStack<M>(Vec<StackItem<M>>);
840
841impl<M> Deref for UndoStack<M> {
842 type Target = Vec<StackItem<M>>;
843
844 fn deref(&self) -> &Self::Target {
845 &self.0
846 }
847}
848
849impl<M> DerefMut for UndoStack<M> {
850 fn deref_mut(&mut self) -> &mut Self::Target {
851 &mut self.0
852 }
853}
854
855impl<M> UndoStack<M> {
856 pub fn is_deleted(&self, id: &ID) -> bool {
857 for item in self.0.iter() {
858 if item.deletions.is_deleted(id) {
859 return true;
860 }
861 }
862 false
863 }
864}
865
866/// Set of options used to configure [UndoManager].
867pub struct Options {
868 /// Undo-/redo-able updates are grouped together in time-constrained snapshots. This field
869 /// determines the period of time, every snapshot will be automatically made in.
870 pub capture_timeout_millis: u64,
871
872 /// List of origins tracked by corresponding [UndoManager].
873 /// If provided, it will track only updates made within transactions of specific origin.
874 /// If not provided, it will track only updates made within transaction with no origin defined.
875 pub tracked_origins: HashSet<Origin>,
876
877 /// Custom logic decider, that along with [tracked_origins] can be used to determine if
878 /// transaction changes should be captured or not.
879 pub capture_transaction: Option<CaptureTransactionFn>,
880
881 /// Custom clock function, that can be used to generate timestamps used by
882 /// [Options::capture_timeout_millis].
883 pub timestamp: Arc<dyn Clock>,
884}
885
886pub type CaptureTransactionFn = Arc<dyn Fn(&TransactionMut) -> bool + Send + Sync + 'static>;
887
888#[cfg(not(target_family = "wasm"))]
889impl Default for Options {
890 fn default() -> Self {
891 Options {
892 capture_timeout_millis: 500,
893 tracked_origins: HashSet::new(),
894 capture_transaction: None,
895 timestamp: Arc::new(crate::sync::time::SystemClock),
896 }
897 }
898}
899
900/// A unit of work for the [UndoManager]. It contains a compressed information about all updates and
901/// deletions tracked by a corresponding undo manager. Whenever an [UndoManger::undo] or
902/// [UndoManager::redo] methods are called a last [StackItem] is being used to modify a state of
903/// the document.
904///
905/// Stack items are stored internally by undo manager and created automatically whenever a new
906/// update from tracked shared type and transaction of tracked origin has been committed within
907/// a threshold specified by [Options::capture_timeout_millis] time window since the previous stack
908/// item creation. They can also be created explicitly by calling [UndoManager::reset], which marks
909/// the end of the last stack item batch.
910#[derive(Debug, Clone, Eq, PartialEq, Hash)]
911pub struct StackItem<T> {
912 deletions: DeleteSet,
913 insertions: DeleteSet,
914
915 /// A custom user metadata that can be attached to a particular [StackItem]. It can be used
916 /// to carry over the additional information (such as ie. user cursor position) between
917 /// undo/redo operations.
918 pub meta: T,
919}
920
921impl<M: Default> StackItem<M> {
922 fn new(deletions: DeleteSet, insertions: DeleteSet) -> Self {
923 StackItem {
924 deletions,
925 insertions,
926 meta: M::default(),
927 }
928 }
929
930 /// A set of identifiers of element deleted at part of the timeframe current [StackItem] is
931 /// responsible for.
932 pub fn deletions(&self) -> &DeleteSet {
933 &self.deletions
934 }
935
936 /// A set of identifiers of element inserted at part of the timeframe current [StackItem] is
937 /// responsible for.
938 pub fn insertions(&self) -> &DeleteSet {
939 &self.insertions
940 }
941}
942
943impl<M> std::fmt::Display for StackItem<M> {
944 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
945 write!(f, "StackItem(")?;
946 if !self.deletions.is_empty() {
947 write!(f, "-{}", self.deletions)?;
948 }
949 if !self.insertions.is_empty() {
950 write!(f, "+{}", self.insertions)?;
951 }
952 write!(f, ")")
953 }
954}
955
956#[derive(Debug)]
957pub struct Event<M> {
958 meta: M,
959 origin: Option<Origin>,
960 kind: EventKind,
961 changed_parent_types: Vec<BranchPtr>,
962}
963
964impl<M> Event<M> {
965 fn undo(meta: M, origin: Option<Origin>, changed_parent_types: Vec<BranchPtr>) -> Self {
966 Event {
967 meta,
968 origin,
969 changed_parent_types,
970 kind: EventKind::Undo,
971 }
972 }
973
974 fn redo(meta: M, origin: Option<Origin>, changed_parent_types: Vec<BranchPtr>) -> Self {
975 Event {
976 meta,
977 origin,
978 changed_parent_types,
979 kind: EventKind::Redo,
980 }
981 }
982
983 pub fn meta(&self) -> &M {
984 &self.meta
985 }
986
987 pub fn meta_mut(&mut self) -> &mut M {
988 &mut self.meta
989 }
990
991 /// Checks if given shared collection has changed in the scope of currently notified update.
992 pub fn has_changed<T: AsRef<Branch>>(&self, target: &T) -> bool {
993 let ptr = BranchPtr::from(target.as_ref());
994 self.changed_parent_types.contains(&ptr)
995 }
996
997 /// Returns a transaction origin related to this update notification.
998 pub fn origin(&self) -> Option<&Origin> {
999 self.origin.as_ref()
1000 }
1001
1002 /// Returns an enum informing if current update is result of undo or redo operation.
1003 pub fn kind(&self) -> EventKind {
1004 self.kind
1005 }
1006
1007 /// Returns info about all changed shared collections.
1008 pub fn changed_parent_types(&self) -> &[BranchPtr] {
1009 &self.changed_parent_types
1010 }
1011}
1012
1013/// Enum which informs if correlated [Event] was produced as a result of either undo or redo
1014/// operation over [UndoManager].
1015#[repr(u8)]
1016#[derive(Debug, Clone, Copy, Ord, PartialOrd, Eq, PartialEq)]
1017pub enum EventKind {
1018 /// Referenced event was result of [UndoManager::undo] operation.
1019 Undo,
1020 /// Referenced event was result of [UndoManager::redo] operation.
1021 Redo,
1022}
1023
1024#[cfg(test)]
1025mod test {
1026 use std::collections::HashMap;
1027 use std::convert::TryInto;
1028 use std::sync::atomic::{AtomicUsize, Ordering};
1029 use std::sync::Arc;
1030
1031 use crate::test_utils::exchange_updates;
1032 use crate::types::text::{Diff, YChange};
1033 use crate::types::{Attrs, ToJson};
1034 use crate::undo::Options;
1035 use crate::updates::decoder::Decode;
1036 use crate::{
1037 any, Any, Array, ArrayPrelim, Doc, GetString, Map, MapPrelim, MapRef, ReadTxn, StateVector,
1038 Text, TextPrelim, TextRef, Transact, UndoManager, Update, Xml, XmlElementPrelim,
1039 XmlElementRef, XmlFragment, XmlTextPrelim,
1040 };
1041
1042 #[test]
1043 fn undo_text() {
1044 let d1 = Doc::with_client_id(1);
1045 let txt1 = d1.get_or_insert_text("test");
1046 let mut mgr = UndoManager::new(&d1, &txt1);
1047
1048 let d2 = Doc::with_client_id(2);
1049 let txt2 = d2.get_or_insert_text("test");
1050
1051 // items that are added & deleted in the same transaction won't be undo
1052 txt1.insert(&mut d1.transact_mut(), 0, "test");
1053 txt1.remove_range(&mut d1.transact_mut(), 0, 4);
1054 mgr.undo_blocking();
1055 assert_eq!(txt1.get_string(&d1.transact()), "");
1056
1057 // follow redone items
1058 txt1.insert(&mut d1.transact_mut(), 0, "a");
1059 mgr.reset();
1060 txt1.remove_range(&mut d1.transact_mut(), 0, 1);
1061 mgr.reset();
1062 mgr.undo_blocking();
1063 assert_eq!(txt1.get_string(&d1.transact()), "a");
1064 mgr.undo_blocking();
1065 assert_eq!(txt1.get_string(&d1.transact()), "");
1066
1067 txt1.insert(&mut d1.transact_mut(), 0, "abc");
1068 txt2.insert(&mut d2.transact_mut(), 0, "xyz");
1069
1070 exchange_updates(&[&d1, &d2]);
1071 mgr.undo_blocking();
1072 assert_eq!(txt1.get_string(&d1.transact()), "xyz");
1073 mgr.redo_blocking();
1074 assert_eq!(txt1.get_string(&d1.transact()), "abcxyz");
1075
1076 exchange_updates(&[&d1, &d2]);
1077
1078 txt2.remove_range(&mut d2.transact_mut(), 0, 1);
1079
1080 exchange_updates(&[&d1, &d2]);
1081
1082 mgr.undo_blocking();
1083 assert_eq!(txt1.get_string(&d1.transact()), "xyz");
1084 mgr.redo_blocking();
1085 assert_eq!(txt1.get_string(&d1.transact()), "bcxyz");
1086
1087 // test marks
1088 let attrs = Attrs::from([("bold".into(), true.into())]);
1089 txt1.format(&mut d1.transact_mut(), 1, 3, attrs.clone());
1090 let diff = txt1.diff(&d1.transact(), YChange::identity);
1091 assert_eq!(
1092 diff,
1093 vec![
1094 Diff::new("b".into(), None),
1095 Diff::new("cxy".into(), Some(Box::new(attrs.clone()))),
1096 Diff::new("z".into(), None),
1097 ]
1098 );
1099
1100 mgr.undo_blocking();
1101 let diff = txt1.diff(&d1.transact(), YChange::identity);
1102 assert_eq!(diff, vec![Diff::new("bcxyz".into(), None)]);
1103
1104 mgr.redo_blocking();
1105 let diff = txt1.diff(&d1.transact(), YChange::identity);
1106 assert_eq!(
1107 diff,
1108 vec![
1109 Diff::new("b".into(), None),
1110 Diff::new("cxy".into(), Some(Box::new(attrs.clone()))),
1111 Diff::new("z".into(), None),
1112 ]
1113 );
1114 }
1115
1116 #[test]
1117 fn double_undo() {
1118 let doc = Doc::with_client_id(1);
1119 let txt = doc.get_or_insert_text("test");
1120 txt.insert(&mut doc.transact_mut(), 0, "1221");
1121
1122 let mut mgr = UndoManager::new(&doc, &txt);
1123 txt.insert(&mut doc.transact_mut(), 2, "3");
1124 txt.insert(&mut doc.transact_mut(), 3, "3");
1125
1126 mgr.undo_blocking();
1127 mgr.undo_blocking();
1128
1129 txt.insert(&mut doc.transact_mut(), 2, "3");
1130 assert_eq!(txt.get_string(&doc.transact()), "12321");
1131 }
1132
1133 #[test]
1134 fn undo_map() {
1135 let d1 = Doc::with_client_id(1);
1136 let map1 = d1.get_or_insert_map("test");
1137
1138 let d2 = Doc::with_client_id(2);
1139 let map2 = d2.get_or_insert_map("test");
1140
1141 map1.insert(&mut d1.transact_mut(), "a", 0);
1142 let mut mgr = UndoManager::new(&d1, &map1);
1143 map1.insert(&mut d1.transact_mut(), "a", 1);
1144 mgr.undo_blocking();
1145 assert_eq!(map1.get(&d1.transact(), "a").unwrap(), 0.into());
1146 mgr.redo_blocking();
1147 assert_eq!(map1.get(&d1.transact(), "a").unwrap(), 1.into());
1148
1149 // testing sub-types and if it can restore a whole type
1150 let sub_type = map1.insert(&mut d1.transact_mut(), "a", MapPrelim::default());
1151 sub_type.insert(&mut d1.transact_mut(), "x", 42);
1152 let actual = map1.to_json(&d1.transact());
1153 let expected = Any::from_json(r#"{ "a": { "x": 42 } }"#).unwrap();
1154 assert_eq!(actual, expected);
1155
1156 mgr.undo_blocking();
1157 assert_eq!(map1.get(&d1.transact(), "a").unwrap(), 1.into());
1158 mgr.redo_blocking();
1159 let actual = map1.to_json(&d1.transact());
1160 let expected = Any::from_json(r#"{ "a": { "x": 42 } }"#).unwrap();
1161 assert_eq!(actual, expected);
1162
1163 exchange_updates(&[&d1, &d2]);
1164
1165 // if content is overwritten by another user, undo operations should be skipped
1166 map2.insert(&mut d2.transact_mut(), "a", 44);
1167
1168 exchange_updates(&[&d1, &d2]);
1169 exchange_updates(&[&d1, &d2]);
1170
1171 mgr.undo_blocking();
1172 assert_eq!(map1.get(&d1.transact(), "a").unwrap(), 44.into());
1173 mgr.redo_blocking();
1174 assert_eq!(map1.get(&d1.transact(), "a").unwrap(), 44.into());
1175
1176 // test setting value multiple times
1177 map1.insert(&mut d1.transact_mut(), "b", "initial");
1178 mgr.reset();
1179 map1.insert(&mut d1.transact_mut(), "b", "val1");
1180 map1.insert(&mut d1.transact_mut(), "b", "val2");
1181 mgr.reset();
1182 mgr.undo_blocking();
1183 assert_eq!(map1.get(&d1.transact(), "b").unwrap(), "initial".into());
1184 }
1185
1186 #[test]
1187 fn undo_array() {
1188 let d1 = Doc::with_client_id(1);
1189 let array1 = d1.get_or_insert_array("test");
1190
1191 let d2 = Doc::with_client_id(2);
1192 let array2 = d2.get_or_insert_array("test");
1193
1194 let mut mgr = UndoManager::new(&d1, &array1);
1195 array1.insert_range(&mut d1.transact_mut(), 0, [1, 2, 3]);
1196 array2.insert_range(&mut d2.transact_mut(), 0, [4, 5, 6]);
1197
1198 exchange_updates(&[&d1, &d2]);
1199
1200 assert_eq!(
1201 array1.to_json(&d1.transact()),
1202 vec![1, 2, 3, 4, 5, 6].into()
1203 );
1204 mgr.undo_blocking();
1205 assert_eq!(array1.to_json(&d1.transact()), vec![4, 5, 6].into());
1206 mgr.redo_blocking();
1207 assert_eq!(
1208 array1.to_json(&d1.transact()),
1209 vec![1, 2, 3, 4, 5, 6].into()
1210 );
1211
1212 exchange_updates(&[&d1, &d2]);
1213
1214 array2.remove_range(&mut d2.transact_mut(), 0, 1); // user2 deletes [1]
1215
1216 exchange_updates(&[&d1, &d2]);
1217
1218 mgr.undo_blocking();
1219 assert_eq!(array1.to_json(&d1.transact()), vec![4, 5, 6].into());
1220 mgr.redo_blocking();
1221 assert_eq!(array1.to_json(&d1.transact()), vec![2, 3, 4, 5, 6].into());
1222 array1.remove_range(&mut d1.transact_mut(), 0, 5);
1223
1224 // test nested structure
1225 let map = array1.insert(&mut d1.transact_mut(), 0, MapPrelim::default());
1226 let actual = array1.to_json(&d1.transact());
1227 let expected = Any::from_json(r#"[{}]"#).unwrap();
1228 assert_eq!(actual, expected);
1229 mgr.reset();
1230 map.insert(&mut d1.transact_mut(), "a", 1);
1231 let actual = array1.to_json(&d1.transact());
1232 let expected = Any::from_json(r#"[{"a":1}]"#).unwrap();
1233 assert_eq!(actual, expected);
1234
1235 mgr.undo_blocking();
1236 let actual = array1.to_json(&d1.transact());
1237 let expected = Any::from_json(r#"[{}]"#).unwrap();
1238 assert_eq!(actual, expected);
1239
1240 mgr.undo_blocking();
1241 assert_eq!(array1.to_json(&d1.transact()), vec![2, 3, 4, 5, 6].into());
1242
1243 mgr.redo_blocking();
1244 let actual = array1.to_json(&d1.transact());
1245 let expected = Any::from_json(r#"[{}]"#).unwrap();
1246 assert_eq!(actual, expected);
1247
1248 mgr.redo_blocking();
1249 let actual = array1.to_json(&d1.transact());
1250 let expected = Any::from_json(r#"[{"a":1}]"#).unwrap();
1251 assert_eq!(actual, expected);
1252
1253 exchange_updates(&[&d1, &d2]);
1254
1255 let map2 = array2
1256 .get(&d2.transact(), 0)
1257 .unwrap()
1258 .cast::<MapRef>()
1259 .unwrap();
1260 map2.insert(&mut d2.transact_mut(), "b", 2);
1261 exchange_updates(&[&d1, &d2]);
1262
1263 let actual = array1.to_json(&d1.transact());
1264 let expected = Any::from_json(r#"[{"a":1,"b":2}]"#).unwrap();
1265 assert_eq!(actual, expected);
1266
1267 mgr.undo_blocking();
1268 let actual = array1.to_json(&d1.transact());
1269 let expected = Any::from_json(r#"[{"b":2}]"#).unwrap();
1270 assert_eq!(actual, expected);
1271
1272 mgr.undo_blocking();
1273 assert_eq!(array1.to_json(&d1.transact()), vec![2, 3, 4, 5, 6].into());
1274
1275 mgr.redo_blocking();
1276 let actual = array1.to_json(&d1.transact());
1277 let expected = Any::from_json(r#"[{"b":2}]"#).unwrap();
1278 assert_eq!(actual, expected);
1279
1280 mgr.redo_blocking();
1281 let actual = array1.to_json(&d1.transact());
1282 let expected = Any::from_json(r#"[{"a":1,"b":2}]"#).unwrap();
1283 assert_eq!(actual, expected);
1284 }
1285
1286 #[test]
1287 fn undo_xml() {
1288 let d1 = Doc::with_client_id(1);
1289 let frag = d1.get_or_insert_xml_fragment("xml");
1290 let xml1 = frag.insert(
1291 &mut d1.transact_mut(),
1292 0,
1293 XmlElementPrelim::empty("undefined"),
1294 );
1295
1296 let mut mgr = UndoManager::new(&d1, &xml1);
1297 let child = xml1.insert(&mut d1.transact_mut(), 0, XmlElementPrelim::empty("p"));
1298 let text_child = child.insert(&mut d1.transact_mut(), 0, XmlTextPrelim::new("content"));
1299
1300 assert_eq!(
1301 xml1.get_string(&d1.transact()),
1302 "<undefined><p>content</p></undefined>"
1303 );
1304 // format textchild and revert that change
1305 mgr.reset();
1306 text_child.format(
1307 &mut d1.transact_mut(),
1308 3,
1309 4,
1310 Attrs::from([("bold".into(), any!({}))]),
1311 );
1312 assert_eq!(
1313 xml1.get_string(&d1.transact()),
1314 "<undefined><p>con<bold>tent</bold></p></undefined>"
1315 );
1316 mgr.undo_blocking();
1317 assert_eq!(
1318 xml1.get_string(&d1.transact()),
1319 "<undefined><p>content</p></undefined>"
1320 );
1321 mgr.redo_blocking();
1322 assert_eq!(
1323 xml1.get_string(&d1.transact()),
1324 "<undefined><p>con<bold>tent</bold></p></undefined>"
1325 );
1326 xml1.remove_range(&mut d1.transact_mut(), 0, 1);
1327 assert_eq!(xml1.get_string(&d1.transact()), "<undefined></undefined>");
1328 mgr.undo_blocking();
1329 assert_eq!(
1330 xml1.get_string(&d1.transact()),
1331 "<undefined><p>con<bold>tent</bold></p></undefined>"
1332 );
1333 }
1334
1335 #[test]
1336 fn undo_events() {
1337 use crate::undo::UndoManager;
1338 type Metadata = HashMap<String, usize>;
1339
1340 let doc = Doc::with_client_id(1);
1341 let txt = doc.get_or_insert_text("test");
1342 let mut mgr: UndoManager<Metadata> = UndoManager::new(&doc, &txt);
1343
1344 let result = Arc::new(AtomicUsize::new(0));
1345 let counter = AtomicUsize::new(1);
1346
1347 let txt_clone = txt.clone();
1348 let _sub1 = mgr.observe_item_added(move |_, e| {
1349 assert!(e.has_changed(&txt_clone));
1350 let c = counter.fetch_add(1, Ordering::SeqCst);
1351 let e = e.meta_mut().entry("test".to_string()).or_default();
1352 *e = c;
1353 });
1354
1355 let txt_clone = txt.clone();
1356 let result_clone = result.clone();
1357 let _sub2 = mgr.observe_item_popped(move |_, e| {
1358 assert!(e.has_changed(&txt_clone));
1359 if let Some(&v) = e.meta_mut().get("test") {
1360 result_clone.store(v, Ordering::Relaxed);
1361 }
1362 });
1363
1364 txt.insert(&mut doc.transact_mut(), 0, "abc");
1365 mgr.undo_blocking();
1366 assert_eq!(result.load(Ordering::SeqCst), 1);
1367 mgr.redo_blocking();
1368 assert_eq!(result.load(Ordering::SeqCst), 2);
1369 }
1370
1371 #[test]
1372 fn undo_until_change_performed() {
1373 let d1 = Doc::with_client_id(1);
1374 let arr1 = d1.get_or_insert_array("array");
1375
1376 let d2 = Doc::with_client_id(2);
1377 let arr2 = d2.get_or_insert_array("array");
1378
1379 let map1a = arr1.push_back(
1380 &mut d1.transact_mut(),
1381 MapPrelim::from([("hello".to_owned(), "world".to_owned())]),
1382 );
1383
1384 let map1b = arr1.push_back(
1385 &mut d1.transact_mut(),
1386 MapPrelim::from([("key".to_owned(), "value".to_owned())]),
1387 );
1388
1389 exchange_updates(&[&d1, &d2]);
1390
1391 let mut mgr1 = UndoManager::new(&d1, &arr1);
1392 mgr1.include_origin(d1.client_id());
1393
1394 let mut mgr2 = UndoManager::new(&d2, &arr2);
1395 mgr2.include_origin(d2.client_id());
1396
1397 map1b.insert(
1398 &mut d1.transact_mut_with(d1.client_id()),
1399 "key",
1400 "value modified",
1401 );
1402
1403 exchange_updates(&[&d1, &d2]);
1404 mgr1.reset();
1405
1406 map1a.insert(
1407 &mut d1.transact_mut_with(d1.client_id()),
1408 "hello",
1409 "world modified",
1410 );
1411
1412 exchange_updates(&[&d1, &d2]);
1413
1414 arr2.remove_range(&mut d2.transact_mut_with(d2.client_id()), 0, 1);
1415
1416 exchange_updates(&[&d1, &d2]);
1417 mgr2.undo_blocking();
1418
1419 exchange_updates(&[&d1, &d2]);
1420 mgr1.undo_blocking();
1421 exchange_updates(&[&d1, &d2]);
1422
1423 assert_eq!(map1b.get(&d1.transact(), "key"), Some("value".into()));
1424 }
1425
1426 #[test]
1427 fn nested_undo() {
1428 // This issue has been reported in https://github.com/yjs/yjs/issues/317
1429 let doc = Doc::with_options(crate::doc::Options {
1430 skip_gc: true,
1431 client_id: 1,
1432 ..crate::doc::Options::default()
1433 });
1434 let design = doc.get_or_insert_map("map");
1435 let mut mgr = UndoManager::with_scope_and_options(&doc, &design, {
1436 let mut o = Options::default();
1437 o.capture_timeout_millis = 0;
1438 o
1439 });
1440 {
1441 let mut txn = doc.transact_mut();
1442 design.insert(
1443 &mut txn,
1444 "text",
1445 MapPrelim::from([(
1446 "blocks",
1447 MapPrelim::from([("text", "Type something".to_owned())]),
1448 )]),
1449 );
1450 }
1451 let text = design
1452 .get(&doc.transact(), "text")
1453 .unwrap()
1454 .cast::<MapRef>()
1455 .unwrap();
1456
1457 {
1458 let mut txn = doc.transact_mut();
1459 text.insert(&mut txn, "blocks", MapPrelim::from([("text", "Something")]));
1460 }
1461
1462 {
1463 let mut txn = doc.transact_mut();
1464 text.insert(
1465 &mut txn,
1466 "blocks",
1467 MapPrelim::from([("text", "Something else")]),
1468 );
1469 }
1470
1471 assert_eq!(
1472 design.to_json(&doc.transact()),
1473 Any::from_json(r#"{ "text": { "blocks": { "text": "Something else" } } }"#).unwrap()
1474 );
1475 mgr.undo_blocking();
1476 assert_eq!(
1477 design.to_json(&doc.transact()),
1478 Any::from_json(r#"{ "text": { "blocks": { "text": "Something" } } }"#).unwrap()
1479 );
1480 mgr.undo_blocking();
1481 assert_eq!(
1482 design.to_json(&doc.transact()),
1483 Any::from_json(r#"{ "text": { "blocks": { "text": "Type something" } } }"#).unwrap()
1484 );
1485 mgr.undo_blocking();
1486 assert_eq!(
1487 design.to_json(&doc.transact()),
1488 Any::from_json(r#"{}"#).unwrap()
1489 );
1490 mgr.redo_blocking();
1491 assert_eq!(
1492 design.to_json(&doc.transact()),
1493 Any::from_json(r#"{ "text": { "blocks": { "text": "Type something" } } }"#).unwrap()
1494 );
1495 mgr.redo_blocking();
1496 assert_eq!(
1497 design.to_json(&doc.transact()),
1498 Any::from_json(r#"{ "text": { "blocks": { "text": "Something" } } }"#).unwrap()
1499 );
1500 mgr.redo_blocking();
1501 assert_eq!(
1502 design.to_json(&doc.transact()),
1503 Any::from_json(r#"{ "text": { "blocks": { "text": "Something else" } } }"#).unwrap()
1504 );
1505 }
1506
1507 #[test]
1508 fn consecutive_redo_bug() {
1509 // https://github.com/yjs/yjs/issues/355
1510 let doc = Doc::with_client_id(1);
1511 let root = doc.get_or_insert_map("root");
1512 let mut mgr = UndoManager::new(&doc, &root);
1513
1514 root.insert(
1515 &mut doc.transact_mut(),
1516 "a",
1517 MapPrelim::from([("x".to_owned(), Any::from(0)), ("y".to_owned(), 0.into())]),
1518 );
1519 let point = root
1520 .get(&doc.transact(), "a")
1521 .unwrap()
1522 .cast::<MapRef>()
1523 .unwrap();
1524 mgr.reset();
1525
1526 point.insert(&mut doc.transact_mut(), "x", 100);
1527 point.insert(&mut doc.transact_mut(), "y", 100);
1528 mgr.reset();
1529
1530 point.insert(&mut doc.transact_mut(), "x", 200);
1531 point.insert(&mut doc.transact_mut(), "y", 200);
1532 mgr.reset();
1533
1534 point.insert(&mut doc.transact_mut(), "x", 300);
1535 point.insert(&mut doc.transact_mut(), "y", 300);
1536 mgr.reset();
1537
1538 let actual = point.to_json(&doc.transact());
1539 assert_eq!(actual, Any::from_json(r#"{"x":300,"y":300}"#).unwrap());
1540
1541 mgr.undo_blocking(); // x=200, y=200
1542 let actual = point.to_json(&doc.transact());
1543 assert_eq!(actual, Any::from_json(r#"{"x":200,"y":200}"#).unwrap());
1544
1545 mgr.undo_blocking(); // x=100, y=100
1546 let actual = point.to_json(&doc.transact());
1547 assert_eq!(actual, Any::from_json(r#"{"x":100,"y":100}"#).unwrap());
1548
1549 mgr.undo_blocking(); // x=0, y=0
1550 let actual = point.to_json(&doc.transact());
1551 assert_eq!(actual, Any::from_json(r#"{"x":0,"y":0}"#).unwrap());
1552
1553 mgr.undo_blocking(); // null
1554 assert_eq!(root.get(&doc.transact(), "a"), None);
1555
1556 mgr.redo_blocking(); // x=0, y=0
1557 let point = root
1558 .get(&doc.transact(), "a")
1559 .unwrap()
1560 .cast::<MapRef>()
1561 .unwrap();
1562
1563 assert_eq!(actual, Any::from_json(r#"{"x":0,"y":0}"#).unwrap());
1564
1565 mgr.redo_blocking(); // x=100, y=100
1566 let actual = point.to_json(&doc.transact());
1567 assert_eq!(actual, Any::from_json(r#"{"x":100,"y":100}"#).unwrap());
1568
1569 mgr.redo_blocking(); // x=200, y=200
1570 let actual = point.to_json(&doc.transact());
1571 assert_eq!(actual, Any::from_json(r#"{"x":200,"y":200}"#).unwrap());
1572
1573 mgr.redo_blocking(); // x=300, y=300
1574 let actual = point.to_json(&doc.transact());
1575 assert_eq!(actual, Any::from_json(r#"{"x":300,"y":300}"#).unwrap());
1576 }
1577
1578 #[test]
1579 fn undo_xml_bug() {
1580 // https://github.com/yjs/yjs/issues/304
1581 const ORIGIN: &str = "origin";
1582 let doc = Doc::with_client_id(1);
1583 let f = doc.get_or_insert_xml_fragment("t");
1584 let mut mgr = UndoManager::with_scope_and_options(&doc, &f, {
1585 let mut o = Options::default();
1586 o.capture_timeout_millis = 0;
1587 o
1588 });
1589 mgr.include_origin(ORIGIN);
1590
1591 // create element
1592 {
1593 let mut txn = doc.transact_mut_with(ORIGIN);
1594 let e = f.insert(&mut txn, 0, XmlElementPrelim::empty("test-node"));
1595 e.insert_attribute(&mut txn, "a", "100");
1596 e.insert_attribute(&mut txn, "b", "0");
1597 }
1598
1599 // change one attribute
1600 {
1601 let mut txn = doc.transact_mut_with(ORIGIN);
1602 let e: XmlElementRef = f.get(&txn, 0).unwrap().try_into().unwrap();
1603 e.insert_attribute(&mut txn, "a", "200");
1604 }
1605
1606 // change both attributes
1607 {
1608 let mut txn = doc.transact_mut_with(ORIGIN);
1609 let e: XmlElementRef = f.get(&txn, 0).unwrap().try_into().unwrap();
1610 e.insert_attribute(&mut txn, "a", "180");
1611 e.insert_attribute(&mut txn, "b", "50");
1612 }
1613
1614 mgr.undo_blocking();
1615 mgr.undo_blocking();
1616 mgr.undo_blocking();
1617
1618 mgr.redo_blocking();
1619 mgr.redo_blocking();
1620 mgr.redo_blocking();
1621
1622 let str = f.get_string(&doc.transact());
1623 assert!(
1624 str == r#"<test-node a="180" b="50"></test-node>"#
1625 || str == r#"<test-node b="50" a="180"></test-node>"#
1626 );
1627 }
1628
1629 #[test]
1630 fn undo_block_bug() {
1631 // https://github.com/yjs/yjs/issues/343
1632 let doc = Doc::with_options({
1633 let mut o = crate::doc::Options::default();
1634 o.client_id = 1;
1635 o.skip_gc = true;
1636 o
1637 });
1638 let design = doc.get_or_insert_map("map");
1639 let mut mgr = UndoManager::with_scope_and_options(&doc, &design, {
1640 let mut o = Options::default();
1641 o.capture_timeout_millis = 0;
1642 o
1643 });
1644 let text = {
1645 let mut txn = doc.transact_mut();
1646 design.insert(
1647 &mut txn,
1648 "text",
1649 MapPrelim::from([(
1650 "blocks",
1651 MapPrelim::from([("text".to_owned(), "1".to_owned())]),
1652 )]),
1653 )
1654 };
1655 {
1656 let mut txn = doc.transact_mut();
1657 text.insert(
1658 &mut txn,
1659 "blocks",
1660 MapPrelim::from([("text".to_owned(), "1".to_owned())]),
1661 );
1662 }
1663 {
1664 let mut txn = doc.transact_mut();
1665 text.insert(
1666 &mut txn,
1667 "blocks",
1668 MapPrelim::from([("text".to_owned(), "3".to_owned())]),
1669 );
1670 }
1671 {
1672 let mut txn = doc.transact_mut();
1673 text.insert(
1674 &mut txn,
1675 "blocks",
1676 MapPrelim::from([("text".to_owned(), "4".to_owned())]),
1677 );
1678 }
1679 // {"text":{"blocks":{"text":"4"}}}
1680 mgr.undo_blocking(); // {"text":{"blocks":{"3"}}}
1681 mgr.undo_blocking(); // {"text":{"blocks":{"text":"2"}}}
1682 mgr.undo_blocking(); // {"text":{"blocks":{"text":"1"}}}
1683 mgr.undo_blocking(); // {}
1684 mgr.redo_blocking(); // {"text":{"blocks":{"text":"1"}}}
1685 mgr.redo_blocking(); // {"text":{"blocks":{"text":"2"}}}
1686 mgr.redo_blocking(); // {"text":{"blocks":{"text":"3"}}}
1687 mgr.redo_blocking(); // {"text":{}}
1688 let actual = design.to_json(&doc.transact());
1689 assert_eq!(
1690 actual,
1691 Any::from_json(r#"{"text":{"blocks":{"text":"4"}}}"#).unwrap()
1692 );
1693 }
1694
1695 #[test]
1696 fn undo_delete_text_format() {
1697 // https://github.com/yjs/yjs/issues/392
1698 fn send(src: &Doc, dst: &Doc) {
1699 let update = Update::decode_v1(
1700 &src.transact()
1701 .encode_state_as_update_v1(&StateVector::default()),
1702 )
1703 .unwrap();
1704 dst.transact_mut().apply_update(update).unwrap();
1705 }
1706
1707 let doc1 = Doc::with_client_id(1);
1708 let txt = doc1.get_or_insert_text("test");
1709 txt.insert(
1710 &mut doc1.transact_mut(),
1711 0,
1712 "Attack ships on fire off the shoulder of Orion.",
1713 ); // D1: 'Attack ships on fire off the shoulder of Orion.'
1714 let doc2 = Doc::with_client_id(2);
1715 let txt2 = doc2.get_or_insert_text("test");
1716
1717 send(&doc1, &doc2); // D2: 'Attack ships on fire off the shoulder of Orion.'
1718 let mut mgr = UndoManager::new(&doc1, &txt);
1719
1720 let attrs = Attrs::from([("bold".into(), true.into())]);
1721 txt.format(&mut doc1.transact_mut(), 13, 7, attrs.clone()); // D1: 'Attack ships <b>on fire</b> off the shoulder of Orion.'
1722
1723 mgr.reset();
1724
1725 send(&doc1, &doc2); // D2: 'Attack ships <b>on fire</b> off the shoulder of Orion.'
1726
1727 let attrs2 = Attrs::from([("bold".into(), Any::Null)]);
1728 txt.format(&mut doc1.transact_mut(), 16, 4, attrs2.clone()); // D1: 'Attack ships <b>on </b>fire off the shoulder of Orion.'
1729
1730 let expected = vec![
1731 Diff::new("Attack ships ".into(), None),
1732 Diff::new("on ".into(), Some(Box::new(attrs.clone()))),
1733 Diff::new("fire off the shoulder of Orion.".into(), None),
1734 ];
1735 let actual = txt.diff(&doc1.transact(), YChange::identity);
1736 assert_eq!(actual, expected);
1737
1738 mgr.reset();
1739 send(&doc1, &doc2); // D2: 'Attack ships <b>on </b>fire off the shoulder of Orion.'
1740
1741 mgr.undo_blocking(); // D1: 'Attack ships <b>on fire</b> off the shoulder of Orion.'
1742 send(&doc1, &doc2); // D2: 'Attack ships <b>on fire</b> off the shoulder of Orion.'
1743
1744 let expected = vec![
1745 Diff::new("Attack ships ".into(), None),
1746 Diff::new("on fire".into(), Some(Box::new(attrs))),
1747 Diff::new(" off the shoulder of Orion.".into(), None),
1748 ];
1749 let actual = txt.diff(&doc1.transact(), YChange::identity);
1750 assert_eq!(actual, expected);
1751 let actual = txt2.diff(&doc2.transact(), YChange::identity);
1752 assert_eq!(actual, expected);
1753 }
1754
1755 #[test]
1756 fn special_deletion_case() {
1757 // https://github.com/yjs/yjs/issues/447
1758 const ORIGIN: &str = "undoable";
1759 let doc = Doc::with_client_id(1);
1760 let f = doc.get_or_insert_xml_fragment("test");
1761 let mut mgr = UndoManager::new(&doc, &f);
1762 mgr.include_origin(ORIGIN);
1763 {
1764 let mut txn = doc.transact_mut();
1765 let e = f.insert(&mut txn, 0, XmlElementPrelim::empty("test"));
1766 e.insert_attribute(&mut txn, "a", "1");
1767 e.insert_attribute(&mut txn, "b", "2");
1768 }
1769 let s = f.get_string(&doc.transact());
1770 assert!(s == r#"<test a="1" b="2"></test>"# || s == r#"<test b="2" a="1"></test>"#);
1771 {
1772 // change attribute "b" and delete test-node
1773 let mut txn = doc.transact_mut_with(ORIGIN);
1774 let e: XmlElementRef = f.get(&txn, 0).unwrap().try_into().unwrap();
1775 e.insert_attribute(&mut txn, "b", "3");
1776 f.remove_range(&mut txn, 0, 1);
1777 }
1778 assert_eq!(f.get_string(&doc.transact()), "");
1779
1780 mgr.undo_blocking();
1781 let s = f.get_string(&doc.transact());
1782 assert!(s == r#"<test a="1" b="2"></test>"# || s == r#"<test b="2" a="1"></test>"#);
1783 }
1784
1785 #[test]
1786 fn undo_in_embed() {
1787 let d1 = Doc::with_client_id(1);
1788 let txt1 = d1.get_or_insert_text("test");
1789 let mut mgr = UndoManager::new(&d1, &txt1);
1790
1791 let d2 = Doc::with_client_id(2);
1792 let txt2 = d2.get_or_insert_text("test");
1793
1794 let attrs = Attrs::from([("bold".into(), true.into())]);
1795 let nested = txt1.insert_embed_with_attributes(
1796 &mut d1.transact_mut(),
1797 0,
1798 TextPrelim::new("initial text"),
1799 attrs,
1800 );
1801 assert_eq!(
1802 nested.get_string(&d1.transact()),
1803 "initial text".to_string()
1804 );
1805 mgr.reset();
1806 {
1807 let mut txn = d1.transact_mut();
1808 let len = nested.len(&txn);
1809 nested.remove_range(&mut txn, 0, len);
1810 }
1811 nested.insert(&mut d1.transact_mut(), 0, "other text");
1812 assert_eq!(nested.get_string(&d1.transact()), "other text".to_string());
1813 mgr.undo_blocking();
1814 assert_eq!(
1815 nested.get_string(&d1.transact()),
1816 "initial text".to_string()
1817 );
1818
1819 exchange_updates(&[&d1, &d2]);
1820 let diff = txt2.diff(&d1.transact(), YChange::identity);
1821 let nested2 = diff[0].insert.clone().cast::<TextRef>().unwrap();
1822 assert_eq!(
1823 nested2.get_string(&d2.transact()),
1824 "initial text".to_string()
1825 );
1826
1827 mgr.undo_blocking();
1828 assert_eq!(nested.len(&d1.transact()), 0);
1829 }
1830
1831 #[test]
1832 fn github_issue_345() {
1833 // https://github.com/y-crdt/y-crdt/issues/345
1834 let doc = Doc::new();
1835 let map = doc.get_or_insert_map("r");
1836 let mut mgr = UndoManager::with_scope_and_options(&doc, &map, Options::default());
1837 mgr.include_origin(doc.client_id());
1838
1839 let s1 = map.insert(
1840 &mut doc.transact_mut_with(doc.client_id()),
1841 "s1",
1842 MapPrelim::default(),
1843 );
1844 mgr.reset();
1845
1846 let mut txn = doc.transact_mut_with(doc.client_id());
1847 let a = s1.insert(&mut txn, "a", ArrayPrelim::default());
1848 a.insert(&mut txn, 0, "a1");
1849 drop(txn);
1850 mgr.reset();
1851
1852 let mut txn = doc.transact_mut_with(doc.client_id());
1853 let b = s1.insert(&mut txn, "b", ArrayPrelim::default());
1854 b.insert(&mut txn, 0, "b1");
1855 drop(txn);
1856 mgr.reset();
1857
1858 b.insert(&mut doc.transact_mut_with(doc.client_id()), 1, "b2");
1859 mgr.reset();
1860
1861 a.insert(&mut doc.transact_mut_with(doc.client_id()), 1, "a3");
1862 mgr.reset();
1863
1864 a.insert(&mut doc.transact_mut_with(doc.client_id()), 2, "a4");
1865 mgr.reset();
1866
1867 a.insert(&mut doc.transact_mut_with(doc.client_id()), 3, "a5");
1868 mgr.reset();
1869
1870 let actual = map.to_json(&doc.transact());
1871 assert_eq!(
1872 actual,
1873 any!({"s1": {"a": ["a1", "a3", "a4", "a5"], "b": ["b1", "b2"]}})
1874 );
1875
1876 mgr.undo_blocking(); // {"s1": {"a": ["a1", "a3", "a4"], "b": ["b1", "b2"]}}
1877 mgr.undo_blocking(); // {"s1": {"a": ["a1", "a3"], "b": ["b1", "b2"]}}
1878 mgr.undo_blocking(); // {"s1": {"a": ["a1"], "b": ["b1", "b2"]}}
1879 mgr.undo_blocking(); // {"s1": {"a": ["a1"], "b": ["b1"]}}
1880 let actual = map.to_json(&doc.transact());
1881 assert_eq!(actual, any!({"s1": {"a": ["a1"], "b": ["b1"]}}));
1882
1883 mgr.redo_blocking();
1884 let actual = map.to_json(&doc.transact());
1885 assert_eq!(actual, any!({"s1": {"b": ["b1", "b2"], "a": ["a1"]}}));
1886
1887 mgr.redo_blocking();
1888 let actual = map.to_json(&doc.transact());
1889 assert_eq!(actual, any!({"s1": {"a": ["a1", "a3"], "b": ["b1", "b2"]}}));
1890
1891 mgr.redo_blocking();
1892 let actual = map.to_json(&doc.transact());
1893 assert_eq!(
1894 actual,
1895 any!({"s1": {"a": ["a1", "a3", "a4"], "b": ["b1", "b2"]}})
1896 );
1897
1898 mgr.redo_blocking();
1899 let actual = map.to_json(&doc.transact());
1900 assert_eq!(
1901 actual,
1902 any!({"s1": {"a": ["a1", "a3", "a4", "a5"], "b": ["b1", "b2"]}})
1903 );
1904 }
1905
1906 #[test]
1907 fn github_issue_345_part_2() {
1908 // https://github.com/y-crdt/y-crdt/issues/345
1909 let d = Doc::new();
1910 let r = d.get_or_insert_map("r");
1911
1912 let s1 = r.insert(&mut d.transact_mut(), "s1", MapPrelim::default());
1913
1914 let mut mgr = UndoManager::with_scope_and_options(&d, &r, Options::default());
1915 {
1916 let mut txn = d.transact_mut();
1917 let b1 = s1.insert(&mut txn, "b1", MapPrelim::default());
1918 b1.insert(&mut txn, "f1", 11);
1919 }
1920 mgr.reset();
1921
1922 s1.remove(&mut d.transact_mut(), "b1");
1923 mgr.reset();
1924
1925 {
1926 let mut txn = d.transact_mut();
1927 let b1 = s1.insert(&mut txn, "b1", MapPrelim::default());
1928 b1.insert(&mut txn, "f1", 20);
1929 }
1930 mgr.reset();
1931
1932 let actual = r.to_json(&d.transact());
1933 assert_eq!(actual, any!({"s1": {"b1": {"f1": 20}}}));
1934
1935 mgr.undo_blocking();
1936 let actual = r.to_json(&d.transact());
1937 assert_eq!(actual, any!({"s1": {}}));
1938 assert!(mgr.can_undo(), "should be able to undo");
1939
1940 mgr.undo_blocking();
1941 let actual = r.to_json(&d.transact());
1942 assert_eq!(actual, any!({"s1": {"b1": {"f1": 11}}}));
1943 assert!(mgr.can_undo(), "should be able to undo to the init state");
1944 }
1945
1946 #[test]
1947 fn issue_371() {
1948 let doc = Doc::with_client_id(1);
1949
1950 let r = doc.get_or_insert_map("r");
1951 let s1 = r.insert(&mut doc.transact_mut(), "s1", MapPrelim::default()); // { s1: {} }
1952 let b1_arr = s1.insert(&mut doc.transact_mut(), "b1", ArrayPrelim::default()); // { s1: { b1: [] } }
1953 let el1 = b1_arr.insert(&mut doc.transact_mut(), 0, MapPrelim::default()); // { s1: { b1: [{}] } }
1954 el1.insert(&mut doc.transact_mut(), "f1", 8); // { s1: { b1: [{ f1: 8 }] } }
1955 el1.insert(&mut doc.transact_mut(), "f2", true); // { s1: { b1: [{ f1: 8, f2: true }] } }
1956
1957 let mut mgr = UndoManager::with_scope_and_options(&doc, &r, Options::default());
1958 {
1959 let mut txn = doc.transact_mut();
1960 let el0 = b1_arr.insert(&mut txn, 0, MapPrelim::default()); // { s1: { b1: [{}, { f1: 8, f2: true }] } }
1961 el0.insert(&mut txn, "f1", 8); // { s1: { b1: [{ f1: 8 }, { f1: 8, f2: true }] } }
1962 el0.insert(&mut txn, "f2", false); // { s1: { b1: [{ f1: 8, f2: false }, { f1: 8, f2: true }] } }
1963
1964 el1.insert(&mut txn, "f1", 13); // { s1: { b1: [{ f1: 8, f2: false }, { f1: 13, f2: true }] } }
1965 el1.remove(&mut txn, "f2"); // { s1: { b1: [{ f1: 8, f2: false }, { f1: 13 }] } }
1966 }
1967 mgr.reset();
1968
1969 el1.insert(&mut doc.transact_mut(), "f2", false); // { s1: { b1: [{ f1: 8, f2: false }, { f1: 13, f2: false }] } }
1970 mgr.reset();
1971
1972 el1.insert(&mut doc.transact_mut(), "f2", true); // { s1: { b1: [{ f1: 8, f2: false }, { f1: 13, f2: true }] } }
1973 mgr.reset();
1974
1975 mgr.undo_blocking(); // { s1: { b1: [{ f1: 8, f2: false }, { f1: 13, f2: false }] } }
1976 assert_eq!(
1977 r.to_json(&doc.transact()),
1978 any!({ "s1": { "b1": [{ "f1": 8, "f2": false }, { "f1": 13, "f2": false }] } })
1979 );
1980 mgr.undo_blocking(); // { s1: { b1: [{ f1: 8, f2: false }, { f1: 13 }] } }
1981 assert_eq!(
1982 r.to_json(&doc.transact()),
1983 any!({ "s1": { "b1": [{ "f1": 8, "f2": false }, { "f1": 13 }] } })
1984 );
1985 mgr.undo_blocking(); // { s1: { b1: [{ f1: 8, f2: true }] } }
1986 assert_eq!(
1987 r.to_json(&doc.transact()),
1988 any!({ "s1": { "b1": [{ "f1": 8, "f2": true }] } })
1989 );
1990 assert!(!mgr.undo_blocking()); // no more changes tracked by undo manager
1991 }
1992
1993 #[test]
1994 fn issue_371_2() {
1995 let doc = Doc::with_client_id(1);
1996 let r = doc.get_or_insert_map("r");
1997 let s1 = r.insert(&mut doc.transact_mut(), "s1", MapPrelim::default()); // { s1:{} }
1998 s1.insert(&mut doc.transact_mut(), "f2", "AAA"); // { s1: { f2: AAA } }
1999 s1.insert(&mut doc.transact_mut(), "f1", false); // { s1: { f1: false, f2: AAA } }
2000
2001 let mut mgr = UndoManager::with_scope_and_options(&doc, &r, Options::default());
2002 s1.remove(&mut doc.transact_mut(), "f2"); // { s1: { f1: false } }
2003 mgr.reset();
2004
2005 s1.insert(&mut doc.transact_mut(), "f2", "C1"); // { s1: { f1: false, f2: C1 } }
2006 mgr.reset();
2007
2008 s1.insert(&mut doc.transact_mut(), "f2", "C2"); // { s1: { f1: false, f2: C2 } }
2009 mgr.reset();
2010
2011 mgr.undo_blocking(); // { s1: { f1: false, f2: C1 } }
2012 assert_eq!(
2013 r.to_json(&doc.transact()),
2014 any!({ "s1": { "f1": false, "f2": "C1" } })
2015 );
2016 mgr.undo_blocking(); // { s1: { f1: false } }
2017 assert_eq!(r.to_json(&doc.transact()), any!({ "s1": { "f1": false } }));
2018 mgr.undo_blocking(); // { s1: { f1: false, f2: AAA } }
2019 assert_eq!(
2020 r.to_json(&doc.transact()),
2021 any!({ "s1": { "f1": false, "f2": "AAA" } })
2022 );
2023 assert!(!mgr.undo_blocking()); // no more changes tracked by undo manager
2024 }
2025
2026 #[test]
2027 fn issue_380() {
2028 let d = Doc::with_client_id(1);
2029 let r = d.get_or_insert_map("r"); // {r:{}}
2030 let s1 = r.insert(&mut d.transact_mut(), "s1", MapPrelim::default()); // {r:{s1:{}}
2031 let b1_arr = s1.insert(&mut d.transact_mut(), "b1", ArrayPrelim::default()); // {r:{s1:{b1:[]}}
2032
2033 let b1_el1 = b1_arr.insert(&mut d.transact_mut(), 0, MapPrelim::default()); // {r:{s1:{b1:[{}]}}
2034 let b2_arr = b1_el1.insert(&mut d.transact_mut(), "b2", ArrayPrelim::default()); // {r:{s1:{b1:[{b2:[]}]}}
2035 let b2_arr_nest = b2_arr.insert(&mut d.transact_mut(), 0, ArrayPrelim::default()); // {r:{s1:{b1:[{b2:[[]]}]}}
2036 b2_arr_nest.insert(&mut d.transact_mut(), 0, 232291652); // {r:{s1:{b1:[{b2:[[232291652]]}]}}
2037 b2_arr_nest.insert(&mut d.transact_mut(), 1, -30); // {r:{s1:{b1:[{b2:[[232291652, -30]]}]}}
2038
2039 let mut mgr = UndoManager::with_scope_and_options(&d, &r, Options::default());
2040
2041 let mut txn = d.transact_mut();
2042 b2_arr_nest.remove(&mut txn, 1); // {r:{s1:{b1:[{b2:[[232291652]]}]}}
2043 b2_arr_nest.insert(&mut txn, 1, -5); // {r:{s1:{b1:[{b2:[[232291652, -5]]}]}}
2044
2045 drop(txn);
2046 mgr.reset();
2047
2048 let mut txn = d.transact_mut();
2049
2050 let b1_el0 = b1_arr.insert(&mut txn, 0, MapPrelim::default()); // {r:{s1:{b1:[{},{b2:[[232291652, -5]]}]}}
2051 let b2_0_arr = b1_el0.insert(&mut txn, "b2", ArrayPrelim::default()); // {r:{s1:{b1:[{b2:[]},{b2:[[232291652, -5]]}]}}
2052 let b2_0_arr_nest = b2_0_arr.insert(&mut txn, 0, ArrayPrelim::default()); // {r:{s1:{b1:[{b2:[[]]},{b2:[[232291652, -5]]}]}}
2053 b2_0_arr_nest.insert(&mut txn, 0, 232291652); // {r:{s1:{b1:[{b2:[[232291652]]},{b2:[[232291652, -5]]}]}}
2054 b2_0_arr_nest.insert(&mut txn, 1, -6); // {r:{s1:{b1:[{b2:[[232291652, -6]]},{b2:[[232291652, -5]]}]}}
2055 b1_arr.remove(&mut txn, 1); // {r:{s1:{b1:[{b2:[[232291652, -6]]}]}}
2056
2057 let b1_el1 = b1_arr.insert(&mut txn, 1, MapPrelim::default()); // {r:{s1:{b1:[{b2:[[232291652, -6]]}, {}]}}
2058 b1_el1.insert(&mut txn, "f2", "C1"); // {r:{s1:{b1:[{b2:[[232291652, -6]]}, {f2:C1}]}}
2059
2060 drop(txn);
2061 mgr.reset();
2062 assert_eq!(
2063 r.to_json(&d.transact()),
2064 any!({"s1":{"b1":[{"b2":[[232291652, -6]]}, {"f2":"C1"}]}})
2065 );
2066
2067 mgr.undo_blocking(); // {r:{s1:{b1:[{b2:[[232291652, -5]]}]}}
2068 assert_eq!(
2069 r.to_json(&d.transact()),
2070 any!({"s1":{"b1":[{"b2":[[232291652, -5]]}]}})
2071 );
2072
2073 mgr.undo_blocking(); // {r:{s1:{b1:[{b2:[[232291652, -30]]}]}}
2074 assert_eq!(
2075 r.to_json(&d.transact()),
2076 any!({"s1":{"b1":[{"b2":[[232291652, -30]]}]}})
2077 );
2078 }
2079}
2080