quadraui 0.1.8

Cross-platform Rust UI toolkit: write one AppLogic and run it unmodified on TUI, GTK4 (Linux), macOS, and Windows backends
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
//! TUI rasteriser for [`crate::ContextMenu`].
//!
//! Box-bordered popup with one row per item. Selected clickable items
//! render inverted (fg/bg swapped); separators draw as a horizontal
//! dash; disabled items render dimmed. Items with `checked == Some(true)`
//! show a leading `✓` glyph in the row's left-padding column. Items with
//! `submenu.is_some()` show a `▶` glyph at the far-right column instead
//! of a keyboard-shortcut hint. The right-aligned shortcut hint is sourced
//! from `item.detail` if set (back-compat), otherwise from
//! `render_accelerator(item.key_equivalent, Platform::Tui)`.
//!
//! [`draw_context_menu_with_submenus`] extends the basic rasteriser to
//! paint the full stack of open nested (pull-right) submenus in one call.

use ratatui::buffer::Buffer;

use super::{ratatui_color, set_cell};
use crate::accelerator::{render_accelerator, Platform};
use crate::primitives::context_menu::{
    ContextMenu, ContextMenuItem, ContextMenuItemMeasure, ContextMenuLayout, ContextMenuPlacement,
};
use crate::theme::Theme;

/// Returns the right-aligned shortcut text for `item`, sourced from
/// `item.detail` (preferred, back-compat) or rendered from
/// `item.key_equivalent`. Returns `None` if neither is set.
fn shortcut_text(item: &ContextMenuItem, platform: Platform) -> Option<String> {
    if let Some(ref det) = item.detail {
        return det.spans.first().map(|s| s.text.clone());
    }
    item.key_equivalent
        .as_ref()
        .map(|acc| render_accelerator(acc, platform))
}

/// Draw a [`ContextMenu`] popup.
pub fn draw_context_menu(
    buf: &mut Buffer,
    menu: &ContextMenu,
    layout: &ContextMenuLayout,
    theme: &Theme,
) {
    let bg = ratatui_color(theme.tab_bar_bg);
    let fg = ratatui_color(theme.foreground);
    let sep_fg = ratatui_color(theme.muted_fg);
    let dim_fg = ratatui_color(theme.muted_fg);

    let inner_x = layout.bounds.x.round() as u16;
    let inner_y = layout.bounds.y.round() as u16;
    let inner_w = layout.bounds.width.round() as u16;
    let inner_h = layout.bounds.height.round() as u16;
    if inner_w == 0 || inner_h == 0 {
        return;
    }
    // `layout.bounds` is the **inner** items region; we draw the chrome
    // border one cell outside on every side.
    let bx = inner_x.saturating_sub(1);
    let by = inner_y.saturating_sub(1);
    let bw = inner_w + 2;
    let bh = inner_h + 2;

    for dy in 0..bh {
        for dx in 0..bw {
            let cx = bx + dx;
            let cy = by + dy;
            let ch = if dy == 0 {
                if dx == 0 {
                    '┌'
                } else if dx == bw - 1 {
                    '┐'
                } else {
                    '─'
                }
            } else if dy == bh - 1 {
                if dx == 0 {
                    '└'
                } else if dx == bw - 1 {
                    '┘'
                } else {
                    '─'
                }
            } else if dx == 0 || dx == bw - 1 {
                '│'
            } else {
                ' '
            };
            set_cell(buf, cx, cy, ch, fg, bg);
        }
    }

    for vis in &layout.visible_items {
        let item = &menu.items[vis.item_idx];
        let row_y = vis.bounds.y.round() as u16;
        if vis.is_separator {
            for dx in 0..inner_w {
                set_cell(buf, inner_x + dx, row_y, '─', sep_fg, bg);
            }
            continue;
        }
        let is_selected = vis.item_idx == menu.selected_idx;
        let (item_fg, item_bg) = if is_selected && vis.clickable {
            (bg, fg) // inverted
        } else if !vis.clickable {
            (dim_fg, bg)
        } else {
            (fg, bg)
        };
        for dx in 0..inner_w {
            set_cell(buf, inner_x + dx, row_y, ' ', item_fg, item_bg);
        }
        // Check prefix — sits in the left-padding column at inner_x.
        // `Some(false)` reserves the slot without filling it (so a
        // column of mixed checked/unchecked items aligns visually).
        if matches!(item.checked, Some(true)) {
            set_cell(buf, inner_x, row_y, '✓', item_fg, item_bg);
        }
        let label = item
            .label
            .spans
            .first()
            .map(|s| s.text.as_str())
            .unwrap_or("");
        for (i, ch) in label.chars().enumerate() {
            let col = inner_x + 1 + i as u16;
            if col >= inner_x + inner_w {
                break;
            }
            set_cell(buf, col, row_y, ch, item_fg, item_bg);
        }
        if item.submenu.is_some() {
            // Submenu-parent: show ▶ at the far-right column.
            // Keyboard shortcuts are not rendered for submenu parents
            // (they open a child menu rather than dispatching an action).
            let arrow_fg = if is_selected && vis.clickable {
                item_fg
            } else {
                dim_fg
            };
            if inner_w > 0 {
                set_cell(buf, inner_x + inner_w - 1, row_y, '▶', arrow_fg, item_bg);
            }
        } else if let Some(shortcut) = shortcut_text(item, Platform::Tui) {
            let sc_w = shortcut.chars().count() as u16;
            let sc_start = inner_x + inner_w.saturating_sub(sc_w + 1);
            let sc_fg = if is_selected && vis.clickable {
                item_fg
            } else {
                dim_fg
            };
            for (i, ch) in shortcut.chars().enumerate() {
                let col = sc_start + i as u16;
                if col >= inner_x + inner_w {
                    break;
                }
                set_cell(buf, col, row_y, ch, sc_fg, item_bg);
            }
        }
    }
}

#[doc(hidden)]
/// Draw a [`ContextMenu`] and any nested submenus that are currently open
/// within it (cascading submenus anchored to the right of their parent).
///
/// This function operates directly on a raw `ratatui::buffer::Buffer` and
/// bypasses the [`crate::backend::Backend`] trait. It exists as a lower-level
/// building block for unit tests; production rendering goes through
/// [`crate::compose::MenuSystem::render`] → `backend.draw_context_menu()`
/// per level. Consumers should use `MenuSystem::render` instead.
///
/// # Arguments
///
/// * `root_menu` / `root_layout` — the top-level menu, as produced by
///   [`ContextMenu::layout`].
/// * `submenu_path` — depth-first path of open submenus.
///   `submenu_path[0]` = `item_idx` in the root menu whose submenu is open;
///   `submenu_path[1]` = `item_idx` in *that* submenu whose sub-submenu is open;
///   etc. Empty slice → draw only the root.
/// * `selected_at_depth` — `selected_at_depth[d]` = selected item index
///   inside the submenu at depth `d` (depth 0 = first child of root).
/// * `viewport` — full paint surface; used for right-edge overflow detection.
///
/// Each child popup anchors its left edge to the parent popup's right
/// border column. If that would overflow the viewport's right edge the
/// popup flips to the left of the parent instead.
pub fn draw_context_menu_with_submenus(
    buf: &mut Buffer,
    root_menu: &ContextMenu,
    root_layout: &ContextMenuLayout,
    submenu_path: &[usize],
    selected_at_depth: &[usize],
    viewport: crate::event::Rect,
    theme: &Theme,
) {
    draw_context_menu(buf, root_menu, root_layout, theme);

    // Walk the open submenu chain.  We keep owned copies so Rust's borrow
    // checker lets us update `parent_*` at the end of each iteration.
    let mut parent_items: Vec<ContextMenuItem> = root_menu.items.clone();
    let mut parent_bounds = root_layout.bounds;
    let mut parent_vis: Vec<crate::primitives::context_menu::VisibleContextMenuItem> =
        root_layout.visible_items.clone();

    // Fixed geometry per level: 1 cell high per item (TUI cells, not pixels).
    const MENU_WIDTH: f32 = 20.0;

    for (depth, &path_idx) in submenu_path.iter().enumerate() {
        // Resolve submenu items at this depth.
        let sub_items = match parent_items
            .get(path_idx)
            .and_then(|item| item.submenu.clone())
        {
            Some(items) => items,
            None => break,
        };

        // Preferred anchor: right border of parent popup + 1 column.
        // Parent inner right = parent_bounds.x + parent_bounds.width
        // Parent right border column = inner_right (draw_context_menu places it at
        // inner_x + inner_w, i.e. bounds.x + bounds.width).
        // We start the child's inner region one column further right.
        let preferred_x = parent_bounds.x + parent_bounds.width + 1.0;

        // Fallback: flip to the left of the parent popup when the right side
        // would overflow the viewport.
        //   Child inner left = parent_bounds.x - MENU_WIDTH - 1
        //   (the −1 places the child's right border at parent_bounds.x − 1,
        //    leaving the parent's left border intact)
        let flipped_x = parent_bounds.x - MENU_WIDTH - 1.0;

        let anchor_x = if preferred_x + MENU_WIDTH <= viewport.x + viewport.width {
            preferred_x
        } else if flipped_x >= viewport.x {
            flipped_x
        } else {
            // Neither side has enough room — clamp to viewport right.
            (viewport.x + viewport.width - MENU_WIDTH).max(viewport.x)
        };

        // Anchor y = top of the row that triggered this submenu.
        let anchor_y = parent_vis
            .iter()
            .find(|v| v.item_idx == path_idx)
            .map(|v| v.bounds.y)
            .unwrap_or(parent_bounds.y);

        let selected = selected_at_depth.get(depth).copied().unwrap_or(0);

        let sub_menu = ContextMenu {
            id: crate::types::WidgetId::new("tui-submenu"),
            items: sub_items.clone(),
            selected_idx: selected,
            bg: None,
            placement: ContextMenuPlacement::AnchorPoint,
        };

        // In TUI every row (item or separator) is exactly 1 cell tall.
        let sub_layout = sub_menu.layout(anchor_x, anchor_y, viewport, MENU_WIDTH, |_| {
            ContextMenuItemMeasure::new(1.0)
        });

        draw_context_menu(buf, &sub_menu, &sub_layout, theme);

        // Advance to next depth.
        parent_items = sub_items;
        parent_bounds = sub_layout.bounds;
        parent_vis = sub_layout.visible_items;
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::primitives::context_menu::{ContextMenu, ContextMenuItem, ContextMenuItemMeasure};
    use crate::types::{StyledSpan, StyledText, WidgetId};
    use ratatui::layout::Rect;

    fn item(label: &str, clickable: bool) -> ContextMenuItem {
        ContextMenuItem {
            id: if clickable {
                Some(WidgetId::new(label))
            } else {
                None
            },
            label: StyledText {
                spans: vec![StyledSpan::plain(label)],
            },
            disabled: !clickable,
            ..Default::default()
        }
    }

    fn make_menu() -> ContextMenu {
        ContextMenu {
            id: WidgetId::new("menu"),
            items: vec![
                item("Open", true),
                item("Open to Side", true),
                // Separator: id = None.
                ContextMenuItem::default(),
                item("Delete", true),
            ],
            selected_idx: 0,
            bg: None,
            placement: crate::primitives::context_menu::ContextMenuPlacement::default(),
        }
    }

    fn cell_char(buf: &Buffer, x: u16, y: u16) -> char {
        buf[(x, y)].symbol().chars().next().unwrap_or(' ')
    }

    #[test]
    fn paints_corner_glyphs_and_items() {
        let mut buf = Buffer::empty(Rect::new(0, 0, 30, 10));
        let menu = make_menu();
        let layout = menu.layout(
            2.0,
            1.0,
            crate::event::Rect::new(0.0, 0.0, 30.0, 10.0),
            20.0,
            |_| ContextMenuItemMeasure::new(1.0),
        );
        draw_context_menu(&mut buf, &menu, &layout, &Theme::default());

        // Border corners around the inner items region (inset by 1).
        let bx = layout.bounds.x.round() as u16 - 1;
        let by = layout.bounds.y.round() as u16 - 1;
        let bw = layout.bounds.width.round() as u16 + 2;
        let bh = layout.bounds.height.round() as u16 + 2;
        assert_eq!(cell_char(&buf, bx, by), '┌');
        assert_eq!(cell_char(&buf, bx + bw - 1, by), '┐');
        assert_eq!(cell_char(&buf, bx, by + bh - 1), '└');
        assert_eq!(cell_char(&buf, bx + bw - 1, by + bh - 1), '┘');
    }

    #[test]
    fn separator_paints_horizontal_dashes() {
        let mut buf = Buffer::empty(Rect::new(0, 0, 30, 10));
        let menu = make_menu();
        let layout = menu.layout(
            2.0,
            1.0,
            crate::event::Rect::new(0.0, 0.0, 30.0, 10.0),
            20.0,
            |_| ContextMenuItemMeasure::new(1.0),
        );
        draw_context_menu(&mut buf, &menu, &layout, &Theme::default());

        // The third visible item is a separator — find a row that's all '─'.
        let mut found_sep_row = false;
        for vis in &layout.visible_items {
            if vis.is_separator {
                let row_y = vis.bounds.y.round() as u16;
                let inner_x = layout.bounds.x.round() as u16;
                let inner_w = layout.bounds.width.round() as u16;
                let row: String = (inner_x..inner_x + inner_w)
                    .map(|x| cell_char(&buf, x, row_y))
                    .collect();
                assert!(row.chars().all(|c| c == '─'), "separator row: {:?}", row);
                found_sep_row = true;
                break;
            }
        }
        assert!(found_sep_row, "expected at least one separator row");
    }

    #[test]
    fn selected_clickable_inverted() {
        let mut buf = Buffer::empty(Rect::new(0, 0, 30, 10));
        let menu = make_menu(); // selected_idx = 0 → "Open"
        let layout = menu.layout(
            2.0,
            1.0,
            crate::event::Rect::new(0.0, 0.0, 30.0, 10.0),
            20.0,
            |_| ContextMenuItemMeasure::new(1.0),
        );
        let theme = Theme {
            tab_bar_bg: crate::types::Color::rgb(0, 0, 0),
            foreground: crate::types::Color::rgb(255, 255, 255),
            ..Theme::default()
        };
        draw_context_menu(&mut buf, &menu, &layout, &theme);

        // Find the "Open" row's first cell (inner_x). The selected row has
        // inverted bg = foreground colour.
        let inner_x = layout.bounds.x.round() as u16;
        let row_y = layout.visible_items[0].bounds.y.round() as u16;
        let bg = buf[(inner_x, row_y)].bg;
        assert_eq!(bg, ratatui::style::Color::Rgb(255, 255, 255));
    }

    #[test]
    fn checked_item_paints_check_glyph_in_left_padding() {
        use crate::primitives::context_menu::ContextMenuItem;
        let menu = ContextMenu {
            id: WidgetId::new("menu"),
            items: vec![
                ContextMenuItem {
                    id: Some(WidgetId::new("toggle-sidebar")),
                    label: StyledText {
                        spans: vec![StyledSpan::plain("Toggle Sidebar")],
                    },
                    checked: Some(true),
                    ..Default::default()
                },
                ContextMenuItem {
                    id: Some(WidgetId::new("toggle-panel")),
                    label: StyledText {
                        spans: vec![StyledSpan::plain("Toggle Panel")],
                    },
                    checked: Some(false),
                    ..Default::default()
                },
            ],
            selected_idx: 0,
            bg: None,
            placement: crate::primitives::context_menu::ContextMenuPlacement::default(),
        };
        let mut buf = Buffer::empty(Rect::new(0, 0, 30, 10));
        let layout = menu.layout(
            2.0,
            1.0,
            crate::event::Rect::new(0.0, 0.0, 30.0, 10.0),
            20.0,
            |_| ContextMenuItemMeasure::new(1.0),
        );
        draw_context_menu(&mut buf, &menu, &layout, &Theme::default());
        let inner_x = layout.bounds.x.round() as u16;
        let checked_row = layout.visible_items[0].bounds.y.round() as u16;
        assert_eq!(
            cell_char(&buf, inner_x, checked_row),
            '✓',
            "checked=Some(true) item should paint ✓ at inner_x",
        );
        let unchecked_row = layout.visible_items[1].bounds.y.round() as u16;
        assert_eq!(
            cell_char(&buf, inner_x, unchecked_row),
            ' ',
            "checked=Some(false) item should leave the slot blank",
        );
    }

    #[test]
    fn key_equivalent_renders_as_right_aligned_shortcut() {
        // key_equivalent set but detail unset → shortcut text comes
        // from render_accelerator(Platform::Tui).
        use crate::accelerator::{Accelerator, AcceleratorId, AcceleratorScope, KeyBinding};
        use crate::primitives::context_menu::ContextMenuItem;
        let menu = ContextMenu {
            id: WidgetId::new("menu"),
            items: vec![ContextMenuItem {
                id: Some(WidgetId::new("save")),
                label: StyledText {
                    spans: vec![StyledSpan::plain("Save")],
                },
                key_equivalent: Some(Accelerator {
                    id: AcceleratorId::new("editor.save"),
                    binding: KeyBinding::Save,
                    scope: AcceleratorScope::Global,
                    label: None,
                }),
                ..Default::default()
            }],
            selected_idx: 0,
            bg: None,
            placement: crate::primitives::context_menu::ContextMenuPlacement::default(),
        };
        let mut buf = Buffer::empty(Rect::new(0, 0, 30, 10));
        let layout = menu.layout(
            2.0,
            1.0,
            crate::event::Rect::new(0.0, 0.0, 30.0, 10.0),
            20.0,
            |_| ContextMenuItemMeasure::new(1.0),
        );
        draw_context_menu(&mut buf, &menu, &layout, &Theme::default());
        // Platform::Tui renders Save as "Ctrl+S" — look for that suffix
        // near the right edge of the row.
        let inner_x = layout.bounds.x.round() as u16;
        let inner_w = layout.bounds.width.round() as u16;
        let row_y = layout.visible_items[0].bounds.y.round() as u16;
        let row: String = (inner_x..inner_x + inner_w)
            .map(|x| cell_char(&buf, x, row_y))
            .collect();
        assert!(
            row.contains("Ctrl+S"),
            "row should contain rendered key_equivalent: row was {row:?}",
        );
    }

    #[test]
    fn detail_wins_over_key_equivalent_for_back_compat() {
        // Pre-existing apps that set `detail` directly should keep
        // seeing that text — even when key_equivalent is also set.
        use crate::accelerator::{Accelerator, AcceleratorId, AcceleratorScope, KeyBinding};
        use crate::primitives::context_menu::ContextMenuItem;
        let menu = ContextMenu {
            id: WidgetId::new("menu"),
            items: vec![ContextMenuItem {
                id: Some(WidgetId::new("save")),
                label: StyledText {
                    spans: vec![StyledSpan::plain("Save")],
                },
                detail: Some(StyledText {
                    spans: vec![StyledSpan::plain("⌘S-legacy")],
                }),
                key_equivalent: Some(Accelerator {
                    id: AcceleratorId::new("editor.save"),
                    binding: KeyBinding::Save,
                    scope: AcceleratorScope::Global,
                    label: None,
                }),
                ..Default::default()
            }],
            selected_idx: 0,
            bg: None,
            placement: crate::primitives::context_menu::ContextMenuPlacement::default(),
        };
        let mut buf = Buffer::empty(Rect::new(0, 0, 30, 10));
        let layout = menu.layout(
            2.0,
            1.0,
            crate::event::Rect::new(0.0, 0.0, 30.0, 10.0),
            20.0,
            |_| ContextMenuItemMeasure::new(1.0),
        );
        draw_context_menu(&mut buf, &menu, &layout, &Theme::default());
        let inner_x = layout.bounds.x.round() as u16;
        let inner_w = layout.bounds.width.round() as u16;
        let row_y = layout.visible_items[0].bounds.y.round() as u16;
        let row: String = (inner_x..inner_x + inner_w)
            .map(|x| cell_char(&buf, x, row_y))
            .collect();
        assert!(
            row.contains("legacy"),
            "detail string should win over key_equivalent: row was {row:?}",
        );
    }

    #[test]
    fn zero_size_is_a_no_op() {
        let mut buf = Buffer::empty(Rect::new(0, 0, 10, 10));
        let menu = make_menu();
        let layout = menu.layout(
            0.0,
            0.0,
            crate::event::Rect::new(0.0, 0.0, 0.0, 0.0),
            0.0,
            |_| ContextMenuItemMeasure::new(0.0),
        );
        draw_context_menu(&mut buf, &menu, &layout, &Theme::default());
        assert_eq!(cell_char(&buf, 0, 0), ' ');
    }

    // ── Submenu (▶ affordance + pull-right popup) ────────────────────────

    fn submenu_parent_menu() -> ContextMenu {
        use crate::types::{StyledSpan, StyledText, WidgetId};
        let sub_item = ContextMenuItem {
            id: Some(WidgetId::new("sub-a")),
            label: StyledText {
                spans: vec![StyledSpan::plain("SubItem")],
            },
            ..Default::default()
        };
        ContextMenu {
            id: WidgetId::new("menu"),
            items: vec![
                ContextMenuItem {
                    id: Some(WidgetId::new("parent")),
                    label: StyledText {
                        spans: vec![StyledSpan::plain("Parent")],
                    },
                    submenu: Some(vec![sub_item]),
                    ..Default::default()
                },
                ContextMenuItem {
                    id: Some(WidgetId::new("leaf")),
                    label: StyledText {
                        spans: vec![StyledSpan::plain("Leaf")],
                    },
                    ..Default::default()
                },
            ],
            selected_idx: 0,
            bg: None,
            placement: crate::primitives::context_menu::ContextMenuPlacement::default(),
        }
    }

    #[test]
    fn submenu_parent_paints_arrow_affordance() {
        let mut buf = Buffer::empty(Rect::new(0, 0, 40, 10));
        let menu = submenu_parent_menu();
        let layout = menu.layout(
            2.0,
            1.0,
            crate::event::Rect::new(0.0, 0.0, 40.0, 10.0),
            16.0,
            |_| ContextMenuItemMeasure::new(1.0),
        );
        draw_context_menu(&mut buf, &menu, &layout, &Theme::default());

        // The ▶ appears at the rightmost inner column of the parent item's row.
        let inner_x = layout.bounds.x.round() as u16;
        let inner_w = layout.bounds.width.round() as u16;
        let row_y = layout.visible_items[0].bounds.y.round() as u16;
        assert_eq!(
            cell_char(&buf, inner_x + inner_w - 1, row_y),
            '▶',
            "submenu-parent item should show ▶ at rightmost inner column",
        );

        // A plain leaf item (no submenu) must not show ▶.
        let leaf_row_y = layout.visible_items[1].bounds.y.round() as u16;
        assert_ne!(
            cell_char(&buf, inner_x + inner_w - 1, leaf_row_y),
            '▶',
            "plain leaf item must not show ▶",
        );
    }

    #[test]
    fn submenu_popup_anchored_at_right_edge() {
        // Root menu inner at x=2, width=16.
        // Viewport 50 wide — plenty of room to the right.
        // Expected: child inner left = 2 + 16 + 1 = 19.
        //           child left border (┌) at (18, anchor_y − 1).
        let mut buf = Buffer::empty(Rect::new(0, 0, 50, 10));
        let menu = submenu_parent_menu();
        let viewport = crate::event::Rect::new(0.0, 0.0, 50.0, 10.0);
        let layout = menu.layout(2.0, 1.0, viewport, 16.0, |_| {
            ContextMenuItemMeasure::new(1.0)
        });

        // submenu_path = [0] means item 0 (the submenu-parent) is open.
        // selected_at_depth = [0] → first child selected.
        draw_context_menu_with_submenus(
            &mut buf,
            &menu,
            &layout,
            &[0],
            &[0],
            viewport,
            &Theme::default(),
        );

        // Root menu ┌ is at (inner_x − 1, inner_y − 1) = (1, 0).
        assert_eq!(cell_char(&buf, 1, 0), '┌', "root menu top-left corner");

        // Child menu: preferred_x = 2 + 16 + 1 = 19 (inner left).
        // Child left border (┌) at inner_x − 1 = 18.
        // anchor_y = bounds.y of visible_items[0] = 1.0
        // by = anchor_y − 1 = 0.
        assert_eq!(
            cell_char(&buf, 18, 0),
            '┌',
            "child popup top-left corner should be at x=18 (right-edge anchor)",
        );
    }

    #[test]
    fn submenu_overflow_flips_left() {
        // Viewport 50 wide.  Root menu inner at x=25, width=10.
        // preferred_x = 25 + 10 + 1 = 36; 36 + 20 = 56 > 50 → overflow.
        // flipped_x   = 25 − 20 − 1 = 4 ≥ 0 → use 4.
        // Child inner left = 4 → child ┌ at (3, anchor_y − 1).
        let mut buf = Buffer::empty(Rect::new(0, 0, 50, 10));
        let menu = submenu_parent_menu();
        let viewport = crate::event::Rect::new(0.0, 0.0, 50.0, 10.0);
        let layout = menu.layout(25.0, 1.0, viewport, 10.0, |_| {
            ContextMenuItemMeasure::new(1.0)
        });

        draw_context_menu_with_submenus(
            &mut buf,
            &menu,
            &layout,
            &[0],
            &[0],
            viewport,
            &Theme::default(),
        );

        // anchor_y = 1.0, child border-top at y = 0.
        assert_eq!(
            cell_char(&buf, 3, 0),
            '┌',
            "flipped child popup top-left corner should be at x=3 (left-flip)",
        );
    }
}