返回 CodeWhale
feedback_picker.rs
根目录 / crates / tui / src / tui / feedback_picker.rs
1 //! `/feedback` picker for GitHub feedback destinations.
2
3 use std::cell::RefCell;
4
5 use crossterm::event::{KeyCode, KeyEvent, KeyModifiers, MouseButton, MouseEvent, MouseEventKind};
6 use ratatui::{
7 buffer::Buffer,
8 layout::Rect,
9 style::{Modifier, Style},
10 text::{Line, Span},
11 widgets::{Paragraph, Widget},
12 };
13
14 use crate::tui::views::rounded::{pad_selected_line, render_rounded_footer, render_rounded_modal};
15 use crate::tui::views::{
16 ActionHint, CommandPaletteAction, ModalKind, ModalView, ViewAction, ViewEvent,
17 centered_modal_area,
18 };
19 use codewhale_palette as palette;
20 use codewhale_tui_kit::menu_style;
21 use unicode_width::UnicodeWidthStr;
22
23 #[derive(Debug, Clone, Copy)]
24 struct FeedbackOption {
25 number: char,
26 label: &'static str,
27 description: &'static str,
28 command: &'static str,
29 }
30
31 const OPTIONS: &[FeedbackOption] = &[
32 FeedbackOption {
33 number: '1',
34 label: "Bug report",
35 description: "Report a problem or regression",
36 command: "/feedback bug",
37 },
38 FeedbackOption {
39 number: '2',
40 label: "Feature request",
41 description: "Suggest an idea or improvement",
42 command: "/feedback feature",
43 },
44 FeedbackOption {
45 number: '3',
46 label: "Security vulnerability",
47 description: "Review the security policy before reporting",
48 command: "/feedback security",
49 },
50 ];
51
52 pub struct FeedbackPickerView {
53 selected: usize,
54 /// Screen row of each option row, recorded as it is painted. Keyboard and
55 /// mouse must reach the same rows; without this the view inherits the
56 /// no-op `handle_mouse` and silently swallows every click.
57 row_hitboxes: RefCell<Vec<Rect>>,
58 }
59
60 impl FeedbackPickerView {
61 #[must_use]
62 pub fn new() -> Self {
63 Self {
64 selected: 0,
65 row_hitboxes: RefCell::new(Vec::new()),
66 }
67 }
68
69 fn move_up(&mut self) {
70 self.selected = codewhale_tui_kit::list_nav::wrap_index(self.selected, OPTIONS.len(), -1);
71 }
72
73 fn move_down(&mut self) {
74 self.selected = codewhale_tui_kit::list_nav::wrap_index(self.selected, OPTIONS.len(), 1);
75 }
76
77 fn select_number(&mut self, number: char) -> Option<ViewAction> {
78 let idx = OPTIONS.iter().position(|option| option.number == number)?;
79 self.selected = idx;
80 Some(self.selected_action())
81 }
82
83 fn selected_action(&self) -> ViewAction {
84 let command = OPTIONS
85 .get(self.selected)
86 .map(|option| option.command)
87 .unwrap_or(OPTIONS[0].command)
88 .to_string();
89 ViewAction::EmitAndClose(ViewEvent::CommandPaletteSelected {
90 action: CommandPaletteAction::ExecuteCommand { command },
91 })
92 }
93 }
94
95 impl Default for FeedbackPickerView {
96 fn default() -> Self {
97 Self::new()
98 }
99 }
100
101 impl ModalView for FeedbackPickerView {
102 fn kind(&self) -> ModalKind {
103 ModalKind::FeedbackPicker
104 }
105
106 fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
107 self
108 }
109
110 fn handle_key(&mut self, key: KeyEvent) -> ViewAction {
111 match key.code {
112 KeyCode::Esc => ViewAction::Close,
113 KeyCode::Enter => self.selected_action(),
114 KeyCode::Up | KeyCode::Char('k') => {
115 self.move_up();
116 ViewAction::None
117 }
118 KeyCode::Down | KeyCode::Char('j') => {
119 self.move_down();
120 ViewAction::None
121 }
122 KeyCode::Char(number)
123 if !key.modifiers.contains(KeyModifiers::CONTROL)
124 && OPTIONS.iter().any(|option| option.number == number) =>
125 {
126 self.select_number(number).unwrap_or(ViewAction::None)
127 }
128 _ => ViewAction::None,
129 }
130 }
131
132 fn render(&self, area: Rect, buf: &mut Buffer) {
133 let popup_area = centered_modal_area(area, 78, (OPTIONS.len() as u16) + 7, 44, 8);
134 let inner = render_rounded_modal(
135 area,
136 popup_area,
137 buf,
138 "Feedback",
139 Some("1-3".to_string()),
140 true,
141 );
142
143 let content = render_rounded_footer(
144 inner,
145 buf,
146 &[
147 ActionHint::new("↑/↓", "move"),
148 ActionHint::new("Enter", "open"),
149 ActionHint::new("Esc", "cancel"),
150 ],
151 );
152
153 let mut lines = Vec::with_capacity(OPTIONS.len() + 2);
154 lines.push(Line::from(""));
155 let mut hitboxes = self.row_hitboxes.borrow_mut();
156 hitboxes.clear();
157
158 let label_col = OPTIONS
159 .iter()
160 .map(|o| UnicodeWidthStr::width(o.label))
161 .max()
162 .unwrap_or(0);
163 let row_width = usize::from(content.width);
164
165 for (idx, option) in OPTIONS.iter().enumerate() {
166 let row = content
167 .y
168 .saturating_add(u16::try_from(idx).unwrap_or(u16::MAX))
169 + 1;
170 if row < content.bottom() {
171 hitboxes.push(Rect::new(content.x, row, content.width, 1));
172 }
173 let is_selected = idx == self.selected;
174 let pointer = codewhale_tui_kit::glyphs::selection_marker(is_selected);
175 let lead = format!("{pointer} {}. ", option.number);
176 let label_pad = label_col
177 .saturating_sub(UnicodeWidthStr::width(option.label))
178 .saturating_add(3);
179 let prefix_width = UnicodeWidthStr::width(lead.as_str())
180 + UnicodeWidthStr::width(option.label)
181 + label_pad;
182 let description_width = row_width.saturating_sub(prefix_width);
183 let description = codewhale_ratatui::text::truncate_words(
184 option.description,
185 description_width,
186 crate::tui::color_compat::ascii_safe_enabled(),
187 );
188
189 if is_selected {
190 let row_style = menu_style::selected_row_style();
191 let desc_style = menu_style::selected_row_bg_style().fg(palette::SELECTION_TEXT);
192 let line = Line::from(vec![
193 Span::styled(lead, row_style),
194 Span::styled(option.label, row_style),
195 Span::styled(" ".repeat(label_pad), row_style),
196 Span::styled(description, desc_style),
197 ]);
198 lines.push(pad_selected_line(line, row_width, desc_style));
199 } else {
200 lines.push(Line::from(vec![
201 Span::styled(
202 format!("{pointer} "),
203 Style::default().fg(palette::TEXT_MUTED),
204 ),
205 Span::styled(
206 format!("{}. ", option.number),
207 Style::default()
208 .fg(palette::WHALE_ACTION)
209 .add_modifier(Modifier::BOLD),
210 ),
211 Span::styled(option.label, Style::default().fg(palette::TEXT_PRIMARY)),
212 Span::raw(" ".repeat(label_pad)),
213 Span::styled(description, Style::default().fg(palette::TEXT_MUTED)),
214 ]));
215 }
216 }
217
218 drop(hitboxes);
219 Paragraph::new(lines).render(content, buf);
220 }
221
222 fn handle_mouse(&mut self, mouse: MouseEvent) -> ViewAction {
223 match mouse.kind {
224 MouseEventKind::ScrollUp => {
225 self.move_up();
226 ViewAction::None
227 }
228 MouseEventKind::ScrollDown => {
229 self.move_down();
230 ViewAction::None
231 }
232 MouseEventKind::Moved => {
233 let hovered = self
234 .row_hitboxes
235 .borrow()
236 .iter()
237 .position(|rect| rect.y == mouse.row);
238 if let Some(index) = hovered {
239 self.selected = index;
240 }
241 ViewAction::None
242 }
243 MouseEventKind::Down(MouseButton::Left) => {
244 let clicked = self
245 .row_hitboxes
246 .borrow()
247 .iter()
248 .position(|rect| rect.y == mouse.row);
249 match clicked {
250 // Click to focus, click again to open — the same two-step
251 // the session picker uses, so a stray click never opens a
252 // browser tab the user did not choose.
253 Some(index) if index == self.selected => self.selected_action(),
254 Some(index) => {
255 self.selected = index;
256 ViewAction::None
257 }
258 None => ViewAction::None,
259 }
260 }
261 _ => ViewAction::None,
262 }
263 }
264 }
265
266 #[cfg(test)]
267 mod tests {
268 use super::*;
269
270 fn mouse(kind: MouseEventKind, row: u16) -> MouseEvent {
271 MouseEvent {
272 kind,
273 column: 2,
274 row,
275 modifiers: KeyModifiers::NONE,
276 }
277 }
278
279 /// Selectable rows need keyboard and mouse parity. This view overrode no
280 /// `handle_mouse`, so it inherited the no-op default and the view stack
281 /// swallowed every click on it — the only list in the picker family that
282 /// could not be used with a pointer.
283 #[test]
284 fn feedback_rows_are_clickable_and_land_on_the_row_under_the_pointer() {
285 use ratatui::{Terminal, backend::TestBackend};
286 let mut view = FeedbackPickerView::new();
287 let mut terminal = Terminal::new(TestBackend::new(100, 24)).expect("terminal");
288 terminal
289 .draw(|frame| view.render(frame.area(), frame.buffer_mut()))
290 .expect("draw");
291
292 let rows: Vec<u16> = view.row_hitboxes.borrow().iter().map(|r| r.y).collect();
293 assert_eq!(rows.len(), OPTIONS.len(), "every option needs a hitbox");
294 assert!(
295 rows.windows(2).all(|w| w[1] == w[0] + 1),
296 "option hitboxes must be consecutive rows, got {rows:?}"
297 );
298
299 // A click on the last option must select that option — an off-by-one
300 // against the leading blank row would put it on its neighbour or drop it.
301 let last = *rows.last().expect("a row");
302 assert!(matches!(
303 view.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), last)),
304 ViewAction::None
305 ));
306 assert_eq!(view.selected, OPTIONS.len() - 1);
307
308 // Clicking the already-selected row opens it; a single stray click
309 // never does, so a misplaced pointer cannot open a browser tab.
310 assert_eq!(
311 emitted_command(
312 view.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), last))
313 ),
314 OPTIONS[OPTIONS.len() - 1].command
315 );
316
317 assert!(matches!(
318 view.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), 0)),
319 ViewAction::None
320 ));
321 }
322
323 fn emitted_command(action: ViewAction) -> String {
324 match action {
325 ViewAction::EmitAndClose(ViewEvent::CommandPaletteSelected {
326 action: CommandPaletteAction::ExecuteCommand { command },
327 }) => command,
328 other => panic!("expected feedback command emit, got {other:?}"),
329 }
330 }
331
332 #[test]
333 fn enter_emits_selected_feedback_command() {
334 let mut view = FeedbackPickerView::new();
335 let command =
336 emitted_command(view.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)));
337 assert_eq!(command, "/feedback bug");
338 }
339
340 #[test]
341 fn arrow_down_selects_feature_command() {
342 let mut view = FeedbackPickerView::new();
343 view.handle_key(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE));
344 let command =
345 emitted_command(view.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)));
346 assert_eq!(command, "/feedback feature");
347 }
348
349 #[test]
350 fn digit_selects_security_command() {
351 let mut view = FeedbackPickerView::new();
352 let command =
353 emitted_command(view.handle_key(KeyEvent::new(KeyCode::Char('3'), KeyModifiers::NONE)));
354 assert_eq!(command, "/feedback security");
355 }
356
357 #[test]
358 fn esc_closes_picker() {
359 let mut view = FeedbackPickerView::new();
360 assert!(matches!(
361 view.handle_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)),
362 ViewAction::Close
363 ));
364 }
365
366 /// The four terminal sizes the v0.8.66 modal blocker (#3732) requires
367 /// every overlay to remain readable and fully operable at.
368 const BLOCKER_SIZES: [(u16, u16); 4] = [(80, 24), (100, 30), (120, 32), (160, 40)];
369
370 #[test]
371 fn feedback_is_usable_and_opaque_at_blocker_sizes() {
372 use crate::tui::views::ViewStack;
373 use ratatui::{buffer::Buffer, layout::Rect};
374 use unicode_width::UnicodeWidthStr;
375
376 for (w, h) in BLOCKER_SIZES {
377 let area = Rect::new(0, 0, w, h);
378 let mut buf = Buffer::empty(area);
379 for y in 0..h {
380 for x in 0..w {
381 buf[(x, y)].set_symbol("X");
382 }
383 }
384 let mut stack = ViewStack::new();
385 stack.push(FeedbackPickerView::new());
386 stack.render(area, &mut buf);
387
388 let rows: Vec<String> = (0..h)
389 .map(|y| {
390 (0..w)
391 .map(|x| buf[(x, y)].symbol().to_string())
392 .collect::<String>()
393 })
394 .collect();
395 let text = rows.join("\n");
396
397 for label in ["move", "open", "cancel"] {
398 assert!(text.contains(label), "{w}x{h}: missing footer '{label}'");
399 }
400 assert!(
401 text.contains(codewhale_tui_kit::glyphs::SELECTION),
402 "{w}x{h}: missing charter selection pointer"
403 );
404 assert!(
405 !text.contains('X'),
406 "{w}x{h}: background bleed-through into modal surface"
407 );
408 assert_eq!(
409 buf[(w / 2, h / 2)].bg,
410 palette::COMPOSER_BG,
411 "{w}x{h}: modal interior must be opaque"
412 );
413 for (y, row) in rows.iter().enumerate() {
414 assert!(
415 UnicodeWidthStr::width(row.trim_end()) <= w as usize,
416 "{w}x{h}: row {y} overflows width: {row:?}"
417 );
418 }
419 }
420 }
421 }
422
422 lines RUST