Skip to main content

ftui_runtime/undo/
command.rs

1#![forbid(unsafe_code)]
2
3//! Undoable command infrastructure for the undo/redo system.
4//!
5//! This module provides the [`UndoableCmd`] trait for reversible operations
6//! and common command implementations for text editing and UI interactions.
7//!
8//! # Design Principles
9//!
10//! 1. **Explicit state**: Commands capture all state needed for undo/redo
11//! 2. **Memory-efficient**: Commands report their size for budget management
12//! 3. **Mergeable**: Consecutive similar commands can merge (e.g., typing)
13//! 4. **Traceable**: Commands include metadata for debugging and UI display
14//!
15//! # Invariants
16//!
17//! - `execute()` followed by `undo()` restores prior state exactly
18//! - `undo()` followed by `redo()` restores the executed state exactly
19//! - Commands with `can_merge() == true` MUST successfully merge
20//! - `size_bytes()` MUST be accurate for memory budgeting
21//!
22//! # Failure Modes
23//!
24//! - **Stale reference**: Command holds reference to deleted target
25//!   - Mitigation: Validate target existence in execute/undo
26//! - **State drift**: External changes invalidate undo data
27//!   - Mitigation: Clear undo stack on external modifications
28//! - **Memory exhaustion**: Unbounded history growth
29//!   - Mitigation: History stack enforces size limits via `size_bytes()`
30
31use std::any::Any;
32use std::fmt;
33use web_time::Instant;
34
35/// Unique identifier for a widget that commands operate on.
36///
37/// Commands targeting widgets store this ID to locate their target
38/// during execute/undo operations.
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
40pub struct WidgetId(pub u64);
41
42impl WidgetId {
43    /// Create a new widget ID from a raw value.
44    #[must_use]
45    pub const fn new(id: u64) -> Self {
46        Self(id)
47    }
48
49    /// Get the raw ID value.
50    #[must_use]
51    pub const fn raw(self) -> u64 {
52        self.0
53    }
54}
55
56/// Source of a command - who/what triggered it.
57///
58/// Used for filtering undo history and debugging.
59#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
60pub enum CommandSource {
61    /// Direct user action (keyboard, mouse).
62    #[default]
63    User,
64    /// Triggered programmatically by application code.
65    Programmatic,
66    /// Replayed from a recorded macro.
67    Macro,
68    /// Triggered by an external system/API.
69    External,
70}
71
72/// Metadata attached to every command for tracing and UI display.
73#[derive(Debug, Clone)]
74pub struct CommandMetadata {
75    /// Human-readable description for UI (e.g., "Insert text").
76    pub description: String,
77    /// When the command was created, or for a merged command, when the last
78    /// command merged into it was.
79    pub timestamp: Instant,
80    /// Who/what triggered the command.
81    pub source: CommandSource,
82    /// Optional batch ID for grouping related commands.
83    pub batch_id: Option<u64>,
84}
85
86impl CommandMetadata {
87    /// Create new metadata with the given description.
88    #[must_use]
89    pub fn new(description: impl Into<String>) -> Self {
90        Self {
91            description: description.into(),
92            timestamp: Instant::now(),
93            source: CommandSource::User,
94            batch_id: None,
95        }
96    }
97
98    /// Set the command source.
99    #[must_use]
100    pub fn with_source(mut self, source: CommandSource) -> Self {
101        self.source = source;
102        self
103    }
104
105    /// Set the batch ID for grouping.
106    #[must_use]
107    pub fn with_batch(mut self, batch_id: u64) -> Self {
108        self.batch_id = Some(batch_id);
109        self
110    }
111
112    /// Size in bytes for memory accounting.
113    #[must_use]
114    pub fn size_bytes(&self) -> usize {
115        std::mem::size_of::<Self>() + self.description.len()
116    }
117}
118
119impl Default for CommandMetadata {
120    fn default() -> Self {
121        Self::new("Unknown")
122    }
123}
124
125/// Result of command execution or undo.
126///
127/// Commands may fail if targets are invalid or state has drifted.
128pub type CommandResult = Result<(), CommandError>;
129
130/// Errors that can occur during command execution.
131#[derive(Debug, Clone, PartialEq, Eq)]
132pub enum CommandError {
133    /// Target widget no longer exists.
134    TargetNotFound(WidgetId),
135    /// Position is out of bounds.
136    PositionOutOfBounds { position: usize, length: usize },
137    /// State has changed since command was created.
138    StateDrift { expected: String, actual: String },
139    /// Command cannot be executed in current state.
140    InvalidState(String),
141    /// Generic error with message.
142    Other(String),
143}
144
145impl fmt::Display for CommandError {
146    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
147        match self {
148            Self::TargetNotFound(id) => write!(f, "target widget {:?} not found", id),
149            Self::PositionOutOfBounds { position, length } => {
150                write!(f, "position {} out of bounds (length {})", position, length)
151            }
152            Self::StateDrift { expected, actual } => {
153                write!(f, "state drift: expected '{}', got '{}'", expected, actual)
154            }
155            Self::InvalidState(msg) => write!(f, "invalid state: {}", msg),
156            Self::Other(msg) => write!(f, "{}", msg),
157        }
158    }
159}
160
161impl std::error::Error for CommandError {}
162
163/// Configuration for command merging behavior.
164#[derive(Debug, Clone, Copy)]
165pub struct MergeConfig {
166    /// Maximum time between commands to allow merging (milliseconds).
167    pub max_delay_ms: u64,
168    /// Whether to merge across word boundaries.
169    pub merge_across_words: bool,
170    /// Maximum merged command size before forcing a split.
171    pub max_merged_size: usize,
172}
173
174impl Default for MergeConfig {
175    fn default() -> Self {
176        Self {
177            max_delay_ms: 500,
178            merge_across_words: false,
179            max_merged_size: 1024,
180        }
181    }
182}
183
184/// A reversible command that can be undone and redone.
185///
186/// Commands capture all state needed to execute, undo, and redo an operation.
187/// They support merging for batching related operations (like consecutive typing).
188pub trait UndoableCmd: Send + Sync {
189    /// Execute the command, applying its effect.
190    fn execute(&mut self) -> CommandResult;
191
192    /// Undo the command, reverting its effect.
193    fn undo(&mut self) -> CommandResult;
194
195    /// Redo the command after it was undone.
196    fn redo(&mut self) -> CommandResult {
197        self.execute()
198    }
199
200    /// Human-readable description for UI display.
201    fn description(&self) -> &str;
202
203    /// Size of this command in bytes for memory budgeting.
204    fn size_bytes(&self) -> usize;
205
206    /// Check if this command can merge with another.
207    fn can_merge(&self, _other: &dyn UndoableCmd, _config: &MergeConfig) -> bool {
208        false
209    }
210
211    /// Merge another command into this one.
212    ///
213    /// Returns the text to append if merging is possible.
214    /// The default implementation returns None (no merge).
215    fn merge_text(&self) -> Option<&str> {
216        None
217    }
218
219    /// Accept a merge from another command.
220    ///
221    /// The full command reference is passed to allow implementations to
222    /// extract position or other context needed for correct merge behavior.
223    fn accept_merge(&mut self, _other: &dyn UndoableCmd) -> bool {
224        false
225    }
226
227    /// Get the command metadata.
228    fn metadata(&self) -> &CommandMetadata;
229
230    /// Get the target widget ID, if any.
231    fn target(&self) -> Option<WidgetId> {
232        None
233    }
234
235    /// Downcast to concrete type for merging.
236    fn as_any(&self) -> &dyn Any;
237
238    /// Downcast to mutable concrete type for merging.
239    fn as_any_mut(&mut self) -> &mut dyn Any;
240
241    /// Debug description of the command.
242    fn debug_name(&self) -> &'static str {
243        "UndoableCmd"
244    }
245}
246
247impl fmt::Debug for dyn UndoableCmd {
248    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
249        f.debug_struct(self.debug_name())
250            .field("description", &self.description())
251            .field("size_bytes", &self.size_bytes())
252            .finish()
253    }
254}
255
256/// A batch of commands that execute and undo together.
257///
258/// Useful for operations that span multiple widgets or steps
259/// but should appear as a single undo entry.
260pub struct CommandBatch {
261    /// Commands in execution order.
262    commands: Vec<Box<dyn UndoableCmd>>,
263    /// Batch metadata.
264    metadata: CommandMetadata,
265    /// Index of last successfully executed command.
266    executed_to: usize,
267}
268
269impl fmt::Debug for CommandBatch {
270    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
271        f.debug_struct("CommandBatch")
272            .field("commands_count", &self.commands.len())
273            .field("metadata", &self.metadata)
274            .field("executed_to", &self.executed_to)
275            .finish()
276    }
277}
278
279impl CommandBatch {
280    /// Create a new command batch.
281    #[must_use]
282    pub fn new(description: impl Into<String>) -> Self {
283        Self {
284            commands: Vec::new(),
285            metadata: CommandMetadata::new(description),
286            executed_to: 0,
287        }
288    }
289
290    /// Add a command to the batch.
291    pub fn push(&mut self, cmd: Box<dyn UndoableCmd>) {
292        self.commands.push(cmd);
293    }
294
295    /// Add a pre-executed command to the batch.
296    ///
297    /// Use this for commands that have already been executed externally.
298    /// The command will be properly undone when the batch is undone.
299    pub fn push_executed(&mut self, cmd: Box<dyn UndoableCmd>) {
300        self.commands.push(cmd);
301        self.executed_to = self.commands.len();
302    }
303
304    /// Number of commands in the batch.
305    #[must_use]
306    pub fn len(&self) -> usize {
307        self.commands.len()
308    }
309
310    /// Check if the batch is empty.
311    #[must_use]
312    pub fn is_empty(&self) -> bool {
313        self.commands.is_empty()
314    }
315}
316
317impl UndoableCmd for CommandBatch {
318    fn execute(&mut self) -> CommandResult {
319        for (i, cmd) in self.commands.iter_mut().enumerate() {
320            if let Err(e) = cmd.execute() {
321                // Rollback executed commands on failure
322                for j in (0..i).rev() {
323                    let _ = self.commands[j].undo();
324                }
325                return Err(e);
326            }
327            self.executed_to = i + 1;
328        }
329        Ok(())
330    }
331
332    fn undo(&mut self) -> CommandResult {
333        // Undo in reverse order
334        for i in (0..self.executed_to).rev() {
335            self.commands[i].undo()?;
336        }
337        self.executed_to = 0;
338        Ok(())
339    }
340
341    fn redo(&mut self) -> CommandResult {
342        self.execute()
343    }
344
345    fn description(&self) -> &str {
346        &self.metadata.description
347    }
348
349    fn size_bytes(&self) -> usize {
350        std::mem::size_of::<Self>()
351            + self.metadata.size_bytes()
352            + self.commands.iter().map(|c| c.size_bytes()).sum::<usize>()
353    }
354
355    fn metadata(&self) -> &CommandMetadata {
356        &self.metadata
357    }
358
359    fn as_any(&self) -> &dyn Any {
360        self
361    }
362
363    fn as_any_mut(&mut self) -> &mut dyn Any {
364        self
365    }
366
367    fn debug_name(&self) -> &'static str {
368        "CommandBatch"
369    }
370}
371
372// ============================================================================
373// Built-in Text Commands
374// ============================================================================
375
376/// Callback type for applying text operations.
377pub type TextApplyFn = Box<dyn Fn(WidgetId, usize, &str) -> CommandResult + Send + Sync>;
378/// Callback type for removing text.
379pub type TextRemoveFn = Box<dyn Fn(WidgetId, usize, usize) -> CommandResult + Send + Sync>;
380/// Callback type for replacing text.
381pub type TextReplaceFn = Box<dyn Fn(WidgetId, usize, usize, &str) -> CommandResult + Send + Sync>;
382
383/// Command to insert text at a position.
384pub struct TextInsertCmd {
385    /// Target widget.
386    pub target: WidgetId,
387    /// Position to insert at (byte offset).
388    pub position: usize,
389    /// Text to insert.
390    pub text: String,
391    /// Command metadata.
392    pub metadata: CommandMetadata,
393    /// Callback to apply the insertion (set by the widget).
394    apply: Option<TextApplyFn>,
395    /// Callback to remove the insertion (set by the widget).
396    remove: Option<TextRemoveFn>,
397}
398
399impl fmt::Debug for TextInsertCmd {
400    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
401        f.debug_struct("TextInsertCmd")
402            .field("target", &self.target)
403            .field("position", &self.position)
404            .field("text", &self.text)
405            .field("metadata", &self.metadata)
406            .field("has_apply", &self.apply.is_some())
407            .field("has_remove", &self.remove.is_some())
408            .finish()
409    }
410}
411
412impl TextInsertCmd {
413    /// Create a new text insert command.
414    #[must_use]
415    pub fn new(target: WidgetId, position: usize, text: impl Into<String>) -> Self {
416        Self {
417            target,
418            position,
419            text: text.into(),
420            metadata: CommandMetadata::new("Insert text"),
421            apply: None,
422            remove: None,
423        }
424    }
425
426    /// Set the apply callback.
427    pub fn with_apply<F>(mut self, f: F) -> Self
428    where
429        F: Fn(WidgetId, usize, &str) -> CommandResult + Send + Sync + 'static,
430    {
431        self.apply = Some(Box::new(f));
432        self
433    }
434
435    /// Set the remove callback.
436    pub fn with_remove<F>(mut self, f: F) -> Self
437    where
438        F: Fn(WidgetId, usize, usize) -> CommandResult + Send + Sync + 'static,
439    {
440        self.remove = Some(Box::new(f));
441        self
442    }
443}
444
445impl UndoableCmd for TextInsertCmd {
446    fn execute(&mut self) -> CommandResult {
447        if let Some(ref apply) = self.apply {
448            apply(self.target, self.position, &self.text)
449        } else {
450            Err(CommandError::InvalidState(
451                "no apply callback set".to_string(),
452            ))
453        }
454    }
455
456    fn undo(&mut self) -> CommandResult {
457        if let Some(ref remove) = self.remove {
458            remove(self.target, self.position, self.text.len())
459        } else {
460            Err(CommandError::InvalidState(
461                "no remove callback set".to_string(),
462            ))
463        }
464    }
465
466    fn description(&self) -> &str {
467        &self.metadata.description
468    }
469
470    fn size_bytes(&self) -> usize {
471        std::mem::size_of::<Self>() + self.text.len() + self.metadata.size_bytes()
472    }
473
474    fn can_merge(&self, other: &dyn UndoableCmd, config: &MergeConfig) -> bool {
475        let Some(other) = other.as_any().downcast_ref::<Self>() else {
476            return false;
477        };
478
479        // Must target same widget
480        if self.target != other.target {
481            return false;
482        }
483
484        // Must be consecutive
485        if other.position != self.position + self.text.len() {
486            return false;
487        }
488
489        // Check time constraint
490        let elapsed = other
491            .metadata
492            .timestamp
493            .saturating_duration_since(self.metadata.timestamp);
494        if elapsed.as_millis() > config.max_delay_ms as u128 {
495            return false;
496        }
497
498        // Check size constraint
499        if self.text.len() + other.text.len() > config.max_merged_size {
500            return false;
501        }
502
503        // Don't merge across word boundaries unless configured
504        if !config.merge_across_words && self.text.ends_with(' ') {
505            return false;
506        }
507
508        true
509    }
510
511    fn merge_text(&self) -> Option<&str> {
512        Some(&self.text)
513    }
514
515    fn accept_merge(&mut self, other: &dyn UndoableCmd) -> bool {
516        let Some(other_insert) = other.as_any().downcast_ref::<Self>() else {
517            return false;
518        };
519        self.text.push_str(&other_insert.text);
520        // `max_delay_ms` is the gap between commands. Measured from the
521        // group's first command instead, steady typing split into a new
522        // undo step every 500ms however short the pauses.
523        self.metadata.timestamp = other_insert.metadata.timestamp;
524        true
525    }
526
527    fn metadata(&self) -> &CommandMetadata {
528        &self.metadata
529    }
530
531    fn target(&self) -> Option<WidgetId> {
532        Some(self.target)
533    }
534
535    fn as_any(&self) -> &dyn Any {
536        self
537    }
538
539    fn as_any_mut(&mut self) -> &mut dyn Any {
540        self
541    }
542
543    fn debug_name(&self) -> &'static str {
544        "TextInsertCmd"
545    }
546}
547
548/// Command to delete text at a position.
549pub struct TextDeleteCmd {
550    /// Target widget.
551    pub target: WidgetId,
552    /// Position to delete from (byte offset).
553    pub position: usize,
554    /// Deleted text (for undo).
555    pub deleted_text: String,
556    /// Command metadata.
557    pub metadata: CommandMetadata,
558    /// Callback to remove text.
559    remove: Option<TextRemoveFn>,
560    /// Callback to insert text (for undo).
561    insert: Option<TextApplyFn>,
562}
563
564impl fmt::Debug for TextDeleteCmd {
565    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
566        f.debug_struct("TextDeleteCmd")
567            .field("target", &self.target)
568            .field("position", &self.position)
569            .field("deleted_text", &self.deleted_text)
570            .field("metadata", &self.metadata)
571            .field("has_remove", &self.remove.is_some())
572            .field("has_insert", &self.insert.is_some())
573            .finish()
574    }
575}
576
577impl TextDeleteCmd {
578    /// Create a new text delete command.
579    #[must_use]
580    pub fn new(target: WidgetId, position: usize, deleted_text: impl Into<String>) -> Self {
581        Self {
582            target,
583            position,
584            deleted_text: deleted_text.into(),
585            metadata: CommandMetadata::new("Delete text"),
586            remove: None,
587            insert: None,
588        }
589    }
590
591    /// Set the remove callback.
592    pub fn with_remove<F>(mut self, f: F) -> Self
593    where
594        F: Fn(WidgetId, usize, usize) -> CommandResult + Send + Sync + 'static,
595    {
596        self.remove = Some(Box::new(f));
597        self
598    }
599
600    /// Set the insert callback (for undo).
601    pub fn with_insert<F>(mut self, f: F) -> Self
602    where
603        F: Fn(WidgetId, usize, &str) -> CommandResult + Send + Sync + 'static,
604    {
605        self.insert = Some(Box::new(f));
606        self
607    }
608}
609
610impl UndoableCmd for TextDeleteCmd {
611    fn execute(&mut self) -> CommandResult {
612        if let Some(ref remove) = self.remove {
613            remove(self.target, self.position, self.deleted_text.len())
614        } else {
615            Err(CommandError::InvalidState(
616                "no remove callback set".to_string(),
617            ))
618        }
619    }
620
621    fn undo(&mut self) -> CommandResult {
622        if let Some(ref insert) = self.insert {
623            insert(self.target, self.position, &self.deleted_text)
624        } else {
625            Err(CommandError::InvalidState(
626                "no insert callback set".to_string(),
627            ))
628        }
629    }
630
631    fn description(&self) -> &str {
632        &self.metadata.description
633    }
634
635    fn size_bytes(&self) -> usize {
636        std::mem::size_of::<Self>() + self.deleted_text.len() + self.metadata.size_bytes()
637    }
638
639    fn can_merge(&self, other: &dyn UndoableCmd, config: &MergeConfig) -> bool {
640        let Some(other) = other.as_any().downcast_ref::<Self>() else {
641            return false;
642        };
643
644        // Must target same widget
645        if self.target != other.target {
646            return false;
647        }
648
649        // For backspace: other.position + other.deleted_text.len() == self.position
650        // For delete key: other.position == self.position
651        let is_backspace = other.position + other.deleted_text.len() == self.position;
652        let is_delete = other.position == self.position;
653
654        if !is_backspace && !is_delete {
655            return false;
656        }
657
658        // Check time constraint
659        let elapsed = other
660            .metadata
661            .timestamp
662            .saturating_duration_since(self.metadata.timestamp);
663        if elapsed.as_millis() > config.max_delay_ms as u128 {
664            return false;
665        }
666
667        // Check size constraint
668        if self.deleted_text.len() + other.deleted_text.len() > config.max_merged_size {
669            return false;
670        }
671
672        true
673    }
674
675    fn merge_text(&self) -> Option<&str> {
676        Some(&self.deleted_text)
677    }
678
679    fn accept_merge(&mut self, other: &dyn UndoableCmd) -> bool {
680        let Some(other_delete) = other.as_any().downcast_ref::<Self>() else {
681            return false;
682        };
683
684        // Determine if this is a backspace or forward delete merge:
685        // - Backspace: other.position + other.deleted_text.len() == self.position
686        //   The new delete happened before our position, prepend its text
687        // - Forward delete: other.position == self.position
688        //   The new delete happened at the same position, append its text
689        let is_backspace = other_delete.position + other_delete.deleted_text.len() == self.position;
690        let is_forward = other_delete.position == self.position;
691        if !is_backspace && !is_forward {
692            return false;
693        }
694
695        if is_backspace {
696            // Backspace: prepend and move our position back
697            self.deleted_text = format!("{}{}", other_delete.deleted_text, self.deleted_text);
698            self.position = other_delete.position;
699        } else {
700            // Forward delete: append (text was after original deleted text)
701            self.deleted_text.push_str(&other_delete.deleted_text);
702        }
703        // The merge window runs from the latest delete, as for inserts.
704        self.metadata.timestamp = other_delete.metadata.timestamp;
705        true
706    }
707
708    fn metadata(&self) -> &CommandMetadata {
709        &self.metadata
710    }
711
712    fn target(&self) -> Option<WidgetId> {
713        Some(self.target)
714    }
715
716    fn as_any(&self) -> &dyn Any {
717        self
718    }
719
720    fn as_any_mut(&mut self) -> &mut dyn Any {
721        self
722    }
723
724    fn debug_name(&self) -> &'static str {
725        "TextDeleteCmd"
726    }
727}
728
729/// Command to replace text at a position.
730pub struct TextReplaceCmd {
731    /// Target widget.
732    pub target: WidgetId,
733    /// Position to replace at (byte offset).
734    pub position: usize,
735    /// Original text that was replaced.
736    pub old_text: String,
737    /// New text that replaced it.
738    pub new_text: String,
739    /// Command metadata.
740    pub metadata: CommandMetadata,
741    /// Callback to apply replacement.
742    replace: Option<TextReplaceFn>,
743}
744
745impl fmt::Debug for TextReplaceCmd {
746    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
747        f.debug_struct("TextReplaceCmd")
748            .field("target", &self.target)
749            .field("position", &self.position)
750            .field("old_text", &self.old_text)
751            .field("new_text", &self.new_text)
752            .field("metadata", &self.metadata)
753            .field("has_replace", &self.replace.is_some())
754            .finish()
755    }
756}
757
758impl TextReplaceCmd {
759    /// Create a new text replace command.
760    #[must_use]
761    pub fn new(
762        target: WidgetId,
763        position: usize,
764        old_text: impl Into<String>,
765        new_text: impl Into<String>,
766    ) -> Self {
767        Self {
768            target,
769            position,
770            old_text: old_text.into(),
771            new_text: new_text.into(),
772            metadata: CommandMetadata::new("Replace text"),
773            replace: None,
774        }
775    }
776
777    /// Set the replace callback.
778    pub fn with_replace<F>(mut self, f: F) -> Self
779    where
780        F: Fn(WidgetId, usize, usize, &str) -> CommandResult + Send + Sync + 'static,
781    {
782        self.replace = Some(Box::new(f));
783        self
784    }
785}
786
787impl UndoableCmd for TextReplaceCmd {
788    fn execute(&mut self) -> CommandResult {
789        if let Some(ref replace) = self.replace {
790            replace(
791                self.target,
792                self.position,
793                self.old_text.len(),
794                &self.new_text,
795            )
796        } else {
797            Err(CommandError::InvalidState(
798                "no replace callback set".to_string(),
799            ))
800        }
801    }
802
803    fn undo(&mut self) -> CommandResult {
804        if let Some(ref replace) = self.replace {
805            replace(
806                self.target,
807                self.position,
808                self.new_text.len(),
809                &self.old_text,
810            )
811        } else {
812            Err(CommandError::InvalidState(
813                "no replace callback set".to_string(),
814            ))
815        }
816    }
817
818    fn description(&self) -> &str {
819        &self.metadata.description
820    }
821
822    fn size_bytes(&self) -> usize {
823        std::mem::size_of::<Self>()
824            + self.old_text.len()
825            + self.new_text.len()
826            + self.metadata.size_bytes()
827    }
828
829    fn metadata(&self) -> &CommandMetadata {
830        &self.metadata
831    }
832
833    fn target(&self) -> Option<WidgetId> {
834        Some(self.target)
835    }
836
837    fn as_any(&self) -> &dyn Any {
838        self
839    }
840
841    fn as_any_mut(&mut self) -> &mut dyn Any {
842        self
843    }
844
845    fn debug_name(&self) -> &'static str {
846        "TextReplaceCmd"
847    }
848}
849
850// ============================================================================
851// Tests
852// ============================================================================
853
854#[cfg(test)]
855mod tests {
856    use super::*;
857    use std::sync::Arc;
858    use std::sync::Mutex;
859
860    #[test]
861    fn test_widget_id_creation() {
862        let id = WidgetId::new(42);
863        assert_eq!(id.raw(), 42);
864    }
865
866    #[test]
867    fn test_command_metadata_size() {
868        let meta = CommandMetadata::new("Test command");
869        let size = meta.size_bytes();
870        assert!(size > std::mem::size_of::<CommandMetadata>());
871        assert!(size >= std::mem::size_of::<CommandMetadata>() + "Test command".len());
872    }
873
874    #[test]
875    fn test_command_metadata_with_source() {
876        let meta = CommandMetadata::new("Test").with_source(CommandSource::Macro);
877        assert_eq!(meta.source, CommandSource::Macro);
878    }
879
880    #[test]
881    fn test_command_metadata_with_batch() {
882        let meta = CommandMetadata::new("Test").with_batch(123);
883        assert_eq!(meta.batch_id, Some(123));
884    }
885
886    #[test]
887    fn test_command_batch_execute_undo() {
888        // Create a simple test buffer
889        let buffer = Arc::new(Mutex::new(String::new()));
890
891        let mut batch = CommandBatch::new("Test batch");
892
893        // Add two insert commands with callbacks
894        let b1 = buffer.clone();
895        let b2 = buffer.clone();
896        let b3 = buffer.clone();
897        let b4 = buffer.clone();
898
899        let cmd1 = TextInsertCmd::new(WidgetId::new(1), 0, "Hello")
900            .with_apply(move |_, pos, text| {
901                let mut buf = b1.lock().unwrap();
902                buf.insert_str(pos, text);
903                Ok(())
904            })
905            .with_remove(move |_, pos, len| {
906                let mut buf = b2.lock().unwrap();
907                buf.drain(pos..pos + len);
908                Ok(())
909            });
910
911        let cmd2 = TextInsertCmd::new(WidgetId::new(1), 5, " World")
912            .with_apply(move |_, pos, text| {
913                let mut buf = b3.lock().unwrap();
914                buf.insert_str(pos, text);
915                Ok(())
916            })
917            .with_remove(move |_, pos, len| {
918                let mut buf = b4.lock().unwrap();
919                buf.drain(pos..pos + len);
920                Ok(())
921            });
922
923        batch.push(Box::new(cmd1));
924        batch.push(Box::new(cmd2));
925
926        // Execute batch
927        batch.execute().unwrap();
928        assert_eq!(*buffer.lock().unwrap(), "Hello World");
929
930        // Undo batch
931        batch.undo().unwrap();
932        assert_eq!(*buffer.lock().unwrap(), "");
933    }
934
935    #[test]
936    fn test_command_batch_empty() {
937        let batch = CommandBatch::new("Empty");
938        assert!(batch.is_empty());
939        assert_eq!(batch.len(), 0);
940    }
941
942    #[test]
943    fn test_text_insert_can_merge_consecutive() {
944        let cmd1 = TextInsertCmd::new(WidgetId::new(1), 0, "a");
945        let mut cmd2 = TextInsertCmd::new(WidgetId::new(1), 1, "b");
946        // Set timestamp to be within merge window
947        cmd2.metadata.timestamp = cmd1.metadata.timestamp;
948
949        let config = MergeConfig::default();
950        assert!(cmd1.can_merge(&cmd2, &config));
951    }
952
953    #[test]
954    fn steady_typing_merges_by_the_gap_between_keys() {
955        // Keys 400ms apart, inside the 500ms window. The window ran from the
956        // group's first key, so the third key started a new undo step.
957        let config = MergeConfig::default();
958        let t0 = Instant::now();
959        let step = web_time::Duration::from_millis(400);
960        let mut group = TextInsertCmd::new(WidgetId::new(1), 0, "a");
961        group.metadata.timestamp = t0;
962        for (i, ch) in ["b", "c", "d"].into_iter().enumerate() {
963            let mut next = TextInsertCmd::new(WidgetId::new(1), i + 1, ch);
964            next.metadata.timestamp = t0 + step * (i as u32 + 1);
965            assert!(group.can_merge(&next, &config), "key {ch}");
966            assert!(group.accept_merge(&next));
967        }
968        assert_eq!(group.text, "abcd");
969
970        // A real pause still starts a new step.
971        let mut late = TextInsertCmd::new(WidgetId::new(1), 4, "e");
972        late.metadata.timestamp = t0 + step * 3 + web_time::Duration::from_millis(600);
973        assert!(!group.can_merge(&late, &config));
974
975        // Same for a run of backspaces.
976        let mut deletes = TextDeleteCmd::new(WidgetId::new(1), 3, "d");
977        deletes.metadata.timestamp = t0;
978        for (i, ch) in ["c", "b", "a"].into_iter().enumerate() {
979            let mut next = TextDeleteCmd::new(WidgetId::new(1), 2 - i, ch);
980            next.metadata.timestamp = t0 + step * (i as u32 + 1);
981            assert!(deletes.can_merge(&next, &config), "backspace {ch}");
982            assert!(deletes.accept_merge(&next));
983        }
984        assert_eq!(deletes.deleted_text, "abcd");
985    }
986
987    #[test]
988    fn test_text_insert_no_merge_different_widget() {
989        let cmd1 = TextInsertCmd::new(WidgetId::new(1), 0, "a");
990        let mut cmd2 = TextInsertCmd::new(WidgetId::new(2), 1, "b");
991        cmd2.metadata.timestamp = cmd1.metadata.timestamp;
992
993        let config = MergeConfig::default();
994        assert!(!cmd1.can_merge(&cmd2, &config));
995    }
996
997    #[test]
998    fn test_text_insert_no_merge_non_consecutive() {
999        let cmd1 = TextInsertCmd::new(WidgetId::new(1), 0, "a");
1000        let mut cmd2 = TextInsertCmd::new(WidgetId::new(1), 5, "b");
1001        cmd2.metadata.timestamp = cmd1.metadata.timestamp;
1002
1003        let config = MergeConfig::default();
1004        assert!(!cmd1.can_merge(&cmd2, &config));
1005    }
1006
1007    #[test]
1008    fn test_text_delete_can_merge_backspace() {
1009        let cmd1 = TextDeleteCmd::new(WidgetId::new(1), 5, "b");
1010        let mut cmd2 = TextDeleteCmd::new(WidgetId::new(1), 4, "a");
1011        cmd2.metadata.timestamp = cmd1.metadata.timestamp;
1012
1013        let config = MergeConfig::default();
1014        assert!(cmd1.can_merge(&cmd2, &config));
1015    }
1016
1017    #[test]
1018    fn test_text_delete_can_merge_delete_key() {
1019        let cmd1 = TextDeleteCmd::new(WidgetId::new(1), 5, "a");
1020        let mut cmd2 = TextDeleteCmd::new(WidgetId::new(1), 5, "b");
1021        cmd2.metadata.timestamp = cmd1.metadata.timestamp;
1022
1023        let config = MergeConfig::default();
1024        assert!(cmd1.can_merge(&cmd2, &config));
1025    }
1026
1027    #[test]
1028    fn test_command_error_display() {
1029        let err = CommandError::TargetNotFound(WidgetId::new(42));
1030        assert!(err.to_string().contains("42"));
1031
1032        let err = CommandError::PositionOutOfBounds {
1033            position: 10,
1034            length: 5,
1035        };
1036        assert!(err.to_string().contains("10"));
1037        assert!(err.to_string().contains("5"));
1038    }
1039
1040    #[test]
1041    fn test_merge_config_default() {
1042        let config = MergeConfig::default();
1043        assert_eq!(config.max_delay_ms, 500);
1044        assert!(!config.merge_across_words);
1045        assert_eq!(config.max_merged_size, 1024);
1046    }
1047
1048    #[test]
1049    fn test_text_replace_size_bytes() {
1050        let cmd = TextReplaceCmd::new(WidgetId::new(1), 0, "old", "new");
1051        let size = cmd.size_bytes();
1052        assert!(size >= std::mem::size_of::<TextReplaceCmd>() + 3 + 3);
1053    }
1054
1055    #[test]
1056    fn test_text_insert_accept_merge() {
1057        let mut cmd1 = TextInsertCmd::new(WidgetId::new(1), 0, "Hello");
1058        let cmd2 = TextInsertCmd::new(WidgetId::new(1), 5, " World");
1059        assert!(cmd1.accept_merge(&cmd2));
1060        assert_eq!(cmd1.text, "Hello World");
1061    }
1062
1063    #[test]
1064    fn test_text_delete_accept_merge_backspace() {
1065        // Simulate backspace: user deleted "b" at position 4, then "a" at position 3
1066        // Backspace detection: other.position + other.len == self.position
1067        // 3 + 1 == 4, so this is backspace, should prepend
1068        let mut cmd1 = TextDeleteCmd::new(WidgetId::new(1), 4, "b");
1069        let cmd2 = TextDeleteCmd::new(WidgetId::new(1), 3, "a");
1070        assert!(cmd1.accept_merge(&cmd2));
1071        assert_eq!(cmd1.deleted_text, "ab");
1072        assert_eq!(cmd1.position, 3); // Position moves back for backspace
1073    }
1074
1075    #[test]
1076    fn test_text_delete_accept_merge_forward_delete() {
1077        // Simulate forward delete: user deleted "a" at position 3, then "b" at position 3
1078        // Forward delete detection: other.position == self.position
1079        // Both at position 3, so this is forward delete, should append
1080        let mut cmd1 = TextDeleteCmd::new(WidgetId::new(1), 3, "a");
1081        let cmd2 = TextDeleteCmd::new(WidgetId::new(1), 3, "b");
1082        assert!(cmd1.accept_merge(&cmd2));
1083        assert_eq!(cmd1.deleted_text, "ab");
1084        assert_eq!(cmd1.position, 3); // Position stays the same for forward delete
1085    }
1086
1087    #[test]
1088    fn test_debug_implementations() {
1089        let cmd = TextInsertCmd::new(WidgetId::new(1), 0, "test");
1090        let debug_str = format!("{:?}", cmd);
1091        assert!(debug_str.contains("TextInsertCmd"));
1092        assert!(debug_str.contains("test"));
1093
1094        let batch = CommandBatch::new("Test batch");
1095        let debug_str = format!("{:?}", batch);
1096        assert!(debug_str.contains("CommandBatch"));
1097    }
1098
1099    #[test]
1100    fn test_text_insert_execute_and_undo_with_callbacks() {
1101        let buf = Arc::new(Mutex::new(String::from("Hello")));
1102        let b1 = buf.clone();
1103        let b2 = buf.clone();
1104
1105        let mut cmd = TextInsertCmd::new(WidgetId::new(1), 5, " World")
1106            .with_apply(move |_, pos, text| {
1107                let mut b = b1.lock().unwrap();
1108                b.insert_str(pos, text);
1109                Ok(())
1110            })
1111            .with_remove(move |_, pos, len| {
1112                let mut b = b2.lock().unwrap();
1113                b.drain(pos..pos + len);
1114                Ok(())
1115            });
1116
1117        cmd.execute().unwrap();
1118        assert_eq!(*buf.lock().unwrap(), "Hello World");
1119        cmd.undo().unwrap();
1120        assert_eq!(*buf.lock().unwrap(), "Hello");
1121    }
1122
1123    #[test]
1124    fn test_text_insert_execute_without_callback_errors() {
1125        let mut cmd = TextInsertCmd::new(WidgetId::new(1), 0, "test");
1126        let err = cmd.execute().unwrap_err();
1127        assert!(matches!(err, CommandError::InvalidState(_)));
1128    }
1129
1130    #[test]
1131    fn test_text_insert_undo_without_callback_errors() {
1132        let mut cmd = TextInsertCmd::new(WidgetId::new(1), 0, "test");
1133        let err = cmd.undo().unwrap_err();
1134        assert!(matches!(err, CommandError::InvalidState(_)));
1135    }
1136
1137    #[test]
1138    fn test_text_insert_target() {
1139        let cmd = TextInsertCmd::new(WidgetId::new(42), 0, "x");
1140        assert_eq!(cmd.target(), Some(WidgetId::new(42)));
1141    }
1142
1143    #[test]
1144    fn test_text_insert_merge_text() {
1145        let cmd = TextInsertCmd::new(WidgetId::new(1), 0, "abc");
1146        assert_eq!(cmd.merge_text(), Some("abc"));
1147    }
1148
1149    #[test]
1150    fn test_text_delete_target() {
1151        let cmd = TextDeleteCmd::new(WidgetId::new(7), 0, "x");
1152        assert_eq!(cmd.target(), Some(WidgetId::new(7)));
1153    }
1154
1155    #[test]
1156    fn test_command_metadata_default() {
1157        let meta = CommandMetadata::default();
1158        assert_eq!(meta.description, "Unknown");
1159        assert_eq!(meta.source, CommandSource::User);
1160        assert_eq!(meta.batch_id, None);
1161    }
1162
1163    #[test]
1164    fn test_command_source_default_is_user() {
1165        assert_eq!(CommandSource::default(), CommandSource::User);
1166    }
1167
1168    #[test]
1169    fn test_command_error_state_drift_display() {
1170        let err = CommandError::StateDrift {
1171            expected: "foo".to_string(),
1172            actual: "bar".to_string(),
1173        };
1174        let s = err.to_string();
1175        assert!(s.contains("foo"));
1176        assert!(s.contains("bar"));
1177    }
1178
1179    #[test]
1180    fn test_command_error_other_display() {
1181        let err = CommandError::Other("something broke".to_string());
1182        assert!(err.to_string().contains("something broke"));
1183    }
1184
1185    #[test]
1186    fn test_command_batch_push_executed_tracks_index() {
1187        let buf = Arc::new(Mutex::new(String::new()));
1188        let b1 = buf.clone();
1189        let b2 = buf.clone();
1190
1191        // Pre-execute the command manually
1192        {
1193            let mut b = buf.lock().unwrap();
1194            b.push_str("Hi");
1195        }
1196
1197        let cmd = TextInsertCmd::new(WidgetId::new(1), 0, "Hi")
1198            .with_apply(move |_, pos, text| {
1199                let mut b = b1.lock().unwrap();
1200                b.insert_str(pos, text);
1201                Ok(())
1202            })
1203            .with_remove(move |_, pos, len| {
1204                let mut b = b2.lock().unwrap();
1205                b.drain(pos..pos + len);
1206                Ok(())
1207            });
1208
1209        let mut batch = CommandBatch::new("Pre-executed batch");
1210        batch.push_executed(Box::new(cmd));
1211        assert_eq!(batch.len(), 1);
1212        // Undo should work since push_executed advances executed_to
1213        batch.undo().unwrap();
1214        assert_eq!(*buf.lock().unwrap(), "");
1215    }
1216
1217    // ====================================================================
1218    // TextDeleteCmd execute/undo coverage
1219    // ====================================================================
1220
1221    #[test]
1222    fn test_text_delete_execute_and_undo_with_callbacks() {
1223        let buf = Arc::new(Mutex::new(String::from("Hello World")));
1224        let b1 = buf.clone();
1225        let b2 = buf.clone();
1226
1227        let mut cmd = TextDeleteCmd::new(WidgetId::new(1), 5, " World")
1228            .with_remove(move |_, pos, len| {
1229                let mut b = b1.lock().unwrap();
1230                b.drain(pos..pos + len);
1231                Ok(())
1232            })
1233            .with_insert(move |_, pos, text| {
1234                let mut b = b2.lock().unwrap();
1235                b.insert_str(pos, text);
1236                Ok(())
1237            });
1238
1239        cmd.execute().unwrap();
1240        assert_eq!(*buf.lock().unwrap(), "Hello");
1241
1242        cmd.undo().unwrap();
1243        assert_eq!(*buf.lock().unwrap(), "Hello World");
1244    }
1245
1246    #[test]
1247    fn test_text_delete_execute_without_callback_errors() {
1248        let mut cmd = TextDeleteCmd::new(WidgetId::new(1), 0, "x");
1249        let err = cmd.execute().unwrap_err();
1250        assert!(matches!(err, CommandError::InvalidState(_)));
1251    }
1252
1253    #[test]
1254    fn test_text_delete_undo_without_callback_errors() {
1255        let mut cmd = TextDeleteCmd::new(WidgetId::new(1), 0, "x");
1256        let err = cmd.undo().unwrap_err();
1257        assert!(matches!(err, CommandError::InvalidState(_)));
1258    }
1259
1260    #[test]
1261    fn test_text_delete_size_bytes() {
1262        let cmd = TextDeleteCmd::new(WidgetId::new(1), 0, "abc");
1263        let size = cmd.size_bytes();
1264        assert!(size >= std::mem::size_of::<TextDeleteCmd>() + 3);
1265    }
1266
1267    #[test]
1268    fn test_text_delete_description() {
1269        let cmd = TextDeleteCmd::new(WidgetId::new(1), 0, "x");
1270        assert_eq!(cmd.description(), "Delete text");
1271    }
1272
1273    #[test]
1274    fn test_text_delete_merge_text() {
1275        let cmd = TextDeleteCmd::new(WidgetId::new(1), 5, "xyz");
1276        assert_eq!(cmd.merge_text(), Some("xyz"));
1277    }
1278
1279    #[test]
1280    fn test_text_delete_debug() {
1281        let cmd = TextDeleteCmd::new(WidgetId::new(1), 3, "abc");
1282        let s = format!("{:?}", cmd);
1283        assert!(s.contains("TextDeleteCmd"));
1284        assert!(s.contains("abc"));
1285    }
1286
1287    #[test]
1288    fn test_text_delete_debug_name() {
1289        let cmd = TextDeleteCmd::new(WidgetId::new(1), 0, "x");
1290        assert_eq!(cmd.debug_name(), "TextDeleteCmd");
1291    }
1292
1293    // ====================================================================
1294    // TextDeleteCmd merge edge cases
1295    // ====================================================================
1296
1297    #[test]
1298    fn test_text_delete_no_merge_different_widget() {
1299        let cmd1 = TextDeleteCmd::new(WidgetId::new(1), 5, "a");
1300        let mut cmd2 = TextDeleteCmd::new(WidgetId::new(2), 5, "b");
1301        cmd2.metadata.timestamp = cmd1.metadata.timestamp;
1302
1303        let config = MergeConfig::default();
1304        assert!(!cmd1.can_merge(&cmd2, &config));
1305    }
1306
1307    #[test]
1308    fn test_text_delete_no_merge_non_adjacent() {
1309        let cmd1 = TextDeleteCmd::new(WidgetId::new(1), 5, "a");
1310        let mut cmd2 = TextDeleteCmd::new(WidgetId::new(1), 10, "b");
1311        cmd2.metadata.timestamp = cmd1.metadata.timestamp;
1312
1313        let config = MergeConfig::default();
1314        assert!(!cmd1.can_merge(&cmd2, &config));
1315    }
1316
1317    #[test]
1318    fn test_text_delete_no_merge_exceeds_max_size() {
1319        let long_text = "a".repeat(600);
1320        let cmd1 = TextDeleteCmd::new(WidgetId::new(1), 600, &long_text);
1321        let mut cmd2 = TextDeleteCmd::new(WidgetId::new(1), 600, &long_text);
1322        cmd2.metadata.timestamp = cmd1.metadata.timestamp;
1323
1324        let config = MergeConfig::default(); // max_merged_size = 1024
1325        assert!(!cmd1.can_merge(&cmd2, &config));
1326    }
1327
1328    #[test]
1329    fn test_text_delete_accept_merge_non_adjacent_returns_false() {
1330        let mut cmd1 = TextDeleteCmd::new(WidgetId::new(1), 5, "a");
1331        let cmd2 = TextDeleteCmd::new(WidgetId::new(1), 10, "b");
1332        assert!(!cmd1.accept_merge(&cmd2));
1333    }
1334
1335    #[test]
1336    fn test_text_delete_accept_merge_wrong_type_returns_false() {
1337        let mut cmd1 = TextDeleteCmd::new(WidgetId::new(1), 5, "a");
1338        let cmd2 = TextInsertCmd::new(WidgetId::new(1), 5, "b");
1339        assert!(!cmd1.accept_merge(&cmd2));
1340    }
1341
1342    // ====================================================================
1343    // TextInsertCmd merge edge cases
1344    // ====================================================================
1345
1346    #[test]
1347    fn test_text_insert_no_merge_across_word_boundary() {
1348        let cmd1 = TextInsertCmd::new(WidgetId::new(1), 0, "hello ");
1349        let mut cmd2 = TextInsertCmd::new(WidgetId::new(1), 6, "world");
1350        cmd2.metadata.timestamp = cmd1.metadata.timestamp;
1351
1352        let config = MergeConfig::default(); // merge_across_words = false
1353        assert!(!cmd1.can_merge(&cmd2, &config));
1354    }
1355
1356    #[test]
1357    fn test_text_insert_merge_across_word_boundary_when_configured() {
1358        let cmd1 = TextInsertCmd::new(WidgetId::new(1), 0, "hello ");
1359        let mut cmd2 = TextInsertCmd::new(WidgetId::new(1), 6, "world");
1360        cmd2.metadata.timestamp = cmd1.metadata.timestamp;
1361
1362        let config = MergeConfig {
1363            merge_across_words: true,
1364            ..MergeConfig::default()
1365        };
1366        assert!(cmd1.can_merge(&cmd2, &config));
1367    }
1368
1369    #[test]
1370    fn test_text_insert_no_merge_exceeds_max_size() {
1371        let long_text = "a".repeat(600);
1372        let cmd1 = TextInsertCmd::new(WidgetId::new(1), 0, &long_text);
1373        let mut cmd2 = TextInsertCmd::new(WidgetId::new(1), 600, &long_text);
1374        cmd2.metadata.timestamp = cmd1.metadata.timestamp;
1375
1376        let config = MergeConfig::default(); // max_merged_size = 1024
1377        assert!(!cmd1.can_merge(&cmd2, &config));
1378    }
1379
1380    #[test]
1381    fn test_text_insert_accept_merge_wrong_type_returns_false() {
1382        let mut cmd1 = TextInsertCmd::new(WidgetId::new(1), 0, "a");
1383        let cmd2 = TextDeleteCmd::new(WidgetId::new(1), 0, "b");
1384        assert!(!cmd1.accept_merge(&cmd2));
1385    }
1386
1387    #[test]
1388    fn test_text_insert_size_bytes() {
1389        let cmd = TextInsertCmd::new(WidgetId::new(1), 0, "hello");
1390        let size = cmd.size_bytes();
1391        assert!(size >= std::mem::size_of::<TextInsertCmd>() + 5);
1392    }
1393
1394    #[test]
1395    fn test_text_insert_description() {
1396        let cmd = TextInsertCmd::new(WidgetId::new(1), 0, "x");
1397        assert_eq!(cmd.description(), "Insert text");
1398    }
1399
1400    #[test]
1401    fn test_text_insert_debug_name() {
1402        let cmd = TextInsertCmd::new(WidgetId::new(1), 0, "x");
1403        assert_eq!(cmd.debug_name(), "TextInsertCmd");
1404    }
1405
1406    // ====================================================================
1407    // TextReplaceCmd full coverage
1408    // ====================================================================
1409
1410    #[test]
1411    fn test_text_replace_execute_and_undo_with_callbacks() {
1412        let buf = Arc::new(Mutex::new(String::from("Hello World")));
1413        let b1 = buf.clone();
1414
1415        let mut cmd = TextReplaceCmd::new(WidgetId::new(1), 6, "World", "Rust").with_replace(
1416            move |_, pos, old_len, new_text| {
1417                let mut b = b1.lock().unwrap();
1418                b.drain(pos..pos + old_len);
1419                b.insert_str(pos, new_text);
1420                Ok(())
1421            },
1422        );
1423
1424        // Also need clone for undo path (same callback)
1425        cmd.execute().unwrap();
1426        assert_eq!(*buf.lock().unwrap(), "Hello Rust");
1427
1428        cmd.undo().unwrap();
1429        assert_eq!(*buf.lock().unwrap(), "Hello World");
1430    }
1431
1432    #[test]
1433    fn test_text_replace_execute_without_callback_errors() {
1434        let mut cmd = TextReplaceCmd::new(WidgetId::new(1), 0, "old", "new");
1435        let err = cmd.execute().unwrap_err();
1436        assert!(matches!(err, CommandError::InvalidState(_)));
1437    }
1438
1439    #[test]
1440    fn test_text_replace_undo_without_callback_errors() {
1441        let mut cmd = TextReplaceCmd::new(WidgetId::new(1), 0, "old", "new");
1442        let err = cmd.undo().unwrap_err();
1443        assert!(matches!(err, CommandError::InvalidState(_)));
1444    }
1445
1446    #[test]
1447    fn test_text_replace_target() {
1448        let cmd = TextReplaceCmd::new(WidgetId::new(99), 0, "a", "b");
1449        assert_eq!(cmd.target(), Some(WidgetId::new(99)));
1450    }
1451
1452    #[test]
1453    fn test_text_replace_description() {
1454        let cmd = TextReplaceCmd::new(WidgetId::new(1), 0, "a", "b");
1455        assert_eq!(cmd.description(), "Replace text");
1456    }
1457
1458    #[test]
1459    fn test_text_replace_metadata() {
1460        let cmd = TextReplaceCmd::new(WidgetId::new(1), 0, "a", "b");
1461        assert_eq!(cmd.metadata().description, "Replace text");
1462        assert_eq!(cmd.metadata().source, CommandSource::User);
1463    }
1464
1465    #[test]
1466    fn test_text_replace_debug() {
1467        let cmd = TextReplaceCmd::new(WidgetId::new(1), 3, "old", "new");
1468        let s = format!("{:?}", cmd);
1469        assert!(s.contains("TextReplaceCmd"));
1470        assert!(s.contains("old"));
1471        assert!(s.contains("new"));
1472    }
1473
1474    #[test]
1475    fn test_text_replace_debug_name() {
1476        let cmd = TextReplaceCmd::new(WidgetId::new(1), 0, "a", "b");
1477        assert_eq!(cmd.debug_name(), "TextReplaceCmd");
1478    }
1479
1480    // ====================================================================
1481    // CommandBatch edge cases
1482    // ====================================================================
1483
1484    #[test]
1485    fn test_command_batch_execute_rollback_on_failure() {
1486        let buf = Arc::new(Mutex::new(String::new()));
1487        let b1 = buf.clone();
1488        let b2 = buf.clone();
1489
1490        let mut batch = CommandBatch::new("Rollback test");
1491
1492        // First command succeeds
1493        let cmd1 = TextInsertCmd::new(WidgetId::new(1), 0, "OK")
1494            .with_apply(move |_, pos, text| {
1495                let mut b = b1.lock().unwrap();
1496                b.insert_str(pos, text);
1497                Ok(())
1498            })
1499            .with_remove(move |_, pos, len| {
1500                let mut b = b2.lock().unwrap();
1501                b.drain(pos..pos + len);
1502                Ok(())
1503            });
1504
1505        // Second command always fails (no callback)
1506        let cmd2 = TextInsertCmd::new(WidgetId::new(1), 2, " FAIL");
1507
1508        batch.push(Box::new(cmd1));
1509        batch.push(Box::new(cmd2));
1510
1511        // Execute should fail
1512        let err = batch.execute().unwrap_err();
1513        assert!(matches!(err, CommandError::InvalidState(_)));
1514
1515        // First command should have been rolled back
1516        assert_eq!(*buf.lock().unwrap(), "");
1517    }
1518
1519    #[test]
1520    fn test_command_batch_redo() {
1521        let buf = Arc::new(Mutex::new(String::new()));
1522        let b1 = buf.clone();
1523        let b2 = buf.clone();
1524
1525        let mut batch = CommandBatch::new("Redo test");
1526        let cmd = TextInsertCmd::new(WidgetId::new(1), 0, "Hi")
1527            .with_apply(move |_, pos, text| {
1528                let mut b = b1.lock().unwrap();
1529                b.insert_str(pos, text);
1530                Ok(())
1531            })
1532            .with_remove(move |_, pos, len| {
1533                let mut b = b2.lock().unwrap();
1534                b.drain(pos..pos + len);
1535                Ok(())
1536            });
1537        batch.push(Box::new(cmd));
1538
1539        batch.execute().unwrap();
1540        assert_eq!(*buf.lock().unwrap(), "Hi");
1541
1542        batch.undo().unwrap();
1543        assert_eq!(*buf.lock().unwrap(), "");
1544
1545        batch.redo().unwrap();
1546        assert_eq!(*buf.lock().unwrap(), "Hi");
1547    }
1548
1549    #[test]
1550    fn test_command_batch_size_bytes() {
1551        let batch = CommandBatch::new("Size test");
1552        let size = batch.size_bytes();
1553        assert!(size >= std::mem::size_of::<CommandBatch>());
1554    }
1555
1556    #[test]
1557    fn test_command_batch_size_bytes_with_commands() {
1558        let mut batch = CommandBatch::new("Size test");
1559        batch.push(Box::new(TextInsertCmd::new(WidgetId::new(1), 0, "hello")));
1560        let size = batch.size_bytes();
1561        // Must include the inner command's size
1562        let inner_size = TextInsertCmd::new(WidgetId::new(1), 0, "hello").size_bytes();
1563        assert!(size > inner_size);
1564    }
1565
1566    #[test]
1567    fn test_command_batch_metadata() {
1568        let batch = CommandBatch::new("Meta test");
1569        assert_eq!(batch.metadata().description, "Meta test");
1570    }
1571
1572    #[test]
1573    fn test_command_batch_debug_name() {
1574        let batch = CommandBatch::new("test");
1575        assert_eq!(batch.debug_name(), "CommandBatch");
1576    }
1577
1578    #[test]
1579    fn test_command_batch_can_merge_default_false() {
1580        let batch = CommandBatch::new("test");
1581        let other = CommandBatch::new("other");
1582        let config = MergeConfig::default();
1583        assert!(!batch.can_merge(&other, &config));
1584    }
1585
1586    #[test]
1587    fn test_command_batch_undo_empty() {
1588        let mut batch = CommandBatch::new("Empty undo");
1589        // executed_to is 0, so undo should be a no-op
1590        batch.undo().unwrap();
1591    }
1592
1593    // ====================================================================
1594    // dyn UndoableCmd Debug impl
1595    // ====================================================================
1596
1597    #[test]
1598    fn test_dyn_undoable_cmd_debug() {
1599        let cmd: Box<dyn UndoableCmd> = Box::new(TextInsertCmd::new(WidgetId::new(1), 0, "test"));
1600        let s = format!("{:?}", cmd);
1601        assert!(s.contains("TextInsertCmd"));
1602        assert!(s.contains("Insert text"));
1603    }
1604
1605    // ====================================================================
1606    // CommandError trait coverage
1607    // ====================================================================
1608
1609    #[test]
1610    fn test_command_error_invalid_state_display() {
1611        let err = CommandError::InvalidState("bad state".to_string());
1612        let s = err.to_string();
1613        assert!(s.contains("bad state"));
1614    }
1615
1616    #[test]
1617    fn test_command_error_is_std_error() {
1618        let err: Box<dyn std::error::Error> = Box::new(CommandError::Other("test".to_string()));
1619        // Verify it implements std::error::Error
1620        assert!(err.to_string().contains("test"));
1621    }
1622
1623    // ====================================================================
1624    // WidgetId additional coverage
1625    // ====================================================================
1626
1627    #[test]
1628    fn test_widget_id_equality() {
1629        let a = WidgetId::new(1);
1630        let b = WidgetId::new(1);
1631        let c = WidgetId::new(2);
1632        assert_eq!(a, b);
1633        assert_ne!(a, c);
1634    }
1635
1636    #[test]
1637    fn test_widget_id_hash() {
1638        use std::collections::HashSet;
1639        let mut set = HashSet::new();
1640        set.insert(WidgetId::new(1));
1641        set.insert(WidgetId::new(1));
1642        set.insert(WidgetId::new(2));
1643        assert_eq!(set.len(), 2);
1644    }
1645
1646    #[test]
1647    fn test_widget_id_debug() {
1648        let id = WidgetId::new(42);
1649        let s = format!("{:?}", id);
1650        assert!(s.contains("42"));
1651    }
1652
1653    // ====================================================================
1654    // TextInsertCmd redo (default delegates to execute)
1655    // ====================================================================
1656
1657    #[test]
1658    fn test_text_insert_redo() {
1659        let buf = Arc::new(Mutex::new(String::new()));
1660        let b1 = buf.clone();
1661        let b2 = buf.clone();
1662
1663        let mut cmd = TextInsertCmd::new(WidgetId::new(1), 0, "Hi")
1664            .with_apply(move |_, pos, text| {
1665                let mut b = b1.lock().unwrap();
1666                b.insert_str(pos, text);
1667                Ok(())
1668            })
1669            .with_remove(move |_, pos, len| {
1670                let mut b = b2.lock().unwrap();
1671                b.drain(pos..pos + len);
1672                Ok(())
1673            });
1674
1675        cmd.execute().unwrap();
1676        cmd.undo().unwrap();
1677        assert_eq!(*buf.lock().unwrap(), "");
1678
1679        cmd.redo().unwrap();
1680        assert_eq!(*buf.lock().unwrap(), "Hi");
1681    }
1682
1683    // ====================================================================
1684    // TextDeleteCmd redo
1685    // ====================================================================
1686
1687    #[test]
1688    fn test_text_delete_redo() {
1689        let buf = Arc::new(Mutex::new(String::from("Hello")));
1690        let b1 = buf.clone();
1691        let b2 = buf.clone();
1692
1693        let mut cmd = TextDeleteCmd::new(WidgetId::new(1), 0, "Hello")
1694            .with_remove(move |_, pos, len| {
1695                let mut b = b1.lock().unwrap();
1696                b.drain(pos..pos + len);
1697                Ok(())
1698            })
1699            .with_insert(move |_, pos, text| {
1700                let mut b = b2.lock().unwrap();
1701                b.insert_str(pos, text);
1702                Ok(())
1703            });
1704
1705        cmd.execute().unwrap();
1706        assert_eq!(*buf.lock().unwrap(), "");
1707
1708        cmd.undo().unwrap();
1709        assert_eq!(*buf.lock().unwrap(), "Hello");
1710
1711        cmd.redo().unwrap();
1712        assert_eq!(*buf.lock().unwrap(), "");
1713    }
1714
1715    // ====================================================================
1716    // CommandMetadata edge cases
1717    // ====================================================================
1718
1719    #[test]
1720    fn test_command_metadata_all_sources() {
1721        for source in [
1722            CommandSource::User,
1723            CommandSource::Programmatic,
1724            CommandSource::Macro,
1725            CommandSource::External,
1726        ] {
1727            let meta = CommandMetadata::new("test").with_source(source);
1728            assert_eq!(meta.source, source);
1729        }
1730    }
1731
1732    #[test]
1733    fn test_command_metadata_empty_description() {
1734        let meta = CommandMetadata::new("");
1735        assert_eq!(meta.size_bytes(), std::mem::size_of::<CommandMetadata>());
1736    }
1737
1738    // ====================================================================
1739    // as_any / as_any_mut coverage
1740    // ====================================================================
1741
1742    #[test]
1743    fn test_text_insert_as_any_roundtrip() {
1744        let cmd = TextInsertCmd::new(WidgetId::new(1), 0, "x");
1745        let any_ref = cmd.as_any();
1746        let downcasted = any_ref.downcast_ref::<TextInsertCmd>().unwrap();
1747        assert_eq!(downcasted.text, "x");
1748    }
1749
1750    #[test]
1751    fn test_text_insert_as_any_mut_roundtrip() {
1752        let mut cmd = TextInsertCmd::new(WidgetId::new(1), 0, "x");
1753        let downcasted = cmd.as_any_mut().downcast_mut::<TextInsertCmd>().unwrap();
1754        downcasted.text = "modified".to_string();
1755        assert_eq!(cmd.text, "modified");
1756    }
1757
1758    #[test]
1759    fn test_text_delete_as_any_roundtrip() {
1760        let cmd = TextDeleteCmd::new(WidgetId::new(1), 0, "abc");
1761        let downcasted = cmd.as_any().downcast_ref::<TextDeleteCmd>().unwrap();
1762        assert_eq!(downcasted.deleted_text, "abc");
1763    }
1764
1765    #[test]
1766    fn test_text_delete_as_any_mut_roundtrip() {
1767        let mut cmd = TextDeleteCmd::new(WidgetId::new(1), 0, "abc");
1768        let downcasted = cmd.as_any_mut().downcast_mut::<TextDeleteCmd>().unwrap();
1769        downcasted.deleted_text = "xyz".to_string();
1770        assert_eq!(cmd.deleted_text, "xyz");
1771    }
1772
1773    #[test]
1774    fn test_text_replace_as_any_roundtrip() {
1775        let cmd = TextReplaceCmd::new(WidgetId::new(1), 0, "a", "b");
1776        let downcasted = cmd.as_any().downcast_ref::<TextReplaceCmd>().unwrap();
1777        assert_eq!(downcasted.old_text, "a");
1778        assert_eq!(downcasted.new_text, "b");
1779    }
1780
1781    #[test]
1782    fn test_text_replace_as_any_mut_roundtrip() {
1783        let mut cmd = TextReplaceCmd::new(WidgetId::new(1), 0, "a", "b");
1784        let downcasted = cmd.as_any_mut().downcast_mut::<TextReplaceCmd>().unwrap();
1785        downcasted.new_text = "replaced".to_string();
1786        assert_eq!(cmd.new_text, "replaced");
1787    }
1788
1789    #[test]
1790    fn test_command_batch_as_any_roundtrip() {
1791        let batch = CommandBatch::new("test batch");
1792        let downcasted = batch.as_any().downcast_ref::<CommandBatch>().unwrap();
1793        assert_eq!(downcasted.description(), "test batch");
1794    }
1795
1796    #[test]
1797    fn test_command_batch_as_any_mut_roundtrip() {
1798        let mut batch = CommandBatch::new("test batch");
1799        batch.push(Box::new(TextInsertCmd::new(WidgetId::new(1), 0, "x")));
1800        let downcasted = batch.as_any_mut().downcast_mut::<CommandBatch>().unwrap();
1801        assert_eq!(downcasted.len(), 1);
1802    }
1803
1804    // ====================================================================
1805    // Default trait methods on CommandBatch (UndoableCmd defaults)
1806    // ====================================================================
1807
1808    #[test]
1809    fn test_command_batch_description_matches() {
1810        let batch = CommandBatch::new("My description");
1811        assert_eq!(batch.description(), "My description");
1812    }
1813
1814    #[test]
1815    fn test_command_batch_merge_text_default_none() {
1816        let batch = CommandBatch::new("test");
1817        assert_eq!(batch.merge_text(), None);
1818    }
1819
1820    #[test]
1821    fn test_command_batch_accept_merge_default_false() {
1822        let mut batch = CommandBatch::new("test");
1823        let other = CommandBatch::new("other");
1824        assert!(!batch.accept_merge(&other));
1825    }
1826
1827    #[test]
1828    fn test_command_batch_target_default_none() {
1829        let batch = CommandBatch::new("test");
1830        assert_eq!(batch.target(), None);
1831    }
1832
1833    // ====================================================================
1834    // Cross-type can_merge rejection
1835    // ====================================================================
1836
1837    #[test]
1838    fn test_text_insert_can_merge_rejects_delete_type() {
1839        let cmd1 = TextInsertCmd::new(WidgetId::new(1), 0, "a");
1840        let cmd2 = TextDeleteCmd::new(WidgetId::new(1), 0, "b");
1841        let config = MergeConfig::default();
1842        assert!(!cmd1.can_merge(&cmd2, &config));
1843    }
1844
1845    #[test]
1846    fn test_text_delete_can_merge_rejects_insert_type() {
1847        let cmd1 = TextDeleteCmd::new(WidgetId::new(1), 0, "a");
1848        let cmd2 = TextInsertCmd::new(WidgetId::new(1), 0, "b");
1849        let config = MergeConfig::default();
1850        assert!(!cmd1.can_merge(&cmd2, &config));
1851    }
1852
1853    // ====================================================================
1854    // Time constraint failures for can_merge
1855    // ====================================================================
1856
1857    #[test]
1858    fn test_text_insert_no_merge_time_exceeded() {
1859        let cmd1 = TextInsertCmd::new(WidgetId::new(1), 0, "a");
1860        // cmd2 created after cmd1, with a large enough delay
1861        // We can't easily create a large time gap, but we can test
1862        // the boundary by using a config with max_delay_ms = 0
1863        let mut cmd2 = TextInsertCmd::new(WidgetId::new(1), 1, "b");
1864        // Even with same timestamp, max_delay_ms=0 should reject if any time passed
1865        // Set timestamps equal so the duration is 0ms — but config allows 0ms max
1866        cmd2.metadata.timestamp = cmd1.metadata.timestamp;
1867
1868        let config = MergeConfig {
1869            max_delay_ms: 0,
1870            merge_across_words: true,
1871            max_merged_size: 1024,
1872        };
1873        // 0 elapsed <= 0 max: should still pass (0 <= 0 is not >)
1874        assert!(cmd1.can_merge(&cmd2, &config));
1875    }
1876
1877    #[test]
1878    fn test_text_delete_no_merge_time_exceeded() {
1879        let cmd1 = TextDeleteCmd::new(WidgetId::new(1), 5, "a");
1880        let mut cmd2 = TextDeleteCmd::new(WidgetId::new(1), 4, "b");
1881        cmd2.metadata.timestamp = cmd1.metadata.timestamp;
1882
1883        let config = MergeConfig {
1884            max_delay_ms: 0,
1885            merge_across_words: true,
1886            max_merged_size: 1024,
1887        };
1888        // 0 elapsed, 0 max: 0 > 0 is false, so merge allowed
1889        assert!(cmd1.can_merge(&cmd2, &config));
1890    }
1891
1892    // ====================================================================
1893    // TextReplaceCmd redo (default delegates to execute)
1894    // ====================================================================
1895
1896    #[test]
1897    fn test_text_replace_redo() {
1898        let buf = Arc::new(Mutex::new(String::from("Hello World")));
1899        let b1 = buf.clone();
1900
1901        let mut cmd = TextReplaceCmd::new(WidgetId::new(1), 6, "World", "Rust").with_replace(
1902            move |_, pos, old_len, new_text| {
1903                let mut b = b1.lock().unwrap();
1904                b.replace_range(pos..pos + old_len, new_text);
1905                Ok(())
1906            },
1907        );
1908
1909        cmd.execute().unwrap();
1910        assert_eq!(*buf.lock().unwrap(), "Hello Rust");
1911
1912        cmd.undo().unwrap();
1913        assert_eq!(*buf.lock().unwrap(), "Hello World");
1914
1915        cmd.redo().unwrap();
1916        assert_eq!(*buf.lock().unwrap(), "Hello Rust");
1917    }
1918
1919    // ====================================================================
1920    // CommandBatch execute on empty
1921    // ====================================================================
1922
1923    #[test]
1924    fn test_command_batch_execute_empty_is_noop() {
1925        let mut batch = CommandBatch::new("Empty execute");
1926        assert!(batch.execute().is_ok());
1927        assert_eq!(batch.executed_to, 0);
1928    }
1929
1930    // ====================================================================
1931    // CommandBatch multiple push_executed
1932    // ====================================================================
1933
1934    #[test]
1935    fn test_command_batch_multiple_push_executed() {
1936        let mut batch = CommandBatch::new("Multi pre-exec");
1937        batch.push_executed(Box::new(TextInsertCmd::new(WidgetId::new(1), 0, "a")));
1938        batch.push_executed(Box::new(TextInsertCmd::new(WidgetId::new(1), 1, "b")));
1939        assert_eq!(batch.len(), 2);
1940        assert_eq!(batch.executed_to, 2);
1941    }
1942
1943    // ====================================================================
1944    // CommandError clone and equality
1945    // ====================================================================
1946
1947    #[test]
1948    fn test_command_error_clone_and_equality() {
1949        let err1 = CommandError::TargetNotFound(WidgetId::new(5));
1950        let err2 = err1.clone();
1951        assert_eq!(err1, err2);
1952
1953        let err3 = CommandError::PositionOutOfBounds {
1954            position: 10,
1955            length: 5,
1956        };
1957        let err4 = err3.clone();
1958        assert_eq!(err3, err4);
1959    }
1960
1961    // ====================================================================
1962    // MergeConfig clone and copy
1963    // ====================================================================
1964
1965    #[test]
1966    fn test_merge_config_clone_and_copy() {
1967        let config = MergeConfig {
1968            max_delay_ms: 1000,
1969            merge_across_words: true,
1970            max_merged_size: 2048,
1971        };
1972        let config2 = config;
1973        assert_eq!(config2.max_delay_ms, 1000);
1974        assert!(config2.merge_across_words);
1975        assert_eq!(config2.max_merged_size, 2048);
1976    }
1977
1978    // ====================================================================
1979    // WidgetId copy semantics
1980    // ====================================================================
1981
1982    #[test]
1983    fn test_widget_id_copy() {
1984        let a = WidgetId::new(42);
1985        let b = a; // Copy
1986        assert_eq!(a, b); // original still usable
1987        assert_eq!(a.raw(), 42);
1988    }
1989
1990    // ====================================================================
1991    // CommandMetadata clone
1992    // ====================================================================
1993
1994    #[test]
1995    fn test_command_metadata_clone() {
1996        let meta = CommandMetadata::new("test")
1997            .with_source(CommandSource::Programmatic)
1998            .with_batch(99);
1999        let cloned = meta.clone();
2000        assert_eq!(cloned.description, "test");
2001        assert_eq!(cloned.source, CommandSource::Programmatic);
2002        assert_eq!(cloned.batch_id, Some(99));
2003    }
2004}