penknife 0.3.0

Git-style remotes for your documents: sync a folder of markdown to GitHub Gists, track drift per file, and copy anything as rich text to paste elsewhere
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
//! Tree, preview, and status-bar state: the refresh pipeline (scan →
//! status cache → git status → tree rebuild), sorting, selection
//! navigation, and mouse routing.

use std::collections::HashMap;
use std::path::{Path, PathBuf};

use crossterm::event::{MouseEvent, MouseEventKind};
use ratatui::layout::Rect;
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::Span;

use super::{App, Mode, PaneFocus, Refresh};
use crate::git::GitStatus;
use crate::scanner::{self, ScannedFile};
use crate::store::{FileEntry, Store};
use crate::sync;
use crate::ui::tree;

/// Shown in the preview pane for a macOS online-only (dataless) file, in place
/// of forcing a blocking cloud download to render bytes the user only glanced
/// at while browsing.
const DATALESS_PREVIEW: &str = "· Online-only file (stored in the cloud, not downloaded).\n\n\
     Open it (e / o) to download and edit it.";

/// Sync status for one scanned file, without ever forcing a cloud placeholder
/// to materialize. An online-only (dataless) tracked file is reported as
/// `Synced`: it can't have been edited locally since it was evicted to the
/// cloud (editing requires the bytes, which materializes it), so its resident
/// state matches its last sync. A later remote poll still flags it
/// `RemoteNewer` if the gist moved ahead - same as for a resident synced file.
fn status_for_file(abs_path: &std::path::Path, entry: Option<&FileEntry>) -> sync::SyncStatus {
    if entry.is_none() {
        return sync::SyncStatus::NotGisted;
    }
    if crate::fsutil::is_dataless(abs_path) {
        return sync::SyncStatus::Synced;
    }
    let content = std::fs::read_to_string(abs_path).unwrap_or_default();
    sync::local_status(&content, entry)
}

/// Compute the per-file sync-status cache from a scanned file list and the
/// (shared) store. Free function (no `&App`) so it runs on a blocking-pool
/// thread during [`App::start_refresh`], reading through the `Arc<Store>` the
/// task captured with an O(1) clone.
fn compute_status_cache(
    files: &[ScannedFile],
    store: &Store,
    root: &Path,
) -> HashMap<String, sync::SyncStatus> {
    let mut cache = HashMap::with_capacity(files.len());
    for f in files {
        let entry = store.get(root, &f.rel_path);
        cache.insert(f.rel_path.clone(), status_for_file(&f.abs_path, entry));
    }
    cache
}

/// Resolve the active root's git repo root and per-file status, translated to
/// active-root-relative keys (matching `ScannedFile.rel_path`). Free function
/// (no `&App`) so the `git status` shell-out can run off the render thread.
/// Returns `(None, empty)` when the root isn't inside a repo.
fn compute_git_status(root: &Path) -> (Option<PathBuf>, HashMap<String, GitStatus>) {
    let Some(repo) = crate::git::find_repo_root(root) else {
        return (None, HashMap::new());
    };
    let raw = crate::git::status(&repo);
    // raw is keyed by repo-relative path. Translate to active-root-relative:
    // if root == repo it's a no-op; if root is a subdir, strip the prefix and
    // drop entries outside our scanned root.
    let prefix = root.strip_prefix(&repo).ok().map(|p| {
        let mut s = p.to_string_lossy().to_string();
        if !s.is_empty() && !s.ends_with('/') {
            s.push('/');
        }
        s
    });
    let mut map = HashMap::new();
    for (path, st) in raw {
        let rel = match &prefix {
            Some(p) if !p.is_empty() => match path.strip_prefix(p.as_str()) {
                Some(r) => r.to_string(),
                None => continue,
            },
            _ => path,
        };
        map.insert(rel, st);
    }
    (Some(repo), map)
}

#[derive(Debug, Default, Clone, Copy)]
struct StatusCounts {
    synced: usize,
    local_newer: usize,
    remote_newer: usize,
    conflict: usize,
    not_gisted: usize,
}

impl App {
    pub(crate) fn rebuild_tree(&mut self) {
        self.apply_sort();
        let built = tree::build_tree(&self.files, &self.status_cache, &self.git_statuses);
        self.tree_items = built.items;
        self.tree_identifiers = built.identifiers;
        self.tree_file_ids = built.file_ids;
    }

    /// Reorder `self.files` per the active sort mode. Status sort needs
    /// store access, which is why this lives on App rather than in scanner.
    fn apply_sort(&mut self) {
        use crate::config::SortMode;
        match self.config.sort.mode {
            SortMode::MtimeDesc => {
                self.files.sort_by_key(|f| std::cmp::Reverse(f.modified));
            }
            SortMode::MtimeAsc => {
                self.files.sort_by_key(|f| f.modified);
            }
            SortMode::AlphaAsc => {
                self.files.sort_by(|a, b| a.rel_path.cmp(&b.rel_path));
            }
            SortMode::AlphaDesc => {
                self.files.sort_by(|a, b| b.rel_path.cmp(&a.rel_path));
            }
            SortMode::Status => {
                // Status rank uses the cached per-file sync state - no
                // disk reads inside the sort comparator.
                let cache = &self.status_cache;
                self.files.sort_by(|a, b| {
                    let sa = status_rank_cached(cache.get(&a.rel_path).copied());
                    let sb = status_rank_cached(cache.get(&b.rel_path).copied());
                    sa.cmp(&sb).then_with(|| b.modified.cmp(&a.modified))
                });
            }
        }
    }

    pub fn refresh_files(&mut self) -> color_eyre::Result<()> {
        if let Some(entry) = self.current_root_entry().cloned() {
            // Surface a missing root explicitly. Without this check the
            // scanner silently returns an empty list (its error tolerance is
            // tuned for "this subdir vanished mid-walk," not "the root
            // itself is gone") and the user sees an empty tree with no
            // explanation.
            if !entry.path.exists() {
                self.status_message =
                    format!("Root missing: {} (check config.toml)", entry.path.display());
                self.files.clear();
                self.status_cache.clear();
                self.git_statuses.clear();
                self.git_repo_root = None;
                self.rebuild_tree();
                return Ok(());
            }
            let ignore = scanner::build_globset(&entry.ignore);
            self.files = scanner::scan_directory(&entry.path, &ignore)?;
        } else {
            self.files.clear();
        }
        self.refresh_status_cache();
        self.refresh_git_status();
        self.rebuild_tree();
        self.update_preview();
        Ok(())
    }

    /// Read each scanned file once, compute its sync status, and cache the
    /// result. Subsequent calls in this refresh cycle (tree render, sort,
    /// dashboard counts, bulk menu) read from the cache instead of repeating
    /// the IO. Must be called *after* `self.files` is populated.
    pub(crate) fn refresh_status_cache(&mut self) {
        self.status_cache.clear();
        let Some(root) = self.current_root().cloned() else {
            return;
        };
        self.status_cache.reserve(self.files.len());
        for f in &self.files {
            let entry = self.store.get(&root, &f.rel_path);
            let status = status_for_file(&f.abs_path, entry);
            self.status_cache.insert(f.rel_path.clone(), status);
        }
    }

    /// Recompute one file's cached sync status (one disk read) after a store
    /// entry changed - push/pull/check results - without rescanning the tree.
    pub(crate) fn refresh_status_for(&mut self, rel_path: &str) {
        let Some(root) = self.current_root().cloned() else {
            return;
        };
        let entry = self.store.get(&root, rel_path);
        let status = status_for_file(&self.abs_path(rel_path), entry);
        self.status_cache.insert(rel_path.to_string(), status);
    }

    /// Cache lookup; defaults to NotGisted for paths not in the cache.
    pub fn cached_status(&self, rel_path: &str) -> sync::SyncStatus {
        self.status_cache
            .get(rel_path)
            .copied()
            .unwrap_or(sync::SyncStatus::NotGisted)
    }

    /// Re-query git for the active root's state (synchronously). Quietly clears
    /// the status map if the root isn't in a repo or if git isn't on PATH. The
    /// live refresh path runs this off-thread via [`compute_git_status`]; this
    /// method is kept for the synchronous startup/suspend contexts.
    pub(crate) fn refresh_git_status(&mut self) {
        let (repo, statuses) = match self.current_root().cloned() {
            Some(root) => compute_git_status(&root),
            None => (None, HashMap::new()),
        };
        self.git_repo_root = repo;
        self.git_statuses = statuses;
    }

    /// Refresh the active root off the render thread: the directory scan, the
    /// per-file status reads, and the `git status` shell-out all run on a
    /// blocking-pool thread and land later as an [`crate::event::AsyncEvent::RefreshDone`]
    /// that [`App::apply_refresh`] adopts. The UI keeps drawing and stays
    /// responsive throughout - even if the scan stalls on a slow mount or git
    /// hangs.
    ///
    /// See [`Refresh`] for the three call-site intents (startup / sweep /
    /// user-initiated) this dispatches on.
    pub(crate) fn start_refresh(&mut self, kind: Refresh) {
        let (select, only_if_changed, progress, done_message) = match kind {
            Refresh::Initial => (None, false, true, None),
            Refresh::Sweep => (None, true, false, None),
            Refresh::User {
                select,
                done_message,
            } => (select, false, false, done_message),
        };

        let Some(entry) = self.current_root_entry().cloned() else {
            // No root configured: nothing to scan. Clear synchronously (cheap,
            // no IO) so a torn-down root doesn't linger in the tree.
            self.files.clear();
            self.status_cache.clear();
            self.git_statuses.clear();
            self.git_repo_root = None;
            self.scanning = false;
            self.rebuild_tree();
            return;
        };
        if !entry.path.exists() {
            // Surface a missing root explicitly rather than showing an empty
            // tree with no explanation (the scanner's error tolerance is tuned
            // for "a subdir vanished mid-walk," not "the root itself is gone").
            self.status_message =
                format!("Root missing: {} (check config.toml)", entry.path.display());
            self.files.clear();
            self.status_cache.clear();
            self.git_statuses.clear();
            self.git_repo_root = None;
            self.scanning = false;
            self.rebuild_tree();
            return;
        }

        self.refresh_generation += 1;
        let generation = self.refresh_generation;
        let root = entry.path.clone();
        let ignore_patterns = entry.ignore.clone();
        // O(1): the task shares the store through the Arc rather than deep-
        // copying every tracked file's mapping on each sweep.
        let store = std::sync::Arc::clone(&self.store);
        // Cheap fingerprint of the current file set so an unchanged sweep can
        // bail before reading any file contents or shelling out to git.
        let prev_fingerprint = super::files_fingerprint(&self.files);
        let tx = self.async_tx.clone();
        let progress_tx = tx.clone();
        self.spawn_tracked(async move {
            let computed = tokio::task::spawn_blocking(move || {
                let ignore = scanner::build_globset(&ignore_patterns);
                let files = if progress {
                    scanner::scan_directory_with_progress(&root, &ignore, &mut |count| {
                        let _ = progress_tx
                            .send(crate::event::AsyncEvent::ScanProgress { generation, count });
                    })
                    .unwrap_or_default()
                } else {
                    scanner::scan_directory(&root, &ignore).unwrap_or_default()
                };
                // Idle sweep with nothing moved on disk: skip the per-file
                // content reads and the git shell-out entirely.
                if only_if_changed && super::files_fingerprint(&files) == prev_fingerprint {
                    return None;
                }
                let status_cache = compute_status_cache(&files, &store, &root);
                let (git_repo_root, git_statuses) = compute_git_status(&root);
                Some((root, files, status_cache, git_repo_root, git_statuses))
            })
            .await;
            if let Ok(Some((root, files, status_cache, git_repo_root, git_statuses))) = computed {
                let _ = tx.send(crate::event::AsyncEvent::RefreshDone {
                    generation,
                    root,
                    files,
                    status_cache,
                    git_repo_root,
                    git_statuses,
                    select,
                    only_if_changed,
                    done_message,
                });
            }
        });
    }

    /// Adopt the result of an off-thread refresh, dropping it if it's stale (a
    /// newer refresh superseded it, or the active root changed) or a no-op
    /// (`only_if_changed` and the file set is unchanged).
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn apply_refresh(
        &mut self,
        generation: u64,
        root: PathBuf,
        files: Vec<ScannedFile>,
        status_cache: HashMap<String, sync::SyncStatus>,
        git_repo_root: Option<PathBuf>,
        git_statuses: HashMap<String, GitStatus>,
        select: Option<String>,
        only_if_changed: bool,
        done_message: Option<String>,
    ) {
        // A later refresh already ran (or is queued): its result is the truth.
        if generation != self.refresh_generation {
            return;
        }
        // The user switched roots while this walk ran; it describes a root we
        // no longer show.
        if self.current_root().is_none_or(|r| r != &root) {
            return;
        }
        // Periodic sweep: skip the rebuild (and the preview-scroll reset it
        // entails) when nothing on disk actually moved.
        if only_if_changed && !super::files_differ(&self.files, &files) {
            return;
        }

        // The scan (initial or otherwise) has landed: leave the scanning state.
        self.scanning = false;
        self.scan_count = 0;
        self.files = files;
        self.status_cache = status_cache;
        self.git_repo_root = git_repo_root;
        self.git_statuses = git_statuses;
        self.rebuild_tree();

        match select {
            // jump_to refreshes the preview and status bar itself.
            Some(sel) => self.jump_to(&sel),
            None => {
                self.update_preview();
                // The idle sweep leaves the status bar alone (matching the old
                // synchronous sweep); explicit refreshes recompute it.
                if !only_if_changed {
                    self.update_status();
                }
            }
        }

        if let Some(msg) = done_message {
            self.status_message = msg;
        }
    }

    /// Switch to a different root by index. Clears the old root's tree
    /// immediately (so stale entries don't linger) and kicks off the new root's
    /// scan off-thread; the tree fills in when the refresh lands.
    pub(crate) fn switch_root(&mut self, index: usize) {
        if index < self.config.roots.len() {
            self.active_root = index;
            self.files.clear();
            self.status_cache.clear();
            self.git_statuses.clear();
            self.git_repo_root = None;
            self.rebuild_tree();
            self.update_status();
            self.start_refresh(super::Refresh::User {
                select: None,
                done_message: None,
            });
        }
    }

    pub fn update_preview(&mut self) {
        if let Some(ref rel) = self.selected_file() {
            let path = self.abs_path(rel);
            // Never force an online-only placeholder to download just because
            // the cursor landed on it - arrow-key browsing would otherwise
            // trigger a cascade of cloud fetches (and hang if offline). Show a
            // hint instead; opening in `$EDITOR` materializes it on demand.
            self.preview_content = if crate::fsutil::is_dataless(&path) {
                DATALESS_PREVIEW.to_string()
            } else {
                std::fs::read_to_string(&path).unwrap_or_default()
            };
        } else {
            self.preview_content.clear();
        }
        // Reset scroll whenever the visible content changes.
        self.preview_scroll = 0;
    }

    /// Handle a terminal mouse event. Left-click selects (in the tree) or
    /// switches focus (right pane); wheel scroll is routed to whichever pane
    /// the cursor is over.
    pub fn handle_mouse(&mut self, event: MouseEvent) {
        let over_tree = rect_contains(&self.tree_pane_rect, event.column, event.row);
        let over_right = rect_contains(&self.right_pane_rect, event.column, event.row);
        match event.kind {
            MouseEventKind::ScrollDown => {
                if over_tree {
                    self.tree_state.scroll_down(3);
                } else {
                    self.scroll_right_pane(3, true);
                }
            }
            MouseEventKind::ScrollUp => {
                if over_tree {
                    self.tree_state.scroll_up(3);
                } else {
                    self.scroll_right_pane(3, false);
                }
            }
            MouseEventKind::Down(crossterm::event::MouseButton::Left) => {
                if over_tree {
                    let pos = ratatui::layout::Position {
                        x: event.column,
                        y: event.row,
                    };
                    if self.tree_state.click_at(pos) {
                        self.focused_pane = PaneFocus::Tree;
                        self.update_preview();
                        self.update_status();
                    }
                } else if over_right {
                    self.focused_pane = PaneFocus::Right;
                }
            }
            _ => {}
        }
    }

    /// Scroll the right pane (preview or diff) by `lines` rows. `down=true`
    /// increases the offset.
    pub(crate) fn scroll_right_pane(&mut self, lines: u16, down: bool) {
        let target = if matches!(self.mode, Mode::Diff { .. }) {
            &mut self.diff_scroll
        } else {
            &mut self.preview_scroll
        };
        if down {
            *target = target.saturating_add(lines);
        } else {
            *target = target.saturating_sub(lines);
        }
    }

    pub(crate) fn nav_down(&mut self) {
        match self.focused_pane {
            PaneFocus::Tree => {
                self.tree_state.key_down();
                self.update_preview();
                self.update_status();
            }
            PaneFocus::Right => self.scroll_right_pane(1, true),
        }
    }

    pub(crate) fn nav_up(&mut self) {
        match self.focused_pane {
            PaneFocus::Tree => {
                self.tree_state.key_up();
                self.update_preview();
                self.update_status();
            }
            PaneFocus::Right => self.scroll_right_pane(1, false),
        }
    }

    pub fn update_status(&mut self) {
        let current_root = self.current_root().cloned();
        let g = crate::glyphs::glyphs();
        if let Some(ref rel) = self.selected_file() {
            let entry = current_root
                .as_ref()
                .and_then(|r| self.store.get(r, rel))
                .cloned();
            // Cached status - populated in refresh_files. One disk read per
            // file per refresh instead of one per status-bar update.
            let status = self.cached_status(rel);
            self.status_color = status.color();
            let url = entry.as_ref().map(|e| e.url.as_str()).unwrap_or("no gist");
            self.status_message = format!("{} {} | {url}", status.icon(), rel);

            let status_color = status.color();
            let mut spans = vec![
                Span::styled(
                    format!("{} ", status.icon()),
                    Style::default().fg(status_color),
                ),
                Span::styled(
                    rel.to_string(),
                    Style::default()
                        .fg(Color::White)
                        .add_modifier(Modifier::BOLD),
                ),
                Span::styled("", Style::default().fg(Color::DarkGray)),
            ];
            if entry.is_some() {
                spans.push(Span::styled(
                    url.to_string(),
                    Style::default()
                        .fg(Color::Magenta)
                        .add_modifier(Modifier::UNDERLINED),
                ));
            } else {
                spans.push(Span::styled(
                    "no gist".to_string(),
                    Style::default()
                        .fg(Color::DarkGray)
                        .add_modifier(Modifier::ITALIC),
                ));
            }
            self.status_spans = spans;
        } else {
            let counts = self.status_counts();
            self.status_color = if counts.conflict > 0 {
                Color::Red
            } else if counts.local_newer > 0 {
                Color::Yellow
            } else if counts.remote_newer > 0 {
                Color::Blue
            } else if counts.not_gisted > 0 {
                Color::DarkGray
            } else {
                Color::Green
            };
            let root_label = current_root
                .map(|r| r.display().to_string())
                .unwrap_or_else(|| "(no root)".into());
            self.status_message = format!(
                "{} {root_label}  |  {} {}  {} {}  {} {}  {} {}  {} {}",
                g.root,
                g.status_synced,
                counts.synced,
                g.status_local_newer,
                counts.local_newer,
                g.status_remote_newer,
                counts.remote_newer,
                g.status_conflict,
                counts.conflict,
                g.status_not_gisted,
                counts.not_gisted,
            );

            // Rich dashboard: root in magenta, each count colored by category.
            // Zero counts dim to keep the eye on what actually needs attention.
            let mut spans: Vec<Span<'static>> = Vec::with_capacity(24);
            spans.push(Span::styled(
                format!("{} ", g.root),
                Style::default().fg(Color::Magenta),
            ));
            spans.push(Span::styled(
                root_label,
                Style::default()
                    .fg(Color::White)
                    .add_modifier(Modifier::BOLD),
            ));
            spans.push(Span::styled("", Style::default().fg(Color::DarkGray)));
            let cells = [
                (
                    g.status_synced,
                    sync::SyncStatus::Synced.color(),
                    counts.synced,
                ),
                (
                    g.status_local_newer,
                    sync::SyncStatus::LocalNewer.color(),
                    counts.local_newer,
                ),
                (
                    g.status_remote_newer,
                    sync::SyncStatus::RemoteNewer.color(),
                    counts.remote_newer,
                ),
                (
                    g.status_conflict,
                    sync::SyncStatus::Conflict.color(),
                    counts.conflict,
                ),
                (
                    g.status_not_gisted,
                    sync::SyncStatus::NotGisted.color(),
                    counts.not_gisted,
                ),
            ];
            for (i, (icon, color, count)) in cells.iter().enumerate() {
                if i > 0 {
                    spans.push(Span::raw("  "));
                }
                if *count == 0 {
                    spans.push(Span::styled(
                        format!("{icon} {count}"),
                        Style::default().fg(Color::DarkGray),
                    ));
                } else {
                    spans.push(Span::styled(
                        format!("{icon} "),
                        Style::default().fg(*color),
                    ));
                    spans.push(Span::styled(
                        count.to_string(),
                        Style::default().fg(*color).add_modifier(Modifier::BOLD),
                    ));
                }
            }
            self.status_spans = spans;
        }
    }

    /// Tally the current set of files by sync status. Used by the status bar
    /// dashboard. Reads from `status_cache` so no disk IO happens here.
    fn status_counts(&self) -> StatusCounts {
        let mut c = StatusCounts::default();
        if self.current_root().is_none() {
            c.not_gisted = self.files.len();
            return c;
        }
        for file in &self.files {
            match self.cached_status(&file.rel_path) {
                sync::SyncStatus::Synced => c.synced += 1,
                sync::SyncStatus::LocalNewer => c.local_newer += 1,
                sync::SyncStatus::RemoteNewer => c.remote_newer += 1,
                sync::SyncStatus::Conflict => c.conflict += 1,
                sync::SyncStatus::NotGisted => c.not_gisted += 1,
            }
        }
        c
    }

    /// Select the given rel_path in the tree, expanding *every* ancestor
    /// directory so the leaf is visible. Also focuses the tree pane.
    ///
    /// Note: tui-tree-widget's `open()` and `select()` both take the *full
    /// path from root* to the target node, not just the target's own id.
    /// Passing a single-element vec only worked for top-level entries.
    pub(crate) fn jump_to(&mut self, rel_path: &str) {
        // Cumulative identifiers, one per depth level:
        //   "a/b/c/d.md" → ["a", "a/b", "a/b/c", "a/b/c/d.md"]
        let mut full_path: Vec<String> = Vec::new();
        let mut acc = String::new();
        for part in rel_path.split('/') {
            if !acc.is_empty() {
                acc.push('/');
            }
            acc.push_str(part);
            full_path.push(acc.clone());
        }
        // Open each ancestor with the full path leading to it.
        for depth in 1..full_path.len() {
            self.tree_state.open(full_path[..depth].to_vec());
        }
        self.tree_state.select(full_path);
        self.tree_state.scroll_selected_into_view();
        self.focused_pane = PaneFocus::Tree;
        self.update_preview();
        self.update_status();
    }

    /// Move the tree selection to the next file whose sync status is anything
    /// other than `Synced`. `forward` controls direction. Wraps once.
    pub(crate) fn jump_to_next_dirty(&mut self, forward: bool) {
        if self.current_root().is_none() {
            return;
        }
        if self.files.is_empty() {
            return;
        }

        // Find current position within the scanned-files list. If the current
        // selection is a directory or nothing, start before the first file.
        let current_id = self
            .tree_state
            .selected()
            .last()
            .cloned()
            .unwrap_or_default();
        let cur_idx = self
            .files
            .iter()
            .position(|f| f.rel_path == current_id)
            .map(|i| i as isize)
            .unwrap_or(-1);

        let n = self.files.len() as isize;
        let mut next = None;
        for step in 1..=n {
            let probe = if forward {
                ((cur_idx + step).rem_euclid(n)) as usize
            } else {
                ((cur_idx - step).rem_euclid(n)) as usize
            };
            let file = &self.files[probe];
            if !matches!(self.cached_status(&file.rel_path), sync::SyncStatus::Synced) {
                next = Some(file.rel_path.clone());
                break;
            }
        }

        let Some(rel_path) = next else {
            self.status_message = "No dirty files.".into();
            return;
        };
        self.jump_to(&rel_path);
    }
}

/// Bucket a cached sync status for sort ordering. Lower = appears first.
/// Files missing from the cache (e.g. newly-added between refreshes) sort
/// as NotGisted.
fn status_rank_cached(status: Option<sync::SyncStatus>) -> u8 {
    match status.unwrap_or(sync::SyncStatus::NotGisted) {
        sync::SyncStatus::Conflict => 0,
        sync::SyncStatus::LocalNewer => 1,
        sync::SyncStatus::RemoteNewer => 2,
        sync::SyncStatus::NotGisted => 3,
        sync::SyncStatus::Synced => 4,
    }
}

/// Check whether `(x, y)` falls inside the given rect.
fn rect_contains(rect: &Rect, x: u16, y: u16) -> bool {
    rect.width > 0
        && rect.height > 0
        && x >= rect.x
        && x < rect.x + rect.width
        && y >= rect.y
        && y < rect.y + rect.height
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::app::test_support::{new_for_test, select, write_file};
    use crate::config::SortMode;
    use crate::event::async_channel;
    use crate::scanner::ScannedFile;
    use crate::store::{FileEntry, GIST_BACKEND};
    use crossterm::event::{KeyModifiers, MouseButton, MouseEvent};
    use std::path::PathBuf;
    use std::time::{Duration, UNIX_EPOCH};

    fn app3() -> (tempfile::TempDir, App) {
        let dir = tempfile::tempdir().unwrap();
        write_file(dir.path(), "a.md", "alpha");
        write_file(dir.path(), "b.md", "beta");
        write_file(dir.path(), "sub/c.md", "gamma");
        let (tx, rx) = async_channel();
        std::mem::forget(rx);
        let app = new_for_test(dir.path(), tx);
        (dir, app)
    }

    fn sf(rel: &str, secs: u64) -> ScannedFile {
        ScannedFile {
            rel_path: rel.to_string(),
            abs_path: PathBuf::from(format!("/x/{rel}")),
            modified: UNIX_EPOCH + Duration::from_secs(secs),
        }
    }

    fn synced_entry(content: &str) -> FileEntry {
        let h = sync::sha256_hex(content);
        FileEntry {
            backend: GIST_BACKEND.into(),
            remote_id: "g".into(),
            url: "u".into(),
            local_sha256: h.clone(),
            remote_sha256: h,
            last_synced: chrono::Utc::now(),
            remote_updated_at: None,
        }
    }

    // ── apply_sort ──────────────────────────────────────────────────────

    #[test]
    fn apply_sort_mtime_desc_and_asc() {
        let (_d, mut app) = app3();
        app.files = vec![sf("old.md", 1), sf("new.md", 9), sf("mid.md", 5)];
        app.config.sort.mode = SortMode::MtimeDesc;
        app.apply_sort();
        let order: Vec<_> = app.files.iter().map(|f| f.rel_path.as_str()).collect();
        assert_eq!(order, vec!["new.md", "mid.md", "old.md"]);

        app.config.sort.mode = SortMode::MtimeAsc;
        app.apply_sort();
        let order: Vec<_> = app.files.iter().map(|f| f.rel_path.as_str()).collect();
        assert_eq!(order, vec!["old.md", "mid.md", "new.md"]);
    }

    #[test]
    fn apply_sort_alpha_asc_and_desc() {
        let (_d, mut app) = app3();
        app.files = vec![sf("b.md", 1), sf("a.md", 2), sf("c.md", 3)];
        app.config.sort.mode = SortMode::AlphaAsc;
        app.apply_sort();
        let order: Vec<_> = app.files.iter().map(|f| f.rel_path.as_str()).collect();
        assert_eq!(order, vec!["a.md", "b.md", "c.md"]);

        app.config.sort.mode = SortMode::AlphaDesc;
        app.apply_sort();
        let order: Vec<_> = app.files.iter().map(|f| f.rel_path.as_str()).collect();
        assert_eq!(order, vec!["c.md", "b.md", "a.md"]);
    }

    #[test]
    fn apply_sort_status_orders_by_rank() {
        let (_d, mut app) = app3();
        app.files = vec![
            sf("synced.md", 1),
            sf("conflict.md", 2),
            sf("remote.md", 3),
            sf("local.md", 4),
        ];
        app.status_cache.clear();
        app.status_cache
            .insert("synced.md".into(), sync::SyncStatus::Synced);
        app.status_cache
            .insert("conflict.md".into(), sync::SyncStatus::Conflict);
        app.status_cache
            .insert("remote.md".into(), sync::SyncStatus::RemoteNewer);
        app.status_cache
            .insert("local.md".into(), sync::SyncStatus::LocalNewer);
        app.config.sort.mode = SortMode::Status;
        app.apply_sort();
        let order: Vec<_> = app.files.iter().map(|f| f.rel_path.as_str()).collect();
        // Conflict(0) < LocalNewer(1) < RemoteNewer(2) < Synced(4).
        assert_eq!(
            order,
            vec!["conflict.md", "local.md", "remote.md", "synced.md"]
        );
    }

    // ── refresh_status_cache ────────────────────────────────────────────

    #[test]
    fn refresh_status_cache_defaults_to_not_gisted() {
        let (_d, app) = app3();
        // No store entries: everything is NotGisted.
        assert_eq!(app.cached_status("a.md"), sync::SyncStatus::NotGisted);
        assert_eq!(app.cached_status("unknown.md"), sync::SyncStatus::NotGisted);
    }

    #[test]
    fn refresh_status_cache_reflects_store() {
        let (_d, mut app) = app3();
        let root = app.active_root_path().unwrap();
        app.store_mut()
            .insert(&root, "a.md".into(), synced_entry("alpha"));
        // A gist whose recorded local hash differs from disk => LocalNewer.
        app.store_mut()
            .insert(&root, "b.md".into(), synced_entry("stale-content"));
        app.refresh_status_cache();
        assert_eq!(app.cached_status("a.md"), sync::SyncStatus::Synced);
        assert_eq!(app.cached_status("b.md"), sync::SyncStatus::LocalNewer);
        assert_eq!(app.cached_status("sub/c.md"), sync::SyncStatus::NotGisted);
    }

    #[test]
    fn refresh_status_for_updates_single_entry() {
        let (_d, mut app) = app3();
        let root = app.active_root_path().unwrap();
        app.store_mut()
            .insert(&root, "a.md".into(), synced_entry("alpha"));
        app.refresh_status_for("a.md");
        assert_eq!(app.cached_status("a.md"), sync::SyncStatus::Synced);
    }

    // ── status_counts / update_status ───────────────────────────────────

    #[test]
    fn status_counts_tallies_all_buckets() {
        let (_d, mut app) = app3();
        app.status_cache.clear();
        app.status_cache
            .insert("a.md".into(), sync::SyncStatus::Synced);
        app.status_cache
            .insert("b.md".into(), sync::SyncStatus::Conflict);
        // sub/c.md left out of the cache => counts as NotGisted.
        let c = app.status_counts();
        assert_eq!(c.synced, 1);
        assert_eq!(c.conflict, 1);
        assert_eq!(c.not_gisted, 1);
    }

    #[test]
    fn update_status_dashboard_when_nothing_selected() {
        let (_d, mut app) = app3();
        // Nothing selected: status bar shows the root dashboard.
        app.update_status();
        assert!(!app.status_spans.is_empty());
        // Three NotGisted files, no conflict => DarkGray dashboard color.
        assert_eq!(app.status_color, Color::DarkGray);
    }

    #[test]
    fn update_status_conflict_colors_red() {
        let (_d, mut app) = app3();
        app.status_cache
            .insert("a.md".into(), sync::SyncStatus::Conflict);
        app.update_status();
        assert_eq!(app.status_color, Color::Red);
    }

    #[test]
    fn update_status_selected_file_shows_path() {
        let (_d, mut app) = app3();
        select(&mut app, "a.md");
        app.update_status();
        assert!(app.status_message.contains("a.md"));
        assert!(app.status_message.contains("no gist"));
    }

    // ── jump_to ─────────────────────────────────────────────────────────

    #[test]
    fn jump_to_expands_ancestors_and_selects_leaf() {
        let (_d, mut app) = app3();
        app.focused_pane = PaneFocus::Right;
        app.jump_to("sub/c.md");
        assert_eq!(app.selected_file().as_deref(), Some("sub/c.md"));
        // jump_to always refocuses the tree.
        assert_eq!(app.focused_pane, PaneFocus::Tree);
    }

    // ── jump_to_next_dirty ──────────────────────────────────────────────

    #[test]
    fn jump_to_next_dirty_finds_dirty_file() {
        let (_d, mut app) = app3();
        // All three files are NotGisted (dirty). From no selection, forward
        // lands on a file.
        app.jump_to_next_dirty(true);
        assert!(app.selected_file().is_some());
    }

    #[test]
    fn jump_to_next_dirty_no_dirty_reports() {
        let (_d, mut app) = app3();
        // Mark every file Synced so nothing is dirty.
        for f in ["a.md", "b.md", "sub/c.md"] {
            app.status_cache.insert(f.into(), sync::SyncStatus::Synced);
        }
        app.jump_to_next_dirty(true);
        assert_eq!(app.status_message, "No dirty files.");
    }

    #[test]
    fn jump_to_next_dirty_wraps_backward() {
        let (_d, mut app) = app3();
        // Only one dirty file; make the rest Synced.
        for f in ["a.md", "b.md", "sub/c.md"] {
            app.status_cache.insert(f.into(), sync::SyncStatus::Synced);
        }
        // Pick the single dirty target deterministically.
        app.config.sort.mode = SortMode::AlphaAsc;
        app.rebuild_tree();
        app.status_cache
            .insert("b.md".into(), sync::SyncStatus::LocalNewer);
        app.jump_to_next_dirty(false);
        assert_eq!(app.selected_file().as_deref(), Some("b.md"));
    }

    // ── handle_mouse ────────────────────────────────────────────────────

    fn mouse(kind: MouseEventKind, col: u16, row: u16) -> MouseEvent {
        MouseEvent {
            kind,
            column: col,
            row,
            modifiers: KeyModifiers::NONE,
        }
    }

    #[test]
    fn mouse_scroll_over_right_pane_scrolls_preview() {
        let (_d, mut app) = app3();
        app.tree_pane_rect = Rect::new(0, 0, 10, 20);
        app.right_pane_rect = Rect::new(10, 0, 30, 20);
        app.handle_mouse(mouse(MouseEventKind::ScrollDown, 20, 5));
        assert_eq!(app.preview_scroll, 3);
        app.handle_mouse(mouse(MouseEventKind::ScrollUp, 20, 5));
        assert_eq!(app.preview_scroll, 0);
    }

    #[test]
    fn mouse_left_click_right_pane_focuses_right() {
        let (_d, mut app) = app3();
        app.tree_pane_rect = Rect::new(0, 0, 10, 20);
        app.right_pane_rect = Rect::new(10, 0, 30, 20);
        app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), 20, 5));
        assert_eq!(app.focused_pane, PaneFocus::Right);
    }

    #[test]
    fn mouse_scroll_over_tree_scrolls_tree_not_preview() {
        let (_d, mut app) = app3();
        app.tree_pane_rect = Rect::new(0, 0, 10, 20);
        app.right_pane_rect = Rect::new(10, 0, 30, 20);
        app.handle_mouse(mouse(MouseEventKind::ScrollDown, 5, 5));
        // Preview untouched; tree pane handled the scroll.
        assert_eq!(app.preview_scroll, 0);
    }

    // ── pure helpers ────────────────────────────────────────────────────

    #[test]
    fn status_rank_cached_orders_states() {
        assert_eq!(status_rank_cached(Some(sync::SyncStatus::Conflict)), 0);
        assert_eq!(status_rank_cached(Some(sync::SyncStatus::LocalNewer)), 1);
        assert_eq!(status_rank_cached(Some(sync::SyncStatus::RemoteNewer)), 2);
        assert_eq!(status_rank_cached(Some(sync::SyncStatus::NotGisted)), 3);
        assert_eq!(status_rank_cached(Some(sync::SyncStatus::Synced)), 4);
        // None sorts as NotGisted.
        assert_eq!(status_rank_cached(None), 3);
    }

    #[test]
    fn rect_contains_boundaries() {
        let r = Rect::new(2, 3, 4, 5); // x:2..6, y:3..8
        assert!(rect_contains(&r, 2, 3));
        assert!(rect_contains(&r, 5, 7));
        assert!(!rect_contains(&r, 6, 3)); // x == x+width is outside
        assert!(!rect_contains(&r, 2, 8));
        assert!(!rect_contains(&r, 1, 3));
        // A zero-area rect contains nothing.
        assert!(!rect_contains(&Rect::new(0, 0, 0, 0), 0, 0));
    }

    #[test]
    fn scroll_right_pane_saturates_at_zero() {
        let (_d, mut app) = app3();
        app.preview_scroll = 2;
        app.scroll_right_pane(5, false);
        assert_eq!(app.preview_scroll, 0);
        app.scroll_right_pane(4, true);
        assert_eq!(app.preview_scroll, 4);
    }
}