clankerdiff-ratatui 0.1.7

Embeddable Ratatui diff review widget
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
use crate::{
    DiffReviewCommand, InteractionPhase, KeyBinding, NavigationPane, ReviewOptions, ThemeChoice,
    default_diff_keybindings,
    drawer::{DrawerEntry, DrawerTree},
    patch_layout::PatchVisualLayout,
    theme_picker::ThemePicker,
};
use clankerdiff_core::{
    DiffDocument, DiffPresentation, DiffScope, DiffSide, FileStatus, Layout, RepositoryAction,
    RevealAmount, Review, ReviewCapabilities, ReviewSession, StageState, ViewMode,
};
use clankerdiff_syntax::{HighlightStats, SyntaxHighlighter};
use clankerdiff_theme::ReviewTheme;
use ratatui::layout::{Position, Rect};
use std::{
    collections::hash_map::DefaultHasher,
    hash::{Hash, Hasher},
    sync::Arc,
};

pub(crate) const SPLIT_BREAKPOINT: u16 = 96;

pub use clankerdiff_core::FocusPane;

/// Current host-provided document state.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DiffReviewStatus {
    /// A host is loading a snapshot.
    Loading,
    /// A document is ready for review.
    Ready,
    /// Loading failed with a host-provided message.
    Error(String),
}

#[derive(Debug, Clone, Copy, Default)]
pub(crate) struct HitLayout {
    pub drawer: Rect,
    pub drawer_stage_column: Option<u16>,
    pub patch: Rect,
}

#[derive(Debug, Clone, Copy, Default)]
enum DrawerFollow {
    #[default]
    Pending,
    Settled,
}

#[derive(Debug)]
pub(crate) enum RepositoryPrompt {
    Commit {
        message: String,
    },
    Discard {
        path: clankerdiff_core::RepoPath,
        status: FileStatus,
    },
}

/// Status of the most recent repository mutation requested by the UI.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum RepositoryOperationStatus {
    #[default]
    Idle,
    Pending,
    Error(String),
}

#[derive(Debug)]
struct CachedPatchLayout {
    key: u64,
    layout: Arc<PatchVisualLayout>,
}

/// Persistent state for [`crate::DiffReviewWidget`].
#[derive(Debug)]
pub struct DiffReviewState {
    pub(crate) session: ReviewSession,
    pub(crate) scope: DiffScope,
    pub(crate) options: ReviewOptions,
    pub(crate) capabilities: ReviewCapabilities,
    pub(crate) keybindings: Vec<KeyBinding<DiffReviewCommand>>,
    pub(crate) theme_choices: Arc<[ThemeChoice]>,
    pub(crate) theme: ReviewTheme,
    pub(crate) highlighter: SyntaxHighlighter,
    pub(crate) status: DiffReviewStatus,
    pub(crate) focus: FocusPane,
    pub(crate) drawer: DrawerTree,
    pub(crate) drawer_selected: usize,
    pub(crate) drawer_scroll: usize,
    pub(crate) drawer_height: usize,
    drawer_follow: DrawerFollow,
    pub(crate) scroll: usize,
    pub(crate) last_height: usize,
    pub(crate) presentation_width: u16,
    patch_layout: Option<CachedPatchLayout>,
    pub(crate) help: bool,
    pub(crate) help_scroll: usize,
    pub(crate) theme_picker: Option<ThemePicker>,
    pub(crate) repository_prompt: Option<RepositoryPrompt>,
    pub(crate) repository_status: RepositoryOperationStatus,
    pub(crate) background_error: Option<String>,
    deferred_document: Option<Arc<DiffDocument>>,
    deferred_scope: Option<DiffScope>,
    pub(crate) hit_layout: HitLayout,
    pub(crate) visible_rows: Vec<(u16, usize)>,
    pub(crate) cursor_position: Option<Position>,
    pub(crate) follow_pending: bool,
    pub(crate) dirty: bool,
}

impl DiffReviewState {
    /// Creates ready state from an immutable document snapshot.
    #[must_use]
    pub fn new(document: Arc<DiffDocument>) -> Self {
        Self::with_theme(document, ReviewTheme::default())
    }

    /// Creates ready state with a shared neutral theme.
    #[must_use]
    pub fn with_theme(document: Arc<DiffDocument>, theme: ReviewTheme) -> Self {
        let drawer = DrawerTree::new(&document);
        let drawer_selected = drawer.position_of_file(0).unwrap_or(0);
        let mut state = Self {
            session: ReviewSession::new(document),
            scope: DiffScope::Both,
            options: ReviewOptions::default(),
            capabilities: ReviewCapabilities::default(),
            keybindings: default_diff_keybindings(),
            theme_choices: Arc::from([]),
            theme,
            highlighter: SyntaxHighlighter::default(),
            status: DiffReviewStatus::Ready,
            focus: FocusPane::Files,
            drawer,
            drawer_selected,
            drawer_scroll: 0,
            drawer_height: 1,
            drawer_follow: DrawerFollow::Pending,
            scroll: 0,
            last_height: 0,
            presentation_width: 0,
            patch_layout: None,
            help: false,
            help_scroll: 0,
            theme_picker: None,
            repository_prompt: None,
            repository_status: RepositoryOperationStatus::Idle,
            background_error: None,
            deferred_document: None,
            deferred_scope: None,
            hit_layout: HitLayout::default(),
            visible_rows: Vec::new(),
            cursor_position: None,
            follow_pending: true,
            dirty: true,
        };
        state.scroll_to_selected_file();
        state
    }

    /// Creates loading state with an empty placeholder document.
    #[must_use]
    pub fn loading() -> Self {
        let mut state = Self::new(Arc::new(DiffDocument::empty()));
        state.status = DiffReviewStatus::Loading;
        state
    }

    #[must_use]
    pub const fn session(&self) -> &ReviewSession {
        &self.session
    }

    pub const fn session_mut(&mut self) -> &mut ReviewSession {
        &mut self.session
    }

    #[must_use]
    pub const fn scope(&self) -> DiffScope {
        self.scope
    }

    pub fn set_scope(&mut self, scope: DiffScope) {
        if self.interaction_phase() == InteractionPhase::Browse {
            self.scope = scope;
            self.mark_dirty();
        } else {
            self.deferred_scope = Some(scope);
        }
    }

    /// Returns the current immutable snapshot.
    #[must_use]
    pub const fn document(&self) -> &Arc<DiffDocument> {
        self.session.document()
    }

    /// Returns the structured review.
    #[must_use]
    pub const fn review(&self) -> &Review {
        self.session.review()
    }

    /// Returns mutable review access for host-driven operations.
    pub const fn review_mut(&mut self) -> &mut Review {
        self.session.review_mut()
    }

    #[must_use]
    pub const fn presentation(&self) -> &DiffPresentation {
        self.session.presentation()
    }

    /// Returns the current load status.
    #[must_use]
    pub const fn status(&self) -> &DiffReviewStatus {
        &self.status
    }

    /// Returns the focused pane.
    #[must_use]
    pub const fn focus(&self) -> FocusPane {
        self.focus
    }

    /// Returns the selected file index, when the document has files.
    #[must_use]
    pub fn selected_file(&self) -> Option<usize> {
        self.session.selected_file()
    }

    /// Returns the selected presentation-row index, when rows exist.
    #[must_use]
    pub fn selected_row(&self) -> Option<usize> {
        self.session.selected_row()
    }

    #[must_use]
    pub const fn selected_side(&self) -> DiffSide {
        self.session.selected_side()
    }

    /// Returns the active renderer-neutral theme.
    #[must_use]
    pub const fn theme(&self) -> &ReviewTheme {
        &self.theme
    }

    /// Returns syntax cache and work counters.
    #[must_use]
    pub const fn highlight_stats(&self) -> HighlightStats {
        self.highlighter.stats()
    }

    /// Returns the first visible rendered-row index in the selected file.
    #[must_use]
    pub const fn scroll_offset(&self) -> usize {
        self.scroll
    }

    /// Returns whether anything since the last frame changed what a redraw
    /// would show.
    ///
    /// Hosts may skip drawing [`crate::DiffReviewWidget`] while this is false,
    /// which keeps pointer motion in a terminal reporting all mouse movement
    /// from costing a frame each. Rendering the widget clears it.
    #[must_use]
    pub const fn is_dirty(&self) -> bool {
        self.dirty
    }

    /// Marks the state as needing a redraw, for changes the widget cannot
    /// observe on its own, such as a terminal resize.
    pub const fn mark_dirty(&mut self) {
        self.dirty = true;
    }

    /// Returns the requested view mode.
    #[must_use]
    pub const fn view_mode(&self) -> ViewMode {
        self.session.view_mode()
    }

    #[must_use]
    pub const fn layout(&self) -> Layout {
        self.session.layout()
    }

    /// Returns the terminal cursor position for an active comment draft.
    ///
    /// Hosts may pass this to `Frame::set_cursor_position` after rendering.
    #[must_use]
    pub const fn cursor_position(&self) -> Option<Position> {
        self.cursor_position
    }

    /// Replaces the complete document while retaining and reconciling review comments.
    pub fn set_document(&mut self, document: Arc<DiffDocument>) {
        if self.interaction_phase() == InteractionPhase::Browse {
            self.install_document(document);
        } else {
            self.deferred_document = Some(document);
        }
    }

    pub(crate) fn install_deferred(&mut self) {
        if self.interaction_phase() != InteractionPhase::Browse {
            return;
        }
        if let Some(document) = self.deferred_document.take() {
            self.install_document(document);
        }
        if let Some(scope) = self.deferred_scope.take() {
            self.set_scope(scope);
        }
    }

    fn install_document(&mut self, document: Arc<DiffDocument>) {
        self.session.set_document(document);
        self.status = DiffReviewStatus::Ready;
        self.cursor_position = None;
        self.mark_dirty();
        let document = self.document().clone();
        self.drawer.rebuild(&document);
        if let Some(selected) = self.session.selected_file() {
            self.drawer.expand_file(&document, selected);
            self.drawer_selected = self.drawer.position_of_file(selected).unwrap_or(0);
        } else {
            self.drawer_selected = 0;
        }
        self.follow_drawer_selection();
        self.request_follow();
    }

    /// Marks the state as waiting for a host snapshot.
    pub fn set_loading(&mut self) {
        self.status = DiffReviewStatus::Loading;
        self.deferred_document = None;
        self.deferred_scope = None;
        self.session.cancel_draft();
        self.cursor_position = None;
        self.mark_dirty();
    }

    /// Shows a host-provided loading error.
    pub fn set_error(&mut self, message: impl Into<String>) {
        self.status = DiffReviewStatus::Error(message.into());
        self.deferred_document = None;
        self.deferred_scope = None;
        self.session.cancel_draft();
        self.cursor_position = None;
        self.mark_dirty();
    }

    /// Marks a repository mutation as in flight while retaining the current snapshot.
    pub fn set_repository_pending(&mut self) {
        self.repository_status = RepositoryOperationStatus::Pending;
        self.repository_prompt = None;
        self.mark_dirty();
    }

    /// Clears a pending repository mutation without replacing the snapshot.
    pub fn clear_repository_pending(&mut self) {
        self.repository_status = RepositoryOperationStatus::Idle;
        self.mark_dirty();
    }

    /// Shows a repository mutation error while retaining the current snapshot.
    pub fn set_repository_error(&mut self, message: impl Into<String>) {
        self.repository_status = RepositoryOperationStatus::Error(message.into());
        self.repository_prompt = None;
        self.mark_dirty();
    }

    /// Reconciles background refresh health independently of command completion.
    pub fn set_background_error(&mut self, message: Option<String>) {
        if self.background_error != message {
            self.background_error = message;
            self.mark_dirty();
        }
    }

    /// Whether a host command is still in flight.
    #[must_use]
    pub fn repository_pending(&self) -> bool {
        matches!(self.repository_status, RepositoryOperationStatus::Pending)
    }

    /// The command error, or otherwise the current background refresh failure.
    #[must_use]
    pub fn repository_error(&self) -> Option<&str> {
        match &self.repository_status {
            RepositoryOperationStatus::Error(message) => Some(message),
            _ => self.background_error.as_deref(),
        }
    }

    pub(crate) fn toggle_stage_action(&self) -> Option<RepositoryAction> {
        let entry = self.drawer.entry(self.drawer_selected)?;
        let document = self.document();
        let state = DrawerTree::stage_state_for_entry(document, entry);
        let paths = DrawerTree::paths_for_entry(document, entry);
        if paths.is_empty() {
            return None;
        }
        Some(if state == StageState::Staged {
            RepositoryAction::UnstagePaths(paths)
        } else {
            RepositoryAction::StagePaths(paths)
        })
    }

    pub(crate) fn begin_commit(&mut self) {
        self.repository_prompt = Some(RepositoryPrompt::Commit {
            message: String::new(),
        });
    }

    pub(crate) fn begin_discard(&mut self) {
        let Some(file) = self
            .selected_file()
            .and_then(|index| self.document().files.get(index))
        else {
            return;
        };
        self.repository_prompt = Some(RepositoryPrompt::Discard {
            path: file.path.clone(),
            status: file.status,
        });
    }

    pub fn set_theme(&mut self, theme: ReviewTheme) {
        self.theme_picker = None;
        self.apply_theme(theme);
    }

    pub(crate) fn apply_theme(&mut self, theme: ReviewTheme) {
        self.theme = theme;
        self.mark_dirty();
    }

    #[must_use]
    pub const fn options(&self) -> &ReviewOptions {
        &self.options
    }

    #[must_use]
    pub fn keybindings(&self) -> &[KeyBinding<DiffReviewCommand>] {
        &self.keybindings
    }

    pub fn set_keybindings(&mut self, bindings: impl Into<Vec<KeyBinding<DiffReviewCommand>>>) {
        self.keybindings = bindings.into();
        self.help_scroll = 0;
        self.mark_dirty();
    }

    pub fn set_options(&mut self, options: ReviewOptions) {
        if matches!(
            options.navigation,
            NavigationPane::Hidden | NavigationPane::Width(0)
        ) {
            self.focus = FocusPane::Diff;
        }
        self.options = options;
        self.hit_layout = HitLayout::default();
        self.request_follow();
    }

    #[must_use]
    pub fn theme_choices(&self) -> &[ThemeChoice] {
        &self.theme_choices
    }

    pub fn set_theme_choices(&mut self, themes: impl Into<Arc<[ThemeChoice]>>) {
        if let Some(picker) = self.theme_picker.take() {
            self.set_theme(picker.cancel());
        }
        self.theme_choices = themes.into();
        self.mark_dirty();
    }

    pub(crate) fn select_file(&mut self, index: usize) -> bool {
        if !self.session.select_file(index) {
            return false;
        }
        self.drawer.expand_file(self.session.document(), index);
        self.drawer_selected = self.drawer.position_of_file(index).unwrap_or(0);
        self.follow_drawer_selection();
        self.scroll_to_selected_file();
        true
    }

    fn finish_projection_change(&mut self, changed: bool) -> bool {
        if changed {
            self.request_follow();
        }
        changed
    }

    pub fn reveal_selected_gap(&mut self, amount: RevealAmount) -> bool {
        let previous = (
            self.session.selected_file_range(),
            self.session.selected_row(),
            self.session.selected_side(),
        );
        self.session.reveal_selected_gap(amount);
        let changed = previous
            != (
                self.session.selected_file_range(),
                self.session.selected_row(),
                self.session.selected_side(),
            );
        self.finish_projection_change(changed)
    }

    pub fn toggle_full_file(&mut self) -> bool {
        let changed = self.session.toggle_full_file();
        self.finish_projection_change(changed)
    }

    /// Selects automatic, unified, or split presentation.
    pub fn set_view_mode(&mut self, mode: ViewMode) {
        if self.session.set_view_mode(mode) {
            self.scroll_to_selected_file();
        }
    }

    /// Clears all queued comments and any active draft.
    pub fn clear_review(&mut self) {
        self.session.clear_review();
        self.cursor_position = None;
        self.mark_dirty();
    }

    pub(crate) fn ensure_presentation(&mut self, width: u16) {
        let width_changed = self.presentation_width != width;
        self.presentation_width = width;
        if self.session.set_split_when_auto(width >= SPLIT_BREAKPOINT) {
            self.scroll_to_selected_file();
        } else if width_changed {
            self.request_follow();
        }
    }

    pub(crate) fn scroll_to_selected_file(&mut self) {
        self.scroll = 0;
        self.request_follow();
    }

    pub(crate) fn move_drawer_entry(&mut self, delta: isize) {
        let last = self.drawer.entries().len().saturating_sub(1);
        self.drawer_selected = offset(self.drawer_selected, delta, last);
        if let Some(DrawerEntry::File { index, .. }) = self.drawer.entry(self.drawer_selected) {
            let index = *index;
            if self.session.select_file(index) {
                self.scroll_to_selected_file();
            }
        }
        self.follow_drawer_selection();
    }

    pub(crate) fn select_drawer_entry(&mut self, index: usize) {
        if index >= self.drawer.entries().len() {
            return;
        }
        self.drawer_selected = index;
        if let Some(DrawerEntry::File { index, .. }) = self.drawer.entry(index) {
            let index = *index;
            if self.session.select_file(index) {
                self.scroll_to_selected_file();
            }
        }
        self.follow_drawer_selection();
    }

    /// Expands the selected directory, or selects the current file. Returns
    /// whether the selected entry was a directory.
    pub(crate) fn expand_or_open_drawer_entry(&mut self) -> bool {
        match self.drawer.entry(self.drawer_selected).cloned() {
            Some(DrawerEntry::Directory { path, .. }) => {
                self.drawer.expand(&path);
                self.drawer_selected = self.drawer.position_of_directory(&path).unwrap_or(0);
                self.follow_drawer_selection();
                self.mark_dirty();
                true
            }
            Some(DrawerEntry::File { index, .. }) => {
                if self.session.select_file(index) {
                    self.scroll_to_selected_file();
                }
                false
            }
            None => false,
        }
    }

    pub(crate) fn collapse_drawer_entry(&mut self) {
        let Some(DrawerEntry::Directory { path, .. }) =
            self.drawer.entry(self.drawer_selected).cloned()
        else {
            return;
        };
        self.drawer.collapse(&path);
        self.drawer_selected = self.drawer.position_of_directory(&path).unwrap_or(0);
        self.follow_drawer_selection();
        self.mark_dirty();
    }

    fn follow_drawer_selection(&mut self) {
        self.drawer_follow = DrawerFollow::Pending;
        if self.drawer_selected < self.drawer_scroll {
            self.drawer_scroll = self.drawer_selected;
        } else if self.drawer_selected >= self.drawer_scroll.saturating_add(self.drawer_height) {
            self.drawer_scroll = self
                .drawer_selected
                .saturating_sub(self.drawer_height.saturating_sub(1));
        }
    }

    pub(crate) fn take_drawer_follow_request(&mut self) -> bool {
        matches!(
            std::mem::replace(&mut self.drawer_follow, DrawerFollow::Settled),
            DrawerFollow::Pending
        )
    }

    pub(crate) fn move_row(&mut self, delta: isize) {
        let selected = self.session.selected_row();
        let side = self.session.selected_side();
        self.session.move_row(delta);
        if self.session.selected_row() != selected || self.session.selected_side() != side {
            self.request_follow();
        }
    }

    pub(crate) fn select_boundary(&mut self, end: bool) {
        self.session.select_boundary(end);
        self.request_follow();
    }

    /// Scrolls the patch viewport without moving the selection. The selection
    /// may leave the viewport; the next selection move brings it back.
    pub(crate) fn scroll_patch(&mut self, delta: isize) {
        let Some(layout) = self.patch_visual_layout() else {
            return;
        };
        if layout.is_empty() {
            return;
        }
        let target = if delta.is_negative() {
            self.scroll.saturating_sub(delta.unsigned_abs())
        } else {
            self.scroll.saturating_add(delta.unsigned_abs())
        };
        let last = layout.len().saturating_sub(self.last_height.max(1));
        let clamped = target.min(last);
        self.follow_pending = false;
        if clamped != self.scroll {
            self.scroll = clamped;
            self.mark_dirty();
        }
    }

    /// Scrolls the file drawer without moving the selected file.
    pub(crate) fn scroll_drawer(&mut self, delta: isize) {
        let last = self
            .drawer
            .entries()
            .len()
            .saturating_sub(self.drawer_height);
        let target = if delta.is_negative() {
            self.drawer_scroll.saturating_sub(delta.unsigned_abs())
        } else {
            self.drawer_scroll.saturating_add(delta.unsigned_abs())
        };
        let clamped = target.min(last);
        self.drawer_follow = DrawerFollow::Settled;
        if clamped != self.drawer_scroll {
            self.drawer_scroll = clamped;
            self.mark_dirty();
        }
    }

    pub(crate) fn page(&mut self, delta: isize) {
        let height = isize::try_from(self.last_height.max(1)).unwrap_or(isize::MAX);
        self.scroll_patch(delta.saturating_mul(height));
    }

    /// Brings the selection back into view against the height the last frame
    /// measured, and asks the next frame to redo it once it knows its own.
    /// Before any frame has drawn there is no height to work from, so the
    /// request only carries over.
    pub(crate) fn request_follow(&mut self) {
        self.follow_pending = true;
        self.mark_dirty();
        self.follow_selection();
    }

    pub(crate) fn take_follow_request(&mut self) -> bool {
        std::mem::take(&mut self.follow_pending)
    }

    pub(crate) fn follow_selection(&mut self) {
        if self.last_height == 0 {
            return;
        }
        let Some(selected) = self.session.selected_row() else {
            return;
        };
        let draft = self.session.draft().is_some();
        let Some(layout) = self.patch_visual_layout() else {
            return;
        };
        let Some(target) = layout.focused_visual_row(selected, draft) else {
            return;
        };
        let height = self.last_height.max(1);
        if target < self.scroll {
            self.scroll = target;
        } else if target >= self.scroll.saturating_add(height) {
            self.scroll = target.saturating_sub(height.saturating_sub(1));
        }
        self.scroll = self.scroll.min(layout.len().saturating_sub(height));
    }

    pub(crate) fn patch_visual_layout(&mut self) -> Option<Arc<PatchVisualLayout>> {
        let range = self.session.selected_file_range()?;
        let key = self.patch_layout_key(&range);
        let rebuild = self
            .patch_layout
            .as_ref()
            .is_none_or(|cached| cached.key != key);
        if rebuild {
            self.patch_layout = Some(CachedPatchLayout {
                key,
                layout: Arc::new(PatchVisualLayout::new(
                    &self.session,
                    range,
                    self.presentation_width,
                )),
            });
        }
        self.patch_layout
            .as_ref()
            .map(|cached| cached.layout.clone())
    }

    fn patch_layout_key(&self, range: &std::ops::Range<usize>) -> u64 {
        let mut hasher = DefaultHasher::new();
        (Arc::as_ptr(self.document()) as usize).hash(&mut hasher);
        self.presentation_width.hash(&mut hasher);
        self.layout().is_split().hash(&mut hasher);
        self.session.projection_revision().hash(&mut hasher);
        range.start.hash(&mut hasher);
        range.end.hash(&mut hasher);
        for comment in self.review().comments() {
            comment.id.hash(&mut hasher);
            comment.anchor.hash(&mut hasher);
            comment.body.hash(&mut hasher);
            comment.outdated.hash(&mut hasher);
        }
        if let Some(draft) = self.session.draft() {
            draft.anchor().hash(&mut hasher);
            draft.body().hash(&mut hasher);
            draft.cursor().hash(&mut hasher);
        }
        hasher.finish()
    }

    pub(crate) fn select_clicked_row(&mut self, row: u16) {
        let clicked = self
            .visible_rows
            .iter()
            .find(|(screen_row, _)| *screen_row == row)
            .map(|(_, index)| *index);
        if let Some(index) = clicked
            && self.session.select_row(index)
        {
            if self.session.presentation().gap_info(index).is_some() {
                self.reveal_selected_gap(RevealAmount::Step);
            }
            self.request_follow();
        }
    }
}

fn offset(current: usize, delta: isize, last: usize) -> usize {
    if delta.is_negative() {
        current.saturating_sub(delta.unsigned_abs())
    } else {
        current.saturating_add(delta.unsigned_abs()).min(last)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use clankerdiff_core::FileDiff;
    use clankerdiff_theme::ThemeId;

    #[test]
    fn new_uses_the_default_sage_theme() {
        let state = DiffReviewState::new(Arc::new(DiffDocument::empty()));
        assert_eq!(state.theme.id(), &ThemeId::Sage);
    }

    #[test]
    fn comments_above_selection_count_toward_viewport_height() {
        let document = Arc::new(DiffDocument {
            repo_root: "/repo".into(),
            files: vec![FileDiff::from_texts("a.rs", "a\nb\nc\n", "A\nB\nC\n").unwrap()],
        });
        let mut state = DiffReviewState::new(document);
        state.last_height = 3;
        let anchor = state.session.selected_anchor().unwrap();
        state.session.review_mut().add_comment(anchor, "note");
        state.session.move_row(2);
        state.follow_selection();
        assert!(state.scroll > 0);
    }
}