Skip to main content

eternal_ui/
layout.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! Sizing and placing elements.
6//!
7//! Containers lay their children out along one axis, like a CSS flex row or
8//! column with `flex-wrap: nowrap`. Sizes come from the stylesheet (`width`,
9//! `height`, `min-*`, `max-*`, `margin`, `padding`, `border`, `gap`); which
10//! way a container goes, whether a child grows, and how children are
11//! aligned are attributes on the elements, since they are about structure
12//! rather than looks: `grow` and `align` on a child, `align_items` and
13//! `justify` on a container.
14//!
15//! `width` and `height` are border-box sizes, as with
16//! `box-sizing: border-box`. Percentages are of the parent's content box.
17//! The root always fills the viewport.
18
19use eternal_styler::{ComputedStyle, LengthPercentageOrAuto, LengthPercentageOrNone, Sides};
20
21use crate::geometry::{Axis, Point, Rect, Size, side_start, sides_along};
22use crate::render::Fonts;
23use crate::ui::{NodeId, Ui};
24
25/// Where a child sits across its container's axis.
26#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
27pub enum Align {
28    Start,
29    Center,
30    End,
31    /// Fill the container across the axis, unless the child has an explicit
32    /// size that way.
33    #[default]
34    Stretch,
35}
36
37impl Align {
38    pub fn parse(text: &str) -> Option<Self> {
39        Some(match text.trim() {
40            "start" => Self::Start,
41            "center" => Self::Center,
42            "end" => Self::End,
43            "stretch" => Self::Stretch,
44            _ => return None,
45        })
46    }
47}
48
49/// How a container spreads its children along its axis when they do not
50/// fill it and none of them grows.
51#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
52pub enum Justify {
53    #[default]
54    Start,
55    Center,
56    End,
57    /// The first child at the start, the last at the end, equal gaps
58    /// between.
59    SpaceBetween,
60}
61
62impl Justify {
63    pub fn parse(text: &str) -> Option<Self> {
64        Some(match text.trim() {
65            "start" => Self::Start,
66            "center" => Self::Center,
67            "end" => Self::End,
68            "space-between" => Self::SpaceBetween,
69            _ => return None,
70        })
71    }
72}
73
74/// Padding plus border on each side, in pixels.
75fn edges(style: &ComputedStyle, basis: f32) -> Sides<f32> {
76    Sides::new(
77        style.padding.top.resolve(basis) + style.border_width.top,
78        style.padding.right.resolve(basis) + style.border_width.right,
79        style.padding.bottom.resolve(basis) + style.border_width.bottom,
80        style.padding.left.resolve(basis) + style.border_width.left,
81    )
82}
83
84/// Margins in pixels. `auto` counts as zero.
85fn margins(style: &ComputedStyle, basis: f32) -> Sides<f32> {
86    let resolve = |m: LengthPercentageOrAuto| m.resolve(basis).unwrap_or(0.0);
87    Sides::new(
88        resolve(style.margin.top),
89        resolve(style.margin.right),
90        resolve(style.margin.bottom),
91        resolve(style.margin.left),
92    )
93}
94
95fn clamp(value: f32, min: LengthPercentageOrAuto, max: LengthPercentageOrNone, basis: f32) -> f32 {
96    let value = match max.resolve(basis) {
97        Some(max) => value.min(max),
98        None => value,
99    };
100    match min.resolve(basis) {
101        Some(min) => value.max(min),
102        None => value,
103    }
104}
105
106impl<M: 'static> Ui<M> {
107    /// Recomputes styles if anything changed, then sizes and places every
108    /// element for a window of `viewport` pixels. Call before painting and
109    /// before hit-testing events after a change.
110    pub fn layout(&mut self, viewport: Size, fonts: &dyn Fonts) {
111        self.viewport = viewport;
112        if self.dirty {
113            self.recompute_styles();
114        }
115        let Some(root) = self.root() else {
116            return;
117        };
118        self.measure(root, viewport, fonts);
119        self.arrange(root, Rect::from_origin_size(Point::ZERO, viewport));
120        self.dirty = false;
121    }
122
123    /// The natural border-box size of `id` given the room its parent has,
124    /// stored on the node and returned.
125    fn measure(&mut self, id: NodeId, available: Size, fonts: &dyn Fonts) -> Size {
126        let node = self.node(id);
127        let style = node.style.clone();
128        let axis = node.widget.axis();
129        let children = node.children.clone();
130        let edges = edges(&style, available.width);
131        let inner = Size::new(
132            available.width - edges.left - edges.right,
133            available.height - edges.top - edges.bottom,
134        )
135        .non_negative();
136
137        let content = match axis {
138            Some(axis) => {
139                let gap = match axis {
140                    Axis::Horizontal => style.column_gap,
141                    Axis::Vertical => style.row_gap,
142                }
143                .resolve(inner.main(axis));
144                let mut main = 0.0;
145                let mut cross: f32 = 0.0;
146                for (index, &child) in children.iter().enumerate() {
147                    let margin = margins(&self.node(child).style, inner.width);
148                    let size = self.measure(child, inner, fonts);
149                    main += size.main(axis) + sides_along(margin, axis);
150                    cross = cross.max(size.cross(axis) + sides_along(margin, axis.cross()));
151                    if index > 0 {
152                        main += gap;
153                    }
154                }
155                Size::from_axis(axis, main, cross)
156            }
157            None => node.widget.measure(fonts, &style),
158        };
159
160        let width = match style.width {
161            LengthPercentageOrAuto::Auto => content.width + edges.left + edges.right,
162            LengthPercentageOrAuto::Px(px) => px,
163            LengthPercentageOrAuto::Percent(p) => p * available.width,
164        };
165        let height = match style.height {
166            LengthPercentageOrAuto::Auto => content.height + edges.top + edges.bottom,
167            LengthPercentageOrAuto::Px(px) => px,
168            LengthPercentageOrAuto::Percent(p) => p * available.height,
169        };
170        let size = Size::new(
171            clamp(width, style.min_width, style.max_width, available.width),
172            clamp(height, style.min_height, style.max_height, available.height),
173        )
174        .non_negative();
175        self.node_mut(id).measured = size;
176        size
177    }
178
179    /// Gives `id` its final border box and places its children inside.
180    fn arrange(&mut self, id: NodeId, rect: Rect) {
181        let node = self.node(id);
182        let style = node.style.clone();
183        let Some(axis) = node.widget.axis() else {
184            let content = rect.inset(edges(&style, rect.width));
185            let node = self.node_mut(id);
186            node.rect = rect;
187            node.content = content;
188            return;
189        };
190        let children = node.children.clone();
191        let (container_align, justify) = node.container_alignment();
192        let content = rect.inset(edges(&style, rect.width));
193        {
194            let node = self.node_mut(id);
195            node.rect = rect;
196            node.content = content;
197        }
198
199        let gap = match axis {
200            Axis::Horizontal => style.column_gap,
201            Axis::Vertical => style.row_gap,
202        }
203        .resolve(content.size().main(axis));
204
205        // What each child asked for.
206        struct Item {
207            id: NodeId,
208            measured: Size,
209            margin: Sides<f32>,
210            grow: f32,
211            align: Align,
212            cross_is_auto: bool,
213        }
214        let items: Vec<Item> = children
215            .iter()
216            .map(|&child| {
217                let node = self.node(child);
218                let cross_is_auto = match axis {
219                    Axis::Horizontal => node.style.height == LengthPercentageOrAuto::Auto,
220                    Axis::Vertical => node.style.width == LengthPercentageOrAuto::Auto,
221                };
222                Item {
223                    id: child,
224                    measured: node.measured,
225                    margin: margins(&node.style, content.width),
226                    grow: node.grow,
227                    align: node.align.unwrap_or(container_align),
228                    cross_is_auto,
229                }
230            })
231            .collect();
232
233        let used: f32 = items
234            .iter()
235            .map(|item| item.measured.main(axis) + sides_along(item.margin, axis))
236            .sum::<f32>()
237            + gap * items.len().saturating_sub(1) as f32;
238        let free = (content.size().main(axis) - used).max(0.0);
239        let grow_total: f32 = items.iter().map(|item| item.grow).sum();
240
241        let (mut offset, extra_gap) = if grow_total > 0.0 || items.is_empty() {
242            (0.0, 0.0)
243        } else {
244            match justify {
245                Justify::Start => (0.0, 0.0),
246                Justify::Center => (free / 2.0, 0.0),
247                Justify::End => (free, 0.0),
248                Justify::SpaceBetween if items.len() > 1 => (0.0, free / (items.len() - 1) as f32),
249                Justify::SpaceBetween => (0.0, 0.0),
250            }
251        };
252
253        let content_cross = content.size().cross(axis);
254        for (index, item) in items.iter().enumerate() {
255            if index > 0 {
256                offset += gap + extra_gap;
257            }
258            let main = item.measured.main(axis)
259                + if grow_total > 0.0 {
260                    free * item.grow / grow_total
261                } else {
262                    0.0
263                };
264            let cross_room = content_cross - sides_along(item.margin, axis.cross());
265            let cross = if item.align == Align::Stretch && item.cross_is_auto {
266                cross_room.max(item.measured.cross(axis))
267            } else {
268                item.measured.cross(axis)
269            };
270            let cross_offset = match item.align {
271                Align::Start | Align::Stretch => 0.0,
272                Align::Center => ((cross_room - cross) / 2.0).max(0.0),
273                Align::End => (cross_room - cross).max(0.0),
274            };
275            let main_start = offset + side_start(item.margin, axis);
276            let cross_start = cross_offset + side_start(item.margin, axis.cross());
277            let child_rect = match axis {
278                Axis::Horizontal => {
279                    Rect::new(content.x + main_start, content.y + cross_start, main, cross)
280                }
281                Axis::Vertical => {
282                    Rect::new(content.x + cross_start, content.y + main_start, cross, main)
283                }
284            };
285            self.arrange(item.id, child_rect);
286            offset += main + sides_along(item.margin, axis);
287        }
288    }
289}