quadraui 0.6.0

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
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
//! TUI rasteriser for [`crate::Dialog`].
//!
//! Bordered modal popup with a title bar, multi-line body text, an
//! optional input field, and a row (or column) of buttons. Renders
//! with the rounded `╭─╮ ╰─╯` glyphs the TUI has used since the
//! pre-D6 dialog renderer.

use ratatui::buffer::Buffer;
use ratatui::layout::Rect as RRect;

use super::{ratatui_color, set_cell};
use crate::primitives::dialog::{Dialog, DialogInput, DialogLayout, DialogTable};
use crate::primitives::toolbar::ToolbarItemMeasure;
use crate::theme::Theme;
use crate::types::StyledText;

/// Flatten a [`StyledText`] to plain — dialog title + body don't carry
/// per-span style overrides today.
fn flatten(text: &StyledText) -> String {
    text.spans.iter().map(|s| s.text.as_str()).collect()
}

/// Compute the TUI dialog layout using cell metrics.
///
/// Uses the same `tui_item_width` measurer as the toolbar rasteriser so
/// toolbar button positions agree between paint and hit-test.
///
/// This function is TUI's own internal default measurer for dialogs painted
/// without a caller-supplied `DialogMeasure`. `Dialog` is an overlay-with-caller-anchor
/// primitive (like `Tooltip`, `ContextMenu`, `Completions`): callers build their own
/// `DialogMeasure` from portable `Backend::line_height()` and call
/// `dialog.layout(...)` directly. See `quadraui/docs/decisions/DECISIONS.md` D-007.
pub fn tui_dialog_layout(dialog: &Dialog, viewport: crate::event::Rect) -> DialogLayout {
    use super::toolbar::tui_item_width;
    use crate::primitives::dialog::DialogMeasure;

    // Measure body height as number of body lines (capped to a maximum
    // to keep the dialog from filling the whole viewport).
    let body_h = (dialog.body.len() as f32).clamp(0.0, 10.0);

    // Compute table dimensions so we can factor them into the dialog width.
    let (table_h, table_preferred_w) = if let Some(t) = &dialog.table {
        let h = t.tui_total_height() as f32;
        // +2 for the 1-cell padding on each side.
        let w = t.tui_total_width() as f32 + 2.0;
        (h, w)
    } else {
        (0.0, 0.0)
    };

    let input_h = if dialog.input.is_some() { 1.0 } else { 0.0 };

    // Dialog width: at least wide enough for the table content.
    let default_w = (viewport.width * 0.5).clamp(30.0, 60.0);
    let dialog_w = default_w.max(table_preferred_w).min(viewport.width - 4.0);

    let measure = DialogMeasure {
        width: dialog_w,
        title_height: if dialog.title.spans.iter().any(|s| !s.text.is_empty()) {
            1.0
        } else {
            0.0
        },
        body_height: body_h,
        table_height: table_h,
        input_height: input_h,
        button_row_height: 1.0,
        button_width: 8.0,
        button_gap: 2.0,
        padding: 1.0,
    };
    dialog.layout(viewport, measure, |btn| {
        ToolbarItemMeasure::new(tui_item_width(btn))
    })
}

/// Render a [`DialogTable`] inside `bounds`.
///
/// Columns are separated by ` │ `.  When headers are present the first two
/// rows are the header row and a `─┼─` separator.
fn draw_table(
    buf: &mut ratatui::buffer::Buffer,
    table: &DialogTable,
    bounds: &crate::event::Rect,
    fg: ratatui::style::Color,
    bg: ratatui::style::Color,
    border_fg: ratatui::style::Color,
) {
    let col_widths = table.auto_col_widths();
    if col_widths.is_empty() {
        return;
    }
    let ncols = col_widths.len();
    let start_x = bounds.x.round() as u16;
    let start_y = bounds.y.round() as u16;
    let max_w = bounds.width.round() as u16;
    let max_h = bounds.height.round() as u16;

    // Build column x-offsets relative to start_x.
    let mut col_offsets = Vec::with_capacity(ncols);
    let mut cursor = 0u16;
    for (j, &w) in col_widths.iter().enumerate() {
        col_offsets.push(cursor);
        cursor += w as u16;
        if j + 1 < ncols {
            cursor += 3; // " │ "
        }
    }

    let mut row_idx = 0u16;

    // Helper closure to paint one text run.
    let paint_cell = |buf: &mut ratatui::buffer::Buffer,
                      row: u16,
                      col_start: u16,
                      col_max_w: u16,
                      text: &str,
                      text_fg: ratatui::style::Color| {
        let y = start_y + row;
        if y >= start_y + max_h {
            return;
        }
        for (i, ch) in text.chars().enumerate() {
            let x = start_x + col_start + i as u16;
            if x >= start_x + col_start + col_max_w || x >= start_x + max_w {
                break;
            }
            set_cell(buf, x, y, ch, text_fg, bg);
        }
    };

    // Draw column separators (vertical ` │ `) for a given row.
    let paint_separators = |buf: &mut ratatui::buffer::Buffer, row: u16, sep_ch: char| {
        let y = start_y + row;
        if y >= start_y + max_h {
            return;
        }
        for j in 0..ncols.saturating_sub(1) {
            let sep_x = start_x + col_offsets[j] + col_widths[j] as u16 + 1;
            if sep_x < start_x + max_w {
                set_cell(buf, sep_x, y, sep_ch, border_fg, bg);
            }
        }
    };

    if let Some(headers) = &table.headers {
        // Header row.
        for (j, h) in headers.iter().enumerate() {
            if j < ncols {
                paint_cell(buf, row_idx, col_offsets[j], col_widths[j] as u16, h, fg);
            }
        }
        paint_separators(buf, row_idx, '│');
        row_idx += 1;

        // Separator row: ────┼────
        {
            let y = start_y + row_idx;
            if y < start_y + max_h {
                let mut x = start_x;
                for (j, &col_w) in col_widths.iter().enumerate().take(ncols) {
                    let w = col_w as u16;
                    for _ in 0..w {
                        if x < start_x + max_w {
                            set_cell(buf, x, y, '─', border_fg, bg);
                        }
                        x += 1;
                    }
                    if j + 1 < ncols {
                        // space before │
                        if x < start_x + max_w {
                            set_cell(buf, x, y, '─', border_fg, bg);
                        }
                        x += 1;
                        // ┼
                        if x < start_x + max_w {
                            set_cell(buf, x, y, '┼', border_fg, bg);
                        }
                        x += 1;
                        // space after │
                        if x < start_x + max_w {
                            set_cell(buf, x, y, '─', border_fg, bg);
                        }
                        x += 1;
                    }
                }
            }
        }
        row_idx += 1;
    }

    // Data rows.
    for row in &table.rows {
        for (j, cell) in row.iter().enumerate() {
            if j < ncols {
                paint_cell(buf, row_idx, col_offsets[j], col_widths[j] as u16, cell, fg);
            }
        }
        paint_separators(buf, row_idx, '│');
        row_idx += 1;
    }
}

/// Draw a [`Dialog`] at its resolved layout.
pub fn draw_dialog(buf: &mut Buffer, dialog: &Dialog, layout: &DialogLayout, theme: &Theme) {
    let bg = ratatui_color(theme.surface_bg);
    let fg = ratatui_color(theme.surface_fg);
    let sel_bg = ratatui_color(theme.selected_bg);
    let border_fg = ratatui_color(theme.border_fg);
    let title_fg = ratatui_color(theme.title_fg);
    let input_bg = ratatui_color(theme.input_bg);

    let x = layout.bounds.x.round() as u16;
    let y = layout.bounds.y.round() as u16;
    let w = layout.bounds.width.round() as u16;
    let h = layout.bounds.height.round() as u16;
    if w == 0 || h == 0 {
        return;
    }

    // Clear the box area.
    for row in y..y + h {
        for col in x..x + w {
            set_cell(buf, col, row, ' ', fg, bg);
        }
    }

    // Top border with title overlay.
    for col in 0..w {
        let ch = if col == 0 {
            '╭'
        } else if col == w - 1 {
            '╮'
        } else {
            '─'
        };
        set_cell(buf, x + col, y, ch, border_fg, bg);
    }
    let title_text = format!(" {} ", flatten(&dialog.title));
    for (i, ch) in title_text.chars().enumerate() {
        let col = 2 + i as u16;
        if col + 1 >= w {
            break;
        }
        set_cell(buf, x + col, y, ch, title_fg, bg);
    }

    // Left/right borders.
    for row in (y + 1)..(y + h - 1) {
        set_cell(buf, x, row, '│', border_fg, bg);
        set_cell(buf, x + w - 1, row, '│', border_fg, bg);
    }
    // Bottom border.
    for col in 0..w {
        let ch = if col == 0 {
            '╰'
        } else if col == w - 1 {
            '╯'
        } else {
            '─'
        };
        set_cell(buf, x + col, y + h - 1, ch, border_fg, bg);
    }

    // Body text — one StyledText per line.
    let body_x = layout.body_bounds.x.round() as u16;
    let body_y = layout.body_bounds.y.round() as u16;
    let body_w = layout.body_bounds.width.round() as u16;
    for (i, line) in dialog.body.iter().enumerate() {
        let row = body_y + i as u16;
        if row >= body_y + layout.body_bounds.height.round() as u16 {
            break;
        }
        let text = flatten(line);
        for (j, ch) in text.chars().enumerate() {
            let col = body_x + j as u16;
            if col >= body_x + body_w {
                break;
            }
            set_cell(buf, col, row, ch, fg, bg);
        }
    }

    // Optional table slot.
    if let (Some(table_bounds), Some(table)) = (layout.table_bounds, &dialog.table) {
        draw_table(buf, table, &table_bounds, fg, bg, border_fg);
    }

    // Optional input slot — text input or embedded toolbar.
    if let (Some(input_bounds), Some(input_kind)) = (layout.input_bounds, &dialog.input) {
        let ix = input_bounds.x.round() as u16;
        let iy = input_bounds.y.round() as u16;
        let iw = input_bounds.width.round() as u16;
        match input_kind {
            DialogInput::TextInput(input) => {
                for col in ix..ix + iw {
                    set_cell(buf, col, iy, ' ', fg, input_bg);
                }
                let display = format!(" {}", input.value);
                for (i, ch) in display.chars().enumerate() {
                    let col = ix + i as u16;
                    if col >= ix + iw {
                        break;
                    }
                    set_cell(buf, col, iy, ch, fg, input_bg);
                }
            }
            DialogInput::Toolbar(toolbar) => {
                // Delegate to the toolbar rasteriser. The toolbar layout
                // was precomputed in `body_toolbar_layout`; we reconstruct
                // the area rect from the input_bounds so draw_toolbar can
                // repaint with hover/pressed state if the caller provides
                // it. For the dialog paint path we pass `None` for both.
                let toolbar_area = RRect::new(ix, iy, iw, 1);
                super::toolbar::draw_toolbar(buf, toolbar_area, toolbar, theme, None, None);
            }
        }
    }

    // Buttons — default-button gets a `selected_bg` highlight.
    for vis in &layout.visible_buttons {
        let btn = &dialog.buttons[vis.button_idx];
        let bx = vis.bounds.x.round() as u16;
        let by = vis.bounds.y.round() as u16;
        let bw = vis.bounds.width.round() as u16;
        let btn_bg = if btn.is_default { sel_bg } else { bg };
        for col in bx..bx + bw {
            set_cell(buf, col, by, ' ', fg, btn_bg);
        }
        let label_w = btn.label.chars().count() as u16;
        // Vertical button lists (e.g. the repo picker) read as a left-justified
        // menu; horizontal action rows keep their centred labels.
        let start = if dialog.vertical_buttons {
            bx + 1
        } else {
            bx + (bw.saturating_sub(label_w)) / 2
        };
        for (i, ch) in btn.label.chars().enumerate() {
            let col = start + i as u16;
            if col >= bx + bw {
                break;
            }
            set_cell(buf, col, by, ch, fg, btn_bg);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::primitives::dialog::{Dialog, DialogButton, DialogMeasure, DialogTextInput};
    use crate::types::{StyledSpan, WidgetId};
    use ratatui::layout::Rect;

    fn make_dialog() -> Dialog {
        Dialog {
            id: WidgetId::new("d"),
            title: StyledText {
                spans: vec![StyledSpan::plain("Confirm")],
            },
            body: vec![StyledText {
                spans: vec![StyledSpan::plain("Save before quitting?")],
            }],
            buttons: vec![
                DialogButton {
                    id: WidgetId::new("save"),
                    label: "Save".into(),
                    is_default: true,
                    is_cancel: false,
                    tint: None,
                },
                DialogButton {
                    id: WidgetId::new("cancel"),
                    label: "Cancel".into(),
                    is_default: false,
                    is_cancel: true,
                    tint: None,
                },
            ],
            severity: None,
            vertical_buttons: false,
            table: None,
            input: None,
        }
    }

    fn make_layout(dialog: &Dialog) -> DialogLayout {
        let measure = DialogMeasure {
            width: 40.0,
            title_height: 1.0,
            body_height: 2.0,
            table_height: 0.0,
            input_height: 0.0,
            button_row_height: 1.0,
            button_width: 8.0,
            button_gap: 2.0,
            padding: 1.0,
        };
        let viewport = crate::event::Rect::new(0.0, 0.0, 80.0, 30.0);
        dialog.layout(viewport, measure, |_| ToolbarItemMeasure::new(0.0))
    }

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

    #[test]
    fn paints_corner_glyphs_and_title() {
        let mut buf = Buffer::empty(Rect::new(0, 0, 80, 30));
        let d = make_dialog();
        let layout = make_layout(&d);
        draw_dialog(&mut buf, &d, &layout, &Theme::default());

        let bx = layout.bounds.x.round() as u16;
        let by = layout.bounds.y.round() as u16;
        let bw = layout.bounds.width.round() as u16;
        let bh = layout.bounds.height.round() as u16;

        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 default_button_has_selected_bg() {
        let mut buf = Buffer::empty(Rect::new(0, 0, 80, 30));
        let d = make_dialog();
        let layout = make_layout(&d);
        let theme = Theme {
            selected_bg: crate::types::Color::rgb(99, 0, 0),
            ..Theme::default()
        };
        draw_dialog(&mut buf, &d, &layout, &theme);

        // The first visible button is "Save" (is_default).
        let vis = &layout.visible_buttons[0];
        let bx = vis.bounds.x.round() as u16;
        let by = vis.bounds.y.round() as u16;
        let bg = buf[(bx, by)].bg;
        assert_eq!(bg, ratatui::style::Color::Rgb(99, 0, 0));
    }

    #[test]
    fn renders_input_field_when_present() {
        let mut buf = Buffer::empty(Rect::new(0, 0, 80, 30));
        let mut d = make_dialog();
        d.input = Some(crate::primitives::dialog::DialogInput::TextInput(
            crate::primitives::dialog::DialogTextInput {
                value: "hello".into(),
                placeholder: String::new(),
                cursor: Some(5),
            },
        ));
        let measure = DialogMeasure {
            width: 40.0,
            title_height: 1.0,
            body_height: 2.0,
            table_height: 0.0,
            input_height: 1.0,
            button_row_height: 1.0,
            button_width: 8.0,
            button_gap: 2.0,
            padding: 1.0,
        };
        let viewport = crate::event::Rect::new(0.0, 0.0, 80.0, 30.0);
        let layout = d.layout(viewport, measure, |_| ToolbarItemMeasure::new(0.0));
        let theme = Theme {
            input_bg: crate::types::Color::rgb(7, 7, 7),
            ..Theme::default()
        };
        draw_dialog(&mut buf, &d, &layout, &theme);

        // Input bounds carry input_bg as the row's bg.
        let ib = layout.input_bounds.expect("input bounds present");
        let bg = buf[(ib.x.round() as u16, ib.y.round() as u16)].bg;
        assert_eq!(bg, ratatui::style::Color::Rgb(7, 7, 7));
    }

    #[test]
    fn zero_size_is_a_no_op() {
        let mut buf = Buffer::empty(Rect::new(0, 0, 80, 30));
        let d = make_dialog();
        // Use a zero-size viewport so the layout collapses.
        let measure = DialogMeasure {
            width: 0.0,
            title_height: 0.0,
            body_height: 0.0,
            table_height: 0.0,
            input_height: 0.0,
            button_row_height: 0.0,
            button_width: 0.0,
            button_gap: 0.0,
            padding: 0.0,
        };
        let viewport = crate::event::Rect::new(0.0, 0.0, 0.0, 0.0);
        let layout = d.layout(viewport, measure, |_| ToolbarItemMeasure::new(0.0));
        draw_dialog(&mut buf, &d, &layout, &Theme::default());
        assert_eq!(cell_char(&buf, 0, 0), ' ');
    }

    // ── Gap A: DialogInput::Toolbar paint↔click round-trip ───────────────

    use crate::primitives::dialog::{DialogHit, DialogInput};
    use crate::primitives::toolbar::{Toolbar, ToolbarButton};

    fn make_toolbar_dialog() -> Dialog {
        Dialog {
            id: WidgetId::new("migrate"),
            title: StyledText {
                spans: vec![StyledSpan::plain("Confirm migration")],
            },
            body: vec![StyledText {
                spans: vec![StyledSpan::plain("Choose an action:")],
            }],
            buttons: vec![DialogButton {
                id: WidgetId::new("ok"),
                label: "OK".into(),
                is_default: true,
                is_cancel: false,
                tint: None,
            }],
            severity: None,
            vertical_buttons: false,
            table: None,
            input: Some(DialogInput::Toolbar(Toolbar {
                id: WidgetId::new("body-toolbar"),
                buttons: vec![
                    ToolbarButton::Action {
                        id: WidgetId::new("preview"),
                        label: "Preview".into(),
                        icon: None,
                        key_hint: None,
                        enabled: true,
                        is_active: false,
                        tooltip: String::new(),
                    },
                    ToolbarButton::Separator,
                    ToolbarButton::Action {
                        id: WidgetId::new("apply"),
                        label: "Apply".into(),
                        icon: None,
                        key_hint: None,
                        enabled: true,
                        is_active: false,
                        tooltip: String::new(),
                    },
                ],
                bg: None,
                focused_index: None,
            })),
        }
    }

    #[test]
    fn body_toolbar_paints_button_brackets() {
        let d = make_toolbar_dialog();
        let viewport = crate::event::Rect::new(0.0, 0.0, 80.0, 30.0);
        let layout = tui_dialog_layout(&d, viewport);
        let mut buf = Buffer::empty(Rect::new(0, 0, 80, 30));
        draw_dialog(&mut buf, &d, &layout, &Theme::default());

        // The input_bounds slot should be set.
        assert!(
            layout.input_bounds.is_some(),
            "input_bounds should be Some for Toolbar variant"
        );
        assert!(
            layout.body_toolbar_layout.is_some(),
            "body_toolbar_layout should be Some"
        );

        // The toolbar should have painted `[` somewhere inside the dialog.
        let ib = layout.input_bounds.unwrap();
        let start_y = ib.y.round() as u16;
        let start_x = ib.x.round() as u16;
        let end_x = (ib.x + ib.width).round() as u16;

        let mut found_bracket = false;
        for x in start_x..end_x {
            if cell_char(&buf, x, start_y) == '[' {
                found_bracket = true;
                break;
            }
        }
        assert!(
            found_bracket,
            "toolbar `[` bracket should be painted in body slot"
        );
    }

    /// Shared body for `body_toolbar_click_routes_to_body_toolbar_button[_at_nonzero_origin]`:
    /// `tui_dialog_layout` bakes `viewport.x`/`viewport.y` into `Dialog::layout`'s
    /// `box_x`/`box_y` (absolute frame), so paint + click must agree at a
    /// non-zero viewport origin too, per LESSONS.md's "layout helpers must
    /// return coords in the same frame across backends". The
    /// dialog is centered in an 80×30 viewport and never exceeds ~60×30, so
    /// a buffer sized to the viewport's far corner (`origin + 80/30`) always
    /// has room for it.
    fn body_toolbar_click_routes_to_body_toolbar_button_at(origin_x: f32, origin_y: f32) {
        let d = make_toolbar_dialog();
        let viewport = crate::event::Rect::new(origin_x, origin_y, 80.0, 30.0);
        let layout = tui_dialog_layout(&d, viewport);
        let buf_w = (origin_x + 80.0).ceil() as u16;
        let buf_h = (origin_y + 30.0).ceil() as u16;
        let mut buf = Buffer::empty(Rect::new(0, 0, buf_w, buf_h));
        draw_dialog(&mut buf, &d, &layout, &Theme::default());

        let tl = layout
            .body_toolbar_layout
            .as_ref()
            .expect("toolbar layout present");
        // Find the "Preview" button in the toolbar layout.
        let preview_vis = tl
            .visible_items
            .iter()
            .find(|v| v.action_id.as_ref().map(|id| id.as_str()) == Some("preview"))
            .expect("preview button visible");
        assert!(preview_vis.clickable, "preview should be clickable");

        // Click inside the "Preview" button bounds.
        let cx = preview_vis.bounds.x + 1.0;
        let cy = preview_vis.bounds.y;
        match layout.hit_test(cx, cy) {
            DialogHit::BodyToolbarButton(id) => {
                assert_eq!(id.as_str(), "preview");
            }
            other => panic!("expected BodyToolbarButton(preview), got {:?}", other),
        }
    }

    #[test]
    fn body_toolbar_click_routes_to_body_toolbar_button() {
        body_toolbar_click_routes_to_body_toolbar_button_at(0.0, 0.0);
    }

    #[test]
    fn body_toolbar_click_routes_to_body_toolbar_button_at_nonzero_origin() {
        body_toolbar_click_routes_to_body_toolbar_button_at(7.0, 13.0);
    }

    /// Shared body for `body_toolbar_apply_button_also_routes[_at_nonzero_origin]`
    /// — see `body_toolbar_click_routes_to_body_toolbar_button_at` for the
    /// non-zero-origin rationale.
    fn body_toolbar_apply_button_also_routes_at(origin_x: f32, origin_y: f32) {
        let d = make_toolbar_dialog();
        let viewport = crate::event::Rect::new(origin_x, origin_y, 80.0, 30.0);
        let layout = tui_dialog_layout(&d, viewport);

        let tl = layout
            .body_toolbar_layout
            .as_ref()
            .expect("toolbar layout present");
        let apply_vis = tl
            .visible_items
            .iter()
            .find(|v| v.action_id.as_ref().map(|id| id.as_str()) == Some("apply"))
            .expect("apply button visible");

        let cx = apply_vis.bounds.x + 1.0;
        let cy = apply_vis.bounds.y;
        match layout.hit_test(cx, cy) {
            DialogHit::BodyToolbarButton(id) => {
                assert_eq!(id.as_str(), "apply");
            }
            other => panic!("expected BodyToolbarButton(apply), got {:?}", other),
        }
    }

    #[test]
    fn body_toolbar_apply_button_also_routes() {
        body_toolbar_apply_button_also_routes_at(0.0, 0.0);
    }

    #[test]
    fn body_toolbar_apply_button_also_routes_at_nonzero_origin() {
        body_toolbar_apply_button_also_routes_at(7.0, 13.0);
    }

    // ── Serde round-trip for DialogInput::Toolbar ─────────────────────────

    #[test]
    fn serde_roundtrip_dialog_input_toolbar() {
        use crate::types::WidgetId;
        let input = DialogInput::Toolbar(Toolbar {
            id: WidgetId::new("tb"),
            buttons: vec![
                ToolbarButton::Action {
                    id: WidgetId::new("preview"),
                    label: "Preview".into(),
                    icon: None,
                    key_hint: None,
                    enabled: true,
                    is_active: false,
                    tooltip: String::new(),
                },
                ToolbarButton::Separator,
            ],
            bg: None,
            focused_index: None,
        });
        let json = serde_json::to_string(&input).unwrap();
        let back: DialogInput = serde_json::from_str(&json).unwrap();
        assert_eq!(input, back);
    }

    #[test]
    fn serde_roundtrip_dialog_input_text_input() {
        let input = DialogInput::TextInput(DialogTextInput {
            value: "hello".into(),
            placeholder: "placeholder".into(),
            cursor: Some(5),
        });
        let json = serde_json::to_string(&input).unwrap();
        let back: DialogInput = serde_json::from_str(&json).unwrap();
        assert_eq!(input, back);
    }
}