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
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
#[cfg(test)]
mod unit {
use super::super::highlight::{
extract_line_text_range, highlight_columns, patch_cursor_highlight,
};
use super::super::state::{MarkdownViewState, VisualMode, VisualRange};
use crate::markdown::{DocBlock, HeadingAnchor, LinkInfo, TextBlockId};
use ratatui::text::{Line, Span, Text};
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
// ── VisualRange ──────────────────────────────────────────────────────────
/// Helper to build a line-mode `VisualRange` for tests that only care about
/// line containment (no column logic).
fn line_range(anchor: u32, cursor: u32) -> VisualRange {
VisualRange {
mode: VisualMode::Line,
anchor_line: anchor,
anchor_col: 0,
cursor_line: cursor,
cursor_col: 0,
}
}
/// A selection anchored at 3 with cursor at 5 should contain 3, 4, 5 and
/// exclude lines outside the range.
#[test]
fn visual_range_contains_inclusive() {
let r = line_range(3, 5);
assert!(r.contains(3), "should contain anchor");
assert!(r.contains(4), "should contain middle");
assert!(r.contains(5), "should contain cursor");
assert!(!r.contains(2), "should not contain below anchor");
assert!(!r.contains(6), "should not contain above cursor");
}
/// A reversed selection (anchor > cursor) should behave identically because
/// `top_line()`/`bottom_line()` normalise the direction.
#[test]
fn visual_range_contains_reversed() {
let r = line_range(5, 3);
assert!(r.contains(3));
assert!(r.contains(4));
assert!(r.contains(5));
assert!(!r.contains(2));
assert!(!r.contains(6));
}
// ── load clears visual_mode ──────────────────────────────────────────────
#[test]
fn load_clears_visual_mode() {
use crate::theme::{Palette, Theme};
let palette = Palette::from_theme(Theme::Default);
let mut view = MarkdownViewState {
visual_mode: Some(line_range(2, 4)),
..Default::default()
};
view.load(
std::path::PathBuf::from("/fake/test.md"),
"test.md".to_string(),
"hello\nworld\n".to_string(),
&palette,
Theme::Default,
);
assert_eq!(view.visual_mode, None, "load() must clear visual_mode");
}
// ── cursor_down / cursor_up extend visual range ─────────────────────────
#[test]
fn cursor_down_in_visual_mode_extends_range() {
let mut v = MarkdownViewState {
total_lines: 10,
cursor_line: 3,
visual_mode: Some(line_range(3, 3)),
..Default::default()
};
v.cursor_down(2);
let range = v.visual_mode.unwrap();
assert_eq!(range.anchor_line, 3, "anchor must stay fixed");
assert_eq!(range.cursor_line, 5, "cursor must extend down");
}
#[test]
fn cursor_up_in_visual_mode_extends_range() {
let mut v = MarkdownViewState {
total_lines: 10,
cursor_line: 5,
visual_mode: Some(line_range(5, 5)),
..Default::default()
};
v.cursor_up(3);
let range = v.visual_mode.unwrap();
assert_eq!(range.anchor_line, 5, "anchor must stay fixed");
assert_eq!(range.cursor_line, 2, "cursor must move up");
}
// ── highlight_columns ────────────────────────────────────────────────────
/// Full-line highlight: start=0, end=width → every span gets bg patched.
#[test]
fn highlight_columns_full_line() {
use ratatui::style::Color;
let bg = Color::Rgb(100, 0, 0);
let line = Line::from(vec![Span::raw("hello"), Span::raw(" world")]);
let result = highlight_columns(&line, 0, 11, bg);
for span in &result.spans {
assert_eq!(span.style.bg, Some(bg), "all spans must carry bg");
}
}
/// Partial single-span selection should produce (before, highlighted, after).
#[test]
fn highlight_columns_partial_single_span() {
use ratatui::style::Color;
let bg = Color::Rgb(0, 100, 0);
// "hello" is 5 cells wide; select cols 1..=3 → "ell"
let line = Line::from(Span::raw("hello"));
let result = highlight_columns(&line, 1, 4, bg);
// Expect: "h" (no bg), "ell" (bg), "o" (no bg)
assert_eq!(result.spans.len(), 3, "must split into 3 spans");
assert_eq!(result.spans[0].content.as_ref(), "h");
assert_eq!(result.spans[0].style.bg, None);
assert_eq!(result.spans[1].content.as_ref(), "ell");
assert_eq!(result.spans[1].style.bg, Some(bg));
assert_eq!(result.spans[2].content.as_ref(), "o");
assert_eq!(result.spans[2].style.bg, None);
}
/// Selection across two spans: each span's base style must be preserved on
/// the non-selected portion and patched with bg on the selected portion.
#[test]
fn highlight_columns_across_spans() {
use ratatui::style::{Color, Style};
let bg = Color::Rgb(0, 0, 200);
let s1 = Style::default().fg(Color::Red);
let s2 = Style::default().fg(Color::Green);
// "abc" (3) + "def" (3) = 6 cols total; select cols 1..5 → "bcde"
let line = Line::from(vec![Span::styled("abc", s1), Span::styled("def", s2)]);
let result = highlight_columns(&line, 1, 5, bg);
// Expect: "a"(s1), "bc"(s1+bg), "de"(s2+bg), "f"(s2)
assert_eq!(result.spans.len(), 4);
assert_eq!(result.spans[0].content.as_ref(), "a");
assert_eq!(result.spans[0].style.fg, Some(Color::Red));
assert_eq!(result.spans[0].style.bg, None);
assert_eq!(result.spans[1].content.as_ref(), "bc");
assert_eq!(result.spans[1].style.bg, Some(bg));
assert_eq!(result.spans[2].content.as_ref(), "de");
assert_eq!(result.spans[2].style.bg, Some(bg));
assert_eq!(result.spans[3].content.as_ref(), "f");
assert_eq!(result.spans[3].style.fg, Some(Color::Green));
assert_eq!(result.spans[3].style.bg, None);
}
/// Empty line: `highlight_columns` must return an empty line without panicking.
#[test]
fn highlight_columns_empty_line() {
use ratatui::style::Color;
let bg = Color::Rgb(1, 2, 3);
let line = Line::from(vec![]);
let result = highlight_columns(&line, 0, 5, bg);
assert!(result.spans.is_empty(), "empty line stays empty");
}
// ── VisualRange::char_range_on_line ──────────────────────────────────────
/// Same-line char selection returns [`start_col`, `end_col`+1).
#[test]
fn visual_range_char_same_line() {
let r = VisualRange {
mode: VisualMode::Char,
anchor_line: 2,
anchor_col: 3,
cursor_line: 2,
cursor_col: 7,
};
assert_eq!(r.char_range_on_line(2, 20), Some((3, 8)));
assert_eq!(r.char_range_on_line(1, 20), None);
assert_eq!(r.char_range_on_line(3, 20), None);
}
/// Multi-line char selection: first line partial, middle full, last partial.
#[test]
fn visual_range_char_multi_line() {
let r = VisualRange {
mode: VisualMode::Char,
anchor_line: 1,
anchor_col: 4,
cursor_line: 3,
cursor_col: 2,
};
// Line 0: outside selection.
assert_eq!(r.char_range_on_line(0, 10), None);
// Line 1 (start line): from anchor_col to end of line.
assert_eq!(r.char_range_on_line(1, 10), Some((4, 10)));
// Line 2 (middle): full line.
assert_eq!(r.char_range_on_line(2, 8), Some((0, 8)));
// Line 3 (end line): from 0 to cursor_col+1.
assert_eq!(r.char_range_on_line(3, 10), Some((0, 3)));
// Line 4: outside.
assert_eq!(r.char_range_on_line(4, 10), None);
}
/// Line mode always returns `(0, line_width)` regardless of column fields.
#[test]
fn visual_range_line_mode_ignores_columns() {
let r = VisualRange {
mode: VisualMode::Line,
anchor_line: 2,
anchor_col: 5,
cursor_line: 4,
cursor_col: 9,
};
assert_eq!(r.char_range_on_line(2, 15), Some((0, 15)));
assert_eq!(r.char_range_on_line(3, 12), Some((0, 12)));
assert_eq!(r.char_range_on_line(4, 7), Some((0, 7)));
assert_eq!(r.char_range_on_line(1, 10), None);
}
// ── extract_line_text_range ──────────────────────────────────────────────
/// Basic substring extraction from a single-span line.
#[test]
fn extract_line_text_range_basic() {
let line = Line::from(Span::raw("hello world"));
// Extract "ello" (cols 1..5)
let s = extract_line_text_range(&line, 1, 5);
assert_eq!(s, "ello");
}
/// Extract across two spans.
#[test]
fn extract_line_text_range_across_spans() {
let line = Line::from(vec![Span::raw("abc"), Span::raw("def")]);
// "bcd" = cols 1..4
let s = extract_line_text_range(&line, 1, 4);
assert_eq!(s, "bcd");
}
// ── clamp_cursor_col ─────────────────────────────────────────────────────
/// Moving to a shorter line must clamp `cursor_col` to `line_width`-1.
#[test]
fn clamp_cursor_col_on_short_line() {
// Build a view with one 10-char line followed by one 3-char line.
let src_lines = vec![0u32, 1];
let n = src_lines.len();
let block_id = {
let mut h = DefaultHasher::new();
src_lines.hash(&mut h);
n.hash(&mut h);
TextBlockId(h.finish())
};
let block = DocBlock::Text {
id: block_id,
text: Text::from(vec![
Line::from(Span::raw("0123456789")), // line 0: width=10
Line::from(Span::raw("abc")), // line 1: width=3
]),
links: vec![],
heading_anchors: vec![],
source_lines: src_lines,
wrapped_height: std::cell::Cell::new(2),
};
// Populate text_layouts so `current_line_width` can read wrapped row widths.
// At width 80 neither line wraps — row 0 width=10, row 1 width=3.
let mut text_layouts = std::collections::HashMap::new();
crate::markdown::update_text_layouts(std::slice::from_ref(&block), &mut text_layouts, 80);
let mut v = MarkdownViewState {
total_lines: 2,
cursor_line: 0,
cursor_col: 9, // at end of line 0
rendered: vec![block],
text_layouts,
..Default::default()
};
// Move down to line 1 — cursor_col must clamp from 9 to 2 (width 3 - 1).
v.cursor_down(1);
assert_eq!(v.cursor_line, 1);
assert_eq!(v.cursor_col, 2, "cursor_col must clamp to width-1=2");
}
/// `current_line_width` must convert the visual-row `cursor_line` into a
/// logical line index before looking it up in `text.lines`. Otherwise
/// the cursor sitting on a wrapped paragraph indexes past the end of
/// `text.lines`, returns 0, and `clamp_cursor_col` resets `cursor_col`
/// to 0 — breaking horizontal arrow movement (regression caught right
/// after 1.18.4 shipped).
#[test]
fn current_line_width_handles_wrapped_lines() {
// After Phase 3, `current_line_width` reads from the `text_layouts` cache
// (pre-wrapped rows), not from `text.lines` directly. Populate the cache
// with width=20 so the 50-'a' line wraps to 3 physical rows of widths
// 20, 20, 10. The cursor on physical row 2 (visual row 2 within the block)
// is the third wrapped row — width 10.
let long: String = "a".repeat(50);
let src_lines = vec![0u32, 1, 2];
let n = src_lines.len();
let block_id = {
let mut h = DefaultHasher::new();
src_lines.hash(&mut h);
n.hash(&mut h);
TextBlockId(h.finish())
};
let block = DocBlock::Text {
id: block_id,
text: Text::from(vec![
Line::from(Span::raw("short")), // logical 0: 1 row
Line::from(Span::raw(long.clone())), // logical 1: wraps to 3 rows at width 20
Line::from(Span::raw("end")), // logical 2: 1 row
]),
links: vec![],
heading_anchors: vec![],
source_lines: src_lines,
// Width 20 -> long line wraps: rows are 20+20+10 = 5 total.
wrapped_height: std::cell::Cell::new(5),
};
// Build the text layout cache at width 20.
let mut text_layouts = std::collections::HashMap::new();
crate::markdown::update_text_layouts(std::slice::from_ref(&block), &mut text_layouts, 20);
let v = MarkdownViewState {
total_lines: 5,
cursor_line: 2, // physical row 2 = second wrapped row of the long line (width 20)
cursor_col: 0,
rendered: vec![block],
layout_width: 20,
text_layouts,
..Default::default()
};
// Physical rows: 0="short"(5), 1=aa...(20), 2=aa...(20), 3=aa...(10), 4="end"(3).
// Cursor at row 2 → second 20-char chunk of the wrapped long line.
assert_eq!(v.current_line_width(), 20);
}
/// Helper: build a `MarkdownViewState` with a given `total_lines` and
/// default scroll/cursor at 0.
fn view_with_lines(total: u32) -> MarkdownViewState {
MarkdownViewState {
total_lines: total,
..Default::default()
}
}
// ── cursor_down / cursor_up ──────────────────────────────────────────────
/// Moving down then back up the same amount must return to line 0.
#[test]
fn cursor_down_then_up_returns_home() {
let mut v = view_with_lines(5);
v.cursor_down(3);
assert_eq!(v.cursor_line, 3);
v.cursor_up(3);
assert_eq!(v.cursor_line, 0);
}
/// Moving down more lines than the document has must clamp to the last line.
#[test]
fn cursor_down_clamps_to_last_line() {
let mut v = view_with_lines(3);
v.cursor_down(100);
// Last valid line index = total_lines - 1 = 2.
assert_eq!(v.cursor_line, 2);
}
// ── scroll_to_cursor ────────────────────────────────────────────────────
/// When the cursor is below the viewport, `scroll_to_cursor` scrolls just
/// enough to bring it to the bottom row of the viewport.
///
/// Document: 10 lines. `view_height`: 5. `scroll_offset`: 0. cursor: 7.
/// Expected: `scroll_offset` = 7 - (5 - 1) = 3.
#[test]
fn cursor_scroll_follows_when_off_screen() {
let mut v = view_with_lines(10);
v.scroll_offset = 0;
v.cursor_line = 7;
v.scroll_to_cursor(5);
assert_eq!(v.scroll_offset, 3);
}
/// When the cursor is already inside the viewport, `scroll_to_cursor` must
/// not change `scroll_offset`.
#[test]
fn cursor_scroll_unchanged_when_already_visible() {
let mut v = view_with_lines(20);
v.scroll_offset = 5;
v.cursor_line = 7;
v.scroll_to_cursor(10);
// cursor (7) is in [5, 15) — no adjustment needed.
assert_eq!(v.scroll_offset, 5);
}
// ── source_line_at ───────────────────────────────────────────────────────
fn make_text_block_with_sources(source_lines: Vec<u32>) -> DocBlock {
let n = source_lines.len();
let text_lines: Vec<Line<'static>> = (0..n)
.map(|i| Line::from(Span::raw(format!("line {i}"))))
.collect();
let block_id = {
let mut h = DefaultHasher::new();
source_lines.hash(&mut h);
n.hash(&mut h);
TextBlockId(h.finish())
};
DocBlock::Text {
id: block_id,
text: Text::from(text_lines),
links: Vec::<LinkInfo>::new(),
heading_anchors: Vec::<HeadingAnchor>::new(),
source_lines,
wrapped_height: std::cell::Cell::new(crate::cast::u32_sat(n)),
}
}
/// Querying each logical line in a Text block returns the expected source line.
#[test]
fn source_line_at_text_block_exact() {
use crate::markdown::{source_line_at, update_text_layouts};
use std::collections::HashMap;
let block = make_text_block_with_sources(vec![0, 1, 2]);
// Populate text_layouts so `source_line_at` can use `physical_to_logical`.
// Width 80 — all lines fit on one row each (no wrapping); logical == physical.
let mut tl = HashMap::new();
update_text_layouts(std::slice::from_ref(&block), &mut tl, 80);
let blocks = vec![block];
let bl = HashMap::new();
assert_eq!(source_line_at(&blocks, 0, &tl, &bl), 0);
assert_eq!(source_line_at(&blocks, 1, &tl, &bl), 1);
assert_eq!(source_line_at(&blocks, 2, &tl, &bl), 2);
}
/// Every logical line within a Table block must return the table's source line.
/// A table with no `row_source_lines` data (empty) falls back to
/// `source_line` for every row position (defensive stub path).
#[test]
fn source_line_at_table_block_returns_table_start() {
use crate::markdown::source_line_at;
use crate::markdown::{TableBlock, TableBlockId};
use std::collections::HashMap;
let block = DocBlock::Table(TableBlock {
id: TableBlockId(0),
headers: vec![],
rows: vec![],
alignments: vec![],
natural_widths: vec![],
rendered_height: 4,
source_line: 5,
row_source_lines: vec![],
});
let blocks = vec![block];
let tl = HashMap::new();
let bl = HashMap::new();
// With no row_source_lines, all positions fall back to source_line = 5.
assert_eq!(source_line_at(&blocks, 0, &tl, &bl), 5);
assert_eq!(source_line_at(&blocks, 3, &tl, &bl), 5);
}
// ── patch_cursor_highlight ───────────────────────────────────────────────
/// Build a slice of simple `Line`s for highlight tests.
fn make_lines(count: usize) -> Vec<Line<'static>> {
(0..count)
.map(|i| Line::from(Span::raw(format!("line {i}"))))
.collect()
}
/// Patching a middle line must set `bg` on all its spans and leave other
/// lines unchanged.
#[test]
fn patch_cursor_highlight_patches_given_line() {
use ratatui::style::Color;
let bg = Color::Rgb(30, 30, 100);
let mut lines = make_lines(3);
patch_cursor_highlight(&mut lines, 1, bg);
// Line 1 spans must carry the bg color.
for span in &lines[1].spans {
assert_eq!(span.style.bg, Some(bg), "line 1 span must have bg color");
}
// Lines 0 and 2 must be untouched.
for span in &lines[0].spans {
assert_eq!(span.style.bg, None, "line 0 must be untouched");
}
for span in &lines[2].spans {
assert_eq!(span.style.bg, None, "line 2 must be untouched");
}
}
/// An empty line at the target index must be replaced with a space span
/// carrying the bg color so the highlight row is visible.
#[test]
fn patch_cursor_highlight_fills_empty_line() {
use ratatui::style::Color;
let bg = Color::Rgb(50, 50, 150);
let mut lines = vec![
Line::from(Span::raw("before")),
Line::from(vec![]), // empty — no spans
Line::from(Span::raw("after")),
];
patch_cursor_highlight(&mut lines, 1, bg);
assert_eq!(
lines[1].spans.len(),
1,
"empty line must have a filler span injected"
);
assert_eq!(
lines[1].spans[0].content.as_ref(),
" ",
"filler span must be a single space"
);
assert_eq!(lines[1].spans[0].style.bg, Some(bg));
}
/// An out-of-bounds `idx` must not panic or mutate anything.
#[test]
fn patch_cursor_highlight_out_of_bounds_noop() {
use ratatui::style::Color;
let bg = Color::Rgb(10, 10, 10);
let mut lines = make_lines(2);
// idx == 2 is one past the end.
patch_cursor_highlight(&mut lines, 2, bg);
// Both lines must be unchanged.
for line in &lines {
for span in &line.spans {
assert_eq!(span.style.bg, None);
}
}
}
// ── source_line_at — Table with row_source_lines ─────────────────────────
/// Build a `TableBlock` with explicit `row_source_lines` and verify that
/// `source_line_at` maps each rendered row to the correct source line.
///
/// Layout (2 body rows):
/// 0: top border → header source (5)
/// 1: header row → 5
/// 2: separator → 5
/// 3: body[0] → 7
/// 4: body[1] → 8
/// 5: bottom border → last body (8)
#[test]
fn source_line_at_table_block_per_row() {
use crate::markdown::{TableBlock, TableBlockId, source_line_at};
use std::collections::HashMap;
let block = DocBlock::Table(TableBlock {
id: TableBlockId(0),
headers: vec![vec![Span::raw("H")]],
rows: vec![vec![vec![Span::raw("a")]], vec![vec![Span::raw("b")]]],
alignments: vec![pulldown_cmark::Alignment::None],
natural_widths: vec![1],
rendered_height: 6,
source_line: 5,
row_source_lines: vec![5, 7, 8],
});
let blocks = vec![block];
let tl = HashMap::new();
let bl = HashMap::new();
// top border → header fallback
assert_eq!(
source_line_at(&blocks, 0, &tl, &bl),
5,
"top border -> header"
);
// header row
assert_eq!(source_line_at(&blocks, 1, &tl, &bl), 5, "header row");
// separator
assert_eq!(
source_line_at(&blocks, 2, &tl, &bl),
5,
"separator -> header"
);
// body[0]
assert_eq!(source_line_at(&blocks, 3, &tl, &bl), 7, "body[0]");
// body[1]
assert_eq!(source_line_at(&blocks, 4, &tl, &bl), 8, "body[1]");
// bottom border → last body fallback
assert_eq!(
source_line_at(&blocks, 5, &tl, &bl),
8,
"bottom border -> last body"
);
}
/// Edge cases: table with only a header (no body rows).
#[test]
fn table_row_source_line_helper_boundary_cases() {
use crate::markdown::{TableBlock, TableBlockId, source_line_at};
use std::collections::HashMap;
let tl = HashMap::new();
let bl = HashMap::new();
// Header-only: rendered_height = 3 (top border, header, bottom border).
let header_only = DocBlock::Table(TableBlock {
id: TableBlockId(1),
headers: vec![vec![Span::raw("H")]],
rows: vec![],
alignments: vec![pulldown_cmark::Alignment::None],
natural_widths: vec![1],
rendered_height: 3,
source_line: 10,
row_source_lines: vec![10],
});
let blocks = vec![header_only];
// Row 0 = top border → header (10)
assert_eq!(source_line_at(&blocks, 0, &tl, &bl), 10);
// Row 1 = header → 10
assert_eq!(source_line_at(&blocks, 1, &tl, &bl), 10);
// Row 2 = bottom border → last (10)
assert_eq!(source_line_at(&blocks, 2, &tl, &bl), 10);
// Empty row_source_lines: must not panic, must fall back to source_line.
let empty_rsl = DocBlock::Table(TableBlock {
id: TableBlockId(2),
headers: vec![vec![Span::raw("H")]],
rows: vec![vec![vec![Span::raw("a")]]],
alignments: vec![pulldown_cmark::Alignment::None],
natural_widths: vec![1],
rendered_height: 4,
source_line: 99,
row_source_lines: vec![],
});
let blocks2 = vec![empty_rsl];
// All positions must fall back to source_line without panicking.
for i in 0..4 {
assert_eq!(
source_line_at(&blocks2, i, &tl, &bl),
99,
"empty rsl row {i}"
);
}
}
// ── Phase 3 cache tests ──────────────────────────────────────────────────
/// After `update_text_layouts` runs, the `text_layouts` HashMap must contain
/// an entry for the Text block's id. The entry's `wrapped` length must be
/// at least as large as the number of logical lines (each line is >= 1 row).
#[test]
fn text_layout_cache_populated_on_width_change() {
use crate::markdown::update_text_layouts;
use std::collections::HashMap;
let block = make_text_block_with_sources(vec![0, 1, 2]);
let id = if let DocBlock::Text { id, .. } = &block {
*id
} else {
panic!("expected Text block")
};
let mut cache = HashMap::new();
update_text_layouts(std::slice::from_ref(&block), &mut cache, 80);
assert!(
cache.contains_key(&id),
"cache must have entry for block id"
);
let layout = &cache[&id];
// 3 logical lines at width 80 → 3 physical rows (no wrapping needed).
assert_eq!(layout.wrapped.len(), 3);
assert_eq!(layout.physical_to_logical, vec![0, 1, 2]);
}
/// The `wrapped_height` cell on the block must equal `layout.wrapped.len()`
/// after `update_text_layouts` runs. This ensures `DocBlock::height()` returns
/// the correct visual-row count for scroll math.
#[test]
fn text_layout_cache_height_matches_wrapped_len() {
use crate::markdown::update_text_layouts;
use std::collections::HashMap;
// 50 'a' chars at width 20 wraps to 3 physical rows.
let long: String = "a".repeat(50);
let src_lines = vec![0u32, 1];
let n = src_lines.len();
let block_id = {
let mut h = DefaultHasher::new();
src_lines.hash(&mut h);
n.hash(&mut h);
TextBlockId(h.finish())
};
let block = DocBlock::Text {
id: block_id,
text: Text::from(vec![
Line::from(Span::raw("short")), // 1 row
Line::from(Span::raw(long.clone())), // 3 rows at width 20
]),
links: vec![],
heading_anchors: vec![],
source_lines: src_lines,
wrapped_height: std::cell::Cell::new(2),
};
let mut cache = HashMap::new();
update_text_layouts(std::slice::from_ref(&block), &mut cache, 20);
let layout = cache.get(&block_id).expect("cache must have entry");
// 1 + 3 = 4 physical rows total.
assert_eq!(layout.wrapped.len(), 4);
// Block's wrapped_height cell must be updated to match.
if let DocBlock::Text { wrapped_height, .. } = &block {
assert_eq!(
wrapped_height.get(),
layout.wrapped.len() as u32,
"wrapped_height must equal wrapped.len()"
);
}
}
/// `current_line_width` must return the display width of the wrapped row
/// under the cursor at each layout width. A 40-char line at width 20 wraps
/// into two rows of 20; at width 80 it stays on one row of 40.
#[test]
fn current_line_width_at_widths_20_40_80_120() {
use crate::markdown::update_text_layouts;
let content: String = "a".repeat(40); // 40 display columns
let src_lines = vec![0u32];
let n = src_lines.len();
let block_id = {
let mut h = DefaultHasher::new();
src_lines.hash(&mut h);
n.hash(&mut h);
TextBlockId(h.finish())
};
for &width in &[20u16, 40, 80, 120] {
let block = DocBlock::Text {
id: block_id,
text: Text::from(vec![Line::from(Span::raw(content.clone()))]),
links: vec![],
heading_anchors: vec![],
source_lines: src_lines.clone(),
wrapped_height: std::cell::Cell::new(1),
};
let mut cache = std::collections::HashMap::new();
update_text_layouts(std::slice::from_ref(&block), &mut cache, width);
let v = MarkdownViewState {
total_lines: block.height(),
cursor_line: 0,
rendered: vec![block],
text_layouts: cache,
..Default::default()
};
// At width 20: row 0 is 20 chars. At width 40+: row 0 is 40 chars.
let expected = width.min(40);
assert_eq!(
v.current_line_width(),
expected,
"width={width}: row 0 should be {expected} cols wide"
);
}
}
/// `current_line_width` on physical row 1 (the tail of a wrapped paragraph)
/// must return the tail width, not the full logical line width. The 'l' key
/// handler uses `current_line_width()` to clamp cursor_col, so this ensures
/// the cursor cannot be placed past the visible text on continuation rows.
#[test]
fn cursor_horizontal_movement_on_wrapped_paragraph() {
use crate::markdown::update_text_layouts;
// "a" * 30 at width 20 → row 0: 20 cols, row 1: 10 cols.
let content: String = "a".repeat(30);
let src_lines = vec![0u32];
let n = src_lines.len();
let block_id = {
let mut h = DefaultHasher::new();
src_lines.hash(&mut h);
n.hash(&mut h);
TextBlockId(h.finish())
};
let block = DocBlock::Text {
id: block_id,
text: Text::from(vec![Line::from(Span::raw(content))]),
links: vec![],
heading_anchors: vec![],
source_lines: src_lines,
wrapped_height: std::cell::Cell::new(2),
};
let mut cache = std::collections::HashMap::new();
update_text_layouts(std::slice::from_ref(&block), &mut cache, 20);
let v = MarkdownViewState {
total_lines: 2,
cursor_line: 1, // physical row 1 = tail (10 cols)
cursor_col: 0,
rendered: vec![block],
text_layouts: cache,
..Default::default()
};
// The max valid cursor_col for row 1 is width - 1 = 9.
let line_width = v.current_line_width();
assert_eq!(line_width, 10, "tail row width must be 10 (30 mod 20)");
assert_eq!(
line_width.saturating_sub(1),
9,
"max cursor col on tail row must be 9"
);
}
/// After `load()` re-renders a file, `text_layouts` must be empty (the cache
/// is cleared). This is the invalidation path: any stale layout entries from
/// the previous file are dropped, and the draw loop will re-populate on the
/// next frame.
#[test]
fn text_layout_cache_invalidated_on_load() {
use crate::markdown::update_text_layouts;
use crate::theme::{Palette, Theme};
let palette = Palette::from_theme(Theme::Default);
let block = make_text_block_with_sources(vec![0, 1]);
let mut cache = std::collections::HashMap::new();
update_text_layouts(std::slice::from_ref(&block), &mut cache, 80);
assert!(!cache.is_empty(), "pre-condition: cache must be populated");
let mut view = MarkdownViewState {
text_layouts: cache,
..Default::default()
};
view.load(
std::path::PathBuf::from("/fake/reload.md"),
"reload.md".to_string(),
"hello\nworld\n".to_string(),
&palette,
Theme::Default,
);
assert!(
view.text_layouts.is_empty(),
"load() must clear the text_layouts cache"
);
}
/// `recompute_positions` must use the `text_layouts` cache to map block-relative
/// logical line indices to absolute visual rows. A link on logical line 1 of a
/// block that starts at visual row 0 should end up at absolute line 1 (or the
/// first physical row of logical line 1 when the cache is populated).
#[test]
fn recompute_positions_uses_cached_layout() {
use crate::markdown::{LinkInfo, update_text_layouts};
let link = LinkInfo {
line: 1, // logical line 1 within the block
col_start: 0,
col_end: 5,
url: "#section".to_string(),
text: "sec".to_string(),
};
let src_lines = vec![0u32, 1, 2];
let n = src_lines.len();
let block_id = {
let mut h = DefaultHasher::new();
src_lines.hash(&mut h);
n.hash(&mut h);
TextBlockId(h.finish())
};
let block = DocBlock::Text {
id: block_id,
text: Text::from(vec![
Line::from(Span::raw("line 0")),
Line::from(Span::raw("line 1")),
Line::from(Span::raw("line 2")),
]),
links: vec![link],
heading_anchors: vec![],
source_lines: src_lines,
wrapped_height: std::cell::Cell::new(3),
};
let mut cache = std::collections::HashMap::new();
update_text_layouts(std::slice::from_ref(&block), &mut cache, 80);
let mut v = MarkdownViewState {
total_lines: 3,
rendered: vec![block],
text_layouts: cache,
..Default::default()
};
v.recompute_positions();
// Logical line 1 maps to physical row 1 at width 80 (no wrapping).
// Absolute visual row = block_start (0) + physical_row (1) = 1.
let link = v.links.first().expect("must have one link");
assert_eq!(
link.line, 1,
"link on logical line 1 must map to visual row 1"
);
}
/// `collect_match_lines` with a populated text_layouts cache must match
/// against physical (wrapped) rows, not logical lines. A search term that
/// appears in the second physical row of a wrapped logical line must return
/// the physical row's absolute index, not the logical line's index.
#[test]
fn collect_match_lines_text_block_uses_cache() {
use crate::app::collect_match_lines;
use crate::markdown::update_text_layouts;
use crate::mermaid::MermaidCache;
use std::collections::HashMap;
// A line that fits in one row — "hello world" is 11 cols, fits at width 80.
let block = make_text_block_with_sources(vec![0, 1, 2]);
let mut text_layouts = HashMap::new();
update_text_layouts(std::slice::from_ref(&block), &mut text_layouts, 80);
let blocks = vec![block];
let table_layouts = HashMap::new();
let cache = MermaidCache::new();
// "line 1" appears in logical line 1 = physical row 1.
let matches = collect_match_lines(&blocks, &text_layouts, &table_layouts, &cache, "line 1");
assert_eq!(matches, vec![1], "match must land on physical row 1");
}
/// When the text_layouts cache is empty (before the first draw), `collect_match_lines`
/// must fall back to iterating logical lines without panicking. The result may
/// differ from the post-wrap result but must not be empty for a term that exists.
#[test]
fn text_block_with_no_cache_falls_back_safely() {
use crate::app::collect_match_lines;
use crate::mermaid::MermaidCache;
use std::collections::HashMap;
let block = make_text_block_with_sources(vec![0, 1, 2]);
let blocks = vec![block];
let text_layouts = HashMap::new(); // empty — simulates pre-draw state
let table_layouts = HashMap::new();
let cache = MermaidCache::new();
// "line 2" is in logical line 2; fallback iterates `text.lines`.
let matches = collect_match_lines(&blocks, &text_layouts, &table_layouts, &cache, "line 2");
assert!(
!matches.is_empty(),
"fallback must still find matches in logical lines"
);
}
/// The blank-padding count in the gutter for a wrapped logical line must equal
/// the number of extra physical rows produced by wrapping (wrap_count - 1).
/// A 50-char line at width 20 produces 3 physical rows → 2 blank gutter rows.
#[test]
fn gutter_blank_padding_count_matches_wrap_count() {
use crate::markdown::update_text_layouts;
// "a" * 50 at width 20 → 3 physical rows.
let long = "a".repeat(50);
let src_lines = vec![0u32];
let n = src_lines.len();
let block_id = {
let mut h = DefaultHasher::new();
src_lines.hash(&mut h);
n.hash(&mut h);
TextBlockId(h.finish())
};
let block = DocBlock::Text {
id: block_id,
text: Text::from(vec![Line::from(Span::raw(long))]),
links: vec![],
heading_anchors: vec![],
source_lines: src_lines,
wrapped_height: std::cell::Cell::new(3),
};
let mut cache = std::collections::HashMap::new();
update_text_layouts(std::slice::from_ref(&block), &mut cache, 20);
let layout = cache.get(&block_id).unwrap();
// Count how many physical rows belong to logical line 0.
let wrap_count = layout
.physical_to_logical
.iter()
.filter(|&&l| l == 0)
.count();
// The first row gets a number; wrap_count - 1 rows get blank entries.
assert_eq!(wrap_count, 3, "50 chars at width 20 must wrap to 3 rows");
// Blank padding rows = wrap_count - 1 = 2.
let blank_count = wrap_count - 1;
assert_eq!(
blank_count, 2,
"2 blank gutter rows expected for a 3-row wrap"
);
}
/// When a document has a link on logical line 1 of a Text block and the
/// `text_layouts` cache is populated, `recompute_positions` must store the
/// link at the correct visual row. A `try_follow_link_click`-style lookup
/// must find the link at its physical row position.
#[test]
fn link_picker_jumps_to_link_on_wrapped_paragraph() {
use crate::markdown::{LinkInfo, update_text_layouts};
// Block: 2 logical lines, each fits on 1 row at width 80.
// Link is on logical line 1.
let link = LinkInfo {
line: 1,
col_start: 0,
col_end: 4,
url: "#target".to_string(),
text: "link".to_string(),
};
let src_lines = vec![0u32, 1];
let n = src_lines.len();
let block_id = {
let mut h = DefaultHasher::new();
src_lines.hash(&mut h);
n.hash(&mut h);
TextBlockId(h.finish())
};
let block = DocBlock::Text {
id: block_id,
text: Text::from(vec![
Line::from(Span::raw("first line")),
Line::from(Span::raw("link text")),
]),
links: vec![link],
heading_anchors: vec![],
source_lines: src_lines,
wrapped_height: std::cell::Cell::new(2),
};
let mut cache = std::collections::HashMap::new();
update_text_layouts(std::slice::from_ref(&block), &mut cache, 80);
let mut v = MarkdownViewState {
total_lines: 2,
rendered: vec![block],
text_layouts: cache,
..Default::default()
};
v.recompute_positions();
// Link on logical line 1 → physical row 1 (no wrapping at width 80).
// Absolute line = 0 (block offset) + 1 (physical row) = 1.
let l = v.links.first().expect("must have one link");
assert_eq!(l.line, 1, "link must be at visual row 1");
assert_eq!(l.url, "#target");
}
/// A search term that appears in the second physical row of a wrapped logical
/// line must return the second row's absolute index (not the logical line's
/// index). This exercises `collect_match_lines`'s physical-row iteration path.
///
/// Layout at width 20:
/// logical line 0: "aaaaaaaaaaaaaaaaaaaa needle" → two words
/// physical row 0: "aaaaaaaaaaaaaaaaaaaa" (20 cols)
/// physical row 1: "needle" ( 6 cols)
/// logical line 1: "other" → physical row 2
#[test]
fn doc_search_match_lands_on_correct_visual_row() {
use crate::app::collect_match_lines;
use crate::markdown::update_text_layouts;
use crate::mermaid::MermaidCache;
use std::collections::HashMap;
// Word-wrap: 20 'a' chars + " needle" — the word "needle" is pushed to row 1.
let line0 = format!("{} needle", "a".repeat(20));
let src_lines = vec![0u32, 1];
let n = src_lines.len();
let block_id = {
let mut h = DefaultHasher::new();
src_lines.hash(&mut h);
n.hash(&mut h);
TextBlockId(h.finish())
};
let block = DocBlock::Text {
id: block_id,
text: Text::from(vec![
Line::from(Span::raw(line0)),
Line::from(Span::raw("other")),
]),
links: vec![],
heading_anchors: vec![],
source_lines: src_lines,
wrapped_height: std::cell::Cell::new(3),
};
let mut tl = HashMap::new();
update_text_layouts(std::slice::from_ref(&block), &mut tl, 20);
let blocks = vec![block];
let bl = HashMap::new();
let cache = MermaidCache::new();
let matches = collect_match_lines(&blocks, &tl, &bl, &cache, "needle");
// Word "needle" is on physical row 1.
assert_eq!(matches, vec![1], "needle must be on physical row 1");
}
/// `source_line_at` on a Text block must correctly map physical rows when
/// the cache is populated. A 2-line text block at width 80 maps physical
/// row 0 → source 0, physical row 1 → source 1.
#[test]
fn source_line_at_with_cache_resolves_physical_rows() {
use crate::markdown::{source_line_at, update_text_layouts};
use std::collections::HashMap;
let block = make_text_block_with_sources(vec![10, 20]);
let mut tl = HashMap::new();
update_text_layouts(std::slice::from_ref(&block), &mut tl, 80);
let blocks = vec![block];
let bl = HashMap::new();
// At width 80, no wrapping: physical row 0 → logical 0 → source 10.
assert_eq!(source_line_at(&blocks, 0, &tl, &bl), 10);
// Physical row 1 → logical 1 → source 20.
assert_eq!(source_line_at(&blocks, 1, &tl, &bl), 20);
}
}