Skip to main content

agg_gui/widgets/
collapsing_header.rs

1//! `CollapsingHeader` — a clickable header that shows/hides child content.
2//!
3//! # Composition
4//!
5//! ```text
6//! CollapsingHeader
7//!   ├── Label (header text, drawn manually)
8//!   └── child widget (shown when expanded, hidden when collapsed)
9//! ```
10//!
11//! The triangle indicator is drawn as a path.  Clicking anywhere on the header
12//! row toggles the collapsed/expanded state.
13
14use std::sync::Arc;
15
16use crate::color::Color;
17use crate::draw_ctx::DrawCtx;
18use crate::event::{Event, EventResult, MouseButton};
19use crate::geometry::{Point, Rect, Size};
20use crate::text::Font;
21use crate::widget::{paint_subtree, Widget};
22use crate::widgets::label::Label;
23
24const HEADER_H: f64 = 22.0;
25const TRIANGLE_SIZE: f64 = 6.0;
26const INDENT: f64 = 12.0;
27
28/// A collapsible section header.  When expanded, the child widget is visible
29/// below the header row.  When collapsed, only the header row is shown.
30pub struct CollapsingHeader {
31    bounds: Rect,
32    children: Vec<Box<dyn Widget>>,
33    label: Label,
34    open: bool,
35    hovered: bool,
36    /// The content shown when expanded.
37    content: Option<Box<dyn Widget>>,
38}
39
40impl CollapsingHeader {
41    /// Create a new header with the given text, using the provided font.
42    /// Starts expanded by default.
43    pub fn new(text: impl Into<String>, font: Arc<Font>) -> Self {
44        let label = Label::new(text, Arc::clone(&font)).with_font_size(13.0);
45        Self {
46            bounds: Rect::default(),
47            children: Vec::new(),
48            label,
49            open: true,
50            hovered: false,
51            content: None,
52        }
53    }
54
55    /// Set whether the section is open (expanded) by default.
56    pub fn default_open(mut self, open: bool) -> Self {
57        self.open = open;
58        self
59    }
60
61    /// Set the child content widget shown when expanded.
62    pub fn with_content(mut self, content: Box<dyn Widget>) -> Self {
63        self.content = Some(content);
64        self
65    }
66}
67
68impl Widget for CollapsingHeader {
69    fn type_name(&self) -> &'static str {
70        "CollapsingHeader"
71    }
72    fn bounds(&self) -> Rect {
73        self.bounds
74    }
75    fn set_bounds(&mut self, b: Rect) {
76        self.bounds = b;
77    }
78    fn children(&self) -> &[Box<dyn Widget>] {
79        &self.children
80    }
81    fn children_mut(&mut self) -> &mut Vec<Box<dyn Widget>> {
82        &mut self.children
83    }
84
85    fn layout(&mut self, available: Size) -> Size {
86        let w = available.width;
87
88        // Sync `children` with `open` state so the framework dispatches events
89        // to the content only when it is visible.  When closed the content
90        // lives in `self.content`; when open it lives in `self.children[0]`.
91        if self.open && self.children.is_empty() {
92            if let Some(c) = self.content.take() {
93                self.children.push(c);
94            }
95        } else if !self.open && !self.children.is_empty() {
96            if let Some(c) = self.children.pop() {
97                self.content = Some(c);
98            }
99        }
100
101        // Layout label inside the header row.
102        let label_available = Size::new(w - INDENT - TRIANGLE_SIZE * 2.0, HEADER_H);
103        let ls = self.label.layout(label_available);
104        let ly = (HEADER_H - ls.height) * 0.5;
105        self.label.set_bounds(Rect::new(
106            INDENT + TRIANGLE_SIZE * 2.0 + 4.0,
107            ly,
108            ls.width,
109            ls.height,
110        ));
111
112        // Layout content if open — as a child so the framework paints and
113        // dispatches events normally.  Content is inset from the left by
114        // INDENT * 0.5 for visual hierarchy.
115        let content_h = if self.open && !self.children.is_empty() {
116            let inset = INDENT * 0.5;
117            let avail_w = (w - inset).max(0.0);
118            let child = &mut self.children[0];
119            let cs = child.layout(Size::new(avail_w, available.height - HEADER_H));
120            // Content sits at the bottom of our bounds (Y-up: y = 0).
121            child.set_bounds(Rect::new(inset, 0.0, cs.width, cs.height));
122            cs.height
123        } else {
124            0.0
125        };
126
127        let total_h = HEADER_H + content_h;
128        self.bounds = Rect::new(0.0, 0.0, w, total_h);
129        Size::new(w, total_h)
130    }
131
132    fn paint(&mut self, ctx: &mut dyn DrawCtx) {
133        let v = ctx.visuals();
134        let w = self.bounds.width;
135        let h = self.bounds.height;
136
137        // Header row background — always shown at a subtle tint so the header
138        // reads as a distinct section boundary even when not hovered.  Hover
139        // deepens the tint slightly as click affordance.  Sits just below the
140        // top divider line so the line remains crisp.
141        let alpha = if self.hovered { 0.10 } else { 0.06 };
142        ctx.set_fill_color(Color::rgba(
143            v.text_color.r,
144            v.text_color.g,
145            v.text_color.b,
146            alpha,
147        ));
148        ctx.begin_path();
149        ctx.rect(0.0, h - HEADER_H, w, HEADER_H - 1.0);
150        ctx.fill();
151
152        // Top divider line — 1px, full-width, in the shared separator colour
153        // so a vertical stack of headers forms consistent section boundaries
154        // matching any `Separator` widgets elsewhere in the UI.
155        ctx.set_fill_color(v.separator);
156        ctx.begin_path();
157        ctx.rect(0.0, h - 1.0, w, 1.0);
158        ctx.fill();
159
160        // Triangle indicator (▶ collapsed, ▼ expanded).
161        // In Y-up: the header row occupies y = h - HEADER_H .. h.
162        let center_y = h - HEADER_H * 0.5;
163        let tx = INDENT;
164        let ts = TRIANGLE_SIZE * 0.5;
165        ctx.set_fill_color(v.text_dim);
166        ctx.begin_path();
167        if self.open {
168            // Pointing down (▼): triangle with point at bottom.
169            ctx.move_to(tx, center_y + ts * 0.5);
170            ctx.line_to(tx + ts * 2.0, center_y + ts * 0.5);
171            ctx.line_to(tx + ts, center_y - ts * 0.8);
172        } else {
173            // Pointing right (▶): triangle with point to the right.
174            ctx.move_to(tx, center_y + ts);
175            ctx.line_to(tx, center_y - ts);
176            ctx.line_to(tx + ts * 1.6, center_y);
177        }
178        ctx.fill();
179
180        // Label.
181        self.label.set_color(v.text_color);
182        let lb = self.label.bounds();
183        // Label y is in header-local coords, but header is at top of our bounds (in Y-up).
184        let label_offset_y = h - HEADER_H + lb.y;
185        ctx.save();
186        ctx.translate(lb.x, label_offset_y);
187        paint_subtree(&mut self.label, ctx);
188        ctx.restore();
189
190        // Content is painted by the framework via normal child recursion —
191        // it lives in `self.children[0]` (when open) and has its own bounds
192        // so `dispatch_event` reaches it without manual forwarding.
193    }
194
195    fn on_event(&mut self, event: &Event) -> EventResult {
196        let h = self.bounds.height;
197
198        match event {
199            Event::MouseMove { pos } => {
200                // Header row: top portion in Y-up = y from (h - HEADER_H) to h.
201                let in_header = pos.x >= 0.0
202                    && pos.x <= self.bounds.width
203                    && pos.y >= h - HEADER_H
204                    && pos.y <= h;
205                let was = self.hovered;
206                self.hovered = in_header;
207                if self.hovered != was {
208                    crate::animation::request_draw();
209                    return EventResult::Consumed;
210                }
211                EventResult::Ignored
212            }
213            Event::MouseDown {
214                button: MouseButton::Left,
215                pos,
216                ..
217            } => {
218                let in_header = pos.x >= 0.0
219                    && pos.x <= self.bounds.width
220                    && pos.y >= h - HEADER_H
221                    && pos.y <= h;
222                if in_header {
223                    self.open = !self.open;
224                    crate::animation::request_draw();
225                    return EventResult::Consumed;
226                }
227                EventResult::Ignored
228            }
229            _ => EventResult::Ignored,
230        }
231    }
232
233    fn hit_test(&self, local_pos: Point) -> bool {
234        local_pos.x >= 0.0
235            && local_pos.x <= self.bounds.width
236            && local_pos.y >= 0.0
237            && local_pos.y <= self.bounds.height
238    }
239}