Skip to main content

fret_ui/layout/
constraints.rs

1use fret_core::Px;
2
3#[derive(Debug, Clone, Copy, PartialEq)]
4pub struct LayoutSize<T> {
5    pub width: T,
6    pub height: T,
7}
8
9impl<T> LayoutSize<T> {
10    pub const fn new(width: T, height: T) -> Self {
11        Self { width, height }
12    }
13
14    pub fn map<U>(self, f: impl FnMut(T) -> U) -> LayoutSize<U> {
15        let LayoutSize { width, height } = self;
16        let mut f = f;
17        LayoutSize {
18            width: f(width),
19            height: f(height),
20        }
21    }
22}
23
24#[derive(Debug, Default, Clone, Copy, PartialEq)]
25pub enum AvailableSpace {
26    Definite(Px),
27    #[default]
28    MinContent,
29    MaxContent,
30}
31
32impl AvailableSpace {
33    pub const fn is_definite(self) -> bool {
34        matches!(self, Self::Definite(_))
35    }
36
37    pub const fn definite(self) -> Option<Px> {
38        match self {
39            Self::Definite(px) => Some(px),
40            Self::MinContent | Self::MaxContent => None,
41        }
42    }
43
44    pub fn shrink_by(self, delta_px: f32) -> Self {
45        match self {
46            Self::Definite(px) => Self::Definite(Px((px.0 - delta_px).max(0.0))),
47            Self::MinContent => Self::MinContent,
48            Self::MaxContent => Self::MaxContent,
49        }
50    }
51}
52
53#[derive(Debug, Clone, Copy, PartialEq)]
54pub struct LayoutConstraints {
55    pub known: LayoutSize<Option<Px>>,
56    pub available: LayoutSize<AvailableSpace>,
57}
58
59impl LayoutConstraints {
60    pub const fn new(known: LayoutSize<Option<Px>>, available: LayoutSize<AvailableSpace>) -> Self {
61        Self { known, available }
62    }
63}