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
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
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
//! TUI rasteriser for [`crate::Palette`].
//!
//! Modal-style fuzzy picker with a title bar, query-input row, and a
//! scrollable result list. Renders in cell-art glyphs:
//!
//! **List mode** (default):
//! ```text
//! ╭ Title  N/M ──[L]╮
//! │ > query          │
//! ├──────────────────┤
//! │  Item 1          │
//! │  Item 2          │
//! │  Item 3  detail  │
//! ╰──────────────────╯
//! ```
//!
//! **Input mode** (`PaletteMode::Input`):
//! ```text
//! ╭ Title ───────[I]╮
//! │ > free text      │
//! ╰──────────────────╯
//! ```
//!
//! Per-item `match_positions` (byte offsets) get highlighted with
//! [`Theme::match_fg`] for fuzzy-search emphasis.
//!
//! The `[L]` / `[I]` badge in the title bar indicates the active mode;
//! press `Tab` to toggle between modes (keyboard-only).

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

use super::{ratatui_color, set_cell};
use crate::primitives::palette::{Palette, PaletteItemMeasure, PaletteLayout, PaletteMode};
use crate::style::Style;
use crate::theme::Theme;

/// Compute the TUI [`Palette`] layout — the shared geometry this
/// module's [`draw_palette`] paints from and `Backend::palette_layout`
/// exposes for hit-testing, ensuring they remain synchronized.
///
/// Row heights mirror `draw_palette`'s own cell-grid math exactly:
/// title is always 1 row; the query area is 2 rows (query row +
/// separator) when `show_query` and not [`PaletteMode::Input`], 1 row
/// alone in `Input` mode (no separator), 0 rows when `!show_query`; one
/// bottom-border row is reserved by shrinking the viewport height passed
/// to [`Palette::layout`] rather than by title/query height, matching
/// `draw_palette`'s `items_row_end = (y_end - 1) - create_reserved`.
///
/// Coordinate frame: **LOCAL** — `(0, 0)` is `area`'s own top-left
/// corner, matching [`Palette::layout`]'s native contract (same
/// convention `mac_palette_layout` / `win_palette_layout` already use).
///
/// **Scrollbar is deliberately omitted** (`scrollbar_width = 0.0`):
/// TUI paints its scrollbar as a single glyph inside the last item
/// column (`sb_col = list_w - 1`), using a whole-row thumb formula
/// (`thumb_len = visible_rows² / total`) that has no equivalent in
/// [`Palette::layout`]'s continuous-track `PaletteScrollbar` — reporting
/// a `ScrollbarThumb`/`ScrollbarTrack` hit region here would require a
/// different formula for a click target TUI has never made draggable.
/// This is a real, documented gap, not a placeholder.
pub fn tui_palette_layout(area: Rect, palette: &Palette) -> PaletteLayout {
    let w = area.width as f32;
    let h = (area.height as f32 - 1.0).max(0.0); // reserve the bottom border row
    let title_h = 1.0;
    let query_h = if !palette.show_query {
        0.0
    } else if palette.mode == PaletteMode::Input {
        1.0
    } else {
        2.0 // query row + separator row
    };
    palette.layout(w, h, title_h, query_h, 0.0, 1.0, |_| {
        PaletteItemMeasure::new(1.0)
    })
}

/// Draw a [`Palette`] modal into `area` on `buf`, painting with
/// [`Style::default`].
///
/// `nerd_fonts_enabled` selects between item icons' Nerd-Font glyph
/// and ASCII fallback. Caller is responsible for sizing / centring
/// the popup within the editor area.
///
/// Callers that need a live, caller-supplied [`Style`] (backdrop
/// opacity included) go through [`draw_palette_with_style`] instead —
/// this free function's signature is part of the crate's public API and
/// stays fixed so downstream consumers calling it directly don't break;
/// `Backend::draw_palette` implementations call the `_with_style`
/// sibling with their own live style.
pub fn draw_palette(
    buf: &mut Buffer,
    area: Rect,
    palette: &Palette,
    theme: &Theme,
    nerd_fonts_enabled: bool,
) {
    draw_palette_with_style(
        buf,
        area,
        palette,
        theme,
        &Style::default(),
        nerd_fonts_enabled,
    );
}

/// Draw a [`Palette`] modal into `area` on `buf` with an explicit
/// [`Style`] — the live-style counterpart to [`draw_palette`], used by
/// `Backend::draw_palette` implementations.
///
/// `style.backdrop_opacity` controls how translucent the popup's
/// backdrop looks — ratatui's `Buffer` has no compositing primitive, so
/// this pre-blends `theme.background.blend(theme.surface_bg,
/// backdrop_opacity)` on the CPU before writing opaque cells, the same
/// technique [`super::draw_minimap`] already uses to simulate a
/// translucent highlight tint. At the default `1.0` this reproduces
/// `theme.surface_bg` exactly. The blend is against `theme.background`
/// — a static theme token, not whatever content the buffer already
/// holds at those cells — so this is a simulated backdrop tint, not a
/// true read-back-and-composite over live screen content.
pub(crate) fn draw_palette_with_style(
    buf: &mut Buffer,
    area: Rect,
    palette: &Palette,
    theme: &Theme,
    style: &Style,
    nerd_fonts_enabled: bool,
) {
    if area.width < 4 || area.height < 4 {
        return;
    }

    let bg = ratatui_color(
        theme
            .background
            .blend(theme.surface_bg, style.backdrop_opacity as f64),
    );
    let fg = ratatui_color(theme.surface_fg);
    let query_fg = ratatui_color(theme.query_fg);
    let border_fg = ratatui_color(theme.border_fg);
    let title_fg = ratatui_color(theme.title_fg);
    let match_fg = ratatui_color(theme.match_fg);
    let sel_bg = ratatui_color(theme.selected_bg);
    let dim_fg = ratatui_color(theme.muted_fg);

    let x0 = area.x;
    let y0 = area.y;
    let w = area.width;
    let h = area.height;
    let y_end = y0 + h;

    // Clear popup so cycling between pickers with different content
    // lengths doesn't leave stale characters behind.
    for y in y0..y_end {
        for x in x0..x0 + w {
            set_cell(buf, x, y, ' ', fg, bg);
        }
    }

    // ── Mode badge ─────────────────────────────────────────────────────
    // "[L]" or "[I]" appears at the far-right of the title row and acts
    // as a clickable mode-toggle target.
    let badge = match palette.mode {
        PaletteMode::List => "[L]",
        PaletteMode::Input => "[I]",
    };
    let badge_w = badge.chars().count() as u16;

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

    // Paint badge right-aligned inside the title border (before the ╮).
    // Leave one cell gap between badge and ╮: badge starts at w - 1 - badge_w.
    let accent_fg = ratatui_color(theme.accent_fg);
    if w > badge_w + 2 {
        let badge_start = w - 1 - badge_w;
        for (i, ch) in badge.chars().enumerate() {
            set_cell(buf, x0 + badge_start + i as u16, y0, ch, accent_fg, bg);
        }
    }

    // Preview pane splits the popup horizontally when present.
    let has_preview = palette.preview.is_some();
    let list_w = if has_preview {
        ((w as f32) * 0.4).round() as u16
    } else {
        w
    };
    let preview_x0 = x0 + list_w;

    // Query line + separator (skipped when show_query is false).
    let items_row0 = if palette.show_query {
        if h >= 3 {
            let row = y0 + 1;
            set_cell(buf, x0, row, '│', border_fg, bg);
            if w >= 2 {
                set_cell(buf, x0 + w - 1, row, '│', border_fg, bg);
            }
            let prompt = "> ";
            let mut col = 1u16;
            for ch in prompt.chars() {
                if col + 1 >= w {
                    break;
                }
                set_cell(buf, x0 + col, row, ch, query_fg, bg);
                col += 1;
            }
            let query_start = col;
            for ch in palette.query.chars() {
                if col + 1 >= w {
                    break;
                }
                set_cell(buf, x0 + col, row, ch, query_fg, bg);
                col += 1;
            }
            let mut byte = 0usize;
            let mut char_idx = 0usize;
            for ch in palette.query.chars() {
                if byte >= palette.query_cursor {
                    break;
                }
                byte += ch.len_utf8();
                char_idx += 1;
            }
            let cursor_col = query_start + char_idx as u16;
            if cursor_col + 1 < w {
                let ch = palette.query.chars().nth(char_idx).unwrap_or(' ');
                set_cell(buf, x0 + cursor_col, row, ch, bg, query_fg);
            }
        }

        // In Input mode there is no item list, so no separator row.
        if h >= 4 && palette.mode != PaletteMode::Input {
            let row = y0 + 2;
            for col in 0..w {
                let ch = if col == 0 {
                    '├'
                } else if col == w - 1 {
                    '┤'
                } else if has_preview && x0 + col == preview_x0 {
                    '┬'
                } else {
                    '─'
                };
                set_cell(buf, x0 + col, row, ch, border_fg, bg);
            }
        }

        // Input mode: no separator row between query and bottom border.
        if palette.mode == PaletteMode::Input {
            y0 + 2
        } else {
            y0 + 3
        }
    } else {
        y0 + 1
    };

    // ── Input mode: no item list — draw bottom border and return ────────
    if palette.mode == PaletteMode::Input {
        // Fill any gap rows between the query row and the bottom border with
        // side borders (handles the case where the caller gave a taller rect).
        for row in items_row0..y_end - 1 {
            set_cell(buf, x0, row, '│', border_fg, bg);
            if w >= 2 {
                set_cell(buf, x0 + w - 1, row, '│', border_fg, bg);
            }
            for col in 1..w - 1 {
                set_cell(buf, x0 + col, row, ' ', fg, bg);
            }
        }
        // Bottom border.
        let row = y_end - 1;
        for col in 0..w {
            let ch = if col == 0 {
                '╰'
            } else if col == w - 1 {
                '╯'
            } else {
                '─'
            };
            set_cell(buf, x0 + col, row, ch, border_fg, bg);
        }
        return;
    }

    // Result rows.
    let has_create = palette.create_label.is_some();
    let create_reserved = if has_create { 1u16 } else { 0 };
    let items_row_end = (y_end - 1).saturating_sub(create_reserved);
    let visible_rows = items_row_end.saturating_sub(items_row0) as usize;
    let total = palette.items.len();
    let has_scrollbar = total > visible_rows;
    let item_end_col = if has_scrollbar {
        list_w - 1
    } else if has_preview {
        list_w
    } else {
        w - 1
    };

    // The renderer is authoritative for row count: resolve scroll_offset
    // against the row count it just computed, keeping the selected item
    // visible and never leaving empty rows when there are items above we
    // could show. `draw_palette` lays out its own cell grid rather than
    // calling `Palette::layout`, so it calls the shared selection-visibility
    // policy directly through `Palette::resolved_scroll_offset`.
    let resolved_offset = palette.resolved_scroll_offset(visible_rows);

    for (vis_i, item) in palette
        .items
        .iter()
        .enumerate()
        .skip(resolved_offset)
        .take(visible_rows)
    {
        let row = items_row0 + (vis_i - resolved_offset) as u16;
        if row >= items_row_end {
            break;
        }
        let is_selected = vis_i == palette.selected_idx && palette.has_focus;
        let row_bg = if is_selected { sel_bg } else { bg };

        set_cell(buf, x0, row, '│', border_fg, bg);
        if !has_preview && w >= 2 {
            set_cell(buf, x0 + w - 1, row, '│', border_fg, bg);
        }
        for col in 1..item_end_col {
            set_cell(buf, x0 + col, row, ' ', fg, row_bg);
        }

        let mut col = 1u16;

        // Selection prefix (▶ when focused, two spaces otherwise — keeps
        // non-selected text aligned with selected text).
        let prefix = if is_selected { "▶ " } else { "  " };
        for ch in prefix.chars() {
            if col >= item_end_col {
                break;
            }
            set_cell(buf, x0 + col, row, ch, fg, row_bg);
            col += 1;
        }

        // Icon.
        if let Some(ref icon) = item.icon {
            let glyph = if nerd_fonts_enabled {
                icon.glyph.as_str()
            } else {
                icon.fallback.as_str()
            };
            for ch in glyph.chars() {
                if col >= item_end_col {
                    break;
                }
                set_cell(buf, x0 + col, row, ch, fg, row_bg);
                col += 1;
            }
            if col < item_end_col {
                set_cell(buf, x0 + col, row, ' ', fg, row_bg);
                col += 1;
            }
        }

        // Text — per-character match highlighting based on byte offsets.
        let full_text: String = item.text.spans.iter().map(|s| s.text.as_str()).collect();
        let mut byte = 0usize;
        for ch in full_text.chars() {
            if col >= item_end_col {
                break;
            }
            let is_match = item.match_positions.contains(&byte);
            let ch_fg = if is_match { match_fg } else { fg };
            set_cell(buf, x0 + col, row, ch, ch_fg, row_bg);
            col += 1;
            byte += ch.len_utf8();
        }
        let text_end_col = col;

        // Detail (right-aligned, dimmed).
        if let Some(ref detail) = item.detail {
            let detail_text: String = detail.spans.iter().map(|s| s.text.as_str()).collect();
            let detail_w = detail_text.chars().count() as u16;
            if item_end_col > text_end_col + detail_w + 1 {
                let start = item_end_col.saturating_sub(detail_w + 1);
                for (dcol, ch) in (start..).zip(detail_text.chars()) {
                    if dcol >= item_end_col {
                        break;
                    }
                    set_cell(buf, x0 + dcol, row, ch, dim_fg, row_bg);
                }
            }
        }

        // Scrollbar.
        if has_scrollbar {
            let sb_col = list_w - 1;
            let track_len = visible_rows;
            let thumb_len = (visible_rows * visible_rows / total.max(1)).max(1);
            let thumb_start = resolved_offset * track_len / total.max(1);
            let vi_off = vis_i - resolved_offset;
            let in_thumb = vi_off >= thumb_start && vi_off < thumb_start + thumb_len;
            let ch = if in_thumb { '█' } else { '░' };
            set_cell(buf, x0 + sb_col, row, ch, border_fg, bg);
        }
    }

    // Empty rows between last item and bottom border.
    let drawn = total.saturating_sub(resolved_offset).min(visible_rows) as u16;
    for row in items_row0 + drawn..items_row_end {
        set_cell(buf, x0, row, '│', border_fg, bg);
        if !has_preview && w >= 2 {
            set_cell(buf, x0 + w - 1, row, '│', border_fg, bg);
        }
    }

    // ── Create action row (pinned below items) ────────────────────────
    if let Some(ref label) = palette.create_label {
        let create_row = items_row_end;
        if create_row < y_end - 1 {
            let accent_fg = ratatui_color(theme.accent_fg);
            set_cell(buf, x0, create_row, '│', border_fg, bg);
            if !has_preview && w >= 2 {
                set_cell(buf, x0 + w - 1, create_row, '│', border_fg, bg);
            }
            let end_col = if has_preview { list_w } else { w - 1 };
            for col in 1..end_col {
                set_cell(buf, x0 + col, create_row, ' ', fg, bg);
            }
            let prefix = "+ ";
            let mut col = 1u16;
            for ch in prefix.chars() {
                if col >= end_col {
                    break;
                }
                set_cell(buf, x0 + col, create_row, ch, accent_fg, bg);
                col += 1;
            }
            for ch in label.chars() {
                if col >= end_col {
                    break;
                }
                set_cell(buf, x0 + col, create_row, ch, accent_fg, bg);
                col += 1;
            }
        }
    }

    // ── Preview pane ─────────────────────────────────────────────────
    if let Some(ref preview) = palette.preview {
        let sep_col = preview_x0;
        let preview_content_x = sep_col + 1;
        let _preview_w = (x0 + w).saturating_sub(preview_content_x + 1);

        // Vertical separator + right border for all item/preview rows.
        for row in items_row0..items_row_end {
            set_cell(buf, sep_col, row, '│', border_fg, bg);
            set_cell(buf, x0 + w - 1, row, '│', border_fg, bg);
        }

        // Preview title row (reuses separator row area in the preview
        // half, or first content row if no title).
        let mut preview_row0 = items_row0;

        if let Some(ref title_text) = preview.title {
            let row = items_row0;
            if row < items_row_end {
                for col in preview_content_x..x0 + w - 1 {
                    set_cell(buf, col, row, ' ', fg, bg);
                }
                for (col, ch) in (preview_content_x + 1..).zip(title_text.chars()) {
                    if col + 1 >= x0 + w - 1 {
                        break;
                    }
                    set_cell(buf, col, row, ch, dim_fg, bg);
                }
                preview_row0 = items_row0 + 1;
            }
        }

        // Preview content lines.
        let highlight_bg = ratatui_color(theme.selected_bg);
        let preview_visible = items_row_end.saturating_sub(preview_row0) as usize;
        for (vi, line_idx) in (preview.scroll_offset..).take(preview_visible).enumerate() {
            let row = preview_row0 + vi as u16;
            if row >= items_row_end {
                break;
            }
            let is_highlight = preview.highlight_line == Some(line_idx);
            let line_bg = if is_highlight { highlight_bg } else { bg };

            for col in preview_content_x..x0 + w - 1 {
                set_cell(buf, col, row, ' ', fg, line_bg);
            }

            if line_idx < preview.lines.len() {
                let line = &preview.lines[line_idx];
                let mut col = preview_content_x + 1;
                for span in &line.spans {
                    let span_fg = span.fg.map(ratatui_color).unwrap_or(fg);
                    for ch in span.text.chars() {
                        if col + 1 >= x0 + w - 1 {
                            break;
                        }
                        set_cell(buf, col, row, ch, span_fg, line_bg);
                        col += 1;
                    }
                }
            }
        }
    }

    // Bottom border.
    let row = y_end - 1;
    for col in 0..w {
        let ch = if col == 0 {
            '╰'
        } else if col == w - 1 {
            '╯'
        } else if has_preview && x0 + col == preview_x0 {
            '┴'
        } else {
            '─'
        };
        set_cell(buf, x0 + col, row, ch, border_fg, bg);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::primitives::palette::{Palette, PaletteItem};
    use crate::types::{Color, StyledSpan, StyledText, WidgetId};

    fn item(text: &str) -> PaletteItem {
        PaletteItem {
            text: StyledText {
                spans: vec![StyledSpan::plain(text)],
            },
            detail: None,
            icon: None,
            match_positions: Vec::new(),
            depth: 0,
            expandable: false,
            expanded: false,
        }
    }

    fn make_palette() -> Palette {
        Palette {
            id: WidgetId::new("p"),
            title: "Search".into(),
            query: "fo".into(),
            query_cursor: 2,
            items: vec![item("foo"), item("food"), item("foggy")],
            selected_idx: 0,
            scroll_offset: 0,
            has_focus: true,
            show_query: true,
            create_label: None,
            total_count: 3,
            preview: None,
            mode: crate::primitives::palette::PaletteMode::List,
        }
    }

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

    #[test]
    fn paints_top_and_bottom_borders_with_corners() {
        let mut buf = Buffer::empty(Rect::new(0, 0, 20, 10));
        let p = make_palette();
        draw_palette(
            &mut buf,
            Rect::new(0, 0, 20, 10),
            &p,
            &Theme::default(),
            false,
        );
        assert_eq!(cell_char(&buf, 0, 0), '╭');
        assert_eq!(cell_char(&buf, 19, 0), '╮');
        assert_eq!(cell_char(&buf, 0, 9), '╰');
        assert_eq!(cell_char(&buf, 19, 9), '╯');
    }

    #[test]
    fn backdrop_opacity_blends_background_and_surface_bg() {
        let mut buf = Buffer::empty(Rect::new(0, 0, 20, 10));
        let p = make_palette();
        let theme = Theme::default();
        let style = Style::default().with_backdrop_opacity(0.5);
        draw_palette_with_style(&mut buf, Rect::new(0, 0, 20, 10), &p, &theme, &style, false);

        let expected_bg = ratatui_color(theme.background.blend(theme.surface_bg, 0.5));
        // (1, 1) sits inside the border, below the title row and above any
        // query/list content — a cell only ever painted with the blended
        // backdrop fill, never overwritten by a more specific element.
        assert_eq!(buf[(1, 1)].bg, expected_bg);
    }

    #[test]
    fn default_backdrop_opacity_reproduces_surface_bg_exactly() {
        let mut buf = Buffer::empty(Rect::new(0, 0, 20, 10));
        let p = make_palette();
        let theme = Theme::default();
        draw_palette(&mut buf, Rect::new(0, 0, 20, 10), &p, &theme, false);

        assert_eq!(buf[(1, 1)].bg, ratatui_color(theme.surface_bg));
    }

    #[test]
    fn paints_query_with_prompt() {
        let mut buf = Buffer::empty(Rect::new(0, 0, 20, 10));
        let p = make_palette();
        draw_palette(
            &mut buf,
            Rect::new(0, 0, 20, 10),
            &p,
            &Theme::default(),
            false,
        );
        // Query row is y=1; prompt "> " starts at col 1, query "fo" follows.
        let row1: String = (1..6).map(|x| cell_char(&buf, x, 1)).collect();
        assert_eq!(row1, "> fo ");
    }

    #[test]
    fn match_positions_use_match_fg() {
        let mut buf = Buffer::empty(Rect::new(0, 0, 20, 10));
        let mut p = make_palette();
        // Highlight bytes 0 and 2 of "foo".
        p.items[0].match_positions = vec![0, 2];
        let theme = Theme {
            match_fg: Color::rgb(99, 99, 99),
            ..Theme::default()
        };
        draw_palette(&mut buf, Rect::new(0, 0, 20, 10), &p, &theme, false);
        // Items start at row 3. Scan the row's cells for the first 'f' to
        // get the column index in cells (NOT byte offsets — `▶` takes 1
        // cell but 3 bytes when collected into a String).
        let f_col = (0..20)
            .find(|&x| buf[(x, 3u16)].symbol().starts_with('f'))
            .expect("expected 'f' painted in row 3");
        let fg0 = buf[(f_col, 3u16)].fg;
        assert_eq!(fg0, ratatui::style::Color::Rgb(99, 99, 99));
        // 'o' at byte 2 of "foo" → second 'o' → f_col + 2.
        let fg2 = buf[(f_col + 2, 3u16)].fg;
        assert_eq!(fg2, ratatui::style::Color::Rgb(99, 99, 99));
    }

    #[test]
    fn preview_pane_paints_content_and_separator() {
        use crate::primitives::palette::PalettePreview;
        // Wide enough for 40/60 split: 40 cells → list_w=16, preview=24.
        let mut buf = Buffer::empty(Rect::new(0, 0, 40, 12));
        let mut p = make_palette();
        p.preview = Some(PalettePreview {
            lines: vec![
                StyledText::plain("line one"),
                StyledText::plain("line two"),
                StyledText::plain("line three"),
            ],
            title: Some("preview.rs".into()),
            scroll_offset: 0,
            highlight_line: Some(1),
        });
        draw_palette(
            &mut buf,
            Rect::new(0, 0, 40, 12),
            &p,
            &Theme::default(),
            false,
        );
        let list_w = ((40.0_f32) * 0.4).round() as u16; // 16
                                                        // Vertical separator on item rows.
        assert_eq!(cell_char(&buf, list_w, 3), '│');
        // Separator junction on the separator row.
        assert_eq!(cell_char(&buf, list_w, 2), '┬');
        // Bottom border junction.
        assert_eq!(cell_char(&buf, list_w, 11), '┴');
        // Preview title painted (first char of "preview.rs").
        let title_col = list_w + 2;
        assert_eq!(cell_char(&buf, title_col, 3), 'p');
        // Preview content line 0 ("line one") at row 4 (after title).
        let content_row = 4;
        let content_col = list_w + 2;
        assert_eq!(cell_char(&buf, content_col, content_row), 'l');
        // Highlight line (line 1) uses selected_bg.
        let highlight_row = 5;
        let highlight_bg = buf[(content_col, highlight_row)].bg;
        let sel_bg_color = ratatui_color(Theme::default().selected_bg);
        assert_eq!(highlight_bg, sel_bg_color);
    }

    #[test]
    fn preview_pane_respects_scroll_offset() {
        use crate::primitives::palette::PalettePreview;
        let mut buf = Buffer::empty(Rect::new(0, 0, 40, 12));
        let mut p = make_palette();
        p.preview = Some(PalettePreview {
            lines: vec![
                StyledText::plain("line zero"),
                StyledText::plain("line one"),
                StyledText::plain("visible"),
            ],
            title: None,
            scroll_offset: 2,
            highlight_line: None,
        });
        draw_palette(
            &mut buf,
            Rect::new(0, 0, 40, 12),
            &p,
            &Theme::default(),
            false,
        );
        let list_w = ((40.0_f32) * 0.4).round() as u16;
        let content_col = list_w + 2;
        // No title → content starts at items_row0 (row 3).
        // scroll_offset=2 → first visible line is "visible".
        assert_eq!(cell_char(&buf, content_col, 3), 'v');
    }

    #[test]
    fn show_query_false_hides_query_and_separator() {
        let mut buf = Buffer::empty(Rect::new(0, 0, 20, 10));
        let mut p = make_palette();
        p.show_query = false;
        draw_palette(
            &mut buf,
            Rect::new(0, 0, 20, 10),
            &p,
            &Theme::default(),
            false,
        );
        // Row 1 should be items, not the query prompt.
        // With show_query=false, items start at y0+1 (right after title).
        let row1_chars: String = (1..6).map(|x| cell_char(&buf, x, 1)).collect();
        assert_ne!(row1_chars, "> fo ");
        // First item "foo" should appear at row 1 (with selection prefix).
        let has_item = (0..20).any(|x| cell_char(&buf, x, 1) == 'f');
        assert!(has_item, "expected item text at row 1 when query hidden");
        // No separator row (├─┤) should exist at row 2.
        assert_ne!(cell_char(&buf, 0, 2), '├');
    }

    #[test]
    fn create_label_renders_pinned_row() {
        let mut buf = Buffer::empty(Rect::new(0, 0, 30, 10));
        let mut p = make_palette();
        p.create_label = Some("Create 'foo'".into());
        draw_palette(
            &mut buf,
            Rect::new(0, 0, 30, 10),
            &p,
            &Theme::default(),
            false,
        );
        // Create row is pinned at items_row_end (y_end - 1 - 1 = row 8).
        // It should show "+ Create 'foo'" with accent_fg.
        let create_row = 8u16;
        let row_text: String = (1..20).map(|x| cell_char(&buf, x, create_row)).collect();
        assert!(
            row_text.contains("+ Create"),
            "expected create label at pinned row, got: {row_text:?}"
        );
    }

    // ── Rule 6: mode badge position derived from palette state ──────────
    // Verifies that the `[L]` / `[I]` badge is painted at the position
    // predicted by the formula: `badge_start = w - 1 - badge_w` (3 chars).
    #[test]
    fn mode_badge_appears_at_computed_right_side_position() {
        // w=20 → badge_w=3 → badge_start = 20 - 1 - 3 = 16.
        let mut buf = Buffer::empty(Rect::new(0, 0, 20, 8));
        let p = make_palette();
        draw_palette(
            &mut buf,
            Rect::new(0, 0, 20, 8),
            &p,
            &Theme::default(),
            false,
        );
        // List-mode badge "[L]" should appear at columns 16, 17, 18 of row 0.
        assert_eq!(cell_char(&buf, 16, 0), '[', "badge '[' at col 16");
        assert_eq!(cell_char(&buf, 17, 0), 'L', "badge 'L' at col 17");
        assert_eq!(cell_char(&buf, 18, 0), ']', "badge ']' at col 18");

        // Input-mode badge "[I]" at the same columns.
        let mut buf2 = Buffer::empty(Rect::new(0, 0, 20, 8));
        let mut p2 = make_palette();
        p2.mode = crate::primitives::palette::PaletteMode::Input;
        draw_palette(
            &mut buf2,
            Rect::new(0, 0, 20, 8),
            &p2,
            &Theme::default(),
            false,
        );
        assert_eq!(cell_char(&buf2, 16, 0), '[', "input badge '[' at col 16");
        assert_eq!(cell_char(&buf2, 17, 0), 'I', "input badge 'I' at col 17");
        assert_eq!(cell_char(&buf2, 18, 0), ']', "input badge ']' at col 18");
    }

    // ── Input mode: no separator row ─────────────────────────────────────
    // Regression guard for the bug where the ├──┤ separator was painted
    // at row 2 even in Input mode (items_row0 was y0+3 so the early-return
    // fill started at row 3, leaving the separator untouched).
    #[test]
    fn input_mode_no_separator_row_painted() {
        let mut buf = Buffer::empty(Rect::new(0, 0, 20, 8));
        let mut p = make_palette();
        p.mode = crate::primitives::palette::PaletteMode::Input;
        draw_palette(
            &mut buf,
            Rect::new(0, 0, 20, 8),
            &p,
            &Theme::default(),
            false,
        );
        // Row 2 must not carry the ├ separator glyph.
        assert_ne!(
            cell_char(&buf, 0, 2),
            '├',
            "separator must not appear in Input mode"
        );
        // The bottom border must be at row 7 (y_end - 1) regardless of
        // how many rows the caller allocated.
        assert_eq!(cell_char(&buf, 0, 7), '╰', "bottom-left corner at last row");
        assert_eq!(
            cell_char(&buf, 19, 7),
            '╯',
            "bottom-right corner at last row"
        );
        // Row 1 should still have the query prompt.
        assert_eq!(cell_char(&buf, 1, 1), '>', "query prompt in Input mode");
    }

    // Paint into a buffer, find where a glyph actually lands, then
    // hit_test that exact cell and assert it resolves to the region the
    // paint pass used it for, verifying `tui_palette_layout` doesn't drift
    // from `draw_palette`.

    #[test]
    fn layout_title_region_covers_the_painted_title_row() {
        let area = Rect::new(0, 0, 20, 10);
        let p = make_palette();
        let mut buf = Buffer::empty(area);
        draw_palette(&mut buf, area, &p, &Theme::default(), false);
        // Title text painted at row 0 (verified by existing border test).
        let layout = tui_palette_layout(area, &p);
        assert_eq!(
            layout.hit_test(5.0, 0.0),
            crate::primitives::palette::PaletteHit::Title
        );
    }

    #[test]
    fn layout_query_region_covers_the_painted_query_row() {
        let area = Rect::new(0, 0, 20, 10);
        let p = make_palette();
        let mut buf = Buffer::empty(area);
        draw_palette(&mut buf, area, &p, &Theme::default(), false);
        // Query prompt "> " painted at row 1 (see `paints_query_with_prompt`).
        assert_eq!(cell_char(&buf, 1, 1), '>');
        let layout = tui_palette_layout(area, &p);
        assert_eq!(
            layout.hit_test(1.0, 1.0),
            crate::primitives::palette::PaletteHit::Query
        );
    }

    #[test]
    fn layout_item_region_matches_the_painted_item_row() {
        let area = Rect::new(0, 0, 20, 10);
        let p = make_palette();
        let mut buf = Buffer::empty(area);
        draw_palette(&mut buf, area, &p, &Theme::default(), false);
        // First item ("foo") painted at row 3 (items_row0 = y0+3 when
        // show_query and not Input mode).
        assert!((0..20).any(|x| cell_char(&buf, x, 3) == 'f'));
        let layout = tui_palette_layout(area, &p);
        assert_eq!(
            layout.hit_test(5.0, 3.0),
            crate::primitives::palette::PaletteHit::Item(0)
        );
    }

    #[test]
    fn layout_reserves_the_bottom_border_row() {
        let area = Rect::new(0, 0, 20, 10);
        let p = make_palette();
        let layout = tui_palette_layout(area, &p);
        // Row 9 (y_end - 1) is the bottom border in `draw_palette` — no
        // hit region should claim it.
        assert_eq!(
            layout.hit_test(5.0, 9.0),
            crate::primitives::palette::PaletteHit::Empty
        );
    }

    #[test]
    fn layout_input_mode_has_no_separator_row_reserved() {
        let area = Rect::new(0, 0, 20, 8);
        let mut p = make_palette();
        p.mode = crate::primitives::palette::PaletteMode::Input;
        p.items = vec![];
        let layout = tui_palette_layout(area, &p);
        // Query area is 1 row tall in Input mode — row 1 is Query, and
        // there is no dedicated item area to claim row 2.
        assert_eq!(
            layout.hit_test(1.0, 1.0),
            crate::primitives::palette::PaletteHit::Query
        );
    }

    #[test]
    fn too_small_is_a_no_op() {
        let mut buf = Buffer::empty(Rect::new(0, 0, 10, 10));
        let p = make_palette();
        draw_palette(
            &mut buf,
            Rect::new(0, 0, 3, 3),
            &p,
            &Theme::default(),
            false,
        );
        // No corner glyphs anywhere — function returned early.
        for y in 0..10 {
            for x in 0..10 {
                let ch = cell_char(&buf, x, y);
                assert_ne!(ch, '╭');
                assert_ne!(ch, '╯');
            }
        }
    }
}