brain: Stale review state recovery

375238324f62b090859278c099ffe0d512079df4
Prompt the reviewer with a modal dialog when the stored review base no
longer matches the branch, offering to reset the hidden state while
keeping comments. Adds a reusable Dialog widget, a shared session event
stream so the prompt and session loop read the same terminal input, and
initial hunk focus on commit load.

Assisted-by: Claude:fable-5
Alexis Sellier committed ago 1 parent 7d735d9e
crates/brain/src/backend.rs +48 -12
97 97
    fn commit_diff(&self, commit: &Commit) -> Result<DiffDocument, Error>;
98 98
99 99
    /// Loads the hidden review state for this backend.
100 100
    fn brain(&self) -> Result<Brain, Error>;
101 101
102 +
    /// Resets and loads the hidden review state for this backend.
103 +
    fn reset_brain(&self) -> Result<Brain, Error>;
104 +
102 105
    /// Returns a repo handle for widening `commit`'s hunk context.
103 106
    fn repo(&self, commit: &Commit) -> git::Repository;
104 107
}
105 108
106 109
impl dyn Backend {
163 166
                        stored_base: parent,
164 167
                        current_base: base,
165 168
                    });
166 169
                }
167 170
            }
168 -
            None => {
169 -
                let tree = repository.tree_id(base)?;
170 -
                let fresh = repository.commit(
171 -
                    tree,
172 -
                    base,
173 -
                    "brain",
174 -
                    "brain@example.invalid",
175 -
                    SYNTHETIC_BRAIN_MESSAGE,
176 -
                )?;
177 -
                repository.update_ref(&state_ref, fresh)?;
178 -
                fresh
179 -
            }
171 +
            None => Brain::write_fresh_state(&repository, base, &state_ref)?,
180 172
        };
181 173
        Ok(Self {
182 174
            repository,
183 175
            state_ref,
184 176
            comments_ref,
185 177
            base,
186 178
            commit,
187 179
        })
188 180
    }
189 181
182 +
    /// Replaces the hidden review state for one review and returns it.
183 +
    fn reset(repository: git::Repository, base: Oid, review: &str) -> Result<Self, Error> {
184 +
        let state_ref = Brain::ref_for(STATE_REF_NAMESPACE, review)?;
185 +
        let comments_ref = Brain::ref_for(COMMENTS_REF_NAMESPACE, review)?;
186 +
        let commit = Brain::write_fresh_state(&repository, base, &state_ref)?;
187 +
188 +
        Ok(Self {
189 +
            repository,
190 +
            state_ref,
191 +
            comments_ref,
192 +
            base,
193 +
            commit,
194 +
        })
195 +
    }
196 +
197 +
    /// Writes an empty accepted-state commit at `base`.
198 +
    fn write_fresh_state(
199 +
        repository: &git::Repository,
200 +
        base: Oid,
201 +
        state_ref: &Qualified<'_>,
202 +
    ) -> Result<Oid, Error> {
203 +
        let tree = repository.tree_id(base)?;
204 +
        let fresh = repository.commit(
205 +
            tree,
206 +
            base,
207 +
            "brain",
208 +
            "brain@example.invalid",
209 +
            SYNTHETIC_BRAIN_MESSAGE,
210 +
        )?;
211 +
        repository.update_ref(state_ref, fresh)?;
212 +
213 +
        Ok(fresh)
214 +
    }
215 +
190 216
    /// Computes the stable Git patch id for `patch` text.
191 217
    pub fn patch_id(&self, patch: &str) -> Result<PatchId, Error> {
192 218
        let patch_id = self.repository.patch_id(patch)?;
193 219
        Ok(patch_id)
194 220
    }
377 403
    fn brain(&self) -> Result<Brain, Error> {
378 404
        let base = self.repository.commit_id(&self.base)?;
379 405
        Brain::load(self.repository.clone(), base, self.target.as_str())
380 406
    }
381 407
408 +
    fn reset_brain(&self) -> Result<Brain, Error> {
409 +
        let base = self.repository.commit_id(&self.base)?;
410 +
        Brain::reset(self.repository.clone(), base, self.target.as_str())
411 +
    }
412 +
382 413
    fn repo(&self, commit: &Commit) -> git::Repository {
383 414
        self.repository.with_selector_args(commit.selectors())
384 415
    }
385 416
}
386 417
425 456
    fn brain(&self) -> Result<Brain, Error> {
426 457
        let base = self.jj.resolve(&self.base)?;
427 458
        Brain::load(self.repository.clone(), base, self.target.as_str())
428 459
    }
429 460
461 +
    fn reset_brain(&self) -> Result<Brain, Error> {
462 +
        let base = self.jj.resolve(&self.base)?;
463 +
        Brain::reset(self.repository.clone(), base, self.target.as_str())
464 +
    }
465 +
430 466
    fn repo(&self, commit: &Commit) -> git::Repository {
431 467
        self.repository.with_selector_args(commit.selectors())
432 468
    }
433 469
}
434 470
crates/brain/src/main.rs +102 -5
20 20
use std::io::{self, Write as _};
21 21
use std::process::ExitCode;
22 22
23 23
use rustik_diff::{Builtins, DiffOptions, FileTreeMode, HunkFocus};
24 24
use rustik_repo::Rev;
25 -
use rustik_tui::Terminal;
25 +
use rustik_tui::{ActionList, Dialog, Event, Key, Line, Size, Terminal};
26 26
use rustik_tui_termion as tui_termion;
27 27
28 28
use crate::comments::ReviewComments;
29 29
use crate::error::Error;
30 30
31 +
/// Terminal backend used by the interactive viewer.
32 +
type BrainTerminal = Terminal<tui_termion::TermionBackend<tui_termion::term::TerminalScreen>>;
33 +
34 +
/// Reviewer choice after stale state is found.
35 +
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
36 +
enum StaleReviewStateAction {
37 +
    /// Replace the stored state with empty state at the current base.
38 +
    Reset,
39 +
    /// Exit without changing stored state.
40 +
    Quit,
41 +
}
42 +
43 +
/// Dialog state shown before the review session can load.
44 +
#[derive(Clone, Copy, Debug)]
45 +
struct StaleReviewStatePrompt;
46 +
47 +
impl StaleReviewStatePrompt {
48 +
    /// Creates the dialog widget for the current frame.
49 +
    fn dialog(self) -> Dialog {
50 +
        Dialog::error()
51 +
            .body([
52 +
                Line::new("The existing review is stale."),
53 +
                Line::new("Its original base commit no longer matches this branch."),
54 +
                Line::blank(),
55 +
                Line::new("Resetting starts this review over on the current branch."),
56 +
                Line::new("Accepted hunks are cleared. Existing comments are kept."),
57 +
            ])
58 +
            .actions(
59 +
                ActionList::new()
60 +
                    .action("r", "reset state")
61 +
                    .action("q", "quit"),
62 +
            )
63 +
            .max_size(Size::new(78, 10))
64 +
    }
65 +
66 +
    /// Draws the prompt.
67 +
    fn draw(self, terminal: &mut BrainTerminal) -> Result<(), Error> {
68 +
        terminal.draw(|frame| {
69 +
            frame.render_widget(self.dialog(), frame.area);
70 +
        })?;
71 +
        Ok(())
72 +
    }
73 +
}
74 +
31 75
/// Program entry point.
32 76
fn main() -> ExitCode {
33 77
    match run(env::args_os().skip(1).collect()) {
34 78
        Ok(()) => ExitCode::SUCCESS,
35 79
        Err(error) => {
56 100
    let target = Rev::try_from(target)
57 101
        .map_err(|error| Error::Usage(format!("target revision is invalid: {error}")))?;
58 102
59 103
    let cwd = env::current_dir()?;
60 104
    let backend = <dyn backend::Backend>::from_path(&cwd, base, target)?;
61 -
    let brain = backend.brain()?;
105 +
    let mut terminal = None;
106 +
    let mut events = None;
107 +
    let brain = match backend.brain() {
108 +
        Ok(brain) => brain,
109 +
        Err(Error::StaleReviewState { .. }) => {
110 +
            let terminal = terminal.get_or_insert(open_terminal()?);
111 +
            let events = events.get_or_insert_with(session::Events::spawn);
112 +
            let action = prompt_stale_review_state(terminal, events);
113 +
            let cursor = terminal.set_cursor_visible(true);
114 +
            let action = action?;
115 +
            cursor?;
116 +
117 +
            match action {
118 +
                StaleReviewStateAction::Reset => backend.reset_brain()?,
119 +
                StaleReviewStateAction::Quit => return Ok(()),
120 +
            }
121 +
        }
122 +
        Err(error) => return Err(error),
123 +
    };
62 124
    let persisted = brain.read_comments()?;
63 125
    let comments = ReviewComments::parse(persisted.as_deref().unwrap_or_default())?;
64 126
65 127
    let assets = Builtins::load().map_err(|error| Error::Highlight(error.to_string()))?;
66 128
    let root = cwd
84 146
    commits.retain(|commit| commit.stats.files_changed > 0);
85 147
    if commits.is_empty() {
86 148
        return Err(Error::Empty);
87 149
    }
88 150
89 -
    let screen = tui_termion::term::screen()?;
90 -
    let mut terminal = Terminal::new(screen)?;
151 +
    let mut terminal = match terminal {
152 +
        Some(terminal) => terminal,
153 +
        None => open_terminal()?,
154 +
    };
155 +
    let events = events.unwrap_or_else(session::Events::spawn);
91 156
92 157
    terminal.clear()?;
93 158
    terminal.set_cursor_visible(false)?;
94 159
95 -
    let result = session::run(&mut terminal, commits, backend, brain, comments, options);
160 +
    let result = session::run(&mut terminal, events, commits, backend, brain, comments, options);
96 161
    let cursor = terminal.set_cursor_visible(true);
97 162
98 163
    result?;
99 164
    cursor.map_err(Error::Io)
100 165
}
166 +
167 +
/// Opens the raw alternate-screen terminal.
168 +
fn open_terminal() -> Result<BrainTerminal, Error> {
169 +
    let screen = tui_termion::term::screen()?;
170 +
    let terminal = Terminal::new(screen)?;
171 +
    Ok(terminal)
172 +
}
173 +
174 +
/// Prompts for how to handle stale hidden review state.
175 +
fn prompt_stale_review_state(
176 +
    terminal: &mut BrainTerminal,
177 +
    events: &session::Events,
178 +
) -> Result<StaleReviewStateAction, Error> {
179 +
    let prompt = StaleReviewStatePrompt;
180 +
181 +
    terminal.clear()?;
182 +
    terminal.set_cursor_visible(false)?;
183 +
    prompt.draw(terminal)?;
184 +
185 +
    while let Some(event) = events.next_input() {
186 +
        match event? {
187 +
            Event::Key(Key::Char('r')) => return Ok(StaleReviewStateAction::Reset),
188 +
            Event::Key(Key::Char('q') | Key::Esc | Key::Ctrl('c')) => {
189 +
                return Ok(StaleReviewStateAction::Quit);
190 +
            }
191 +
            Event::Resize(_) => prompt.draw(terminal)?,
192 +
            _ => {}
193 +
        }
194 +
    }
195 +
196 +
    Ok(StaleReviewStateAction::Quit)
197 +
}
crates/brain/src/session.rs +55 -4
1 1
//! Terminal session loop for the `brain` review TUI.
2 2
3 3
use std::io;
4 4
use std::mem;
5 -
use std::sync::mpsc::{self, Sender};
5 +
use std::sync::mpsc::{self, Receiver, Sender};
6 6
7 7
use rustik_diff::{
8 8
    ContextChange, DiffAction, DiffDocument, DiffFocus, DiffOptions, DiffViewer, FileDiff,
9 9
    FileTreeMode, HighlightOutput, HighlightRequest, Highlighter, ViewChange, spawn_highlighter,
10 10
};
40 40
    /// Boxed because the hunk view owns its own diff viewer, which would
41 41
    /// otherwise dominate the size of every mode value.
42 42
    Hunk(Box<HunkView>),
43 43
}
44 44
45 +
/// Terminal event channel shared by pre-session prompts and the session loop.
46 +
///
47 +
/// Reading terminal input consumes it, so one input worker must feed every
48 +
/// consumer; creating a second stream would steal keystrokes from the first.
49 +
pub struct Events {
50 +
    /// Sender cloned by background workers.
51 +
    tx: Sender<TerminalEvent>,
52 +
    /// Receiver drained by the session loop.
53 +
    rx: Receiver<TerminalEvent>,
54 +
}
55 +
56 +
impl Events {
57 +
    /// Creates the channel and spawns the blocking terminal input worker.
58 +
    pub fn spawn() -> Self {
59 +
        let (tx, rx) = mpsc::channel();
60 +
        TerminalEvent::spawn_input_worker(tx.clone());
61 +
        Self { tx, rx }
62 +
    }
63 +
64 +
    /// Blocks until the next terminal input event, skipping other events.
65 +
    ///
66 +
    /// Returns `None` once the input worker has disconnected.
67 +
    pub fn next_input(&self) -> Option<io::Result<Event<()>>> {
68 +
        loop {
69 +
            match self.rx.recv() {
70 +
                Ok(TerminalEvent::Input(event)) => return Some(event),
71 +
                Ok(_) => {}
72 +
                Err(_) => return None,
73 +
            }
74 +
        }
75 +
    }
76 +
}
77 +
45 78
/// Runs the terminal event loop until the reviewer quits.
46 79
pub fn run(
47 80
    terminal: &mut BrainTerminal,
81 +
    events: Events,
48 82
    commits: Vec<Commit>,
49 83
    backend: Box<dyn Backend>,
50 84
    brain: Brain,
51 85
    comments: ReviewComments,
52 86
    options: DiffOptions,
53 87
) -> Result<(), Error> {
54 -
    let (events_tx, events_rx) = mpsc::channel();
55 -
    TerminalEvent::spawn_input_worker(events_tx.clone());
88 +
    let Events {
89 +
        tx: events_tx,
90 +
        rx: events_rx,
91 +
    } = events;
56 92
57 93
    let mut session = Session {
58 94
        terminal,
59 95
        commits: commits
60 96
            .into_iter()
79 115
        context_fetch: ContextFetch::default(),
80 116
    };
81 117
    session.current()?;
82 118
    session.reconcile_reviews()?;
83 119
    session.activate()?;
120 +
    session.focus_initial_hunk(viewer_area(session.terminal.area()))?;
84 121
    session.redraw()?;
85 122
86 123
    while let Ok(event) = events_rx.recv() {
87 124
        let mut redraw = false;
88 125
        let mut next = Some(event);
296 333
        if newly_loaded {
297 334
            // Classify the freshly decoded hunks against the accepted tree.
298 335
            self.reconcile_reviews()?;
299 336
        }
300 337
        self.activate()?;
338 +
        if newly_loaded {
339 +
            self.focus_initial_hunk(viewer_area(self.terminal.area()))?;
340 +
        }
301 341
302 342
        Ok(())
303 343
    }
304 344
305 345
    /// Routes one key while the commit-list tab is open.
669 709
        self.restart_highlighter()?;
670 710
671 711
        Ok(())
672 712
    }
673 713
714 +
    /// Focuses the first visible hunk when a commit has no restored focus.
715 +
    fn focus_initial_hunk(&mut self, area: Rect) -> Result<(), Error> {
716 +
        let loaded = self.current()?;
717 +
        if loaded.viewer.state().focus.is_none() {
718 +
            loaded.viewer.apply(DiffAction::NextHunk, area);
719 +
        }
720 +
        Ok(())
721 +
    }
722 +
674 723
    /// Rebuilds the current commit's files to match accepted-hunk visibility.
675 724
    ///
676 725
    /// The original decoded files are kept in `CommitReview::files`; the viewer
677 726
    /// receives a filtered copy when accepted hunks are hidden.
678 727
    fn refresh_visibility(&mut self) -> Result<(), Error> {
836 885
        match &mut self.mode {
837 886
            Mode::Hunk(view) => {
838 887
                let mut comments = self.commits[current]
839 888
                    .loaded
840 889
                    .as_ref()
841 -
                    .map_or_else(Vec::new, |loaded| loaded.comments.for_hunk(view.hunk).to_vec());
890 +
                    .map_or_else(Vec::new, |loaded| {
891 +
                        loaded.comments.for_hunk(view.hunk).to_vec()
892 +
                    });
842 893
                self.terminal.draw(|frame| {
843 894
                    let (body, footer_area) = Status::areas(frame.area);
844 895
                    frame.render_stateful_widget(&mut **view, body, &mut comments);
845 896
                    frame.render_widget(&mut footer, footer_area);
846 897
                })?;
crates/brain/src/session/hunk.rs +2 -5
265 265
                    &comment_age(comment),
266 266
                    editor_body_rows,
267 267
                    cols,
268 268
                ));
269 269
            } else if stored_rows < MAX_COMMENT_ROWS {
270 -
                let card = comment_card_lines(
271 -
                    comment,
272 -
                    !self.is_editing() && index == selected,
273 -
                    cols,
274 -
                );
270 +
                let card =
271 +
                    comment_card_lines(comment, !self.is_editing() && index == selected, cols);
275 272
                let take = card.len().min(MAX_COMMENT_ROWS - stored_rows);
276 273
                stored_rows += take;
277 274
                lines.extend(card.into_iter().take(take));
278 275
            }
279 276
        }
a.txt +0 -0
crates/diff/src/viewer.rs +4 -3
1967 1967
        } else {
1968 1968
            let fg = match self.header.kind {
1969 1969
                FileKind::Added => palette.positive_fg,
1970 1970
                FileKind::Deleted => palette.negative_fg,
1971 1971
                FileKind::Renamed => FILE_KIND_BADGE_FG,
1972 -
                FileKind::Modified | FileKind::Copied | FileKind::ModeChanged | FileKind::Binary => {
1973 -
                    Color::Yellow
1974 -
                }
1972 +
                FileKind::Modified
1973 +
                | FileKind::Copied
1974 +
                | FileKind::ModeChanged
1975 +
                | FileKind::Binary => Color::Yellow,
1975 1976
            };
1976 1977
            left.push(Label::from_char(self.header.kind.marker()).fg(fg));
1977 1978
        }
1978 1979
        left.push(Label::space());
1979 1980
        left = left.extend(self.path_line());
a.rs +0 -0
a.rs +0 -0
b.rs +0 -0
a.rs +0 -0
a.rs +0 -0
a.rs +0 -0
b.rs +0 -0
crates/diff/tests/golden/sticky_header_before_next_file_64x5.txt +0 -0
src/a.rs +0 -0
src/b.rs +0 -0
README.md +0 -0
src/app/a.rs +0 -0
src/lib/b.rs +0 -0
README.md +0 -0
a.rs +0 -0
b.rs +0 -0
assets/css/style.css +0 -0
assets/css/style.css +0 -0
first.rs +0 -0
second.rs +0 -0
a.rs +0 -0
a.rs +0 -0
a.rs +0 -0
a.rs +0 -0
b.rs +0 -0
crates/tui-termion/src/term.rs +6 -3
92 92
/// Returns typed events from the terminal.
93 93
pub fn events() -> impl Iterator<Item = io::Result<Event<()>>> {
94 94
    event_receiver().into_iter()
95 95
}
96 96
97 -
/// Returns typed events from the terminal device.
98 -
fn terminal_events() -> io::Result<impl Iterator<Item = io::Result<Event<()>>>> {
97 +
/// Returns typed input events from the terminal device.
98 +
///
99 +
/// This stream does not install signal handlers or synthesize resize events.
100 +
/// Use [`events`] for a full application event stream.
101 +
fn input_events() -> io::Result<impl Iterator<Item = io::Result<Event<()>>>> {
99 102
    let terminal = File::open(TTY_DEVICE)
100 103
        .or_else(|_| File::open(STDOUT_DEVICE))
101 104
        .or_else(|_| File::open(STDERR_DEVICE))?;
102 105
103 106
    Ok(terminal
195 198
    let (tx, rx) = mpsc::channel();
196 199
197 200
    // Spawns a blocking terminal event reader.
198 201
    thread::spawn({
199 202
        let tx = tx.clone();
200 -
        move || match terminal_events() {
203 +
        move || match input_events() {
201 204
            Ok(events) => {
202 205
                for event in events {
203 206
                    if tx.send(event).is_err() {
204 207
                        break;
205 208
                    }
crates/tui-widgets/src/dialog.rs added +409 -0
1 +
//! Modal dialog widget.
2 +
3 +
use crate::{ActionBar, ActionList, overlay_area};
4 +
use rustik_tui_core as tui_core;
5 +
use tui_core::{
6 +
    Border, BorderChars, Buffer, Cell, Color, Constraint, Line, Rect, Size, Style, Widget, colors,
7 +
};
8 +
9 +
/// Default maximum dialog panel size.
10 +
pub const DEFAULT_DIALOG_MAX_SIZE: Size = Size::new(72, 12);
11 +
/// Default minimum margin around a dialog panel.
12 +
pub const DEFAULT_DIALOG_MARGIN: Size = Size::new(2, 1);
13 +
14 +
/// Horizontal padding inside the dialog frame.
15 +
const DIALOG_PADDING: usize = 1;
16 +
/// Square border glyphs used by modal dialogs.
17 +
const DIALOG_BORDER_CHARS: BorderChars = BorderChars {
18 +
    top_left: 'โ”Œ',
19 +
    top_right: 'โ”',
20 +
    bottom_left: 'โ””',
21 +
    bottom_right: 'โ”˜',
22 +
    vertical: 'โ”‚',
23 +
    horizontal: 'โ”€',
24 +
    divider_left: 'โ”œ',
25 +
    divider_right: 'โ”ค',
26 +
};
27 +
28 +
/// Visual treatment for a dialog.
29 +
#[derive(Debug, Clone, Copy, Default, Eq, PartialEq)]
30 +
pub enum DialogKind {
31 +
    /// Neutral dialog.
32 +
    #[default]
33 +
    Normal,
34 +
    /// Error dialog with negative chrome.
35 +
    Error,
36 +
}
37 +
38 +
impl DialogKind {
39 +
    /// Returns the foreground color used for dialog chrome.
40 +
    fn color(self) -> Color {
41 +
        match self {
42 +
            Self::Normal => colors::FAINT,
43 +
            Self::Error => colors::rgb::NEGATIVE_LIGHT,
44 +
        }
45 +
    }
46 +
47 +
    /// Returns the border used by the dialog.
48 +
    fn border(self) -> Border {
49 +
        Border {
50 +
            style: Style::new(self.color()),
51 +
            chars: DIALOG_BORDER_CHARS,
52 +
        }
53 +
    }
54 +
55 +
    /// Returns the heading style.
56 +
    fn heading_style(self) -> Style {
57 +
        match self {
58 +
            Self::Normal => Style::default(),
59 +
            Self::Error => Style::new(self.color()).bold(),
60 +
        }
61 +
    }
62 +
63 +
    /// Returns an action bar for this dialog kind.
64 +
    fn action_bar(self, actions: ActionList) -> ActionBar {
65 +
        ActionBar::new(actions)
66 +
            .cap_style(Style::new(self.key_background()))
67 +
            .key_style(self.key_style())
68 +
            .action_style(self.action_style())
69 +
    }
70 +
71 +
    /// Returns the background color used for shortcut pills.
72 +
    fn key_background(self) -> Color {
73 +
        match self {
74 +
            Self::Normal => self.color(),
75 +
            Self::Error => Color::Fixed(250),
76 +
        }
77 +
    }
78 +
79 +
    /// Returns the style used for action key text.
80 +
    fn key_style(self) -> Style {
81 +
        match self {
82 +
            Self::Normal => Style::new(Color::White).bg(self.color()).bold(),
83 +
            Self::Error => Style::new(Color::Black).bg(self.key_background()).bold(),
84 +
        }
85 +
    }
86 +
87 +
    /// Returns the style used for action labels.
88 +
    fn action_style(self) -> Style {
89 +
        match self {
90 +
            Self::Normal => Style::new(colors::fixed::DIM),
91 +
            Self::Error => Style::new(Color::Fixed(244)),
92 +
        }
93 +
    }
94 +
}
95 +
96 +
/// Centered modal dialog with body text and an optional action bar.
97 +
#[derive(Debug, Clone)]
98 +
pub struct Dialog {
99 +
    /// Dialog heading shown as the first content row.
100 +
    heading: Line,
101 +
    /// Dialog visual treatment.
102 +
    kind: DialogKind,
103 +
    /// Body lines rendered above the actions.
104 +
    body: Vec<Line>,
105 +
    /// Action metadata rendered as key hints.
106 +
    actions: ActionList,
107 +
    /// Cell used to clear the dialog panel.
108 +
    background: Cell,
109 +
    /// Largest panel size.
110 +
    max_size: Size,
111 +
    /// Minimum parent-space margin kept around the panel.
112 +
    margin: Size,
113 +
}
114 +
115 +
impl Dialog {
116 +
    /// Creates an empty dialog with `heading`.
117 +
    pub fn new(heading: impl Into<Line>) -> Self {
118 +
        Self {
119 +
            heading: heading.into(),
120 +
            kind: DialogKind::Normal,
121 +
            body: Vec::new(),
122 +
            actions: ActionList::new(),
123 +
            background: Cell::blank(),
124 +
            max_size: DEFAULT_DIALOG_MAX_SIZE,
125 +
            margin: DEFAULT_DIALOG_MARGIN,
126 +
        }
127 +
    }
128 +
129 +
    /// Creates an error dialog.
130 +
    pub fn error() -> Self {
131 +
        Self::new("ERROR").kind(DialogKind::Error)
132 +
    }
133 +
134 +
    /// Sets the dialog visual treatment.
135 +
    pub const fn kind(mut self, kind: DialogKind) -> Self {
136 +
        self.kind = kind;
137 +
        self
138 +
    }
139 +
140 +
    /// Sets the body lines.
141 +
    pub fn body(mut self, body: impl IntoIterator<Item = Line>) -> Self {
142 +
        self.body = body.into_iter().collect();
143 +
        self
144 +
    }
145 +
146 +
    /// Adds one body line.
147 +
    pub fn body_line(mut self, line: impl Into<Line>) -> Self {
148 +
        self.body.push(line.into());
149 +
        self
150 +
    }
151 +
152 +
    /// Sets the action list.
153 +
    pub fn actions(mut self, actions: ActionList) -> Self {
154 +
        self.actions = actions;
155 +
        self
156 +
    }
157 +
158 +
    /// Sets the cell used to clear the dialog panel.
159 +
    pub fn background(mut self, cell: Cell) -> Self {
160 +
        self.background = cell;
161 +
        self
162 +
    }
163 +
164 +
    /// Sets the largest panel size.
165 +
    pub const fn max_size(mut self, size: Size) -> Self {
166 +
        self.max_size = size;
167 +
        self
168 +
    }
169 +
170 +
    /// Sets the minimum parent-space margin around the panel.
171 +
    pub const fn margin(mut self, margin: Size) -> Self {
172 +
        self.margin = margin;
173 +
        self
174 +
    }
175 +
176 +
    /// Returns the largest panel size available inside `area`.
177 +
    fn available_max(&self, area: Rect) -> Size {
178 +
        Size::new(
179 +
            self.max_size
180 +
                .cols
181 +
                .min(area.cols.saturating_sub(self.margin.cols.saturating_mul(2))),
182 +
            self.max_size
183 +
                .rows
184 +
                .min(area.rows.saturating_sub(self.margin.rows.saturating_mul(2))),
185 +
        )
186 +
    }
187 +
188 +
    /// Returns the dialog size under `max`.
189 +
    fn panel_size(&self, max: Size) -> Size {
190 +
        let action = self.action_line();
191 +
        let body_width = self.body.iter().map(Line::width).max().unwrap_or_default();
192 +
        let content_width = self.heading.width().max(body_width).max(action.width());
193 +
        let content_rows = 1
194 +
            + usize::from(!self.body.is_empty() || !self.actions.items().is_empty())
195 +
            + self.body.len()
196 +
            + if self.actions.items().is_empty() {
197 +
                0
198 +
            } else {
199 +
                2
200 +
            };
201 +
        let size = Size::new(
202 +
            content_width
203 +
                .saturating_add(DIALOG_PADDING.saturating_mul(2))
204 +
                .saturating_add(2),
205 +
            content_rows.saturating_add(2),
206 +
        );
207 +
        let min = Size::new(2.min(max.cols), 2.min(max.rows));
208 +
209 +
        size.constrain(Constraint::new(min, max))
210 +
    }
211 +
212 +
    /// Returns the rendered action line.
213 +
    fn action_line(&self) -> Line {
214 +
        self.kind.action_bar(self.actions.clone()).line()
215 +
    }
216 +
217 +
    /// Renders the dialog heading.
218 +
    fn render_heading(&self, area: Rect, buf: &mut Buffer) {
219 +
        let heading = self.heading.clone().style(self.kind.heading_style());
220 +
        Line::renders([heading], area, buf);
221 +
    }
222 +
223 +
    /// Renders dialog body lines without entering the reserved action rows.
224 +
    fn render_body(&self, area: Rect, buf: &mut Buffer) {
225 +
        Line::renders(self.body.iter().take(area.rows).cloned(), area, buf);
226 +
    }
227 +
228 +
    /// Renders the action row at the bottom of the dialog.
229 +
    fn render_actions(&self, area: Rect, buf: &mut Buffer) {
230 +
        if self.actions.items().is_empty() {
231 +
            return;
232 +
        }
233 +
        Line::renders([self.action_line()], area, buf);
234 +
    }
235 +
}
236 +
237 +
impl Widget for Dialog {
238 +
    fn size(&self, parent: Constraint) -> Size {
239 +
        parent.bounded_size()
240 +
    }
241 +
242 +
    fn render(&mut self, area: Rect, buf: &mut Buffer) {
243 +
        let max = self.available_max(area);
244 +
        let size = self.panel_size(max);
245 +
        let area = overlay_area(area, size, self.margin);
246 +
247 +
        if area.is_empty() {
248 +
            return;
249 +
        }
250 +
251 +
        buf.fill(area, self.background.clone());
252 +
        self.kind.border().draw(area, buf);
253 +
254 +
        let content = area.inner(1);
255 +
        let content_cols = content
256 +
            .cols
257 +
            .saturating_sub(DIALOG_PADDING.saturating_mul(2));
258 +
        let content_x = content.x + DIALOG_PADDING.min(content.cols);
259 +
        let heading_area = Rect::new(content_x, content.y, content_cols, 1);
260 +
        self.render_heading(heading_area, buf);
261 +
262 +
        let action_area = if self.actions.items().is_empty() || content.rows < 2 {
263 +
            Rect::ZERO
264 +
        } else {
265 +
            Rect::new(
266 +
                content_x,
267 +
                content.bottom().saturating_sub(1),
268 +
                content_cols,
269 +
                1,
270 +
            )
271 +
        };
272 +
        let body_y = content.y.saturating_add(2);
273 +
        let body_bottom = if action_area.is_empty() {
274 +
            content.bottom()
275 +
        } else {
276 +
            action_area.y.saturating_sub(1)
277 +
        };
278 +
        let body_area = Rect::new(
279 +
            content_x,
280 +
            body_y,
281 +
            content_cols,
282 +
            body_bottom.saturating_sub(body_y),
283 +
        );
284 +
285 +
        self.render_body(body_area, buf);
286 +
        self.render_actions(action_area, buf);
287 +
    }
288 +
}
289 +
290 +
#[cfg(test)]
291 +
mod tests {
292 +
    use super::*;
293 +
    use tui_core::{Buffer, Rect};
294 +
295 +
    #[test]
296 +
    fn error_dialog_uses_negative_chrome() {
297 +
        let mut dialog = Dialog::error()
298 +
            .body_line("State mismatch")
299 +
            .max_size(Size::new(24, 6))
300 +
            .margin(Size::MIN);
301 +
        let mut buffer = Buffer::empty(Rect::new(0, 0, 28, 7));
302 +
303 +
        dialog.render(buffer.area(), &mut buffer);
304 +
305 +
        assert!(first_position_with_foreground(&buffer, colors::rgb::NEGATIVE_LIGHT).is_some());
306 +
    }
307 +
308 +
    #[test]
309 +
    fn dialog_keeps_actions_visible_when_body_is_taller_than_panel() {
310 +
        let body = [
311 +
            Line::new("one"),
312 +
            Line::new("two"),
313 +
            Line::new("three"),
314 +
            Line::new("four"),
315 +
            Line::new("five"),
316 +
        ];
317 +
        let mut dialog = Dialog::error()
318 +
            .body(body)
319 +
            .actions(ActionList::new().action("r", "reset").action("q", "quit"))
320 +
            .max_size(Size::new(30, 7))
321 +
            .margin(Size::MIN);
322 +
        let mut buffer = Buffer::empty(Rect::new(0, 0, 34, 9));
323 +
324 +
        dialog.render(buffer.area(), &mut buffer);
325 +
326 +
        assert!(first_position_with_background(&buffer, Color::Fixed(250)).is_some());
327 +
    }
328 +
329 +
    #[test]
330 +
    fn tiny_dialog_drops_actions_instead_of_overwriting_the_heading() {
331 +
        let mut dialog = Dialog::error()
332 +
            .actions(ActionList::new().action("q", "quit"))
333 +
            .max_size(Size::new(24, 3))
334 +
            .margin(Size::MIN);
335 +
        let mut buffer = Buffer::empty(Rect::new(0, 0, 28, 3));
336 +
337 +
        dialog.render(buffer.area(), &mut buffer);
338 +
339 +
        assert!(first_position_with_background(&buffer, Color::Fixed(250)).is_none());
340 +
    }
341 +
342 +
    #[test]
343 +
    fn error_dialog_actions_use_grey_pills_black_keys_and_lighter_labels() {
344 +
        let mut dialog = Dialog::error()
345 +
            .actions(ActionList::new().action("r", "reset"))
346 +
            .max_size(Size::new(24, 5))
347 +
            .margin(Size::MIN);
348 +
        let mut buffer = Buffer::empty(Rect::new(0, 0, 28, 7));
349 +
350 +
        dialog.render(buffer.area(), &mut buffer);
351 +
352 +
        let key = first_foreground_with_background(&buffer, Color::Fixed(250));
353 +
        let label = first_position_with_foreground(&buffer, Color::Fixed(244));
354 +
355 +
        assert_eq!(key, Some(Color::Black));
356 +
        assert!(label.is_some());
357 +
    }
358 +
359 +
    /// Returns the first position whose foreground color is `foreground`.
360 +
    fn first_position_with_foreground(
361 +
        buffer: &Buffer,
362 +
        foreground: Color,
363 +
    ) -> Option<(usize, usize)> {
364 +
        for y in 0..buffer.area().rows {
365 +
            for x in 0..buffer.area().cols {
366 +
                let Some(cell) = buffer.get(x, y) else {
367 +
                    continue;
368 +
                };
369 +
                if cell.style().fg_color() == foreground {
370 +
                    return Some((x, y));
371 +
                }
372 +
            }
373 +
        }
374 +
        None
375 +
    }
376 +
377 +
    /// Returns the first position whose background color is `background`.
378 +
    fn first_position_with_background(
379 +
        buffer: &Buffer,
380 +
        background: Color,
381 +
    ) -> Option<(usize, usize)> {
382 +
        for y in 0..buffer.area().rows {
383 +
            for x in 0..buffer.area().cols {
384 +
                let Some(cell) = buffer.get(x, y) else {
385 +
                    continue;
386 +
                };
387 +
                if cell.style().bg_color() == background {
388 +
                    return Some((x, y));
389 +
                }
390 +
            }
391 +
        }
392 +
        None
393 +
    }
394 +
395 +
    /// Returns the foreground color of the first cell with `background`.
396 +
    fn first_foreground_with_background(buffer: &Buffer, background: Color) -> Option<Color> {
397 +
        for y in 0..buffer.area().rows {
398 +
            for x in 0..buffer.area().cols {
399 +
                let Some(cell) = buffer.get(x, y) else {
400 +
                    continue;
401 +
                };
402 +
                if cell.style().bg_color() == background {
403 +
                    return Some(cell.style().fg_color());
404 +
                }
405 +
            }
406 +
        }
407 +
        None
408 +
    }
409 +
}
crates/tui-widgets/src/lib.rs +3 -0
12 12
13 13
/// One-line action hint bar.
14 14
pub mod action_bar;
15 15
/// Compact text badge widget.
16 16
pub mod badge;
17 +
/// Centered modal dialog widget.
18 +
pub mod dialog;
17 19
/// Editable text input widget.
18 20
pub mod input;
19 21
/// Selectable list widget.
20 22
pub mod list;
21 23
/// Centered overlay widget.
31 33
/// Scroll viewport primitives.
32 34
pub mod viewport;
33 35
34 36
pub use action_bar::{ActionBar, ActionItem, ActionList};
35 37
pub use badge::Badge;
38 +
pub use dialog::{DEFAULT_DIALOG_MARGIN, DEFAULT_DIALOG_MAX_SIZE, Dialog, DialogKind};
36 39
pub use input::{TextField, TextInput};
37 40
pub use list::{List, ListState, Selection};
38 41
pub use overlay::{Overlay, overlay_area};
39 42
pub use panel::Panel;
40 43
pub use scrollbar::{Scrollbar, ScrollbarStyle};