quadraui 0.6.1

Cross-platform Rust UI toolkit: write one AppLogic and run it unmodified on TUI, GTK4 (Linux), macOS, and Windows backends
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
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
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
//! `DiffView` primitive: a two-pane side-by-side or unified diff viewer.
//!
//! # Backend contract
//!
//! **Purely declarative** — hunks are app-computed via
//! `quadraui::diff::compute_hunks`; backends only render. The app calls
//! `compute_hunks(left, right)` whenever the inputs change, stores the
//! result in `DiffView::hunks`, and passes the struct to the backend for
//! rasterisation. Backends never recompute the diff.
//!
//! # Scroll model
//!
//! A single `scroll_offset` drives lock-step scrolling of both panes.
//! The offset counts display rows from the beginning of the first hunk.
//! Per-pane independent scrolling is out of scope for v1; the planned
//! additive field is `right_scroll_offset: Option<usize>`.
//!
//! # Editability
//!
//! `DiffEditability::RightEditable` signals to consumers that the right
//! pane should accept edits on TUI. Events in this architecture flow
//! from `AppLogic::handle`, not from rasterisers — the app processes key
//! input, mutates `DiffView::right`, and recomputes hunks itself. Full
//! text-input machinery (cursor, insertion, deletion) is a follow-up
//! story; on GTK v1 the right pane remains read-only regardless of this
//! setting.
//!
//! # Distinct from `Editor` with `diff_status`
//!
//! `DiffView` renders a self-contained diff primitive from pre-computed
//! hunks. The `Editor` primitive decorates live buffer content with
//! per-line gutter colours. They are not interchangeable.
//!
//! # Shared layout
//!
//! Row/pane geometry — pane widths, the divider position, the optional
//! header strip, and the scroll-clamped visible-line window — is now
//! computed once by [`DiffView::layout`] rather than re-derived by every
//! backend independently. [`row_colors`] / [`unified_row_style`] /
//! [`unified_row_text`] / [`unified_hunk_header`] are the single source of
//! colour/text selection. Every backend (gtk, macos, tui, win) calls these
//! instead of carrying its own copy.

use crate::event::Rect;
use crate::theme::Theme;
use crate::types::{Color, WidgetId};
use serde::{Deserialize, Serialize};

/// The kind of change a [`DiffRow`] represents.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum DiffRowKind {
    /// Line is identical on both sides.
    Same,
    /// Left side has a line, right side has a different line (modified).
    Changed,
    /// Left side has a line, right side is empty (deleted from right).
    Removed,
    /// Right side has a line, left side is empty (added on right).
    Added,
}

/// A single display row in a [`DiffHunk`].
///
/// Either side may be `None` (padding row) when one side has more lines
/// in a change run than the other.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DiffRow {
    /// Content from the left (original) file, or `None` for padding.
    pub left: Option<String>,
    /// Content from the right (modified) file, or `None` for padding.
    pub right: Option<String>,
    /// Change kind — drives background / foreground colour selection.
    pub kind: DiffRowKind,
}

/// The `row kind → colour` table for **side-by-side** mode — used by
/// every backend's rasteriser (gtk, macos, tui, win). This single function
/// is the only definition, and every backend converts its `Color` output to
/// its own native colour type at the call site (`qc` on TUI, `cairo_rgb`
/// on GTK, a passthrough on macOS/Win).
///
/// Returns `(left_fg, left_bg, right_fg, right_bg)`.
pub fn row_colors(kind: DiffRowKind, theme: &Theme) -> (Color, Color, Color, Color) {
    match kind {
        DiffRowKind::Same => (
            theme.muted_fg,
            theme.background,
            theme.muted_fg,
            theme.background,
        ),
        DiffRowKind::Changed => (
            theme.git_deleted,
            theme.diff_removed_bg,
            theme.git_added,
            theme.diff_added_bg,
        ),
        DiffRowKind::Removed => (
            theme.git_deleted,
            theme.diff_removed_bg,
            theme.muted_fg,
            theme.diff_padding_bg,
        ),
        DiffRowKind::Added => (
            theme.muted_fg,
            theme.diff_padding_bg,
            theme.git_added,
            theme.diff_added_bg,
        ),
    }
}

/// The `row kind → (prefix, colour)` table for **unified** mode — the
/// single-column twin of [`row_colors`], likewise lifted out of three
/// backend copies.
///
/// Returns `(prefix_char, fg, bg)`.
pub fn unified_row_style(kind: DiffRowKind, theme: &Theme) -> (char, Color, Color) {
    match kind {
        DiffRowKind::Same => (' ', theme.muted_fg, theme.background),
        DiffRowKind::Removed | DiffRowKind::Changed => {
            ('-', theme.git_deleted, theme.diff_removed_bg)
        }
        DiffRowKind::Added => ('+', theme.git_added, theme.diff_added_bg),
    }
}

/// The unified-mode content text for a [`DiffRow`]: the left text for a
/// `Removed` row, otherwise the right text falling back to the left
/// (`Changed`/`Added`/`Same`). Lifted out of three identical `match`
/// arms.
pub fn unified_row_text(row: &DiffRow) -> &str {
    match row.kind {
        DiffRowKind::Removed => row.left.as_deref().unwrap_or(""),
        _ => row.right.as_deref().or(row.left.as_deref()).unwrap_or(""),
    }
}

/// A contiguous group of rows to display, bracketed by context lines.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DiffHunk {
    /// 1-based line number of the first row's left content in the original
    /// left text. Used to render `@@ -left_start,N +right_start,M @@` headers
    /// in unified mode.
    pub left_start: usize,
    /// 1-based line number of the first row's right content in the right text.
    pub right_start: usize,
    /// Ordered display rows for this hunk (context + changed lines).
    pub rows: Vec<DiffRow>,
}

/// Render a hunk's `@@ -l,n +r,m @@` unified-diff header line.
///
/// `-n` counts rows sourced from the LEFT file (`row.left.is_some()`),
/// `+m` from the RIGHT (`row.right.is_some()`) — these differ from
/// `hunk.rows.len()` whenever a change run produces padding rows (unequal
/// removed/added counts). Lifted out of three identical copies.
pub fn unified_hunk_header(hunk: &DiffHunk) -> String {
    let left_count = hunk.rows.iter().filter(|r| r.left.is_some()).count();
    let right_count = hunk.rows.iter().filter(|r| r.right.is_some()).count();
    format!(
        "@@ -{},{} +{},{} @@",
        hunk.left_start, left_count, hunk.right_start, right_count
    )
}

/// Display mode for the diff widget.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum DiffMode {
    /// Two-column layout: left (original) on the left, right (modified) on
    /// the right, separated by a centre divider.
    #[default]
    SideBySide,
    /// Single-column layout with `+`/`-`/` ` prefixes. Hunk headers are
    /// rendered as `@@ -l,n +r,m @@` lines.
    Unified,
}

/// Whether the right pane of the diff is editable.
///
/// `RightEditable` signals to consumers that the right pane should accept
/// edits on TUI. Events in this architecture flow from `AppLogic::handle`,
/// not from rasterisers — the app processes key input and mutates the
/// right text itself. Full text-input machinery (cursor, insertion,
/// deletion) ships in a follow-up. On GTK v1 this setting is accepted but
/// the right pane renders read-only.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum DiffEditability {
    /// Both panes are read-only (default).
    #[default]
    ReadOnly,
    /// Right pane accepts edits on TUI; the app mutates
    /// [`DiffView::right`] from `AppLogic::handle` after processing
    /// each edit key. GTK v1 renders as read-only; full editing
    /// machinery is a follow-up.
    RightEditable,
}

/// Which pane has keyboard focus.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum DiffPane {
    /// Left (original) pane.
    #[default]
    Left,
    /// Right (modified) pane.
    Right,
}

/// Layout information returned by `draw_diff_view`.
///
/// Used by `AppLogic` to clamp scroll offsets after a resize.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DiffViewLayout {
    /// Number of content rows that fit on screen (after the optional header row).
    pub visible_rows: usize,
    /// Total number of display lines the backend used for rendering.
    ///
    /// In **side-by-side** mode this equals `DiffView::total_rows()` (one
    /// display line per `DiffRow`).
    ///
    /// In **unified** mode each hunk contributes an extra `@@ … @@` header
    /// line, so `total_rows = view.total_rows() + hunk_count`.  Always use
    /// this field — not `DiffView::total_rows()` — when clamping scroll:
    /// ```ignore
    /// view.scroll_offset = view.scroll_offset
    ///     .min(layout.total_rows.saturating_sub(layout.visible_rows));
    /// ```
    pub total_rows: usize,
}

/// Divider thickness between the left and right panes, in the backend's
/// native units (1 cell on TUI, 1 px/DIP everywhere else — every backend
/// used the same numeric value before #737, so it is a shared constant
/// rather than a fourth per-backend copy).
pub const DIFF_DIVIDER_W: f32 = 1.0;

/// Header strip geometry for **side-by-side** mode (only present when
/// `left_label`/`right_label` is set). Resolved once by [`DiffView::layout`]
/// rather than re-derived by each backend.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct DiffHeaderGeometry {
    /// Bounds of the left label strip.
    pub left: Rect,
    /// Bounds of the right label strip.
    pub right: Rect,
    /// Bounds of the 1-unit divider segment within the header row.
    pub divider: Rect,
}

/// What a [`DiffDisplayLine`] renders: either a synthesized unified `@@ …
/// @@` hunk header, or a real diff row.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DiffLineContent {
    /// A unified-mode hunk header. `hunk_idx` indexes [`DiffView::hunks`];
    /// render its text with [`unified_hunk_header`].
    UnifiedHeader {
        /// Index into [`DiffView::hunks`].
        hunk_idx: usize,
    },
    /// A real diff row. `row_idx` indexes [`DiffView::flat_rows`] — stable
    /// across both display modes, since row *content* doesn't change
    /// between side-by-side and unified, only how headers interleave.
    Row {
        /// Index into [`DiffView::flat_rows`].
        row_idx: usize,
    },
}

/// One on-screen line resolved by [`DiffView::layout`] — already
/// scroll-clamped, so `DiffView::layout(..).lines` is exactly the visible
/// window in paint order.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct DiffDisplayLine {
    /// Full-width bounds of this line (used directly in unified mode; in
    /// side-by-side mode `left`/`right`/`divider` subdivide it instead).
    pub bounds: Rect,
    /// Left-pane bounds. `Some` only for [`DiffMode::SideBySide`] rows.
    pub left: Option<Rect>,
    /// Right-pane bounds. `Some` only for [`DiffMode::SideBySide`] rows.
    pub right: Option<Rect>,
    /// Pane-divider bounds. `Some` only for [`DiffMode::SideBySide`] rows.
    pub divider: Option<Rect>,
    /// What to render at this line.
    pub content: DiffLineContent,
}

/// Top-level pane geometry for **side-by-side** mode — present even when
/// `lines` is empty (e.g. an empty diff), so a backend painting trailing
/// blank rows or an empty-pane divider never needs to re-derive
/// `left_w`/`right_w`/`divider_x` by hand.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct DiffPaneGeometry {
    /// Left-pane width.
    pub left_w: f32,
    /// Right-pane width.
    pub right_w: f32,
    /// Absolute x of the 1-unit divider column.
    pub divider_x: f32,
    /// Top of the content area (below the header strip, if any).
    pub content_y: f32,
    /// Height of the content area (viewport height minus the header strip).
    pub content_h: f32,
}

/// Fully-resolved `DiffView` geometry — the row-position/colour-agnostic
/// spatial layout that backends need to render. Computed once by
/// [`DiffView::layout`] rather than re-derived independently by each
/// backend. Backends still own colour selection ([`row_colors`] /
/// [`unified_row_style`]) and text painting; this answers only "where".
///
/// `lines` already reflects `scroll_offset` — it is the visible window,
/// not the full row list — so callers never re-implement the scroll-clamp
/// arithmetic.
#[derive(Debug, Clone, PartialEq)]
pub struct DiffViewGeometry {
    /// The viewport this geometry was computed for.
    pub bounds: Rect,
    /// Side-by-side header strip, when present.
    pub header: Option<DiffHeaderGeometry>,
    /// Side-by-side pane widths/divider position. `None` in
    /// [`DiffMode::Unified`], where there is only one column.
    pub panes: Option<DiffPaneGeometry>,
    /// Number of content rows that fit in the viewport.
    pub visible_rows: usize,
    /// Total number of display lines — same contract as
    /// [`DiffViewLayout::total_rows`] (content rows in side-by-side mode,
    /// `+ hunk_count` in unified mode).
    pub total_rows: usize,
    /// The visible window of display lines, top to bottom.
    pub lines: Vec<DiffDisplayLine>,
}

/// Hit-test classification for a click against a [`DiffViewGeometry`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DiffViewHit {
    /// Click landed on a real diff row. `row_idx` indexes
    /// [`DiffView::flat_rows`], matching [`DiffLineContent::Row`].
    /// `pane` is `Some` in [`DiffMode::SideBySide`] when the click falls
    /// within the row's `left`/`right` sub-rect, `None` in
    /// [`DiffMode::Unified`] or when it lands on the divider column.
    Row {
        row_idx: usize,
        pane: Option<DiffPane>,
    },
    /// Click landed on a synthesized unified hunk header.
    UnifiedHeader { hunk_idx: usize },
    /// Click missed every display line.
    Empty,
}

impl DiffViewGeometry {
    /// The [`DiffViewLayout`] scroll-clamp summary for this geometry —
    /// every backend's `draw_diff_view` returns this.
    pub fn as_layout(&self) -> DiffViewLayout {
        DiffViewLayout {
            visible_rows: self.visible_rows,
            total_rows: self.total_rows,
        }
    }

    /// Hit-test a click at `(x, y)` against [`Self::lines`].
    ///
    /// Coordinate frame: **ABSOLUTE** — matches every `bounds` field on
    /// [`DiffDisplayLine`], which already carry the `viewport` rect
    /// passed to [`DiffView::layout`].
    pub fn hit_test(&self, x: f32, y: f32) -> DiffViewHit {
        for line in &self.lines {
            let b = line.bounds;
            if !(x >= b.x && x < b.x + b.width && y >= b.y && y < b.y + b.height) {
                continue;
            }
            return match line.content {
                DiffLineContent::UnifiedHeader { hunk_idx } => {
                    DiffViewHit::UnifiedHeader { hunk_idx }
                }
                DiffLineContent::Row { row_idx } => {
                    let pane = match (line.left, line.right) {
                        (Some(left), _) if x >= left.x && x < left.x + left.width => {
                            Some(DiffPane::Left)
                        }
                        (_, Some(right)) if x >= right.x && x < right.x + right.width => {
                            Some(DiffPane::Right)
                        }
                        _ => None,
                    };
                    DiffViewHit::Row { row_idx, pane }
                }
            };
        }
        DiffViewHit::Empty
    }
}

/// Resolve `(start, end)` — the half-open range of the flat display-line
/// list that is on-screen — from a scroll offset. Used by both
/// [`DiffView::layout`] modes.
fn scroll_window(scroll_offset: usize, visible_rows: usize, total: usize) -> (usize, usize) {
    let start = scroll_offset.min(total.saturating_sub(1));
    let end = (start + visible_rows).min(total);
    (start, end)
}

/// The `DiffView` primitive: a two-pane or unified diff viewer.
///
/// Apps build this from pre-computed [`DiffHunk`]s (via
/// `quadraui::diff::compute_hunks`) and pass it to `backend.draw_diff_view`.
/// The backend never recomputes the diff — it only rasterises.
///
/// # Examples
///
/// ```
/// use quadraui::{DiffHunk, DiffMode, DiffRow, DiffRowKind, DiffView, DiffViewHit, Rect, WidgetId};
///
/// let view = DiffView {
///     id: WidgetId::new("diff:review"),
///     left: "old\n".to_string(),
///     right: "new\n".to_string(),
///     left_label: Some("a/file.rs".to_string()),
///     right_label: Some("b/file.rs".to_string()),
///     hunks: vec![DiffHunk {
///         left_start: 1,
///         right_start: 1,
///         rows: vec![DiffRow {
///             left: Some("old".to_string()),
///             right: Some("new".to_string()),
///             kind: DiffRowKind::Changed,
///         }],
///     }],
///     mode: DiffMode::SideBySide,
///     editability: Default::default(),
///     scroll_offset: 0,
///     focused_pane: Default::default(),
///     has_focus: false,
/// };
///
/// let geometry = view.layout(Rect::new(0.0, 0.0, 80.0, 24.0), 1.0);
/// match geometry.hit_test(1.0, geometry.lines[0].bounds.y) {
///     DiffViewHit::Row { row_idx, .. } => assert_eq!(row_idx, 0),
///     other => panic!("expected a row hit, got {other:?}"),
/// }
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DiffView {
    /// Stable identifier for this widget instance.
    pub id: WidgetId,
    /// Original (left-side) text. Source for `compute_hunks`.
    ///
    /// Carried alongside the pre-computed `hunks` so the view is the
    /// canonical single-struct state: an edited-right consumer can
    /// reconstruct the new right buffer and re-diff against `left`
    /// without threading extra strings out-of-band, and a serialised
    /// `DiffView` can re-compute `hunks` if the cached copy is stale.
    pub left: String,
    /// Proposed (right-side) text. Source for `compute_hunks`. Mutated
    /// by the app when `editability == RightEditable`.
    pub right: String,
    /// Optional label shown above the left pane (e.g. file path / branch name).
    pub left_label: Option<String>,
    /// Optional label shown above the right pane.
    pub right_label: Option<String>,
    /// Pre-computed diff hunks. Set by calling
    /// `quadraui::diff::compute_hunks(&self.left, &self.right)`.
    pub hunks: Vec<DiffHunk>,
    /// Display mode — side-by-side (default) or unified.
    pub mode: DiffMode,
    /// Editability of the right pane. Currently all backends render as read-only.
    pub editability: DiffEditability,
    /// Row scroll offset (from the top of the first hunk).
    pub scroll_offset: usize,
    /// Which pane currently has keyboard focus.
    pub focused_pane: DiffPane,
    /// Whether the widget as a whole has keyboard focus.
    ///
    /// **Currently unused by all backends.** Reserved for a future focus
    /// border; setting this to `true` produces no visual change in v1.
    pub has_focus: bool,
}

impl DiffView {
    /// Total number of display rows across all hunks.
    ///
    /// Use this to clamp `scroll_offset` after the hunk list changes:
    /// `view.scroll_offset = view.scroll_offset.min(view.total_rows().saturating_sub(1))`.
    pub fn total_rows(&self) -> usize {
        self.hunks.iter().map(|h| h.rows.len()).sum()
    }

    /// Flatten every hunk's rows into one list, in display order. The
    /// resulting index is what [`DiffLineContent::Row::row_idx`] refers
    /// to, in both [`DiffMode::SideBySide`] and [`DiffMode::Unified`].
    pub fn flat_rows(&self) -> Vec<&DiffRow> {
        self.hunks.iter().flat_map(|h| h.rows.iter()).collect()
    }

    /// Compute this view's row/pane geometry for a `viewport` of the given
    /// `line_height` (backend-native units: 1.0 for TUI cells, font pixel
    /// height for GTK/macOS/Win).
    ///
    /// Returns pane widths, the divider position, the header strip, and the
    /// scroll-clamped visible-line window. Backends own colour selection
    /// ([`row_colors`] / [`unified_row_style`]) and text painting.
    ///
    /// Returns an empty (zero-`visible_rows`) geometry when `viewport` or
    /// `line_height` is non-positive — a guard that prevents division by zero.
    pub fn layout(&self, viewport: Rect, line_height: f32) -> DiffViewGeometry {
        if viewport.width <= 0.0 || viewport.height <= 0.0 || line_height <= 0.0 {
            return DiffViewGeometry {
                bounds: viewport,
                header: None,
                panes: None,
                visible_rows: 0,
                total_rows: self.total_rows(),
                lines: Vec::new(),
            };
        }

        match self.mode {
            DiffMode::SideBySide => self.layout_side_by_side(viewport, line_height),
            DiffMode::Unified => self.layout_unified(viewport, line_height),
        }
    }

    fn layout_side_by_side(&self, viewport: Rect, line_height: f32) -> DiffViewGeometry {
        let has_header = self.left_label.is_some() || self.right_label.is_some();
        let header_h = if has_header { line_height } else { 0.0 };

        let left_w = ((viewport.width - DIFF_DIVIDER_W) / 2.0).floor();
        let right_w = (viewport.width - DIFF_DIVIDER_W - left_w).max(0.0);
        let divider_x = viewport.x + left_w;

        let header = has_header.then(|| DiffHeaderGeometry {
            left: Rect::new(viewport.x, viewport.y, left_w, header_h),
            right: Rect::new(divider_x + DIFF_DIVIDER_W, viewport.y, right_w, header_h),
            divider: Rect::new(divider_x, viewport.y, DIFF_DIVIDER_W, header_h),
        });

        let content_y = viewport.y + header_h;
        let content_h = (viewport.height - header_h).max(0.0);
        let visible_rows = (content_h / line_height).floor() as usize;

        let total_rows = self.total_rows();
        let (start, end) = scroll_window(self.scroll_offset, visible_rows, total_rows);

        let mut lines = Vec::with_capacity(end.saturating_sub(start));
        for (i, row_idx) in (start..end).enumerate() {
            let row_y = content_y + i as f32 * line_height;
            lines.push(DiffDisplayLine {
                bounds: Rect::new(viewport.x, row_y, viewport.width, line_height),
                left: Some(Rect::new(viewport.x, row_y, left_w, line_height)),
                right: Some(Rect::new(
                    divider_x + DIFF_DIVIDER_W,
                    row_y,
                    right_w,
                    line_height,
                )),
                divider: Some(Rect::new(divider_x, row_y, DIFF_DIVIDER_W, line_height)),
                content: DiffLineContent::Row { row_idx },
            });
        }

        DiffViewGeometry {
            bounds: viewport,
            header,
            panes: Some(DiffPaneGeometry {
                left_w,
                right_w,
                divider_x,
                content_y,
                content_h,
            }),
            visible_rows,
            total_rows,
            lines,
        }
    }

    fn layout_unified(&self, viewport: Rect, line_height: f32) -> DiffViewGeometry {
        let mut sequence: Vec<DiffLineContent> = Vec::new();
        let mut row_idx = 0usize;
        for (hunk_idx, hunk) in self.hunks.iter().enumerate() {
            sequence.push(DiffLineContent::UnifiedHeader { hunk_idx });
            for _ in &hunk.rows {
                sequence.push(DiffLineContent::Row { row_idx });
                row_idx += 1;
            }
        }
        let total_display = sequence.len();

        let visible_rows = (viewport.height / line_height).floor() as usize;
        let (start, end) = scroll_window(self.scroll_offset, visible_rows, total_display);

        let mut lines = Vec::with_capacity(end.saturating_sub(start));
        for (i, content) in sequence[start..end].iter().enumerate() {
            let row_y = viewport.y + i as f32 * line_height;
            lines.push(DiffDisplayLine {
                bounds: Rect::new(viewport.x, row_y, viewport.width, line_height),
                left: None,
                right: None,
                divider: None,
                content: *content,
            });
        }

        DiffViewGeometry {
            bounds: viewport,
            header: None,
            panes: None,
            visible_rows,
            total_rows: total_display,
            lines,
        }
    }
}

// Unified implementation of `draw_diff_view` for all backends (gtk, macos,
// tui, win), written against [`crate::paint_surface::PaintSurface`] instead
// of any one backend's drawing API. Uses the layout geometry from
// [`DiffView::layout`] and applies row colouring and text from the
// [`row_colors`] and [`unified_row_style`] functions.
//
// Rendering differences from pre-unified implementations:
//
// 1. **Row/header text vertical alignment:** draws at the row rect's top
//    (established by prior primitives `status_bar` and `text_display` via
//    [`crate::paint_surface::PaintSurface::surface_draw_text_run`]), not
//    vertically centred as GTK previously did.
//
// 2. **Header-label overflow handling:** hard-clips overflowing labels at
//    the pane edge (as macOS/Windows did), not ellipsized (as GTK did).
#[cfg(any(
    feature = "gtk",
    feature = "win",
    all(feature = "macos", target_os = "macos")
))]
#[allow(dead_code)]
pub(crate) mod native_surface_paint {
    use super::{
        row_colors, unified_hunk_header, unified_row_style, unified_row_text, DiffLineContent,
        DiffMode, DiffView, DiffViewGeometry, DiffViewLayout,
    };
    use crate::event::Rect;
    use crate::paint_surface::PaintSurface;
    use crate::theme::Theme;
    use crate::types::Color;

    /// Text inset from a pane's left edge — mirrors every deleted
    /// per-backend `TEXT_PAD`/`TEXT_PAD_DIP` constant (all `4.0`).
    const TEXT_PAD: f32 = 4.0;
    /// Text inset used in unified mode — mirrors every deleted
    /// per-backend `UNIFIED_PAD`/`UNIFIED_PAD_DIP` constant (all `2.0`).
    const UNIFIED_PAD: f32 = 2.0;

    /// Paint a [`DiffView`] into `rect` on `surface`, returning
    /// [`DiffViewLayout`] for scroll clamping — same contract as every
    /// deleted per-backend `draw_diff_view`.
    pub(crate) fn paint(
        view: &DiffView,
        surface: &mut dyn PaintSurface,
        theme: &Theme,
        rect: Rect,
        line_height: f32,
    ) -> DiffViewLayout {
        let geometry = view.layout(rect, line_height);
        if rect.width <= 0.0 || rect.height <= 0.0 || line_height <= 0.0 {
            return geometry.as_layout();
        }

        surface.surface_fill_rect(rect, theme.background);

        match view.mode {
            DiffMode::SideBySide => paint_side_by_side(view, surface, theme, &geometry),
            DiffMode::Unified => paint_unified(view, surface, theme, &geometry),
        }

        geometry.as_layout()
    }

    /// Paint `text` clipped to `rect`, inset by `pad` on its left edge and
    /// top-aligned within `rect` (see this module's doc, divergence 1). A
    /// non-positive `rect` or empty `text` paints nothing — mirrors
    /// `macos::diff_view`'s pre-migration `clipped_text` guard.
    fn paint_clipped_text(
        surface: &mut dyn PaintSurface,
        rect: Rect,
        pad: f32,
        text: &str,
        color: Color,
    ) {
        if rect.width <= 0.0 || rect.height <= 0.0 || text.is_empty() {
            return;
        }
        surface.surface_push_clip(rect);
        surface.surface_draw_text_run(
            Rect::new(
                rect.x + pad,
                rect.y,
                (rect.width - pad).max(0.0),
                rect.height,
            ),
            text,
            color,
        );
        surface.surface_pop_clip();
    }

    fn paint_side_by_side(
        view: &DiffView,
        surface: &mut dyn PaintSurface,
        theme: &Theme,
        geometry: &DiffViewGeometry,
    ) {
        let flat = view.flat_rows();

        if let Some(header) = &geometry.header {
            let strip = Rect::new(
                header.left.x,
                header.left.y,
                header.left.width + header.divider.width + header.right.width,
                header.left.height,
            );
            surface.surface_fill_rect(strip, theme.header_bg);
            surface.surface_fill_rect(header.divider, theme.border_fg);

            if let Some(label) = &view.left_label {
                paint_clipped_text(surface, header.left, TEXT_PAD, label, theme.header_fg);
            }
            if let Some(label) = &view.right_label {
                paint_clipped_text(surface, header.right, TEXT_PAD, label, theme.header_fg);
            }
        }

        for line in &geometry.lines {
            let DiffLineContent::Row { row_idx } = line.content else {
                continue;
            };
            let row = flat[row_idx];
            let (left_fg, left_bg, right_fg, right_bg) = row_colors(row.kind, theme);

            let left_r = line.left.expect("side-by-side row has left bounds");
            let right_r = line.right.expect("side-by-side row has right bounds");
            let divider_r = line.divider.expect("side-by-side row has divider bounds");

            surface.surface_fill_rect(left_r, left_bg);
            surface.surface_fill_rect(right_r, right_bg);
            surface.surface_fill_rect(divider_r, theme.border_fg);

            if let Some(text) = &row.left {
                paint_clipped_text(surface, left_r, TEXT_PAD, text, left_fg);
            }
            if let Some(text) = &row.right {
                paint_clipped_text(surface, right_r, TEXT_PAD, text, right_fg);
            }
        }
    }

    fn paint_unified(
        view: &DiffView,
        surface: &mut dyn PaintSurface,
        theme: &Theme,
        geometry: &DiffViewGeometry,
    ) {
        let flat = view.flat_rows();

        for line in &geometry.lines {
            let bounds = line.bounds;

            match line.content {
                DiffLineContent::UnifiedHeader { hunk_idx } => {
                    let header_text = unified_hunk_header(&view.hunks[hunk_idx]);
                    surface.surface_fill_rect(bounds, theme.background);
                    paint_clipped_text(surface, bounds, UNIFIED_PAD, &header_text, theme.accent_fg);
                }
                DiffLineContent::Row { row_idx } => {
                    let row = flat[row_idx];
                    let (prefix, fg, bg) = unified_row_style(row.kind, theme);
                    surface.surface_fill_rect(bounds, bg);

                    let prefix_str = prefix.to_string();
                    let (prefix_w, _) = surface.surface_measure_text(&prefix_str);
                    surface.surface_draw_text_run(
                        Rect::new(
                            bounds.x + UNIFIED_PAD,
                            bounds.y,
                            prefix_w.max(1.0),
                            bounds.height,
                        ),
                        &prefix_str,
                        fg,
                    );

                    let text = unified_row_text(row);
                    let text_x = bounds.x + UNIFIED_PAD + prefix_w + TEXT_PAD;
                    let text_rect = Rect::new(
                        text_x,
                        bounds.y,
                        (bounds.x + bounds.width - text_x).max(0.0),
                        bounds.height,
                    );
                    paint_clipped_text(surface, text_rect, 0.0, text, fg);
                }
            }
        }
    }

    #[cfg(test)]
    mod tests {
        use super::*;
        use crate::backend::ImagePaintResult;
        use crate::event::Viewport;
        use crate::primitives::diff_view::{DiffHunk, DiffRow, DiffRowKind};
        use crate::types::WidgetId;
        use crate::Image;

        /// Records every drawing verb `paint` issues — mirrors
        /// `primitives::chart`/`primitives::text_display`'s own
        /// `RecordingSurface`.
        #[derive(Default)]
        struct RecordingSurface {
            fills: Vec<(Rect, Color)>,
            text_runs: Vec<(Rect, String, Color)>,
            clip_pushes: Vec<Rect>,
            clip_pops: usize,
        }

        impl PaintSurface for RecordingSurface {
            fn surface_begin_frame(&mut self, _viewport: Viewport) {}
            fn surface_end_frame(&mut self) {}
            fn surface_viewport(&self) -> Viewport {
                Viewport::new(200.0, 100.0, 1.0)
            }
            fn surface_line_height(&self) -> f32 {
                16.0
            }
            fn surface_char_width(&self) -> f32 {
                8.0
            }
            fn surface_measure_text(&self, text: &str) -> (f32, f32) {
                (text.chars().count() as f32 * 8.0, 14.0)
            }
            fn surface_fill_rect(&mut self, rect: Rect, color: Color) {
                self.fills.push((rect, color));
            }
            /// Test-only recorder — `paint` never calls this verb
            /// (see this module's own doc for why no primitive here has been
            /// migrated onto it yet); this exists only so `RecordingSurface`
            /// satisfies the trait. Records into the same `fills` list as
            /// `surface_fill_rect` (radius dropped) — no test asserts on it
            /// today.
            fn surface_fill_rounded_rect(&mut self, rect: Rect, _radius: f32, color: Color) {
                self.fills.push((rect, color));
            }
            fn surface_stroke_rect(&mut self, _rect: Rect, _color: Color, _stroke_width: f32) {}
            fn surface_stroke_rounded_rect(
                &mut self,
                _rect: Rect,
                _radius: f32,
                _color: Color,
                _stroke_width: f32,
            ) {
            }
            fn surface_draw_text_run(&mut self, rect: Rect, text: &str, color: Color) {
                self.text_runs.push((rect, text.to_string(), color));
            }
            fn surface_draw_line(
                &mut self,
                _from: crate::Point,
                _to: crate::Point,
                _color: Color,
                _stroke_width: f32,
            ) {
            }
            fn surface_push_clip(&mut self, rect: Rect) {
                self.clip_pushes.push(rect);
            }
            fn surface_pop_clip(&mut self) {
                self.clip_pops += 1;
            }
            fn surface_draw_image(&mut self, _rect: Rect, _image: &Image) -> ImagePaintResult {
                ImagePaintResult::Unsupported
            }
        }

        fn sample_view(mode: DiffMode) -> DiffView {
            DiffView {
                id: WidgetId::new("diff"),
                left: "one\ntwo\n".into(),
                right: "one\nTWO\n".into(),
                left_label: None,
                right_label: None,
                hunks: vec![DiffHunk {
                    left_start: 1,
                    right_start: 1,
                    rows: vec![
                        DiffRow {
                            left: Some("one".into()),
                            right: Some("one".into()),
                            kind: DiffRowKind::Same,
                        },
                        DiffRow {
                            left: Some("two".into()),
                            right: Some("TWO".into()),
                            kind: DiffRowKind::Changed,
                        },
                    ],
                }],
                mode,
                editability: Default::default(),
                scroll_offset: 0,
                focused_pane: Default::default(),
                has_focus: false,
            }
        }

        #[test]
        fn zero_size_rect_paints_nothing() {
            let view = sample_view(DiffMode::SideBySide);
            let mut surface = RecordingSurface::default();
            let layout = paint(
                &view,
                &mut surface,
                &Theme::default(),
                Rect::new(0.0, 0.0, 0.0, 0.0),
                16.0,
            );
            assert_eq!(layout.visible_rows, 0);
            assert!(surface.fills.is_empty());
            assert!(surface.text_runs.is_empty());
        }

        #[test]
        fn side_by_side_paints_row_backgrounds_and_divider() {
            let view = sample_view(DiffMode::SideBySide);
            let theme = Theme::default();
            let mut surface = RecordingSurface::default();
            paint(
                &view,
                &mut surface,
                &theme,
                Rect::new(0.0, 0.0, 100.0, 32.0),
                16.0,
            );

            // 1 full-view background + (left, right, divider) per row × 2 rows.
            assert_eq!(surface.fills.len(), 1 + 3 * 2);
        }

        /// Regression for divergence 1: text paints top-aligned (`y` equal
        /// to the pane rect's own `y`), not vertically centred within
        /// `line_height` the way GTK's pre-migration copy did.
        #[test]
        fn row_text_paints_clipped_and_top_aligned() {
            let view = sample_view(DiffMode::SideBySide);
            let theme = Theme::default();
            let mut surface = RecordingSurface::default();
            paint(
                &view,
                &mut surface,
                &theme,
                Rect::new(0.0, 0.0, 100.0, 32.0),
                16.0,
            );

            assert_eq!(surface.clip_pushes.len(), surface.clip_pops);
            assert!(!surface.text_runs.is_empty());
            let (rect, text, _) = &surface.text_runs[0];
            assert_eq!(text, "one");
            assert_eq!(
                rect.y, 0.0,
                "row 0 text must be top-aligned at the row's own y"
            );
        }

        /// Regression for divergence 2: an overlong header label clips
        /// (pushes a clip at the header strip's own bounds) rather than
        /// ellipsizing.
        #[test]
        fn header_label_paints_clipped_not_ellipsized() {
            let mut view = sample_view(DiffMode::SideBySide);
            view.left_label = Some("a/very/long/path/that/would/overflow.rs".into());
            let theme = Theme::default();
            let mut surface = RecordingSurface::default();
            let layout = paint(
                &view,
                &mut surface,
                &theme,
                Rect::new(0.0, 0.0, 40.0, 32.0),
                16.0,
            );

            assert_eq!(layout.visible_rows, 1, "header steals one row");
            assert_eq!(surface.clip_pushes.len(), surface.clip_pops);
            assert!(
                surface.clip_pushes.iter().any(|r| r.height == 16.0),
                "header label clip uses the header strip's own height"
            );
        }

        #[test]
        fn unified_mode_paints_hunk_header_and_prefix() {
            let view = sample_view(DiffMode::Unified);
            let theme = Theme::default();
            let mut surface = RecordingSurface::default();
            let layout = paint(
                &view,
                &mut surface,
                &theme,
                Rect::new(0.0, 0.0, 100.0, 100.0),
                16.0,
            );

            assert_eq!(layout.total_rows, view.total_rows() + view.hunks.len());
            let header_text = surface
                .text_runs
                .iter()
                .find(|(_, t, _)| t.starts_with("@@"))
                .map(|(_, t, _)| t.clone())
                .expect("hunk header text painted");
            assert_eq!(header_text, "@@ -1,2 +1,2 @@");

            // The `Changed` row's unified prefix is `-`.
            assert!(surface.text_runs.iter().any(|(_, t, _)| t == "-"));
        }

        /// A padding row (`None` on one side) must not push/pop a clip for
        /// the missing side — mirrors every pre-migration backend's `if
        /// let Some(text)` guard.
        #[test]
        fn padding_row_paints_no_clip_for_missing_side() {
            let view = DiffView {
                id: WidgetId::new("diff"),
                left: String::new(),
                right: String::new(),
                left_label: None,
                right_label: None,
                hunks: vec![DiffHunk {
                    left_start: 1,
                    right_start: 1,
                    rows: vec![DiffRow {
                        left: Some("x".into()),
                        right: None,
                        kind: DiffRowKind::Removed,
                    }],
                }],
                mode: DiffMode::SideBySide,
                editability: Default::default(),
                scroll_offset: 0,
                focused_pane: Default::default(),
                has_focus: false,
            };
            let theme = Theme::default();
            let mut surface = RecordingSurface::default();
            paint(
                &view,
                &mut surface,
                &theme,
                Rect::new(0.0, 0.0, 100.0, 16.0),
                16.0,
            );

            assert_eq!(surface.text_runs.len(), 1);
            assert_eq!(surface.text_runs[0].1, "x");
            assert_eq!(surface.clip_pushes.len(), 1);
            assert_eq!(surface.clip_pops, 1);
        }
    }
}

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

    /// Asserts the default field values for a freshly-constructed `DiffView`.
    #[test]
    fn diff_view_field_defaults() {
        let view = DiffView {
            id: WidgetId::new("test"),
            left: String::new(),
            right: String::new(),
            left_label: None,
            right_label: None,
            hunks: vec![],
            mode: DiffMode::default(),
            editability: DiffEditability::default(),
            scroll_offset: 0,
            focused_pane: DiffPane::default(),
            has_focus: false,
        };
        assert_eq!(view.mode, DiffMode::SideBySide);
        assert_eq!(view.editability, DiffEditability::ReadOnly);
        assert_eq!(view.focused_pane, DiffPane::Left);
        assert_eq!(view.scroll_offset, 0);
        assert!(!view.has_focus);
        assert_eq!(view.total_rows(), 0);
    }

    /// `DiffView::total_rows` correctly sums across multiple hunks.
    #[test]
    fn total_rows_sums_hunks() {
        let make_hunk = |n: usize| DiffHunk {
            left_start: 1,
            right_start: 1,
            rows: (0..n)
                .map(|_| DiffRow {
                    left: Some("x".into()),
                    right: Some("x".into()),
                    kind: DiffRowKind::Same,
                })
                .collect(),
        };
        let view = DiffView {
            id: WidgetId::new("t"),
            left: String::new(),
            right: String::new(),
            left_label: None,
            right_label: None,
            hunks: vec![make_hunk(3), make_hunk(5)],
            mode: DiffMode::default(),
            editability: DiffEditability::default(),
            scroll_offset: 0,
            focused_pane: DiffPane::default(),
            has_focus: false,
        };
        assert_eq!(view.total_rows(), 8);
    }

    /// The constructor accepts left and right strings, computes diff hunks,
    /// and stores everything in the resulting struct.
    #[test]
    fn acceptance_criterion_constructor_compiles_and_runs() {
        use crate::diff::compute_hunks;
        let left = "a\nb\n";
        let right = "a\nc\n";
        let view = DiffView {
            id: WidgetId::new("acceptance"),
            left: left.into(),
            right: right.into(),
            left_label: None,
            right_label: None,
            hunks: compute_hunks(left, right),
            mode: DiffMode::SideBySide,
            editability: DiffEditability::ReadOnly,
            scroll_offset: 0,
            focused_pane: DiffPane::Left,
            has_focus: false,
        };
        // Sanity: hunks were computed and the source strings round-trip
        // through the struct without modification.
        assert!(!view.hunks.is_empty(), "expected at least one hunk");
        assert_eq!(view.left, "a\nb\n");
        assert_eq!(view.right, "a\nc\n");
    }

    fn two_hunk_view(mode: DiffMode) -> DiffView {
        DiffView {
            id: WidgetId::new("layout-test"),
            left: String::new(),
            right: String::new(),
            left_label: None,
            right_label: None,
            hunks: vec![
                DiffHunk {
                    left_start: 1,
                    right_start: 1,
                    rows: vec![
                        DiffRow {
                            left: Some("alpha".into()),
                            right: Some("ALPHA".into()),
                            kind: DiffRowKind::Changed,
                        },
                        DiffRow {
                            left: Some("beta".into()),
                            right: Some("beta".into()),
                            kind: DiffRowKind::Same,
                        },
                    ],
                },
                DiffHunk {
                    left_start: 10,
                    right_start: 10,
                    rows: vec![
                        DiffRow {
                            left: Some("gamma".into()),
                            right: None,
                            kind: DiffRowKind::Removed,
                        },
                        DiffRow {
                            left: None,
                            right: Some("delta".into()),
                            kind: DiffRowKind::Added,
                        },
                    ],
                },
            ],
            mode,
            editability: DiffEditability::ReadOnly,
            scroll_offset: 0,
            focused_pane: DiffPane::Left,
            has_focus: false,
        }
    }

    /// `flat_rows` concatenates every hunk's rows, in order, regardless of
    /// mode — the index [`DiffLineContent::Row::row_idx`] refers to.
    #[test]
    fn flat_rows_concatenates_every_hunk() {
        let view = two_hunk_view(DiffMode::SideBySide);
        let flat = view.flat_rows();
        assert_eq!(flat.len(), 4);
        assert_eq!(flat[0].left.as_deref(), Some("alpha"));
        assert_eq!(flat[3].right.as_deref(), Some("delta"));
    }

    /// Non-positive viewport or line height returns an empty geometry without
    /// dividing by zero or underflowing.
    #[test]
    fn zero_size_viewport_returns_empty_geometry() {
        let view = two_hunk_view(DiffMode::SideBySide);
        let geometry = view.layout(Rect::new(0.0, 0.0, 0.0, 10.0), 1.0);
        assert_eq!(geometry.visible_rows, 0);
        assert_eq!(geometry.total_rows, view.total_rows());
        assert!(geometry.lines.is_empty());

        let geometry = view.layout(Rect::new(0.0, 0.0, 10.0, 10.0), 0.0);
        assert_eq!(geometry.visible_rows, 0);
    }

    /// Side-by-side pane geometry: `left_w + DIFF_DIVIDER_W + right_w`
    /// exactly reconstructs the viewport width, and the divider sits at
    /// `viewport.x + left_w`.
    #[test]
    fn side_by_side_panes_reconstruct_viewport_width() {
        let view = two_hunk_view(DiffMode::SideBySide);
        let viewport = Rect::new(5.0, 0.0, 41.0, 10.0);
        let geometry = view.layout(viewport, 1.0);
        let panes = geometry.panes.expect("side-by-side mode has panes");

        assert_eq!(
            panes.left_w + DIFF_DIVIDER_W + panes.right_w,
            viewport.width
        );
        assert_eq!(panes.divider_x, viewport.x + panes.left_w);
    }

    /// A header strip is present only when a label is set, and it
    /// reserves exactly one `line_height` band from the content area.
    #[test]
    fn header_present_only_when_a_label_is_set() {
        let mut view = two_hunk_view(DiffMode::SideBySide);
        let viewport = Rect::new(0.0, 0.0, 40.0, 10.0);

        let no_header = view.layout(viewport, 1.0);
        assert!(no_header.header.is_none());
        assert_eq!(no_header.visible_rows, 10);

        view.left_label = Some("a/main.rs".into());
        let with_header = view.layout(viewport, 1.0);
        let header = with_header.header.expect("label set implies a header");
        assert_eq!(header.left.height, 1.0);
        assert_eq!(with_header.visible_rows, 9, "header steals one row");
    }

    /// `lines` is exactly the scroll-clamped visible window: at
    /// `scroll_offset = 1` on a 2-row-tall viewport, the first display
    /// line is row 1, not row 0.
    #[test]
    fn side_by_side_lines_respect_scroll_offset() {
        let mut view = two_hunk_view(DiffMode::SideBySide);
        view.scroll_offset = 1;
        let geometry = view.layout(Rect::new(0.0, 0.0, 40.0, 2.0), 1.0);
        assert_eq!(geometry.lines.len(), 2);
        assert_eq!(
            geometry.lines[0].content,
            DiffLineContent::Row { row_idx: 1 }
        );
        assert_eq!(
            geometry.lines[1].content,
            DiffLineContent::Row { row_idx: 2 }
        );
    }

    /// Unified mode interleaves a `UnifiedHeader` before each hunk's rows,
    /// and `total_rows` counts both.
    #[test]
    fn unified_lines_interleave_headers_with_rows() {
        let view = two_hunk_view(DiffMode::Unified);
        let geometry = view.layout(Rect::new(0.0, 0.0, 40.0, 100.0), 1.0);
        // 2 headers + 4 rows = 6 display lines, all visible (viewport is
        // tall enough).
        assert_eq!(geometry.total_rows, 6);
        assert_eq!(geometry.lines.len(), 6);
        assert_eq!(
            geometry.lines[0].content,
            DiffLineContent::UnifiedHeader { hunk_idx: 0 }
        );
        assert_eq!(
            geometry.lines[1].content,
            DiffLineContent::Row { row_idx: 0 }
        );
        assert_eq!(
            geometry.lines[2].content,
            DiffLineContent::Row { row_idx: 1 }
        );
        assert_eq!(
            geometry.lines[3].content,
            DiffLineContent::UnifiedHeader { hunk_idx: 1 }
        );
        assert_eq!(
            geometry.lines[4].content,
            DiffLineContent::Row { row_idx: 2 }
        );
        assert_eq!(
            geometry.lines[5].content,
            DiffLineContent::Row { row_idx: 3 }
        );
    }

    /// `row_colors` covers every [`DiffRowKind`] without panicking, and
    /// `Same` uses the same background on both sides (no left/right tint).
    #[test]
    fn row_colors_same_uses_uniform_background() {
        let theme = Theme::default();
        let (_, left_bg, _, right_bg) = row_colors(DiffRowKind::Same, &theme);
        assert_eq!(left_bg, theme.background);
        assert_eq!(right_bg, theme.background);
    }

    /// `unified_row_style` assigns the conventional `-`/`+`/` ` prefixes.
    #[test]
    fn unified_row_style_prefixes() {
        let theme = Theme::default();
        assert_eq!(unified_row_style(DiffRowKind::Removed, &theme).0, '-');
        assert_eq!(unified_row_style(DiffRowKind::Changed, &theme).0, '-');
        assert_eq!(unified_row_style(DiffRowKind::Added, &theme).0, '+');
        assert_eq!(unified_row_style(DiffRowKind::Same, &theme).0, ' ');
    }

    /// `unified_row_text` prefers the left text for `Removed`, otherwise
    /// the right text falling back to the left.
    #[test]
    fn unified_row_text_prefers_left_only_for_removed() {
        let removed = DiffRow {
            left: Some("old".into()),
            right: None,
            kind: DiffRowKind::Removed,
        };
        assert_eq!(unified_row_text(&removed), "old");

        let changed = DiffRow {
            left: Some("old".into()),
            right: Some("new".into()),
            kind: DiffRowKind::Changed,
        };
        assert_eq!(unified_row_text(&changed), "new");
    }

    /// `unified_hunk_header` counts left/right rows independently, so a
    /// hunk with padding rows (unequal removed/added counts) doesn't
    /// inflate either number to `rows.len()`.
    #[test]
    fn unified_hunk_header_excludes_padding_from_counts() {
        let hunk = DiffHunk {
            left_start: 5,
            right_start: 7,
            rows: vec![
                DiffRow {
                    left: Some("old1".into()),
                    right: Some("new1".into()),
                    kind: DiffRowKind::Changed,
                },
                DiffRow {
                    left: Some("old2".into()),
                    right: None,
                    kind: DiffRowKind::Removed,
                },
                DiffRow {
                    left: None,
                    right: Some("new3".into()),
                    kind: DiffRowKind::Added,
                },
            ],
        };
        assert_eq!(unified_hunk_header(&hunk), "@@ -5,2 +7,2 @@");
    }

    #[test]
    fn hit_test_side_by_side_left_pane_returns_row_and_left_pane() {
        let view = two_hunk_view(DiffMode::SideBySide);
        let geometry = view.layout(Rect::new(0.0, 0.0, 40.0, 10.0), 1.0);
        match geometry.hit_test(2.0, 0.5) {
            DiffViewHit::Row { row_idx, pane } => {
                assert_eq!(row_idx, 0);
                assert_eq!(pane, Some(DiffPane::Left));
            }
            other => panic!("expected Row hit, got {other:?}"),
        }
    }

    #[test]
    fn hit_test_side_by_side_right_pane_returns_right() {
        let view = two_hunk_view(DiffMode::SideBySide);
        let geometry = view.layout(Rect::new(0.0, 0.0, 40.0, 10.0), 1.0);
        let panes = geometry.panes.expect("side-by-side has panes");
        let x_in_right = panes.divider_x + DIFF_DIVIDER_W + 1.0;
        match geometry.hit_test(x_in_right, 0.5) {
            DiffViewHit::Row { row_idx, pane } => {
                assert_eq!(row_idx, 0);
                assert_eq!(pane, Some(DiffPane::Right));
            }
            other => panic!("expected Row hit, got {other:?}"),
        }
    }

    #[test]
    fn hit_test_unified_header_returns_hunk_idx() {
        let view = two_hunk_view(DiffMode::Unified);
        let geometry = view.layout(Rect::new(0.0, 0.0, 40.0, 10.0), 1.0);
        // Unified sequence: [Header(0), Row(0), Row(1), Header(1), Row(2), Row(3)].
        assert_eq!(
            geometry.hit_test(2.0, 0.5),
            DiffViewHit::UnifiedHeader { hunk_idx: 0 }
        );
        assert_eq!(
            geometry.hit_test(2.0, 3.5),
            DiffViewHit::UnifiedHeader { hunk_idx: 1 }
        );
    }

    #[test]
    fn hit_test_unified_row_has_no_pane() {
        let view = two_hunk_view(DiffMode::Unified);
        let geometry = view.layout(Rect::new(0.0, 0.0, 40.0, 10.0), 1.0);
        match geometry.hit_test(2.0, 1.5) {
            DiffViewHit::Row { row_idx, pane } => {
                assert_eq!(row_idx, 0);
                assert_eq!(pane, None);
            }
            other => panic!("expected Row hit, got {other:?}"),
        }
    }

    #[test]
    fn hit_test_outside_all_lines_is_empty() {
        let view = two_hunk_view(DiffMode::SideBySide);
        let geometry = view.layout(Rect::new(0.0, 0.0, 40.0, 10.0), 1.0);
        assert_eq!(geometry.hit_test(2.0, 99.0), DiffViewHit::Empty);
    }
}