ghtui 0.2.0

A keyboard-driven terminal client for GitHub, with a pull request diff viewer that goes further than GitHub's
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
//! Pages: documents of styled lines with links, laid out like GitHub's.
//!
//! Builders produce lines from data with *semantic* roles (title, body,
//! link, code, ...), never colors; [`PageView`] maps roles to theme styles.
//! Lines can sit in boxes (rounded outlines, like GitHub's file list, README
//! and comments). Links are URLs: GitHub web URLs for anything ghtui can
//! show itself, so following one works like clicking it on the website.
//! *Items* are the rows you select and open (a file, an issue, a comment);
//! an optional *aside* is GitHub's right-hand sidebar.

#![deny(clippy::arithmetic_side_effects)]

use crate::theme::{Bg, DiffBg, Fg, Syntax};
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::Widget;

use std::collections::HashMap;
use std::ops::Range;

use crate::ui::{Ctx, cols, fill, idx, put, text};

/// Where following a link leads: a URL, or something the page does. Only
/// pages create the actions; Markdown from GitHub can only make URLs.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Link {
    Url(String),
    /// Load the next page of a list.
    More,
    /// Star or unstar the repository.
    Star,
    /// Write a comment.
    Comment,
    /// Edit the list's filter.
    Filter,
    /// Change the list's sort.
    Sort,
    /// Show the list's items in this state (`open`, `closed`...).
    State(String),
    /// Switch branches.
    Branch,
    /// Find a file in the repository.
    FindFile,
    /// A Home section, by its place: its whole list, or what's wrong.
    Section(usize),
    /// Reply quoting the comment `author` wrote `at` a time, its id.
    Quote {
        author: String,
        at: String,
        body: String,
    },
    /// One of a form's rows.
    Form(crate::ui::form::Row),
    /// A run's artifact, by its ID: opening it saves it.
    Artifact {
        id: u64,
        name: String,
    },
    /// A release's asset, by its name: opening it saves it.
    Asset(String),
    /// Something a pull request's review leads to.
    Review(ReviewLink),
    /// A row of a repository's Settings tab ([`crate::settings`]).
    Setting(crate::ui::pages::SettingLink),
    /// A write queued for GitHub, by its place in the queue
    /// ([`crate::offline`]).
    Queued(u64),
}

/// What a row about a review does.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum ReviewLink {
    /// Folds or unfolds a long review's threads, by the review's anchor.
    Fold(String),
    /// A review's own page, by GitHub's number for it.
    Open {
        pr: crate::api::model::PrRef,
        id: u64,
    },
    /// The pull request's changes as the review saw them: up to its
    /// commit, from git.
    AsReviewed {
        pr: crate::api::model::PrRef,
        commit: String,
    },
    /// What changed since the review's commit.
    Since {
        pr: crate::api::model::PrRef,
        commit: String,
    },
    /// Your draft `id`, at `url`: its line in Files changed.
    Draft {
        pr: crate::api::model::PrRef,
        id: u64,
        url: String,
    },
}

impl Link {
    pub fn url(&self) -> Option<&str> {
        match self {
            Link::Url(url) | Link::Review(ReviewLink::Draft { url, .. }) => Some(url),
            _ => None,
        }
    }
}

impl From<String> for Link {
    fn from(url: String) -> Self {
        Link::Url(url)
    }
}

impl From<&str> for Link {
    fn from(url: &str) -> Self {
        Link::Url(url.to_owned())
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Role {
    Body,
    Title,
    Heading,
    Strong,
    Emph,
    Strike,
    Meta,
    Link,
    /// Inline code.
    Code,
    /// A token inside a code block.
    Syntax(Syntax),
    Success,
    Error,
    Accent,
    Added,
    Removed,
    /// A tonal chip.
    Chip(Bg),
    /// A GitHub label chip (`rrggbb`).
    Label(String),
    /// A contribution graph cell, by level (0–4).
    Heat(u8),
    /// What a search on the page matched; stronger on the current match's
    /// line.
    Match,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Seg {
    /// Tabs already turned to spaces, so it's measured as it's drawn.
    text: String,
    pub role: Role,
    /// Index into [`Page::links`].
    pub link: Option<u32>,
}

impl Seg {
    pub fn new(text: impl Into<String>, role: Role) -> Self {
        Self::linked(text, role, None)
    }

    pub fn linked(text: impl Into<String>, role: Role, link: impl Into<Option<u32>>) -> Self {
        Self {
            text: text::expand_tabs(text),
            role,
            link: link.into(),
        }
    }

    pub fn text(&self) -> &str {
        &self.text
    }
}

/// `seg` with each match of `query` picked out (ASCII case doesn't
/// matter).
pub fn highlight(seg: Seg, query: &str) -> Vec<Seg> {
    let q = query.to_ascii_lowercase();
    if q.is_empty() {
        return vec![seg];
    }
    // Lowercasing ASCII keeps every byte where it was.
    let lower = seg.text().to_ascii_lowercase();
    let piece = |text: &str, role: &Role| Seg::linked(text, role.clone(), seg.link);
    let mut out = Vec::new();
    let mut from = 0;
    for found in text::hits(&lower, &q) {
        let (at, end) = (found.start, found.end);
        let (Some(before), Some(hit)) = (seg.text().get(from..at), seg.text().get(at..end)) else {
            continue;
        };
        if !before.is_empty() {
            out.push(piece(before, &seg.role));
        }
        out.push(piece(hit, &Role::Match));
        from = end;
    }
    if out.is_empty() {
        return vec![seg];
    }
    if let Some(rest) = seg.text().get(from..).filter(|r| !r.is_empty()) {
        out.push(piece(rest, &seg.role));
    }
    out
}

/// Where a line sits in a box.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Frame {
    #[default]
    None,
    /// `╭─ title ──── right ─╮`
    Top,
    /// `│ content │`
    Body,
    /// `├────────┤`
    Rule,
    /// `╰────────╯`
    Bottom,
}

/// The background inside a line.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Tone {
    #[default]
    Plain,
    /// A code block.
    Code,
    /// A code line a link points at.
    Marked,
    /// A line a suggested change adds.
    Added,
    /// A line a suggested change replaces.
    Removed,
}

#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct PageLine {
    pub segs: Vec<Seg>,
    /// Columns before the first segment (inside the box, if framed).
    pub indent: u16,
    /// Right-aligned segments (metadata in lists).
    pub right: Vec<Seg>,
    pub frame: Frame,
    pub tone: Tone,
    /// Leading segments that stay put when code scrolls sideways (its
    /// line number).
    pub fixed: u8,
}

impl PageLine {
    /// No text (a gap, or a box border).
    pub fn is_blank(&self) -> bool {
        self.segs.iter().all(|s| s.text.trim().is_empty()) && self.right.is_empty()
    }

    pub fn text(&self) -> String {
        self.segs.iter().map(|s| s.text.as_str()).collect()
    }

    /// A code line's code (after its fixed segments), and the columns
    /// the fixed segments take before it.
    pub fn code(&self) -> Option<(String, usize)> {
        if self.tone == Tone::Plain {
            return None;
        }
        let fixed = usize::from(self.fixed);
        let before = (self.segs.iter().take(fixed))
            .fold(0, |w: usize, s| w.saturating_add(text::width(&s.text)));
        let code = self.segs.iter().skip(fixed).map(|s| s.text.as_str());
        Some((code.collect(), before))
    }

    /// The column in a code line's code where a search's first match on
    /// it starts.
    pub fn first_match(&self) -> Option<usize> {
        let mut col = 0usize;
        for seg in self.segs.iter().skip(usize::from(self.fixed)) {
            if seg.role == Role::Match {
                return Some(col);
            }
            col = col.saturating_add(text::width(&seg.text));
        }
        None
    }

    /// The line with its code (after the fixed segments) scrolled left
    /// by `shift` columns.
    fn shifted(&self, shift: usize) -> PageLine {
        let fixed = usize::from(self.fixed);
        let mut skip = shift;
        let mut segs: Vec<Seg> = self.segs.iter().take(fixed).cloned().collect();
        for seg in self.segs.iter().skip(fixed) {
            if skip == 0 {
                segs.push(seg.clone());
                continue;
            }
            let mut rest = String::new();
            for c in seg.text.chars() {
                let w = text::width(c.encode_utf8(&mut [0; 4]));
                if skip >= w && rest.is_empty() {
                    skip = skip.saturating_sub(w);
                } else {
                    skip = 0;
                    rest.push(c);
                }
            }
            if !rest.is_empty() {
                segs.push(Seg::linked(rest, seg.role.clone(), seg.link));
            }
        }
        PageLine {
            segs,
            ..self.clone()
        }
    }
}

/// A selectable row: lines `start..end`, opened by following `link`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Item {
    pub start: usize,
    pub end: usize,
    pub link: u32,
    /// The columns of its lines it takes (from, how many), when it shares
    /// them with others laid out beside it ([`Page::side_by_side`]).
    pub cols: Option<(u16, u16)>,
}

/// Columns a box's border and padding take on each side.
const BOX_PAD: u16 = 2;
/// Columns between the page and its aside.
pub const ASIDE_GAP: u16 = 3;

/// GitHub's right-hand sidebar: the columns kept for it beside the main
/// column, and what it says once built.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Aside {
    pub width: u16,
    pub lines: Vec<PageLine>,
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Page {
    pub lines: Vec<PageLine>,
    /// Link targets, shared by the aside.
    pub links: Vec<Link>,
    /// Each link's index in `links`.
    link_ids: HashMap<Link, u32>,
    /// Columns of the main column.
    pub width: u16,
    pub items: Vec<Item>,
    /// The sidebar, drawn right of the main column and scrolled with it:
    /// kept only on a page wide enough for one ([`Page::with_aside`]).
    pub aside: Option<Aside>,
    /// Lists take one row per item.
    pub compact: bool,
    /// The line the page opens scrolled to (a linked line), if not the top.
    pub jump: Option<usize>,
    /// The item the page opens selected, if not the first in view.
    pub selects: Option<usize>,
    /// Named places a link's `#fragment` can point at (a comment), by line.
    pub anchors: HashMap<String, usize>,
    /// The lines a search on the page matched, in order.
    pub marks: Vec<usize>,
    /// A file's lines, by number from 1: the item each is.
    pub numbered: Vec<usize>,
}

impl Page {
    pub fn new(width: u16) -> Self {
        Self {
            width: width.max(20),
            ..Self::default()
        }
    }

    /// A page `total` columns wide that keeps a sidebar beside its column,
    /// if there's room for one: 30 columns, and one more for every three
    /// past 140, up to 48.
    pub fn with_aside(total: u16) -> Self {
        if total < 104 {
            return Self::new(total);
        }
        let grown = total.saturating_sub(140).checked_div(3).unwrap_or(0);
        let width = grown.saturating_add(30).min(48);
        Self {
            aside: Some(Aside {
                width,
                lines: Vec::new(),
            }),
            ..Self::new(total.saturating_sub(width.saturating_add(ASIDE_GAP)))
        }
    }

    /// Registers a link target, returning its index.
    pub fn link(&mut self, link: impl Into<Link>) -> u32 {
        let link = link.into();
        if let Some(&i) = self.link_ids.get(&link) {
            return i;
        }
        let i = idx(self.links.len());
        self.links.push(link.clone());
        self.link_ids.insert(link, i);
        i
    }

    /// Names the next line, for links that point at it (`#issuecomment-1`).
    pub fn anchor(&mut self, name: impl Into<String>) {
        let line = self.lines.len();
        self.anchors.entry(name.into()).or_insert(line);
    }

    /// What following link `i` does.
    pub fn target(&self, i: u32) -> Option<&Link> {
        self.links.get(i as usize)
    }

    /// The item following `link` nearest item `near`; any takes the place of "Load more".
    pub fn find(&self, link: &Link, near: usize) -> Option<usize> {
        let same = |l: &Link| match (l, link) {
            // An edited comment is still the same comment.
            (Link::Quote { at, .. }, Link::Quote { at: was, .. }) => at == was,
            _ => l == link || *link == Link::More,
        };
        let items = self.items.iter().enumerate();
        let found = items.filter(|(_, it)| self.target(it.link).is_some_and(same));
        found.map(|(i, _)| i).min_by_key(|i| i.abs_diff(near))
    }

    pub fn push(&mut self, line: PageLine) {
        self.lines.push(line);
    }

    /// A line of `segs`, `indent` columns in, with `right` on its right.
    pub(crate) fn add(&mut self, frame: Frame, indent: u16, segs: Vec<Seg>, right: Vec<Seg>) {
        self.lines.push(PageLine {
            segs,
            indent,
            right,
            frame,
            tone: Tone::Plain,
            fixed: 0,
        });
    }

    /// A gap line (none at the top, never two in a row).
    pub fn blank(&mut self) {
        if self
            .lines
            .last()
            .is_some_and(|l| !(l.is_blank() && l.frame == Frame::None))
        {
            self.lines.push(PageLine::default());
        }
    }

    /// A line of segments.
    pub fn line(&mut self, segs: Vec<Seg>) {
        self.add(Frame::None, 0, segs, Vec::new());
    }

    /// A line with a single link segment.
    pub fn link_line(
        &mut self,
        text: impl Into<String>,
        url: impl Into<Link>,
        role: Role,
        indent: u16,
    ) -> u32 {
        let link = self.link(url);
        self.add(
            Frame::None,
            indent,
            vec![Seg::linked(text, role, link)],
            Vec::new(),
        );
        link
    }

    /// Columns for text on a line with this frame and indent.
    pub fn room(&self, frame: Frame, indent: u16) -> u16 {
        let inner = match frame {
            Frame::None => self.width,
            _ => self.width.saturating_sub(2 * BOX_PAD),
        };
        inner.saturating_sub(indent).max(8)
    }

    /// Word-wraps segments into lines `indent` columns in.
    pub fn wrapped(&mut self, segs: Vec<Seg>, indent: u16, frame: Frame) {
        let width = usize::from(self.room(frame, indent));
        for segs in wrap_segs(segs, width) {
            self.add(frame, indent, segs, Vec::new());
        }
    }

    /// A thin rule across the line (GitHub's header borders, Markdown's
    /// `---`).
    pub fn rule(&mut self, indent: u16, frame: Frame) {
        let rule = "─".repeat(usize::from(self.room(frame, indent)));
        self.add(frame, indent, vec![Seg::new(rule, Role::Meta)], Vec::new());
    }

    /// Opens a box: `╭─ title ──── right ─╮`.
    pub fn box_top(&mut self, title: Vec<Seg>, right: Vec<Seg>) {
        self.blank_before_box();
        self.add(Frame::Top, 0, title, right);
    }

    pub fn box_rule(&mut self) {
        self.add(Frame::Rule, 0, Vec::new(), Vec::new());
    }

    pub fn box_bottom(&mut self) {
        // No empty line just inside the bottom edge.
        while self
            .lines
            .last()
            .is_some_and(|l| l.frame == Frame::Body && l.is_blank() && l.tone == Tone::Plain)
        {
            self.lines.pop();
        }
        self.add(Frame::Bottom, 0, Vec::new(), Vec::new());
    }

    /// An empty line inside a box.
    pub fn box_gap(&mut self) {
        if self
            .lines
            .last()
            .is_some_and(|l| !(l.frame == Frame::Body && l.is_blank()) && l.frame != Frame::Top)
        {
            self.add(Frame::Body, 0, Vec::new(), Vec::new());
        }
    }

    /// A line inside a box.
    pub fn box_line(&mut self, segs: Vec<Seg>, right: Vec<Seg>, indent: u16) {
        self.add(Frame::Body, indent, segs, right);
    }

    fn blank_before_box(&mut self) {
        if self.lines.last().is_some_and(|l| l.frame == Frame::Bottom) {
            self.lines.push(PageLine::default());
            return;
        }
        self.blank();
    }

    /// Marks lines `start..` (to the end so far) as one item opening `link`.
    pub fn item(&mut self, start: usize, link: u32) {
        let end = self.lines.len();
        // Gaps before a box aren't part of it.
        let gaps = self.lines.iter().skip(start);
        let start = start.saturating_add(
            gaps.take_while(|l| l.frame == Frame::None && l.is_blank())
                .count(),
        );
        if end > start {
            self.items.push(Item {
                start,
                end,
                link,
                cols: None,
            });
        }
    }

    /// Lays out pages side by side, `gap` columns apart: `f` builds the
    /// one `widths[i]` wide (sharing this page's links), and their lines
    /// are put together row by row. Their items keep to their columns,
    /// in order, column by column.
    pub fn side_by_side(&mut self, widths: &[u16], gap: u16, mut f: impl FnMut(usize, &mut Page)) {
        let mut columns = Vec::new();
        for (i, width) in widths.iter().enumerate() {
            let mut column = Page::new(*width);
            column.compact = self.compact;
            column.links = std::mem::take(&mut self.links);
            column.link_ids = std::mem::take(&mut self.link_ids);
            f(i, &mut column);
            self.links = std::mem::take(&mut column.links);
            self.link_ids = std::mem::take(&mut column.link_ids);
            columns.push(column);
        }
        let base = self.lines.len();
        let rows = columns.iter().map(|c| c.lines.len()).max().unwrap_or(0);
        for row in 0..rows {
            let mut segs = Vec::new();
            for (i, column) in columns.iter().enumerate() {
                if i > 0 {
                    segs.push(Seg::new(" ".repeat(usize::from(gap)), Role::Body));
                }
                match column.lines.get(row) {
                    Some(line) => segs.extend(flatten(line, column.width)),
                    None => segs.push(Seg::new(" ".repeat(usize::from(column.width)), Role::Body)),
                }
            }
            self.add(Frame::None, 0, segs, Vec::new());
        }
        let mut x = 0u16;
        for column in &columns {
            for it in &column.items {
                self.items.push(Item {
                    start: base.saturating_add(it.start),
                    end: base.saturating_add(it.end),
                    link: it.link,
                    cols: Some((x, column.width)),
                });
            }
            x = x.saturating_add(column.width).saturating_add(gap);
        }
    }

    /// Builds the sidebar, if the page keeps one, with `f`, which gets a
    /// page as wide as it that shares this page's links. False if it
    /// doesn't: what the sidebar would say goes in the column.
    pub fn build_aside(&mut self, f: impl FnOnce(&mut Page)) -> bool {
        let Some(Aside { width, .. }) = self.aside else {
            return false;
        };
        let mut aside = Page::new(width);
        aside.links = std::mem::take(&mut self.links);
        aside.link_ids = std::mem::take(&mut self.link_ids);
        f(&mut aside);
        self.links = std::mem::take(&mut aside.links);
        self.link_ids = std::mem::take(&mut aside.link_ids);
        let lines = aside.lines;
        self.aside = Some(Aside { width, lines });
        true
    }

    /// Rows the page takes (the longer of the column and the aside).
    /// Where sections start: boxes, and headings.
    pub fn sections(&self) -> Vec<usize> {
        let starts = self.lines.iter().enumerate().filter(|(_, l)| {
            l.frame == Frame::Top
                || l.segs
                    .first()
                    .is_some_and(|s| matches!(s.role, Role::Heading | Role::Title))
        });
        // A heading wrapped onto several lines starts one section.
        let mut out = Vec::new();
        let mut previous = None;
        for (i, _) in starts {
            if previous.is_none_or(|p: usize| p.saturating_add(1) != i) {
                out.push(i);
            }
            previous = Some(i);
        }
        out
    }

    /// Picks out `query` on every line it's on, and marks those lines
    /// for `n`/`N`.
    pub fn mark(&mut self, query: &str) {
        let q = query.to_ascii_lowercase();
        for (i, line) in self.lines.iter_mut().enumerate() {
            if text::has(&line.text().to_ascii_lowercase(), &q) {
                let segs = std::mem::take(&mut line.segs);
                line.segs = segs.into_iter().flat_map(|s| highlight(s, &q)).collect();
                self.marks.push(i);
            }
        }
    }

    /// Columns code can scroll left by before its longest line ends.
    pub fn wide(&self) -> usize {
        let code = self.lines.iter().filter(|l| l.tone != Tone::Plain);
        let width = |l: &PageLine| l.segs.iter().map(|s| text::width(&s.text)).sum::<usize>();
        let longest = code.map(width).max().unwrap_or(0);
        longest.saturating_sub(usize::from(self.width) / 2)
    }

    pub fn height(&self) -> usize {
        let aside = self.aside.as_ref().map_or(0, |a| a.lines.len());
        self.lines.len().max(aside)
    }

    /// The first line of the main column with a link to `link`.
    pub fn line_of(&self, link: &Link) -> Option<usize> {
        let id = *self.link_ids.get(link)?;
        (self.lines.iter()).position(|l| l.segs.iter().any(|s| s.link == Some(id)))
    }

    /// The item containing `line`.
    pub fn item_at(&self, line: usize) -> Option<usize> {
        self.items
            .iter()
            .position(|i| (i.start..i.end).contains(&line))
    }
}

/// `text` wrapped to `max` columns as a page wraps it: blank lines and
/// indentation kept, tabs turned to spaces, words longer than a line broken.
pub fn wrap(text: &str, max: usize) -> Vec<String> {
    wrap_segs(vec![Seg::new(text.trim_end(), Role::Body)], max.max(1))
        .into_iter()
        .map(|line| line.into_iter().map(|s| s.text).collect())
        .collect()
}

/// Splits segments into lines of at most `width` columns, breaking at
/// spaces (or mid-word for words longer than a line). Newlines in segment
/// text force breaks.
pub(crate) fn wrap_segs(segs: Vec<Seg>, width: usize) -> Vec<Vec<Seg>> {
    let mut lines: Vec<Vec<Seg>> = vec![Vec::new()];
    let mut used = 0usize;
    let push = |lines: &mut Vec<Vec<Seg>>, seg: &Seg, text: &str| {
        let Some(line) = lines.last_mut() else {
            return;
        };
        match line.last_mut() {
            Some(last) if last.role == seg.role && last.link == seg.link => {
                last.text.push_str(text);
            }
            _ => line.push(Seg {
                text: text.to_owned(),
                role: seg.role.clone(),
                link: seg.link,
            }),
        }
    };
    for seg in segs {
        for (n, part) in seg.text.split('\n').enumerate() {
            if n > 0 {
                lines.push(Vec::new());
                used = 0;
            }
            // Words with the spaces that follow them.
            for word in part.split_inclusive(' ') {
                let w = text::width(word.trim_end());
                if used > 0 && used.saturating_add(w) > width {
                    lines.push(Vec::new());
                    used = 0;
                    if word.trim().is_empty() {
                        continue;
                    }
                }
                if w > width {
                    // Hard-break a long word.
                    let mut chunk = String::new();
                    for (g, gw) in text::graphemes(word) {
                        if used.saturating_add(gw) > width {
                            push(&mut lines, &seg, &chunk);
                            chunk.clear();
                            lines.push(Vec::new());
                            used = 0;
                        }
                        chunk.push_str(g);
                        used = used.saturating_add(gw);
                    }
                    push(&mut lines, &seg, &chunk);
                    continue;
                }
                push(&mut lines, &seg, word);
                used = used.saturating_add(text::width(word));
            }
        }
    }
    // Drop trailing spaces.
    for last in lines.iter_mut().filter_map(|l| l.last_mut()) {
        last.text.truncate(last.text.trim_end().len());
    }
    lines
}

const PAGE_BG: Bg = Bg::ContainerLow;
const CODE_BG: Bg = Bg::Diff(DiffBg::Context);
const MARKED_BG: Bg = Bg::DiffSelected(DiffBg::Context);

/// Where a page's columns go in `area`: centered, as on GitHub.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Columns {
    pub main_x: u16,
    pub aside_x: Option<u16>,
}

pub fn columns(page: &Page, area: Rect) -> Columns {
    let aside = (page.aside.as_ref()).map(|a| ASIDE_GAP.saturating_add(a.width));
    let total = page.width.saturating_add(aside.unwrap_or(0));
    let main_x = area.x.saturating_add(area.width.saturating_sub(total) / 2);
    Columns {
        main_x,
        aside_x: aside.map(|_| main_x.saturating_add(page.width).saturating_add(ASIDE_GAP)),
    }
}

/// A link's place on screen (for letter hints).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Spot {
    pub x: u16,
    pub y: u16,
    pub link: u32,
}

/// What's under a screen position.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct PageHit {
    /// A line of the main column.
    pub line: Option<usize>,
    pub link: Option<u32>,
}

/// Where a line's text goes on a row from `x`, `width` wide: its first
/// column and how many it has (none on a box's edge).
fn inside(line: &PageLine, x: u16, width: u16) -> Option<(u16, u16)> {
    match line.frame {
        Frame::None => Some((
            x.saturating_add(line.indent),
            width.saturating_sub(line.indent),
        )),
        Frame::Body => Some((
            x.saturating_add(BOX_PAD).saturating_add(line.indent),
            width.saturating_sub((2 * BOX_PAD).saturating_add(line.indent)),
        )),
        Frame::Top => Some((x.saturating_add(3), width.saturating_sub(6))),
        Frame::Rule | Frame::Bottom => None,
    }
}

/// Segments of a line placed on a row: `(x, visible text, seg)`.
fn place(line: &PageLine, x: u16, width: u16) -> Vec<(u16, String, &Seg)> {
    let Some((tx, tw)) = inside(line, x, width) else {
        return Vec::new();
    };
    // Between the sides; a top edge keeps a column of rule on each.
    let gap = if line.frame == Frame::Top { 4 } else { 2 };
    // The right side gets at most half when there's a left side too.
    let right_cap = if line.segs.is_empty() { tw } else { tw / 2 };
    let right_w = line
        .right
        .iter()
        .map(|s| cols(text::width(&s.text)))
        .fold(0, u16::saturating_add)
        .min(right_cap);
    let left_w = if right_w > 0 {
        tw.saturating_sub(right_w.saturating_add(gap))
    } else {
        tw
    };
    let mut out = Vec::new();
    lay_out(&mut out, &line.segs, tx, left_w);
    let right_x = tx.saturating_add(tw.saturating_sub(right_w));
    lay_out(&mut out, &line.right, right_x, right_w);
    out
}

/// `segs` from `x` on, cut to `room` columns.
fn lay_out<'a>(out: &mut Vec<(u16, String, &'a Seg)>, segs: &'a [Seg], mut x: u16, room: u16) {
    let mut room = usize::from(room);
    for seg in segs {
        if room == 0 {
            break;
        }
        let shown = text::truncate(&seg.text, room);
        let w = text::width(&shown);
        room = room.saturating_sub(w);
        out.push((x, shown, seg));
        x = x.saturating_add(cols(w));
    }
}

/// A line `width` columns wide drawn as plain segments, its box's edges
/// and all, as [`PageView`] would draw it: to lay it beside others.
fn flatten(line: &PageLine, width: u16) -> Vec<Seg> {
    let w = usize::from(width);
    // Each column's text and how it looks; `None` is the second column
    // of a wide character.
    let blank = Some((" ".to_owned(), Role::Body, None));
    let mut cells: Vec<Option<(String, Role, Option<u32>)>> = vec![blank; w];
    let put = |cells: &mut Vec<_>, x: usize, text: &str, role: Role, link: Option<u32>| {
        if let Some(cell) = cells.get_mut(x) {
            *cell = Some((text.to_owned(), role, link));
        }
    };
    let edges = match line.frame {
        Frame::Top => Some(("╭", "─", "╮")),
        Frame::Rule => Some(("├", "─", "┤")),
        Frame::Bottom => Some(("╰", "─", "╯")),
        Frame::Body => Some(("│", " ", "│")),
        Frame::None => None,
    };
    if let Some((left, middle, right)) = edges {
        for x in 0..w {
            let edge = match x {
                0 => left,
                x if x.saturating_add(1) == w => right,
                _ => middle,
            };
            put(&mut cells, x, edge, Role::Meta, None);
        }
    }
    for (sx, shown, seg) in place(line, 0, width) {
        let mut x = usize::from(sx);
        // Titles sit in gaps cut into a top edge.
        if line.frame == Frame::Top {
            let after = x.saturating_add(text::width(&shown));
            for gap in [x.saturating_sub(1), after] {
                put(&mut cells, gap, " ", Role::Body, None);
            }
        }
        for c in shown.chars() {
            let mut buf = [0; 4];
            let c = c.encode_utf8(&mut buf);
            let cw = text::width(c);
            if x.saturating_add(cw) > w {
                break;
            }
            put(&mut cells, x, c, seg.role.clone(), seg.link);
            for k in 1..cw {
                if let Some(cell) = cells.get_mut(x.saturating_add(k)) {
                    *cell = None;
                }
            }
            x = x.saturating_add(cw);
        }
    }
    let mut out: Vec<Seg> = Vec::new();
    for (text, role, link) in cells.into_iter().flatten() {
        match out.last_mut() {
            Some(last) if last.role == role && last.link == link => last.text.push_str(&text),
            _ => out.push(Seg::linked(text, role, link)),
        }
    }
    out
}

/// Visible links' positions, main column then aside, top to bottom.
pub fn spots(page: &Page, area: Rect, scroll: usize) -> Vec<Spot> {
    let layout = columns(page, area);
    let mut out = Vec::new();
    let mut add = |lines: &[PageLine], x: u16, width: u16| {
        for (line, y) in lines.iter().skip(scroll).zip(area.top()..area.bottom()) {
            let mut seen = Vec::new();
            for (sx, _, seg) in place(line, x, width) {
                if let Some(link) = seg.link
                    && !seen.contains(&link)
                {
                    seen.push(link);
                    out.push(Spot { x: sx, y, link });
                }
            }
        }
    };
    add(&page.lines, layout.main_x, page.width);
    if let (Some(ax), Some(a)) = (layout.aside_x, &page.aside) {
        add(&a.lines, ax, a.width);
    }
    out.sort_by_key(|s| (s.y, s.x));
    out
}

/// What's at `(x, y)`.
pub fn hit(page: &Page, area: Rect, scroll: usize, x: u16, y: u16) -> PageHit {
    if !(area.y..area.bottom()).contains(&y) {
        return PageHit::default();
    }
    let row = scroll.saturating_add(usize::from(y.saturating_sub(area.y)));
    let layout = columns(page, area);
    let link_at = |line: &PageLine, lx: u16, width: u16| {
        place(line, lx, width)
            .into_iter()
            .find(|(sx, shown, _)| (*sx..sx.saturating_add(cols(text::width(shown)))).contains(&x))
            .and_then(|(_, _, seg)| seg.link)
    };
    if let (Some(ax), Some(a)) = (layout.aside_x, &page.aside)
        && x >= ax
    {
        let link = a.lines.get(row).and_then(|l| link_at(l, ax, a.width));
        return PageHit { line: None, link };
    }
    let Some(line) = page.lines.get(row) else {
        return PageHit::default();
    };
    PageHit {
        line: Some(row),
        link: link_at(line, layout.main_x, page.width),
    }
}

/// A letter hint drawn over a link.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HintLabel {
    pub x: u16,
    pub y: u16,
    pub label: String,
}

/// Letter hints over the links they follow, in `area`.
pub fn draw_hints(theme: &crate::theme::Theme, hints: &[HintLabel], area: Rect, buf: &mut Buffer) {
    for hint in hints {
        let style = theme
            .fill(Bg::TertiaryContainer)
            .add_modifier(Modifier::BOLD);
        // Just before the link (over the space, padding or icon there),
        // so the link's own text stays readable.
        let width = cols(text::width(&hint.label));
        let x = hint
            .x
            .checked_sub(width)
            .filter(|x| *x >= area.x)
            .unwrap_or(hint.x);
        Span::styled(hint.label.clone(), style).render(
            Rect {
                x,
                y: hint.y,
                width,
                height: 1,
            },
            buf,
        );
    }
}

/// Renders a page scrolled to `scroll`, with `selected` item highlighted
/// and the search match on line `current` marked as the one gone to.
pub struct PageView<'a> {
    pub ctx: Ctx<'a>,
    pub page: &'a Page,
    pub scroll: usize,
    pub selected: Option<usize>,
    /// Where a selection of several items started, to `selected`.
    pub from: Option<usize>,
    pub current: Option<usize>,
    pub hints: &'a [HintLabel],
    /// Columns code is scrolled left by.
    pub shift: usize,
    /// The word cursor: its line, and its columns in the line's code.
    pub word: Option<(usize, Range<usize>)>,
}

impl Widget for PageView<'_> {
    fn render(self, area: Rect, buf: &mut Buffer) {
        let theme = self.ctx.theme;
        fill(buf, area, theme, PAGE_BG);
        let layout = columns(self.page, area);
        // The selected lines: an item's, or a run of items'.
        let items = |i: Option<usize>| i.and_then(|i| self.page.items.get(i)).copied();
        // An item beside others is marked in its own columns, below.
        let beside = items(self.selected).filter(|s| s.cols.is_some() && self.from.is_none());
        let selected =
            items(self.selected)
                .filter(|_| beside.is_none())
                .map(|s| match items(self.from) {
                    Some(f) => s.start.min(f.start)..s.end.max(f.end),
                    None => s.start..s.end,
                });
        for (row, y) in (area.top()..area.bottom()).enumerate() {
            let i = self.scroll.saturating_add(row);
            if let Some(line) = self.page.lines.get(i) {
                let sel = selected.as_ref().is_some_and(|s| s.contains(&i));
                let here = self.current == Some(i);
                self.line(
                    buf,
                    line,
                    layout.main_x,
                    y,
                    self.page.width,
                    sel || here,
                    here,
                );
                if let Some((_, cols)) = self.word.as_ref().filter(|(at, _)| *at == i) {
                    self.word(buf, line, (layout.main_x, y), cols);
                }
                if let Some(Item {
                    cols: Some((from, width)),
                    ..
                }) = beside.filter(|s| (s.start..s.end).contains(&i))
                {
                    // Just inside its box's edges, as a framed line's.
                    let x = layout.main_x.saturating_add(from).saturating_add(1);
                    let band = Rect {
                        x,
                        y,
                        width: width.saturating_sub(2),
                        height: 1,
                    }
                    .intersection(area);
                    if let Some(bg) = theme.fill(Bg::Selected).bg {
                        buf.set_style(band, Style::new().bg(bg));
                    }
                    put(buf, x, y, "▌", theme.accent(Bg::Selected));
                }
            }
            if let (Some(ax), Some(a)) = (layout.aside_x, &self.page.aside)
                && let Some(line) = a.lines.get(i)
            {
                self.line(buf, line, ax, y, a.width, false, false);
            }
        }
        self.scrollbar(area, buf);
        draw_hints(theme, self.hints, area, buf);
    }
}

impl PageView<'_> {
    #[expect(
        clippy::too_many_arguments,
        reason = "a line, where, and how it's marked"
    )]
    fn line(
        &self,
        buf: &mut Buffer,
        line: &PageLine,
        x: u16,
        y: u16,
        width: u16,
        sel: bool,
        current: bool,
    ) {
        let theme = self.ctx.theme;
        let row = |x: u16, w: u16| Rect {
            x,
            y,
            width: w,
            height: 1,
        };
        let inner_bg = match (line.tone, sel) {
            _ if current => Bg::Selected,
            (Tone::Code, _) => CODE_BG,
            (Tone::Marked, _) => MARKED_BG,
            (Tone::Added, _) => Bg::Diff(DiffBg::Added),
            (Tone::Removed, _) => Bg::Diff(DiffBg::Removed),
            (Tone::Plain, true) => Bg::Selected,
            (Tone::Plain, false) => PAGE_BG,
        };
        let framed = line.frame != Frame::None;
        // Backgrounds.
        if sel {
            // The stripe sits in the gutter, or just inside the box.
            let band = if framed {
                row(x.saturating_add(1), width.saturating_sub(2))
            } else {
                row(x.saturating_sub(2), width.saturating_add(2))
            };
            fill(buf, band, theme, Bg::Selected);
            put(buf, band.x, y, "▌", theme.accent(Bg::Selected));
        } else if line.tone != Tone::Plain {
            let band = if framed {
                row(x.saturating_add(1), width.saturating_sub(2))
            } else {
                row(x, width)
            };
            fill(buf, band, theme, inner_bg);
        }
        // Borders.
        let border = theme.separator(PAGE_BG);
        let rule = |buf: &mut Buffer, left: &str, right: &str| {
            let middle = "─".repeat(usize::from(width.saturating_sub(2)));
            put(buf, x, y, &format!("{left}{middle}{right}"), border);
        };
        match line.frame {
            Frame::None => {}
            Frame::Top => rule(buf, "╭", "╮"),
            Frame::Rule => rule(buf, "├", "┤"),
            Frame::Bottom => rule(buf, "╰", "╯"),
            Frame::Body => {
                put(buf, x, y, "│", border);
                put(
                    buf,
                    x.saturating_add(width.saturating_sub(1)),
                    y,
                    "│",
                    border,
                );
            }
        }
        // Text.
        let shifted;
        let line = if self.shift > 0 && line.tone != Tone::Plain {
            shifted = line.shifted(self.shift);
            &shifted
        } else {
            line
        };
        let placed = place(line, x, width);
        if line.frame == Frame::Top {
            // Titles sit in gaps cut into the top edge.
            for (sx, shown, _) in &placed {
                let w = cols(text::width(shown));
                fill(
                    buf,
                    row(sx.saturating_sub(1), w.saturating_add(2)),
                    theme,
                    PAGE_BG,
                );
            }
        }
        for (sx, shown, seg) in placed {
            let w = cols(text::width(&shown));
            let style = match seg.role {
                Role::Match if current => theme.fill(Bg::Primary),
                _ => self.style(&seg.role, inner_bg),
            };
            Line::from(Span::styled(shown, style)).render(row(sx, w), buf);
        }
    }

    /// Shows columns `cols` of a code line's code, drawn from `(x, y)`,
    /// as the word under the cursor.
    fn word(&self, buf: &mut Buffer, line: &PageLine, (x, y): (u16, u16), cols: &Range<usize>) {
        let (Some((_, before)), Some((tx, tw))) = (line.code(), inside(line, x, self.page.width))
        else {
            return;
        };
        let code_x = usize::from(tx).saturating_add(before);
        let end = usize::from(tx.saturating_add(tw));
        let at = |c: usize| {
            let c = code_x.saturating_add(c.saturating_sub(self.shift));
            u16::try_from(c.min(end)).unwrap_or(u16::MAX)
        };
        let from = at(cols.start);
        let area = Rect {
            x: from,
            y,
            width: at(cols.end).saturating_sub(from),
            height: 1,
        };
        buf.set_style(area, Style::new().add_modifier(Modifier::REVERSED));
    }

    fn scrollbar(&self, area: Rect, buf: &mut Buffer) {
        let total = self.page.height();
        let h = usize::from(area.height);
        if total <= h || h == 0 || area.width < 2 {
            return;
        }
        let thumb = h
            .saturating_mul(h)
            .checked_div(total)
            .unwrap_or(h)
            .clamp(1, h);
        let top = self
            .scroll
            .saturating_mul(h.saturating_sub(thumb))
            .checked_div(total.saturating_sub(h))
            .unwrap_or(0);
        let x = area.right().saturating_sub(1);
        for r in top..top.saturating_add(thumb).min(h) {
            let y = area.y.saturating_add(cols(r));
            put(buf, x, y, "▐", self.ctx.theme.separator(PAGE_BG));
        }
    }

    fn style(&self, role: &Role, bg: Bg) -> Style {
        role_style(self.ctx.theme, role, bg)
    }
}

/// How text in `role` looks on `bg`.
pub(crate) fn role_style(theme: &crate::theme::Theme, role: &Role, bg: Bg) -> Style {
    match role {
        Role::Body => theme.body(bg),
        Role::Title => theme.title(bg),
        Role::Heading => theme.accent(bg).add_modifier(Modifier::BOLD),
        Role::Strong => theme.body(bg).add_modifier(Modifier::BOLD),
        Role::Emph => theme.body(bg).add_modifier(Modifier::ITALIC),
        Role::Strike => theme.meta(bg).add_modifier(Modifier::CROSSED_OUT),
        Role::Meta => theme.meta(bg),
        Role::Link | Role::Accent => theme.accent(bg),
        Role::Code => match bg {
            Bg::Diff(_) | Bg::DiffSelected(_) => theme.style(Fg::Syntax(Syntax::String), bg),
            // GitHub's gray chip.
            _ => theme.fill(Bg::ContainerHigh),
        },
        Role::Syntax(s) => match bg {
            Bg::Diff(_) | Bg::DiffSelected(_) => theme.style(Fg::Syntax(*s), bg),
            _ => theme.body(bg),
        },
        Role::Success => theme.style(Fg::Success, bg),
        Role::Error => theme.error(bg),
        Role::Added => theme.style(Fg::DiffAddedSign, bg),
        Role::Removed => theme.style(Fg::DiffRemovedSign, bg),
        Role::Chip(chip) => theme.fill(*chip),
        Role::Label(color) => theme.label_chip(color),
        Role::Heat(level) => theme.style(Fg::Heat(*level), bg),
        Role::Match => theme.fill(Bg::TertiaryContainer),
    }
}

/// Scrolls as little as possible to show rows `start..end` with `margin`
/// rows of context (less if the range is taller than the view).
pub fn reveal(
    start: usize,
    end: usize,
    scroll: usize,
    height: usize,
    total: usize,
    margin: usize,
) -> usize {
    let height = height.max(1);
    let max = total.saturating_sub(height);
    let margin = margin.min(height.saturating_sub(end.saturating_sub(start)) / 2);
    let mut scroll = scroll.min(max);
    if end.saturating_add(margin) > scroll.saturating_add(height) {
        scroll = end.saturating_add(margin).saturating_sub(height);
    }
    if start < scroll.saturating_add(margin) {
        scroll = start.saturating_sub(margin);
    }
    scroll.min(max)
}

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

    fn texts(lines: &[Vec<Seg>]) -> Vec<String> {
        lines
            .iter()
            .map(|l| l.iter().map(|s| s.text.as_str()).collect())
            .collect()
    }

    #[test]
    fn wraps_across_segments() {
        let segs = vec![
            Seg::new("hello ", Role::Body),
            Seg::new("bold words ", Role::Strong),
            Seg::new("and more text", Role::Body),
        ];
        let lines = wrap_segs(segs, 12);
        assert_eq!(texts(&lines), ["hello bold", "words and", "more text"]);
        assert_eq!(lines[0][1].role, Role::Strong);
    }

    #[test]
    fn wraps_words() {
        assert_eq!(wrap("one two three", 7), ["one two", "three"]);
        assert_eq!(wrap("a\n\nabcdefghij", 4), ["a", "", "abcd", "efgh", "ij"]);
        assert_eq!(wrap("", 4), [""]);
        assert_eq!(wrap("a\r\n\tb", 10), ["a", "    b"]);
    }

    #[test]
    fn links_are_shared_and_items_mark_rows() {
        let mut page = Page::new(40);
        page.line(vec![Seg::new("title", Role::Title)]);
        page.blank();
        let start = page.lines.len();
        let a = page.link_line("one", "https://github.com/a", Role::Link, 0);
        page.line(vec![Seg::new("its second line", Role::Meta)]);
        page.item(start, a);
        let b = page.link_line("again", "https://github.com/a", Role::Link, 0);
        assert_eq!(a, b, "same URL, same link");
        assert_eq!(
            page.items,
            [Item {
                start: 2,
                end: 4,
                link: a,
                cols: None,
            }]
        );
        assert_eq!(page.item_at(3), Some(0));
        assert_eq!(page.item_at(4), None);
    }

    #[test]
    fn boxes_wrap_inside_their_borders_and_place_titles_on_the_edge() {
        let mut page = Page::new(24);
        page.box_top(
            vec![Seg::new("Title", Role::Strong)],
            vec![Seg::new("3", Role::Meta)],
        );
        page.wrapped(
            vec![Seg::new("one two three four five", Role::Body)],
            0,
            Frame::Body,
        );
        page.box_gap();
        page.box_bottom();
        let texts: Vec<String> = page.lines.iter().map(PageLine::text).collect();
        assert_eq!(texts, ["Title", "one two three four", "five", ""]);
        assert_eq!(
            page.lines.last().unwrap().frame,
            Frame::Bottom,
            "no gap above the edge"
        );

        let area = Rect::new(0, 0, 24, 10);
        let spots = spots(&page, area, 0);
        assert!(spots.is_empty());
        let placed = place(&page.lines[0], 0, 24);
        assert_eq!(placed[0].0, 3, "after `╭─ `");
        assert_eq!(placed[1].0, 24 - 3 - 1, "right title ends before ` ─╮`");
    }

    #[test]
    fn hits_and_spots_find_links_in_both_columns() {
        let mut page = Page::with_aside(110);
        let link = page.link("https://github.com/a");
        page.line(vec![
            Seg::new("see ", Role::Body),
            Seg::linked("here", Role::Link, link),
        ]);
        assert!(page.build_aside(|aside| {
            aside.link_line("b", "https://github.com/b", Role::Link, 0);
        }));
        let area = Rect::new(0, 0, 120, 5);
        let cols = columns(&page, area);
        assert_eq!(cols.main_x, (120 - 110) / 2);
        let spots = spots(&page, area, 0);
        assert_eq!(spots.len(), 2);
        assert_eq!(spots[0].x, cols.main_x + 4);
        assert_eq!(
            page.links[spots[1].link as usize],
            Link::from("https://github.com/b")
        );
        let h = hit(&page, area, 0, cols.main_x + 5, 0);
        assert_eq!(
            h,
            PageHit {
                line: Some(0),
                link: Some(link)
            }
        );
        let h = hit(&page, area, 0, cols.main_x + 1, 0);
        assert_eq!(
            h,
            PageHit {
                line: Some(0),
                link: None
            }
        );
        let h = hit(&page, area, 0, cols.aside_x.unwrap(), 0);
        assert_eq!(h.link, Some(spots[1].link));
    }

    #[test]
    fn reveal_scrolls_as_little_as_possible() {
        assert_eq!(reveal(0, 1, 0, 10, 100, 2), 0);
        assert_eq!(reveal(20, 22, 0, 10, 100, 2), 14);
        assert_eq!(reveal(5, 6, 12, 10, 100, 2), 3);
        assert_eq!(reveal(99, 100, 0, 10, 100, 2), 90);
        // Taller than the view: its top shows.
        assert_eq!(reveal(10, 40, 0, 10, 100, 2), 10);
    }
}