ftui-widgets 0.4.0

Widget library built on FrankenTUI render and layout.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
#![forbid(unsafe_code)]

//! Undo support for widgets.
//!
//! This module provides the [`UndoSupport`] trait that widgets can implement
//! to enable undo/redo functionality for their state changes.
//!
//! # Design
//!
//! The undo system is based on the Command Pattern. Each undoable operation
//! creates a command that knows how to:
//! 1. Execute the operation (already done when the command is created)
//! 2. Undo the operation (reverse the change)
//! 3. Redo the operation (reapply the change)
//!
//! Commands are stored in a history stack managed by [`HistoryManager`].
//!
//! # Usage
//!
//! Widgets that implement `UndoSupport` can generate commands for their
//! state changes. These commands can then be pushed to a history manager
//! for undo/redo support.
//!
//! ```ignore
//! use ftui_widgets::undo_support::{UndoSupport, TextEditOperation};
//! use ftui_runtime::undo::HistoryManager;
//!
//! let mut history = HistoryManager::default();
//! let mut input = TextInput::new();
//!
//! // Perform an edit and create an undo command
//! if let Some(cmd) = input.create_undo_command(TextEditOperation::Insert {
//!     position: 0,
//!     text: "Hello".to_string(),
//! }) {
//!     history.push(cmd);
//! }
//! ```
//!
//! [`HistoryManager`]: ftui_runtime::undo::HistoryManager

use std::any::Any;
use std::fmt;
use std::sync::atomic::{AtomicU64, Ordering};

/// Unique identifier for a widget instance.
///
/// Used to associate undo commands with specific widgets.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct UndoWidgetId(u64);

impl UndoWidgetId {
    /// Create a new unique widget ID.
    pub fn new() -> Self {
        static COUNTER: AtomicU64 = AtomicU64::new(1);
        Self(COUNTER.fetch_add(1, Ordering::Relaxed))
    }

    /// Create a widget ID from a raw value.
    ///
    /// Use this when you need to associate commands with a specific widget.
    #[must_use]
    pub const fn from_raw(id: u64) -> Self {
        Self(id)
    }

    /// Get the raw value.
    #[must_use]
    pub const fn raw(self) -> u64 {
        self.0
    }
}

impl Default for UndoWidgetId {
    fn default() -> Self {
        Self::new()
    }
}

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

/// Text edit operation types.
///
/// These represent the atomic operations that can be performed on text.
#[derive(Debug, Clone)]
pub enum TextEditOperation {
    /// Insert text at a position.
    Insert {
        /// Grapheme index where text was inserted.
        position: usize,
        /// The inserted text.
        text: String,
    },
    /// Delete text at a position.
    Delete {
        /// Grapheme index where deletion started.
        position: usize,
        /// The deleted text (for undo).
        deleted_text: String,
    },
    /// Replace text at a position.
    Replace {
        /// Grapheme index where replacement started.
        position: usize,
        /// The old text (for undo).
        old_text: String,
        /// The new text.
        new_text: String,
    },
    /// Set the entire value.
    SetValue {
        /// The old value (for undo).
        old_value: String,
        /// The new value.
        new_value: String,
    },
}

impl TextEditOperation {
    /// Get a description of this operation.
    #[must_use]
    pub fn description(&self) -> &'static str {
        match self {
            Self::Insert { .. } => "Insert text",
            Self::Delete { .. } => "Delete text",
            Self::Replace { .. } => "Replace text",
            Self::SetValue { .. } => "Set value",
        }
    }

    /// Calculate the size in bytes of this operation.
    #[must_use]
    pub fn size_bytes(&self) -> usize {
        std::mem::size_of::<Self>()
            + match self {
                Self::Insert { text, .. } => text.len(),
                Self::Delete { deleted_text, .. } => deleted_text.len(),
                Self::Replace {
                    old_text, new_text, ..
                } => old_text.len() + new_text.len(),
                Self::SetValue {
                    old_value,
                    new_value,
                } => old_value.len() + new_value.len(),
            }
    }
}

/// Selection state operation types.
#[derive(Debug, Clone)]
pub enum SelectionOperation {
    /// Selection changed.
    Changed {
        /// Old selection anchor.
        old_anchor: Option<usize>,
        /// Old cursor position.
        old_cursor: usize,
        /// New selection anchor.
        new_anchor: Option<usize>,
        /// New cursor position.
        new_cursor: usize,
    },
}

/// Tree expansion operation types.
#[derive(Debug, Clone)]
pub enum TreeOperation {
    /// Node expanded.
    Expand {
        /// Path to the node (indices).
        path: Vec<usize>,
    },
    /// Node collapsed.
    Collapse {
        /// Path to the node (indices).
        path: Vec<usize>,
    },
    /// Multiple nodes toggled.
    ToggleBatch {
        /// Paths that were expanded.
        expanded: Vec<Vec<usize>>,
        /// Paths that were collapsed.
        collapsed: Vec<Vec<usize>>,
    },
}

impl TreeOperation {
    /// Get a description of this operation.
    #[must_use]
    pub fn description(&self) -> &'static str {
        match self {
            Self::Expand { .. } => "Expand node",
            Self::Collapse { .. } => "Collapse node",
            Self::ToggleBatch { .. } => "Toggle nodes",
        }
    }
}

/// List selection operation types.
#[derive(Debug, Clone)]
pub enum ListOperation {
    /// Selection changed.
    Select {
        /// Old selection.
        old_selection: Option<usize>,
        /// New selection.
        new_selection: Option<usize>,
    },
    /// Multiple selection changed.
    MultiSelect {
        /// Old selections.
        old_selections: Vec<usize>,
        /// New selections.
        new_selections: Vec<usize>,
    },
}

impl ListOperation {
    /// Get a description of this operation.
    #[must_use]
    pub fn description(&self) -> &'static str {
        match self {
            Self::Select { .. } => "Change selection",
            Self::MultiSelect { .. } => "Change selections",
        }
    }
}

/// Table operation types.
#[derive(Debug, Clone)]
pub enum TableOperation {
    /// Sort column changed.
    Sort {
        /// Old sort column.
        old_column: Option<usize>,
        /// Old sort ascending.
        old_ascending: bool,
        /// New sort column.
        new_column: Option<usize>,
        /// New sort ascending.
        new_ascending: bool,
    },
    /// Filter applied.
    Filter {
        /// Old filter string.
        old_filter: String,
        /// New filter string.
        new_filter: String,
    },
    /// Row selection changed.
    SelectRow {
        /// Old selected row.
        old_row: Option<usize>,
        /// New selected row.
        new_row: Option<usize>,
    },
}

impl TableOperation {
    /// Get a description of this operation.
    #[must_use]
    pub fn description(&self) -> &'static str {
        match self {
            Self::Sort { .. } => "Change sort",
            Self::Filter { .. } => "Apply filter",
            Self::SelectRow { .. } => "Select row",
        }
    }
}

/// Callback for applying a text edit operation.
pub type TextEditApplyFn =
    Box<dyn Fn(UndoWidgetId, &TextEditOperation) -> Result<(), String> + Send + Sync>;

/// Callback for undoing a text edit operation.
pub type TextEditUndoFn =
    Box<dyn Fn(UndoWidgetId, &TextEditOperation) -> Result<(), String> + Send + Sync>;

/// A widget undo command for text editing.
pub struct WidgetTextEditCmd {
    /// Widget ID this command operates on.
    widget_id: UndoWidgetId,
    /// The operation.
    operation: TextEditOperation,
    /// Apply callback.
    apply_fn: Option<TextEditApplyFn>,
    /// Undo callback.
    undo_fn: Option<TextEditUndoFn>,
    /// Whether the operation has been executed.
    executed: bool,
}

impl WidgetTextEditCmd {
    /// Create a new text edit command.
    #[must_use]
    pub fn new(widget_id: UndoWidgetId, operation: TextEditOperation) -> Self {
        Self {
            widget_id,
            operation,
            apply_fn: None,
            undo_fn: None,
            executed: false,
        }
    }

    /// Set the apply callback (builder).
    #[must_use]
    pub fn with_apply<F>(mut self, f: F) -> Self
    where
        F: Fn(UndoWidgetId, &TextEditOperation) -> Result<(), String> + Send + Sync + 'static,
    {
        self.apply_fn = Some(Box::new(f));
        self
    }

    /// Set the undo callback (builder).
    #[must_use]
    pub fn with_undo<F>(mut self, f: F) -> Self
    where
        F: Fn(UndoWidgetId, &TextEditOperation) -> Result<(), String> + Send + Sync + 'static,
    {
        self.undo_fn = Some(Box::new(f));
        self
    }

    /// Get the widget ID.
    #[must_use]
    pub fn widget_id(&self) -> UndoWidgetId {
        self.widget_id
    }

    /// Get the operation.
    #[must_use]
    pub fn operation(&self) -> &TextEditOperation {
        &self.operation
    }
}

impl fmt::Debug for WidgetTextEditCmd {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("WidgetTextEditCmd")
            .field("widget_id", &self.widget_id)
            .field("operation", &self.operation)
            .field("executed", &self.executed)
            .finish()
    }
}

// Implement UndoableCmd trait from ftui_runtime
// Note: We can't directly implement the trait here because it's in ftui_runtime
// and we can't have a circular dependency. Instead, we provide methods that
// match the trait's interface, and the integration happens at runtime.

impl WidgetTextEditCmd {
    /// Execute the command.
    #[must_use = "handle the result; errors indicate the edit was not applied"]
    pub fn execute(&mut self) -> Result<(), String> {
        if let Some(ref apply_fn) = self.apply_fn {
            apply_fn(self.widget_id, &self.operation)?;
        }
        self.executed = true;
        Ok(())
    }

    /// Undo the command.
    #[must_use = "handle the result; errors indicate the undo was not applied"]
    pub fn undo(&mut self) -> Result<(), String> {
        if let Some(ref undo_fn) = self.undo_fn {
            undo_fn(self.widget_id, &self.operation)?;
        }
        self.executed = false;
        Ok(())
    }

    /// Redo the command (same as execute).
    #[must_use = "handle the result; errors indicate the redo was not applied"]
    pub fn redo(&mut self) -> Result<(), String> {
        self.execute()
    }

    /// Get the description.
    #[must_use]
    pub fn description(&self) -> &'static str {
        self.operation.description()
    }

    /// Get the size in bytes.
    #[must_use]
    pub fn size_bytes(&self) -> usize {
        std::mem::size_of::<Self>() + self.operation.size_bytes()
    }
}

/// Trait for widgets that support undo operations.
///
/// Widgets implement this trait to provide undo/redo functionality.
/// The trait provides a standardized way to:
/// 1. Track widget identity for command association
/// 2. Create undo commands for state changes
/// 3. Restore state from undo/redo operations
pub trait UndoSupport {
    /// Get the widget's unique ID for undo tracking.
    fn undo_widget_id(&self) -> UndoWidgetId;

    /// Create a snapshot of the current state for undo purposes.
    ///
    /// This is used to create "before" state for operations.
    fn create_snapshot(&self) -> Box<dyn Any + Send>;

    /// Restore state from a snapshot.
    ///
    /// Returns true if the restore was successful.
    fn restore_snapshot(&mut self, snapshot: &dyn Any) -> bool;
}

/// Extension trait for text input widgets with undo support.
pub trait TextInputUndoExt: UndoSupport {
    /// Get the current text value.
    fn text_value(&self) -> &str;

    /// Set the text value directly (for undo/redo).
    fn set_text_value(&mut self, value: &str);

    /// Get the current cursor position.
    fn cursor_position(&self) -> usize;

    /// Set the cursor position directly.
    fn set_cursor_position(&mut self, pos: usize);

    /// Insert text at a position.
    fn insert_text_at(&mut self, position: usize, text: &str);

    /// Delete text at a range.
    fn delete_text_range(&mut self, start: usize, end: usize);
}

/// Extension trait for tree widgets with undo support.
pub trait TreeUndoExt: UndoSupport {
    /// Check if a node is expanded.
    fn is_node_expanded(&self, path: &[usize]) -> bool;

    /// Expand a node.
    fn expand_node(&mut self, path: &[usize]);

    /// Collapse a node.
    fn collapse_node(&mut self, path: &[usize]);
}

/// Extension trait for list widgets with undo support.
pub trait ListUndoExt: UndoSupport {
    /// Get the current selection.
    fn selected_index(&self) -> Option<usize>;

    /// Set the selection.
    fn set_selected_index(&mut self, index: Option<usize>);
}

/// Extension trait for table widgets with undo support.
pub trait TableUndoExt: UndoSupport {
    /// Get the current sort state.
    fn sort_state(&self) -> (Option<usize>, bool);

    /// Set the sort state.
    fn set_sort_state(&mut self, column: Option<usize>, ascending: bool);

    /// Get the current filter.
    fn filter_text(&self) -> &str;

    /// Set the filter.
    fn set_filter_text(&mut self, filter: &str);
}

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

    #[test]
    fn test_undo_widget_id_uniqueness() {
        let id1 = UndoWidgetId::new();
        let id2 = UndoWidgetId::new();
        assert_ne!(id1, id2);
    }

    #[test]
    fn test_undo_widget_id_from_raw() {
        let id = UndoWidgetId::from_raw(42);
        assert_eq!(id.raw(), 42);
    }

    #[test]
    fn test_text_edit_operation_description() {
        assert_eq!(
            TextEditOperation::Insert {
                position: 0,
                text: "x".to_string()
            }
            .description(),
            "Insert text"
        );
        assert_eq!(
            TextEditOperation::Delete {
                position: 0,
                deleted_text: "x".to_string()
            }
            .description(),
            "Delete text"
        );
    }

    #[test]
    fn test_text_edit_operation_size_bytes() {
        let op = TextEditOperation::Insert {
            position: 0,
            text: "hello".to_string(),
        };
        assert!(op.size_bytes() > 5);
    }

    #[test]
    fn test_widget_text_edit_cmd_creation() {
        let widget_id = UndoWidgetId::new();
        let cmd = WidgetTextEditCmd::new(
            widget_id,
            TextEditOperation::Insert {
                position: 0,
                text: "test".to_string(),
            },
        );
        assert_eq!(cmd.widget_id(), widget_id);
        assert_eq!(cmd.description(), "Insert text");
    }

    #[test]
    fn test_widget_text_edit_cmd_with_callbacks() {
        use std::sync::Arc;
        use std::sync::atomic::{AtomicBool, Ordering};

        let applied = Arc::new(AtomicBool::new(false));
        let undone = Arc::new(AtomicBool::new(false));
        let applied_clone = applied.clone();
        let undone_clone = undone.clone();

        let widget_id = UndoWidgetId::new();
        let mut cmd = WidgetTextEditCmd::new(
            widget_id,
            TextEditOperation::Insert {
                position: 0,
                text: "test".to_string(),
            },
        )
        .with_apply(move |_, _| {
            applied_clone.store(true, Ordering::SeqCst);
            Ok(())
        })
        .with_undo(move |_, _| {
            undone_clone.store(true, Ordering::SeqCst);
            Ok(())
        });

        cmd.execute().unwrap();
        assert!(applied.load(Ordering::SeqCst));

        cmd.undo().unwrap();
        assert!(undone.load(Ordering::SeqCst));
    }

    #[test]
    fn test_tree_operation_description() {
        assert_eq!(
            TreeOperation::Expand { path: vec![0] }.description(),
            "Expand node"
        );
        assert_eq!(
            TreeOperation::Collapse { path: vec![0] }.description(),
            "Collapse node"
        );
    }

    #[test]
    fn test_list_operation_description() {
        assert_eq!(
            ListOperation::Select {
                old_selection: None,
                new_selection: Some(0)
            }
            .description(),
            "Change selection"
        );
    }

    #[test]
    fn test_table_operation_description() {
        assert_eq!(
            TableOperation::Sort {
                old_column: None,
                old_ascending: true,
                new_column: Some(0),
                new_ascending: true
            }
            .description(),
            "Change sort"
        );
    }

    // --- UndoWidgetId ---

    #[test]
    fn widget_id_display() {
        let id = UndoWidgetId::from_raw(7);
        assert_eq!(format!("{id}"), "Widget(7)");
    }

    #[test]
    fn widget_id_default_is_unique() {
        let a = UndoWidgetId::default();
        let b = UndoWidgetId::default();
        assert_ne!(a, b);
    }

    #[test]
    fn widget_id_hash_eq() {
        let id = UndoWidgetId::from_raw(99);
        let id2 = UndoWidgetId::from_raw(99);
        assert_eq!(id, id2);

        use std::collections::HashSet;
        let mut set = HashSet::new();
        set.insert(id);
        assert!(set.contains(&id2));
    }

    // --- TextEditOperation descriptions and size_bytes ---

    #[test]
    fn text_edit_replace_description() {
        let op = TextEditOperation::Replace {
            position: 0,
            old_text: "old".to_string(),
            new_text: "new".to_string(),
        };
        assert_eq!(op.description(), "Replace text");
    }

    #[test]
    fn text_edit_set_value_description() {
        let op = TextEditOperation::SetValue {
            old_value: "".to_string(),
            new_value: "hello".to_string(),
        };
        assert_eq!(op.description(), "Set value");
    }

    #[test]
    fn text_edit_delete_size_bytes() {
        let op = TextEditOperation::Delete {
            position: 5,
            deleted_text: "abc".to_string(),
        };
        assert!(op.size_bytes() >= 3);
    }

    #[test]
    fn text_edit_replace_size_bytes() {
        let op = TextEditOperation::Replace {
            position: 0,
            old_text: "aaa".to_string(),
            new_text: "bbbbb".to_string(),
        };
        // Should include both old and new text lengths
        assert!(op.size_bytes() >= 8); // 3 + 5
    }

    #[test]
    fn text_edit_set_value_size_bytes() {
        let op = TextEditOperation::SetValue {
            old_value: "x".to_string(),
            new_value: "yyyy".to_string(),
        };
        assert!(op.size_bytes() >= 5); // 1 + 4
    }

    // --- WidgetTextEditCmd ---

    #[test]
    fn cmd_execute_without_callbacks_succeeds() {
        let mut cmd = WidgetTextEditCmd::new(
            UndoWidgetId::from_raw(1),
            TextEditOperation::Insert {
                position: 0,
                text: "hi".to_string(),
            },
        );
        assert!(cmd.execute().is_ok());
    }

    #[test]
    fn cmd_undo_without_callbacks_succeeds() {
        let mut cmd = WidgetTextEditCmd::new(
            UndoWidgetId::from_raw(1),
            TextEditOperation::Delete {
                position: 0,
                deleted_text: "x".to_string(),
            },
        );
        assert!(cmd.undo().is_ok());
    }

    #[test]
    fn cmd_redo_calls_execute() {
        use std::sync::Arc;
        use std::sync::atomic::{AtomicUsize, Ordering};

        let count = Arc::new(AtomicUsize::new(0));
        let count_clone = count.clone();

        let mut cmd = WidgetTextEditCmd::new(
            UndoWidgetId::from_raw(1),
            TextEditOperation::Insert {
                position: 0,
                text: "t".to_string(),
            },
        )
        .with_apply(move |_, _| {
            count_clone.fetch_add(1, Ordering::SeqCst);
            Ok(())
        });

        cmd.execute().unwrap();
        assert_eq!(count.load(Ordering::SeqCst), 1);

        cmd.redo().unwrap();
        assert_eq!(count.load(Ordering::SeqCst), 2);
    }

    #[test]
    fn cmd_debug_format() {
        let cmd = WidgetTextEditCmd::new(
            UndoWidgetId::from_raw(5),
            TextEditOperation::Insert {
                position: 0,
                text: "abc".to_string(),
            },
        );
        let dbg = format!("{cmd:?}");
        assert!(dbg.contains("WidgetTextEditCmd"));
        assert!(dbg.contains("Insert"));
    }

    #[test]
    fn cmd_size_bytes_nonzero() {
        let cmd = WidgetTextEditCmd::new(
            UndoWidgetId::from_raw(1),
            TextEditOperation::Insert {
                position: 0,
                text: "hello world".to_string(),
            },
        );
        assert!(cmd.size_bytes() > 11);
    }

    // --- TreeOperation ---

    #[test]
    fn tree_toggle_batch_description() {
        let op = TreeOperation::ToggleBatch {
            expanded: vec![vec![0, 1]],
            collapsed: vec![vec![2]],
        };
        assert_eq!(op.description(), "Toggle nodes");
    }

    // --- ListOperation ---

    #[test]
    fn list_multi_select_description() {
        let op = ListOperation::MultiSelect {
            old_selections: vec![0, 1],
            new_selections: vec![2, 3],
        };
        assert_eq!(op.description(), "Change selections");
    }

    // --- TableOperation ---

    #[test]
    fn table_filter_description() {
        let op = TableOperation::Filter {
            old_filter: "".to_string(),
            new_filter: "test".to_string(),
        };
        assert_eq!(op.description(), "Apply filter");
    }

    #[test]
    fn table_select_row_description() {
        let op = TableOperation::SelectRow {
            old_row: Some(0),
            new_row: Some(5),
        };
        assert_eq!(op.description(), "Select row");
    }

    // --- SelectionOperation ---

    #[test]
    fn selection_operation_fields() {
        let op = SelectionOperation::Changed {
            old_anchor: Some(0),
            old_cursor: 5,
            new_anchor: None,
            new_cursor: 10,
        };
        let dbg = format!("{op:?}");
        assert!(dbg.contains("Changed"));
    }
}