Skip to main content

vtcode_tui/core_tui/session/render/
modal_renderer.rs

1use super::*;
2use crate::config::constants::ui;
3use crate::core_tui::types::InlineMessageKind;
4use crate::ui::tui::session::modal::{
5    ModalBodyContext, ModalListState, ModalRenderStyles, render_modal_body,
6    render_wizard_modal_body,
7};
8use crate::ui::tui::types::InlineListSelection;
9use ratatui::widgets::{Clear, Paragraph, Wrap};
10
11const MAX_INLINE_MODAL_HEIGHT: u16 = 20;
12const MAX_INLINE_MODAL_HEIGHT_MULTILINE: u16 = 32;
13const MAX_INLINE_INSTRUCTION_ROWS: usize = 6;
14
15fn list_has_two_line_items(list: &ModalListState) -> bool {
16    list.visible_indices.iter().any(|&index| {
17        list.items.get(index).is_some_and(|item| {
18            item.subtitle
19                .as_ref()
20                .is_some_and(|subtitle| !subtitle.trim().is_empty())
21        })
22    })
23}
24
25fn list_row_cap(list: &ModalListState) -> usize {
26    if list_has_two_line_items(list) {
27        ui::INLINE_LIST_MAX_ROWS_MULTILINE
28    } else {
29        ui::INLINE_LIST_MAX_ROWS
30    }
31}
32
33fn list_desired_rows(list: &ModalListState) -> usize {
34    list.visible_indices.len().clamp(1, list_row_cap(list))
35}
36
37fn modal_title_text(session: &Session) -> &str {
38    session
39        .wizard_overlay()
40        .map(|wizard| wizard.title.as_str())
41        .or_else(|| session.modal_state().map(|modal| modal.title.as_str()))
42        .unwrap_or("")
43}
44
45fn modal_has_title(session: &Session) -> bool {
46    !modal_title_text(session).trim().is_empty()
47}
48
49fn wizard_step_has_inline_custom_editor(
50    wizard: &crate::ui::tui::session::modal::WizardModalState,
51) -> bool {
52    let Some(step) = wizard.steps.get(wizard.current_step) else {
53        return false;
54    };
55    let Some(selected_visible) = step.list.list_state.selected() else {
56        return false;
57    };
58    let Some(&item_index) = step.list.visible_indices.get(selected_visible) else {
59        return false;
60    };
61    let Some(item) = step.list.items.get(item_index) else {
62        return false;
63    };
64    matches!(
65        item.selection.as_ref(),
66        Some(InlineListSelection::RequestUserInputAnswer {
67            selected,
68            other,
69            ..
70        }) if selected.is_empty() && other.is_some()
71    )
72}
73
74pub fn split_inline_modal_area(session: &Session, area: Rect) -> (Rect, Option<Rect>) {
75    if area.width == 0 || area.height == 0 {
76        return (area, None);
77    }
78
79    let multiline_list_present = if let Some(wizard) = session.wizard_overlay() {
80        wizard
81            .steps
82            .get(wizard.current_step)
83            .is_some_and(|step| list_has_two_line_items(&step.list))
84    } else if let Some(modal) = session.modal_state() {
85        modal.list.as_ref().is_some_and(list_has_two_line_items)
86    } else {
87        false
88    };
89
90    let desired_lines = if let Some(wizard) = session.wizard_overlay() {
91        let mut lines = 0usize;
92        lines = lines.saturating_add(1); // tabs/header
93        if wizard.search.is_some() {
94            lines = lines.saturating_add(1);
95        }
96        lines = lines.saturating_add(2); // question and spacing
97        let (list_rows, summary_rows) = wizard
98            .steps
99            .get(wizard.current_step)
100            .map(|step| {
101                (
102                    list_desired_rows(&step.list),
103                    step.list.summary_line_rows(None),
104                )
105            })
106            .unwrap_or((1, 0));
107        lines = lines.saturating_add(list_rows);
108        lines = lines.saturating_add(summary_rows);
109        if wizard
110            .steps
111            .get(wizard.current_step)
112            .is_some_and(|step| step.notes_active || !step.notes.is_empty())
113            && !wizard_step_has_inline_custom_editor(wizard)
114        {
115            lines = lines.saturating_add(1);
116        }
117        lines = lines.saturating_add(
118            wizard
119                .instruction_lines()
120                .len()
121                .min(MAX_INLINE_INSTRUCTION_ROWS),
122        );
123        if modal_has_title(session) {
124            lines = lines.saturating_add(1); // title row
125        }
126        lines
127    } else if let Some(modal) = session.modal_state() {
128        let mut lines = modal.lines.len().clamp(1, MAX_INLINE_INSTRUCTION_ROWS);
129        if modal.search.is_some() {
130            lines = lines.saturating_add(1);
131        }
132        if modal.secure_prompt.is_some() {
133            lines = lines.saturating_add(2);
134        }
135        if let Some(list) = modal.list.as_ref() {
136            lines = lines.saturating_add(list_desired_rows(list));
137            lines = lines.saturating_add(list.summary_line_rows(modal.footer_hint.as_deref()));
138        } else {
139            lines = lines.saturating_add(1);
140        }
141        if modal_has_title(session) {
142            lines = lines.saturating_add(1); // title row
143        }
144        lines
145    } else {
146        return (area, None);
147    };
148
149    let max_panel_height = area.height.saturating_sub(1);
150    if max_panel_height == 0 {
151        return (area, None);
152    }
153
154    let min_height = ui::MODAL_MIN_HEIGHT.min(max_panel_height).max(1);
155    let modal_height_cap = if multiline_list_present {
156        MAX_INLINE_MODAL_HEIGHT_MULTILINE
157    } else {
158        MAX_INLINE_MODAL_HEIGHT
159    };
160    let capped_max = modal_height_cap.min(max_panel_height).max(min_height);
161    let desired_height = (desired_lines.min(u16::MAX as usize) as u16)
162        .max(min_height)
163        .min(capped_max);
164
165    let chunks =
166        Layout::vertical([Constraint::Min(1), Constraint::Length(desired_height)]).split(area);
167    (chunks[0], Some(chunks[1]))
168}
169
170pub(crate) fn floating_modal_area(area: Rect) -> Rect {
171    if area.width == 0 || area.height == 0 {
172        return area;
173    }
174
175    let height = (area.height / 2).max(1);
176    let y = area.y.saturating_add(area.height.saturating_sub(height));
177    Rect::new(area.x, y, area.width, height)
178}
179
180pub fn render_modal(session: &mut Session, frame: &mut Frame<'_>, area: Rect) {
181    if area.width == 0 || area.height == 0 {
182        session.set_modal_list_area(None);
183        return;
184    }
185
186    // Auto-approve modals when skip_confirmations is set (for tests and headless mode)
187    if session.skip_confirmations
188        && let Some(mut modal) = session.take_modal_state()
189    {
190        if let Some(list) = &mut modal.list
191            && let Some(_selection) = list.current_selection()
192        {
193            // Note: We can't easily emit an event from here without access to the sender.
194            // Instead, we just clear the modal and assume the tool execution logic
195            // or whatever triggered the modal will check skip_confirmations as well.
196            // This is handled in ensure_tool_permission.
197        }
198        session.input_enabled = modal.restore_input;
199        session.cursor_visible = modal.restore_cursor;
200        session.needs_full_clear = true;
201        session.needs_redraw = true;
202        session.set_modal_list_area(None);
203        return;
204    }
205
206    let styles = modal_render_styles(session);
207    let title = modal_title_text(session).trim().to_owned();
208    let body_area = if title.is_empty() {
209        area
210    } else {
211        let chunks = Layout::vertical([Constraint::Length(1), Constraint::Min(0)]).split(area);
212        let title_area = chunks[0];
213        frame.render_widget(Clear, title_area);
214        frame.render_widget(
215            Paragraph::new(Line::from(Span::styled(title, styles.title))).wrap(Wrap { trim: true }),
216            title_area,
217        );
218        chunks[1]
219    };
220
221    if let Some(wizard) = session.wizard_overlay_mut() {
222        frame.render_widget(Clear, body_area);
223        if body_area.width == 0 || body_area.height == 0 {
224            session.set_modal_list_area(None);
225            return;
226        }
227        let list_area = render_wizard_modal_body(frame, body_area, wizard, &styles);
228        session.set_modal_list_area(list_area);
229        return;
230    }
231
232    let input = session.input_manager.content().to_owned();
233    let cursor = session.input_manager.cursor();
234    let Some(modal) = session.modal_state_mut() else {
235        session.set_modal_list_area(None);
236        return;
237    };
238
239    frame.render_widget(Clear, body_area);
240    if body_area.width == 0 || body_area.height == 0 {
241        session.set_modal_list_area(None);
242        return;
243    }
244    let list_area = render_modal_body(
245        frame,
246        body_area,
247        ModalBodyContext {
248            instructions: &modal.lines,
249            footer_hint: modal.footer_hint.as_deref(),
250            list: modal.list.as_mut(),
251            styles: &styles,
252            secure_prompt: modal.secure_prompt.as_ref(),
253            search: modal.search.as_ref(),
254            input: &input,
255            cursor,
256        },
257    );
258    session.set_modal_list_area(list_area);
259}
260
261pub(crate) fn modal_render_styles(session: &Session) -> ModalRenderStyles {
262    let default_style = session.styles.default_style();
263    let accent_style = session.styles.accent_style();
264    let border_style = session.styles.border_style();
265    ModalRenderStyles {
266        border: border_style,
267        highlight: modal_list_highlight_style(session),
268        badge: border_style.add_modifier(Modifier::DIM | Modifier::BOLD),
269        header: accent_style.add_modifier(Modifier::BOLD),
270        selectable: default_style,
271        detail: default_style.add_modifier(Modifier::DIM),
272        search_match: accent_style.add_modifier(Modifier::BOLD | Modifier::UNDERLINED),
273        title: accent_style.add_modifier(Modifier::BOLD),
274        divider: default_style.add_modifier(Modifier::DIM | Modifier::ITALIC),
275        instruction_border: border_style,
276        instruction_title: session.section_title_style(),
277        instruction_bullet: accent_style.add_modifier(Modifier::BOLD),
278        instruction_body: default_style,
279        hint: default_style.add_modifier(Modifier::DIM | Modifier::ITALIC),
280    }
281}
282
283#[allow(dead_code)]
284pub(super) fn handle_tool_code_fence_marker(session: &mut Session, text: &str) -> bool {
285    let trimmed = text.trim();
286    let stripped = trimmed
287        .strip_prefix("```")
288        .or_else(|| trimmed.strip_prefix("~~~"));
289
290    let Some(rest) = stripped else {
291        return false;
292    };
293
294    if rest.contains("```") || rest.contains("~~~") {
295        return false;
296    }
297
298    if session.in_tool_code_fence {
299        session.in_tool_code_fence = false;
300        remove_trailing_empty_tool_line(session);
301    } else {
302        session.in_tool_code_fence = true;
303    }
304
305    true
306}
307
308#[allow(dead_code)]
309fn remove_trailing_empty_tool_line(session: &mut Session) {
310    let should_remove = session
311        .lines
312        .last()
313        .map(|line| line.kind == InlineMessageKind::Tool && line.segments.is_empty())
314        .unwrap_or(false);
315    if should_remove {
316        session.lines.pop();
317        session.invalidate_scroll_metrics();
318    }
319}
320
321#[cfg(test)]
322mod tests {
323    use super::*;
324    use crate::ui::tui::InlineTheme;
325
326    #[test]
327    fn modal_title_text_uses_modal_title_and_empty_default() {
328        let mut session = Session::new(InlineTheme::default(), None, 20);
329        assert_eq!(modal_title_text(&session), "");
330
331        session.show_modal("Config".to_owned(), vec![], None);
332        assert_eq!(modal_title_text(&session), "Config");
333    }
334
335    #[test]
336    fn modal_title_style_is_accent_and_bold() {
337        let session = Session::new(InlineTheme::default(), None, 20);
338        let styles = modal_render_styles(&session);
339
340        assert_eq!(
341            styles.title,
342            session.styles.accent_style().add_modifier(Modifier::BOLD)
343        );
344    }
345
346    #[test]
347    fn floating_modal_area_uses_bottom_half_of_viewport() {
348        let area = floating_modal_area(Rect::new(3, 5, 80, 31));
349
350        assert_eq!(area, Rect::new(3, 21, 80, 15));
351    }
352
353    #[test]
354    fn floating_modal_area_uses_exact_half_for_even_height() {
355        let area = floating_modal_area(Rect::new(0, 0, 80, 30));
356
357        assert_eq!(area, Rect::new(0, 15, 80, 15));
358    }
359
360    #[test]
361    fn floating_modal_area_preserves_single_row_viewport() {
362        let area = floating_modal_area(Rect::new(0, 0, 80, 1));
363
364        assert_eq!(area, Rect::new(0, 0, 80, 1));
365    }
366}