quvyta-framework 0.1.29

A Rust framework for building terminal applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
//! Context menus: actions for what is under the pointer, opened with a right click (or, when
//! asked, a left click).

use std::time::Duration;

use super::context_item::{self as menu, ContextItem};
use super::placement::{self, Placement};
use crate::event::{Event, KeyEvent, MouseButton, MouseKind};
use crate::geometry::{Rect, Size, clamp_u16};
use crate::keymap::{Key, Modifiers};
use crate::motion::Easing;
use crate::widget::{Axis, Container, EventCx, Flex, Length, MeasureCx, Node, PaintCx, Widget};

/// Wraps an area and opens a menu of [`ContextItem`]s at the pointer on a right click, or next to
/// the focused widget on Shift+F10 or the menu key.
///
/// The menu is a layer on the overlay surface that unfolds over `motion.enter`. Hovered and
/// highlighted rows show the pillar and slide their label one cell while shortcuts stay at the
/// right edge. ↑/↓ move (skipping gaps and disabled rows), Home/End jump, typing a letter jumps to
/// the next row starting with it, → or Enter opens a submenu, ← or Esc closes it, Enter or Space
/// chooses. Choosing sends the item's message. A press anywhere outside the menu closes it and
/// still reaches what it landed on; a right click inside the area reopens it there.
///
/// [`ContextMenu::on_left_click`] lets a left click open the menu too, at the pointer, for an
/// area whose whole purpose is the menu, such as a status bar item that lists sessions.
///
/// Style keys: see [`ContextItem`].
///
/// ```
/// use qframe::prelude::*;
/// use qframe::widgets::{ContextMenu, ContextItem};
///
/// struct Files { deleted: bool }
///
/// #[derive(Clone)]
/// enum Msg { Delete }
///
/// impl App for Files {
///     type Msg = Msg;
///     fn update(&mut self, Msg::Delete: Msg) -> Command<Msg> {
///         self.deleted = true;
///         Command::none()
///     }
///     fn view(&self, ui: &mut View<'_, Msg>) {
///         let items = [ContextItem::new("Delete", Msg::Delete).danger(true)];
///         ui.add_with(ContextMenu::new(items), |ui| {
///             ui.add(Text::new("report.pdf"));
///         });
///     }
/// }
///
/// let mut app = Harness::new(Files { deleted: false }, 30, 5);
/// app.set_reduced_motion(true);
/// app.mouse(qframe::event::MouseKind::Down(qframe::event::MouseButton::Right), 2, 0);
/// app.press("down").press("enter");
/// assert!(app.app().deleted);
/// ```
pub struct ContextMenu<Msg> {
    items: Vec<ContextItem<Msg>>,
    body: Vec<Node<Msg>>,
    left_click: bool,
}

#[derive(Debug, Default)]
struct ContextMenuMemory {
    open: bool,
    anchor: Rect,
    /// The highlighted row of every open level; the last level has the keyboard.
    levels: Vec<Option<usize>>,
    opened_at: Vec<Duration>,
    rects: Vec<Rect>,
    last_pointer: Option<(i32, i32)>,
    /// When a left press on the menu's own area closed it: the same press reaches the area next
    /// and must not open the menu again, so a status item shows and hides its menu like a button.
    closed_by_press: Option<Duration>,
}

impl<Msg: Clone + 'static> ContextMenu<Msg> {
    /// A context menu of `items` over the widgets added with
    /// [`View::add_with`](crate::widget::View::add_with).
    #[must_use]
    pub fn new(items: impl IntoIterator<Item = ContextItem<Msg>>) -> Self {
        Self {
            items: items.into_iter().collect(),
            body: vec![Node::new(Flex::new(Axis::Column, Vec::new()), 0)],
            left_click: false,
        }
    }

    /// Opens the menu with a left click as well, at the pointer, as a right click does. A left
    /// click on the area while the menu is open closes it, so the area works as a button that
    /// shows and hides its menu. Presses an interactive child takes, such as a button's, still
    /// go to that child. Default: off; a left click reaches only the content.
    #[must_use]
    pub fn on_left_click(mut self, on: bool) -> Self {
        self.left_click = on;
        self
    }

    /// Whether a press of `button` on the area opens the menu.
    fn opens_with(&self, button: MouseButton) -> bool {
        !self.items.is_empty() && (button == MouseButton::Right || (button == MouseButton::Left && self.left_click))
    }

    /// The items shown at `depth` for the open levels in `levels`.
    fn level<'s>(&'s self, levels: &[Option<usize>], depth: usize) -> &'s [ContextItem<Msg>] {
        let mut items: &[ContextItem<Msg>] = &self.items;
        for highlight in levels.iter().take(depth) {
            match highlight.and_then(|row| items.get(row)) {
                Some(item) => items = item.children(),
                None => return &[],
            }
        }
        items
    }

    /// Opens the menu below `anchor`, with the first choosable row highlighted when
    /// `highlight_first` (for menus opened from the keyboard), and takes the keys.
    pub(crate) fn open(&self, cx: &mut EventCx<'_, Msg>, anchor: Rect, highlight_first: bool) {
        let now = cx.now();
        let first = if highlight_first { menu::edge(&self.items, false) } else { None };
        let memory = cx.memory::<ContextMenuMemory>();
        memory.open = true;
        memory.anchor = anchor;
        memory.levels = vec![first];
        memory.opened_at = vec![now];
        memory.rects.clear();
        memory.last_pointer = None;
        cx.capture_keys(true);
    }

    /// Closes the menu and gives the keys back.
    pub(crate) fn close(cx: &mut EventCx<'_, Msg>) {
        let memory = cx.memory::<ContextMenuMemory>();
        memory.open = false;
        memory.levels.clear();
        memory.opened_at.clear();
        memory.rects.clear();
        cx.capture_keys(false);
    }

    /// Opens the submenu of the highlighted row of the last level, if it has one.
    fn enter_submenu(&self, cx: &mut EventCx<'_, Msg>) -> bool {
        let now = cx.now();
        let levels = cx.memory::<ContextMenuMemory>().levels.clone();
        let depth = levels.len() - 1;
        let items = self.level(&levels, depth);
        let Some(item) = levels[depth].and_then(|row| items.get(row)).filter(|item| item.has_submenu()) else {
            return false;
        };
        let first = menu::edge(item.children(), false);
        let memory = cx.memory::<ContextMenuMemory>();
        memory.levels.push(first);
        memory.opened_at.push(now);
        true
    }

    fn activate(&self, cx: &mut EventCx<'_, Msg>) {
        if self.enter_submenu(cx) {
            return;
        }
        let levels = cx.memory::<ContextMenuMemory>().levels.clone();
        let depth = levels.len() - 1;
        let items = self.level(&levels, depth);
        if let Some(message) = levels[depth].and_then(|row| items.get(row)).and_then(ContextItem::message) {
            let message = message.clone();
            Self::close(cx);
            cx.emit(message);
        }
    }

    fn set_highlight(cx: &mut EventCx<'_, Msg>, row: Option<usize>) {
        if let Some(last) = cx.memory::<ContextMenuMemory>().levels.last_mut() {
            *last = row;
        }
    }

    fn key(&self, cx: &mut EventCx<'_, Msg>, key: &KeyEvent) -> bool {
        let levels = cx.memory::<ContextMenuMemory>().levels.clone();
        let depth = levels.len() - 1;
        let items = self.level(&levels, depth);
        let highlight = levels[depth];
        if key.is_plain(Key::Esc) || (key.is_plain(Key::Left) && depth > 0) {
            if depth == 0 {
                Self::close(cx);
            } else {
                let memory = cx.memory::<ContextMenuMemory>();
                memory.levels.pop();
                memory.opened_at.pop();
            }
        } else if key.is_plain(Key::Tab) {
            Self::close(cx);
            return false;
        } else if key.is_plain(Key::Up) {
            Self::set_highlight(cx, menu::step(items, highlight, false));
        } else if key.is_plain(Key::Down) {
            Self::set_highlight(cx, menu::step(items, highlight, true));
        } else if key.is_plain(Key::Home) {
            Self::set_highlight(cx, menu::edge(items, false));
        } else if key.is_plain(Key::End) {
            Self::set_highlight(cx, menu::edge(items, true));
        } else if key.is_plain(Key::Right) {
            self.enter_submenu(cx);
        } else if key.is_plain(Key::Enter) || key.is_plain(Key::Space) {
            self.activate(cx);
        } else if let (Some(typed), false) = (key.text, key.chord.mods.ctrl || key.chord.mods.alt)
            && let Some(row) = menu::type_ahead(items, highlight, typed)
        {
            Self::set_highlight(cx, Some(row));
        }
        true
    }

    /// Handles a press while open. Returns whether the press was used; a left press on the area
    /// outside the menu only closes it and goes on to what lies there.
    fn press(&self, cx: &mut EventCx<'_, Msg>, x: i32, y: i32, button: MouseButton) -> bool {
        let (rects, levels) = open_rects(cx.memory::<ContextMenuMemory>());
        // A press outside the menu closes it and is not swallowed.
        let Some(depth) = rects.iter().rposition(|rect| rect.contains(x, y)) else {
            Self::close(cx);
            if !self.opens_with(button) || !cx.area().contains(x, y) {
                return false;
            }
            // The release after this press belongs to the menu, not to what lies under it.
            cx.capture_pointer();
            // A left click on the area toggles: the press that closes the menu does not reopen it.
            if button == MouseButton::Right {
                self.open(cx, Rect::new(x, y, 1, 1), false);
            }
            return true;
        };
        // The release after this press belongs to the menu, not to what lies under it.
        cx.capture_pointer();
        let row = usize::try_from(y - rects[depth].y).unwrap_or(0);
        let items = self.level(&levels, depth);
        if !items.get(row).is_some_and(ContextItem::selectable) {
            return true;
        }
        let memory = cx.memory::<ContextMenuMemory>();
        memory.levels.truncate(depth + 1);
        memory.opened_at.truncate(depth + 1);
        memory.levels[depth] = Some(row);
        self.activate(cx);
        true
    }

    /// Follows the pointer: the row under it is highlighted and a submenu under it opens. Only
    /// when the pointer moved, so a resting pointer does not undo keyboard moves.
    fn follow_pointer(&self, cx: &mut PaintCx<'_>) {
        let pointer = cx.pointer();
        let now = cx.now();
        let (moved, rects, mut levels) = {
            let memory = cx.memory::<ContextMenuMemory>();
            let moved = pointer.is_some() && pointer != memory.last_pointer;
            memory.last_pointer = pointer;
            let (rects, levels) = open_rects(memory);
            (moved, rects, levels)
        };
        let Some((x, y)) = pointer.filter(|_| moved) else {
            return;
        };
        let Some(depth) = rects.iter().rposition(|rect| rect.contains(x, y)) else {
            return;
        };
        let row = usize::try_from(y - rects[depth].y).unwrap_or(0);
        let item = self.level(&levels, depth).get(row).filter(|item| item.selectable());
        let opens = item.is_some_and(ContextItem::has_submenu);
        let unchanged = levels.get(depth) == Some(&item.map(|_| row)) && (levels.len() == depth + 2) == opens;
        if unchanged {
            return;
        }
        levels.truncate(depth + 1);
        levels[depth] = item.map(|_| row);
        let memory = cx.memory::<ContextMenuMemory>();
        memory.opened_at.truncate(depth + 1);
        if opens {
            levels.push(None);
            memory.opened_at.push(now);
        }
        memory.levels = levels;
    }
}

/// Whether `key` opens a context menu from the keyboard: Shift+F10 or the menu key.
pub(crate) fn is_menu_key(key: &KeyEvent) -> bool {
    let shift = Modifiers { shift: true, ..Modifiers::default() };
    (key.chord.key == Key::F(10) && key.chord.mods == shift) || key.is_plain(Key::Menu)
}

/// Whether `(x, y)` is on a level of the context menu kept in the memory of the widget handling an
/// event, as painted last frame.
pub(crate) fn contains<Msg>(cx: &mut EventCx<'_, Msg>, x: i32, y: i32) -> bool {
    let (rects, _) = open_rects(cx.memory::<ContextMenuMemory>());
    rects.iter().any(|rect| rect.contains(x, y))
}

/// The rects of the levels painted last frame that are still open, and the open levels. Events
/// arrive in batches between frames, so a key that closed a submenu can come before a press on
/// where that submenu was drawn.
fn open_rects(memory: &ContextMenuMemory) -> (Vec<Rect>, Vec<Option<usize>>) {
    let open = memory.rects.len().min(memory.levels.len());
    (memory.rects[..open].to_vec(), memory.levels.clone())
}

// Menus driven by the widget that owns them, for the edit menus of text widgets.
/// Whether the context menu kept in the memory of the widget being painted is open.
pub(crate) fn is_open(cx: &mut PaintCx<'_>) -> bool {
    cx.memory::<ContextMenuMemory>().open
}

/// Whether the context menu kept in the memory of the widget handling an event is open.
pub(crate) fn is_open_in<Msg>(cx: &mut EventCx<'_, Msg>) -> bool {
    cx.memory::<ContextMenuMemory>().open
}

impl<Msg: Clone + 'static> Container<Msg> for ContextMenu<Msg> {
    fn set_children(&mut self, children: Vec<Node<Msg>>) {
        let mut column = Node::new(Flex::new(Axis::Column, children), 0);
        column.layout.width = Length::Fill(1);
        column.layout.height = Length::Fill(1);
        self.body = vec![column];
    }
}

impl<Msg: Clone + 'static> Widget<Msg> for ContextMenu<Msg> {
    fn measure(&self, cx: &mut MeasureCx<'_>, available: Size) -> Size {
        self.body.first().map_or(Size::default(), |body| cx.measure_child(body, available))
    }

    fn paint(&self, cx: &mut PaintCx<'_>, area: Rect) {
        // Plain content still receives the right click; interactive children sit on top.
        cx.register_hit(area);
        if let Some(body) = self.body.first() {
            cx.paint_child(body, area);
        }
        if cx.memory::<ContextMenuMemory>().open {
            cx.request_overlay(area);
        }
    }

    fn paint_overlay(&self, cx: &mut PaintCx<'_>, _area: Rect) {
        let screen = cx.clip();
        // Only the menu rows take presses (`menu::paint` registers them); the runtime closes the
        // menu on a press anywhere else and passes that press on.
        self.follow_pointer(cx);
        let (anchor, levels, opened_at) = {
            let memory = cx.memory::<ContextMenuMemory>();
            (memory.anchor, memory.levels.clone(), memory.opened_at.clone())
        };
        let enter = cx.env().theme().motion().enter;
        let mut rects = Vec::new();
        let mut parent_row = anchor;
        for depth in 0..levels.len() {
            let items = self.level(&levels, depth);
            if items.is_empty() {
                break;
            }
            let preferred = if depth == 0 { Placement::Below } else { Placement::Right };
            let (full, side) = placement::place(parent_row, menu::size(cx, items), screen, preferred);
            let started = opened_at.get(depth).copied().unwrap_or_default();
            let progress = cx.progress_since(started, enter, Easing::EaseOut);
            // Submenus beside their row unfold downwards too.
            let shown =
                placement::unfold(full, if side == Placement::Above { side } else { Placement::Below }, progress);
            menu::paint(cx, items, full, shown, levels[depth]);
            rects.push(full);
            let Some(row) = levels[depth] else {
                break;
            };
            parent_row = full.row(clamp_u16(i32::try_from(row).unwrap_or(i32::MAX)));
        }
        cx.memory::<ContextMenuMemory>().rects = rects;
    }

    fn event(&self, cx: &mut EventCx<'_, Msg>, event: &Event) -> bool {
        let open = cx.memory::<ContextMenuMemory>().open;
        match event {
            Event::PointerOutside => {
                // A press on a widget inside the area that takes the pointer itself, a tooltip
                // for one, comes here first; the same press then reaches the area.
                let on_area = self.left_click
                    && open
                    && cx.interaction.pointer.is_some_and(|(x, y)| {
                        cx.area().contains(x, y)
                            && !cx.memory::<ContextMenuMemory>().rects.iter().any(|rect| rect.contains(x, y))
                    });
                Self::close(cx);
                if on_area {
                    cx.memory::<ContextMenuMemory>().closed_by_press = Some(cx.now());
                }
                true
            }
            Event::Key(key) if open => self.key(cx, key),
            Event::Key(key) => {
                if !is_menu_key(key) || self.items.is_empty() {
                    return false;
                }
                let area = cx.area();
                let anchor =
                    cx.focused_area().filter(|rect| !rect.is_empty()).unwrap_or(Rect::new(area.x, area.y, 1, 1));
                self.open(cx, anchor, true);
                true
            }
            Event::Mouse(mouse) => match mouse.kind {
                MouseKind::Down(button) if open => self.press(cx, mouse.x, mouse.y, button),
                MouseKind::Down(button) if self.opens_with(button) => {
                    let now = cx.now();
                    let closed = cx.memory::<ContextMenuMemory>().closed_by_press.take();
                    if button == MouseButton::Left && closed == Some(now) {
                        return true;
                    }
                    self.open(cx, Rect::new(mouse.x, mouse.y, 1, 1), false);
                    true
                }
                MouseKind::Up(_) | MouseKind::Drag(_) | MouseKind::ScrollUp | MouseKind::ScrollDown => open,
                _ => false,
            },
            Event::Paste(_) => false,
        }
    }

    fn children(&self) -> &[Node<Msg>] {
        &self.body
    }

    fn children_mut(&mut self) -> &mut [Node<Msg>] {
        &mut self.body
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::runtime::{App, Command, Harness};
    use crate::widget::View;
    use crate::widgets::{Button, Text};

    #[derive(Default)]
    struct Demo {
        chosen: Vec<&'static str>,
        pressed: u32,
    }

    #[derive(Clone)]
    enum Msg {
        Chose(&'static str),
        Press,
    }

    impl App for Demo {
        type Msg = Msg;
        fn update(&mut self, msg: Msg) -> Command<Msg> {
            match msg {
                Msg::Chose(name) => self.chosen.push(name),
                Msg::Press => self.pressed += 1,
            }
            Command::none()
        }
        fn view(&self, ui: &mut View<'_, Msg>) {
            let items = [
                ContextItem::new("Restart", Msg::Chose("restart")).shortcut("ctrl r"),
                ContextItem::new("Pause", Msg::Chose("pause")).disabled(true),
                ContextItem::submenu("Move to", [ContextItem::new("Staging", Msg::Chose("staging"))]),
                ContextItem::gap(),
                ContextItem::new("Delete", Msg::Chose("delete")).danger(true),
            ];
            ui.column(|ui| {
                ui.add_with(ContextMenu::new(items), |ui| {
                    ui.add(Text::new("api-gateway"));
                    ui.add(Button::new("Logs").on_press(Msg::Press)).id("logs");
                })
                .height(Length::Cells(10))
                .fill_width();
            })
            .fill_width();
        }
    }

    fn right_click<A: App>(h: &mut Harness<A>, x: i32, y: i32) {
        h.mouse(MouseKind::Down(MouseButton::Right), x, y);
        h.mouse(MouseKind::Up(MouseButton::Right), x, y);
    }

    #[test]
    fn right_click_opens_at_the_pointer_with_shortcuts_anchored_right() {
        let mut h = Harness::new(Demo::default(), 40, 12);
        right_click(&mut h, 3, 0);
        h.advance(Duration::from_millis(200));
        let screen = h.screen();
        let lines: Vec<&str> = screen.lines().collect();
        // The menu opens one row under the pointer and covers what is below it.
        assert_eq!(lines[1], "  L  Restart    ctrl r", "{screen}");
        assert_eq!(lines[2], "     Pause");
        assert_eq!(lines[3], "     Move to         ▶");
        assert_eq!(lines[4], "");
        assert_eq!(lines[5], "     Delete");
        let theme = h.env().theme();
        assert_eq!(h.bg(3, 1), theme.color("overlay"));
        assert_eq!(h.fg(5, 5), theme.color("danger"));
        assert_eq!(h.fg(5, 2), theme.color("muted"));
        assert_eq!(h.fg(16, 1), theme.color("muted"));
    }

    #[test]
    fn keyboard_skips_disabled_rows_and_gaps_and_chooses() {
        let mut h = Harness::new(Demo::default(), 40, 12);
        h.set_reduced_motion(true);
        right_click(&mut h, 3, 0);
        h.press("down").press("down");
        let screen = h.screen();
        assert!(screen.lines().nth(3).is_some_and(|line| line.starts_with("   ▌  Move to")), "{screen}");
        h.press("down").press("enter");
        assert_eq!(h.app().chosen, vec!["delete"]);
        assert!(!h.screen().contains("Restart"));
    }

    #[test]
    fn submenus_open_with_right_and_close_with_left() {
        let mut h = Harness::new(Demo::default(), 40, 12);
        h.set_reduced_motion(true);
        right_click(&mut h, 3, 0);
        h.press("m").press("right");
        assert!(h.screen().contains("Staging"), "{}", h.screen());
        h.press("left");
        assert!(!h.screen().contains("Staging"));
        h.press("enter").press("enter");
        assert_eq!(h.app().chosen, vec!["staging"]);
    }

    #[test]
    fn hovering_a_submenu_opens_it_and_clicks_choose() {
        let mut h = Harness::new(Demo::default(), 40, 12);
        h.set_reduced_motion(true);
        right_click(&mut h, 3, 0);
        h.hover(8, 3);
        let (x, y) = h.find("Staging").expect("submenu opened on hover");
        h.click(x, y);
        assert_eq!(h.app().chosen, vec!["staging"]);
    }

    #[test]
    fn outside_press_closes_and_still_reaches_the_button() {
        let mut h = Harness::new(Demo::default(), 40, 12);
        h.set_reduced_motion(true);
        right_click(&mut h, 20, 8);
        assert!(h.screen().contains("Restart"));
        h.click_text("Logs");
        assert_eq!(h.app().pressed, 1, "one press closes the menu and presses the button");
        assert!(!h.screen().contains("Restart"));
        assert!(h.app().chosen.is_empty());
    }

    #[test]
    fn shift_f10_opens_next_to_the_focused_widget() {
        let mut h = Harness::new(Demo::default(), 40, 12);
        h.set_reduced_motion(true);
        h.press("tab").press("shift+f10");
        let screen = h.screen();
        assert!(screen.lines().nth(2).is_some_and(|line| line.starts_with("▌  Restart   ctrl r")), "{screen}");
        h.press("esc");
        assert!(!h.screen().contains("Restart"));
        assert!(h.is_focused("logs"));
    }

    #[test]
    fn flips_above_near_the_bottom() {
        let mut h = Harness::new(Demo::default(), 40, 12);
        h.set_reduced_motion(true);
        right_click(&mut h, 3, 9);
        let (_, y) = h.find("Delete").expect("open");
        assert_eq!(y, 8);
    }

    /// A status bar item whose left click lists sessions, as a menu of its own.
    #[derive(Default)]
    struct Sessions {
        chosen: Vec<&'static str>,
    }

    impl App for Sessions {
        type Msg = Msg;
        fn update(&mut self, msg: Msg) -> Command<Msg> {
            if let Msg::Chose(name) = msg {
                self.chosen.push(name);
            }
            Command::none()
        }
        fn view(&self, ui: &mut View<'_, Msg>) {
            let items = [
                ContextItem::new("work", Msg::Chose("work")),
                ContextItem::new("notes", Msg::Chose("notes")),
                ContextItem::new("build", Msg::Chose("build")),
            ];
            ui.column(|ui| {
                ui.add_with(ContextMenu::new(items).on_left_click(true), |ui| {
                    ui.add(Text::new("tmux 3"));
                });
            })
            .fill();
        }
    }

    fn sessions() -> Harness<Sessions> {
        let mut h = Harness::new(Sessions::default(), 30, 8);
        h.set_reduced_motion(true);
        h
    }

    #[test]
    fn a_left_click_opens_the_menu_at_the_pointer_and_a_click_chooses() {
        let mut by_right = sessions();
        right_click(&mut by_right, 2, 0);
        let mut h = sessions();
        h.click(2, 0);
        let screen = h.screen();
        let lines: Vec<&str> = screen.lines().collect();
        // One row under the pointer, starting at its column, exactly as a right click opens it.
        assert_eq!(lines[1], "    work", "{screen}");
        assert_eq!(lines[3], "    build");
        assert_eq!(screen, by_right.screen());
        assert_eq!(h.bg(3, 1), h.env().theme().color("overlay"));
        h.click_text("notes");
        assert_eq!(h.app().chosen, vec!["notes"]);
        assert!(!h.screen().contains("build"), "choosing closes the menu");
    }

    #[test]
    fn a_left_click_menu_takes_the_keys_and_esc_closes_it() {
        let mut h = sessions();
        h.click(2, 0);
        h.press("down").press("down").press("enter");
        assert_eq!(h.app().chosen, vec!["notes"]);
        h.click(2, 0);
        assert!(h.screen().contains("build"));
        h.press("esc");
        assert!(!h.screen().contains("build"));
        assert!(h.app().chosen.len() == 1, "esc chooses nothing");
    }

    #[test]
    fn a_second_left_click_on_the_area_closes_and_the_right_click_still_opens() {
        let mut h = sessions();
        h.click(2, 0);
        assert!(h.screen().contains("work"));
        h.click(4, 0);
        assert!(!h.screen().contains("work"), "the item works as a button that shows and hides the menu");
        right_click(&mut h, 2, 0);
        h.click_text("build");
        assert_eq!(h.app().chosen, vec!["build"]);
    }

    /// A status item whose content takes the pointer itself to show a tooltip, as qdesk's does.
    #[derive(Default)]
    struct Hinted {
        chosen: Vec<&'static str>,
    }

    impl App for Hinted {
        type Msg = Msg;
        fn update(&mut self, msg: Msg) -> Command<Msg> {
            if let Msg::Chose(name) = msg {
                self.chosen.push(name);
            }
            Command::none()
        }
        fn view(&self, ui: &mut View<'_, Msg>) {
            let items = [ContextItem::new("work", Msg::Chose("work")), ContextItem::new("notes", Msg::Chose("notes"))];
            ui.column(|ui| {
                ui.add_with(ContextMenu::new(items).on_left_click(true), |ui| {
                    ui.add_with(crate::widgets::Tooltip::new("tmux sessions"), |ui| {
                        ui.add(Text::new("tmux 2"));
                    });
                });
            })
            .fill();
        }
    }

    #[test]
    fn a_second_left_click_closes_even_when_the_item_takes_the_pointer_itself() {
        let mut h = Harness::new(Hinted::default(), 30, 8);
        h.set_reduced_motion(true);
        h.click(2, 0);
        assert!(h.screen().contains("notes"), "the first click opens:\n{}", h.screen());
        h.click(2, 0);
        assert!(!h.screen().contains("notes"), "the second click on the same place closes:\n{}", h.screen());
        h.click(2, 0);
        assert!(h.screen().contains("notes"), "and a third opens again:\n{}", h.screen());
    }

    #[test]
    fn a_left_click_opens_nothing_unless_asked() {
        let mut h = Harness::new(Demo::default(), 40, 12);
        h.set_reduced_motion(true);
        h.click(3, 0);
        assert!(!h.screen().contains("Restart"), "{}", h.screen());
    }

    /// A menu whose rows carry notes: one beside a shortcut, one on a disabled row.
    struct Notes;

    impl App for Notes {
        type Msg = Msg;
        fn update(&mut self, _msg: Msg) -> Command<Msg> {
            Command::none()
        }
        fn view(&self, ui: &mut View<'_, Msg>) {
            let items = [
                ContextItem::new("Open", Msg::Chose("open")),
                ContextItem::new("Compress", Msg::Chose("compress")).detail("slow").shortcut("ctrl k"),
                ContextItem::new("Extract here", Msg::Chose("extract")).detail("bsdtar needed").disabled(true),
            ];
            ui.add_with(ContextMenu::new(items), |ui| {
                ui.add(Text::new("archive.tar"));
            })
            .fill();
        }
    }

    /// The foreground at a cell `find` returned.
    fn fg_at<A: App>(h: &Harness<A>, x: i32, y: i32) -> Option<crate::color::Rgb> {
        h.fg(u16::try_from(x).unwrap(), u16::try_from(y).unwrap())
    }

    fn open_notes(width: u16) -> Harness<Notes> {
        let mut h = Harness::new(Notes, width, 8);
        h.set_reduced_motion(true);
        right_click(&mut h, 0, 0);
        h
    }

    #[test]
    fn a_note_sits_on_the_right_in_the_muted_tone_also_on_a_disabled_row() {
        let h = open_notes(60);
        let screen = h.screen();
        let (x, y) = h.find("bsdtar needed").expect("the note of the disabled row is drawn");
        let muted = h.env().theme().color("muted");
        assert_eq!(fg_at(&h, x, y), muted, "{screen}");
        assert_eq!(fg_at(&h, x + 12, y), muted);
        let line = screen.lines().nth(usize::try_from(y).unwrap()).unwrap();
        assert_eq!(line.trim(), "Extract here    bsdtar needed", "plain text, no brackets: {screen}");
    }

    #[test]
    fn the_shortcut_stays_outermost_with_the_note_before_it() {
        let h = open_notes(60);
        let screen = h.screen();
        let (note_x, y) = h.find("slow").expect("note drawn");
        let (key_x, key_y) = h.find("ctrl k").expect("shortcut drawn");
        assert_eq!(y, key_y);
        assert_eq!(key_x, note_x + 4 + 2, "two cells between the note and the shortcut: {screen}");
        assert_eq!(fg_at(&h, note_x, y), h.env().theme().color("muted"));
        // The shortcut ends where the other rows' notes end: at the menu's right margin.
        let (other_x, _) = h.find("bsdtar needed").expect("note drawn");
        assert_eq!(key_x + 6, other_x + 13, "{screen}");
    }

    #[test]
    fn a_narrow_screen_cuts_the_note_before_the_label() {
        let h = open_notes(24);
        let screen = h.screen();
        assert!(screen.contains("Extract here"), "the label is whole: {screen}");
        assert!(!screen.contains("bsdtar needed"), "{screen}");
        let (x, y) = h.find("bsd").expect("the note is cut, not dropped, while it has room");
        assert!(screen.lines().nth(usize::try_from(y).unwrap()).unwrap().contains('…'), "{screen}");
        assert_eq!(fg_at(&h, x, y), h.env().theme().color("muted"));

        let h = open_notes(18);
        let screen = h.screen();
        assert!(screen.contains("Extract here"), "the label is still whole: {screen}");
        assert!(!screen.contains("bsd"), "with no room left the note goes: {screen}");
    }
}