cell-sheet-tui 0.5.0

A terminal spreadsheet editor with Vim-like keybindings
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
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
use cell_sheet_core::model::CellPos;

/// Logical region a screen coordinate maps to. Built by [`hit_test`] from
/// a [`GridLayout`] published by the render layer.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MouseTarget {
    Cell(CellPos),
    ColHeader(usize),
    RowHeader(usize),
    Outside,
}

/// Geometry snapshot of the most recent grid render. Built by
/// `render::grid::Grid::render` and stashed on `App` so the next mouse
/// event can hit-test against accurate coordinates.
#[derive(Debug, Clone)]
pub struct GridLayout {
    /// Top-left corner of the grid widget (in terminal cells).
    pub x: u16,
    pub y: u16,
    pub width: u16,
    pub height: u16,
    /// Width of the row-number gutter on the left edge of the grid.
    pub row_num_width: u16,
    /// Height of the column-header row at the top of the grid.
    pub header_height: u16,
    /// `viewport.row_offset` at render time.
    pub row_offset: usize,
    /// Visible columns in left-to-right order: `(col_index, screen_x, width)`.
    pub visible_cols: Vec<(usize, u16, u16)>,
}

/// Map a terminal coordinate to a [`MouseTarget`]. Pure.
pub fn hit_test(layout: &GridLayout, x: u16, y: u16) -> MouseTarget {
    let in_x = x >= layout.x && x < layout.x + layout.width;
    let in_y = y >= layout.y && y < layout.y + layout.height;
    if !in_x || !in_y {
        return MouseTarget::Outside;
    }

    let row_num_x_end = layout.x + layout.row_num_width;
    let header_y_end = layout.y + layout.header_height;
    let in_gutter = x < row_num_x_end;
    let in_header = y < header_y_end;

    if in_gutter && in_header {
        return MouseTarget::Outside;
    }
    if in_header {
        for &(col, cx, cw) in &layout.visible_cols {
            if x >= cx && x < cx + cw {
                return MouseTarget::ColHeader(col);
            }
        }
        return MouseTarget::Outside;
    }
    if in_gutter {
        let row_offset_y = y - header_y_end;
        return MouseTarget::RowHeader(layout.row_offset + row_offset_y as usize);
    }

    let row_offset_y = y - header_y_end;
    let row = layout.row_offset + row_offset_y as usize;
    for &(col, cx, cw) in &layout.visible_cols {
        if x >= cx && x < cx + cw {
            return MouseTarget::Cell((row, col));
        }
    }
    MouseTarget::Outside
}

use crate::action::{Action, Mode};
use crate::app::App;
use crossterm::event::{KeyModifiers, MouseButton, MouseEvent, MouseEventKind};
use std::time::{Duration, Instant};

pub const DOUBLE_CLICK_MS: u64 = 400;

pub const MOUSE_SCROLL_LINES: i32 = 3;

#[derive(Debug, Default)]
pub struct MouseState {
    pub drag: MouseDragState,
    pub last_click: Option<LastClick>,
}

#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum MouseDragState {
    #[default]
    Idle,
    DraggingCells {
        anchor: CellPos,
    },
    DraggingColumns {
        anchor_col: usize,
    },
    DraggingRows {
        anchor_row: usize,
    },
}

#[derive(Debug, Clone, Copy)]
pub struct LastClick {
    pub at: Instant,
    pub pos: CellPos,
}

impl MouseState {
    pub fn new() -> Self {
        Self::default()
    }
}

/// Translate a single `MouseEvent` into an `Action`. The handler is the
/// only place that mutates `state` (drag tracking, double-click history).
/// `app` and `layout` are read-only; the handler does not own selection
/// or cursor mutations — those live in `App::process_action`.
pub fn handle_mouse_event(
    event: MouseEvent,
    state: &mut MouseState,
    _app: &App,
    layout: Option<&GridLayout>,
) -> Action {
    if event.modifiers.contains(KeyModifiers::SHIFT) {
        return Action::Noop;
    }
    let layout = match layout {
        Some(l) => l,
        None => return Action::Noop,
    };
    let target = hit_test(layout, event.column, event.row);

    match event.kind {
        MouseEventKind::Down(MouseButton::Left) => match target {
            MouseTarget::Cell(pos) => {
                let now = Instant::now();
                let is_double = state
                    .last_click
                    .map(|lc| {
                        lc.pos == pos
                            && now.duration_since(lc.at) <= Duration::from_millis(DOUBLE_CLICK_MS)
                    })
                    .unwrap_or(false);
                if is_double {
                    state.drag = MouseDragState::Idle;
                    state.last_click = None;
                    Action::ChangeMode(Mode::Insert)
                } else {
                    state.drag = MouseDragState::DraggingCells { anchor: pos };
                    state.last_click = Some(LastClick { at: now, pos });
                    Action::MouseClickCell(pos)
                }
            }
            MouseTarget::ColHeader(c) => {
                state.drag = MouseDragState::DraggingColumns { anchor_col: c };
                state.last_click = None;
                Action::MouseSelectColumn(c)
            }
            MouseTarget::RowHeader(r) => {
                state.drag = MouseDragState::DraggingRows { anchor_row: r };
                state.last_click = None;
                Action::MouseSelectRow(r)
            }
            _ => Action::Noop,
        },
        MouseEventKind::Drag(MouseButton::Left) => {
            if state.drag == MouseDragState::Idle {
                return Action::Noop;
            }
            // Edge auto-scroll: a drag landing outside the grid in
            // the direction of motion advances the viewport one step.
            // The user keeps holding the drag; the next event lands
            // inside the freshly-revealed row/column and the
            // per-drag-state matcher below extends the selection
            // normally. Edge sensitivity is per drag mode: cell drags
            // scroll on all four edges, column drags only on the
            // right edge, and row drags only on the bottom edge. The
            // header band and gutter are the natural anchor surfaces
            // for column/row drags, so scrolling there would make it
            // impossible to drag back to a column/row the user
            // already passed.
            let grid_bottom = layout.y + layout.height;
            let grid_right = layout.x + layout.width;
            let header_y_end = layout.y + layout.header_height;
            let row_num_x_end = layout.x + layout.row_num_width;
            match state.drag {
                MouseDragState::DraggingCells { .. } => {
                    if event.row >= grid_bottom {
                        return Action::MouseScroll { dx: 0, dy: 1 };
                    }
                    if event.row < header_y_end {
                        return Action::MouseScroll { dx: 0, dy: -1 };
                    }
                    if event.column >= grid_right {
                        return Action::MouseScroll { dx: 1, dy: 0 };
                    }
                    if event.column < row_num_x_end {
                        return Action::MouseScroll { dx: -1, dy: 0 };
                    }
                }
                MouseDragState::DraggingColumns { .. } => {
                    if event.column >= grid_right {
                        return Action::MouseScroll { dx: 1, dy: 0 };
                    }
                }
                MouseDragState::DraggingRows { .. } => {
                    if event.row >= grid_bottom {
                        return Action::MouseScroll { dx: 0, dy: 1 };
                    }
                }
                MouseDragState::Idle => {}
            }
            match state.drag {
                MouseDragState::DraggingCells { .. } => match target {
                    MouseTarget::Cell(pos) => Action::MouseDragTo(pos),
                    _ => Action::Noop,
                },
                MouseDragState::DraggingColumns { .. } => match target {
                    MouseTarget::ColHeader(c) | MouseTarget::Cell((_, c)) => {
                        Action::MouseSelectColumn(c)
                    }
                    _ => Action::Noop,
                },
                MouseDragState::DraggingRows { .. } => match target {
                    MouseTarget::RowHeader(r) | MouseTarget::Cell((r, _)) => {
                        Action::MouseSelectRow(r)
                    }
                    _ => Action::Noop,
                },
                MouseDragState::Idle => Action::Noop,
            }
        }
        MouseEventKind::Up(MouseButton::Left) => {
            state.drag = MouseDragState::Idle;
            Action::Noop
        }
        MouseEventKind::ScrollDown => Action::MouseScroll {
            dx: 0,
            dy: MOUSE_SCROLL_LINES,
        },
        MouseEventKind::ScrollUp => Action::MouseScroll {
            dx: 0,
            dy: -MOUSE_SCROLL_LINES,
        },
        MouseEventKind::ScrollLeft => Action::MouseScroll {
            dx: -MOUSE_SCROLL_LINES,
            dy: 0,
        },
        MouseEventKind::ScrollRight => Action::MouseScroll {
            dx: MOUSE_SCROLL_LINES,
            dy: 0,
        },
        _ => Action::Noop,
    }
}

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

    fn fixture() -> GridLayout {
        // Grid at (0, 1) with 1-row header, row-number gutter of width 5.
        // Three visible columns of widths 10, 12, 8 starting at x = 6 (after
        // the gutter), with a 1-byte separator between each column (so col 1
        // starts at x = 17, col 2 at x = 30).
        GridLayout {
            x: 0,
            y: 1,
            width: 40,
            height: 10,
            row_num_width: 5,
            header_height: 1,
            row_offset: 0,
            visible_cols: vec![(0, 6, 10), (1, 17, 12), (2, 30, 8)],
        }
    }

    #[test]
    fn click_in_cell() {
        // x=8 is in column 0 (6..16), y=3 is in row 1 (after header at y=1).
        assert_eq!(hit_test(&fixture(), 8, 3), MouseTarget::Cell((1, 0)));
    }

    #[test]
    fn click_in_column_header() {
        // y=1 is the header row.
        assert_eq!(hit_test(&fixture(), 18, 1), MouseTarget::ColHeader(1));
    }

    #[test]
    fn click_in_row_header() {
        // x=2 is in the gutter, y=4 is row 2 (header_y_end=2 → row_offset_y=2).
        assert_eq!(hit_test(&fixture(), 2, 4), MouseTarget::RowHeader(2));
    }

    #[test]
    fn click_top_left_corner_is_outside() {
        assert_eq!(hit_test(&fixture(), 2, 1), MouseTarget::Outside);
    }

    #[test]
    fn click_outside_grid_widget() {
        // y=0 is above the grid widget.
        assert_eq!(hit_test(&fixture(), 8, 0), MouseTarget::Outside);
    }

    #[test]
    fn click_in_padding_right_of_last_visible_col() {
        // Last visible col ends at x=37 (30+8-1); x=39 is in padding.
        assert_eq!(hit_test(&fixture(), 39, 3), MouseTarget::Outside);
    }

    #[test]
    fn click_below_last_rendered_row() {
        // Layout height is 10, so y=11 is outside.
        assert_eq!(hit_test(&fixture(), 8, 11), MouseTarget::Outside);
    }

    #[test]
    fn click_uses_per_column_widths() {
        // Column 1 has width 12 (17..29). x=27 must hit col 1, not col 2.
        // y=5 → row_offset_y = 5 - 2 = 3.
        assert_eq!(hit_test(&fixture(), 27, 5), MouseTarget::Cell((3, 1)));
    }

    #[test]
    fn click_with_nonzero_row_offset() {
        let mut layout = fixture();
        layout.row_offset = 100;
        // y=2 → row_offset_y = 2 - 2 = 0 → row 100
        assert_eq!(hit_test(&layout, 8, 2), MouseTarget::Cell((100, 0)));
    }

    #[test]
    fn click_in_inter_column_gap_is_outside() {
        // x=16 sits between col 0 (6..16) and col 1 (17..29).
        assert_eq!(hit_test(&fixture(), 16, 3), MouseTarget::Outside);
    }

    use crate::action::Action;
    use crate::app::App;
    use crossterm::event::{KeyModifiers, MouseButton, MouseEvent, MouseEventKind};

    fn synth(kind: MouseEventKind, x: u16, y: u16) -> MouseEvent {
        MouseEvent {
            kind,
            column: x,
            row: y,
            modifiers: KeyModifiers::NONE,
        }
    }

    #[test]
    fn fresh_mouse_state_is_idle() {
        let s = MouseState::new();
        assert_eq!(s.drag, MouseDragState::Idle);
        assert!(s.last_click.is_none());
    }

    #[test]
    fn down_left_on_cell_in_normal_emits_click() {
        let app = App::new();
        let mut state = MouseState::new();
        let layout = fixture();
        let event = synth(MouseEventKind::Down(MouseButton::Left), 8, 3);
        assert_eq!(
            handle_mouse_event(event, &mut state, &app, Some(&layout)),
            Action::MouseClickCell((1, 0))
        );
        assert_eq!(state.drag, MouseDragState::DraggingCells { anchor: (1, 0) });
    }

    #[test]
    fn shift_click_is_noop_for_terminal_passthrough() {
        let app = App::new();
        let mut state = MouseState::new();
        let layout = fixture();
        let event = MouseEvent {
            kind: MouseEventKind::Down(MouseButton::Left),
            column: 8,
            row: 3,
            modifiers: KeyModifiers::SHIFT,
        };
        assert_eq!(
            handle_mouse_event(event, &mut state, &app, Some(&layout)),
            Action::Noop
        );
        // Shift-click must NOT arm a drag.
        assert_eq!(state.drag, MouseDragState::Idle);
    }

    #[test]
    fn down_left_with_no_layout_is_noop() {
        let app = App::new();
        let mut state = MouseState::new();
        let event = synth(MouseEventKind::Down(MouseButton::Left), 8, 3);
        assert_eq!(
            handle_mouse_event(event, &mut state, &app, None),
            Action::Noop
        );
    }

    #[test]
    fn up_left_clears_drag_state() {
        let app = App::new();
        let mut state = MouseState::new();
        state.drag = MouseDragState::DraggingCells { anchor: (1, 0) };
        let layout = fixture();
        let event = synth(MouseEventKind::Up(MouseButton::Left), 8, 3);
        let _ = handle_mouse_event(event, &mut state, &app, Some(&layout));
        assert_eq!(state.drag, MouseDragState::Idle);
    }

    #[test]
    fn drag_after_down_emits_drag_to() {
        let app = App::new();
        let mut state = MouseState::new();
        let layout = fixture();
        let down = synth(MouseEventKind::Down(MouseButton::Left), 8, 3);
        handle_mouse_event(down, &mut state, &app, Some(&layout));
        let drag = synth(MouseEventKind::Drag(MouseButton::Left), 18, 5);
        assert_eq!(
            handle_mouse_event(drag, &mut state, &app, Some(&layout)),
            Action::MouseDragTo((3, 1))
        );
    }

    #[test]
    fn drag_without_down_is_noop() {
        let app = App::new();
        let mut state = MouseState::new();
        let layout = fixture();
        let drag = synth(MouseEventKind::Drag(MouseButton::Left), 18, 5);
        assert_eq!(
            handle_mouse_event(drag, &mut state, &app, Some(&layout)),
            Action::Noop
        );
    }

    #[test]
    fn drag_into_formula_bar_scrolls_up() {
        let app = App::new();
        let mut state = MouseState::new();
        let layout = fixture();
        let down = synth(MouseEventKind::Down(MouseButton::Left), 8, 3);
        handle_mouse_event(down, &mut state, &app, Some(&layout));
        // y=0 is above the grid (in the formula bar region), which the
        // edge auto-scroll logic treats as "past the top".
        let drag = synth(MouseEventKind::Drag(MouseButton::Left), 8, 0);
        assert_eq!(
            handle_mouse_event(drag, &mut state, &app, Some(&layout)),
            Action::MouseScroll { dx: 0, dy: -1 }
        );
    }

    #[test]
    fn click_then_drag_moves_cursor_to_target() {
        let mut app = App::new();
        app.process_action(Action::MouseClickCell((1, 0)));
        app.process_action(Action::MouseDragTo((3, 2)));
        assert_eq!(app.cursor, (3, 2));
    }

    #[test]
    fn down_on_column_header_emits_select_column() {
        let app = App::new();
        let mut state = MouseState::new();
        let layout = fixture();
        // x=18, y=1 → ColHeader(1).
        let event = synth(MouseEventKind::Down(MouseButton::Left), 18, 1);
        assert_eq!(
            handle_mouse_event(event, &mut state, &app, Some(&layout)),
            Action::MouseSelectColumn(1)
        );
        assert_eq!(
            state.drag,
            MouseDragState::DraggingColumns { anchor_col: 1 }
        );
    }

    #[test]
    fn drag_in_column_mode_extends_to_other_column() {
        let app = App::new();
        let mut state = MouseState::new();
        let layout = fixture();
        handle_mouse_event(
            synth(MouseEventKind::Down(MouseButton::Left), 18, 1),
            &mut state,
            &app,
            Some(&layout),
        );
        // x=32, y=5 → Cell(_, 2). Drag from col 1 to col 2.
        let drag = synth(MouseEventKind::Drag(MouseButton::Left), 32, 5);
        assert_eq!(
            handle_mouse_event(drag, &mut state, &app, Some(&layout)),
            Action::MouseSelectColumn(2)
        );
    }

    #[test]
    fn drag_in_column_mode_back_to_header_extends() {
        let app = App::new();
        let mut state = MouseState::new();
        let layout = fixture();
        handle_mouse_event(
            synth(MouseEventKind::Down(MouseButton::Left), 18, 1),
            &mut state,
            &app,
            Some(&layout),
        );
        // x=32, y=1 → ColHeader(2).
        let drag = synth(MouseEventKind::Drag(MouseButton::Left), 32, 1);
        assert_eq!(
            handle_mouse_event(drag, &mut state, &app, Some(&layout)),
            Action::MouseSelectColumn(2)
        );
    }

    #[test]
    fn down_on_row_header_emits_select_row() {
        let app = App::new();
        let mut state = MouseState::new();
        let layout = fixture();
        // x=2 is the gutter, y=4 → row_offset_y = 2 → row 2.
        let event = synth(MouseEventKind::Down(MouseButton::Left), 2, 4);
        assert_eq!(
            handle_mouse_event(event, &mut state, &app, Some(&layout)),
            Action::MouseSelectRow(2)
        );
        assert_eq!(state.drag, MouseDragState::DraggingRows { anchor_row: 2 });
    }

    #[test]
    fn drag_in_row_mode_extends_to_other_row() {
        let app = App::new();
        let mut state = MouseState::new();
        let layout = fixture();
        handle_mouse_event(
            synth(MouseEventKind::Down(MouseButton::Left), 2, 4),
            &mut state,
            &app,
            Some(&layout),
        );
        // x=8, y=6 → Cell((4, 0)). Drag from row 2 to row 4.
        let drag = synth(MouseEventKind::Drag(MouseButton::Left), 8, 6);
        assert_eq!(
            handle_mouse_event(drag, &mut state, &app, Some(&layout)),
            Action::MouseSelectRow(4)
        );
    }

    #[test]
    fn drag_in_row_mode_back_to_gutter_extends() {
        let app = App::new();
        let mut state = MouseState::new();
        let layout = fixture();
        handle_mouse_event(
            synth(MouseEventKind::Down(MouseButton::Left), 2, 4),
            &mut state,
            &app,
            Some(&layout),
        );
        // x=2 is gutter, y=6 → row 4 → RowHeader(4).
        let drag = synth(MouseEventKind::Drag(MouseButton::Left), 2, 6);
        assert_eq!(
            handle_mouse_event(drag, &mut state, &app, Some(&layout)),
            Action::MouseSelectRow(4)
        );
    }

    #[test]
    fn scroll_down_emits_positive_dy() {
        let app = App::new();
        let mut state = MouseState::new();
        let layout = fixture();
        let event = synth(MouseEventKind::ScrollDown, 8, 3);
        assert_eq!(
            handle_mouse_event(event, &mut state, &app, Some(&layout)),
            Action::MouseScroll { dx: 0, dy: 3 }
        );
    }

    #[test]
    fn scroll_up_emits_negative_dy() {
        let app = App::new();
        let mut state = MouseState::new();
        let layout = fixture();
        let event = synth(MouseEventKind::ScrollUp, 8, 3);
        assert_eq!(
            handle_mouse_event(event, &mut state, &app, Some(&layout)),
            Action::MouseScroll { dx: 0, dy: -3 }
        );
    }

    #[test]
    fn scroll_left_emits_negative_dx() {
        let app = App::new();
        let mut state = MouseState::new();
        let layout = fixture();
        let event = synth(MouseEventKind::ScrollLeft, 8, 3);
        assert_eq!(
            handle_mouse_event(event, &mut state, &app, Some(&layout)),
            Action::MouseScroll { dx: -3, dy: 0 }
        );
    }

    #[test]
    fn scroll_right_emits_positive_dx() {
        let app = App::new();
        let mut state = MouseState::new();
        let layout = fixture();
        let event = synth(MouseEventKind::ScrollRight, 8, 3);
        assert_eq!(
            handle_mouse_event(event, &mut state, &app, Some(&layout)),
            Action::MouseScroll { dx: 3, dy: 0 }
        );
    }

    #[test]
    fn scroll_does_not_move_cursor() {
        let mut app = App::new();
        app.cursor = (5, 2);
        app.process_action(Action::MouseScroll { dx: 0, dy: 3 });
        assert_eq!(app.cursor, (5, 2));
        assert_eq!(app.viewport.row_offset, 3);
    }

    #[test]
    fn scroll_up_at_top_saturates_to_zero() {
        let mut app = App::new();
        // viewport starts at row_offset=0; scrolling up should saturate.
        app.process_action(Action::MouseScroll { dx: 0, dy: -10 });
        assert_eq!(app.viewport.row_offset, 0);
    }

    #[test]
    fn drag_past_bottom_emits_scroll_down() {
        let app = App::new();
        let mut state = MouseState::new();
        let layout = fixture();
        // Arm DraggingCells first.
        handle_mouse_event(
            synth(MouseEventKind::Down(MouseButton::Left), 8, 3),
            &mut state,
            &app,
            Some(&layout),
        );
        // Layout: y=1, height=10 → grid_bottom = 11. y=11 is past the bottom.
        let drag = synth(MouseEventKind::Drag(MouseButton::Left), 8, 11);
        assert_eq!(
            handle_mouse_event(drag, &mut state, &app, Some(&layout)),
            Action::MouseScroll { dx: 0, dy: 1 }
        );
    }

    #[test]
    fn drag_past_top_emits_scroll_up() {
        let app = App::new();
        let mut state = MouseState::new();
        let layout = fixture();
        handle_mouse_event(
            synth(MouseEventKind::Down(MouseButton::Left), 8, 3),
            &mut state,
            &app,
            Some(&layout),
        );
        // Layout: y=1, header_height=1 → header_y_end = 2. y=1 is in header
        // (above the data rows), which counts as "past the top" for drag purposes.
        let drag = synth(MouseEventKind::Drag(MouseButton::Left), 8, 1);
        assert_eq!(
            handle_mouse_event(drag, &mut state, &app, Some(&layout)),
            Action::MouseScroll { dx: 0, dy: -1 }
        );
    }

    #[test]
    fn drag_past_right_emits_scroll_right() {
        let app = App::new();
        let mut state = MouseState::new();
        let layout = fixture();
        handle_mouse_event(
            synth(MouseEventKind::Down(MouseButton::Left), 8, 3),
            &mut state,
            &app,
            Some(&layout),
        );
        // Layout: x=0, width=40 → grid_right = 40. x=40 is past.
        let drag = synth(MouseEventKind::Drag(MouseButton::Left), 40, 5);
        assert_eq!(
            handle_mouse_event(drag, &mut state, &app, Some(&layout)),
            Action::MouseScroll { dx: 1, dy: 0 }
        );
    }

    #[test]
    fn drag_past_left_into_gutter_emits_scroll_left() {
        let app = App::new();
        let mut state = MouseState::new();
        let layout = fixture();
        handle_mouse_event(
            synth(MouseEventKind::Down(MouseButton::Left), 8, 3),
            &mut state,
            &app,
            Some(&layout),
        );
        // Layout: x=0, row_num_width=5 → row_num_x_end = 5. x=4 is in gutter.
        let drag = synth(MouseEventKind::Drag(MouseButton::Left), 4, 5);
        assert_eq!(
            handle_mouse_event(drag, &mut state, &app, Some(&layout)),
            Action::MouseScroll { dx: -1, dy: 0 }
        );
    }

    #[test]
    fn click_in_insert_committed_cell_then_moves() {
        // Simulate Task 11's run_loop logic by hand: commit Insert
        // edit, then dispatch MouseClickCell.
        let mut app = App::new();
        app.mode = crate::action::Mode::Insert;
        app.cursor = (0, 0);
        app.insert_buffer = "hello".to_string();

        let pos = app.cursor;
        let buf = std::mem::take(&mut app.insert_buffer);
        app.process_action(Action::EditCell(pos, buf));
        app.mode = crate::action::Mode::Normal;
        app.process_action(Action::MouseClickCell((3, 5)));

        assert_eq!(app.cursor, (3, 5));
        assert_eq!(app.mode, crate::action::Mode::Normal);
        assert_eq!(
            app.sheet.get_cell((0, 0)).map(|c| c.raw.clone()),
            Some("hello".into()),
            "buffer should have been committed"
        );
    }

    #[test]
    fn click_in_visual_records_last_visual_for_gv() {
        // Simulate Task 11's Visual-exit branch: snapshot last_visual
        // BEFORE clearing visual_state, so a later `gv` can re-enter.
        use crate::action::Mode;
        use crate::mode::visual::{VisualKind, VisualState};

        let mut app = App::new();
        app.cursor = (4, 6);
        app.mode = Mode::Visual;
        let vs = VisualState::new((2, 3), VisualKind::Character);

        // The exact two lines the run_loop performs on a click in Visual:
        app.record_last_visual(vs.anchor, vs.kind);
        app.mode = Mode::Normal;
        // ...and then the click action is dispatched:
        app.process_action(Action::MouseClickCell((9, 9)));

        let lv = app.last_visual.expect("last_visual must be recorded");
        assert_eq!(lv.anchor, (2, 3));
        // cursor snapshot must capture the pre-click position, not the
        // post-click position.
        assert_eq!(lv.cursor, (4, 6));
        assert_eq!(lv.kind, VisualKind::Character);
        assert_eq!(app.cursor, (9, 9));
        assert_eq!(app.mode, Mode::Normal);
    }

    #[test]
    fn double_click_enters_insert_mode() {
        use crate::action::Mode;
        let app = App::new();
        let mut state = MouseState::new();
        let layout = fixture();
        let event = synth(MouseEventKind::Down(MouseButton::Left), 8, 3);
        let _ = handle_mouse_event(event, &mut state, &app, Some(&layout));
        let event2 = synth(MouseEventKind::Down(MouseButton::Left), 8, 3);
        assert_eq!(
            handle_mouse_event(event2, &mut state, &app, Some(&layout)),
            Action::ChangeMode(Mode::Insert)
        );
    }

    #[test]
    fn click_then_different_cell_is_two_singles() {
        let app = App::new();
        let mut state = MouseState::new();
        let layout = fixture();
        let _ = handle_mouse_event(
            synth(MouseEventKind::Down(MouseButton::Left), 8, 3),
            &mut state,
            &app,
            Some(&layout),
        );
        let event2 = synth(MouseEventKind::Down(MouseButton::Left), 18, 5);
        assert_eq!(
            handle_mouse_event(event2, &mut state, &app, Some(&layout)),
            Action::MouseClickCell((3, 1))
        );
    }

    #[test]
    fn double_click_clears_drag_and_last_click() {
        // After firing the double-click action, no stale drag/last_click
        // should linger so a subsequent third click is a fresh single
        // click, not a triple-click.
        use crate::action::Mode;
        let app = App::new();
        let mut state = MouseState::new();
        let layout = fixture();
        let _ = handle_mouse_event(
            synth(MouseEventKind::Down(MouseButton::Left), 8, 3),
            &mut state,
            &app,
            Some(&layout),
        );
        let _ = handle_mouse_event(
            synth(MouseEventKind::Down(MouseButton::Left), 8, 3),
            &mut state,
            &app,
            Some(&layout),
        );
        // After the double-click:
        assert_eq!(state.drag, MouseDragState::Idle);
        assert!(state.last_click.is_none());
        // A third click on the same cell is a fresh single click,
        // because last_click was cleared.
        let third = synth(MouseEventKind::Down(MouseButton::Left), 8, 3);
        assert_eq!(
            handle_mouse_event(third, &mut state, &app, Some(&layout)),
            Action::MouseClickCell((1, 0))
        );
        // And it now has Mode::Insert in scope so the test compiles.
        let _ = Mode::Insert;
    }

    #[test]
    fn click_in_command_clears_prompt_and_returns_to_normal() {
        // Simulate Task 11's Command-cancel branch for the colon prompt.
        use crate::action::{CommandKind, Mode};

        let mut app = App::new();
        app.mode = Mode::Command;
        app.command.enter(CommandKind::Colon);
        app.command.line = "se".into();
        app.command.history_idx = Some(0);
        app.command.history_scratch = "abc".into();

        // The mouse-cancel branch (colon path):
        app.command.reset_history_browse();
        app.command.clear_line();
        app.mode = Mode::Normal;
        app.process_action(Action::MouseClickCell((1, 1)));

        assert_eq!(app.mode, Mode::Normal);
        assert!(app.command.line.is_empty());
        assert!(app.command.history_idx.is_none());
        assert!(app.command.history_scratch.is_empty());
        assert_eq!(app.cursor, (1, 1));
    }

    #[test]
    fn double_click_after_long_insert_does_not_panic() {
        // Regression: double-click → ChangeMode(Insert) must initialize
        // insert_cursor against the new cell's content length, not carry
        // a stale value from a prior Insert session. Without the fix in
        // run_loop's Event::Mouse arm, typing after this sequence would
        // panic with `byte index N is out of bounds`.
        //
        // We can't drive run_loop directly from a unit test, but we can
        // reproduce the state machine and verify that App's insert_buffer
        // is rewritten from the new cell's raw on ChangeMode(Insert),
        // which is what the run_loop initializer reads from.
        use crate::action::Mode;
        let mut app = App::new();
        // First Insert: long content at A1.
        app.sheet.set_cell((0, 0), "hello world more");
        // Simulate Esc-out: app.mode is whatever; we just need cell B5
        // to have shorter content.
        app.sheet.set_cell((4, 1), "hi");
        // Cursor is now (4, 1) (as if a click + double-click landed it there).
        app.cursor = (4, 1);
        // ChangeMode(Insert) populates insert_buffer from app.cursor's cell.
        app.process_action(Action::ChangeMode(Mode::Insert));
        assert_eq!(app.insert_buffer, "hi");
        // The run_loop initializer would set insert_cursor to
        // sheet.get_cell(cursor).map(|c| c.raw.len()).unwrap_or(0).
        // For cell (4, 1) with raw "hi", that's 2.
        let new_insert_cursor = app
            .sheet
            .get_cell(app.cursor)
            .map(|c| c.raw.len())
            .unwrap_or(0);
        assert_eq!(new_insert_cursor, 2);
    }

    #[test]
    fn column_drag_past_right_edge_scrolls_right() {
        let app = App::new();
        let mut state = MouseState::new();
        let layout = fixture();
        // Down on a column header to arm DraggingColumns.
        handle_mouse_event(
            synth(MouseEventKind::Down(MouseButton::Left), 18, 1),
            &mut state,
            &app,
            Some(&layout),
        );
        // Drag past the right edge (grid right = x=40).
        let drag = synth(MouseEventKind::Drag(MouseButton::Left), 40, 1);
        assert_eq!(
            handle_mouse_event(drag, &mut state, &app, Some(&layout)),
            Action::MouseScroll { dx: 1, dy: 0 }
        );
    }

    #[test]
    fn row_drag_past_bottom_edge_scrolls_down() {
        let app = App::new();
        let mut state = MouseState::new();
        let layout = fixture();
        // Down on a row header to arm DraggingRows.
        handle_mouse_event(
            synth(MouseEventKind::Down(MouseButton::Left), 2, 4),
            &mut state,
            &app,
            Some(&layout),
        );
        // Drag past the bottom edge (grid bottom = y=11).
        let drag = synth(MouseEventKind::Drag(MouseButton::Left), 2, 11);
        assert_eq!(
            handle_mouse_event(drag, &mut state, &app, Some(&layout)),
            Action::MouseScroll { dx: 0, dy: 1 }
        );
    }

    #[test]
    fn select_column_keeps_cursor_at_top_not_bottom() {
        let mut app = App::new();
        // Populate enough rows that "last_row" is non-trivially != 0.
        for r in 0..5 {
            app.sheet.set_cell((r, 2), "x");
        }
        app.process_action(Action::MouseSelectColumn(2));
        // Cursor must be at the TOP of the column (row 0), not the
        // bottom — otherwise the highlighted cell sits at the far end
        // of the selection instead of where the user clicked.
        assert_eq!(app.cursor, (0, 2));
    }

    #[test]
    fn select_row_keeps_cursor_at_left_not_right() {
        let mut app = App::new();
        for c in 0..5 {
            app.sheet.set_cell((3, c), "x");
        }
        app.process_action(Action::MouseSelectRow(3));
        // Cursor must be at the LEFTMOST cell of the row (col 0), not
        // the right edge.
        assert_eq!(app.cursor, (3, 0));
    }
}