返回 CodeWhale
context_menu.rs
根目录 / crates / tui / src / tui / context_menu.rs
1 //! Right-click context menu for mouse-captured TUI sessions.
2 //!
3 //! v0.9.1: elevated, lightly rounded surface with leading glyphs, section
4 //! grouping, right-aligned key-hint chips, hover-follow, and a primary action
5 //! focused by default. Reduced motion opens instantly (no appear frames).
6
7 use std::cell::Cell;
8 use std::time::Instant;
9
10 use crossterm::event::{KeyCode, KeyEvent, KeyModifiers, MouseButton, MouseEvent, MouseEventKind};
11 use ratatui::{
12 buffer::Buffer,
13 layout::Rect,
14 style::{Modifier, Style},
15 text::{Line, Span},
16 widgets::{Clear, Paragraph, Widget},
17 };
18 use unicode_width::UnicodeWidthStr;
19
20 use crate::tui::ocean;
21 use crate::tui::views::{ContextMenuAction, ModalKind, ModalView, ViewAction, ViewEvent};
22 use codewhale_palette as palette;
23 use codewhale_tui_kit::menu_style;
24
25 #[derive(Debug, Clone)]
26 pub struct ContextMenuEntry {
27 pub label: String,
28 pub description: String,
29 pub action: ContextMenuAction,
30 /// Leading glyph / icon (e.g. "⎘", "↗", "⌥").
31 pub glyph: String,
32 /// Right-aligned key that runs this entry (e.g. "y", "1"). Every hint
33 /// shown is live: `handle_key` runs the entry whose hint matches.
34 pub hint: String,
35 /// When true, starts a new visual section above this entry.
36 pub section_start: bool,
37 /// Primary (most likely) action — focused by default and accent-styled.
38 pub primary: bool,
39 /// Destructive entries are confirmed in place: the first activation arms
40 /// the row and swaps its label for this text, the second runs it.
41 pub confirm_label: Option<String>,
42 }
43
44 impl ContextMenuEntry {
45 pub fn new(
46 label: impl Into<String>,
47 description: impl Into<String>,
48 action: ContextMenuAction,
49 ) -> Self {
50 Self {
51 label: label.into(),
52 description: description.into(),
53 action,
54 glyph: String::new(),
55 hint: String::new(),
56 section_start: false,
57 primary: false,
58 confirm_label: None,
59 }
60 }
61
62 #[must_use]
63 pub fn with_glyph(mut self, glyph: impl Into<String>) -> Self {
64 self.glyph = glyph.into();
65 self
66 }
67
68 #[must_use]
69 pub fn with_hint(mut self, hint: impl Into<String>) -> Self {
70 self.hint = hint.into();
71 self
72 }
73
74 #[must_use]
75 pub fn section_start(mut self) -> Self {
76 self.section_start = true;
77 self
78 }
79
80 #[must_use]
81 pub fn primary(mut self) -> Self {
82 self.primary = true;
83 self
84 }
85
86 /// Require a second activation. `armed_label` replaces the row label
87 /// while the entry waits for it, and says what confirms it ("Stop agent:
88 /// Enter or click again to confirm").
89 #[must_use]
90 /// A `{label}` in `armed_label` becomes this row's label (without a
91 /// trailing `…`), so the armed row still names what it will do.
92 pub fn confirm(mut self, armed_label: impl Into<String>) -> Self {
93 let label = self.label.trim_end_matches('…').trim_end();
94 self.confirm_label = Some(armed_label.into().replace("{label}", label));
95 self
96 }
97 }
98
99 /// Keys the menu itself uses; never handed out as entry hints.
100 const RESERVED_KEYS: [char; 3] = ['j', 'k', 'q'];
101 /// Letters handed to entries past the ninth, after digits run out.
102 const BACKFILL_LETTERS: &str = "abcdfghilmnorstuvwxz";
103 /// A second click on an armed row sooner than this is the tail of a
104 /// double-click, not a decision, so it does not confirm. Same window the
105 /// composer uses to tell a double-click from two clicks.
106 const CONFIRM_CLICK_GUARD: std::time::Duration =
107 std::time::Duration::from_millis(crate::tui::mouse_ui::DOUBLE_CLICK_MS);
108
109 /// One painted row of the menu body, top to bottom.
110 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
111 enum MenuRow {
112 Title,
113 Divider,
114 Entry(usize),
115 MoreAbove(usize),
116 MoreBelow(usize),
117 Detail,
118 }
119
120 pub struct ContextMenuView {
121 entries: Vec<ContextMenuEntry>,
122 selected: usize,
123 /// Entry waiting for its confirming second activation.
124 armed: Option<usize>,
125 /// When `armed` was set, so a double-click cannot arm and confirm a
126 /// destructive row in one gesture.
127 armed_at: Option<Instant>,
128 /// First entry drawn when the menu is taller than the screen. Kept in a
129 /// `Cell` because render (`&self`) is where the height is known.
130 scroll: Cell<usize>,
131 column: u16,
132 row: u16,
133 last_rect: Cell<Option<Rect>>,
134 title: String,
135 opened_at: Instant,
136 reduced_motion: bool,
137 }
138
139 impl ContextMenuView {
140 pub fn new_with_motion(
141 entries: Vec<ContextMenuEntry>,
142 column: u16,
143 row: u16,
144 title: String,
145 reduced_motion: bool,
146 ) -> Self {
147 // Focus the primary action by default when present.
148 let selected = entries.iter().position(|e| e.primary).unwrap_or(0);
149 let mut entries = entries;
150 assign_hints(&mut entries);
151 for entry in &mut entries {
152 if entry.glyph.is_empty() {
153 entry.glyph = default_glyph_for(&entry.action);
154 }
155 }
156 Self {
157 entries,
158 selected,
159 armed: None,
160 armed_at: None,
161 scroll: Cell::new(0),
162 column,
163 row,
164 last_rect: Cell::new(None),
165 title,
166 opened_at: Instant::now(),
167 reduced_motion,
168 }
169 }
170
171 fn move_selection(&mut self, delta: isize) {
172 self.armed = None;
173 self.selected =
174 codewhale_tui_kit::list_nav::wrap_index(self.selected, self.entries.len(), delta);
175 }
176
177 /// Run entry `idx`, or arm it when it needs confirming. `confirm` is false
178 /// for a hint key: a letter arms a destructive row but never confirms it.
179 fn activate(&mut self, idx: usize, confirm: bool) -> ViewAction {
180 let Some(entry) = self.entries.get(idx) else {
181 return ViewAction::None;
182 };
183 if self.selected != idx {
184 self.armed = None;
185 }
186 self.selected = idx;
187 if entry.confirm_label.is_some() && !(confirm && self.armed == Some(idx)) {
188 if self.armed != Some(idx) {
189 self.armed_at = Some(Instant::now());
190 }
191 self.armed = Some(idx);
192 return ViewAction::None;
193 }
194 ViewAction::EmitAndClose(ViewEvent::ContextMenuSelected {
195 action: entry.action.clone(),
196 })
197 }
198
199 fn label_for(&self, idx: usize) -> &str {
200 let entry = &self.entries[idx];
201 match (&entry.confirm_label, self.armed == Some(idx)) {
202 (Some(armed), true) => armed.as_str(),
203 _ => entry.label.as_str(),
204 }
205 }
206
207 fn menu_width(&self, area_width: u16) -> u16 {
208 let widest = self
209 .entries
210 .iter()
211 .map(|entry| {
212 let label_width = UnicodeWidthStr::width(entry.label.as_str()).max(
213 entry
214 .confirm_label
215 .as_deref()
216 .map_or(0, UnicodeWidthStr::width),
217 );
218 let action_width = UnicodeWidthStr::width(entry.glyph.as_str())
219 .saturating_add(label_width)
220 .saturating_add(UnicodeWidthStr::width(entry.hint.as_str()))
221 .saturating_add(7);
222 let detail_width =
223 UnicodeWidthStr::width(entry.description.as_str()).saturating_add(4);
224 action_width.max(detail_width)
225 })
226 .max()
227 .unwrap_or(20)
228 .max(UnicodeWidthStr::width(self.title.as_str()).saturating_add(4));
229 let width = u16::try_from(widest.clamp(22, 56)).unwrap_or(56);
230 width.min(area_width.max(1))
231 }
232
233 fn has_detail(&self) -> bool {
234 self.entries.iter().any(|e| !e.description.is_empty())
235 }
236
237 fn visual_row_count(&self) -> usize {
238 // title + entries + section dividers + a stable selected-detail row
239 let dividers = self
240 .entries
241 .iter()
242 .enumerate()
243 .filter(|(idx, e)| e.section_start && *idx > 0)
244 .count();
245 self.entries
246 .len()
247 .saturating_add(usize::from(!self.title.is_empty()))
248 .saturating_add(dividers)
249 .saturating_add(usize::from(self.has_detail()) * 2)
250 }
251
252 fn menu_rect(&self, area: Rect) -> Rect {
253 let width = self.menu_width(area.width);
254 // +2: the top rail and one row of bottom padding.
255 let desired_height =
256 u16::try_from(self.visual_row_count().saturating_add(2)).unwrap_or(u16::MAX);
257 let height = desired_height.min(area.height.max(1));
258 let max_x = area.right().saturating_sub(width).max(area.x);
259 let max_y = area.bottom().saturating_sub(height).max(area.y);
260 let x = self.column.max(area.x).min(max_x);
261 let y = self.row.max(area.y).min(max_y);
262 Rect {
263 x,
264 y,
265 width,
266 height,
267 }
268 }
269
270 /// The body rows for a menu drawn in `rect`, starting one row below the
271 /// top rail. When the entries do not fit, a window around the selection
272 /// is shown with `↑ n more` / `↓ n more` rows, so every entry stays
273 /// reachable and the keyboard selection is always on screen.
274 fn layout(&self, rect: Rect) -> Vec<MenuRow> {
275 let body = usize::from(rect.height.saturating_sub(2));
276 let fixed = usize::from(!self.title.is_empty()) + usize::from(self.has_detail()) * 2;
277 let budget = body.saturating_sub(fixed).max(1);
278 let (start, end) = self.window(budget);
279
280 let mut rows = Vec::new();
281 if !self.title.is_empty() {
282 rows.push(MenuRow::Title);
283 }
284 if start > 0 {
285 rows.push(MenuRow::MoreAbove(start));
286 }
287 for (idx, entry) in self.entries.iter().enumerate().take(end).skip(start) {
288 if idx > start && entry.section_start {
289 rows.push(MenuRow::Divider);
290 }
291 rows.push(MenuRow::Entry(idx));
292 }
293 if end < self.entries.len() {
294 rows.push(MenuRow::MoreBelow(self.entries.len() - end));
295 }
296 if self.has_detail() {
297 rows.push(MenuRow::Divider);
298 rows.push(MenuRow::Detail);
299 }
300 rows
301 }
302
303 /// `[start, end)` of the entries that fit in `budget` rows with the
304 /// selection visible.
305 fn window(&self, budget: usize) -> (usize, usize) {
306 let len = self.entries.len();
307 if len == 0 {
308 return (0, 0);
309 }
310 let fill = |start: usize| {
311 let mut used = usize::from(start > 0);
312 let mut idx = start;
313 while idx < len {
314 let cost = 1 + usize::from(idx > start && self.entries[idx].section_start);
315 let more_below = usize::from(idx + 1 < len);
316 if used + cost + more_below > budget {
317 break;
318 }
319 used += cost;
320 idx += 1;
321 }
322 idx.max(start + 1).min(len)
323 };
324 let mut start = self.scroll.get().min(self.selected);
325 loop {
326 let end = fill(start);
327 if self.selected < end || start >= self.selected {
328 self.scroll.set(start);
329 return (start, end);
330 }
331 start += 1;
332 }
333 }
334
335 /// Map a mouse row to what is painted there.
336 fn row_at(&self, mouse_row: u16, rect: Rect) -> Option<MenuRow> {
337 let first = rect.y.saturating_add(1);
338 if mouse_row < first || mouse_row >= rect.bottom() {
339 return None;
340 }
341 self.layout(rect)
342 .get(usize::from(mouse_row - first))
343 .copied()
344 }
345
346 /// Map a mouse row to an entry index. Title, dividers, overflow markers
347 /// and the detail row are not entries.
348 fn entry_at_row(&self, mouse_row: u16, rect: Rect) -> Option<usize> {
349 match self.row_at(mouse_row, rect)? {
350 MenuRow::Entry(idx) => Some(idx),
351 _ => None,
352 }
353 }
354
355 fn inside(&self, mouse: MouseEvent) -> Option<Rect> {
356 let rect = self.last_rect.get()?;
357 (mouse.column >= rect.x
358 && mouse.column < rect.right()
359 && mouse.row >= rect.y
360 && mouse.row < rect.bottom())
361 .then_some(rect)
362 }
363
364 fn clicked_entry(&self, mouse: MouseEvent) -> Option<usize> {
365 let rect = self.inside(mouse)?;
366 self.entry_at_row(mouse.row, rect)
367 }
368
369 fn appear_progress(&self) -> f32 {
370 if self.reduced_motion {
371 return 1.0;
372 }
373 let ms = self.opened_at.elapsed().as_millis() as f32;
374 // Two-frame (~80 ms) soft open.
375 (ms / 80.0).clamp(0.0, 1.0)
376 }
377 }
378
379 /// Give every entry a working key. Explicit hints are kept unless an earlier
380 /// entry already owns the key (two menus merged into one can both ask for
381 /// `y`); entries without one get `1`–`9` by position, then a spare letter.
382 fn assign_hints(entries: &mut [ContextMenuEntry]) {
383 let mut taken: Vec<String> = RESERVED_KEYS.iter().map(char::to_string).collect();
384 for entry in entries.iter_mut() {
385 if entry.hint.is_empty() {
386 continue;
387 }
388 if taken.contains(&entry.hint) {
389 entry.hint.clear();
390 } else {
391 taken.push(entry.hint.clone());
392 }
393 }
394 let mut spare = BACKFILL_LETTERS.chars().map(|c| c.to_string());
395 for (idx, entry) in entries.iter_mut().enumerate() {
396 if !entry.hint.is_empty() {
397 continue;
398 }
399 // Digits keep meaning "the Nth row" where that row is free to take it.
400 let digit = (idx < 9).then(|| (idx + 1).to_string());
401 let key = match digit {
402 Some(digit) if !taken.contains(&digit) => digit,
403 _ => match spare.find(|key| !taken.contains(key)) {
404 Some(key) => key,
405 None => continue,
406 },
407 };
408 taken.push(key.clone());
409 entry.hint = key;
410 }
411 }
412
413 impl ModalView for ContextMenuView {
414 fn kind(&self) -> ModalKind {
415 ModalKind::ContextMenu
416 }
417
418 /// The context menu is a small anchored popup, not a full-screen modal:
419 /// scope the central backdrop to the menu itself so opening it does not
420 /// blank the transcript behind it (#3868).
421 fn occupied_region(&self, area: Rect) -> Rect {
422 self.menu_rect(area)
423 }
424
425 fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
426 self
427 }
428
429 fn handle_key(&mut self, key: KeyEvent) -> ViewAction {
430 match key.code {
431 KeyCode::Esc | KeyCode::Char('q') => ViewAction::Close,
432 KeyCode::Up | KeyCode::Char('k') => {
433 self.move_selection(-1);
434 ViewAction::None
435 }
436 KeyCode::Down | KeyCode::Char('j') => {
437 self.move_selection(1);
438 ViewAction::None
439 }
440 KeyCode::Enter => self.activate(self.selected, true),
441 // A hint is the bare letter: Ctrl+C or Alt+Y must not run the
442 // row that happens to carry `c` or `y`.
443 KeyCode::Char(c)
444 if !key.modifiers.intersects(
445 KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SUPER,
446 ) =>
447 {
448 let key = c.to_string();
449 match self.entries.iter().position(|entry| entry.hint == key) {
450 Some(idx) => self.activate(idx, false),
451 None => ViewAction::None,
452 }
453 }
454 _ => ViewAction::None,
455 }
456 }
457
458 fn handle_mouse(&mut self, mouse: MouseEvent) -> ViewAction {
459 match mouse.kind {
460 MouseEventKind::Moved => {
461 // Hover-follow: selection tracks the pointer over rows.
462 if let Some(idx) = self.clicked_entry(mouse)
463 && self.selected != idx
464 {
465 self.armed = None;
466 self.selected = idx;
467 }
468 ViewAction::None
469 }
470 MouseEventKind::Down(MouseButton::Left) => {
471 if let Some(idx) = self.clicked_entry(mouse) {
472 // The second half of a double-click lands on the row the
473 // first half just armed; it keeps the row armed and
474 // waits for a deliberate click or Enter.
475 let double_click_tail = self.armed == Some(idx)
476 && self
477 .armed_at
478 .is_some_and(|at| at.elapsed() < CONFIRM_CLICK_GUARD);
479 if double_click_tail {
480 return ViewAction::None;
481 }
482 return self.activate(idx, true);
483 }
484 // The title, dividers, overflow markers and detail row are
485 // part of the menu, not a way out of it. Only a click
486 // outside dismisses.
487 if self.inside(mouse).is_some() {
488 ViewAction::None
489 } else {
490 ViewAction::Close
491 }
492 }
493 MouseEventKind::Down(MouseButton::Right) => ViewAction::Close,
494 MouseEventKind::ScrollUp => {
495 self.move_selection(-1);
496 ViewAction::None
497 }
498 MouseEventKind::ScrollDown => {
499 self.move_selection(1);
500 ViewAction::None
501 }
502 _ => ViewAction::None,
503 }
504 }
505
506 fn render(&self, area: Rect, buf: &mut Buffer) {
507 let menu_area = self.menu_rect(area);
508 self.last_rect.set(Some(menu_area));
509 Clear.render(menu_area, buf);
510
511 let progress = self.appear_progress();
512 let elevated = palette::SURFACE_ELEVATED;
513 let shadow = ocean::mix_colors(elevated, palette::WHALE_BG, 0.35);
514 let accent = palette::WHALE_ACTION;
515 let soft_accent = ocean::mix_colors(accent, elevated, 0.72);
516
517 // Soft depth: paint a one-cell shadow offset below/right when space allows.
518 if progress >= 1.0 && menu_area.right() < area.right() {
519 for y in menu_area.y..menu_area.bottom() {
520 let cell = &mut buf[(menu_area.right(), y)];
521 if cell.symbol() == " " || cell.symbol().is_empty() {
522 cell.set_bg(shadow);
523 }
524 }
525 }
526 if progress >= 1.0 && menu_area.bottom() < area.bottom() {
527 for x in menu_area.x..menu_area.right() {
528 let cell = &mut buf[(x, menu_area.bottom())];
529 if cell.symbol() == " " || cell.symbol().is_empty() {
530 cell.set_bg(shadow);
531 }
532 }
533 }
534
535 // Fill elevated surface (borderless form).
536 for y in menu_area.y..menu_area.bottom() {
537 for x in menu_area.x..menu_area.right() {
538 buf[(x, y)].set_bg(elevated);
539 }
540 }
541
542 // Soft top accent rail (1 cell) instead of a heavy border.
543 for x in menu_area.x..menu_area.right() {
544 buf[(x, menu_area.y)].set_bg(soft_accent);
545 }
546
547 let inner_width = menu_area.width.saturating_sub(2) as usize;
548 let muted = Style::default().fg(palette::TEXT_HINT).bg(elevated);
549 let divider = Line::from(Span::styled(
550 format!(" {}", "─".repeat(inner_width.min(48))),
551 Style::default().fg(palette::BORDER_COLOR).bg(elevated),
552 ));
553 let mut lines: Vec<Line<'static>> = Vec::new();
554
555 for row in self.layout(menu_area) {
556 match row {
557 MenuRow::Title => {
558 let title = trim_to_width(&self.title, inner_width);
559 lines.push(Line::from(Span::styled(
560 format!(" {title}"),
561 muted.add_modifier(Modifier::BOLD),
562 )));
563 }
564 MenuRow::Divider => lines.push(divider.clone()),
565 MenuRow::MoreAbove(count) => {
566 lines.push(Line::from(Span::styled(format!(" ↑ {count} more"), muted)));
567 }
568 MenuRow::MoreBelow(count) => {
569 lines.push(Line::from(Span::styled(format!(" ↓ {count} more"), muted)));
570 }
571 MenuRow::Detail => {
572 let description = self
573 .entries
574 .get(self.selected)
575 .map(|entry| {
576 trim_to_width(&entry.description, inner_width.saturating_sub(2))
577 })
578 .unwrap_or_default();
579 lines.push(Line::from(Span::styled(format!(" {description}"), muted)));
580 }
581 MenuRow::Entry(idx) => {
582 lines.push(self.entry_line(idx, inner_width, elevated, accent));
583 }
584 }
585 }
586
587 let body = Rect {
588 x: menu_area.x,
589 y: menu_area.y.saturating_add(1),
590 width: menu_area.width,
591 height: menu_area.height.saturating_sub(1),
592 };
593 Paragraph::new(lines).render(body, buf);
594 }
595 }
596
597 impl ContextMenuView {
598 fn entry_line(
599 &self,
600 idx: usize,
601 inner_width: usize,
602 elevated: ratatui::style::Color,
603 accent: ratatui::style::Color,
604 ) -> Line<'static> {
605 let entry = &self.entries[idx];
606 let selected = idx == self.selected;
607 let row_style = if selected {
608 menu_style::selected_row_style()
609 } else {
610 let label_fg = if entry.primary {
611 accent
612 } else {
613 palette::TEXT_SOFT
614 };
615 Style::default().fg(label_fg).bg(elevated)
616 };
617 let glyph = if entry.glyph.is_empty() {
618 "·"
619 } else {
620 entry.glyph.as_str()
621 };
622 let hint = entry.hint.as_str();
623 let glyph_width = UnicodeWidthStr::width(glyph);
624 // Fixed glyph slot of two display columns: full-width icons (📌,
625 // 2 cols) fit as-is, narrow ones (? / ↩, 1 col) get a trailing
626 // space so every label starts at the same column.
627 let glyph_slot = if glyph_width < 2 {
628 format!("{glyph} ")
629 } else {
630 glyph.to_string()
631 };
632 let label_budget = inner_width
633 .saturating_sub(glyph_width.max(2))
634 .saturating_sub(UnicodeWidthStr::width(hint))
635 .saturating_sub(4);
636 let label = trim_to_width(self.label_for(idx), label_budget);
637 let pad = label_budget.saturating_sub(UnicodeWidthStr::width(label.as_str()));
638 let text = format!(" {glyph_slot} {label}{} {hint} ", " ".repeat(pad));
639 let style = if self.armed == Some(idx) {
640 row_style
641 .fg(palette::STATUS_WARNING)
642 .add_modifier(Modifier::BOLD)
643 } else if !selected && entry.primary {
644 row_style.add_modifier(Modifier::BOLD)
645 } else {
646 row_style
647 };
648 Line::from(Span::styled(text, style))
649 }
650 }
651
652 fn default_glyph_for(action: &ContextMenuAction) -> String {
653 // Best-effort icons from the action discriminant name.
654 let name = format!("{action:?}");
655 if name.contains("Copy") {
656 "⎘".to_string()
657 } else if name.contains("Paste") {
658 "📋".to_string()
659 } else if name.contains("Open") || name.contains("Edit") {
660 "↗".to_string()
661 } else if name.contains("Reveal") {
662 "◈".to_string()
663 } else if name.contains("Diff") || name.contains("Git") {
664 "⌥".to_string()
665 } else if name.contains("Select") {
666 "▣".to_string()
667 } else {
668 "·".to_string()
669 }
670 }
671
672 fn trim_to_width(text: &str, max_width: usize) -> String {
673 codewhale_tui_kit::ui_text::truncate_line_to_width(text, max_width)
674 }
675
676 #[cfg(test)]
677 mod tests {
678 use super::*;
679
680 #[test]
681 fn trim_to_width_keeps_grapheme_clusters_whole() {
682 let trimmed = trim_to_width("cafe\u{301} au lait", 7);
683 assert!(trimmed.starts_with("cafe\u{301}"), "{trimmed:?}");
684 assert!(UnicodeWidthStr::width(trimmed.as_str()) <= 7);
685 }
686
687 #[test]
688 fn primary_entry_is_selected_by_default() {
689 let entries = vec![
690 ContextMenuEntry::new("Copy", "", ContextMenuAction::CopySelection),
691 ContextMenuEntry::new("Paste", "", ContextMenuAction::Paste).primary(),
692 ];
693 let view = ContextMenuView::new_with_motion(entries, 0, 0, "menu".into(), false);
694 assert_eq!(view.selected, 1);
695 }
696
697 #[test]
698 fn reduced_motion_opens_instantly() {
699 let view = ContextMenuView::new_with_motion(
700 vec![ContextMenuEntry::new(
701 "Copy",
702 "",
703 ContextMenuAction::CopySelection,
704 )],
705 0,
706 0,
707 "menu".into(),
708 true,
709 );
710 assert!((view.appear_progress() - 1.0).abs() < f32::EPSILON);
711 }
712
713 #[test]
714 fn hover_rows_match_titled_menu_entries_and_dividers() {
715 let entries = vec![
716 ContextMenuEntry::new("Copy", "", ContextMenuAction::CopySelection),
717 ContextMenuEntry::new("Paste", "", ContextMenuAction::Paste).section_start(),
718 ContextMenuEntry::new("Help", "", ContextMenuAction::OpenHelp).primary(),
719 ];
720 let mut view = ContextMenuView::new_with_motion(entries, 0, 0, "Actions".into(), false);
721 let rect = Rect::new(10, 5, 30, 10);
722 view.last_rect.set(Some(rect));
723 let moved = |row| MouseEvent {
724 kind: MouseEventKind::Moved,
725 column: rect.x.saturating_add(1),
726 row,
727 modifiers: crossterm::event::KeyModifiers::NONE,
728 };
729
730 // The title and section divider are not selectable.
731 view.handle_mouse(moved(rect.y.saturating_add(1)));
732 assert_eq!(view.selected, 2);
733 view.handle_mouse(moved(rect.y.saturating_add(2)));
734 assert_eq!(view.selected, 0);
735 view.handle_mouse(moved(rect.y.saturating_add(3)));
736 assert_eq!(view.selected, 0);
737
738 view.handle_mouse(moved(rect.y.saturating_add(4)));
739 assert_eq!(view.selected, 1);
740 view.handle_mouse(moved(rect.y.saturating_add(5)));
741 assert_eq!(view.selected, 2);
742 }
743
744 #[test]
745 fn untitled_menu_entries_start_on_first_body_row() {
746 let view = ContextMenuView::new_with_motion(
747 vec![ContextMenuEntry::new(
748 "Copy",
749 "",
750 ContextMenuAction::CopySelection,
751 )],
752 0,
753 0,
754 String::new(),
755 false,
756 );
757 let rect = Rect::new(10, 5, 30, 5);
758
759 assert_eq!(view.entry_at_row(rect.y.saturating_add(1), rect), Some(0));
760 }
761
762 fn key(code: KeyCode) -> KeyEvent {
763 KeyEvent::new(code, crossterm::event::KeyModifiers::NONE)
764 }
765
766 fn click(column: u16, row: u16) -> MouseEvent {
767 MouseEvent {
768 kind: MouseEventKind::Down(MouseButton::Left),
769 column,
770 row,
771 modifiers: crossterm::event::KeyModifiers::NONE,
772 }
773 }
774
775 fn emitted(action: ViewAction) -> Option<ContextMenuAction> {
776 match action {
777 ViewAction::EmitAndClose(ViewEvent::ContextMenuSelected { action }) => Some(action),
778 _ => None,
779 }
780 }
781
782 fn cell(index: usize) -> ContextMenuAction {
783 ContextMenuAction::HideCell { cell_index: index }
784 }
785
786 /// T3: the letters drawn in the menu used to be decoration — only digits,
787 /// Enter, j/k, q and Esc were handled. Every hint shown now runs its row.
788 #[test]
789 fn letter_hints_run_their_entry() {
790 let entries = vec![
791 ContextMenuEntry::new("Paste", "", ContextMenuAction::Paste).with_hint("p"),
792 ContextMenuEntry::new("Copy", "", ContextMenuAction::CopySelection).with_hint("y"),
793 ContextMenuEntry::new("Help", "", ContextMenuAction::OpenHelp),
794 ];
795 let mut view = ContextMenuView::new_with_motion(entries, 0, 0, String::new(), true);
796
797 assert_eq!(
798 emitted(view.handle_key(key(KeyCode::Char('y')))),
799 Some(ContextMenuAction::CopySelection)
800 );
801 assert_eq!(
802 emitted(view.handle_key(key(KeyCode::Char('p')))),
803 Some(ContextMenuAction::Paste)
804 );
805 // The third row has no letter of its own and gets its position.
806 assert_eq!(view.entries[2].hint, "3");
807 assert_eq!(
808 emitted(view.handle_key(key(KeyCode::Char('3')))),
809 Some(ContextMenuAction::OpenHelp)
810 );
811 assert!(matches!(
812 view.handle_key(key(KeyCode::Char('x'))),
813 ViewAction::None
814 ));
815 // A modified letter is a different shortcut, not the row's hint.
816 for modifiers in [KeyModifiers::CONTROL, KeyModifiers::ALT] {
817 assert!(matches!(
818 view.handle_key(KeyEvent::new(KeyCode::Char('y'), modifiers)),
819 ViewAction::None
820 ));
821 }
822 }
823
824 /// Entries past the ninth had no key at all. Each now gets a spare
825 /// letter that is shown and works; j, k and q stay navigation.
826 #[test]
827 fn entries_past_nine_get_a_working_key() {
828 let entries = (0..12)
829 .map(|index| ContextMenuEntry::new(format!("row {index}"), "", cell(index)))
830 .collect();
831 let mut view = ContextMenuView::new_with_motion(entries, 0, 0, String::new(), true);
832
833 let hints: Vec<&str> = view.entries.iter().map(|e| e.hint.as_str()).collect();
834 assert_eq!(&hints[..9], ["1", "2", "3", "4", "5", "6", "7", "8", "9"]);
835 for hint in &hints[9..] {
836 assert!(!hint.is_empty(), "every row has a key: {hints:?}");
837 assert!(!["j", "k", "q"].contains(hint), "{hints:?}");
838 }
839 let tenth = view.entries[9].hint.chars().next().expect("tenth hint");
840 assert_eq!(
841 emitted(view.handle_key(key(KeyCode::Char(tenth)))),
842 Some(cell(9))
843 );
844 }
845
846 /// Two builders asking for the same letter (a row's Copy and Copy
847 /// selection both want `y`) must not leave a hint that runs the wrong row.
848 #[test]
849 fn a_duplicate_hint_goes_to_the_first_entry_only() {
850 let entries = vec![
851 ContextMenuEntry::new("Copy row", "", ContextMenuAction::Paste).with_hint("y"),
852 ContextMenuEntry::new("Copy selection", "", ContextMenuAction::CopySelection)
853 .with_hint("y"),
854 ];
855 let view = ContextMenuView::new_with_motion(entries, 0, 0, String::new(), true);
856 assert_eq!(view.entries[0].hint, "y");
857 assert_eq!(view.entries[1].hint, "2");
858 }
859
860 /// T9: the title, dividers and detail row are part of the menu. Clicking
861 /// them used to close it; only a click outside the menu dismisses now.
862 #[test]
863 fn clicks_on_title_divider_and_detail_are_inert() {
864 let entries = vec![
865 ContextMenuEntry::new("Copy", "copy it", ContextMenuAction::CopySelection),
866 ContextMenuEntry::new("Paste", "paste it", ContextMenuAction::Paste).section_start(),
867 ];
868 let mut view = ContextMenuView::new_with_motion(entries, 0, 0, "Title".into(), true);
869 let rect = Rect::new(10, 5, 30, 10);
870 view.last_rect.set(Some(rect));
871 let rows = view.layout(rect);
872 assert_eq!(
873 rows,
874 vec![
875 MenuRow::Title,
876 MenuRow::Entry(0),
877 MenuRow::Divider,
878 MenuRow::Entry(1),
879 MenuRow::Divider,
880 MenuRow::Detail,
881 ]
882 );
883 for (offset, row) in rows.iter().enumerate() {
884 if matches!(row, MenuRow::Entry(_)) {
885 continue;
886 }
887 let y = rect.y + 1 + u16::try_from(offset).unwrap();
888 assert!(
889 matches!(view.handle_mouse(click(rect.x + 2, y)), ViewAction::None),
890 "{row:?} must not close the menu"
891 );
892 }
893 // The rail and the padding row are inside the menu too.
894 assert!(matches!(
895 view.handle_mouse(click(rect.x + 2, rect.y)),
896 ViewAction::None
897 ));
898 assert!(matches!(
899 view.handle_mouse(click(rect.x + 2, rect.bottom() - 1)),
900 ViewAction::None
901 ));
902 assert!(matches!(
903 view.handle_mouse(click(rect.right() + 1, rect.y)),
904 ViewAction::Close
905 ));
906 assert_eq!(
907 emitted(view.handle_mouse(click(rect.x + 2, rect.y + 4))),
908 Some(ContextMenuAction::Paste)
909 );
910 }
911
912 /// Destructive rows are confirmed in place: the first Enter or click arms
913 /// the row, the second runs it, and moving away disarms. A letter can
914 /// arm a row but never confirms it.
915 #[test]
916 fn a_confirm_entry_needs_a_second_activation() {
917 let entries = vec![
918 ContextMenuEntry::new("Copy", "", ContextMenuAction::CopySelection),
919 ContextMenuEntry::new("Stop agent…", "", ContextMenuAction::Paste)
920 .confirm("{label}: Enter or click again to confirm")
921 .with_hint("s"),
922 ];
923 let mut view = ContextMenuView::new_with_motion(entries, 0, 0, String::new(), true);
924
925 assert!(matches!(
926 view.handle_key(key(KeyCode::Char('s'))),
927 ViewAction::None
928 ));
929 assert_eq!(view.armed, Some(1));
930 assert_eq!(
931 view.label_for(1),
932 "Stop agent: Enter or click again to confirm",
933 "the armed row names its action and what confirms it"
934 );
935 assert!(
936 matches!(view.handle_key(key(KeyCode::Char('s'))), ViewAction::None),
937 "a letter never confirms"
938 );
939 assert_eq!(
940 emitted(view.handle_key(key(KeyCode::Enter))),
941 Some(ContextMenuAction::Paste)
942 );
943
944 let entries = vec![
945 ContextMenuEntry::new("Copy", "", ContextMenuAction::CopySelection),
946 ContextMenuEntry::new("Stop", "", ContextMenuAction::Paste).confirm("again"),
947 ];
948 let mut view = ContextMenuView::new_with_motion(entries, 0, 0, String::new(), true);
949 view.handle_key(key(KeyCode::Down));
950 assert!(matches!(
951 view.handle_key(key(KeyCode::Enter)),
952 ViewAction::None
953 ));
954 view.handle_key(key(KeyCode::Up));
955 view.handle_key(key(KeyCode::Down));
956 assert_eq!(view.armed, None, "moving the selection disarms");
957 assert_eq!(view.label_for(1), "Stop");
958 assert!(matches!(
959 view.handle_key(key(KeyCode::Enter)),
960 ViewAction::None
961 ));
962 }
963
964 /// A double-click on a destructive row used to arm it and confirm it in
965 /// one gesture. The second click of a double-click is now ignored; a
966 /// later, separate click (or Enter) still confirms.
967 #[test]
968 fn a_double_click_does_not_confirm_a_destructive_row() {
969 let entries = vec![
970 ContextMenuEntry::new("Copy", "", ContextMenuAction::CopySelection),
971 ContextMenuEntry::new("Stop agent…", "", ContextMenuAction::Paste)
972 .confirm("{label}: Enter or click again to confirm"),
973 ];
974 let mut view = ContextMenuView::new_with_motion(entries, 0, 0, String::new(), true);
975 let rect = Rect::new(0, 0, 40, 6);
976 view.last_rect.set(Some(rect));
977 let stop_row = rect.y + 2;
978 assert_eq!(view.entry_at_row(stop_row, rect), Some(1));
979
980 assert!(matches!(
981 view.handle_mouse(click(2, stop_row)),
982 ViewAction::None
983 ));
984 assert_eq!(view.armed, Some(1));
985 assert!(
986 matches!(view.handle_mouse(click(2, stop_row)), ViewAction::None),
987 "the second click of a double-click must not confirm"
988 );
989 assert_eq!(view.armed, Some(1), "the row stays armed");
990
991 // A deliberate click after the double-click window confirms.
992 view.armed_at = Instant::now().checked_sub(CONFIRM_CLICK_GUARD * 2);
993 assert_eq!(
994 emitted(view.handle_mouse(click(2, stop_row))),
995 Some(ContextMenuAction::Paste)
996 );
997
998 // Enter confirms at once: a key press is never a double-click.
999 let entries = vec![
1000 ContextMenuEntry::new("Stop", "", ContextMenuAction::Paste)
1001 .confirm("{label}: Enter or click again to confirm"),
1002 ];
1003 let mut view = ContextMenuView::new_with_motion(entries, 0, 0, String::new(), true);
1004 view.last_rect.set(Some(rect));
1005 view.handle_mouse(click(2, rect.y + 1));
1006 assert_eq!(view.armed, Some(0));
1007 assert_eq!(
1008 emitted(view.handle_key(key(KeyCode::Enter))),
1009 Some(ContextMenuAction::Paste)
1010 );
1011 }
1012
1013 /// T9: a menu taller than the screen used to be cut off. It now shows a
1014 /// window with `n more` markers that follows the keyboard selection.
1015 #[test]
1016 fn a_tall_menu_scrolls_to_keep_the_selection_visible() {
1017 let entries = (0..20)
1018 .map(|index| ContextMenuEntry::new(format!("row {index}"), "", cell(index)))
1019 .collect();
1020 let mut view = ContextMenuView::new_with_motion(entries, 0, 0, String::new(), true);
1021 let rect = Rect::new(0, 0, 30, 8);
1022 let rows = view.layout(rect);
1023 assert_eq!(rows.first(), Some(&MenuRow::Entry(0)));
1024 assert!(
1025 matches!(rows.last(), Some(MenuRow::MoreBelow(_))),
1026 "{rows:?}"
1027 );
1028 assert!(rows.len() <= 6, "the body fits the rect: {rows:?}");
1029
1030 // Up from the first row wraps to the last one, which must be drawn.
1031 view.handle_key(key(KeyCode::Up));
1032 let rows = view.layout(rect);
1033 assert!(rows.contains(&MenuRow::Entry(19)), "{rows:?}");
1034 assert!(
1035 matches!(rows.first(), Some(MenuRow::MoreAbove(_))),
1036 "{rows:?}"
1037 );
1038 let y = 1 + u16::try_from(
1039 rows.iter()
1040 .position(|row| *row == MenuRow::Entry(19))
1041 .unwrap(),
1042 )
1043 .unwrap();
1044 assert_eq!(view.entry_at_row(y, rect), Some(19));
1045 }
1046 }
1047
1047 lines RUST