quadraui 0.6.1

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
//! TUI rasteriser for [`crate::primitives::toolbar::Toolbar`].
//!
//! Paints a single-row strip of `[icon label (key)]` cells with hit
//! zones per `Action`. Separators render as a dim ` │ ` cell; non-
//! clickable `Label` items paint their text in `theme.muted_fg`.
//!
//! ## Per-state colouring
//!
//! Priority (highest first): pressed → hovered → focused → is_active → enabled.
//!
//! | State              | Foreground             | Background          |
//! |--------------------|------------------------|---------------------|
//! | Action, enabled    | `theme.foreground`     | `bar_bg`            |
//! | Action, disabled   | `theme.muted_fg`       | `bar_bg`            |
//! | Action, is_active  | `theme.foreground`     | `theme.selected_bg` |
//! | Action, focused    | `theme.foreground`     | `theme.accent_bg`   |
//! | Action, hovered    | `theme.hover_fg`       | `theme.hover_bg`    |
//! | Action, pressed    | `theme.foreground`     | `theme.selected_bg` |
//! | Separator          | `theme.muted_fg`       | `bar_bg`            |
//! | Label              | `Label.fg` or `muted_fg`| `bar_bg`           |
//!
//! `bar_bg` is `Toolbar.bg.unwrap_or(theme.header_bg)`.
//!
//! Focus is set via [`crate::primitives::toolbar::Toolbar::focused_index`].
//! The host app advances focus with Tab / Shift-Tab and activates with
//! Enter / Space; this rasteriser is purely declarative.

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

use super::text::{char_cell_width, display_width};
use super::{qc, set_cell};
use crate::primitives::toolbar::{
    Toolbar, ToolbarButton, ToolbarItemMeasure, ToolbarLayout, ToolbarPaintOptions, ToolbarVAlign,
};
use crate::theme::Theme;
use crate::types::WidgetId;

/// Resolve which row within `[area.y, area.y + area.height)` button /
/// label text paints on, per `valign`. TUI's own cell-grid
/// twin of [`crate::primitives::toolbar::valign_offset_y`] — kept
/// separate because a terminal row is already a quantized unit, so
/// folding this into the pixel-unit `f32` formula would just re-round
/// it back.
///
/// `Center`'s formula places text on the row above centre for even
/// heights, matching the pixel backends' `(slot_height - content_height) / 2.0`
/// integer-truncating behaviour.
pub(crate) fn tui_text_row(valign: ToolbarVAlign, area: Rect) -> u16 {
    match valign {
        ToolbarVAlign::Top => area.y,
        ToolbarVAlign::Center => area.y + area.height.saturating_sub(1) / 2,
        ToolbarVAlign::Bottom => area.y + area.height.saturating_sub(1),
    }
}

/// Compute the TUI cell-unit width of a single toolbar item.
///
/// Action layout:
/// - icon-only (label empty): `[ {icon} ]` = 4 + icon_w cells
/// - normal: `[ {icon }{label}{ (key)} ]` = 4 + icon_block + label_w + hint_block
///
/// Separator: 2 cells (` │`). Label: text width (double-width aware).
pub(crate) fn tui_item_width(btn: &ToolbarButton) -> f32 {
    match btn {
        ToolbarButton::Action {
            label,
            icon,
            key_hint,
            ..
        } => {
            let label_w = display_width(label);
            let icon_w = icon.as_ref().map(|s| display_width(s)).unwrap_or(0);
            // Icon-only: drop the trailing space after the icon — pack
            // glyph snug between the brackets.
            let icon_block = if icon.is_some() && label_w > 0 {
                icon_w + 1
            } else {
                icon_w
            };
            let hint_w = key_hint
                .as_ref()
                .map(|s| display_width(s) + 3) // " (xxx)"
                .unwrap_or(0);
            // "[ " + icon_block + label + hint_w + " ]"
            (4 + icon_block + label_w + hint_w) as f32
        }
        ToolbarButton::Separator => 2.0,
        ToolbarButton::Label { text, .. } => display_width(text) as f32,
    }
}

/// Compute the layout the rasteriser would produce. No paint side-effects.
pub fn tui_toolbar_layout(bar: &Toolbar, area: Rect) -> ToolbarLayout {
    bar.layout(
        area.x as f32,
        area.y as f32,
        area.width as f32,
        area.height.max(1) as f32,
        |btn| ToolbarItemMeasure::new(tui_item_width(btn)),
    )
}

/// Draw a [`Toolbar`] into `area` on `buf`. Returns the layout for host
/// click dispatch.
///
/// Equivalent to [`draw_toolbar_with_options`] with
/// [`ToolbarPaintOptions::default()`] — kept as a separate, **unchanged**
/// function (rather than growing this one's argument list) so every
/// existing caller of this re-exported `pub fn` keeps compiling
/// untouched. See [`ToolbarPaintOptions`] and `CLAUDE.md`'s *Downstream
/// consumers* rule 2.
pub fn draw_toolbar(
    buf: &mut Buffer,
    area: Rect,
    bar: &Toolbar,
    theme: &Theme,
    hovered_id: Option<&WidgetId>,
    pressed_id: Option<&WidgetId>,
) -> ToolbarLayout {
    draw_toolbar_with_options(
        buf,
        area,
        bar,
        theme,
        hovered_id,
        pressed_id,
        ToolbarPaintOptions::default(),
    )
}

/// [`draw_toolbar`], plus [`ToolbarPaintOptions`]: `options.valign`
/// resolves which row button/label text paints on when
/// `area.height > 1` — see [`tui_text_row`].
pub fn draw_toolbar_with_options(
    buf: &mut Buffer,
    area: Rect,
    bar: &Toolbar,
    theme: &Theme,
    hovered_id: Option<&WidgetId>,
    pressed_id: Option<&WidgetId>,
    options: ToolbarPaintOptions,
) -> ToolbarLayout {
    if area.width == 0 || area.height == 0 {
        // A zero-height area should not produce clickable buttons for a row
        // that was never painted; return an empty layout instead.
        return ToolbarLayout::empty(crate::event::Rect::new(
            area.x as f32,
            area.y as f32,
            area.width as f32,
            area.height as f32,
        ));
    }

    let layout = tui_toolbar_layout(bar, area);

    let bar_bg = qc(bar.bg.unwrap_or(theme.header_bg));
    let fg = qc(theme.foreground);
    let muted = qc(theme.muted_fg);
    let hover_bg = qc(theme.hover_bg);
    let hover_fg = qc(theme.hover_fg);
    let active_bg = qc(theme.selected_bg);
    let focus_bg = qc(theme.accent_bg);

    // Resolve the text row per `options.valign`. On a
    // 1-row slot every variant resolves to `area.y`.
    let text_row = tui_text_row(options.valign, area);

    // Fill every row of the bar background so multi-row hosts (Gap 1)
    // get a uniform-coloured strip rather than 1 row painted + N-1
    // rows of stale buffer.
    for dy in 0..area.height {
        for dx in 0..area.width {
            set_cell(buf, area.x + dx, area.y + dy, ' ', fg, bar_bg);
        }
    }

    for vis in &layout.visible_items {
        let item_x = vis.bounds.x.round() as u16;
        let item_w = vis.bounds.width.round() as u16;
        if item_w == 0 {
            continue;
        }
        let btn = &bar.buttons[vis.item_idx];

        match btn {
            ToolbarButton::Action {
                id,
                label,
                icon,
                key_hint,
                enabled,
                is_active,
                ..
            } => {
                let is_hovered = *enabled && hovered_id == Some(id);
                let is_pressed = *enabled && pressed_id == Some(id);
                let is_focused = *enabled && bar.focused_index == Some(vis.item_idx);
                // Priority: pressed > hovered > focused > is_active > enabled.
                let (cell_fg, cell_bg) = if !*enabled {
                    (muted, bar_bg)
                } else if is_pressed || *is_active {
                    (fg, active_bg)
                } else if is_hovered {
                    (hover_fg, hover_bg)
                } else if is_focused {
                    (fg, focus_bg)
                } else {
                    (fg, bar_bg)
                };

                // Build the rendered cells. Icon-only buttons compact
                // to `[ icon ]` (no trailing space after the icon).
                let label_w = display_width(label);
                let icon_only = icon.is_some() && label_w == 0;
                let mut cells: Vec<char> = Vec::with_capacity(item_w as usize);
                cells.push('[');
                cells.push(' ');
                if let Some(icon) = icon {
                    for ch in icon.chars() {
                        cells.push(ch);
                    }
                    if !icon_only {
                        cells.push(' ');
                    }
                }
                for ch in label.chars() {
                    cells.push(ch);
                }
                if let Some(hint) = key_hint {
                    cells.push(' ');
                    cells.push('(');
                    for ch in hint.chars() {
                        cells.push(ch);
                    }
                    cells.push(')');
                }
                cells.push(' ');
                cells.push(']');

                // Paint background across every row of the item so the
                // hover/active highlight reads as one solid button on
                // multi-row toolbars (Gap 1).
                for dy in 0..area.height {
                    for dx in 0..item_w {
                        set_cell(buf, item_x + dx, area.y + dy, ' ', cell_fg, cell_bg);
                    }
                }

                // Paint text on the vertically-centred row, advancing
                // by the wide-char-aware cell width of each glyph.
                let mut col: u16 = 0;
                for ch in cells {
                    let cw = char_cell_width(ch);
                    if col + cw > item_w {
                        break;
                    }
                    set_cell(buf, item_x + col, text_row, ch, cell_fg, cell_bg);
                    col += cw;
                }
            }
            ToolbarButton::Separator => {
                // 2 cells: ` │`, drawn through every row of the bar so
                // the divider reads as a single full-height rule on
                // multi-row toolbars.
                for dy in 0..area.height {
                    if item_w >= 1 {
                        set_cell(buf, item_x, area.y + dy, ' ', muted, bar_bg);
                    }
                    if item_w >= 2 {
                        set_cell(buf, item_x + 1, area.y + dy, '│', muted, bar_bg);
                    }
                }
            }
            ToolbarButton::Label { text, fg: label_fg } => {
                let color = label_fg.map(qc).unwrap_or(muted);
                let mut col: u16 = 0;
                for ch in text.chars() {
                    let cw = char_cell_width(ch);
                    if col + cw > item_w {
                        break;
                    }
                    set_cell(buf, item_x + col, text_row, ch, color, bar_bg);
                    col += cw;
                }
            }
        }
    }

    layout
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::primitives::toolbar::{ToolbarButton, ToolbarHit};
    use crate::types::WidgetId;

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

    fn mk_action(id: &str, label: &str, enabled: bool) -> ToolbarButton {
        ToolbarButton::Action {
            id: WidgetId::new(id),
            label: label.to_string(),
            icon: None,
            key_hint: None,
            enabled,
            is_active: false,
            tooltip: String::new(),
        }
    }

    #[test]
    fn draws_action_buttons_with_brackets() {
        let area = Rect::new(0, 0, 40, 1);
        let mut buf = Buffer::empty(area);
        let bar = Toolbar {
            id: WidgetId::new("tb"),
            buttons: vec![mk_action("a", "Refine", true)],
            bg: None,
            focused_index: None,
        };
        let _layout = draw_toolbar(&mut buf, area, &bar, &Theme::default(), None, None);
        // First two cells should be `[` then ` `.
        assert_eq!(cell_char(&buf, 0, 0), '[');
        assert_eq!(cell_char(&buf, 1, 0), ' ');
    }

    // Parametrized over the area's origin — LESSONS.md "Layout helpers
    // must return coords in the same frame across backends".
    // `tui_toolbar_layout` bakes `area.x`/`area.y` straight into
    // `bar.layout`'s returned bounds (absolute frame), so the regression
    // guard is a full paint+hit_test round trip re-run at a non-zero
    // origin.
    fn click_round_trip_at(origin_x: u16, origin_y: u16) {
        let area = Rect::new(origin_x, origin_y, 40, 1);
        let mut buf = Buffer::empty(area);
        let bar = Toolbar {
            id: WidgetId::new("tb"),
            buttons: vec![mk_action("a", "Refine", true), mk_action("b", "Drop", true)],
            bg: None,
            focused_index: None,
        };
        let layout = draw_toolbar(&mut buf, area, &bar, &Theme::default(), None, None);
        // Click inside the first button.
        let b = layout.visible_items[0].bounds;
        assert_eq!(
            b.x, origin_x as f32,
            "bounds should be absolute (area.x baked in)"
        );
        assert_eq!(
            b.y, origin_y as f32,
            "bounds should be absolute (area.y baked in)"
        );
        let hit = layout.hit_test(b.x + 1.0, b.y);
        match hit {
            ToolbarHit::Button(id) => assert_eq!(id.as_str(), "a"),
            _ => panic!("expected button-a hit"),
        }
        // Click inside the second.
        let b = layout.visible_items[1].bounds;
        let hit = layout.hit_test(b.x + 1.0, b.y);
        match hit {
            ToolbarHit::Button(id) => assert_eq!(id.as_str(), "b"),
            _ => panic!("expected button-b hit"),
        }
    }

    #[test]
    fn click_round_trip_through_layout() {
        click_round_trip_at(0, 0);
    }

    /// Verify that the same click round trip holds when the toolbar isn't
    /// painted at the screen origin.
    #[test]
    fn click_round_trip_through_layout_at_nonzero_origin() {
        click_round_trip_at(7, 13);
    }

    #[test]
    fn disabled_action_not_clickable_after_paint() {
        let area = Rect::new(0, 0, 40, 1);
        let mut buf = Buffer::empty(area);
        let bar = Toolbar {
            id: WidgetId::new("tb"),
            buttons: vec![mk_action("a", "Refine", false)],
            bg: None,
            focused_index: None,
        };
        let layout = draw_toolbar(&mut buf, area, &bar, &Theme::default(), None, None);
        let b = layout.visible_items[0].bounds;
        assert_eq!(layout.hit_test(b.x + 1.0, b.y), ToolbarHit::Empty);
    }

    #[test]
    fn separator_draws_pipe() {
        let area = Rect::new(0, 0, 40, 1);
        let mut buf = Buffer::empty(area);
        let bar = Toolbar {
            id: WidgetId::new("tb"),
            buttons: vec![ToolbarButton::Separator],
            bg: None,
            focused_index: None,
        };
        let _layout = draw_toolbar(&mut buf, area, &bar, &Theme::default(), None, None);
        // First cell is space, second is the pipe char.
        assert_eq!(cell_char(&buf, 0, 0), ' ');
        assert_eq!(cell_char(&buf, 1, 0), '│');
    }

    #[test]
    fn label_draws_text() {
        let area = Rect::new(0, 0, 40, 1);
        let mut buf = Buffer::empty(area);
        let bar = Toolbar {
            id: WidgetId::new("tb"),
            buttons: vec![ToolbarButton::Label {
                text: "2/5".into(),
                fg: None,
            }],
            bg: None,
            focused_index: None,
        };
        let _layout = draw_toolbar(&mut buf, area, &bar, &Theme::default(), None, None);
        assert_eq!(cell_char(&buf, 0, 0), '2');
        assert_eq!(cell_char(&buf, 1, 0), '/');
        assert_eq!(cell_char(&buf, 2, 0), '5');
    }

    #[test]
    fn zero_size_area_is_noop() {
        let buf_area = Rect::new(0, 0, 10, 1);
        let mut buf = Buffer::empty(buf_area);
        let area = Rect::new(0, 0, 0, 0);
        let bar = Toolbar {
            id: WidgetId::new("tb"),
            buttons: vec![mk_action("a", "X", true)],
            bg: None,
            focused_index: None,
        };
        let layout = draw_toolbar(&mut buf, area, &bar, &Theme::default(), None, None);
        assert_eq!(cell_char(&buf, 0, 0), ' ');
        assert!(layout.visible_items.is_empty());
        assert_eq!(layout.hit_test(0.0, 0.0), ToolbarHit::Empty);
    }

    /// A zero-height area must not produce hit-testable buttons. Even though
    /// `tui_toolbar_layout` forces `bar_height` to `area.height.max(1)`, a
    /// `height == 0` area should return an empty layout with no clickable
    /// buttons, not invisible-but-clickable buttons for a row that was never painted.
    #[test]
    fn zero_height_area_has_no_hit_testable_buttons() {
        let buf_area = Rect::new(0, 0, 10, 1);
        let mut buf = Buffer::empty(buf_area);
        let area = Rect::new(0, 0, 10, 0);
        let bar = Toolbar {
            id: WidgetId::new("tb"),
            buttons: vec![mk_action("a", "X", true)],
            bg: None,
            focused_index: None,
        };
        let layout = draw_toolbar(&mut buf, area, &bar, &Theme::default(), None, None);
        assert!(layout.visible_items.is_empty());
        // Pre-fix, the forced `bar_height.max(1)` row band at y == 0
        // would hit-test the button here even though nothing painted.
        assert_eq!(layout.hit_test(1.0, 0.0), ToolbarHit::Empty);
    }

    // ── Gap 1: multi-row rasteriser ─────────────────────────────────────

    #[test]
    fn multi_row_fills_background_across_all_rows() {
        // 3-row bar with a single action button. Every cell of every
        // row must be painted (not just row 0).
        let area = Rect::new(0, 0, 12, 3);
        let mut buf = Buffer::empty(area);
        let bar = Toolbar {
            id: WidgetId::new("tb"),
            buttons: vec![mk_action("a", "Go", true)],
            bg: None,
            focused_index: None,
        };
        let _ = draw_toolbar(&mut buf, area, &bar, &Theme::default(), None, None);

        // Row 0 (top): button text painted in centre — but the bg
        // outside the button text still fills.
        // Row 1 (middle): button text is here (centred vertically).
        // Row 2 (bottom): background fill only.
        //
        // Pre-Gap-1 behaviour would leave row 1 and row 2 untouched
        // (default Buffer cell symbol = " " but with default colours
        // not the bar's). Use any non-text cell (last column past the
        // button) — it should carry the bar bg every row.
        for y in 0..area.height {
            let cell = &buf[(area.width - 1, y)];
            assert_eq!(
                cell.symbol(),
                " ",
                "row {} last column not background-filled",
                y
            );
        }
    }

    #[test]
    fn multi_row_center_valign_centres_button_text_vertically() {
        // Height 3, `ToolbarVAlign::Center` → text on row 1 (middle).
        let area = Rect::new(0, 0, 12, 3);
        let mut buf = Buffer::empty(area);
        let bar = Toolbar {
            id: WidgetId::new("tb"),
            buttons: vec![mk_action("a", "Go", true)],
            bg: None,
            focused_index: None,
        };
        let options = ToolbarPaintOptions {
            valign: ToolbarVAlign::Center,
        };
        let _ =
            draw_toolbar_with_options(&mut buf, area, &bar, &Theme::default(), None, None, options);
        // Row 1 col 0 should be `[`.
        assert_eq!(cell_char(&buf, 0, 1), '[');
        // Rows 0 and 2 should not have the bracket.
        assert_ne!(cell_char(&buf, 0, 0), '[');
        assert_ne!(cell_char(&buf, 0, 2), '[');
    }

    #[test]
    fn multi_row_default_valign_is_top() {
        // `ToolbarPaintOptions::default()` → `ToolbarVAlign::Top` → text
        // on row 0, padding below (the default).
        let area = Rect::new(0, 0, 12, 3);
        let mut buf = Buffer::empty(area);
        let bar = Toolbar {
            id: WidgetId::new("tb"),
            buttons: vec![mk_action("a", "Go", true)],
            bg: None,
            focused_index: None,
        };
        let _ = draw_toolbar(&mut buf, area, &bar, &Theme::default(), None, None);
        assert_eq!(cell_char(&buf, 0, 0), '[');
        assert_ne!(cell_char(&buf, 0, 1), '[');
        assert_ne!(cell_char(&buf, 0, 2), '[');
    }

    #[test]
    fn multi_row_bottom_valign_puts_text_on_last_row() {
        // `ToolbarVAlign::Bottom` → text on the last row, padding above.
        let area = Rect::new(0, 0, 12, 3);
        let mut buf = Buffer::empty(area);
        let bar = Toolbar {
            id: WidgetId::new("tb"),
            buttons: vec![mk_action("a", "Go", true)],
            bg: None,
            focused_index: None,
        };
        let options = ToolbarPaintOptions {
            valign: ToolbarVAlign::Bottom,
        };
        let _ =
            draw_toolbar_with_options(&mut buf, area, &bar, &Theme::default(), None, None, options);
        assert_eq!(cell_char(&buf, 0, 2), '[');
        assert_ne!(cell_char(&buf, 0, 0), '[');
        assert_ne!(cell_char(&buf, 0, 1), '[');
    }

    #[test]
    fn one_row_slot_every_valign_resolves_identically() {
        // On a 1-row slot there's only one row to paint on — Top,
        // Center, and Bottom must all resolve to it, so this is
        // purely a multi-row concern (per `ToolbarVAlign`'s own doc).
        for valign in [
            ToolbarVAlign::Top,
            ToolbarVAlign::Center,
            ToolbarVAlign::Bottom,
        ] {
            let area = Rect::new(0, 0, 12, 1);
            let mut buf = Buffer::empty(area);
            let bar = Toolbar {
                id: WidgetId::new("tb"),
                buttons: vec![mk_action("a", "Go", true)],
                bg: None,
                focused_index: None,
            };
            let _ = draw_toolbar_with_options(
                &mut buf,
                area,
                &bar,
                &Theme::default(),
                None,
                None,
                ToolbarPaintOptions { valign },
            );
            assert_eq!(cell_char(&buf, 0, 0), '[', "valign={valign:?}");
        }
    }

    #[test]
    fn toolbar_valign_defaults_to_top_when_omitted_from_serde() {
        // An object that omits `valign` must deserialise to `Top`.
        #[derive(serde::Deserialize)]
        struct Wrapper {
            #[serde(default)]
            valign: ToolbarVAlign,
        }
        let w: Wrapper = serde_json::from_str("{}").unwrap();
        assert_eq!(w.valign, ToolbarVAlign::Top);

        // Serialises back to a tagged string the same wrapper can
        // round-trip.
        let json = serde_json::to_string(&ToolbarVAlign::Bottom).unwrap();
        let back: ToolbarVAlign = serde_json::from_str(&json).unwrap();
        assert_eq!(back, ToolbarVAlign::Bottom);
    }

    #[test]
    fn multi_row_click_in_any_row_hits_button() {
        let area = Rect::new(0, 0, 20, 3);
        let mut buf = Buffer::empty(area);
        let bar = Toolbar {
            id: WidgetId::new("tb"),
            buttons: vec![mk_action("a", "Go", true)],
            bg: None,
            focused_index: None,
        };
        let layout = draw_toolbar(&mut buf, area, &bar, &Theme::default(), None, None);
        let r = layout.visible_items[0].bounds;
        // Click in each row of the button bounds — every row should
        // resolve to the button.
        for dy in 0..3 {
            let hit = layout.hit_test(r.x + 1.0, r.y + dy as f32);
            match hit {
                ToolbarHit::Button(ref id) => assert_eq!(id.as_str(), "a"),
                _ => panic!("row {dy} did not hit button"),
            }
        }
    }

    #[test]
    fn multi_row_separator_extends_full_height() {
        let area = Rect::new(0, 0, 10, 3);
        let mut buf = Buffer::empty(area);
        let bar = Toolbar {
            id: WidgetId::new("tb"),
            buttons: vec![ToolbarButton::Separator],
            bg: None,
            focused_index: None,
        };
        let _ = draw_toolbar(&mut buf, area, &bar, &Theme::default(), None, None);
        // The │ glyph should appear on every row at column 1.
        for y in 0..area.height {
            assert_eq!(cell_char(&buf, 1, y), '│', "row {y} missing pipe");
        }
    }

    // ── Gap 4: icon-only buttons + wide-glyph icons ─────────────────────

    #[test]
    fn icon_only_button_compacts_to_three_plus_icon() {
        // Icon-only button: `[ X ]` = 5 cells (4 wrapper + 1-cell icon).
        // The pre-Gap-4 layout would emit `[ X  ]` = 6 cells (trailing
        // space after the icon).
        let area = Rect::new(0, 0, 20, 1);
        let mut buf = Buffer::empty(area);
        let bar = Toolbar {
            id: WidgetId::new("tb"),
            buttons: vec![ToolbarButton::Action {
                id: WidgetId::new("a"),
                label: "".into(),
                icon: Some("X".into()),
                key_hint: None,
                enabled: true,
                is_active: false,
                tooltip: String::new(),
            }],
            bg: None,
            focused_index: None,
        };
        let layout = draw_toolbar(&mut buf, area, &bar, &Theme::default(), None, None);
        assert_eq!(layout.visible_items[0].bounds.width, 5.0);
        // Painted: `[ X ]`
        assert_eq!(cell_char(&buf, 0, 0), '[');
        assert_eq!(cell_char(&buf, 1, 0), ' ');
        assert_eq!(cell_char(&buf, 2, 0), 'X');
        assert_eq!(cell_char(&buf, 3, 0), ' ');
        assert_eq!(cell_char(&buf, 4, 0), ']');
    }

    #[test]
    fn double_width_icon_reserves_two_cells() {
        // CJK or emoji glyphs occupy 2 cells. The measurer must
        // reserve that width so the right bracket lands at the
        // expected column. Use 一 (U+4E00) — explicit 2-cell width.
        let area = Rect::new(0, 0, 20, 1);
        let mut buf = Buffer::empty(area);
        let bar = Toolbar {
            id: WidgetId::new("tb"),
            buttons: vec![ToolbarButton::Action {
                id: WidgetId::new("a"),
                label: "Go".into(),
                icon: Some("一".into()),
                key_hint: None,
                enabled: true,
                is_active: false,
                tooltip: String::new(),
            }],
            bg: None,
            focused_index: None,
        };
        let layout = draw_toolbar(&mut buf, area, &bar, &Theme::default(), None, None);
        // "[ " (2) + icon (2 cells) + " " (1) + "Go" (2) + " ]" (2) = 9
        assert_eq!(layout.visible_items[0].bounds.width, 9.0);
    }
}