rootle 0.8.4

Modal TUI for browsing remote source-control systems (GitHub in-tree, any forge via stdio providers) from the terminal
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
//! Three-pane miller browser over org → repo → dir → file (PLAN.md §1).
//! Yazi semantics: `h` moves focus left into the parent column, where
//! j/k then browse the parent — the child column rebuilds (cascades)
//! from the new selection. `l` drills back in / deeper.
//! Org repos and repo trees arrive asynchronously from the GitHub API;
//! no mock content is ever shown for trees (honest empty until loaded).

use super::pane::{Entry, EntryKind, Pane};
use super::preview::Preview;
use super::scrollbar;
use super::vim_input::VimInput;
use crate::action::Action;
use crate::provider::TreeNode;
use crate::theme::Theme;
use ratatui::Frame;
use ratatui::layout::{Constraint, Direction, Layout, Rect};
use ratatui::style::Style;
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, Paragraph};
use std::collections::{HashMap, HashSet};

mod tree;

pub use tree::RepoTree;

/// One fetched blob, cache entry for `Browser::blobs`.
struct CachedBlob {
    /// File name (syntax detection for restyle).
    name: String,
    /// Language label for the preview footer.
    lang: String,
    /// Sanitized raw text — the restyle source of truth.
    text: String,
    /// Highlighted lines under the current palette.
    lines: Vec<Line<'static>>,
}

pub struct Browser {
    /// Level stack: levels[i] lists the children of the selection in
    /// levels[i-1]. levels[0] = orgs, levels[1] = repos, 2 = repo root,
    /// 3+ = dirs.
    levels: Vec<Pane>,
    /// Which level owns the keyboard. Default = deepest level.
    focus: usize,
    tree: Option<RepoTree>,
    /// Blob content by sha (in-memory, session-scoped): sanitized raw
    /// text + highlighted lines. Lines are cached so navigation never
    /// re-highlights; the raw text lets a theme switch restyle
    /// everything without a refetch.
    blobs: HashMap<String, CachedBlob>,
    /// Shas with an in-flight fetch (dedupe worker spawns).
    pending_blobs: HashSet<String>,
    /// Set by refresh when the selected file needs a fetch; the app
    /// drains it via `take_blob_request` and routes `LoadBlob`.
    blob_request: Option<(String, String)>,
    pub preview: Preview,
    /// `/` filter input, owned here, active in SEARCH mode.
    pub filter_input: VimInput,
    /// `␣ /` find-in-file input, active in FIND mode (plans/0007 §3).
    pub find_input: VimInput,
    /// VISUAL mode (plans/0004 §1): marked entries, keyed
    /// `"<pane title>/<entry name>"` so marks survive cascades.
    visual: bool,
    marks: std::collections::HashSet<String>,
    /// plans/0016 M1a: the browsed revision (None = default branch).
    current_ref: Option<String>,
    /// plans/0016 M1b: the file-history lens over the preview pane.
    /// Some(_) while active; the preview survives underneath.
    history: Option<History>,
    /// plans/0016 M1c: blame ranges for the previewed file.
    blame: Option<BlameState>,
    /// Viewing a file at a commit (history Enter): the restore point
    /// is the present-day blob — (path, sha) — re-rendered from the
    /// in-memory cache on the way back.
    at_commit: Option<(String, String)>,
}

/// The file-history lens over the preview pane (plans/0016 M1b).
/// Data arrives from the provider via `history_loaded`; until then the
/// lens shows a loading row.
pub struct History {
    /// The file the lens is open on.
    path: String,
    /// Cursor over the visible (filtered) rows.
    cursor: usize,
    scroll: u16,
    entries: Vec<crate::provider::LogEntry>,
    truncated: bool,
    loading: bool,
    /// Enter-from-blame: position the cursor at this sha on landing.
    pending_sha: Option<String>,
    /// Transient `/` session over the commits (house rule: every list
    /// filters) — subject, sha, and author match.
    filter: VimInput,
    filtering: bool,
    filter_value: String,
    pre_filter: String,
}

impl History {
    /// The lens positioned at a commit (blame → history composition).
    fn at(path: &str, pending_sha: Option<String>) -> Self {
        History {
            path: path.to_string(),
            cursor: 0,
            scroll: 0,
            entries: Vec::new(),
            truncated: false,
            loading: true,
            pending_sha,
            filter: VimInput::transient(),
            filtering: false,
            filter_value: String::new(),
            pre_filter: String::new(),
        }
    }

    fn loaded(&mut self, entries: Vec<crate::provider::LogEntry>, truncated: bool) {
        self.loading = false;
        self.truncated = truncated;
        self.entries = entries;
        // The blamed-commit composition lands the cursor on its row.
        if let Some(sha) = self.pending_sha.take()
            && let Some(i) = self
                .entries
                .iter()
                .position(|e| e.sha == sha || e.sha.starts_with(&sha))
        {
            self.cursor = self.visible().iter().position(|&vi| vi == i).unwrap_or(0);
        }
    }

    /// Entry indices surviving the committed filter.
    fn visible(&self) -> Vec<usize> {
        let needle = self.filter_value.to_lowercase();
        self.entries
            .iter()
            .enumerate()
            .filter(|(_, c)| {
                needle.is_empty()
                    || c.subject.to_lowercase().contains(&needle)
                    || c.sha.contains(&needle)
                    || c.author.to_lowercase().contains(&needle)
            })
            .map(|(i, _)| i)
            .collect()
    }

    fn selected(&self) -> Option<&crate::provider::LogEntry> {
        let vis = self.visible();
        vis.get(self.cursor.min(vis.len().saturating_sub(1)))
            .map(|&i| &self.entries[i])
    }
}

/// Blame lens state (plans/0016 M1c): ranges for one path, fetched on
/// demand; the marks live in the Preview. Shared with the search
/// view's expanded pane (0019 parity).
pub(crate) struct BlameState {
    pub(crate) path: String,
    pub(crate) ranges: Vec<crate::provider::BlameRange>,
    pub(crate) loading: bool,
}

impl Default for Browser {
    fn default() -> Self {
        Self::new(&[], &[])
    }
}

impl Browser {
    pub fn new(recent_orgs: &[String], defaults: &[String]) -> Self {
        let mut names: Vec<String> = recent_orgs.to_vec();
        for d in defaults {
            if !names.iter().any(|n| n == d) {
                names.push(d.to_string());
            }
        }
        let orgs = names
            .iter()
            .map(|n| Entry::new(n, EntryKind::Org))
            .collect();
        // Starts folded at the orgs level; the repos level arrives
        // asynchronously via `org_repos_loaded`.
        let mut browser = Browser {
            levels: vec![Pane::new("orgs", orgs)],
            focus: 0,
            tree: None,
            blobs: HashMap::new(),
            pending_blobs: HashSet::new(),
            blob_request: None,
            preview: Preview::new(),
            filter_input: VimInput::transient(),
            find_input: VimInput::transient(),
            visual: false,
            marks: std::collections::HashSet::new(),
            current_ref: None,
            history: None,
            blame: None,
            at_commit: None,
        };
        browser.sync();
        browser
    }

    /// Selected org at the top level, if any.
    pub fn selected_org(&self) -> Option<String> {
        self.levels[0].selected_entry().map(|e| e.name.clone())
    }

    /// Default branch of the open repo, if a tree is loaded.
    pub fn branch(&self) -> Option<&str> {
        self.tree.as_ref().map(|t| t.branch.as_str())
    }

    /// Repo-level entries as full names (`org/repo`), if loaded.
    pub fn org_repo_full_names(&self) -> Vec<String> {
        let Some(org) = self.selected_org() else {
            return vec![];
        };
        let Some(repos) = self.levels.get(1) else {
            return vec![];
        };
        repos
            .entries
            .iter()
            .filter(|e| e.kind == EntryKind::Repo)
            .map(|e| format!("{org}/{}", e.name))
            .collect()
    }

    /// The browsed revision (plans/0016 M1a), if switched off the
    /// default branch.
    pub fn current_ref(&self) -> Option<&str> {
        self.current_ref.as_deref()
    }

    /// Live-preview or commit a revision switch — the crumb follows;
    /// the tree refetch is the app's (LoadRepoTree reads this).
    /// Switching invalidates the revision lenses: history and blame
    /// were fetched for the previous ref.
    pub fn set_current_ref(&mut self, name: Option<String>) {
        self.current_ref = name;
        self.history = None;
        self.blame = None;
        self.preview.set_blame(None);
        self.at_commit = None;
    }

    /// Preview submode keys (plans/0016 M1, `␣ p`): the vim vertical
    /// motions are owned by `Preview::motion_key` (counts, gg/G,
    /// pages, paragraphs, %, zt/zz/zb); everything else maps through
    /// the named table in keymap.rs (hint rows derive from it).
    pub fn preview_key(&mut self, key: ratatui::crossterm::event::KeyEvent) -> Action {
        use ratatui::crossterm::event::KeyCode;
        if self.preview.motion_key(key) {
            return Action::Noop;
        }
        match key.code {
            // vim V (pane-local): anchor at the cursor, motions extend.
            KeyCode::Char('v') => {
                self.preview.toggle_visual();
                Action::Noop
            }
            // Y copies content — the selection, else the cursor line.
            KeyCode::Char('Y') => Action::PreviewCopy,
            // The ladder: Esc clears a selection before exiting.
            KeyCode::Esc if self.preview.clear_visual() => Action::Noop,
            _ => crate::keymap::preview_named(key.code),
        }
    }

    /// The yank anchor: the visual range when one is live, else the
    /// cursor line alone — web_url takes (line, end).
    pub fn yank_anchor(&self) -> (Option<u32>, Option<u32>) {
        match self.preview.visual_range() {
            Some((lo, hi)) => (Some(lo), Some(hi)),
            None => (self.preview.line(), None),
        }
    }

    /// `␣ p b` off: drop the lens. (On is the app's: it fetches
    /// ranges via `blame_request` and they land in `blame_store`.)
    pub fn clear_blame(&mut self) {
        self.blame = None;
        self.preview.set_blame(None);
    }

    /// Toggle on: ranges already fetched for the file under preview
    /// apply immediately; otherwise the app spawns the fetch. Returns
    /// the (repo-path) the marks belong to when a fetch is needed.
    pub fn blame_toggle_on(&mut self) -> bool {
        if self.preview.text_line_count() == 0 {
            return false;
        }
        let apply = matches!(&self.blame, Some(b) if !b.loading);
        if apply {
            self.blame_apply();
        }
        true
    }

    /// The path a blame fetch should cover, if one is needed.
    pub fn blame_needed_for(&self) -> Option<String> {
        if self.preview.text_line_count() == 0 {
            return None;
        }
        match &self.blame {
            Some(b) if b.loading => None, // in flight
            Some(_) => None,              // loaded — blame_apply covers it
            None => self.selected_file().map(|(p, _)| p),
        }
    }

    pub fn blame_mark_loading(&mut self, path: String) {
        self.blame = Some(BlameState {
            path,
            ranges: Vec::new(),
            loading: true,
        });
    }

    /// Ranges landed (identity-checked by the caller); apply when the
    /// lens is open on this path.
    pub fn blame_store(&mut self, path: String, ranges: Vec<crate::provider::BlameRange>) {
        let active = self
            .blame
            .as_ref()
            .map(|b| b.loading && b.path == path)
            .unwrap_or(false);
        self.blame = Some(BlameState {
            path,
            ranges,
            loading: false,
        });
        if active {
            self.blame_apply();
        }
    }

    /// Ranges → per-line run marks on the preview (v1.5 shape:
    /// coalesced 1-based inclusive ranges; run starts carry the mark).
    fn blame_apply(&mut self) {
        let Some(b) = &self.blame else { return };
        let lines = self.preview.text_line_count();
        if lines == 0 {
            return;
        }
        let mut marks: Vec<Option<crate::components::preview::BlameMark>> = vec![None; lines];
        for r in &b.ranges {
            let start = (r.start_line as usize).saturating_sub(1);
            if start < lines {
                marks[start] = Some(crate::components::preview::BlameMark {
                    sha: r.sha.chars().take(7).collect(),
                    author: r.author.clone(),
                });
            }
        }
        self.preview.set_blame(Some(marks));
    }

    /// Enter on a blame line: the sha the margin names for that line —
    /// the history lens opens positioned at it. None outside blame.
    pub fn blame_line_sha(&self) -> Option<String> {
        if !self.preview.blaming() {
            return None;
        }
        let b = self.blame.as_ref()?;
        if b.loading {
            return None;
        }
        let line = self.preview_line().unwrap_or(1) as usize;
        b.ranges
            .iter()
            .find(|r| r.start_line as usize <= line && line <= r.end_line as usize)
            .map(|r| r.sha.clone())
    }
    /// `␣ p h` opens the history lens on the previewed file, if any —
    /// a loading row first; entries land via `history_loaded`.
    /// `at_sha` positions the cursor (blame → history composition).
    pub fn open_history(&mut self, at_sha: Option<String>) -> bool {
        match self.selected_file() {
            Some((path, _)) => {
                self.history = Some(History::at(&path, at_sha));
                true
            }
            None => false,
        }
    }

    /// Log entries landed from the provider.
    pub fn history_loaded(&mut self, entries: Vec<crate::provider::LogEntry>, truncated: bool) {
        if let Some(h) = &mut self.history {
            h.loaded(entries, truncated);
        }
    }

    /// The path the open lens serves (event identity check).
    pub fn history_path(&self) -> Option<&str> {
        self.history.as_ref().map(|h| h.path.as_str())
    }

    pub fn history_active(&self) -> bool {
        self.history.is_some()
    }

    /// History lens `/` session active (keys route to the filter).
    pub fn history_filtering(&self) -> bool {
        self.history.as_ref().map(|h| h.filtering).unwrap_or(false)
    }

    /// Begin the `/` session (remembers the committed filter so the
    /// session's Esc restores it).
    pub fn history_begin_filter(&mut self) {
        if let Some(h) = &mut self.history {
            h.pre_filter = h.filter_value.clone();
            h.filtering = true;
        }
    }

    /// A key for the filter session; commits/cancels end it. The list
    /// narrows as you type (pane-style live filter, not commit-only).
    pub fn history_filter_key(&mut self, key: ratatui::crossterm::event::KeyEvent) {
        if let Some(h) = &mut self.history {
            match h.filter.handle_key(key) {
                crate::components::vim_input::Outcome::Changed => {
                    h.filter_value = h.filter.value();
                    h.cursor = 0;
                    h.scroll = 0;
                }
                crate::components::vim_input::Outcome::Submitted => {
                    h.filtering = false;
                    h.filter_value = h.filter.value();
                    h.cursor = 0;
                    h.scroll = 0;
                }
                crate::components::vim_input::Outcome::Cancelled => {
                    h.filtering = false;
                    h.filter_value = h.pre_filter.clone();
                }
                _ => {}
            }
        }
    }

    /// Esc in the lens: a committed filter clears first (the wizard
    /// ladder), the second Esc closes. Returns true when it closed.
    pub fn history_esc(&mut self) -> bool {
        if let Some(h) = &mut self.history
            && !h.filter_value.is_empty()
        {
            h.filter_value.clear();
            h.cursor = 0;
            return false;
        }
        self.close_history();
        true
    }

    pub fn close_history(&mut self) {
        self.history = None;
    }

    pub fn history_move(&mut self, delta: i64) {
        if let Some(h) = &mut self.history {
            let len = h.visible().len() as i64;
            if len > 0 {
                h.cursor = ((h.cursor as i64 + delta).rem_euclid(len)) as usize;
            }
        }
    }

    /// Entering open-at-commit: save the present-day blob's identity
    /// (the tree cursor is on the file the lens serves).
    pub fn note_commit_view(&mut self) {
        self.at_commit = self.selected_file();
        // Present-day blame marks are stale over a commit's content.
        self.preview.set_blame(None);
    }

    /// Show a file at a commit (v1.5): bypass refresh_preview — the
    /// tree cursor's sha is the present-day one — but cache the bytes
    /// so switching back and forth stays free.
    #[allow(clippy::too_many_arguments)]
    pub fn show_at_commit(
        &mut self,
        sha: &str,
        name: &str,
        lang: &str,
        text: String,
        lines: Vec<Line<'static>>,
        band: Option<crate::components::preview::BandContext>,
    ) {
        self.note_commit_view();
        self.blobs.insert(
            sha.to_string(),
            CachedBlob {
                name: name.to_string(),
                lang: lang.to_string(),
                text,
                lines: lines.clone(),
            },
        );
        self.preview.set_highlighted(name, lang, lines);
        // The band: the path stays, the commit context dresses it.
        let path = name.split(" @ ").next().unwrap_or(name).to_string();
        self.preview.set_band(Some(path), band);
    }

    pub fn at_commit_view(&self) -> bool {
        self.at_commit.is_some()
    }

    /// Esc from a commit view: the present-day blob re-renders from
    /// the in-memory cache (it was fetched moments ago — zero network).
    pub fn commit_view_close(&mut self) {
        let Some((path, sha)) = self.at_commit.take() else {
            return;
        };
        if let Some(c) = self.blobs.get(&sha) {
            let (lang, lines) = (c.lang.clone(), c.lines.clone());
            // The cached name carries the at-commit marker — the
            // present-day view's title is the plain path.
            self.preview.set_highlighted(&path, &lang, lines);
            self.preview.set_band(Some(path), None);
        } else {
            // Cache evicted under us: fall back to the blob path.
            self.preview
                .set_bytes(&path, b"reload the file to restore it");
        }
    }

    /// The picked commit as a LogEntry (the band needs the subject).
    pub fn history_pick_entry(&self) -> Option<crate::provider::LogEntry> {
        self.history.as_ref()?.selected().cloned()
    }

    /// The picked commit (path + full sha) — open-at-commit and the
    /// permalink yank.
    pub fn history_pick(&self) -> Option<(String, String)> {
        let h = self.history.as_ref()?;
        let c = h.selected()?;
        Some((h.path.clone(), c.sha.clone()))
    }

    /// VISUAL mode on: checkboxes appear on every pane.
    pub fn enter_visual(&mut self) {
        self.visual = true;
        self.sync();
    }

    /// VISUAL off; marks are kept (a following `:clone` consumes them).
    pub fn exit_visual(&mut self) {
        self.visual = false;
        self.sync();
    }

    /// Toggle the mark on the focused pane's selected entry.
    pub fn toggle_selected(&mut self) {
        let pane = &self.levels[self.focus];
        let Some(entry) = pane.selected_entry() else {
            return;
        };
        let key = format!("{}/{}", pane.title, entry.name);
        if !self.marks.remove(&key) {
            self.marks.insert(key);
        }
        self.sync();
    }

    /// Drop every VISUAL mark (␣ c).
    pub fn clear_marks(&mut self) {
        self.marks.clear();
        self.sync();
    }

    /// Delete marked orgs from the orgs level (␣ d). Returns the
    /// deleted org names; non-org marks are left untouched (reported
    /// by the caller).
    pub fn delete_marked_orgs(&mut self) -> Vec<String> {
        let orgs_prefix = "orgs/";
        let deleted: Vec<String> = self
            .marks
            .iter()
            .filter_map(|k| k.strip_prefix(orgs_prefix).map(str::to_string))
            .collect();
        if deleted.is_empty() {
            return deleted;
        }
        self.levels[0]
            .entries
            .retain(|e| !deleted.contains(&e.name));
        for org in &deleted {
            self.marks.remove(&format!("{orgs_prefix}{org}"));
        }
        // Selected org deleted → drop to the first remaining entry.
        if let Some(sel) = self.levels[0].selected_entry()
            && deleted.contains(&sel.name)
        {
            self.levels[0].select(0);
        }
        self.sync();
        deleted
    }

    /// Marked entries as `"<pane title>/<name>"` keys.
    pub fn visual_marks(&self) -> Vec<String> {
        let mut marks: Vec<String> = self.marks.iter().cloned().collect();
        marks.sort();
        marks
    }

    /// Ensure `org` exists in the orgs level and select it.
    pub fn select_org(&mut self, org: &str) {
        let pos = self.levels[0]
            .entries
            .iter()
            .position(|e| e.name == org)
            .unwrap_or_else(|| {
                self.levels[0]
                    .entries
                    .insert(0, Entry::new(org, EntryKind::Org));
                0
            });
        self.levels[0].select(pos);
        self.focus = 0;
        self.sync();
    }

    /// Org repos arrived from the API: install/replace the repos level.
    /// Ignored if the user has since selected a different org.
    pub fn org_repos_loaded(&mut self, org: &str, repos: Vec<crate::provider::RepoInfo>) {
        if self.selected_org().as_deref() != Some(org) {
            return;
        }
        let entries = repos
            .iter()
            .map(|r| Entry::new(&r.name, EntryKind::Repo))
            .collect();
        self.levels.truncate(1);
        self.levels.push(Pane::new(org, entries));
        self.focus = 1;
        self.cascade();
        self.sync();
    }

    /// Repo tree arrived: install it and rebuild the dir columns.
    /// Ignored if it doesn't match the currently selected repo.
    pub fn tree_loaded(
        &mut self,
        owner: &str,
        name: &str,
        entries: Vec<TreeNode>,
        truncated: bool,
        branch: String,
    ) {
        if self.levels.get(1).map(|p| p.title.as_str()) != Some(owner) {
            return;
        }
        let current_repo = self.levels[1].selected_entry().map(|e| e.name.clone());
        if current_repo.as_deref() != Some(name) {
            return;
        }
        self.tree = Some(RepoTree::new(
            owner.to_string(),
            name.to_string(),
            truncated,
            branch,
            entries,
        ));
        self.levels.truncate(2);
        self.focus = 1;
        self.cascade();
        // Complete the interrupted drill: the tree load was requested by
        // acting on this repo, so land the user in its root pane rather
        // than leaving them on the repos pane to press `l` again.
        if self.levels.len() > 2 {
            self.focus = 2;
        }
        self.sync();
    }

    fn current(&mut self) -> &mut Pane {
        &mut self.levels[self.focus]
    }

    /// Recompute focused flags + preview after any state change.
    fn sync(&mut self) {
        for (i, pane) in self.levels.iter_mut().enumerate() {
            pane.focused = i == self.focus;
            // Marks stay visible after leaving VISUAL (they drive
            // :clone / ␣d); ○ only while visual is active.
            let prefix = format!("{}/", pane.title);
            let pane_marks: std::collections::HashSet<String> = self
                .marks
                .iter()
                .filter_map(|k| k.strip_prefix(&prefix).map(str::to_string))
                .collect();
            pane.checkboxes = if self.visual || !pane_marks.is_empty() {
                Some(pane_marks)
            } else {
                None
            };
            pane.marks_only = !self.visual;
        }
        self.refresh_preview();
    }

    pub fn context(&self) -> String {
        // Path up to the focused level (level 0 = orgs, not shown).
        let crumbs = self
            .levels
            .iter()
            .skip(1)
            .take(self.focus)
            .map(|p| p.title.clone())
            .collect::<Vec<_>>()
            .join(" · ");
        // plans/0016 M1a: off-default revisions say so in the crumb.
        match &self.current_ref {
            Some(r) if !crumbs.is_empty() => format!("{crumbs} @ {r}"),
            _ => crumbs,
        }
    }

    pub fn selected_kind(&self) -> Option<EntryKind> {
        self.levels[self.focus].selected_entry().map(|e| e.kind)
    }

    /// Repos level title = owner of whatever is being browsed.
    fn current_owner(&self) -> Option<&str> {
        self.levels.get(1).map(|p| p.title.as_str())
    }

    /// Children of an entry: orgs never expand locally (API), repos/dirs
    /// expand from the loaded tree only — no mock trees, ever.
    fn children_of(&self, entry: &Entry) -> Option<Vec<Entry>> {
        let tree = self.tree.as_ref()?;
        match entry.kind {
            EntryKind::Org | EntryKind::File => None,
            EntryKind::Repo => (tree.owner == self.current_owner()? && tree.name == entry.name)
                .then(|| tree.children("")),
            EntryKind::Dir => {
                let base = self.dir_path();
                let child_path = if base.is_empty() {
                    entry.name.clone()
                } else {
                    format!("{base}/{}", entry.name)
                };
                Some(tree.children(&child_path))
            }
        }
    }

    pub fn set_repo(&mut self, owner: &str, name: &str) {
        self.select_org(owner);
        // Reuse the API-loaded repos level if present; otherwise the
        // repos pane waits for the org load (never mock repos for an
        // org we haven't loaded — except the static defaults).
        if self.levels.len() < 2 || self.levels[1].title != owner {
            self.levels.truncate(1);
            self.levels.push(Pane::new(owner, vec![]));
        }
        if let Some(pos) = self.levels[1].entries.iter().position(|e| e.name == name) {
            self.levels[1].select(pos);
        } else {
            self.levels[1]
                .entries
                .push(Entry::new(name, EntryKind::Repo));
            let last = self.levels[1].entries.len() - 1;
            self.levels[1].select(last);
        }
        self.focus = 1;
        self.cascade();
        self.sync();
    }

    pub fn update(&mut self, action: &Action) -> Action {
        match action {
            Action::MoveUp | Action::MoveDown => {
                self.current().update(action);
                // Selection changed in the focused column: every column
                // to its right is stale — rebuild from the new selection.
                self.cascade();
                self.sync();
            }
            Action::DrillIn => {
                let action = self.drill_in();
                self.sync();
                return action;
            }
            Action::DrillOut => {
                if self.focus > 0 {
                    self.focus -= 1;
                }
                self.sync();
            }
            Action::PreviewLineDown => self.preview.move_cursor(1),
            Action::PreviewLineUp => self.preview.move_cursor(-1),
            _ => {}
        }
        Action::Noop
    }

    /// Drop levels right of focus and re-derive the immediate child
    /// level from the focused selection. Org entries never cascade —
    /// their repos come from the API (`LoadOrgRepos`).
    fn cascade(&mut self) {
        self.levels.truncate(self.focus + 1);
        let Some(entry) = self.levels[self.focus].selected_entry().cloned() else {
            return;
        };
        if let Some(children) = self.children_of(&entry) {
            self.levels.push(Pane::new(entry.name.clone(), children));
        }
    }

    /// Drill into the focused entry. Org entries don't have their repos
    /// locally — the caller must fetch them (`LoadOrgRepos`); repos
    /// likewise fetch their tree (`LoadRepoTree`).
    fn drill_in(&mut self) -> Action {
        let Some(entry) = self.levels[self.focus].selected_entry().cloned() else {
            return Action::Noop;
        };
        match entry.kind {
            EntryKind::File => Action::Noop, // OpenSelected handled by app
            EntryKind::Org => Action::LoadOrgRepos(entry.name.clone()),
            EntryKind::Repo => {
                if self.children_of(&entry).is_none() {
                    let owner = self.current_owner().unwrap_or_default().to_string();
                    return Action::LoadRepoTree {
                        owner,
                        name: entry.name,
                    };
                }
                if self.focus == self.levels.len() - 1
                    && let Some(children) = self.children_of(&entry)
                {
                    self.levels.push(Pane::new(entry.name.clone(), children));
                }
                if self.focus + 1 < self.levels.len() {
                    self.focus += 1;
                }
                Action::Noop
            }
            EntryKind::Dir => {
                if self.focus == self.levels.len() - 1
                    && let Some(children) = self.children_of(&entry)
                {
                    self.levels.push(Pane::new(entry.name.clone(), children));
                }
                if self.focus + 1 < self.levels.len() {
                    self.focus += 1;
                }
                Action::Noop
            }
        }
    }

    /// Dir path relative to the repo root, from the level titles
    /// (levels: 0=orgs, 1=repos, 2=repo root, 3+=dirs). Also persisted
    /// as `last_path` in the state store.
    pub fn dir_path(&self) -> String {
        self.levels
            .iter()
            .take(self.focus + 1)
            .skip(3)
            .map(|p| p.title.as_str())
            .collect::<Vec<_>>()
            .join("/")
    }

    pub fn apply_filter(&mut self) {
        let filter = self.filter_input.value();
        self.current().set_filter(filter);
        self.cascade();
        self.sync();
    }

    pub fn clear_filter(&mut self) {
        self.filter_input.clear();
        self.current().set_filter(String::new());
        self.cascade();
        self.sync();
    }

    /// The file under the cursor needs its blob fetched, if any.
    /// Taking a request marks the sha in-flight — without this, the
    /// end-of-route drain would re-request on every keystroke and
    /// recurse (stack overflow, caught by the filter-commit test).
    pub fn take_blob_request(&mut self) -> Option<(String, String)> {
        let (sha, name) = self.blob_request.take()?;
        self.pending_blobs
            .insert(sha.clone())
            .then_some((sha, name))
    }

    /// Blob arrived: store raw text + highlighted lines, refresh if
    /// still selected.
    pub fn blob_loaded(
        &mut self,
        sha: &str,
        name: &str,
        lang: &str,
        text: String,
        lines: Vec<Line<'static>>,
    ) {
        self.blobs.insert(
            sha.to_string(),
            CachedBlob {
                name: name.to_string(),
                lang: lang.to_string(),
                text,
                lines,
            },
        );
        self.pending_blobs.remove(sha);
        self.refresh_preview();
        // The header band (GitHub's file header): the full path rides
        // every file preview; at-commit context only from
        // show_at_commit.
        if let Some((path, s)) = self.selected_file()
            && s == sha
        {
            self.preview.set_band(Some(path), None);
        }
    }

    /// Re-highlight every cached blob under a new palette and refresh
    /// the visible preview (theme switched, plans/0007 §2).
    pub fn restyle_blobs(&mut self, highlighter: &crate::highlight::Highlighter) {
        for blob in self.blobs.values_mut() {
            blob.lines = highlighter.highlight(&blob.name, &blob.text);
        }
        self.refresh_preview();
    }

    pub fn blob_failed(&mut self, _sha: &str, message: &str) {
        // Stay marked pending: no auto-retry while the user keeps
        // moving (avoids hammering a failing endpoint per keystroke).
        self.preview.content = super::preview::PreviewContent::Text(format!("error: {message}"));
    }

    /// Current preview line cursor (1-based) — anchors `␣ y` (v1.1).
    pub fn preview_line(&self) -> Option<u32> {
        self.preview.line()
    }

    /// The repo coordinates for a blob fetch.
    pub fn repo_coords(&self) -> Option<(String, String)> {
        let owner = self.current_owner()?.to_string();
        let name = self.tree.as_ref()?.name.clone();
        Some((owner, name))
    }

    /// The file under the cursor, as (full repo-relative path, blob sha).
    pub fn selected_file(&self) -> Option<(String, String)> {
        let entry = self.levels[self.focus].selected_entry()?;
        if entry.kind != EntryKind::File {
            return None;
        }
        let base = self.dir_path();
        let full = if base.is_empty() {
            entry.name.clone()
        } else {
            format!("{base}/{}", entry.name)
        };
        let sha = self.tree.as_ref()?.find(&full)?.sha.clone();
        Some((full, sha))
    }

    fn refresh_preview(&mut self) {
        let Some(entry) = self.levels[self.focus].selected_entry().cloned() else {
            self.preview.content = Default::default();
            return;
        };
        match entry.kind {
            EntryKind::File => {
                let base = self.dir_path();
                let full = if base.is_empty() {
                    entry.name.clone()
                } else {
                    format!("{base}/{}", entry.name)
                };
                let node = self.tree.as_ref().and_then(|t| t.find(&full)).cloned();
                match node {
                    Some(node) => {
                        if let Some(blob) = self.blobs.get(&node.sha) {
                            let lines = blob.lines.clone();
                            let lang = blob.lang.clone();
                            self.preview.set_highlighted(&entry.name, &lang, lines);
                        } else {
                            if !self.pending_blobs.contains(&node.sha) {
                                self.blob_request = Some((node.sha.clone(), entry.name.clone()));
                            }
                            self.preview
                                .set_file_meta(&entry.name, node.size, &node.sha);
                        }
                    }
                    None => self.preview.content = Default::default(),
                }
            }
            EntryKind::Dir => {
                let children = self.children_of(&entry).unwrap_or_default();
                self.preview.set_dir(&entry.name, children);
            }
            EntryKind::Repo => {
                let children = self.children_of(&entry).unwrap_or_default();
                self.preview.set_dir(&entry.name, children);
            }
            EntryKind::Org => {
                // Repos load over the API; don't mock them in preview.
                self.preview.title = entry.name.clone();
                self.preview.content = Default::default();
            }
        }
    }

    pub fn render(&mut self, frame: &mut Frame, area: Rect, theme: &Theme, zoomed: bool) {
        // ␣ p zoom (tmux `prefix z` model, plans/0016 M1): the preview
        // — or the history lens over it — takes the whole content row;
        // the miller columns are untouched underneath, Esc restores.
        if zoomed {
            if self.history.is_some() {
                self.render_history(frame, area, theme);
            } else {
                self.preview.render(frame, area, theme);
            }
            return;
        }
        // Top level (orgs): fold to a single full-width pane. There is
        // no parent above orgs, so a three-pane split would leave the
        // left column empty (PLAN.md §5).
        if self.focus == 0 {
            self.levels[0].render(frame, area, theme);
            return;
        }

        let cols = Layout::default()
            .direction(Direction::Horizontal)
            .constraints([
                Constraint::Percentage(20),
                Constraint::Percentage(40),
                Constraint::Percentage(40),
            ])
            .split(area);

        // Window over the level stack: parent | focused | preview.
        let parent = self.focus - 1;
        self.levels[parent].render(frame, cols[0], theme);
        let focus = self.focus;
        self.levels[focus].render(frame, cols[1], theme);
        // plans/0016 M1b: the history lens swaps the preview's content
        // (same rect, same border idiom) — the preview is untouched
        // underneath and Esc restores it.
        if self.history.is_some() {
            self.render_history(frame, cols[2], theme);
        } else {
            self.preview.render(frame, cols[2], theme);
        }
    }

    /// tig-shaped commit list for the previewed file (mock data).
    fn render_history(&mut self, frame: &mut Frame, area: Rect, theme: &Theme) {
        let Some(h) = &mut self.history else {
            return;
        };
        let sem = &theme.semantic;
        let mut title = format!(" history — {} ", h.path);
        if h.filtering || !h.filter_value.is_empty() {
            title = format!(" history — {} /{} ", h.path, h.filter.value());
        }
        let block = Block::default()
            .borders(Borders::ALL)
            .border_type(theme.border_type())
            .border_style(Style::default().fg(sem.border_focused))
            .style(Style::default().bg(sem.base))
            .title(Span::styled(title, Style::default().fg(sem.subtext0)))
            .title_bottom(Span::styled(
                " j/k commit · enter file at commit · / filter · esc back ",
                Style::default().fg(sem.hint),
            ));
        let inner = block.inner(area);
        frame.render_widget(block, area);

        if h.loading {
            frame.render_widget(
                Paragraph::new(Line::from(Span::styled(
                    "  loading history…",
                    Style::default().fg(sem.subtext0),
                ))),
                inner,
            );
            return;
        }
        let vis = h.visible();
        let mut lines: Vec<Line> = Vec::new();
        for (row, &i) in vis.iter().enumerate() {
            let c = &h.entries[i];
            let selected = row == h.cursor;
            let style = if selected {
                Style::default().fg(sem.selection_fg).bg(sem.selection_bg)
            } else {
                Style::default().fg(sem.text)
            };
            let dim = if selected {
                style
            } else {
                Style::default().fg(sem.subtext0)
            };
            lines.push(Line::from(vec![
                Span::styled(
                    if selected { "▌ " } else { "  " },
                    Style::default().fg(sem.border_focused),
                ),
                Span::styled(
                    format!("{} ", c.sha.chars().take(7).collect::<String>()),
                    Style::default().fg(sem.warning),
                ),
                Span::styled(c.subject.clone(), style),
            ]));
            lines.push(Line::from(vec![
                Span::raw("    "),
                Span::styled(format!("{} · {}", c.author, c.date), dim),
            ]));
        }
        if vis.is_empty() {
            lines.push(Line::from(Span::styled(
                "  no matching commits",
                Style::default().fg(sem.subtext0),
            )));
        }
        // Bounded compute: past the render budget the provider said
        // truncated — narrow with /.
        if h.truncated {
            lines.push(Line::from(Span::styled(
                "  ⋮ truncated — / filters",
                Style::default().fg(sem.subtext0),
            )));
        }
        let height = inner.height as usize;
        let total = lines.len();
        let max_scroll = total.saturating_sub(height) as u16;
        // Keep the selected commit's two-line row visible.
        let want = (h.cursor * 2) as u16;
        if want < h.scroll {
            h.scroll = want;
        } else if want + 1 >= h.scroll + height as u16 {
            h.scroll = (want + 2).saturating_sub(height as u16);
        }
        h.scroll = h.scroll.min(max_scroll);
        let scroll = h.scroll;
        frame.render_widget(Paragraph::new(lines).scroll((scroll, 0)), inner);
        scrollbar(frame, area, height, total, scroll as usize, theme);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::highlight::Highlighter;
    use crate::theme::Theme;

    #[test]
    fn restyle_blobs_recolors_cached_lines_without_refetch() {
        let mut b = Browser::new(&[], &[]);
        let mocha = Highlighter::default();
        let lines = mocha.highlight("lib.rs", "fn main() {}\n");
        b.blob_loaded("sha1", "lib.rs", "rust", "fn main() {}\n".into(), lines);
        // Sanity: cached under mocha (mauve keyword).
        assert_eq!(
            b.blobs["sha1"].lines[0].spans[0].style.fg,
            Some(ratatui::style::Color::Rgb(203, 166, 247))
        );
        let dracula = Highlighter::new(&Theme::embedded("dracula").unwrap());
        b.restyle_blobs(&dracula);
        assert_eq!(
            b.blobs["sha1"].lines[0].spans[0].style.fg,
            Some(ratatui::style::Color::Rgb(255, 121, 198)),
            "cached lines should follow the new palette from raw text"
        );
    }
}