blit-widget 0.1.0

built-in widgets for blit
Documentation
use blit::{Axis, Context, Fit, LayoutCx, NodeId, Scalar};

use super::{Align, Justify, Sizing, justify_offset, percent_share};

blit::builder! {
    /// wraps children into rows or columns
    ///
    /// measured sizes choose the runs, then grow children share the space left in each run
    /// if a grow child reaches its limit, the unused space is left for justification
    #[derive(Clone, Copy, Debug, PartialEq)]
    pub struct Layout<T: Scalar> {
        new(axis: Axis),
        item_gap: T = T::ZERO,
        run_gap: T = T::ZERO,
        align: Align = Align::Start,
        justify: Justify = Justify::Start,
    }
}

blit::builder! {
    /// sizing overrides for a wrapping child
    /// exact local dimensions take precedence over item sizing
    #[derive(Clone, Copy, Debug, PartialEq)]
    pub struct Item<T: Scalar> {
        new(),
        #[into]
        width: Sizing<T> = Sizing::fit(),
        #[into]
        height: Sizing<T> = Sizing::fit(),
    }
}

impl<T: Scalar> Layout<T> {
    pub fn gap(mut self, gap: T) -> Self {
        self.item_gap = gap;
        self.run_gap = gap;
        self
    }
}

impl<T: Scalar> Item<T> {
    pub fn grow(mut self) -> Self {
        self.width = Sizing::grow();
        self.height = Sizing::grow();
        self
    }

    pub fn sizing(&self, axis: Axis) -> Sizing<T> {
        match axis {
            Axis::Horizontal => self.width,
            Axis::Vertical => self.height,
        }
    }
}

pub fn new<T: Scalar>(axis: Axis) -> Layout<T> {
    Layout::new(axis)
}

pub fn horizontal<T: Scalar>() -> Layout<T> {
    new(Axis::Horizontal)
}

pub fn vertical<T: Scalar>() -> Layout<T> {
    new(Axis::Vertical)
}

pub fn item<T: Scalar>() -> Item<T> {
    Item::new()
}

impl<C: Context<Scalar = T>, T: Scalar> blit::Layout<C> for Layout<T> {
    type Item = Item<T>;

    fn fit(&self, cx: &mut LayoutCx<'_, C, Self::Item>, axis: Axis) -> Fit<T> {
        let item_gap = self.item_gap.max(T::ZERO);
        let run_gap = self.run_gap.max(T::ZERO);
        if axis == self.axis {
            let mut min = T::ZERO;
            let mut natural = T::ZERO;
            let mut count = 0usize;
            for child in cx.children() {
                let fit = child_fit(cx, child, axis, T::UNBOUNDED, &mut 0.0);
                min = min.max(fit.min);
                natural += fit.natural;
                count += 1;
            }
            if count > 1 {
                natural += item_gap.repeat(count - 1);
            }
            return Fit::new(min, natural);
        }
        let available = cx.across();
        let mut pending = cx.children().peekable();
        let mut children = cx.children();
        let mut percentages = 0.0;
        let mut total_cross = Fit::ZERO;
        let mut runs = 0usize;
        let use_size = self.axis == Axis::Horizontal;
        while pending.peek().is_some() {
            let (count, _) = next_run(
                &mut pending,
                |child| {
                    if use_size {
                        self.axis.extent(cx.size(*child))
                    } else {
                        child_fit(cx, *child, self.axis, available, &mut percentages).natural
                    }
                },
                available,
                item_gap,
            );
            let mut run_cross = Fit::ZERO;
            for child in children.by_ref().take(count) {
                run_cross = run_cross.max(child_fit(cx, child, axis, T::UNBOUNDED, &mut 0.0));
            }
            let gap = if runs == 0 { T::ZERO } else { run_gap };
            total_cross += run_cross + Fit::exact(gap);
            runs += 1;
        }
        total_cross
    }

    fn distribute(&self, cx: &mut LayoutCx<'_, C, Self::Item>, axis: Axis, extent: T) {
        let item_gap = self.item_gap.max(T::ZERO);
        let run_gap = self.run_gap.max(T::ZERO);
        if axis == self.axis {
            let mut pending = cx.children().peekable();
            let mut children = cx.children();
            let mut percentages = 0.0;
            while pending.peek().is_some() {
                let saved = percentages;
                let mut peek_pct = saved;
                let (count, _) = next_run(
                    &mut pending,
                    |child| child_fit(cx, *child, axis, extent, &mut peek_pct).natural,
                    extent,
                    item_gap,
                );
                let gaps = item_gap.repeat(count.saturating_sub(1));
                let mut used = gaps;
                let mut grows = 0usize;
                let mut run_pct = saved;
                for child in children.take(count) {
                    used += child_fit(cx, child, axis, extent, &mut run_pct).natural;
                    if let Sizing::Grow { .. } = resolve_sizing(cx, child, axis) {
                        grows += 1;
                    }
                }
                let growth = if grows == 0 || !extent.is_finite() {
                    0.0
                } else {
                    (extent - used).max(T::ZERO).to_f32() / grows as f32
                };
                let mut allocation = 0.0;
                let mut run_pct = saved;
                let mut main = gaps;
                for child in children.take(count) {
                    let base = child_fit(cx, child, axis, extent, &mut run_pct).natural;
                    let sizing = resolve_sizing(cx, child, axis);
                    let assigned = if let Sizing::Grow { min, max } = sizing {
                        let capacity = if max == T::UNBOUNDED {
                            f32::INFINITY
                        } else {
                            (max.max(min.max(T::ZERO)) - base).max(T::ZERO).to_f32()
                        };
                        sizing.clamp(base + T::allocate(&mut allocation, growth.min(capacity)))
                    } else {
                        base
                    };
                    main += cx.set_extent(child, assigned);
                }
                percentages = run_pct;
                let (offset, mut spacing, extra_gap) =
                    justify_offset(self.justify, (extent - main).max(T::ZERO), count);
                let mut main_cursor = offset;
                for child in children.by_ref().take(count) {
                    cx.set_offset(child, main_cursor + T::from_f32(spacing));
                    main_cursor += self.axis.extent(cx.size(child)) + item_gap;
                    spacing += extra_gap;
                }
            }
            return;
        }

        let available = cx.across();
        let mut pending = cx.children().peekable();
        let mut children = cx.children();
        let mut percentages = 0.0;
        let use_size = self.axis == Axis::Horizontal;
        let mut cross_cursor = T::ZERO;
        while pending.peek().is_some() {
            let (count, _) = next_run(
                &mut pending,
                |child| {
                    if use_size {
                        self.axis.extent(cx.size(*child))
                    } else {
                        child_fit(cx, *child, self.axis, available, &mut percentages).natural
                    }
                },
                available,
                item_gap,
            );
            let mut run_cross = T::ZERO;
            for child in children.take(count) {
                run_cross = run_cross.max(child_fit(cx, child, axis, extent, &mut 0.0).natural);
            }
            for child in children.by_ref().take(count) {
                let sizing = resolve_sizing(cx, child, axis);
                let assigned = match (sizing, self.align) {
                    (Sizing::Grow { .. }, _) | (Sizing::Fit { .. }, Align::Stretch) => sizing.clamp(run_cross),
                    _ => child_fit(cx, child, axis, extent, &mut 0.0).natural,
                };
                let child_cross = cx.set_extent(child, assigned);
                let cross_offset = match self.align {
                    Align::Start | Align::Stretch => T::ZERO,
                    Align::Center => T::ZERO.lerp((run_cross - child_cross).max(T::ZERO), 0.5),
                    Align::End => (run_cross - child_cross).max(T::ZERO),
                };
                cx.set_offset(child, cross_cursor + cross_offset);
            }
            cross_cursor += run_cross + run_gap;
        }
    }
}

fn next_run<T: Scalar, I: Iterator>(
    widths: &mut core::iter::Peekable<I>,
    mut size: impl FnMut(&I::Item) -> T,
    available: T,
    gap: T,
) -> (usize, T) {
    let mut count = 0;
    let mut used = T::ZERO;
    let tolerance = T::from_f32(available.to_f32().abs() * f32::EPSILON);
    while let Some(item) = widths.peek() {
        let width = size(item);
        let needed = width.endpoint(if count == 0 { T::ZERO } else { gap });
        let total = used.endpoint(needed);
        if count != 0 && total > available.endpoint(tolerance.repeat(count + 1)) {
            break;
        }
        widths.next();
        used = total;
        count += 1;
    }
    (count, used)
}

fn resolve_sizing<C: Context>(cx: &LayoutCx<'_, C, Item<C::Scalar>>, child: NodeId, axis: Axis) -> Sizing<C::Scalar> {
    cx.fixed_extent(child, axis)
        .map_or(cx.item(child).sizing(axis), Sizing::Fixed)
}

fn child_fit<C: Context>(
    cx: &LayoutCx<'_, C, Item<C::Scalar>>,
    child: NodeId,
    axis: Axis,
    available: C::Scalar,
    percentages: &mut f32,
) -> Fit<C::Scalar> {
    let sizing = resolve_sizing(cx, child, axis);
    match sizing {
        Sizing::Fixed(v) => Fit::exact(v.max(C::Scalar::ZERO)),
        Sizing::Percent(p) => Fit::exact(percent_share(available, p, percentages)),
        Sizing::Fit { .. } | Sizing::Grow { .. } => {
            let fit = cx.fit(child, axis);
            let min = sizing.clamp(fit.min);
            let natural = sizing.clamp(fit.natural).min(available).max(min);
            Fit::new(min, natural)
        }
    }
}