blit-widget 0.1.0

built-in widgets for blit
Documentation
pub mod absolute;
pub mod flex;
pub mod grid;
pub mod rect;
pub mod wrap;

use blit::Scalar;

/// allocation requested from a parent layout on one axis
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Sizing<T> {
    Fit { min: T, max: T },
    Grow { min: T, max: T },
    Fixed(T),
    Percent(f32),
}

impl<T: Scalar> Sizing<T> {
    pub const fn fit() -> Self {
        Self::fit_range(T::ZERO, T::UNBOUNDED)
    }
    pub const fn fit_range(min: T, max: T) -> Self {
        Self::Fit { min, max }
    }
    pub const fn grow() -> Self {
        Self::grow_range(T::ZERO, T::UNBOUNDED)
    }
    pub const fn grow_range(min: T, max: T) -> Self {
        Self::Grow { min, max }
    }
    pub const fn fixed(size: T) -> Self {
        Self::Fixed(size)
    }
    pub const fn percent(fraction: f32) -> Self {
        Self::Percent(fraction)
    }

    #[inline]
    pub fn clamp(self, size: T) -> T {
        match self {
            Self::Fit { min, max } | Self::Grow { min, max } => {
                let min = min.max(T::ZERO);
                size.clamp(min, max.max(min))
            }
            Self::Fixed(fixed) => fixed.max(T::ZERO),
            Self::Percent(_) => size.max(T::ZERO),
        }
    }
}

impl<T: Scalar> From<T> for Sizing<T> {
    fn from(size: T) -> Self {
        Self::Fixed(size)
    }
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Align {
    Start,
    Center,
    End,
    #[default]
    Stretch,
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Justify {
    #[default]
    Start,
    Center,
    End,
    SpaceBetween,
    SpaceAround,
    SpaceEvenly,
}

#[inline]
fn percent_share<T: Scalar>(available: T, fraction: f32, cursor: &mut f32) -> T {
    assert!((0.0..=1.0).contains(&fraction));
    let share = if available.is_finite() {
        available.to_f32() * fraction
    } else {
        0.0
    };
    T::allocate(cursor, share)
}

fn justify_offset<T: Scalar>(justify: Justify, remaining: T, count: usize) -> (T, f32, f32) {
    match justify {
        Justify::Start => (T::ZERO, 0.0, 0.0),
        Justify::Center => (T::ZERO.lerp(remaining, 0.5), 0.0, 0.0),
        Justify::End => (remaining, 0.0, 0.0),
        Justify::SpaceBetween if count > 1 => (T::ZERO, 0.0, remaining.to_f32() / (count - 1) as f32),
        Justify::SpaceAround if count != 0 => {
            let space = remaining.to_f32() / count as f32;
            (T::ZERO, space / 2.0, space)
        }
        Justify::SpaceEvenly if count != 0 => {
            let space = remaining.to_f32() / (count + 1) as f32;
            (T::ZERO, space, space)
        }
        _ => (T::ZERO, 0.0, 0.0),
    }
}