Skip to main content

egui_macview/layout/
stack_view.rs

1//! Authentic macOS AppKit Stack View (NSStackView equivalent).
2//!
3//! Grounded in macOS HIG and W3C DTCG tokens via `MacTheme`.
4//! Fully data-driven: zero hardcoded dimensions or colors.
5//! Features automatic horizontal/vertical component stacking,
6//! configurable token-driven spacing and padding, section grouping,
7//! and optional hairline divider lines.
8
9use crate::layout::subpixel_snap;
10use crate::theme::MacTheme;
11use egui::{FontId, Pos2, Rect, Stroke, Ui, UiBuilder, Vec2};
12
13/// Orientation of a [`MacStackView`].
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
15pub enum MacStackOrientation {
16    /// Vertical auto-stacking (column layout, default).
17    #[default]
18    Vertical,
19    /// Horizontal auto-stacking (row layout).
20    Horizontal,
21}
22
23/// Alignment along the cross-axis.
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
25pub enum MacStackAlignment {
26    /// Align items to the leading edge (left for vertical, top for horizontal).
27    #[default]
28    Leading,
29    /// Center items along the cross-axis.
30    Center,
31    /// Align items to the trailing edge.
32    Trailing,
33}
34
35/// Authentic macOS AppKit linear stacking container (`NSStackView` equivalent).
36///
37/// Supports automatic horizontal or vertical component stacking,
38/// configurable token-driven spacing and padding, grouped sections with header labels,
39/// and optional hairline divider lines between items.
40///
41/// # Example
42///
43/// ```rust
44/// use egui_macview::{MacStackView, MacTheme};
45///
46/// # let ctx = egui::Context::default();
47/// # let mut output = ctx.run_ui(egui::RawInput::default(), |ui| {
48/// let theme = MacTheme::default();
49///
50/// MacStackView::vertical()
51///     .theme(&theme)
52///     .spacing(12.0)
53///     .show_separators(true)
54///     .show(ui, |stack| {
55///         stack.add(|ui| {
56///             ui.label("First item");
57///         });
58///         stack.add_section(Some("Section 2"), |ui| {
59///             ui.label("Section content");
60///         });
61///     });
62/// # });
63/// # output.textures_delta.clear();
64/// ```
65pub struct MacStackView<'a> {
66    orientation: MacStackOrientation,
67    alignment: MacStackAlignment,
68    theme: Option<&'a MacTheme>,
69    spacing: Option<f32>,
70    padding: Option<f32>,
71    show_separators: bool,
72    width: Option<f32>,
73    height: Option<f32>,
74}
75
76/// Interactive stacking context passed to closures in [`MacStackView::show`].
77pub struct MacStackUi<'a> {
78    /// Underlying egui `Ui` instance for embedding widgets inside the stack.
79    pub ui: &'a mut Ui,
80
81    theme: &'a MacTheme,
82    orientation: MacStackOrientation,
83    spacing: f32,
84    separator_thickness: f32,
85    show_separators: bool,
86    container_height: Option<f32>,
87    padding: f32,
88    item_count: usize,
89    section_count: usize,
90}
91
92/// Output returned by [`MacStackView::show`].
93#[derive(Debug, Clone)]
94pub struct MacStackViewOutput<R> {
95    /// Return value of the inner closure.
96    pub inner: R,
97    /// Bounding rectangle enclosing the stacked items and padding.
98    pub rect: Rect,
99    /// Total count of items added to the stack.
100    pub item_count: usize,
101    /// Total count of sections added to the stack.
102    pub section_count: usize,
103}
104
105impl<'a> MacStackUi<'a> {
106    /// Adds an item closure to the stack with automatic spacing and separators.
107    pub fn add<R>(&mut self, item: impl FnOnce(&mut Ui) -> R) -> R {
108        if self.item_count > 0 {
109            if self.show_separators {
110                self.draw_separator();
111            } else {
112                self.advance_spacing();
113            }
114        }
115        self.item_count += 1;
116        item(self.ui)
117    }
118
119    /// Adds a grouped section with an optional section header label.
120    pub fn add_section<R>(
121        &mut self,
122        header: Option<&str>,
123        content: impl FnOnce(&mut Ui) -> R,
124    ) -> R {
125        if self.item_count > 0 || self.section_count > 0 {
126            self.draw_separator();
127        }
128        self.section_count += 1;
129
130        if let Some(title) = header {
131            let label_color = self.theme.secondary_label();
132            let font_size = self.theme.stack_view().section_header_font_size.points();
133            let font_id = FontId::proportional(font_size);
134            self.ui.add(egui::Label::new(
135                egui::RichText::new(title).font(font_id).color(label_color),
136            ));
137            self.advance_spacing();
138        }
139
140        self.item_count += 1;
141        content(self.ui)
142    }
143
144    /// Explicitly inserts a hairline divider line spanning the cross-axis.
145    pub fn separator(&mut self) {
146        self.draw_separator();
147    }
148
149    /// Explicitly inserts custom spacing in points.
150    pub fn spacing(&mut self, pts: f32) {
151        self.ui.add_space(pts);
152    }
153
154    fn advance_spacing(&mut self) {
155        self.ui.add_space(self.spacing);
156    }
157
158    fn draw_separator(&mut self) {
159        self.ui.add_space(self.spacing * 0.5);
160        let scale = self.ui.pixels_per_point();
161        let th = self.separator_thickness;
162        let color = self.theme.separator();
163
164        match self.orientation {
165            MacStackOrientation::Vertical => {
166                let avail_w = self.ui.available_width();
167                let (rect, _) = self
168                    .ui
169                    .allocate_exact_size(Vec2::new(avail_w, th), egui::Sense::hover());
170                let y = subpixel_snap(rect.center().y, scale);
171                self.ui.painter().line_segment(
172                    [Pos2::new(rect.left(), y), Pos2::new(rect.right(), y)],
173                    Stroke::new(th, color),
174                );
175            }
176            MacStackOrientation::Horizontal => {
177                let avail_h = if let Some(ch) = self.container_height {
178                    (ch - 2.0 * self.padding).max(1.0)
179                } else {
180                    let current_h = self.ui.min_rect().height();
181                    if current_h > 0.0 {
182                        current_h
183                    } else {
184                        self.theme.stack_view().default_item_height.points()
185                    }
186                };
187                let (rect, _) = self
188                    .ui
189                    .allocate_exact_size(Vec2::new(th, avail_h), egui::Sense::hover());
190                let x = subpixel_snap(rect.center().x, scale);
191                self.ui.painter().line_segment(
192                    [Pos2::new(x, rect.top()), Pos2::new(x, rect.bottom())],
193                    Stroke::new(th, color),
194                );
195            }
196        }
197        self.ui.add_space(self.spacing * 0.5);
198    }
199}
200
201impl<'a> MacStackView<'a> {
202    /// Creates a new stack view with the specified orientation.
203    pub fn new(orientation: MacStackOrientation) -> Self {
204        Self {
205            orientation,
206            alignment: MacStackAlignment::Leading,
207            theme: None,
208            spacing: None,
209            padding: None,
210            show_separators: false,
211            width: None,
212            height: None,
213        }
214    }
215
216    /// Creates a vertical column stack view (default).
217    pub fn vertical() -> Self {
218        Self::new(MacStackOrientation::Vertical)
219    }
220
221    /// Creates a horizontal row stack view.
222    pub fn horizontal() -> Self {
223        Self::new(MacStackOrientation::Horizontal)
224    }
225
226    /// Injects dynamic theme to eliminate hardcoded metrics and colors.
227    pub fn theme(mut self, theme: &'a MacTheme) -> Self {
228        self.theme = Some(theme);
229        self
230    }
231
232    /// Sets cross-axis alignment.
233    pub fn alignment(mut self, alignment: MacStackAlignment) -> Self {
234        self.alignment = alignment;
235        self
236    }
237
238    /// Customizes spacing between adjacent elements in points.
239    pub fn spacing(mut self, spacing: f32) -> Self {
240        self.spacing = Some(spacing);
241        self
242    }
243
244    /// Customizes outer edge padding around all stacked elements in points.
245    pub fn padding(mut self, padding: f32) -> Self {
246        self.padding = Some(padding);
247        self
248    }
249
250    /// Enables automatic hairline separators between adjacent items and sections.
251    pub fn show_separators(mut self, show: bool) -> Self {
252        self.show_separators = show;
253        self
254    }
255
256    /// Sets container width constraint in points.
257    pub fn width(mut self, width: f32) -> Self {
258        self.width = Some(width);
259        self
260    }
261
262    /// Sets container height constraint in points.
263    pub fn height(mut self, height: f32) -> Self {
264        self.height = Some(height);
265        self
266    }
267
268    /// Renders the linear stack and executes the items closure.
269    pub fn show<R>(
270        self,
271        ui: &mut Ui,
272        add_contents: impl FnOnce(&mut MacStackUi<'_>) -> R,
273    ) -> MacStackViewOutput<R> {
274        let fallback_theme;
275        let theme = match self.theme {
276            Some(t) => t,
277            None => {
278                fallback_theme = MacTheme::default();
279                &fallback_theme
280            }
281        };
282
283        let metrics = theme.stack_view();
284        let spacing = self
285            .spacing
286            .unwrap_or_else(|| metrics.default_spacing.points());
287        let padding = self
288            .padding
289            .unwrap_or_else(|| metrics.edge_padding.points());
290        let separator_thickness = metrics.separator_thickness.points();
291
292        let available = ui.available_rect_before_wrap();
293        let target_w = self.width.unwrap_or(available.width());
294        let target_h = self.height.unwrap_or(available.height());
295        let container_rect = Rect::from_min_size(available.min, Vec2::new(target_w, target_h));
296
297        let inner_rect = container_rect.shrink(padding);
298
299        let mut child_ui = match self.orientation {
300            MacStackOrientation::Vertical => {
301                let layout = egui::Layout::top_down(match self.alignment {
302                    MacStackAlignment::Leading => egui::Align::Min,
303                    MacStackAlignment::Center => egui::Align::Center,
304                    MacStackAlignment::Trailing => egui::Align::Max,
305                });
306                ui.new_child(UiBuilder::new().max_rect(inner_rect).layout(layout))
307            }
308            MacStackOrientation::Horizontal => {
309                let layout = egui::Layout::left_to_right(match self.alignment {
310                    MacStackAlignment::Leading => egui::Align::Min,
311                    MacStackAlignment::Center => egui::Align::Center,
312                    MacStackAlignment::Trailing => egui::Align::Max,
313                });
314                ui.new_child(UiBuilder::new().max_rect(inner_rect).layout(layout))
315            }
316        };
317
318        let mut stack_ui = MacStackUi {
319            ui: &mut child_ui,
320            theme,
321            orientation: self.orientation,
322            spacing,
323            separator_thickness,
324            show_separators: self.show_separators,
325            container_height: self.height,
326            padding,
327            item_count: 0,
328            section_count: 0,
329        };
330
331        let inner = add_contents(&mut stack_ui);
332        let items_rect = stack_ui.ui.min_rect();
333        let content_w = if items_rect.is_positive() {
334            items_rect.width() + padding * 2.0
335        } else {
336            padding * 2.0
337        };
338        let content_h = if items_rect.is_positive() {
339            items_rect.height() + padding * 2.0
340        } else {
341            padding * 2.0
342        };
343        let final_w = self.width.unwrap_or(content_w).max(content_w);
344        let final_h = self.height.unwrap_or(content_h).max(content_h);
345        let final_rect = Rect::from_min_size(container_rect.min, Vec2::new(final_w, final_h));
346
347        ui.allocate_rect(final_rect, egui::Sense::hover());
348
349        MacStackViewOutput {
350            inner,
351            rect: final_rect,
352            item_count: stack_ui.item_count,
353            section_count: stack_ui.section_count,
354        }
355    }
356}