ghtui 0.1.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
//! 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 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,
    },
}

impl Link {
    pub fn url(&self) -> Option<&str> {
        match self {
            Link::Url(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
    }
}

/// 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,
}

#[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,
}

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 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,
}

/// 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>,
    /// 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>,
}

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.
    pub fn with_aside(total: u16) -> Self {
        const WIDTH: u16 = 30;
        if total < 104 {
            return Self::new(total);
        }
        Self {
            aside: Some(Aside {
                width: WIDTH,
                lines: Vec::new(),
            }),
            ..Self::new(total.saturating_sub(WIDTH + 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,
        });
    }

    /// 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 });
        }
    }

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

    /// 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>,
}

/// 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 (tx, tw) = match line.frame {
        Frame::None => (
            x.saturating_add(line.indent),
            width.saturating_sub(line.indent),
        ),
        Frame::Body => (
            x.saturating_add(BOX_PAD).saturating_add(line.indent),
            width.saturating_sub((2 * BOX_PAD).saturating_add(line.indent)),
        ),
        Frame::Top => (x.saturating_add(3), width.saturating_sub(6)),
        Frame::Rule | Frame::Bottom => 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));
    }
}

/// 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,
}

/// 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>,
    pub current: Option<usize>,
    pub hints: &'a [HintLabel],
}

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);
        let selected = self.selected.and_then(|i| self.page.items.get(i)).copied();
        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.is_some_and(|s| (s.start..s.end).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(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);
        for hint in self.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,
            );
        }
    }
}

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::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 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);
        }
    }

    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 {
        let theme = self.ctx.theme;
        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
            }]
        );
        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);
    }
}