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
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
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
//! `SidebarPanel` primitive: a vertical container with an optional
//! [`Toolbar`] header at the top + a content region beneath that the
//! host paints into.
//!
//! Solves the "panel-with-toolbar" composition gap surfaced in #259.
//! Hosts that wanted a sidebar with a clickable action header used to
//! carve a top rect by hand, paint a `Toolbar` into it, remember to
//! always reserve the slot (so content didn't shift when the toolbar
//! came/went), and hit-test the bar manually before falling through
//! to content. That coordination — paint + hit-test + layout-reserve
//! — is the easy-to-get-wrong part this primitive owns.
//!
//! ## Why "SidebarPanel" and not "Sidebar"
//!
//! The compose layer already exports a `SidebarEvent` enum tied to
//! the multi-section [`crate::SidebarSystem`]. Adding a `Sidebar`
//! primitive with its own `SidebarEvent` would collide at the lib
//! re-export boundary. `SidebarPanel` reads correctly at consumer
//! use sites (each panel IS a sidebar panel) and keeps the names
//! disjoint.
//!
//! ## Shape
//!
//! - `toolbar`:
//!   - `None`: no slot reserved. Content occupies the full rect.
//!   - `Some(bar)`: header slot reserved at `toolbar_height`. Reserved
//!     *even when `bar.buttons.is_empty()`*, so content below doesn't
//!     shift as toolbar items come and go (a bug a consumer app hit
//!     when toolbar appearance was state-dependent).
//! - `toolbar_height`: optional explicit height in native units. When
//!   `None`, backends pick an idiomatic default (`1.0` cells TUI,
//!   `line_height` GTK / macOS).
//!
//! ## Backend contract
//!
//! Each backend renders the toolbar into the header slot and **does
//! not paint the content region** — the content rect is returned in
//! `SidebarPanelLayout.content_bounds` for the host to paint into
//! (typically a tree, list, form, etc.). This is the same pattern
//! [`crate::Panel`] uses for its content region.
//!
//! Hit-test:
//! - Click inside the toolbar slot routes via the nested
//!   `ToolbarLayout::hit_test` to a [`SidebarPanelHit::ToolbarButton`]
//!   or, for misses inside the slot,
//!   [`SidebarPanelHit::ToolbarEmpty`].
//! - Click inside the content rect produces
//!   [`SidebarPanelHit::Content`] with content-local coordinates.
//! - Click outside both produces [`SidebarPanelHit::Empty`].

use crate::event::Rect;
use crate::primitives::toolbar::{Toolbar, ToolbarHit, ToolbarItemMeasure, ToolbarLayout};
use crate::types::WidgetId;
use serde::{Deserialize, Serialize};

// ── Data model ───────────────────────────────────────────────────────────────

/// Vertical container: optional header toolbar + content region.
///
/// # Examples
///
/// ```
/// use quadraui::{
///     Rect, SidebarPanel, SidebarPanelHit, SidebarPanelMeasure, ToolbarItemMeasure, WidgetId,
/// };
///
/// let panel = SidebarPanel {
///     id: WidgetId::new("sidebar:explorer"),
///     toolbar: None,
///     toolbar_height: None,
/// };
///
/// let bounds = Rect::new(0.0, 0.0, 40.0, 20.0);
/// let measure = SidebarPanelMeasure::new(1.0, 3.0);
/// // `toolbar` is `None` above, so `layout` never calls this closure — it's
/// // only reached when a toolbar slot is reserved.
/// let layout = panel.layout(bounds, measure, |_| ToolbarItemMeasure::new(10.0));
///
/// // No toolbar means no slot reserved — content gets the full rect.
/// assert_eq!(layout.content_bounds, bounds);
/// assert_eq!(layout.hit_test(1.0, 1.0), SidebarPanelHit::Content { x: 1.0, y: 1.0 });
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SidebarPanel {
    pub id: WidgetId,
    /// Optional header toolbar. When `None` the slot is **not**
    /// reserved (content gets the full rect). When `Some`, the slot
    /// is always reserved at `toolbar_height` even if `buttons` is
    /// empty — so content below doesn't shift as buttons appear /
    /// disappear.
    #[serde(default)]
    pub toolbar: Option<Toolbar>,
    /// Reserved height for the toolbar slot in native units. When
    /// `None`, backends pick an idiomatic default (1 cell TUI,
    /// `line_height` GTK / macOS).
    #[serde(default)]
    pub toolbar_height: Option<f32>,
}

// ── Layout + hit-testing ─────────────────────────────────────────────────────

/// Fully-resolved layout for a [`SidebarPanel`].
#[derive(Debug, Clone, PartialEq)]
pub struct SidebarPanelLayout {
    /// Bounds of the entire panel as given to `layout()`.
    pub panel_bounds: Rect,
    /// Bounds of the toolbar slot. `None` when the panel has no
    /// toolbar (slot wasn't reserved). When `Some`, this rect is
    /// reserved even if the toolbar has no buttons.
    pub toolbar_bounds: Option<Rect>,
    /// Bounds of the content area. Always populated — equals the
    /// panel minus the toolbar slot.
    pub content_bounds: Rect,
    /// Resolved inner toolbar layout. `None` mirrors `toolbar_bounds`.
    pub toolbar_layout: Option<ToolbarLayout>,
}

/// Classification of a hit-test result on a [`SidebarPanel`].
#[derive(Debug, Clone, PartialEq)]
pub enum SidebarPanelHit {
    /// Click landed on a clickable toolbar button — carries its id.
    ToolbarButton(WidgetId),
    /// Click landed inside the toolbar slot but not on a clickable
    /// button (gap, separator, label, or disabled action).
    ToolbarEmpty,
    /// Click landed inside the content area. `(x, y)` are
    /// **content-local** — relative to `content_bounds.x` / `.y`.
    Content { x: f32, y: f32 },
    /// Click missed both the toolbar slot and the content area
    /// (outside the panel entirely).
    Empty,
}

impl SidebarPanelLayout {
    /// Test point `(x, y)` against the layout. Toolbar slot wins over
    /// the content area when bounds overlap (which they shouldn't —
    /// `layout()` carves disjoint rects — but the precedence is
    /// documented in case future relaxations of that invariant break
    /// it).
    pub fn hit_test(&self, x: f32, y: f32) -> SidebarPanelHit {
        if let (Some(tb), Some(tlayout)) = (self.toolbar_bounds, &self.toolbar_layout) {
            if contains(tb, x, y) {
                return match tlayout.hit_test(x, y) {
                    ToolbarHit::Button(id) => SidebarPanelHit::ToolbarButton(id),
                    ToolbarHit::Empty => SidebarPanelHit::ToolbarEmpty,
                };
            }
        }
        if contains(self.content_bounds, x, y) {
            return SidebarPanelHit::Content {
                x: x - self.content_bounds.x,
                y: y - self.content_bounds.y,
            };
        }
        SidebarPanelHit::Empty
    }
}

fn contains(r: Rect, x: f32, y: f32) -> bool {
    x >= r.x && x < r.x + r.width && y >= r.y && y < r.y + r.height
}

// ── Measurement ──────────────────────────────────────────────────────────────

/// Caller-supplied measurements for computing a
/// [`SidebarPanelLayout`].
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct SidebarPanelMeasure {
    /// Default header height when `SidebarPanel.toolbar_height` is
    /// `None`. Use `1.0` for TUI cells, `line_height` for native.
    pub default_toolbar_height: f32,
    /// Per-toolbar-item width in native units — passed through to the
    /// nested `Toolbar::layout`. Backends supply the same measurer
    /// they would use for a standalone toolbar in the same rect.
    pub item_width: f32,
}

impl SidebarPanelMeasure {
    pub fn new(default_toolbar_height: f32, item_width: f32) -> Self {
        Self {
            default_toolbar_height,
            item_width,
        }
    }
}

impl SidebarPanel {
    /// Compute the full layout for this panel.
    ///
    /// `measure_item` is the per-toolbar-item width measurer. It
    /// receives each `ToolbarButton` and returns its width in the
    /// caller's native unit — TUI passes a cell-count measurer, GTK
    /// passes a Pango pixel measurer. When the panel has no toolbar
    /// the closure is never invoked.
    pub fn layout<F>(
        &self,
        bounds: Rect,
        measure: SidebarPanelMeasure,
        measure_item: F,
    ) -> SidebarPanelLayout
    where
        F: Fn(&crate::primitives::toolbar::ToolbarButton) -> ToolbarItemMeasure,
    {
        let toolbar_height = self
            .toolbar_height
            .unwrap_or(measure.default_toolbar_height);

        match &self.toolbar {
            Some(bar) => {
                // Reserve the slot even when `bar.buttons.is_empty()`
                // so content doesn't shift as toolbar items come and
                // go (a bug a consumer app hit twice).
                let slot_height = toolbar_height.min(bounds.height).max(0.0);
                let toolbar_bounds = Rect::new(bounds.x, bounds.y, bounds.width, slot_height);
                let content_y = bounds.y + slot_height;
                let content_h = (bounds.height - slot_height).max(0.0);
                let content_bounds = Rect::new(bounds.x, content_y, bounds.width, content_h);

                let toolbar_layout = bar.layout(
                    toolbar_bounds.x,
                    toolbar_bounds.y,
                    toolbar_bounds.width,
                    toolbar_bounds.height,
                    measure_item,
                );

                SidebarPanelLayout {
                    panel_bounds: bounds,
                    toolbar_bounds: Some(toolbar_bounds),
                    content_bounds,
                    toolbar_layout: Some(toolbar_layout),
                }
            }
            None => SidebarPanelLayout {
                panel_bounds: bounds,
                toolbar_bounds: None,
                content_bounds: bounds,
                toolbar_layout: None,
            },
        }
    }
}

// Shared implementation for all backends, written against
// [`crate::paint_surface::PaintSurface`] instead of individual
// backend drawing APIs.
//
// `SidebarPanel` paints nothing of its own — its entire visible
// surface is the optional [`Toolbar`] header; the content region
// is left to the host. `paint_toolbar_header` below duplicates
// toolbar rendering logic scoped to what a sidebar panel's header
// needs. When `Toolbar` gets unified painting, extract a shared
// helper or consolidate this copy.
//
// Rendering choices made to unify backends:
//
// 1. **Plain rect highlights**, not rounded: `PaintSurface` has no
//    rounded-rect verb, so this follows the macOS/Win majority
//    (GTK previously painted 4px-radius rounded-rect pills).
// 2. **Clip on all backends**: GTK and macOS clipped to toolbar
//    bounds before drawing; Win did not. This now clips uniformly.
// 3. **Alpha-channel preserved**: Uses `surface_fill_rect` which
//    respects `Color::a`, unlike the old GTK path that dropped it.
// 4. **Default theme on Win**: `WinBackend::draw_sidebar_panel`
//    passes `Theme::default()`, not live theme — consistent with
//    how `Panel` chrome is rendered.
//
// `#[allow(dead_code)]`: only called when a real pixel backend is
// compiled in, exercised by each backend's `Backend::draw_sidebar_panel`
// call site plus this module's `RecordingSurface` tests.
#[cfg(any(
    feature = "gtk",
    feature = "win",
    all(feature = "macos", target_os = "macos")
))]
#[allow(dead_code)]
pub(crate) mod native_surface_paint {
    use super::{SidebarPanel, SidebarPanelLayout, SidebarPanelMeasure};
    use crate::event::{Point, Rect};
    use crate::paint_surface::PaintSurface;
    use crate::primitives::layout_metrics::TextMeasure;
    use crate::primitives::toolbar::{
        action_text, measure_button, Toolbar, ToolbarButton, ToolbarItemMeasure, ToolbarLayout,
    };
    use crate::theme::Theme;
    use crate::types::WidgetId;

    /// Adapts a live `&dyn PaintSurface` to the shared [`TextMeasure`]
    /// trait so [`measure_button`] never has to name a backend-specific
    /// font type — generalises `gtk::toolbar::PangoMeasure` /
    /// `macos::toolbar::CtFontMeasure` / `win::toolbar::DWriteMeasure`
    /// into the one adapter every backend now shares.
    struct SurfaceMeasure<'a>(&'a dyn PaintSurface);

    impl TextMeasure for SurfaceMeasure<'_> {
        fn width_of(&self, text: &str) -> f32 {
            self.0.surface_measure_text(text).0
        }
    }

    /// Paint a [`SidebarPanel`] into `bounds` on `surface`, returning
    /// the resolved [`SidebarPanelLayout`]. The `content_bounds` and
    /// `toolbar_bounds` in the layout are absolute (shifted by
    /// `bounds.x`/`bounds.y`). The content region is never painted
    /// — the host paints `layout.content_bounds` itself.
    ///
    /// `hovered_toolbar_id` / `pressed_toolbar_id` tint the matching
    /// toolbar action button; the primitive carries no mouse state.
    ///
    /// Non-positive `bounds.width` or `bounds.height` short-circuits
    /// without touching `surface`.
    pub(crate) fn paint(
        panel: &SidebarPanel,
        surface: &mut dyn PaintSurface,
        theme: &Theme,
        bounds: Rect,
        default_toolbar_height: f32,
        hovered_toolbar_id: Option<&WidgetId>,
        pressed_toolbar_id: Option<&WidgetId>,
    ) -> SidebarPanelLayout {
        let layout = {
            // `item_width` (the measure's second field) is dead in
            // `SidebarPanel::layout` — every backend's own layout helper
            // already passes `0.0` for it (see e.g. `win_sidebar_panel_layout`)
            // since real per-button widths come from the `measure_item`
            // closure below, not this field.
            let measurer = SurfaceMeasure(&*surface);
            panel.layout(
                bounds,
                SidebarPanelMeasure::new(default_toolbar_height, 0.0),
                |btn| ToolbarItemMeasure::new(measure_button(&measurer, btn)),
            )
        };

        if bounds.width <= 0.0 || bounds.height <= 0.0 {
            return layout;
        }

        if let (Some(bar), Some(tb_bounds)) = (&panel.toolbar, layout.toolbar_bounds) {
            if let Some(toolbar_layout) = &layout.toolbar_layout {
                paint_toolbar_header(
                    bar,
                    toolbar_layout,
                    surface,
                    theme,
                    tb_bounds,
                    hovered_toolbar_id,
                    pressed_toolbar_id,
                );
            }
        }

        layout
    }

    /// Paint `bar`'s buttons into `tb_bounds` on `surface` — see this
    /// module's doc for why this exists (a `PaintSurface`-generic port
    /// of `gtk`/`macos`/`win`'s own `toolbar::draw_toolbar`, scoped to
    /// what a sidebar panel's header needs) and for the four named
    /// divergences found while porting it.
    fn paint_toolbar_header(
        bar: &Toolbar,
        toolbar_layout: &ToolbarLayout,
        surface: &mut dyn PaintSurface,
        theme: &Theme,
        tb_bounds: Rect,
        hovered_id: Option<&WidgetId>,
        pressed_id: Option<&WidgetId>,
    ) {
        // Clip to toolbar bounds on all backends.
        surface.surface_push_clip(tb_bounds);

        let bar_bg = bar.bg.unwrap_or(theme.header_bg);
        surface.surface_fill_rect(tb_bounds, bar_bg);

        for vis in &toolbar_layout.visible_items {
            let item = vis.bounds;
            if item.width <= 0.0 || item.height <= 0.0 {
                continue;
            }
            let Some(btn) = bar.buttons.get(vis.item_idx) else {
                continue;
            };

            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);

                    // Highlight background: pressed/active > hovered > none.
                    // Plain rect (no rounded corners).
                    let highlight = if is_pressed || *is_active {
                        Some(theme.selected_bg)
                    } else if is_hovered {
                        Some(theme.hover_bg)
                    } else {
                        None
                    };
                    if let Some(bg) = highlight {
                        let inset = Rect::new(
                            item.x + 2.0,
                            item.y + 2.0,
                            (item.width - 4.0).max(0.0),
                            (item.height - 4.0).max(0.0),
                        );
                        surface.surface_fill_rect(inset, bg);
                    }

                    // Focus ring: only when not already visually
                    // dominated by hover/pressed/active.
                    if is_focused && !is_hovered && !is_pressed && !*is_active {
                        let ring = Rect::new(
                            item.x + 1.5,
                            item.y + 1.5,
                            (item.width - 3.0).max(0.0),
                            (item.height - 3.0).max(0.0),
                        );
                        surface.surface_stroke_rect(ring, theme.accent_fg, 1.0);
                    }

                    let fg = if !*enabled {
                        theme.muted_fg
                    } else if is_hovered {
                        theme.hover_fg
                    } else {
                        theme.foreground
                    };

                    let text = action_text(label, icon.as_deref(), key_hint.as_deref());
                    let (tw, th) = surface.surface_measure_text(&text);
                    let tx = item.x + (item.width - tw) / 2.0;
                    let ty = item.y + (item.height - th) / 2.0;
                    surface.surface_draw_text_run(Rect::new(tx, ty, tw, th), &text, fg);
                }
                ToolbarButton::Separator => {
                    let mid_x = item.x + item.width / 2.0;
                    let pad_y = (item.height * 0.2).max(2.0);
                    surface.surface_draw_line(
                        Point::new(mid_x, item.y + pad_y),
                        Point::new(mid_x, item.y + item.height - pad_y),
                        theme.muted_fg,
                        1.0,
                    );
                }
                ToolbarButton::Label { text, fg } => {
                    let color = fg.unwrap_or(theme.muted_fg);
                    let (tw, th) = surface.surface_measure_text(text);
                    let ty = item.y + (item.height - th) / 2.0;
                    surface.surface_draw_text_run(Rect::new(item.x, ty, tw, th), text, color);
                }
            }
        }

        surface.surface_pop_clip();
    }

    #[cfg(test)]
    mod tests {
        use super::*;
        use crate::backend::ImagePaintResult;
        use crate::event::Viewport;
        use crate::types::Color;
        use crate::Image;

        /// Records every surface verb this primitive's paint uses —
        /// mirrors `primitives::status_bar`'s `RecordingSurface` test
        /// double, so this test runs on any host without Cairo/Core
        /// Graphics/Direct2D.
        #[derive(Default)]
        struct RecordingSurface {
            fills: Vec<(Rect, Color)>,
            strokes: Vec<(Rect, Color, f32)>,
            text_runs: Vec<(Rect, String, Color)>,
            lines: Vec<(Point, Point, Color)>,
            clip_pushes: Vec<Rect>,
            clip_pops: usize,
        }

        impl PaintSurface for RecordingSurface {
            fn surface_begin_frame(&mut self, _viewport: Viewport) {}
            fn surface_end_frame(&mut self) {}
            fn surface_viewport(&self) -> Viewport {
                Viewport::new(200.0, 100.0, 1.0)
            }
            fn surface_line_height(&self) -> f32 {
                16.0
            }
            fn surface_char_width(&self) -> f32 {
                8.0
            }
            fn surface_measure_text(&self, text: &str) -> (f32, f32) {
                (text.chars().count() as f32 * 8.0, 16.0)
            }
            fn surface_fill_rect(&mut self, rect: Rect, color: Color) {
                self.fills.push((rect, color));
            }
            /// Test-only recorder — `paint` never calls this verb
            /// (see this module's own doc for why no primitive here has been
            /// migrated onto it yet); this exists only so `RecordingSurface`
            /// satisfies the trait. Records into the same `fills` list as
            /// `surface_fill_rect` (radius dropped) — no test asserts on it
            /// today.
            fn surface_fill_rounded_rect(&mut self, rect: Rect, _radius: f32, color: Color) {
                self.fills.push((rect, color));
            }
            fn surface_stroke_rect(&mut self, rect: Rect, color: Color, stroke_width: f32) {
                self.strokes.push((rect, color, stroke_width));
            }
            fn surface_stroke_rounded_rect(
                &mut self,
                rect: Rect,
                _radius: f32,
                color: Color,
                stroke_width: f32,
            ) {
                self.strokes.push((rect, color, stroke_width));
            }
            fn surface_draw_text_run(&mut self, rect: Rect, text: &str, color: Color) {
                self.text_runs.push((rect, text.to_string(), color));
            }
            fn surface_draw_line(
                &mut self,
                from: Point,
                to: Point,
                color: Color,
                _stroke_width: f32,
            ) {
                self.lines.push((from, to, color));
            }
            fn surface_push_clip(&mut self, rect: Rect) {
                self.clip_pushes.push(rect);
            }
            fn surface_pop_clip(&mut self) {
                self.clip_pops += 1;
            }
            fn surface_draw_image(&mut self, _rect: Rect, _image: &Image) -> ImagePaintResult {
                ImagePaintResult::Unsupported
            }
        }

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

        fn panel_with_toolbar() -> SidebarPanel {
            SidebarPanel {
                id: WidgetId::new("sb"),
                toolbar: Some(Toolbar {
                    id: WidgetId::new("sb:toolbar"),
                    buttons: vec![mk_action("a", "Refine", true), mk_action("b", "Drop", true)],
                    bg: None,
                    focused_index: None,
                }),
                toolbar_height: None,
            }
        }

        #[test]
        fn no_toolbar_paints_nothing() {
            let panel = SidebarPanel {
                id: WidgetId::new("sb"),
                toolbar: None,
                toolbar_height: None,
            };
            let theme = Theme::default();
            let mut surface = RecordingSurface::default();
            let layout = paint(
                &panel,
                &mut surface,
                &theme,
                Rect::new(0.0, 0.0, 100.0, 50.0),
                16.0,
                None,
                None,
            );
            assert!(surface.fills.is_empty());
            assert!(surface.text_runs.is_empty());
            assert_eq!(layout.content_bounds, Rect::new(0.0, 0.0, 100.0, 50.0));
        }

        #[test]
        fn zero_size_bounds_paints_nothing() {
            let panel = panel_with_toolbar();
            let theme = Theme::default();
            let mut surface = RecordingSurface::default();
            paint(
                &panel,
                &mut surface,
                &theme,
                Rect::new(0.0, 0.0, 0.0, 0.0),
                16.0,
                None,
                None,
            );
            assert!(surface.fills.is_empty());
            assert!(surface.clip_pushes.is_empty());
        }

        #[test]
        fn toolbar_header_fills_bar_background_and_clips() {
            let panel = panel_with_toolbar();
            let theme = Theme::default();
            let mut surface = RecordingSurface::default();
            let layout = paint(
                &panel,
                &mut surface,
                &theme,
                Rect::new(0.0, 0.0, 100.0, 50.0),
                16.0,
                None,
                None,
            );
            let tb = layout.toolbar_bounds.expect("toolbar slot reserved");
            assert_eq!(surface.clip_pushes, vec![tb]);
            assert_eq!(surface.clip_pops, 1);
            assert_eq!(surface.fills[0], (tb, theme.header_bg));
        }

        #[test]
        fn hovered_button_gets_hover_bg_and_hover_fg() {
            let panel = panel_with_toolbar();
            let theme = Theme::default();
            let mut surface = RecordingSurface::default();
            paint(
                &panel,
                &mut surface,
                &theme,
                Rect::new(0.0, 0.0, 100.0, 50.0),
                16.0,
                Some(&WidgetId::new("a")),
                None,
            );
            // fills[0] = bar background, fills[1] = hovered button's
            // highlight inset.
            assert_eq!(surface.fills[1].1, theme.hover_bg);
            let (_, _text, color) = surface
                .text_runs
                .iter()
                .find(|(_, t, _)| t == "Refine")
                .expect("Refine label drawn");
            assert_eq!(*color, theme.hover_fg);
        }

        #[test]
        fn pressed_button_gets_selected_bg() {
            let panel = panel_with_toolbar();
            let theme = Theme::default();
            let mut surface = RecordingSurface::default();
            paint(
                &panel,
                &mut surface,
                &theme,
                Rect::new(0.0, 0.0, 100.0, 50.0),
                16.0,
                None,
                Some(&WidgetId::new("a")),
            );
            assert_eq!(surface.fills[1].1, theme.selected_bg);
        }

        #[test]
        fn disabled_action_paints_muted_fg_no_highlight() {
            let panel = SidebarPanel {
                id: WidgetId::new("sb"),
                toolbar: Some(Toolbar {
                    id: WidgetId::new("sb:toolbar"),
                    buttons: vec![mk_action("a", "Refine", false)],
                    bg: None,
                    focused_index: None,
                }),
                toolbar_height: None,
            };
            let theme = Theme::default();
            let mut surface = RecordingSurface::default();
            paint(
                &panel,
                &mut surface,
                &theme,
                Rect::new(0.0, 0.0, 100.0, 50.0),
                16.0,
                Some(&WidgetId::new("a")), // hover on a disabled button is a no-op
                None,
            );
            // Only the bar background fill — no highlight for a disabled
            // (thus never "hovered") action.
            assert_eq!(surface.fills.len(), 1);
            let (_, _, color) = &surface.text_runs[0];
            assert_eq!(*color, theme.muted_fg);
        }

        #[test]
        fn focused_button_gets_stroke_ring_when_not_hovered_or_pressed() {
            let panel = SidebarPanel {
                id: WidgetId::new("sb"),
                toolbar: Some(Toolbar {
                    id: WidgetId::new("sb:toolbar"),
                    buttons: vec![mk_action("a", "Refine", true)],
                    bg: None,
                    focused_index: Some(0),
                }),
                toolbar_height: None,
            };
            let theme = Theme::default();
            let mut surface = RecordingSurface::default();
            paint(
                &panel,
                &mut surface,
                &theme,
                Rect::new(0.0, 0.0, 100.0, 50.0),
                16.0,
                None,
                None,
            );
            assert_eq!(surface.strokes.len(), 1);
            assert_eq!(surface.strokes[0].1, theme.accent_fg);
        }

        #[test]
        fn separator_draws_a_vertical_line_not_a_fill() {
            let panel = SidebarPanel {
                id: WidgetId::new("sb"),
                toolbar: Some(Toolbar {
                    id: WidgetId::new("sb:toolbar"),
                    buttons: vec![mk_action("a", "Refine", true), ToolbarButton::Separator],
                    bg: None,
                    focused_index: None,
                }),
                toolbar_height: None,
            };
            let theme = Theme::default();
            let mut surface = RecordingSurface::default();
            paint(
                &panel,
                &mut surface,
                &theme,
                Rect::new(0.0, 0.0, 100.0, 50.0),
                16.0,
                None,
                None,
            );
            assert_eq!(surface.lines.len(), 1);
            assert_eq!(surface.lines[0].2, theme.muted_fg);
        }

        #[test]
        fn label_draws_left_aligned_unhighlighted_text() {
            let panel = SidebarPanel {
                id: WidgetId::new("sb"),
                toolbar: Some(Toolbar {
                    id: WidgetId::new("sb:toolbar"),
                    buttons: vec![ToolbarButton::Label {
                        text: "2 of 5".into(),
                        fg: None,
                    }],
                    bg: None,
                    focused_index: None,
                }),
                toolbar_height: None,
            };
            let theme = Theme::default();
            let mut surface = RecordingSurface::default();
            let layout = paint(
                &panel,
                &mut surface,
                &theme,
                Rect::new(0.0, 0.0, 100.0, 50.0),
                16.0,
                None,
                None,
            );
            let tb = layout.toolbar_bounds.unwrap();
            // Only the bar background fill — labels never get a
            // highlight fill.
            assert_eq!(surface.fills.len(), 1);
            let (rect, text, color) = &surface.text_runs[0];
            assert_eq!(text, "2 of 5");
            assert_eq!(rect.x, tb.x);
            assert_eq!(*color, theme.muted_fg);
        }

        #[test]
        fn content_bounds_still_start_below_toolbar_slot() {
            let panel = panel_with_toolbar();
            let theme = Theme::default();
            let mut surface = RecordingSurface::default();
            let layout = paint(
                &panel,
                &mut surface,
                &theme,
                Rect::new(0.0, 0.0, 100.0, 50.0),
                16.0,
                None,
                None,
            );
            let tb = layout.toolbar_bounds.unwrap();
            assert_eq!(layout.content_bounds.y, tb.y + tb.height);
        }
    }
}

// ── Tests ────────────────────────────────────────────────────────────────────

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

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

    fn panel_with_toolbar() -> SidebarPanel {
        SidebarPanel {
            id: WidgetId::new("sb"),
            toolbar: Some(Toolbar {
                id: WidgetId::new("sb:toolbar"),
                buttons: vec![mk_action("a", "Refine"), mk_action("b", "Drop")],
                bg: None,
                focused_index: None,
            }),
            toolbar_height: None,
        }
    }

    fn measure() -> (
        SidebarPanelMeasure,
        impl Fn(&ToolbarButton) -> ToolbarItemMeasure,
    ) {
        let m = SidebarPanelMeasure::new(1.0, 8.0);
        (m, |_btn: &ToolbarButton| ToolbarItemMeasure::new(8.0))
    }

    #[test]
    fn no_toolbar_gives_full_rect_to_content() {
        let panel = SidebarPanel {
            id: WidgetId::new("sb"),
            toolbar: None,
            toolbar_height: None,
        };
        let (m, mi) = measure();
        let layout = panel.layout(Rect::new(0.0, 0.0, 30.0, 10.0), m, mi);
        assert!(layout.toolbar_bounds.is_none());
        assert!(layout.toolbar_layout.is_none());
        assert_eq!(layout.content_bounds, Rect::new(0.0, 0.0, 30.0, 10.0));
    }

    #[test]
    fn toolbar_reserves_top_slot() {
        let panel = panel_with_toolbar();
        let (m, mi) = measure();
        let layout = panel.layout(Rect::new(0.0, 0.0, 30.0, 10.0), m, mi);
        let tb = layout.toolbar_bounds.expect("toolbar slot reserved");
        assert_eq!(tb.x, 0.0);
        assert_eq!(tb.y, 0.0);
        assert_eq!(tb.width, 30.0);
        assert_eq!(tb.height, 1.0); // default_toolbar_height
                                    // Content starts below the slot.
        assert_eq!(layout.content_bounds.y, 1.0);
        assert_eq!(layout.content_bounds.height, 9.0);
    }

    #[test]
    fn empty_toolbar_still_reserves_slot() {
        // The whole point of Gap 2 is that content doesn't shift when
        // the toolbar's buttons vector is temporarily empty.
        let panel = SidebarPanel {
            id: WidgetId::new("sb"),
            toolbar: Some(Toolbar {
                id: WidgetId::new("sb:toolbar"),
                buttons: vec![], // empty!
                bg: None,
                focused_index: None,
            }),
            toolbar_height: None,
        };
        let (m, mi) = measure();
        let layout = panel.layout(Rect::new(0.0, 0.0, 30.0, 10.0), m, mi);
        assert!(layout.toolbar_bounds.is_some());
        // Slot still reserved — content offset by the toolbar height.
        assert_eq!(layout.content_bounds.y, 1.0);
        assert_eq!(layout.content_bounds.height, 9.0);
    }

    #[test]
    fn explicit_toolbar_height_overrides_default() {
        let mut panel = panel_with_toolbar();
        panel.toolbar_height = Some(3.0);
        let (m, mi) = measure();
        let layout = panel.layout(Rect::new(0.0, 0.0, 30.0, 10.0), m, mi);
        let tb = layout.toolbar_bounds.unwrap();
        assert_eq!(tb.height, 3.0);
        assert_eq!(layout.content_bounds.y, 3.0);
        assert_eq!(layout.content_bounds.height, 7.0);
    }

    #[test]
    fn hit_test_routes_toolbar_button_click() {
        let panel = panel_with_toolbar();
        let (m, mi) = measure();
        let layout = panel.layout(Rect::new(0.0, 0.0, 30.0, 10.0), m, mi);
        // First button is at x=0..8 in the toolbar slot.
        match layout.hit_test(2.0, 0.0) {
            SidebarPanelHit::ToolbarButton(id) => assert_eq!(id.as_str(), "a"),
            other => panic!("expected ToolbarButton hit, got {other:?}"),
        }
    }

    #[test]
    fn hit_test_inside_toolbar_slot_off_button_is_toolbar_empty() {
        let panel = panel_with_toolbar();
        let (m, mi) = measure();
        let layout = panel.layout(Rect::new(0.0, 0.0, 30.0, 10.0), m, mi);
        // Past the second button's right edge (16) but still in the
        // toolbar slot (y < 1).
        let hit = layout.hit_test(20.0, 0.0);
        assert_eq!(hit, SidebarPanelHit::ToolbarEmpty);
    }

    #[test]
    fn hit_test_content_returns_content_local_coords() {
        let panel = panel_with_toolbar();
        let (m, mi) = measure();
        let layout = panel.layout(Rect::new(10.0, 5.0, 30.0, 10.0), m, mi);
        // Click at panel-absolute (12.0, 8.0): toolbar slot is rows
        // 5..6, so y=8 lands in content. Content origin is (10, 6).
        // Local: (12-10, 8-6) = (2.0, 2.0).
        match layout.hit_test(12.0, 8.0) {
            SidebarPanelHit::Content { x, y } => {
                assert_eq!(x, 2.0);
                assert_eq!(y, 2.0);
            }
            other => panic!("expected Content hit, got {other:?}"),
        }
    }

    #[test]
    fn hit_test_outside_panel_is_empty() {
        let panel = panel_with_toolbar();
        let (m, mi) = measure();
        let layout = panel.layout(Rect::new(0.0, 0.0, 30.0, 10.0), m, mi);
        assert_eq!(layout.hit_test(100.0, 100.0), SidebarPanelHit::Empty);
    }

    #[test]
    fn toolbar_height_clamps_to_panel_height() {
        // If a host accidentally asks for a toolbar taller than the
        // panel, the slot must not overflow into negative-content
        // territory.
        let mut panel = panel_with_toolbar();
        panel.toolbar_height = Some(50.0);
        let (m, mi) = measure();
        let layout = panel.layout(Rect::new(0.0, 0.0, 30.0, 10.0), m, mi);
        let tb = layout.toolbar_bounds.unwrap();
        assert_eq!(tb.height, 10.0); // clamped to panel height
        assert_eq!(layout.content_bounds.height, 0.0);
    }

    #[test]
    fn serde_roundtrip() {
        let panel = panel_with_toolbar();
        let json = serde_json::to_string(&panel).unwrap();
        let back: SidebarPanel = serde_json::from_str(&json).unwrap();
        assert_eq!(panel, back);
    }
}