1
//! Undo/Redo Manager for text editing operations
2
//!
3
//! This module implements a per-node undo/redo stack that records text changesets
4
//! and the state before they were applied. This allows reverting changes with Ctrl+Z
5
//! and re-applying them with Ctrl+Y/Ctrl+Shift+Z.
6
//!
7
//! ## Architecture
8
//!
9
//! - **Per-Node Tracking**: Each text node has its own undo/redo stack
10
//! - **Changeset-Based**: Records `TextChangesets` from changeset.rs
11
//! - **State Snapshots**: Saves node state BEFORE changeset application (for revert)
12
//! - **Bounded History**: Keeps last 10 operations per node (configurable)
13
//! - **Callback Integration**: User can intercept via `preventDefault()`
14
//!
15
//! ## Usage Flow
16
//!
17
//! 1. User types text → `TextChangeset` created
18
//! 2. Pre-callback: Record current node state
19
//! 3. User callback: Can query/modify via `CallbackInfo`
20
//! 4. Apply changeset (if !preventDefault)
21
//! 5. Post-callback: Push changeset + pre-state to undo stack
22
//!
23
//! 6. User presses Ctrl+Z → Undo event detected
24
//! 7. Pre-callback: Pop undo stack, create revert changeset
25
//! 8. User callback: Can preventDefault or inspect
26
//! 9. Apply revert (if !preventDefault)
27
//! 10. Post-callback: Push original changeset to redo stack
28

            
29
use alloc::{collections::VecDeque, vec::Vec};
30

            
31
use azul_core::{
32
    dom::{DomId, NodeId},
33
    selection::{OptionSelectionRange, OptionTextCursor},
34
    task::Instant,
35
};
36
use azul_css::{impl_option, impl_option_inner, AzString};
37

            
38
use super::changeset::TextChangeset;
39

            
40
/// Maximum number of undo operations to keep per node
41
pub const MAX_UNDO_HISTORY: usize = 10;
42

            
43
/// Maximum number of redo operations to keep per node
44
pub const MAX_REDO_HISTORY: usize = 10;
45

            
46
/// Snapshot of a text node's state before a changeset was applied.
47
///
48
/// This contains enough information to fully revert a text operation.
49
#[derive(Debug, Clone)]
50
#[repr(C)]
51
pub struct NodeStateSnapshot {
52
    /// The node this snapshot belongs to
53
    pub node_id: NodeId,
54
    /// Full text content before changeset
55
    pub text_content: AzString,
56
    /// Cursor position before changeset (if applicable)
57
    /// For now, we store the logical position, not the `TextCursor`
58
    pub cursor_position: OptionTextCursor,
59
    /// Selection range before changeset (if applicable)
60
    pub selection_range: OptionSelectionRange,
61
    /// When this snapshot was taken
62
    pub timestamp: Instant,
63
}
64

            
65
/// A recorded operation that can be undone/redone.
66
///
67
/// Combines the changeset that was applied with the state before application.
68
#[derive(Debug, Clone)]
69
#[repr(C)]
70
pub struct UndoableOperation {
71
    /// The changeset that was applied
72
    pub changeset: TextChangeset,
73
    /// Node state BEFORE the changeset was applied
74
    pub pre_state: NodeStateSnapshot,
75
    /// The SEAT that made the edit (9b-ii-a-i-d-ii-d): 0 is the primary.
76
    /// Undo is per person: a seat's Undo pops its own latest edit, and only
77
    /// while that edit is still the top of the node's stack (nobody else has
78
    /// edited the node since); otherwise it is refused rather than undoing
79
    /// someone else's work or clobbering it with a stale snapshot.
80
    pub seat_id: u64,
81
}
82

            
83
impl_option!(
84
    UndoableOperation,
85
    OptionUndoableOperation,
86
    copy = false,
87
    [Debug, Clone]
88
);
89

            
90
/// Per-node undo/redo stack
91
#[derive(Debug, Clone)]
92
pub struct NodeUndoRedoStack {
93
    /// Node ID this stack belongs to
94
    pub node_id: NodeId,
95
    /// Undo stack (most recent at back)
96
    pub undo_stack: VecDeque<UndoableOperation>,
97
    /// Redo stack (most recent at back)
98
    pub redo_stack: VecDeque<UndoableOperation>,
99
}
100

            
101
impl NodeUndoRedoStack {
102
    #[must_use]
103
611
    pub fn new(node_id: NodeId) -> Self {
104
611
        Self {
105
611
            node_id,
106
611
            undo_stack: VecDeque::with_capacity(MAX_UNDO_HISTORY),
107
611
            redo_stack: VecDeque::with_capacity(MAX_REDO_HISTORY),
108
611
        }
109
611
    }
110

            
111
    /// Push a new operation to the undo stack
112
3011
    pub fn push_undo(&mut self, operation: UndoableOperation) {
113
        // Clear redo stack when new operation is performed
114
3011
        self.redo_stack.clear();
115

            
116
        // Add to undo stack
117
3011
        self.undo_stack.push_back(operation);
118

            
119
        // Limit stack size
120
3011
        if self.undo_stack.len() > MAX_UNDO_HISTORY {
121
1852
            self.undo_stack.pop_front();
122
1869
        }
123
3011
    }
124

            
125
    /// MWA-C-undo_redo: move a REDONE operation back onto the undo stack
126
    /// WITHOUT clearing the redo stack — `push_undo` clears it (correct for
127
    /// fresh user edits), which made every redo destroy the remaining redo
128
    /// history.
129
54
    pub fn push_undo_preserving_redo(&mut self, operation: UndoableOperation) {
130
54
        self.undo_stack.push_back(operation);
131
54
        if self.undo_stack.len() > MAX_UNDO_HISTORY {
132
30
            self.undo_stack.pop_front();
133
40
        }
134
54
    }
135

            
136
    /// Pop the most recent operation from undo stack
137
117
    pub fn pop_undo(&mut self) -> Option<UndoableOperation> {
138
117
        self.undo_stack.pop_back()
139
117
    }
140

            
141
    /// Per-person undo (9b-ii-a-i-d-ii-d): pop the top only if `seat_id`
142
    /// made it. A seat whose latest edit is buried under another seat's
143
    /// edits gets `None` - the interleaved case needs operational
144
    /// transformation, which is 9b-ii-a-i-d-ii-d-i.
145
46
    pub fn pop_undo_for_seat(&mut self, seat_id: u64) -> Option<UndoableOperation> {
146
46
        if self
147
46
            .undo_stack
148
46
            .back()
149
46
            .is_some_and(|op| op.seat_id == seat_id)
150
        {
151
23
            self.undo_stack.pop_back()
152
        } else {
153
23
            None
154
        }
155
46
    }
156

            
157
    /// Per-person redo: the counterpart of [`Self::pop_undo_for_seat`].
158
2
    pub fn pop_redo_for_seat(&mut self, seat_id: u64) -> Option<UndoableOperation> {
159
2
        if self
160
2
            .redo_stack
161
2
            .back()
162
2
            .is_some_and(|op| op.seat_id == seat_id)
163
        {
164
1
            self.redo_stack.pop_back()
165
        } else {
166
1
            None
167
        }
168
2
    }
169

            
170
    /// Push an operation to the redo stack (after undo)
171
72
    pub fn push_redo(&mut self, operation: UndoableOperation) {
172
72
        self.redo_stack.push_back(operation);
173

            
174
        // Limit stack size
175
72
        if self.redo_stack.len() > MAX_REDO_HISTORY {
176
13
            self.redo_stack.pop_front();
177
59
        }
178
72
    }
179

            
180
    /// Pop the most recent operation from redo stack
181
112
    pub fn pop_redo(&mut self) -> Option<UndoableOperation> {
182
112
        self.redo_stack.pop_back()
183
112
    }
184

            
185
    /// Check if undo is available
186
    #[must_use]
187
128
    pub fn can_undo(&self) -> bool {
188
128
        !self.undo_stack.is_empty()
189
128
    }
190

            
191
    /// Check if redo is available
192
    #[must_use]
193
117
    pub fn can_redo(&self) -> bool {
194
117
        !self.redo_stack.is_empty()
195
117
    }
196

            
197
    /// Peek at the most recent undo operation without removing it
198
    #[must_use]
199
23
    pub fn peek_undo(&self) -> Option<&UndoableOperation> {
200
23
        self.undo_stack.back()
201
23
    }
202

            
203
    /// Peek at the most recent redo operation without removing it
204
    #[must_use]
205
17
    pub fn peek_redo(&self) -> Option<&UndoableOperation> {
206
17
        self.redo_stack.back()
207
17
    }
208
}
209

            
210
/// MWA-C-undo_redo: styled-content snapshots for an operation.
211
///
212
/// Kept OUT of the FFI-exposed `UndoableOperation` (which crosses the C API
213
/// via `inspect_undo_operation`) and keyed by `TextChangeset.id`. Undo restores
214
/// `pre`, redo restores `post` — previously both rebuilt the text with
215
/// `StyleProperties::default()`, discarding all styling, and redo re-entered
216
/// the recording pipeline (double-recording + clearing the redo stack).
217
#[derive(Debug, Clone)]
218
pub struct ContentSnapshot {
219
    /// Full styled inline content BEFORE the operation
220
    pub pre: Vec<crate::text3::cache::InlineContent>,
221
    /// Full styled inline content AFTER the operation
222
    pub post: Vec<crate::text3::cache::InlineContent>,
223
}
224

            
225
/// Bound on the styled-snapshot side table (undo+redo stacks hold at most
226
/// 10+10 per node; 64 gives headroom across a handful of editable nodes —
227
/// lookup misses fall back to the plain-text restore).
228
const MAX_CONTENT_SNAPSHOTS: usize = 64;
229

            
230
/// A recorded STRUCTURAL edit (Enter split / merge / …) — the tree-shaped
231
/// undo entry.
232
///
233
/// Undoing never mutates: it re-RECORDS `inverse` as a fresh
234
/// `DocumentChangeset` through the same record→app-apply loop the original
235
/// edit took (`LayoutWindow::undo_structural_edit`).
236
#[derive(Debug, Clone)]
237
pub struct StructuralUndoEntry {
238
    /// The operation the app applied.
239
    pub op: super::changeset::DocumentOperation,
240
    /// The operation that undoes it (as returned by
241
    /// `document_edit::apply_document_operation` or supplied by the app).
242
    pub inverse: super::changeset::DocumentOperation,
243
    /// The resume point of the APPLIED edit (caret after redo).
244
    pub resume_after: super::changeset::EditResumePoint,
245
}
246

            
247
/// Maximum retained structural undo/redo entries (whole-document scope, so a
248
/// flat cap — not per-node like text).
249
pub const MAX_STRUCTURAL_HISTORY: usize = 64;
250

            
251
/// Manager for undo/redo operations across all text nodes
252
#[derive(Debug, Clone, Default)]
253
pub struct UndoRedoManager {
254
    /// Per-node undo/redo stacks
255
    /// Using Vec instead of `HashMap` for `no_std` compatibility
256
    pub node_stacks: Vec<NodeUndoRedoStack>,
257
    /// Styled-content snapshots keyed by `TextChangeset.id` (see
258
    /// [`ContentSnapshot`]); FIFO-capped at [`MAX_CONTENT_SNAPSHOTS`].
259
    pub content_snapshots: Vec<(super::changeset::ChangesetId, ContentSnapshot)>,
260
    /// Structural undo stack (most recent at back). Document-scoped: block
261
    /// splits/merges cross node boundaries, so per-node stacks cannot hold
262
    /// them.
263
    pub structural_undo: VecDeque<StructuralUndoEntry>,
264
    /// Structural redo stack (most recent at back).
265
    pub structural_redo: VecDeque<StructuralUndoEntry>,
266
}
267

            
268
impl UndoRedoManager {
269
    /// Push an APPLIED structural edit. Clears the redo stack (a fresh user
270
    /// edit invalidates redo, same rule as text).
271
96
    pub fn push_structural(&mut self, entry: StructuralUndoEntry) {
272
96
        self.structural_redo.clear();
273
96
        self.structural_undo.push_back(entry);
274
96
        if self.structural_undo.len() > MAX_STRUCTURAL_HISTORY {
275
10
            self.structural_undo.pop_front();
276
86
        }
277
96
    }
278

            
279
    /// Pop the newest structural edit for undoing; the caller re-records its
280
    /// `inverse` and must push the SWAPPED entry onto [`Self::structural_redo`]
281
    /// (see `redo_structural`).
282
22
    pub fn pop_structural_undo(&mut self) -> Option<StructuralUndoEntry> {
283
22
        self.structural_undo.pop_back()
284
22
    }
285

            
286
    /// Move an undone entry onto the redo stack (op/inverse roles swap at
287
    /// USE time, not storage time — the entry stays as recorded).
288
22
    pub fn push_structural_redo(&mut self, entry: StructuralUndoEntry) {
289
22
        self.structural_redo.push_back(entry);
290
22
        if self.structural_redo.len() > MAX_STRUCTURAL_HISTORY {
291
            self.structural_redo.pop_front();
292
22
        }
293
22
    }
294

            
295
    /// Pop the newest redoable structural edit; the caller re-records its
296
    /// `op` and pushes the entry back onto the undo stack WITHOUT clearing
297
    /// redo (`push_structural` would — a redo is not a fresh edit).
298
21
    pub fn pop_structural_redo(&mut self) -> Option<StructuralUndoEntry> {
299
21
        self.structural_redo.pop_back()
300
21
    }
301

            
302
    /// Re-push after a redo (bypasses the redo-clearing of `push_structural`).
303
21
    pub fn push_structural_undo_after_redo(&mut self, entry: StructuralUndoEntry) {
304
21
        self.structural_undo.push_back(entry);
305
21
        if self.structural_undo.len() > MAX_STRUCTURAL_HISTORY {
306
            self.structural_undo.pop_front();
307
21
        }
308
21
    }
309

            
310
    /// Create a new empty undo/redo manager
311
    #[must_use]
312
7608
    pub const fn new() -> Self {
313
7608
        Self {
314
7608
            node_stacks: Vec::new(),
315
7608
            content_snapshots: Vec::new(),
316
7608
            structural_undo: VecDeque::new(),
317
7608
            structural_redo: VecDeque::new(),
318
7608
        }
319
7608
    }
320

            
321
    /// Store the styled pre/post content for a changeset (see [`ContentSnapshot`]).
322
3690
    pub fn store_content_snapshot(
323
3690
        &mut self,
324
3690
        id: super::changeset::ChangesetId,
325
3690
        pre: Vec<crate::text3::cache::InlineContent>,
326
3690
        post: Vec<crate::text3::cache::InlineContent>,
327
3690
    ) {
328
3690
        self.content_snapshots
329
122256
            .retain(|(existing, _)| *existing != id);
330
3690
        self.content_snapshots
331
3690
            .push((id, ContentSnapshot { pre, post }));
332
3690
        if self.content_snapshots.len() > MAX_CONTENT_SNAPSHOTS {
333
1138
            self.content_snapshots.remove(0);
334
2928
        }
335
3690
    }
336

            
337
    /// Look up the styled snapshot for a changeset id.
338
    #[must_use]
339
22
    pub fn get_content_snapshot(
340
22
        &self,
341
22
        id: super::changeset::ChangesetId,
342
22
    ) -> Option<&ContentSnapshot> {
343
22
        self.content_snapshots
344
22
            .iter()
345
525
            .find(|(existing, _)| *existing == id)
346
22
            .map(|(_, snap)| snap)
347
22
    }
348

            
349
    /// MWA-C-undo_redo: put a redone operation back on the undo stack
350
    /// WITHOUT clearing the redo stack (see
351
    /// [`NodeUndoRedoStack::push_undo_preserving_redo`]).
352
    /// # Panics
353
    /// Panics if the operation's changeset target node is None.
354
14
    pub fn reinstate_undo(&mut self, operation: UndoableOperation) {
355
14
        let node_id = operation
356
14
            .changeset
357
14
            .target
358
14
            .node
359
14
            .into_crate_internal()
360
14
            .expect("TextChangeset target node should not be None");
361
14
        let stack = self.get_or_create_stack_mut(node_id);
362
14
        stack.push_undo_preserving_redo(operation);
363
14
    }
364

            
365
    /// Get or create a stack for a specific node
366
    /// # Panics
367
    ///
368
    /// Panics if the per-node stack list is unexpectedly empty after insertion.
369
3030
    pub fn get_or_create_stack_mut(&mut self, node_id: NodeId) -> &mut NodeUndoRedoStack {
370
3030
        if let Some(pos) = self.node_stacks.iter().position(|s| s.node_id == node_id) {
371
2436
            &mut self.node_stacks[pos]
372
        } else {
373
594
            self.node_stacks.push(NodeUndoRedoStack::new(node_id));
374
594
            self.node_stacks.last_mut().unwrap()
375
        }
376
3030
    }
377

            
378
    /// Get a stack for a specific node (immutable)
379
    #[must_use]
380
70
    pub fn get_stack(&self, node_id: NodeId) -> Option<&NodeUndoRedoStack> {
381
70
        self.node_stacks.iter().find(|s| s.node_id == node_id)
382
70
    }
383

            
384
    /// Get a stack for a specific node (mutable)
385
15
    fn get_stack_mut(&mut self, node_id: NodeId) -> Option<&mut NodeUndoRedoStack> {
386
15
        self.node_stacks.iter_mut().find(|s| s.node_id == node_id)
387
15
    }
388

            
389
    /// Record a text operation (push to undo stack)
390
    ///
391
    /// This should be called AFTER a changeset has been successfully applied.
392
    /// The `pre_state` should contain the node state BEFORE the changeset was applied.
393
    ///
394
    /// ## Arguments
395
    /// * `changeset` - The changeset that was applied
396
    /// * `pre_state` - Node state before the changeset
397
    /// # Panics
398
    ///
399
    /// Panics if the changeset's target node is None.
400
44
    pub fn record_operation(&mut self, changeset: TextChangeset, pre_state: NodeStateSnapshot) {
401
44
        self.record_operation_for_seat(
402
44
            changeset,
403
44
            pre_state,
404
            azul_core::window::PRIMARY_POINTER_SEAT,
405
        );
406
44
    }
407

            
408
    /// [`Self::record_operation`] attributed to a seat (9b-ii-a-i-d-ii-d).
409
2955
    pub fn record_operation_for_seat(
410
2955
        &mut self,
411
2955
        changeset: TextChangeset,
412
2955
        pre_state: NodeStateSnapshot,
413
2955
        seat_id: u64,
414
2955
    ) {
415
2955
        let node_id = changeset
416
2955
            .target
417
2955
            .node
418
2955
            .into_crate_internal()
419
2955
            .expect("TextChangeset target node should not be None");
420
2955
        let stack = self.get_or_create_stack_mut(node_id);
421

            
422
2955
        let operation = UndoableOperation {
423
2955
            changeset,
424
2955
            pre_state,
425
2955
            seat_id,
426
2955
        };
427

            
428
2955
        stack.push_undo(operation);
429
2955
    }
430

            
431
    /// Per-person undo on `node_id` (9b-ii-a-i-d-ii-d); see
432
    /// [`NodeUndoRedoStack::pop_undo_for_seat`].
433
40
    pub fn pop_undo_for_seat(
434
40
        &mut self,
435
40
        node_id: NodeId,
436
40
        seat_id: u64,
437
40
    ) -> Option<UndoableOperation> {
438
40
        self.get_or_create_stack_mut(node_id)
439
40
            .pop_undo_for_seat(seat_id)
440
40
    }
441

            
442
    /// Per-person redo on `node_id`.
443
    pub fn pop_redo_for_seat(
444
        &mut self,
445
        node_id: NodeId,
446
        seat_id: u64,
447
    ) -> Option<UndoableOperation> {
448
        self.get_or_create_stack_mut(node_id)
449
            .pop_redo_for_seat(seat_id)
450
    }
451

            
452
    /// Check if undo is available for a node
453
    #[must_use]
454
23
    pub fn can_undo(&self, node_id: NodeId) -> bool {
455
23
        self.get_stack(node_id)
456
23
            .is_some_and(NodeUndoRedoStack::can_undo)
457
23
    }
458

            
459
    /// Check if redo is available for a node
460
    #[must_use]
461
10
    pub fn can_redo(&self, node_id: NodeId) -> bool {
462
10
        self.get_stack(node_id)
463
10
            .is_some_and(NodeUndoRedoStack::can_redo)
464
10
    }
465

            
466
    /// Peek at the next undo operation for a node (without removing it)
467
    ///
468
    /// This allows user callbacks to inspect what would be undone.
469
    #[must_use]
470
13
    pub fn peek_undo(&self, node_id: NodeId) -> Option<&UndoableOperation> {
471
13
        self.get_stack(node_id).and_then(|s| s.peek_undo())
472
13
    }
473

            
474
    /// Peek at the next redo operation for a node (without removing it)
475
    ///
476
    /// This allows user callbacks to inspect what would be redone.
477
    #[must_use]
478
7
    pub fn peek_redo(&self, node_id: NodeId) -> Option<&UndoableOperation> {
479
7
        self.get_stack(node_id).and_then(|s| s.peek_redo())
480
7
    }
481

            
482
    /// Pop an operation from the undo stack
483
    ///
484
    /// This should be called during undo processing to get the operation to revert.
485
    /// After reverting, the operation should be pushed to the redo stack.
486
    ///
487
    /// ## Returns
488
    /// * `Some(operation)` - The operation to undo
489
    /// * `None` - No undo history available
490
9
    pub fn pop_undo(&mut self, node_id: NodeId) -> Option<UndoableOperation> {
491
9
        self.get_stack_mut(node_id)?.pop_undo()
492
9
    }
493

            
494
    /// Pop an operation from the redo stack
495
    ///
496
    /// This should be called during redo processing to get the operation to re-apply.
497
    /// After re-applying, the operation should be pushed to the undo stack.
498
    ///
499
    /// ## Returns
500
    /// * `Some(operation)` - The operation to redo
501
    /// * `None` - No redo history available
502
6
    pub fn pop_redo(&mut self, node_id: NodeId) -> Option<UndoableOperation> {
503
6
        self.get_stack_mut(node_id)?.pop_redo()
504
6
    }
505

            
506
    /// Push an operation to the redo stack (after successful undo)
507
    ///
508
    /// This should be called AFTER an undo operation has been successfully applied.
509
    /// # Panics
510
    ///
511
    /// Panics if the operation's changeset target node is None.
512
17
    pub fn push_redo(&mut self, operation: UndoableOperation) {
513
17
        let node_id = operation
514
17
            .changeset
515
17
            .target
516
17
            .node
517
17
            .into_crate_internal()
518
17
            .expect("TextChangeset target node should not be None");
519
17
        let stack = self.get_or_create_stack_mut(node_id);
520
17
        stack.push_redo(operation);
521
17
    }
522

            
523
    /// Push an operation to the undo stack (after successful redo)
524
    ///
525
    /// This should be called AFTER a redo operation has been successfully applied.
526
    /// # Panics
527
    ///
528
    /// Panics if the operation's changeset target node is None.
529
2
    pub fn push_undo(&mut self, operation: UndoableOperation) {
530
2
        let node_id = operation
531
2
            .changeset
532
2
            .target
533
2
            .node
534
2
            .into_crate_internal()
535
2
            .expect("TextChangeset target node should not be None");
536
2
        let stack = self.get_or_create_stack_mut(node_id);
537
2
        stack.push_undo(operation);
538
2
    }
539
}
540

            
541
impl crate::managers::NodeIdRemap for UndoRedoManager {
542
    /// Remap the per-node undo/redo stacks after a DOM rebuild.
543
    ///
544
    /// This is the worst offender of the "stale manager" family: the stacks are
545
    /// keyed by a bare `NodeId`, so deleting a PRECEDING SIBLING (which shifts
546
    /// every following index down by one) used to leave the whole undo history
547
    /// silently re-attached to a DIFFERENT, still-live element — undo would edit
548
    /// the wrong node, with no panic and no error.
549
    ///
550
    /// A stack is attributed to a DOM through the `DomNodeId` target of its
551
    /// operations (an empty stack carries no information and is treated as
552
    /// belonging to the DOM being reconciled). Stacks for unmounted nodes are
553
    /// dropped, and the content snapshots they referenced are GC'd with them.
554
457
    fn remap_node_ids(&mut self, dom: DomId, map: &crate::managers::NodeIdMap) {
555
457
        let old_stacks = core::mem::take(&mut self.node_stacks);
556

            
557
483
        for mut stack in old_stacks {
558
            // Which DOM does this stack belong to? Derived from its operations.
559
26
            let stack_dom = stack
560
26
                .undo_stack
561
26
                .front()
562
26
                .or_else(|| stack.redo_stack.front())
563
26
                .map(|op| op.changeset.target.dom);
564

            
565
26
            if stack_dom.is_some_and(|d| d != dom) {
566
                // Belongs to a different DOM — this reconciliation says nothing about it.
567
1
                self.node_stacks.push(stack);
568
1
                continue;
569
25
            }
570

            
571
25
            let Some(new_node_id) = map.resolve(stack.node_id) else {
572
                // Node unmounted — drop the whole history (GC). Keeping it would
573
                // re-attach this history to whichever node inherits the index.
574
8
                continue;
575
            };
576

            
577
17
            stack.node_id = new_node_id;
578
17
            for op in stack
579
17
                .undo_stack
580
17
                .iter_mut()
581
17
                .chain(stack.redo_stack.iter_mut())
582
17
            {
583
17
                remap_operation(op, dom, map, new_node_id);
584
17
            }
585
17
            self.node_stacks.push(stack);
586
        }
587

            
588
        // GC content snapshots whose changesets no longer exist in any stack.
589
457
        let live: alloc::collections::BTreeSet<_> = self
590
457
            .node_stacks
591
457
            .iter()
592
457
            .flat_map(|s| s.undo_stack.iter().chain(s.redo_stack.iter()))
593
457
            .map(|op| op.changeset.id)
594
457
            .collect();
595
457
        self.content_snapshots.retain(|(id, _)| live.contains(id));
596
457
    }
597
}
598

            
599
/// Rewrite the `NodeIds` embedded inside a single undoable operation.
600
23
fn remap_operation(
601
23
    op: &mut UndoableOperation,
602
23
    dom: DomId,
603
23
    map: &crate::managers::NodeIdMap,
604
23
    new_node_id: NodeId,
605
23
) {
606
    use azul_core::styled_dom::NodeHierarchyItemId;
607
23
    if op.changeset.target.dom == dom {
608
22
        op.changeset.target.node = NodeHierarchyItemId::from_crate_internal(Some(new_node_id));
609
22
    }
610
23
    if let Some(remapped) = map.resolve(op.pre_state.node_id) {
611
22
        op.pre_state.node_id = remapped;
612
22
    } else {
613
1
        // The snapshot's node vanished but the stack's node survived: keep the
614
1
        // stack coherent by pointing the snapshot at the (surviving) stack node.
615
1
        op.pre_state.node_id = new_node_id;
616
1
    }
617
23
}
618

            
619
#[cfg(test)]
620
mod undo_redo_tests {
621
    use azul_core::{
622
        dom::{DomId, DomNodeId},
623
        styled_dom::NodeHierarchyItemId,
624
        task::SystemTick,
625
        window::CursorPosition,
626
    };
627

            
628
    use super::*;
629
    use crate::managers::changeset::{TextChangeset, TextOpInsertText, TextOperation};
630

            
631
18
    fn ts() -> Instant {
632
18
        Instant::Tick(SystemTick { tick_counter: 0 })
633
18
    }
634

            
635
9
    fn op(id: usize, node: usize) -> UndoableOperation {
636
9
        UndoableOperation {
637
9
            changeset: TextChangeset {
638
9
                id,
639
9
                target: DomNodeId {
640
9
                    dom: DomId { inner: 0 },
641
9
                    node: NodeHierarchyItemId::from_crate_internal(Some(NodeId::new(node))),
642
9
                },
643
9
                operation: TextOperation::InsertText(TextOpInsertText {
644
9
                    text: "x".into(),
645
9
                    position: CursorPosition::Uninitialized,
646
9
                    new_cursor: CursorPosition::Uninitialized,
647
9
                }),
648
9
                timestamp: ts(),
649
9
            },
650
9
            pre_state: NodeStateSnapshot {
651
9
                node_id: NodeId::new(node),
652
9
                text_content: "".into(),
653
9
                cursor_position: None.into(),
654
9
                selection_range: None.into(),
655
9
                timestamp: ts(),
656
9
            },
657
9
            seat_id: 0,
658
9
        }
659
9
    }
660

            
661
    #[test]
662
1
    fn push_undo_clears_redo_but_reinstate_preserves_it() {
663
1
        let mut stack = NodeUndoRedoStack::new(NodeId::new(1));
664
1
        stack.push_redo(op(1, 1));
665
1
        stack.push_redo(op(2, 1));
666
1
        assert_eq!(stack.redo_stack.len(), 2);
667

            
668
        // Fresh user edit: redo history is invalidated.
669
1
        stack.push_undo(op(3, 1));
670
1
        assert_eq!(stack.redo_stack.len(), 0);
671

            
672
        // Redone operation moving back to undo: remaining redos survive.
673
1
        stack.push_redo(op(4, 1));
674
1
        stack.push_redo(op(5, 1));
675
1
        stack.push_undo_preserving_redo(op(6, 1));
676
1
        assert_eq!(stack.redo_stack.len(), 2);
677
1
        assert!(stack.can_undo());
678
1
    }
679

            
680
    #[test]
681
1
    fn content_snapshots_replace_lookup_and_evict() {
682
1
        let mut mgr = UndoRedoManager::new();
683
1
        mgr.store_content_snapshot(7, Vec::new(), Vec::new());
684
1
        assert!(mgr.get_content_snapshot(7).is_some());
685
1
        assert!(mgr.get_content_snapshot(8).is_none());
686

            
687
        // Same id replaces, no duplicate entries.
688
1
        mgr.store_content_snapshot(7, Vec::new(), Vec::new());
689
1
        assert_eq!(mgr.content_snapshots.len(), 1);
690

            
691
        // FIFO cap: oldest evicted once over MAX_CONTENT_SNAPSHOTS.
692
64
        for id in 100..(100 + MAX_CONTENT_SNAPSHOTS) {
693
64
            mgr.store_content_snapshot(id, Vec::new(), Vec::new());
694
64
        }
695
1
        assert!(mgr.content_snapshots.len() <= MAX_CONTENT_SNAPSHOTS);
696
1
        assert!(
697
1
            mgr.get_content_snapshot(7).is_none(),
698
            "oldest entry evicted"
699
        );
700
1
        assert!(mgr
701
1
            .get_content_snapshot(100 + MAX_CONTENT_SNAPSHOTS - 1)
702
1
            .is_some());
703
1
    }
704

            
705
    #[test]
706
1
    fn reinstate_undo_keeps_manager_redo_stack() {
707
1
        let mut mgr = UndoRedoManager::new();
708
1
        mgr.record_operation(op(1, 3).changeset, op(1, 3).pre_state);
709
1
        let popped = mgr.pop_undo(NodeId::new(3)).unwrap();
710
1
        mgr.push_redo(popped);
711
1
        let redone = mgr.pop_redo(NodeId::new(3)).unwrap();
712
        // Second redo entry that must survive the reinstate:
713
1
        mgr.push_redo(op(2, 3));
714
1
        mgr.reinstate_undo(redone);
715
1
        assert!(mgr.can_undo(NodeId::new(3)));
716
1
        assert!(mgr.can_redo(NodeId::new(3)), "redo stack preserved");
717
1
    }
718
}
719

            
720
#[cfg(test)]
721
mod structural_history_tests {
722
    use azul_core::{
723
        dom::{DomId, DomNodeId},
724
        selection::{CursorAffinity, GraphemeClusterId, TextCursor},
725
        styled_dom::NodeHierarchyItemId,
726
    };
727

            
728
    use super::*;
729
    use crate::managers::changeset::{
730
        DocOpRemoveChildren, DocOpSplitNode, DocumentOperation, EditResumePoint, NodePosition,
731
    };
732

            
733
76
    fn entry(tag: u32) -> StructuralUndoEntry {
734
76
        let node = DomNodeId {
735
76
            dom: DomId { inner: 0 },
736
76
            node: NodeHierarchyItemId::from_crate_internal(None),
737
76
        };
738
76
        StructuralUndoEntry {
739
76
            op: DocumentOperation::SplitNode(DocOpSplitNode {
740
76
                node,
741
76
                at: NodePosition::in_text_child(0, tag),
742
76
            }),
743
76
            inverse: DocumentOperation::RemoveChildren(DocOpRemoveChildren {
744
76
                parent: node,
745
76
                start: 0,
746
76
                end: 1,
747
76
            }),
748
76
            resume_after: EditResumePoint {
749
76
                anchor_key: u64::from(tag),
750
76
                node_path: vec![1].into(),
751
76
                position: NodePosition::before_child(0),
752
76
            },
753
76
        }
754
76
    }
755

            
756
    #[test]
757
1
    fn fresh_edit_clears_redo_but_redo_repush_does_not() {
758
1
        let mut m = UndoRedoManager::new();
759
1
        m.push_structural(entry(1));
760
1
        let undone = m.pop_structural_undo().expect("undo");
761
1
        m.push_structural_redo(undone);
762
1
        assert_eq!(m.structural_redo.len(), 1);
763

            
764
        // Redo: pop redo, re-push onto undo WITHOUT clearing redo.
765
1
        let redone = m.pop_structural_redo().expect("redo");
766
1
        m.push_structural_undo_after_redo(redone);
767
1
        assert_eq!(m.structural_undo.len(), 1);
768

            
769
        // A FRESH edit invalidates redo (the text rule):
770
1
        if let Some(e) = m.pop_structural_undo() {
771
1
            m.push_structural_redo(e)
772
        }
773
1
        assert_eq!(m.structural_redo.len(), 1);
774
1
        m.push_structural(entry(2));
775
1
        assert!(m.structural_redo.is_empty(), "fresh edit clears redo");
776
1
    }
777

            
778
    #[test]
779
1
    fn structural_history_is_capped() {
780
1
        let mut m = UndoRedoManager::new();
781
74
        for i in 0..(MAX_STRUCTURAL_HISTORY as u32 + 10) {
782
74
            m.push_structural(entry(i));
783
74
        }
784
1
        assert_eq!(m.structural_undo.len(), MAX_STRUCTURAL_HISTORY);
785
        // The OLDEST entries were dropped (FIFO at the front).
786
1
        let front = m.structural_undo.front().expect("front");
787
1
        assert_eq!(front.resume_after.anchor_key, 10);
788
1
    }
789
}
790

            
791
#[cfg(test)]
792
mod autotest_generated {
793
    use azul_core::{
794
        dom::DomNodeId,
795
        geom::LogicalPosition,
796
        selection::{CursorAffinity, GraphemeClusterId, TextCursor},
797
        styled_dom::NodeHierarchyItemId,
798
        task::SystemTick,
799
        window::CursorPosition,
800
    };
801

            
802
    use super::*;
803
    use crate::{
804
        managers::{
805
            changeset::{TextOpInsertText, TextOperation},
806
            NodeIdMap, NodeIdRemap,
807
        },
808
        text3::cache::{InlineContent, InlineSpace},
809
    };
810

            
811
    // ---------------------------------------------------------------------
812
    // helpers
813
    // ---------------------------------------------------------------------
814

            
815
    fn tick(t: u64) -> Instant {
816
        Instant::Tick(SystemTick { tick_counter: t })
817
    }
818

            
819
    fn cursor(run: u32, byte: u32) -> TextCursor {
820
        TextCursor {
821
            cluster_id: GraphemeClusterId {
822
                source_run: run,
823
                start_byte_in_run: byte,
824
            },
825
            affinity: CursorAffinity::Leading,
826
        }
827
    }
828

            
829
    /// Full operation with explicitly-chosen dom / node / changeset id / text.
830
    fn op_full(id: usize, dom: usize, node: usize, text: &str) -> UndoableOperation {
831
        UndoableOperation {
832
            changeset: TextChangeset {
833
                id,
834
                target: DomNodeId {
835
                    dom: DomId { inner: dom },
836
                    node: NodeHierarchyItemId::from_crate_internal(Some(NodeId::new(node))),
837
                },
838
                operation: TextOperation::InsertText(TextOpInsertText {
839
                    text: text.into(),
840
                    position: CursorPosition::Uninitialized,
841
                    new_cursor: CursorPosition::Uninitialized,
842
                }),
843
                timestamp: tick(u64::from(id as u32)),
844
            },
845
            pre_state: NodeStateSnapshot {
846
                node_id: NodeId::new(node),
847
                text_content: text.into(),
848
                cursor_position: Some(cursor(0, 0)).into(),
849
                selection_range: None.into(),
850
                timestamp: tick(u64::from(id as u32)),
851
            },
852
            seat_id: 0,
853
        }
854
    }
855

            
856
    /// Operation on DOM 0 (the common case).
857
    fn op(id: usize, node: usize) -> UndoableOperation {
858
        op_full(id, 0, node, "x")
859
    }
860

            
861
    /// Operation whose changeset target node is `None` — the input every
862
    /// `expect()` in this module is documented to panic on.
863
    fn op_with_none_target(id: usize) -> UndoableOperation {
864
        let mut o = op(id, 0);
865
        o.changeset.target.node = NodeHierarchyItemId::from_crate_internal(None);
866
        o
867
    }
868

            
869
    fn text_of(o: &UndoableOperation) -> &str {
870
        match &o.changeset.operation {
871
            TextOperation::InsertText(i) => i.text.as_str(),
872
            _ => panic!("helper only builds InsertText operations"),
873
        }
874
    }
875

            
876
    fn target_node(o: &UndoableOperation) -> Option<NodeId> {
877
        o.changeset.target.node.into_crate_internal()
878
    }
879

            
880
    fn space(width: f32) -> InlineContent {
881
        InlineContent::Space(InlineSpace {
882
            width,
883
            is_breaking: false,
884
            is_stretchy: false,
885
        })
886
    }
887

            
888
    fn space_width(c: &InlineContent) -> f32 {
889
        match c {
890
            InlineContent::Space(s) => s.width,
891
            _ => panic!("expected an InlineContent::Space"),
892
        }
893
    }
894

            
895
    fn one(c: InlineContent) -> Vec<InlineContent> {
896
        vec![c]
897
    }
898

            
899
    // ---------------------------------------------------------------------
900
    // NodeUndoRedoStack — constructor + invariants
901
    // ---------------------------------------------------------------------
902

            
903
    #[test]
904
    fn stack_new_holds_invariants_for_extreme_node_ids() {
905
        // NodeId::ZERO, a normal id, and the largest id that still survives the
906
        // 1-based FFI encoding (`usize::MAX` would overflow `into_raw`).
907
        for node in [0usize, 7, usize::MAX - 1] {
908
            let s = NodeUndoRedoStack::new(NodeId::new(node));
909
            assert_eq!(s.node_id.index(), node);
910
            assert!(s.undo_stack.is_empty());
911
            assert!(s.redo_stack.is_empty());
912
            assert!(!s.can_undo());
913
            assert!(!s.can_redo());
914
            assert!(s.peek_undo().is_none());
915
            assert!(s.peek_redo().is_none());
916
            assert!(s.undo_stack.capacity() >= MAX_UNDO_HISTORY);
917
            assert!(s.redo_stack.capacity() >= MAX_REDO_HISTORY);
918
        }
919
    }
920

            
921
    #[test]
922
    fn stack_draining_an_empty_stack_never_panics() {
923
        let mut s = NodeUndoRedoStack::new(NodeId::new(0));
924
        for _ in 0..100 {
925
            assert!(s.pop_undo().is_none());
926
            assert!(s.pop_redo().is_none());
927
            assert!(!s.can_undo());
928
            assert!(!s.can_redo());
929
        }
930
    }
931

            
932
    // ---------------------------------------------------------------------
933
    // NodeUndoRedoStack — bounded history (saturation, not growth)
934
    // ---------------------------------------------------------------------
935

            
936
    #[test]
937
    fn undo_stack_saturates_at_max_history_and_evicts_oldest() {
938
        let mut s = NodeUndoRedoStack::new(NodeId::new(1));
939
        let total = MAX_UNDO_HISTORY * 3 + 7;
940
        for id in 0..total {
941
            s.push_undo(op(id, 1));
942
        }
943
        assert_eq!(s.undo_stack.len(), MAX_UNDO_HISTORY, "history is bounded");
944
        // FIFO eviction: the surviving window is the LAST MAX_UNDO_HISTORY pushes.
945
        assert_eq!(
946
            s.undo_stack.front().unwrap().changeset.id,
947
            total - MAX_UNDO_HISTORY
948
        );
949
        assert_eq!(s.peek_undo().unwrap().changeset.id, total - 1);
950
    }
951

            
952
    #[test]
953
    fn redo_stack_saturates_at_max_history_and_evicts_oldest() {
954
        let mut s = NodeUndoRedoStack::new(NodeId::new(1));
955
        let total = MAX_REDO_HISTORY * 2 + 3;
956
        for id in 0..total {
957
            s.push_redo(op(id, 1));
958
        }
959
        assert_eq!(s.redo_stack.len(), MAX_REDO_HISTORY);
960
        assert_eq!(
961
            s.redo_stack.front().unwrap().changeset.id,
962
            total - MAX_REDO_HISTORY
963
        );
964
        assert_eq!(s.peek_redo().unwrap().changeset.id, total - 1);
965
    }
966

            
967
    #[test]
968
    fn push_undo_preserving_redo_is_bounded_too_and_leaves_redo_alone() {
969
        let mut s = NodeUndoRedoStack::new(NodeId::new(1));
970
        for id in 0..MAX_REDO_HISTORY {
971
            s.push_redo(op(id, 1));
972
        }
973
        for id in 1000..(1000 + MAX_UNDO_HISTORY * 4) {
974
            s.push_undo_preserving_redo(op(id, 1));
975
        }
976
        assert_eq!(s.undo_stack.len(), MAX_UNDO_HISTORY);
977
        assert_eq!(
978
            s.redo_stack.len(),
979
            MAX_REDO_HISTORY,
980
            "preserving variant must not touch the redo stack"
981
        );
982
        assert_eq!(s.peek_redo().unwrap().changeset.id, MAX_REDO_HISTORY - 1);
983
    }
984

            
985
    #[test]
986
    fn push_undo_clears_a_full_redo_stack() {
987
        let mut s = NodeUndoRedoStack::new(NodeId::new(1));
988
        for id in 0..MAX_REDO_HISTORY {
989
            s.push_redo(op(id, 1));
990
        }
991
        assert!(s.can_redo());
992
        s.push_undo(op(999, 1));
993
        assert!(
994
            !s.can_redo(),
995
            "a fresh edit invalidates the whole redo branch"
996
        );
997
        assert!(s.redo_stack.is_empty());
998
        assert!(s.peek_redo().is_none());
999
        assert!(s.can_undo());
    }
    // ---------------------------------------------------------------------
    // NodeUndoRedoStack — LIFO ordering + peek is non-destructive
    // ---------------------------------------------------------------------
    #[test]
    fn pop_undo_and_pop_redo_are_lifo_then_drain_to_none() {
        let mut s = NodeUndoRedoStack::new(NodeId::new(2));
        for id in 0..5 {
            s.push_undo(op(id, 2));
        }
        for expected in (0..5).rev() {
            assert_eq!(s.pop_undo().unwrap().changeset.id, expected);
        }
        assert!(s.pop_undo().is_none());
        for id in 0..5 {
            s.push_redo(op(id, 2));
        }
        for expected in (0..5).rev() {
            assert_eq!(s.pop_redo().unwrap().changeset.id, expected);
        }
        assert!(s.pop_redo().is_none());
    }
    #[test]
    fn peek_is_non_destructive_and_agrees_with_pop() {
        let mut s = NodeUndoRedoStack::new(NodeId::new(2));
        s.push_undo(op(1, 2));
        s.push_undo(op(2, 2));
        s.push_redo(op(3, 2));
        for _ in 0..10 {
            assert_eq!(s.peek_undo().unwrap().changeset.id, 2);
            assert_eq!(s.peek_redo().unwrap().changeset.id, 3);
        }
        assert_eq!(s.undo_stack.len(), 2, "peek must not consume");
        assert_eq!(s.redo_stack.len(), 1);
        assert_eq!(s.pop_undo().unwrap().changeset.id, 2, "peek == next pop");
        assert_eq!(s.pop_redo().unwrap().changeset.id, 3);
    }
    #[test]
    fn can_undo_can_redo_track_emptiness_exactly() {
        let mut s = NodeUndoRedoStack::new(NodeId::new(2));
        assert!(!s.can_undo() && !s.can_redo());
        s.push_undo(op(1, 2));
        assert!(s.can_undo() && !s.can_redo());
        assert_eq!(s.can_undo(), !s.undo_stack.is_empty());
        s.push_redo(op(2, 2));
        assert!(s.can_undo() && s.can_redo());
        assert!(s.pop_undo().is_some());
        assert!(!s.can_undo() && s.can_redo());
        assert!(s.pop_redo().is_some());
        assert!(!s.can_undo() && !s.can_redo());
    }
    // ---------------------------------------------------------------------
    // Round-trip: what goes onto a stack comes back off byte-identical
    // ---------------------------------------------------------------------
    #[test]
    fn undo_redo_round_trip_preserves_unicode_payload_exactly() {
        // Combining mark, ZWJ emoji sequence, RTL override, astral plane, and a
        // NUL byte in the middle — none of which the stacks may normalize.
        let nasty = "a\u{0301}👩\u{200D}👩\u{200D}👧\u{202E}rtl\u{0000}end\u{FFFD}";
        let mut s = NodeUndoRedoStack::new(NodeId::new(4));
        s.push_undo(op_full(usize::MAX, 0, 4, nasty));
        let undone = s.pop_undo().unwrap();
        assert_eq!(text_of(&undone), nasty);
        assert_eq!(undone.pre_state.text_content.as_str(), nasty);
        assert_eq!(undone.changeset.id, usize::MAX, "ChangesetId::MAX survives");
        s.push_redo(undone);
        let redone = s.pop_redo().unwrap();
        assert_eq!(text_of(&redone), nasty, "encode == decode across undo→redo");
        assert_eq!(redone.pre_state.text_content.as_str(), nasty);
        assert_eq!(target_node(&redone), Some(NodeId::new(4)));
        assert_eq!(redone.pre_state.node_id, NodeId::new(4));
    }
    #[test]
    fn round_trip_preserves_huge_text_and_extreme_timestamps() {
        let huge: AzString = "é".repeat(50_000).into();
        assert_eq!(huge.as_str().len(), 100_000, "2 bytes per 'é'");
        let mut o = op(1, 6);
        o.pre_state.text_content = huge.clone();
        o.pre_state.timestamp = tick(u64::MAX);
        o.changeset.timestamp = tick(u64::MAX);
        let mut s = NodeUndoRedoStack::new(NodeId::new(6));
        s.push_undo(o);
        let back = s.pop_undo().unwrap();
        assert_eq!(back.pre_state.text_content.as_str().len(), 100_000);
        assert_eq!(back.pre_state.text_content.as_str(), huge.as_str());
        match back.pre_state.timestamp {
            Instant::Tick(t) => assert_eq!(t.tick_counter, u64::MAX, "u64::MAX tick unclamped"),
            Instant::System(_) => panic!("helper builds Tick instants"),
        }
    }
    #[test]
    fn round_trip_preserves_nan_and_infinite_cursor_coordinates() {
        let mut o = op(1, 6);
        o.changeset.operation = TextOperation::InsertText(TextOpInsertText {
            text: "q".into(),
            position: CursorPosition::InWindow(LogicalPosition {
                x: f32::NAN,
                y: f32::NEG_INFINITY,
            }),
            new_cursor: CursorPosition::OutOfWindow(LogicalPosition {
                x: f32::INFINITY,
                y: -0.0,
            }),
        });
        let mut s = NodeUndoRedoStack::new(NodeId::new(6));
        s.push_undo(o);
        let back = s.pop_undo().unwrap();
        match back.changeset.operation {
            TextOperation::InsertText(i) => {
                match i.position {
                    CursorPosition::InWindow(p) => {
                        assert!(p.x.is_nan(), "NaN must not be normalized away");
                        assert_eq!(p.y, f32::NEG_INFINITY);
                    }
                    _ => panic!("position variant changed across the stack"),
                }
                match i.new_cursor {
                    CursorPosition::OutOfWindow(p) => {
                        assert_eq!(p.x, f32::INFINITY);
                        assert!(
                            p.y.is_sign_negative(),
                            "-0.0 must keep its sign bit through the stack"
                        );
                    }
                    _ => panic!("new_cursor variant changed across the stack"),
                }
            }
            _ => panic!("operation variant changed across the stack"),
        }
    }
    // ---------------------------------------------------------------------
    // UndoRedoManager — constructor + queries on unknown nodes
    // ---------------------------------------------------------------------
    #[test]
    fn manager_new_and_default_are_empty_and_agree() {
        let a = UndoRedoManager::new();
        let b = UndoRedoManager::default();
        for mgr in [&a, &b] {
            assert!(mgr.node_stacks.is_empty());
            assert!(mgr.content_snapshots.is_empty());
        }
        for node in [0usize, 1, usize::MAX - 1] {
            assert!(!a.can_undo(NodeId::new(node)));
            assert!(!a.can_redo(NodeId::new(node)));
            assert!(a.get_stack(NodeId::new(node)).is_none());
            assert!(a.peek_undo(NodeId::new(node)).is_none());
            assert!(a.peek_redo(NodeId::new(node)).is_none());
        }
        assert!(a.get_content_snapshot(0).is_none());
        assert!(a.get_content_snapshot(usize::MAX).is_none());
    }
    #[test]
    fn manager_queries_on_unknown_node_return_none_without_allocating_a_stack() {
        let mut mgr = UndoRedoManager::new();
        for node in [0usize, 42, usize::MAX - 1] {
            assert!(mgr.pop_undo(NodeId::new(node)).is_none());
            assert!(mgr.pop_redo(NodeId::new(node)).is_none());
        }
        assert!(
            mgr.node_stacks.is_empty(),
            "read/pop paths must not silently create per-node stacks"
        );
    }
    #[test]
    fn get_or_create_stack_mut_is_idempotent_and_mutations_persist() {
        let mut mgr = UndoRedoManager::new();
        let boundary = NodeId::new(usize::MAX - 1);
        mgr.get_or_create_stack_mut(NodeId::new(3))
            .push_undo(op(1, 3));
        // Second call for the same node must reuse, not duplicate.
        mgr.get_or_create_stack_mut(NodeId::new(3))
            .push_undo(op(2, 3));
        assert_eq!(mgr.node_stacks.len(), 1);
        assert_eq!(mgr.get_stack(NodeId::new(3)).unwrap().undo_stack.len(), 2);
        mgr.get_or_create_stack_mut(boundary).push_undo(op(3, 0));
        assert_eq!(mgr.node_stacks.len(), 2);
        assert_eq!(mgr.get_or_create_stack_mut(boundary).node_id, boundary);
        assert_eq!(mgr.node_stacks.len(), 2, "no duplicate for the boundary id");
        assert!(mgr.can_undo(boundary));
    }
    // ---------------------------------------------------------------------
    // UndoRedoManager — recording, per-node isolation, bounds
    // ---------------------------------------------------------------------
    #[test]
    fn record_operation_is_bounded_and_isolated_per_node() {
        let mut mgr = UndoRedoManager::new();
        for id in 0..(MAX_UNDO_HISTORY * 2 + 5) {
            let o = op(id, 1);
            mgr.record_operation(o.changeset, o.pre_state);
        }
        for id in 500..503 {
            let o = op(id, 2);
            mgr.record_operation(o.changeset, o.pre_state);
        }
        assert_eq!(mgr.node_stacks.len(), 2);
        assert_eq!(
            mgr.get_stack(NodeId::new(1)).unwrap().undo_stack.len(),
            MAX_UNDO_HISTORY
        );
        assert_eq!(mgr.get_stack(NodeId::new(2)).unwrap().undo_stack.len(), 3);
        // Draining node 2 must leave node 1 untouched.
        while mgr.pop_undo(NodeId::new(2)).is_some() {}
        assert!(!mgr.can_undo(NodeId::new(2)));
        assert!(mgr.can_undo(NodeId::new(1)));
        assert_eq!(
            mgr.peek_undo(NodeId::new(1)).unwrap().changeset.id,
            MAX_UNDO_HISTORY * 2 + 4
        );
    }
    #[test]
    fn manager_push_undo_clears_only_the_target_nodes_redo_stack() {
        let mut mgr = UndoRedoManager::new();
        mgr.push_redo(op(1, 1));
        mgr.push_redo(op(2, 2));
        assert!(mgr.can_redo(NodeId::new(1)) && mgr.can_redo(NodeId::new(2)));
        mgr.push_undo(op(3, 1));
        assert!(
            !mgr.can_redo(NodeId::new(1)),
            "fresh edit drops node 1's redo branch"
        );
        assert!(
            mgr.can_redo(NodeId::new(2)),
            "node 2 is an independent history"
        );
    }
    #[test]
    fn full_undo_then_redo_cycle_returns_the_same_operation() {
        let mut mgr = UndoRedoManager::new();
        let original = op_full(11, 0, 5, "hello");
        mgr.record_operation(original.changeset.clone(), original.pre_state.clone());
        // Undo: pop from undo, push to redo.
        let undone = mgr.pop_undo(NodeId::new(5)).unwrap();
        assert_eq!(undone.changeset.id, 11);
        mgr.push_redo(undone);
        assert!(!mgr.can_undo(NodeId::new(5)));
        assert!(mgr.can_redo(NodeId::new(5)));
        // Redo: pop from redo, reinstate onto undo.
        let redone = mgr.pop_redo(NodeId::new(5)).unwrap();
        assert_eq!(text_of(&redone), "hello", "payload survives undo→redo");
        mgr.reinstate_undo(redone);
        assert!(mgr.can_undo(NodeId::new(5)));
        assert!(!mgr.can_redo(NodeId::new(5)));
        assert_eq!(mgr.peek_undo(NodeId::new(5)).unwrap().changeset.id, 11);
    }
    #[test]
    fn reinstate_undo_preserves_a_full_redo_stack() {
        let mut mgr = UndoRedoManager::new();
        for id in 0..MAX_REDO_HISTORY {
            mgr.push_redo(op(id, 9));
        }
        let redone = mgr.pop_redo(NodeId::new(9)).unwrap();
        mgr.reinstate_undo(redone);
        assert_eq!(
            mgr.get_stack(NodeId::new(9)).unwrap().redo_stack.len(),
            MAX_REDO_HISTORY - 1,
            "reinstating one redo must not wipe the remaining redo branch"
        );
        assert!(mgr.can_undo(NodeId::new(9)));
    }
    // ---------------------------------------------------------------------
    // UndoRedoManager — documented panics on a None changeset target
    // ---------------------------------------------------------------------
    #[test]
    #[should_panic(expected = "TextChangeset target node should not be None")]
    fn record_operation_panics_on_none_target() {
        let mut mgr = UndoRedoManager::new();
        let o = op_with_none_target(1);
        mgr.record_operation(o.changeset, o.pre_state);
    }
    #[test]
    #[should_panic(expected = "TextChangeset target node should not be None")]
    fn manager_push_undo_panics_on_none_target() {
        UndoRedoManager::new().push_undo(op_with_none_target(1));
    }
    #[test]
    #[should_panic(expected = "TextChangeset target node should not be None")]
    fn manager_push_redo_panics_on_none_target() {
        UndoRedoManager::new().push_redo(op_with_none_target(1));
    }
    #[test]
    #[should_panic(expected = "TextChangeset target node should not be None")]
    fn reinstate_undo_panics_on_none_target() {
        UndoRedoManager::new().reinstate_undo(op_with_none_target(1));
    }
    // ---------------------------------------------------------------------
    // Content snapshots — lookup, replacement, FIFO cap, float payloads
    // ---------------------------------------------------------------------
    #[test]
    fn content_snapshot_does_not_swap_pre_and_post() {
        let mut mgr = UndoRedoManager::new();
        mgr.store_content_snapshot(3, one(space(1.0)), one(space(2.0)));
        let snap = mgr
            .get_content_snapshot(3)
            .expect("stored id must be found");
        assert_eq!(space_width(&snap.pre[0]), 1.0, "pre must stay pre");
        assert_eq!(space_width(&snap.post[0]), 2.0, "post must stay post");
    }
    #[test]
    fn content_snapshot_preserves_nan_and_infinite_widths() {
        let mut mgr = UndoRedoManager::new();
        mgr.store_content_snapshot(1, one(space(f32::NAN)), one(space(f32::INFINITY)));
        let snap = mgr.get_content_snapshot(1).unwrap();
        assert!(space_width(&snap.pre[0]).is_nan(), "NaN width round-trips");
        assert_eq!(space_width(&snap.post[0]), f32::INFINITY);
    }
    #[test]
    fn content_snapshot_boundary_ids_and_misses() {
        let mut mgr = UndoRedoManager::new();
        mgr.store_content_snapshot(0, Vec::new(), Vec::new());
        mgr.store_content_snapshot(usize::MAX, one(space(0.0)), Vec::new());
        assert!(
            mgr.get_content_snapshot(0).is_some(),
            "id 0 is a real key, not a sentinel"
        );
        assert!(mgr.get_content_snapshot(usize::MAX).is_some());
        assert!(mgr.get_content_snapshot(1).is_none());
        assert!(mgr.get_content_snapshot(usize::MAX - 1).is_none());
        assert_eq!(mgr.content_snapshots.len(), 2);
    }
    #[test]
    fn storing_the_same_id_replaces_the_entry_and_refreshes_its_recency() {
        let mut mgr = UndoRedoManager::new();
        for id in 0..MAX_CONTENT_SNAPSHOTS {
            mgr.store_content_snapshot(id, one(space(0.0)), Vec::new());
        }
        assert_eq!(mgr.content_snapshots.len(), MAX_CONTENT_SNAPSHOTS);
        // Re-store the OLDEST id with a new payload: it is replaced (no duplicate)
        // and moves to the back of the FIFO.
        mgr.store_content_snapshot(0, one(space(42.0)), Vec::new());
        assert_eq!(
            mgr.content_snapshots.len(),
            MAX_CONTENT_SNAPSHOTS,
            "no duplicate key"
        );
        assert_eq!(
            space_width(&mgr.get_content_snapshot(0).unwrap().pre[0]),
            42.0
        );
        // One more insert evicts id 1 (now the oldest), NOT the refreshed id 0.
        mgr.store_content_snapshot(9_999, Vec::new(), Vec::new());
        assert_eq!(
            mgr.content_snapshots.len(),
            MAX_CONTENT_SNAPSHOTS,
            "cap holds"
        );
        assert!(
            mgr.get_content_snapshot(0).is_some(),
            "refreshed entry survived"
        );
        assert!(
            mgr.get_content_snapshot(1).is_none(),
            "second-oldest evicted"
        );
        assert!(mgr.get_content_snapshot(9_999).is_some());
    }
    #[test]
    fn content_snapshot_table_never_exceeds_its_cap_under_heavy_churn() {
        let mut mgr = UndoRedoManager::new();
        for id in 0..(MAX_CONTENT_SNAPSHOTS * 10) {
            mgr.store_content_snapshot(id, one(space(id as f32)), one(space(0.0)));
            assert!(mgr.content_snapshots.len() <= MAX_CONTENT_SNAPSHOTS);
        }
        assert_eq!(mgr.content_snapshots.len(), MAX_CONTENT_SNAPSHOTS);
        // The surviving window is the newest MAX_CONTENT_SNAPSHOTS ids.
        let newest = MAX_CONTENT_SNAPSHOTS * 10 - 1;
        assert!(mgr.get_content_snapshot(newest).is_some());
        assert!(mgr
            .get_content_snapshot(newest - MAX_CONTENT_SNAPSHOTS)
            .is_none());
    }
    // ---------------------------------------------------------------------
    // remap_node_ids — the stale-manager failure mode
    // ---------------------------------------------------------------------
    #[test]
    fn remap_shifts_stack_and_every_embedded_node_id() {
        let mut mgr = UndoRedoManager::new();
        let o = op_full(1, 0, 3, "a");
        mgr.record_operation(o.changeset, o.pre_state);
        mgr.push_redo(op_full(2, 0, 3, "b"));
        mgr.store_content_snapshot(1, one(space(1.0)), Vec::new());
        // Preceding sibling deleted: node 3 becomes node 2.
        let map = NodeIdMap::from_pairs([(NodeId::new(3), NodeId::new(2))]);
        mgr.remap_node_ids(DomId { inner: 0 }, &map);
        assert!(
            mgr.get_stack(NodeId::new(3)).is_none(),
            "old key must be gone"
        );
        let stack = mgr
            .get_stack(NodeId::new(2))
            .expect("stack re-keyed to the new id");
        assert_eq!(stack.node_id, NodeId::new(2));
        let undo = stack.peek_undo().unwrap();
        assert_eq!(
            target_node(undo),
            Some(NodeId::new(2)),
            "changeset target remapped"
        );
        assert_eq!(
            undo.pre_state.node_id,
            NodeId::new(2),
            "snapshot node remapped"
        );
        let redo = stack.peek_redo().unwrap();
        assert_eq!(
            target_node(redo),
            Some(NodeId::new(2)),
            "redo stack remapped too"
        );
        assert_eq!(redo.pre_state.node_id, NodeId::new(2));
        assert!(
            mgr.get_content_snapshot(1).is_some(),
            "snapshot of a still-live changeset must survive the GC"
        );
    }
    #[test]
    fn remap_drops_unmounted_history_and_gcs_its_snapshots() {
        let mut mgr = UndoRedoManager::new();
        let o = op_full(1, 0, 3, "a");
        mgr.record_operation(o.changeset, o.pre_state);
        mgr.store_content_snapshot(1, one(space(1.0)), Vec::new());
        // Node 3 is not in the map → it was unmounted.
        let map = NodeIdMap::from_pairs([(NodeId::new(0), NodeId::new(0))]);
        mgr.remap_node_ids(DomId { inner: 0 }, &map);
        assert!(
            mgr.node_stacks.is_empty(),
            "history of an unmounted node is dropped"
        );
        assert!(!mgr.can_undo(NodeId::new(3)));
        assert!(
            !mgr.can_undo(NodeId::new(2)),
            "history must NOT re-attach to a neighbour"
        );
        assert!(
            mgr.content_snapshots.is_empty(),
            "snapshots of dropped changesets are GC'd"
        );
    }
    #[test]
    fn remap_leaves_stacks_belonging_to_another_dom_untouched() {
        let mut mgr = UndoRedoManager::new();
        // Stack on node 3 of DOM 1 (a *different* DOM from the one being rebuilt).
        let o = op_full(1, 1, 3, "a");
        mgr.record_operation(o.changeset, o.pre_state);
        mgr.store_content_snapshot(1, one(space(1.0)), Vec::new());
        let map = NodeIdMap::from_pairs([(NodeId::new(3), NodeId::new(2))]);
        mgr.remap_node_ids(DomId { inner: 0 }, &map);
        let stack = mgr
            .get_stack(NodeId::new(3))
            .expect("a foreign DOM's stack keeps its key");
        assert_eq!(stack.node_id, NodeId::new(3));
        let undo = stack.peek_undo().unwrap();
        assert_eq!(
            target_node(undo),
            Some(NodeId::new(3)),
            "foreign target untouched"
        );
        assert_eq!(undo.changeset.target.dom, DomId { inner: 1 });
        assert_eq!(undo.pre_state.node_id, NodeId::new(3));
        assert!(mgr.get_content_snapshot(1).is_some());
    }
    #[test]
    fn remap_of_an_empty_stack_follows_the_map_or_drops_it() {
        // An empty stack carries no DOM evidence, so it is treated as belonging to
        // the DOM being reconciled: mapped → re-keyed, unmapped → dropped.
        let mut mapped = UndoRedoManager::new();
        mapped.get_or_create_stack_mut(NodeId::new(7));
        mapped.remap_node_ids(
            DomId { inner: 0 },
            &NodeIdMap::from_pairs([(NodeId::new(7), NodeId::new(9))]),
        );
        assert!(mapped.get_stack(NodeId::new(9)).is_some());
        assert!(mapped.get_stack(NodeId::new(7)).is_none());
        let mut dropped = UndoRedoManager::new();
        dropped.get_or_create_stack_mut(NodeId::new(7));
        dropped.remap_node_ids(DomId { inner: 0 }, &NodeIdMap::from_pairs([]));
        assert!(dropped.node_stacks.is_empty());
    }
    #[test]
    fn remap_with_an_empty_map_drops_every_stack_of_that_dom() {
        let mut mgr = UndoRedoManager::new();
        for node in 0..5 {
            let o = op_full(node, 0, node, "a");
            mgr.record_operation(o.changeset, o.pre_state);
        }
        assert_eq!(mgr.node_stacks.len(), 5);
        mgr.remap_node_ids(DomId { inner: 0 }, &NodeIdMap::from_pairs([]));
        assert!(mgr.node_stacks.is_empty(), "nothing survived the rebuild");
        assert!(mgr.content_snapshots.is_empty());
    }
    #[test]
    fn remap_is_idempotent_when_the_map_is_the_identity() {
        let mut mgr = UndoRedoManager::new();
        let o = op_full(1, 0, 3, "a");
        mgr.record_operation(o.changeset, o.pre_state);
        let identity = NodeIdMap::from_pairs([(NodeId::new(3), NodeId::new(3))]);
        for _ in 0..3 {
            mgr.remap_node_ids(DomId { inner: 0 }, &identity);
        }
        assert_eq!(mgr.node_stacks.len(), 1);
        let stack = mgr.get_stack(NodeId::new(3)).unwrap();
        assert_eq!(
            stack.undo_stack.len(),
            1,
            "repeated remaps must not duplicate ops"
        );
        assert_eq!(
            target_node(stack.peek_undo().unwrap()),
            Some(NodeId::new(3))
        );
    }
    #[test]
    fn remap_gcs_a_snapshot_whose_changeset_was_never_recorded() {
        // A snapshot stored for an operation that never made it onto a stack is
        // collected by the very next remap — documented GC behaviour, pinned here
        // so a future change to the GC predicate is a visible test failure.
        let mut mgr = UndoRedoManager::new();
        mgr.store_content_snapshot(77, one(space(1.0)), Vec::new());
        assert!(mgr.get_content_snapshot(77).is_some());
        mgr.remap_node_ids(DomId { inner: 0 }, &NodeIdMap::from_pairs([]));
        assert!(mgr.get_content_snapshot(77).is_none());
    }
    // ---------------------------------------------------------------------
    // remap_operation (private) — direct unit tests
    // ---------------------------------------------------------------------
    #[test]
    fn remap_operation_rewrites_target_and_snapshot_for_the_matching_dom() {
        let mut o = op_full(1, 0, 3, "a");
        let map = NodeIdMap::from_pairs([(NodeId::new(3), NodeId::new(2))]);
        remap_operation(&mut o, DomId { inner: 0 }, &map, NodeId::new(2));
        assert_eq!(target_node(&o), Some(NodeId::new(2)));
        assert_eq!(o.pre_state.node_id, NodeId::new(2));
    }
    #[test]
    fn remap_operation_leaves_a_foreign_doms_target_alone() {
        let mut o = op_full(1, 1, 3, "a");
        let map = NodeIdMap::from_pairs([(NodeId::new(3), NodeId::new(2))]);
        remap_operation(&mut o, DomId { inner: 0 }, &map, NodeId::new(2));
        assert_eq!(
            target_node(&o),
            Some(NodeId::new(3)),
            "target in DOM 1 must not be rewritten by a DOM 0 reconciliation"
        );
        assert_eq!(o.changeset.target.dom, DomId { inner: 1 });
        // The bare pre_state NodeId has no DOM tag, so it still follows the map.
        assert_eq!(o.pre_state.node_id, NodeId::new(2));
    }
    #[test]
    fn remap_operation_falls_back_to_the_stack_node_for_a_vanished_snapshot() {
        let mut o = op_full(1, 0, 3, "a");
        o.pre_state.node_id = NodeId::new(88); // snapshot node not in the map
        let map = NodeIdMap::from_pairs([(NodeId::new(3), NodeId::new(2))]);
        remap_operation(&mut o, DomId { inner: 0 }, &map, NodeId::new(2));
        assert_eq!(target_node(&o), Some(NodeId::new(2)));
        assert_eq!(
            o.pre_state.node_id,
            NodeId::new(2),
            "unresolvable snapshot node is pinned to the surviving stack node"
        );
    }
    #[test]
    fn remap_operation_handles_the_largest_encodable_node_id() {
        // NodeId(usize::MAX - 1) is the largest id the 1-based FFI encoding can
        // hold (`into_raw` computes n + 1); it must survive a remap round-trip.
        let boundary = NodeId::new(usize::MAX - 1);
        let mut o = op_full(1, 0, 3, "a");
        let map = NodeIdMap::from_pairs([(NodeId::new(3), boundary)]);
        remap_operation(&mut o, DomId { inner: 0 }, &map, boundary);
        assert_eq!(
            target_node(&o),
            Some(boundary),
            "encode/decode is lossless at the boundary"
        );
        assert_eq!(o.pre_state.node_id, boundary);
        assert_eq!(target_node(&o).unwrap().index(), usize::MAX - 1);
    }
    #[test]
    fn remap_operation_is_idempotent() {
        let mut o = op_full(1, 0, 3, "a");
        let map = NodeIdMap::from_pairs([
            (NodeId::new(3), NodeId::new(2)),
            (NodeId::new(2), NodeId::new(2)),
        ]);
        remap_operation(&mut o, DomId { inner: 0 }, &map, NodeId::new(2));
        remap_operation(&mut o, DomId { inner: 0 }, &map, NodeId::new(2));
        assert_eq!(target_node(&o), Some(NodeId::new(2)), "no double-shift");
        assert_eq!(o.pre_state.node_id, NodeId::new(2));
    }
}
#[cfg(test)]
mod seat_attribution_tests {
    use azul_core::{
        dom::{DomId, DomNodeId},
        styled_dom::NodeHierarchyItemId,
        task::SystemTick,
        window::CursorPosition,
    };
    use super::*;
    use crate::managers::changeset::{TextChangeset, TextOpInsertText, TextOperation};
10
    fn ts() -> Instant {
10
        Instant::Tick(SystemTick { tick_counter: 0 })
10
    }
5
    fn sample(id: usize, node: usize) -> UndoableOperation {
5
        UndoableOperation {
5
            changeset: TextChangeset {
5
                id,
5
                target: DomNodeId {
5
                    dom: DomId { inner: 0 },
5
                    node: NodeHierarchyItemId::from_crate_internal(Some(NodeId::new(node))),
5
                },
5
                operation: TextOperation::InsertText(TextOpInsertText {
5
                    text: "x".into(),
5
                    position: CursorPosition::Uninitialized,
5
                    new_cursor: CursorPosition::Uninitialized,
5
                }),
5
                timestamp: ts(),
5
            },
5
            pre_state: NodeStateSnapshot {
5
                node_id: NodeId::new(node),
5
                text_content: "".into(),
5
                cursor_position: None.into(),
5
                selection_range: None.into(),
5
                timestamp: ts(),
5
            },
5
            seat_id: 0,
5
        }
5
    }
4
    fn op_for(seat_id: u64) -> UndoableOperation {
4
        let mut o = sample(1, 1);
4
        o.seat_id = seat_id;
4
        o
4
    }
    /// 9b-ii-a-i-d-ii-d: a seat undoes its own latest edit only while it is
    /// the top of the node's stack; another seat's later edit blocks it, and
    /// the primary is seat 0 like everyone else.
    #[test]
1
    fn a_seats_undo_pops_only_its_own_top_edit() {
1
        let mut stack = NodeUndoRedoStack::new(NodeId::new(1));
1
        stack.push_undo(op_for(7));
1
        assert!(
1
            stack.pop_undo_for_seat(0).is_none(),
            "the primary cannot undo the seat's edit"
        );
1
        assert_eq!(stack.pop_undo_for_seat(7).map(|o| o.seat_id), Some(7));
1
        assert!(stack.pop_undo_for_seat(7).is_none(), "nothing left");
1
        stack.push_undo(op_for(7));
1
        stack.push_undo(op_for(0));
1
        assert!(
1
            stack.pop_undo_for_seat(7).is_none(),
            "buried under the primary's edit"
        );
1
        assert_eq!(stack.pop_undo_for_seat(0).map(|o| o.seat_id), Some(0));
1
        assert_eq!(
1
            stack.pop_undo_for_seat(7).map(|o| o.seat_id),
            Some(7),
            "unburied"
        );
1
    }
    #[test]
1
    fn redo_is_attributed_the_same_way() {
1
        let mut stack = NodeUndoRedoStack::new(NodeId::new(1));
1
        stack.push_redo(op_for(7));
1
        assert!(stack.pop_redo_for_seat(0).is_none());
1
        assert_eq!(stack.pop_redo_for_seat(7).map(|o| o.seat_id), Some(7));
1
    }
    #[test]
1
    fn record_operation_attributes_to_the_primary() {
1
        let mut mgr = UndoRedoManager::default();
1
        let o = sample(1, 1);
1
        let node = o.changeset.target.node.into_crate_internal().unwrap();
1
        mgr.record_operation(o.changeset.clone(), o.pre_state.clone());
1
        assert_eq!(mgr.peek_undo(node).map(|o| o.seat_id), Some(0));
1
        mgr.record_operation_for_seat(o.changeset, o.pre_state, 9);
1
        assert_eq!(mgr.peek_undo(node).map(|o| o.seat_id), Some(9));
1
    }
}