Skip to main content

blit_widget/layout/
wrap.rs

1use blit::{Axis, Context, Fit, LayoutCx, NodeId, Scalar};
2
3use super::{Align, Justify, Sizing, justify_offset, percent_share};
4
5blit::builder! {
6    /// wraps children into rows or columns
7    ///
8    /// measured sizes choose the runs, then grow children share the space left in each run
9    /// if a grow child reaches its limit, the unused space is left for justification
10    #[derive(Clone, Copy, Debug, PartialEq)]
11    pub struct Layout<T: Scalar> {
12        new(axis: Axis),
13        item_gap: T = T::ZERO,
14        run_gap: T = T::ZERO,
15        align: Align = Align::Start,
16        justify: Justify = Justify::Start,
17    }
18}
19
20blit::builder! {
21    /// sizing overrides for a wrapping child
22    /// exact local dimensions take precedence over item sizing
23    #[derive(Clone, Copy, Debug, PartialEq)]
24    pub struct Item<T: Scalar> {
25        new(),
26        #[into]
27        width: Sizing<T> = Sizing::fit(),
28        #[into]
29        height: Sizing<T> = Sizing::fit(),
30    }
31}
32
33impl<T: Scalar> Layout<T> {
34    pub fn gap(mut self, gap: T) -> Self {
35        self.item_gap = gap;
36        self.run_gap = gap;
37        self
38    }
39}
40
41impl<T: Scalar> Item<T> {
42    pub fn grow(mut self) -> Self {
43        self.width = Sizing::grow();
44        self.height = Sizing::grow();
45        self
46    }
47
48    pub fn sizing(&self, axis: Axis) -> Sizing<T> {
49        match axis {
50            Axis::Horizontal => self.width,
51            Axis::Vertical => self.height,
52        }
53    }
54}
55
56pub fn new<T: Scalar>(axis: Axis) -> Layout<T> {
57    Layout::new(axis)
58}
59
60pub fn horizontal<T: Scalar>() -> Layout<T> {
61    new(Axis::Horizontal)
62}
63
64pub fn vertical<T: Scalar>() -> Layout<T> {
65    new(Axis::Vertical)
66}
67
68pub fn item<T: Scalar>() -> Item<T> {
69    Item::new()
70}
71
72impl<C: Context<Scalar = T>, T: Scalar> blit::Layout<C> for Layout<T> {
73    type Item = Item<T>;
74
75    fn fit(&self, cx: &mut LayoutCx<'_, C, Self::Item>, axis: Axis) -> Fit<T> {
76        let item_gap = self.item_gap.max(T::ZERO);
77        let run_gap = self.run_gap.max(T::ZERO);
78        if axis == self.axis {
79            let mut min = T::ZERO;
80            let mut natural = T::ZERO;
81            let mut count = 0usize;
82            for child in cx.children() {
83                let fit = child_fit(cx, child, axis, T::UNBOUNDED, &mut 0.0);
84                min = min.max(fit.min);
85                natural += fit.natural;
86                count += 1;
87            }
88            if count > 1 {
89                natural += item_gap.repeat(count - 1);
90            }
91            return Fit::new(min, natural);
92        }
93        let available = cx.across();
94        let mut pending = cx.children().peekable();
95        let mut children = cx.children();
96        let mut percentages = 0.0;
97        let mut total_cross = Fit::ZERO;
98        let mut runs = 0usize;
99        let use_size = self.axis == Axis::Horizontal;
100        while pending.peek().is_some() {
101            let (count, _) = next_run(
102                &mut pending,
103                |child| {
104                    if use_size {
105                        self.axis.extent(cx.size(*child))
106                    } else {
107                        child_fit(cx, *child, self.axis, available, &mut percentages).natural
108                    }
109                },
110                available,
111                item_gap,
112            );
113            let mut run_cross = Fit::ZERO;
114            for child in children.by_ref().take(count) {
115                run_cross = run_cross.max(child_fit(cx, child, axis, T::UNBOUNDED, &mut 0.0));
116            }
117            let gap = if runs == 0 { T::ZERO } else { run_gap };
118            total_cross += run_cross + Fit::exact(gap);
119            runs += 1;
120        }
121        total_cross
122    }
123
124    fn distribute(&self, cx: &mut LayoutCx<'_, C, Self::Item>, axis: Axis, extent: T) {
125        let item_gap = self.item_gap.max(T::ZERO);
126        let run_gap = self.run_gap.max(T::ZERO);
127        if axis == self.axis {
128            let mut pending = cx.children().peekable();
129            let mut children = cx.children();
130            let mut percentages = 0.0;
131            while pending.peek().is_some() {
132                let saved = percentages;
133                let mut peek_pct = saved;
134                let (count, _) = next_run(
135                    &mut pending,
136                    |child| child_fit(cx, *child, axis, extent, &mut peek_pct).natural,
137                    extent,
138                    item_gap,
139                );
140                let gaps = item_gap.repeat(count.saturating_sub(1));
141                let mut used = gaps;
142                let mut grows = 0usize;
143                let mut run_pct = saved;
144                for child in children.take(count) {
145                    used += child_fit(cx, child, axis, extent, &mut run_pct).natural;
146                    if let Sizing::Grow { .. } = resolve_sizing(cx, child, axis) {
147                        grows += 1;
148                    }
149                }
150                let growth = if grows == 0 || !extent.is_finite() {
151                    0.0
152                } else {
153                    (extent - used).max(T::ZERO).to_f32() / grows as f32
154                };
155                let mut allocation = 0.0;
156                let mut run_pct = saved;
157                let mut main = gaps;
158                for child in children.take(count) {
159                    let base = child_fit(cx, child, axis, extent, &mut run_pct).natural;
160                    let sizing = resolve_sizing(cx, child, axis);
161                    let assigned = if let Sizing::Grow { min, max } = sizing {
162                        let capacity = if max == T::UNBOUNDED {
163                            f32::INFINITY
164                        } else {
165                            (max.max(min.max(T::ZERO)) - base).max(T::ZERO).to_f32()
166                        };
167                        sizing.clamp(base + T::allocate(&mut allocation, growth.min(capacity)))
168                    } else {
169                        base
170                    };
171                    main += cx.set_extent(child, assigned);
172                }
173                percentages = run_pct;
174                let (offset, mut spacing, extra_gap) =
175                    justify_offset(self.justify, (extent - main).max(T::ZERO), count);
176                let mut main_cursor = offset;
177                for child in children.by_ref().take(count) {
178                    cx.set_offset(child, main_cursor + T::from_f32(spacing));
179                    main_cursor += self.axis.extent(cx.size(child)) + item_gap;
180                    spacing += extra_gap;
181                }
182            }
183            return;
184        }
185
186        let available = cx.across();
187        let mut pending = cx.children().peekable();
188        let mut children = cx.children();
189        let mut percentages = 0.0;
190        let use_size = self.axis == Axis::Horizontal;
191        let mut cross_cursor = T::ZERO;
192        while pending.peek().is_some() {
193            let (count, _) = next_run(
194                &mut pending,
195                |child| {
196                    if use_size {
197                        self.axis.extent(cx.size(*child))
198                    } else {
199                        child_fit(cx, *child, self.axis, available, &mut percentages).natural
200                    }
201                },
202                available,
203                item_gap,
204            );
205            let mut run_cross = T::ZERO;
206            for child in children.take(count) {
207                run_cross = run_cross.max(child_fit(cx, child, axis, extent, &mut 0.0).natural);
208            }
209            for child in children.by_ref().take(count) {
210                let sizing = resolve_sizing(cx, child, axis);
211                let assigned = match (sizing, self.align) {
212                    (Sizing::Grow { .. }, _) | (Sizing::Fit { .. }, Align::Stretch) => sizing.clamp(run_cross),
213                    _ => child_fit(cx, child, axis, extent, &mut 0.0).natural,
214                };
215                let child_cross = cx.set_extent(child, assigned);
216                let cross_offset = match self.align {
217                    Align::Start | Align::Stretch => T::ZERO,
218                    Align::Center => T::ZERO.lerp((run_cross - child_cross).max(T::ZERO), 0.5),
219                    Align::End => (run_cross - child_cross).max(T::ZERO),
220                };
221                cx.set_offset(child, cross_cursor + cross_offset);
222            }
223            cross_cursor += run_cross + run_gap;
224        }
225    }
226}
227
228fn next_run<T: Scalar, I: Iterator>(
229    widths: &mut core::iter::Peekable<I>,
230    mut size: impl FnMut(&I::Item) -> T,
231    available: T,
232    gap: T,
233) -> (usize, T) {
234    let mut count = 0;
235    let mut used = T::ZERO;
236    let tolerance = T::from_f32(available.to_f32().abs() * f32::EPSILON);
237    while let Some(item) = widths.peek() {
238        let width = size(item);
239        let needed = width.endpoint(if count == 0 { T::ZERO } else { gap });
240        let total = used.endpoint(needed);
241        if count != 0 && total > available.endpoint(tolerance.repeat(count + 1)) {
242            break;
243        }
244        widths.next();
245        used = total;
246        count += 1;
247    }
248    (count, used)
249}
250
251fn resolve_sizing<C: Context>(cx: &LayoutCx<'_, C, Item<C::Scalar>>, child: NodeId, axis: Axis) -> Sizing<C::Scalar> {
252    cx.fixed_extent(child, axis)
253        .map_or(cx.item(child).sizing(axis), Sizing::Fixed)
254}
255
256fn child_fit<C: Context>(
257    cx: &LayoutCx<'_, C, Item<C::Scalar>>,
258    child: NodeId,
259    axis: Axis,
260    available: C::Scalar,
261    percentages: &mut f32,
262) -> Fit<C::Scalar> {
263    let sizing = resolve_sizing(cx, child, axis);
264    match sizing {
265        Sizing::Fixed(v) => Fit::exact(v.max(C::Scalar::ZERO)),
266        Sizing::Percent(p) => Fit::exact(percent_share(available, p, percentages)),
267        Sizing::Fit { .. } | Sizing::Grow { .. } => {
268            let fit = cx.fit(child, axis);
269            let min = sizing.clamp(fit.min);
270            let natural = sizing.clamp(fit.natural).min(available).max(min);
271            Fit::new(min, natural)
272        }
273    }
274}