1
//! Text editing changeset system
2
//!
3
//! **STATUS:** The core types (`TextChangeset`, `TextOperation`, `TextOp*` structs) are
4
//! actively used by `window.rs`, `undo_redo.rs`, `event.rs`, and platform code.
5
//!
6
//! The live copy/cut/select-all/delete paths run through `common/event.rs`
7
//! (`SystemChange::CopyToClipboard`/`CutToClipboard`, `CallbackChange::SetSelectAllRange`,
8
//! `LayoutWindow::delete_selection`), not through changeset constructors. The earlier
9
//! `create_*_changeset` helpers were a never-wired parallel implementation (with
10
//! placeholder `deleted_text`, `CursorPosition::Uninitialized` cursors, and byte±1
11
//! UTF-8 deletion) and have been removed.
12
//!
13
//! ## Architecture
14
//!
15
//! This module implements a two-phase changeset system for all text editing operations:
16
//! 1. **Create changesets** (pre-callback): Analyze what would change, don't mutate yet
17
//! 2. **Apply changesets** (post-callback): Actually mutate state if !preventDefault
18
//!
19
//! This pattern enables:
20
//! - preventDefault support for ALL operations (not just text input)
21
//! - Undo/redo stack (record changesets before applying)
22
//! - Validation (check bounds, permissions before mutation)
23
//! - Inspection (user callbacks can see planned changes)
24

            
25
use azul_core::{
26
    dom::DomNodeId,
27
    selection::{OptionSelectionRange, SelectionRange},
28
    task::Instant,
29
    window::CursorPosition,
30
};
31
use azul_css::{impl_option, impl_option_inner, AzString};
32

            
33
use crate::managers::selection::ClipboardContent;
34

            
35
/// Unique identifier for a changeset (for undo/redo)
36
pub type ChangesetId = usize;
37

            
38
/// A text editing changeset that can be inspected before application
39
#[derive(Debug, Clone)]
40
#[repr(C)]
41
pub struct TextChangeset {
42
    /// Unique ID for undo/redo tracking
43
    pub id: ChangesetId,
44
    /// Target DOM node
45
    pub target: DomNodeId,
46
    /// The operation to perform
47
    pub operation: TextOperation,
48
    /// When this changeset was created
49
    pub timestamp: Instant,
50
}
51

            
52
/// Insert text at cursor position
53
#[derive(Debug, Clone)]
54
#[repr(C)]
55
pub struct TextOpInsertText {
56
    pub text: AzString,
57
    pub position: CursorPosition,
58
    pub new_cursor: CursorPosition,
59
}
60

            
61
/// Delete text in range
62
#[derive(Debug, Clone)]
63
#[repr(C)]
64
pub struct TextOpDeleteText {
65
    pub range: SelectionRange,
66
    pub deleted_text: AzString,
67
    pub new_cursor: CursorPosition,
68
}
69

            
70
/// Replace text in range with new text
71
#[derive(Debug, Clone)]
72
#[repr(C)]
73
pub struct TextOpReplaceText {
74
    pub range: SelectionRange,
75
    pub old_text: AzString,
76
    pub new_text: AzString,
77
    pub new_cursor: CursorPosition,
78
}
79

            
80
/// Set selection to new range
81
#[derive(Copy, Debug, Clone)]
82
#[repr(C)]
83
pub struct TextOpSetSelection {
84
    pub old_range: OptionSelectionRange,
85
    pub new_range: SelectionRange,
86
}
87

            
88
/// Extend selection in a direction
89
#[derive(Copy, Debug, Clone)]
90
#[repr(C)]
91
pub struct TextOpExtendSelection {
92
    pub old_range: SelectionRange,
93
    pub new_range: SelectionRange,
94
    pub direction: SelectionDirection,
95
}
96

            
97
/// Clear all selections
98
#[derive(Copy, Debug, Clone)]
99
#[repr(C)]
100
pub struct TextOpClearSelection {
101
    pub old_range: SelectionRange,
102
}
103

            
104
/// Move cursor to new position
105
#[derive(Copy, Debug, Clone)]
106
#[repr(C)]
107
pub struct TextOpMoveCursor {
108
    pub old_position: CursorPosition,
109
    pub new_position: CursorPosition,
110
    pub movement: CursorMovement,
111
}
112

            
113
/// Copy selection to clipboard (no text change)
114
#[derive(Debug, Clone)]
115
#[repr(C)]
116
pub struct TextOpCopy {
117
    pub range: SelectionRange,
118
    pub content: ClipboardContent,
119
}
120

            
121
/// Cut selection to clipboard (deletes text)
122
#[derive(Debug, Clone)]
123
#[repr(C)]
124
pub struct TextOpCut {
125
    pub range: SelectionRange,
126
    pub content: ClipboardContent,
127
    pub new_cursor: CursorPosition,
128
}
129

            
130
/// Paste from clipboard (inserts text)
131
#[derive(Debug, Clone)]
132
#[repr(C)]
133
pub struct TextOpPaste {
134
    pub content: ClipboardContent,
135
    pub position: CursorPosition,
136
    pub new_cursor: CursorPosition,
137
}
138

            
139
/// Select all text in node
140
#[derive(Copy, Debug, Clone)]
141
#[repr(C)]
142
pub struct TextOpSelectAll {
143
    pub old_range: OptionSelectionRange,
144
    pub new_range: SelectionRange,
145
}
146

            
147
/// Text editing operation (what will change)
148
#[derive(Debug, Clone)]
149
#[repr(C, u8)]
150
pub enum TextOperation {
151
    /// Insert text at cursor position
152
    InsertText(TextOpInsertText),
153
    /// Delete text in range
154
    DeleteText(TextOpDeleteText),
155
    /// Replace text in range with new text
156
    ReplaceText(TextOpReplaceText),
157
    /// Set selection to new range
158
    SetSelection(TextOpSetSelection),
159
    /// Extend selection in a direction
160
    ExtendSelection(TextOpExtendSelection),
161
    /// Clear all selections
162
    ClearSelection(TextOpClearSelection),
163
    /// Move cursor to new position
164
    MoveCursor(TextOpMoveCursor),
165
    /// Copy selection to clipboard (no text change)
166
    Copy(TextOpCopy),
167
    /// Cut selection to clipboard (deletes text)
168
    Cut(TextOpCut),
169
    /// Paste from clipboard (inserts text)
170
    Paste(TextOpPaste),
171
    /// Select all text in node
172
    SelectAll(TextOpSelectAll),
173
}
174

            
175
/// Re-export from events module
176
pub use azul_core::events::SelectionDirection;
177
// ============================================================================
178
// Structural document changesets (`DocumentOperation`)
179
// ============================================================================
180
//
181
// Azul NEVER applies these to `StyledDom` — the DOM is immutable. Azul
182
// records intent (Enter → SplitBlock, Backspace-at-start → MergeBlocks, a
183
// bold-toolbar → WrapRange) and delivers it; the APP applies it to its own
184
// document model and regenerates, or uses the provided helper
185
// (`crate::document_edit::apply_document_operation`) on its XML tree. The
186
// existing remap machinery (`NodeIdRemap` + `calculate_contenteditable_key`)
187
// preserves caret/selection/undo across the resulting generation swap.
188
use azul_css::corety::U32Vec;
189

            
190
/// A position INSIDE a node, expressed structurally: before direct child
191
/// `child_index`, optionally at `text_byte` INSIDE that child when (and only
192
/// when) it is a text node.
193
///
194
/// This is the vocabulary's split/join coordinate - deliberately NOT a text
195
/// cursor: a `<ul>` splits between two `<li>`s (`text_byte: None`), a `<p>`
196
/// splits mid-word (`text_byte: Some(5)` inside its text child), a `<div>`
197
/// splits between arbitrary subtrees. Element children always move WHOLESALE
198
/// to one side; only a text child is ever cut, and only at a char boundary.
199
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
200
#[repr(C)]
201
pub struct NodePosition {
202
    /// Index among the node's DIRECT children the position sits before /
203
    /// inside.
204
    pub child_index: u32,
205
    /// Byte offset inside `children[child_index]` when that child is a TEXT
206
    /// node and the position falls inside it. `None` = the position is
207
    /// BETWEEN children (a pure structural boundary).
208
    pub text_byte: azul_css::corety::OptionU32,
209
}
210

            
211
impl NodePosition {
212
    /// A pure structural boundary before child `child_index`.
213
    #[must_use]
214
293
    pub const fn before_child(child_index: u32) -> Self {
215
293
        Self {
216
293
            child_index,
217
293
            text_byte: azul_css::corety::OptionU32::None,
218
293
        }
219
293
    }
220

            
221
    /// A position inside the text child at `child_index`.
222
    #[must_use]
223
322
    pub const fn in_text_child(child_index: u32, text_byte: u32) -> Self {
224
322
        Self {
225
322
            child_index,
226
322
            text_byte: azul_css::corety::OptionU32::Some(text_byte),
227
322
        }
228
322
    }
229
}
230

            
231
/// Split a node at a structural position.
232
///
233
/// Enter in a contenteditable is ONE producer; splitting any container
234
/// between children is the same op.
235
#[derive(Debug, Clone, Copy)]
236
#[repr(C)]
237
pub struct DocOpSplitNode {
238
    /// The node being split.
239
    pub node: DomNodeId,
240
    /// Where: children before the position stay, children after move to the
241
    /// new sibling; a text child AT the position is cut at `text_byte`.
242
    pub at: NodePosition,
243
}
244

            
245
/// Merge two adjacent sibling nodes.
246
///
247
/// Backspace at start / Delete at end are ONE producer; joining any two
248
/// containers is the same op: `second`'s children are appended to `first`,
249
/// `second` is removed. Subtrees are preserved wholesale; only adjacent TEXT
250
/// children at the seam coalesce.
251
#[derive(Debug, Clone, Copy)]
252
#[repr(C)]
253
pub struct DocOpMergeNodes {
254
    /// The surviving first node.
255
    pub first: DomNodeId,
256
    /// The node whose children are appended to `first`.
257
    pub second: DomNodeId,
258
    /// The seam (where the caret lands): `first`'s old child count, with
259
    /// `text_byte` set when the seam coalesces two text nodes.
260
    pub join: NodePosition,
261
}
262

            
263
/// Wrap a contiguous CONTENT RANGE of a node in a new wrapper element.
264
///
265
/// The toolbar bold/italic/link op, expressed structurally: everything
266
/// between `start` and `end` moves INTO the wrapper (boundary TEXT children
267
/// are cut at the range edges; element children move wholesale). Wrapping a
268
/// word in `<strong>` and wrapping three paragraphs in a `<blockquote>` are
269
/// the SAME operation.
270
#[derive(Debug, Clone)]
271
#[repr(C)]
272
pub struct DocOpWrapRange {
273
    /// The node whose children the range covers.
274
    pub node: DomNodeId,
275
    /// Range start (inclusive; byte inside a text child cuts it).
276
    pub start: NodePosition,
277
    /// Range end (exclusive at a child boundary; a byte inside a text child
278
    /// includes that child's text up to the byte).
279
    pub end: NodePosition,
280
    /// The wrapper ELEMENT as a node payload: `wrapper.root` is the element
281
    /// (its `NodeData` carries tag, classes and attributes - an `<a href>`
282
    /// rides its dataset/attributes); `wrapper.children` is ignored.
283
    pub wrapper: azul_core::dom::Dom,
284
}
285

            
286
/// Remove a wrapper element, splicing its children into its place.
287
///
288
/// The wrapper is the direct child of `node` at `at`; adjacent text at both
289
/// seams coalesces, so wrap → unwrap round-trips. The inverse of wrap.
290
#[derive(Debug, Clone, Copy)]
291
#[repr(C)]
292
pub struct DocOpUnwrapRange {
293
    /// The node whose direct child is the wrapper.
294
    pub node: DomNodeId,
295
    /// Position of the wrapper child (`text_byte` is ignored).
296
    pub at: NodePosition,
297
}
298

            
299
/// Insert node SUBTREES under `parent` at child `index` - the immutable-DOM
300
/// analog of `.insertChild()`.
301
///
302
/// The content is a [`azul_core::dom::Dom`] (the native tree apps already
303
/// build), NOT a markup string: a paragraph, a list item, a whole table -
304
/// any subtree, the same op.
305
#[derive(Debug, Clone)]
306
#[repr(C)]
307
pub struct DocOpInsertChildren {
308
    /// Parent the new children are inserted under.
309
    pub parent: DomNodeId,
310
    /// Child index within `parent` (clamped by the applier).
311
    pub index: u32,
312
    /// The subtree(s) to insert. `content.root` is the FIRST inserted child;
313
    /// `content.children`-siblings pattern: a `Dom` is one subtree - multiple
314
    /// siblings are inserted by wrapping in a fragment container is NOT
315
    /// required: the applier inserts exactly this one subtree. (Insert
316
    /// several = several ops, or a `ReplaceChildren`.)
317
    pub content: azul_core::dom::Dom,
318
}
319

            
320
/// Remove a RANGE of direct children of `parent` (with their subtrees) -
321
/// the analog of `.removeChild()`, generalized to a contiguous range.
322
#[derive(Debug, Clone, Copy)]
323
#[repr(C)]
324
pub struct DocOpRemoveChildren {
325
    pub parent: DomNodeId,
326
    /// `[start, end)` among `parent`'s direct children.
327
    pub start: u32,
328
    pub end: u32,
329
}
330

            
331
/// Replace a range of direct children of `parent` with a subtree - the
332
/// analog of `.replaceChild()`. `Insert` and `Remove` are its two
333
/// degenerate forms; the three share one inverse algebra.
334
#[derive(Debug, Clone)]
335
#[repr(C)]
336
pub struct DocOpReplaceChildren {
337
    pub parent: DomNodeId,
338
    /// `[start, end)` among `parent`'s direct children to replace.
339
    pub start: u32,
340
    pub end: u32,
341
    /// The replacement subtree.
342
    pub content: azul_core::dom::Dom,
343
}
344

            
345
/// A structural document edit - the vocabulary `TextOperation` lacks
346
/// (everything here crosses or creates block boundaries).
347
///
348
/// The tree-mutation vocabulary a MUTABLE DOM would express as methods
349
/// (`insertChild` / `removeChild` / `replaceChild` / split / merge),
350
/// expressed here as RECORDED INTENT because the DOM is immutable: azul
351
/// delivers the operation, the app applies it to ITS model (or the
352
/// `document_edit` helper applies it to a `Dom`), and the overlay previews
353
/// it until the re-render lands.
354
///
355
/// Positions are STRUCTURAL ([`NodePosition`]: child index + byte only when
356
/// the boundary child is text). Content payloads are node SUBTREES
357
/// ([`azul_core::dom::Dom`]), never markup strings. The two `*Range` ops are
358
/// the deliberately text-specific pair (inline formatting).
359
#[derive(Debug, Clone)]
360
#[repr(C, u8)]
361
pub enum DocumentOperation {
362
    /// Split ANY node at a structural position.
363
    SplitNode(DocOpSplitNode),
364
    /// Merge two adjacent sibling nodes.
365
    MergeNodes(DocOpMergeNodes),
366
    /// Insert a subtree under a parent (`.insertChild`).
367
    InsertChildren(DocOpInsertChildren),
368
    /// Remove a range of direct children (`.removeChild`).
369
    RemoveChildren(DocOpRemoveChildren),
370
    /// Replace a range of direct children with a subtree (`.replaceChild`).
371
    ReplaceChildren(DocOpReplaceChildren),
372
    /// TEXT-SPECIFIC: wrap a text range in an inline element (bold/italic).
373
    WrapRange(DocOpWrapRange),
374
    /// TEXT-SPECIFIC: remove an inline wrapper from a text range.
375
    UnwrapRange(DocOpUnwrapRange),
376
}
377

            
378
/// Where the caret/selection anchor should land after the app re-renders,
379
/// expressed RE-RENDER-STABLY.
380
///
381
/// `NodeId`s in the changeset refer to the current generation and die at the
382
/// swap, so the resume point is defined against the POST-edit logical
383
/// structure instead. Nothing here presumes text: the anchor is any stable
384
/// node, the path is child indices, the position is structural.
385
#[derive(Debug, Clone)]
386
#[repr(C)]
387
pub struct EditResumePoint {
388
    /// Stable key of the ANCHOR node (via `calculate_contenteditable_key`,
389
    /// which works for any node: explicit key > css id > structural path).
390
    pub anchor_key: u64,
391
    /// Child-index path from the anchor to the target node, in the POST-edit
392
    /// tree (e.g. after a split: the path to the NEW second part).
393
    pub node_path: U32Vec,
394
    /// Where inside the target node (child boundary, or byte in a text
395
    /// child).
396
    pub position: NodePosition,
397
}
398

            
399
/// A recorded structural edit: intent + resume point + identity for the
400
/// commit handshake (`LayoutWindow::mark_document_edit_applied`).
401
#[derive(Debug, Clone)]
402
#[repr(C)]
403
pub struct DocumentChangeset {
404
    /// Monotonic id - the commit-handshake token.
405
    pub id: u64,
406
    /// Primary affected node (the event target), CURRENT generation.
407
    pub target: DomNodeId,
408
    pub operation: DocumentOperation,
409
    pub resume: EditResumePoint,
410
    pub timestamp: Instant,
411
}
412

            
413
impl DocumentChangeset {
414
    /// Create a changeset with a fresh monotonic id.
415
321
    pub fn new(
416
321
        target: DomNodeId,
417
321
        operation: DocumentOperation,
418
321
        resume: EditResumePoint,
419
321
        timestamp: Instant,
420
321
    ) -> Self {
421
        use std::sync::atomic::{AtomicU64, Ordering};
422
        static DOCUMENT_CHANGESET_ID: AtomicU64 = AtomicU64::new(1);
423
321
        Self {
424
321
            id: DOCUMENT_CHANGESET_ID.fetch_add(1, Ordering::Relaxed),
425
321
            target,
426
321
            operation,
427
321
            resume,
428
321
            timestamp,
429
321
        }
430
321
    }
431

            
432
    /// Whether this operation restructures the node tree (vs inline-only wrap).
433
    #[must_use]
434
    pub const fn changes_block_structure(&self) -> bool {
435
        matches!(
436
            self.operation,
437
            DocumentOperation::SplitNode(_)
438
                | DocumentOperation::MergeNodes(_)
439
                | DocumentOperation::InsertChildren(_)
440
                | DocumentOperation::RemoveChildren(_)
441
                | DocumentOperation::ReplaceChildren(_)
442
        )
443
    }
444
}
445

            
446
impl_option!(
447
    DocumentChangeset,
448
    OptionDocumentChangeset,
449
    copy = false,
450
    [Debug, Clone]
451
);
452

            
453
/// Type of cursor movement
454
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
455
#[repr(C)]
456
pub enum CursorMovement {
457
    /// Move left one character
458
    Left,
459
    /// Move right one character
460
    Right,
461
    /// Move up one line
462
    Up,
463
    /// Move down one line
464
    Down,
465
    /// Jump to previous word boundary
466
    WordLeft,
467
    /// Jump to next word boundary
468
    WordRight,
469
    /// Jump to start of line
470
    LineStart,
471
    /// Jump to end of line
472
    LineEnd,
473
    /// Jump to start of document
474
    DocumentStart,
475
    /// Jump to end of document
476
    DocumentEnd,
477
    /// Absolute position (not relative)
478
    Absolute,
479
}
480

            
481
impl TextChangeset {
482
    /// Create a new changeset with unique ID
483
2351
    pub fn new(target: DomNodeId, operation: TextOperation, timestamp: Instant) -> Self {
484
        use std::sync::atomic::{AtomicUsize, Ordering};
485
        static CHANGESET_ID_COUNTER: AtomicUsize = AtomicUsize::new(0);
486

            
487
2351
        Self {
488
2351
            id: CHANGESET_ID_COUNTER.fetch_add(1, Ordering::Relaxed),
489
2351
            target,
490
2351
            operation,
491
2351
            timestamp,
492
2351
        }
493
2351
    }
494

            
495
    /// Check if this changeset actually mutates text (vs just selection/cursor)
496
    #[must_use]
497
91
    pub const fn mutates_text(&self) -> bool {
498
49
        matches!(
499
91
            self.operation,
500
            TextOperation::InsertText { .. }
501
                | TextOperation::DeleteText { .. }
502
                | TextOperation::ReplaceText { .. }
503
                | TextOperation::Cut { .. }
504
                | TextOperation::Paste { .. }
505
        )
506
91
    }
507

            
508
    /// Check if this changeset changes selection (including cursor moves)
509
    #[must_use]
510
72
    pub const fn changes_selection(&self) -> bool {
511
37
        matches!(
512
72
            self.operation,
513
            TextOperation::SetSelection { .. }
514
                | TextOperation::ExtendSelection { .. }
515
                | TextOperation::ClearSelection { .. }
516
                | TextOperation::MoveCursor { .. }
517
                | TextOperation::SelectAll { .. }
518
        )
519
72
    }
520

            
521
    /// Check if this changeset involves clipboard
522
    #[must_use]
523
58
    pub const fn uses_clipboard(&self) -> bool {
524
40
        matches!(
525
58
            self.operation,
526
            TextOperation::Copy { .. } | TextOperation::Cut { .. } | TextOperation::Paste { .. }
527
        )
528
58
    }
529

            
530
    /// Get the target cursor position after this changeset is applied
531
    #[must_use]
532
29
    pub const fn resulting_cursor_position(&self) -> Option<CursorPosition> {
533
29
        match &self.operation {
534
6
            TextOperation::InsertText(op) => Some(op.new_cursor),
535
5
            TextOperation::DeleteText(op) => Some(op.new_cursor),
536
3
            TextOperation::ReplaceText(op) => Some(op.new_cursor),
537
2
            TextOperation::Cut(op) => Some(op.new_cursor),
538
3
            TextOperation::Paste(op) => Some(op.new_cursor),
539
3
            TextOperation::MoveCursor(op) => Some(op.new_position),
540
7
            _ => None,
541
        }
542
29
    }
543

            
544
    /// Get the target selection range after this changeset is applied
545
    #[must_use]
546
28
    pub const fn resulting_selection_range(&self) -> Option<SelectionRange> {
547
28
        match &self.operation {
548
3
            TextOperation::SetSelection(op) => Some(op.new_range),
549
3
            TextOperation::ExtendSelection(op) => Some(op.new_range),
550
3
            TextOperation::SelectAll(op) => Some(op.new_range),
551
19
            _ => None,
552
        }
553
28
    }
554
}
555

            
556
/// Gated on `xml`: the body of `apply_to_dom` - and its return type - is
557
/// `crate::document_edit`, which `layout/src/lib.rs` declares as
558
/// `#[cfg(all(feature = "text_layout", feature = "xml"))] pub mod
559
/// document_edit;`. `managers` is already `#[cfg(feature = "text_layout")]`,
560
/// so `xml` is the only half of that gate still missing here.
561
///
562
/// What an `xml`-less build loses: the Path-2 convenience method only. Apps
563
/// with their own document model are unaffected - they apply the
564
/// `DocumentOperation` themselves; it is the built-in "apply this changeset to
565
/// a plain `Dom`" helper that disappears.
566
#[cfg(feature = "xml")]
567
/// Gated exactly like [`crate::document_edit`], the module this reaches into:
568
/// `text_layout` alone (printpdf's reduced build) compiles the changeset types
569
/// but not `document_edit`, and an ungated method referring to it fails to
570
/// resolve. Same class as the `cpurender` gaps on `tray_icon` and
571
/// `rasterize_svg_clip_to_r8`.
572
#[cfg(all(feature = "text_layout", feature = "xml"))]
573
impl DocumentChangeset {
574
    /// Apply this changeset to an app-model [`Dom`](azul_core::dom::Dom) -
575
    /// the Path-2 helper [`crate::document_edit::apply_document_operation`]
576
    /// as a method, so API consumers reach it without free-function plumbing.
577
    ///
578
    /// `host_path` is the root-to-host child-index path (empty = the model
579
    /// root hosts the blocks). On success the returned
580
    /// [`AppliedEdit`](crate::document_edit::AppliedEdit) carries the resume
581
    /// point and the INVERSE operation to hand back to
582
    /// `CallbackInfo::mark_document_edit_applied_with_inverse`.
583
    ///
584
    /// # Errors
585
    /// The tree is left unchanged on error (host/target not found).
586
    pub fn apply_to_dom(
587
        &self,
588
        model: &mut azul_core::dom::Dom,
589
        host_path: U32Vec,
590
    ) -> crate::document_edit::ResultAppliedEditDocumentEditError {
591
        crate::document_edit::apply_document_operation(model, host_path.as_ref(), self).into()
592
    }
593
}
594

            
595
#[cfg(test)]
596
mod autotest_generated {
597
    use std::{collections::HashSet, thread};
598

            
599
    use azul_core::{
600
        dom::DomId,
601
        geom::LogicalPosition,
602
        selection::{CursorAffinity, GraphemeClusterId, TextCursor},
603
        styled_dom::NodeHierarchyItemId,
604
        task::SystemTick,
605
    };
606

            
607
    use super::*;
608
    use crate::managers::selection::StyledTextRun;
609

            
610
    // =========================================================================
611
    // Fixtures
612
    //
613
    // `TextChangeset` is a plain data carrier: the constructor stamps a unique
614
    // id and the five getters are pure classifiers over `TextOperation`. The
615
    // adversarial surface is therefore (a) the atomic id counter under
616
    // contention, (b) whether the getters partition the 11 operation variants
617
    // exactly as documented, and (c) whether extreme payloads (NaN / infinite
618
    // cursors, u32::MAX cluster ids, huge and non-ASCII strings) survive a
619
    // round trip through the getters bit-for-bit instead of being normalized.
620
    // =========================================================================
621

            
622
    fn node(dom: usize, raw: usize) -> DomNodeId {
623
        DomNodeId {
624
            dom: DomId { inner: dom },
625
            node: NodeHierarchyItemId::from_raw(raw),
626
        }
627
    }
628

            
629
    fn ts(tick: u64) -> Instant {
630
        Instant::Tick(SystemTick::new(tick))
631
    }
632

            
633
    fn cur(x: f32, y: f32) -> CursorPosition {
634
        CursorPosition::InWindow(LogicalPosition::new(x, y))
635
    }
636

            
637
    fn tc(run: u32, byte: u32, affinity: CursorAffinity) -> TextCursor {
638
        TextCursor {
639
            cluster_id: GraphemeClusterId {
640
                source_run: run,
641
                start_byte_in_run: byte,
642
            },
643
            affinity,
644
        }
645
    }
646

            
647
    fn range(start: TextCursor, end: TextCursor) -> SelectionRange {
648
        SelectionRange { start, end }
649
    }
650

            
651
    /// A plain zero-to-one-character forward range.
652
    fn simple_range() -> SelectionRange {
653
        range(
654
            tc(0, 0, CursorAffinity::Leading),
655
            tc(0, 1, CursorAffinity::Trailing),
656
        )
657
    }
658

            
659
    /// A range at the numeric ceiling, selected *backwards* (end before start).
660
    fn extreme_range() -> SelectionRange {
661
        range(
662
            tc(u32::MAX, u32::MAX, CursorAffinity::Trailing),
663
            tc(0, 0, CursorAffinity::Leading),
664
        )
665
    }
666

            
667
    fn clip(text: &str) -> ClipboardContent {
668
        ClipboardContent {
669
            plain_text: AzString::from(text),
670
            styled_runs: Vec::<StyledTextRun>::new().into(),
671
        }
672
    }
673

            
674
    /// One changeset per `TextOperation` variant, labelled by variant name.
675
    ///
676
    /// Deliberately built from extreme payloads so every truth-table test
677
    /// doubles as a no-panic test on hostile input.
678
    fn all_ops() -> Vec<(&'static str, TextOperation)> {
679
        vec![
680
            (
681
                "InsertText",
682
                TextOperation::InsertText(TextOpInsertText {
683
                    text: AzString::from("a\u{0301}\u{1F600}\u{202E}\0"),
684
                    position: cur(f32::NAN, f32::NEG_INFINITY),
685
                    new_cursor: cur(f32::MAX, f32::MIN),
686
                }),
687
            ),
688
            (
689
                "DeleteText",
690
                TextOperation::DeleteText(TextOpDeleteText {
691
                    range: extreme_range(),
692
                    deleted_text: AzString::from(""),
693
                    new_cursor: CursorPosition::Uninitialized,
694
                }),
695
            ),
696
            (
697
                "ReplaceText",
698
                TextOperation::ReplaceText(TextOpReplaceText {
699
                    range: simple_range(),
700
                    old_text: AzString::from("\u{FFFD}"),
701
                    new_text: AzString::from("\u{10FFFF}"),
702
                    new_cursor: CursorPosition::OutOfWindow(LogicalPosition::new(-0.0, 0.0)),
703
                }),
704
            ),
705
            (
706
                "SetSelection",
707
                TextOperation::SetSelection(TextOpSetSelection {
708
                    old_range: OptionSelectionRange::None,
709
                    new_range: extreme_range(),
710
                }),
711
            ),
712
            (
713
                "ExtendSelection",
714
                TextOperation::ExtendSelection(TextOpExtendSelection {
715
                    old_range: simple_range(),
716
                    new_range: extreme_range(),
717
                    direction: SelectionDirection::Backward,
718
                }),
719
            ),
720
            (
721
                "ClearSelection",
722
                TextOperation::ClearSelection(TextOpClearSelection {
723
                    old_range: extreme_range(),
724
                }),
725
            ),
726
            (
727
                "MoveCursor",
728
                TextOperation::MoveCursor(TextOpMoveCursor {
729
                    old_position: CursorPosition::Uninitialized,
730
                    new_position: cur(f32::INFINITY, f32::NAN),
731
                    movement: CursorMovement::DocumentEnd,
732
                }),
733
            ),
734
            (
735
                "Copy",
736
                TextOperation::Copy(TextOpCopy {
737
                    range: extreme_range(),
738
                    content: clip(""),
739
                }),
740
            ),
741
            (
742
                "Cut",
743
                TextOperation::Cut(TextOpCut {
744
                    range: extreme_range(),
745
                    content: clip("\u{1F600}"),
746
                    new_cursor: cur(0.0, 0.0),
747
                }),
748
            ),
749
            (
750
                "Paste",
751
                TextOperation::Paste(TextOpPaste {
752
                    content: clip("\r\n\t"),
753
                    position: cur(-1.0e30, 1.0e30),
754
                    new_cursor: cur(f32::EPSILON, -f32::EPSILON),
755
                }),
756
            ),
757
            (
758
                "SelectAll",
759
                TextOperation::SelectAll(TextOpSelectAll {
760
                    old_range: OptionSelectionRange::Some(simple_range()),
761
                    new_range: extreme_range(),
762
                }),
763
            ),
764
        ]
765
    }
766

            
767
    /// Variant name -> (mutates_text, changes_selection, uses_clipboard).
768
    ///
769
    /// Transcribed from the doc comments, not from the `matches!` arms, so a
770
    /// silent reclassification of a variant fails here.
771
    fn expected_predicates(name: &str) -> (bool, bool, bool) {
772
        match name {
773
            "InsertText" | "DeleteText" | "ReplaceText" => (true, false, false),
774
            "SetSelection" | "ExtendSelection" | "ClearSelection" | "MoveCursor" | "SelectAll" => {
775
                (false, true, false)
776
            }
777
            "Copy" => (false, false, true),
778
            "Cut" | "Paste" => (true, false, true),
779
            other => panic!("unclassified TextOperation variant: {other}"),
780
        }
781
    }
782

            
783
    fn changeset_for(op: TextOperation) -> TextChangeset {
784
        TextChangeset::new(node(0, 1), op, ts(0))
785
    }
786

            
787
    // =========================================================================
788
    // 1. Constructor
789
    // =========================================================================
790

            
791
    #[test]
792
    fn new_preserves_every_argument_verbatim() {
793
        let target = node(usize::MAX, usize::MAX);
794
        let timestamp = ts(u64::MAX);
795
        let op = TextOperation::InsertText(TextOpInsertText {
796
            text: AzString::from("hello"),
797
            position: cur(1.0, 2.0),
798
            new_cursor: cur(3.0, 4.0),
799
        });
800

            
801
        let cs = TextChangeset::new(target, op, timestamp.clone());
802

            
803
        assert_eq!(cs.target, target, "target must round-trip unchanged");
804
        assert_eq!(
805
            cs.timestamp, timestamp,
806
            "timestamp must round-trip unchanged"
807
        );
808
        match &cs.operation {
809
            TextOperation::InsertText(op) => assert_eq!(op.text.as_str(), "hello"),
810
            other => panic!("constructor swapped the operation variant: {other:?}"),
811
        }
812
    }
813

            
814
    #[test]
815
    fn new_does_not_panic_on_extreme_arguments() {
816
        // usize::MAX DomId + 1-based-encoded usize::MAX node id: the constructor
817
        // must not interpret, decode or index with either.
818
        let huge_text = "\u{1F600}".repeat(64 * 1024); // 256 KiB of 4-byte chars
819
        let cs = TextChangeset::new(
820
            node(usize::MAX, usize::MAX),
821
            TextOperation::ReplaceText(TextOpReplaceText {
822
                range: extreme_range(),
823
                old_text: AzString::from(huge_text.as_str()),
824
                new_text: AzString::from(""),
825
                new_cursor: cur(f32::NAN, f32::NAN),
826
            }),
827
            ts(u64::MAX),
828
        );
829

            
830
        assert_eq!(cs.target.dom.inner, usize::MAX);
831
        assert_eq!(cs.target.node.into_raw(), usize::MAX);
832
        assert!(cs.mutates_text());
833
        assert!(cs.resulting_cursor_position().is_some());
834
        match &cs.operation {
835
            TextOperation::ReplaceText(op) => {
836
                assert_eq!(op.old_text.as_str().len(), 256 * 1024);
837
                assert!(op.new_text.as_str().is_empty());
838
            }
839
            other => panic!("unexpected variant: {other:?}"),
840
        }
841
    }
842

            
843
    #[test]
844
    fn new_assigns_strictly_increasing_unique_ids() {
845
        let mut ids = Vec::new();
846
        for i in 0..256_u64 {
847
            let cs = TextChangeset::new(
848
                node(0, 1),
849
                TextOperation::ClearSelection(TextOpClearSelection {
850
                    old_range: simple_range(),
851
                }),
852
                ts(i),
853
            );
854
            ids.push(cs.id);
855
        }
856

            
857
        // Other tests in this binary share the global counter, so only
858
        // *monotonicity within this sequence* is guaranteed — not `id == i`.
859
        for w in ids.windows(2) {
860
            assert!(
861
                w[1] > w[0],
862
                "changeset ids must strictly increase: {} then {}",
863
                w[0],
864
                w[1]
865
            );
866
        }
867
        let unique: HashSet<ChangesetId> = ids.iter().copied().collect();
868
        assert_eq!(unique.len(), ids.len(), "changeset ids must be unique");
869
    }
870

            
871
    #[test]
872
    fn new_ids_stay_unique_across_threads() {
873
        // The id comes from a `fetch_add(Relaxed)` on a process-global counter.
874
        // Relaxed is fine for uniqueness (RMW ops are atomic regardless of
875
        // ordering) — this pins that down under contention.
876
        const THREADS: usize = 8;
877
        const PER_THREAD: usize = 250;
878

            
879
        let handles: Vec<_> = (0..THREADS)
880
            .map(|_| {
881
                thread::spawn(|| {
882
                    (0..PER_THREAD)
883
                        .map(|_| {
884
                            TextChangeset::new(
885
                                node(0, 1),
886
                                TextOperation::Copy(TextOpCopy {
887
                                    range: simple_range(),
888
                                    content: clip("x"),
889
                                }),
890
                                ts(0),
891
                            )
892
                            .id
893
                        })
894
                        .collect::<Vec<ChangesetId>>()
895
                })
896
            })
897
            .collect();
898

            
899
        let mut all = Vec::new();
900
        for h in handles {
901
            all.extend(h.join().expect("worker thread panicked"));
902
        }
903

            
904
        let unique: HashSet<ChangesetId> = all.iter().copied().collect();
905
        assert_eq!(
906
            unique.len(),
907
            THREADS * PER_THREAD,
908
            "concurrent TextChangeset::new handed out duplicate ids"
909
        );
910
    }
911

            
912
    #[test]
913
    fn clone_keeps_the_id_but_new_mints_a_fresh_one() {
914
        let cs = changeset_for(TextOperation::ClearSelection(TextOpClearSelection {
915
            old_range: simple_range(),
916
        }));
917
        let cloned = cs.clone();
918
        assert_eq!(cloned.id, cs.id, "Clone must not re-mint the id");
919

            
920
        let fresh = changeset_for(TextOperation::ClearSelection(TextOpClearSelection {
921
            old_range: simple_range(),
922
        }));
923
        assert!(fresh.id > cs.id, "new() must mint a fresh id");
924
    }
925

            
926
    // =========================================================================
927
    // 2. Predicate truth table + partition invariants
928
    // =========================================================================
929

            
930
    #[test]
931
    fn predicates_match_the_documented_truth_table() {
932
        for (name, op) in all_ops() {
933
            let cs = changeset_for(op);
934
            let got = (
935
                cs.mutates_text(),
936
                cs.changes_selection(),
937
                cs.uses_clipboard(),
938
            );
939
            assert_eq!(
940
                got,
941
                expected_predicates(name),
942
                "{name}: (mutates_text, changes_selection, uses_clipboard) mismatch"
943
            );
944
        }
945
    }
946

            
947
    #[test]
948
    fn all_eleven_variants_are_covered_and_none_is_both_text_and_selection() {
949
        let ops = all_ops();
950
        assert_eq!(
951
            ops.len(),
952
            11,
953
            "all_ops() must cover every TextOperation variant"
954
        );
955

            
956
        for (name, op) in ops {
957
            let cs = changeset_for(op);
958

            
959
            // Invariant: the two predicates are documented as alternatives
960
            // ("mutates text (vs just selection/cursor)"), so no variant may
961
            // claim both.
962
            assert!(
963
                !(cs.mutates_text() && cs.changes_selection()),
964
                "{name} classifies as both a text mutation and a selection change"
965
            );
966

            
967
            // Invariant: every variant is reachable through at least one
968
            // predicate — otherwise a caller dispatching on these three getters
969
            // would silently drop the operation.
970
            assert!(
971
                cs.mutates_text() || cs.changes_selection() || cs.uses_clipboard(),
972
                "{name} is invisible to all three predicates"
973
            );
974
        }
975
    }
976

            
977
    #[test]
978
    fn predicates_are_pure_and_ignore_target_and_timestamp() {
979
        for (name, op) in all_ops() {
980
            let a = TextChangeset::new(node(0, 0), op.clone(), ts(0));
981
            let b = TextChangeset::new(node(usize::MAX, usize::MAX), op, ts(u64::MAX));
982

            
983
            assert_eq!(a.mutates_text(), b.mutates_text(), "{name}: mutates_text");
984
            assert_eq!(
985
                a.changes_selection(),
986
                b.changes_selection(),
987
                "{name}: changes_selection"
988
            );
989
            assert_eq!(
990
                a.uses_clipboard(),
991
                b.uses_clipboard(),
992
                "{name}: uses_clipboard"
993
            );
994

            
995
            // Idempotent: repeated calls on the same instance agree.
996
            assert_eq!(a.mutates_text(), a.mutates_text());
997
            assert_eq!(a.changes_selection(), a.changes_selection());
998
            assert_eq!(a.uses_clipboard(), a.uses_clipboard());
999
        }
    }
    // =========================================================================
    // 3. resulting_cursor_position
    // =========================================================================
    #[test]
    fn resulting_cursor_position_is_some_exactly_for_cursor_moving_ops() {
        for (name, op) in all_ops() {
            let cs = changeset_for(op);
            let expected = matches!(
                name,
                "InsertText" | "DeleteText" | "ReplaceText" | "Cut" | "Paste" | "MoveCursor"
            );
            assert_eq!(
                cs.resulting_cursor_position().is_some(),
                expected,
                "{name}: resulting_cursor_position() presence"
            );
            // Invariant: anything that rewrites the text must say where the
            // cursor lands, otherwise the caller has nowhere to put it.
            if cs.mutates_text() {
                assert!(
                    cs.resulting_cursor_position().is_some(),
                    "{name} mutates text but reports no resulting cursor"
                );
            }
        }
    }
    #[test]
    fn resulting_cursor_position_returns_the_new_cursor_not_the_old_one() {
        let cs = changeset_for(TextOperation::MoveCursor(TextOpMoveCursor {
            old_position: cur(1.0, 1.0),
            new_position: cur(9.0, 9.0),
            movement: CursorMovement::Absolute,
        }));
        assert_eq!(cs.resulting_cursor_position(), Some(cur(9.0, 9.0)));
        let cs = changeset_for(TextOperation::Paste(TextOpPaste {
            content: clip("abc"),
            position: cur(1.0, 1.0),
            new_cursor: cur(4.0, 1.0),
        }));
        assert_eq!(cs.resulting_cursor_position(), Some(cur(4.0, 1.0)));
    }
    #[test]
    fn resulting_cursor_position_preserves_nan_and_infinity_bit_for_bit() {
        // `LogicalPosition`'s PartialEq quantizes (NaN -> i64::MIN, huge -> i64::MAX),
        // so `==` would happily call NaN and f32::MAX "equal" to other values.
        // Compare raw bits instead: the getter must hand back the exact payload
        // it was given, without clamping, canonicalizing NaN, or flipping -0.0.
        let payloads = [
            (f32::NAN, f32::NEG_INFINITY),
            (f32::INFINITY, -0.0),
            (f32::MAX, f32::MIN),
            (f32::MIN_POSITIVE, -f32::MIN_POSITIVE),
        ];
        for (x, y) in payloads {
            let cs = changeset_for(TextOperation::InsertText(TextOpInsertText {
                text: AzString::from("t"),
                position: CursorPosition::Uninitialized,
                new_cursor: cur(x, y),
            }));
            match cs.resulting_cursor_position() {
                Some(CursorPosition::InWindow(p)) => {
                    assert_eq!(p.x.to_bits(), x.to_bits(), "x mangled for ({x}, {y})");
                    assert_eq!(p.y.to_bits(), y.to_bits(), "y mangled for ({x}, {y})");
                }
                other => panic!("expected InWindow cursor, got {other:?}"),
            }
        }
    }
    #[test]
    fn resulting_cursor_position_preserves_the_cursor_variant() {
        // Uninitialized / OutOfWindow must survive as themselves — a getter that
        // "helpfully" normalized them to InWindow(0,0) would place the caret at
        // the window origin.
        for expected in [
            CursorPosition::Uninitialized,
            CursorPosition::OutOfWindow(LogicalPosition::new(-5.0, -5.0)),
            CursorPosition::InWindow(LogicalPosition::new(0.0, 0.0)),
        ] {
            let cs = changeset_for(TextOperation::DeleteText(TextOpDeleteText {
                range: simple_range(),
                deleted_text: AzString::from("x"),
                new_cursor: expected,
            }));
            assert_eq!(cs.resulting_cursor_position(), Some(expected));
        }
    }
    // =========================================================================
    // 4. resulting_selection_range
    // =========================================================================
    #[test]
    fn resulting_selection_range_is_some_exactly_for_range_setting_ops() {
        for (name, op) in all_ops() {
            let cs = changeset_for(op);
            let expected = matches!(name, "SetSelection" | "ExtendSelection" | "SelectAll");
            assert_eq!(
                cs.resulting_selection_range().is_some(),
                expected,
                "{name}: resulting_selection_range() presence"
            );
            // Invariant: a resulting range implies the changeset changes the
            // selection. (The converse does NOT hold — ClearSelection and
            // MoveCursor change the selection but produce no range; that
            // asymmetry is asserted below.)
            if cs.resulting_selection_range().is_some() {
                assert!(
                    cs.changes_selection(),
                    "{name} yields a selection range but denies changing the selection"
                );
            }
        }
    }
    #[test]
    fn clear_and_move_change_selection_but_yield_no_range() {
        let cleared = changeset_for(TextOperation::ClearSelection(TextOpClearSelection {
            old_range: simple_range(),
        }));
        assert!(cleared.changes_selection());
        assert_eq!(cleared.resulting_selection_range(), None);
        assert_eq!(cleared.resulting_cursor_position(), None);
        let moved = changeset_for(TextOperation::MoveCursor(TextOpMoveCursor {
            old_position: cur(0.0, 0.0),
            new_position: cur(1.0, 0.0),
            movement: CursorMovement::WordRight,
        }));
        assert!(moved.changes_selection());
        assert_eq!(moved.resulting_selection_range(), None);
        assert_eq!(moved.resulting_cursor_position(), Some(cur(1.0, 0.0)));
    }
    #[test]
    fn resulting_selection_range_does_not_normalize_a_backwards_range() {
        // A backwards (end < start) selection is legal — "the direction is
        // implicit". The getter must not silently swap the endpoints.
        let backwards = extreme_range();
        assert!(backwards.end < backwards.start);
        let cs = changeset_for(TextOperation::SetSelection(TextOpSetSelection {
            old_range: OptionSelectionRange::None,
            new_range: backwards,
        }));
        let got = cs
            .resulting_selection_range()
            .expect("SetSelection must yield a range");
        assert_eq!(got, backwards, "endpoints were reordered or clamped");
        assert_eq!(got.start.cluster_id.source_run, u32::MAX);
        assert_eq!(got.start.cluster_id.start_byte_in_run, u32::MAX);
        assert_eq!(got.start.affinity, CursorAffinity::Trailing);
        assert_eq!(got.end, tc(0, 0, CursorAffinity::Leading));
    }
    #[test]
    fn resulting_selection_range_returns_new_range_and_preserves_empty_ranges() {
        // Collapsed range (start == end) is a caret, not "no selection" — it
        // must come back as Some, not None.
        let caret = range(
            tc(7, 3, CursorAffinity::Leading),
            tc(7, 3, CursorAffinity::Leading),
        );
        let cs = changeset_for(TextOperation::ExtendSelection(TextOpExtendSelection {
            old_range: extreme_range(),
            new_range: caret,
            direction: SelectionDirection::Forward,
        }));
        assert_eq!(cs.resulting_selection_range(), Some(caret));
        // SelectAll must return `new_range`, never `old_range`.
        let cs = changeset_for(TextOperation::SelectAll(TextOpSelectAll {
            old_range: OptionSelectionRange::Some(simple_range()),
            new_range: caret,
        }));
        assert_eq!(cs.resulting_selection_range(), Some(caret));
    }
    // =========================================================================
    // 5. Payload round-trips (unicode / huge / empty)
    // =========================================================================
    #[test]
    fn text_payloads_round_trip_through_the_changeset_unchanged() {
        let cases = [
            "",                              // empty
            "\0",                            // interior NUL
            "a\u{0301}",                     // combining acute
            "\u{1F1E9}\u{1F1EA}",            // regional-indicator pair
            "\u{202E}txet desrever\u{202C}", // bidi override
            "\u{10FFFF}",                    // highest scalar value
            "line1\r\nline2\u{2028}line3",   // CRLF + LINE SEPARATOR
        ];
        for s in cases {
            let cs = changeset_for(TextOperation::ReplaceText(TextOpReplaceText {
                range: simple_range(),
                old_text: AzString::from(s),
                new_text: AzString::from(s),
                new_cursor: CursorPosition::Uninitialized,
            }));
            match &cs.operation {
                TextOperation::ReplaceText(op) => {
                    assert_eq!(op.old_text.as_str(), s, "old_text mangled for {s:?}");
                    assert_eq!(op.new_text.as_str(), s, "new_text mangled for {s:?}");
                    assert_eq!(op.old_text.as_str().len(), s.len(), "byte length changed");
                }
                other => panic!("unexpected variant: {other:?}"),
            }
        }
    }
    #[test]
    fn clipboard_payloads_survive_and_stay_classified_as_clipboard_ops() {
        let big = "\u{00E9}".repeat(128 * 1024); // 256 KiB of 2-byte chars
        let cs = changeset_for(TextOperation::Cut(TextOpCut {
            range: extreme_range(),
            content: clip(&big),
            new_cursor: cur(0.0, 0.0),
        }));
        assert!(cs.uses_clipboard());
        assert!(
            cs.mutates_text(),
            "Cut deletes text, so it must count as a mutation"
        );
        assert!(!cs.changes_selection());
        match &cs.operation {
            TextOperation::Cut(op) => {
                assert_eq!(op.content.plain_text.as_str().len(), 256 * 1024);
                assert!(op.content.styled_runs.as_slice().is_empty());
                // Empty styled_runs => empty <div> wrapper, no panic on a huge run.
                assert_eq!(op.content.to_html(), "<div></div>");
            }
            other => panic!("unexpected variant: {other:?}"),
        }
        // An empty clipboard payload is still a clipboard op.
        let empty = changeset_for(TextOperation::Copy(TextOpCopy {
            range: simple_range(),
            content: clip(""),
        }));
        assert!(empty.uses_clipboard());
        assert!(!empty.mutates_text());
        assert_eq!(empty.resulting_cursor_position(), None);
        assert_eq!(empty.resulting_selection_range(), None);
    }
    #[test]
    fn timestamps_round_trip_and_stay_ordered() {
        let zero = changeset_for_ts(ts(0));
        let max = changeset_for_ts(ts(u64::MAX));
        assert_eq!(zero.timestamp, ts(0));
        assert_eq!(max.timestamp, ts(u64::MAX));
        assert!(
            zero.timestamp < max.timestamp,
            "tick ordering must survive being stored in a changeset"
        );
    }
    fn changeset_for_ts(timestamp: Instant) -> TextChangeset {
        TextChangeset::new(
            node(0, 1),
            TextOperation::ClearSelection(TextOpClearSelection {
                old_range: simple_range(),
            }),
            timestamp,
        )
    }
}