Skip to main content

aylis_core/
align.rs

1//! Alinhamento e âncoras dos controles dentro do pai.
2
3use std::ops::BitOr;
4
5use crate::prop::PropEnum;
6
7/// Alinhamento de um controle dentro do pai.
8///
9/// Os alinhamentos de encaixe (`MostTop`…`Right`) consomem espaço da área livre do pai,
10/// nesta ordem: `MostTop`, `MostBottom`, `MostLeft`, `MostRight`, `Top`, `Bottom`,
11/// `Left`, `Right`. Controles com o mesmo alinhamento seguem a ordem dos filhos.
12/// Os demais usam a área que sobrou.
13#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
14pub enum Align {
15    /// Posição e tamanho livres; obedece às [`Anchors`].
16    #[default]
17    None,
18    Top,
19    Bottom,
20    Left,
21    Right,
22    MostTop,
23    MostBottom,
24    MostLeft,
25    MostRight,
26    /// Ocupa toda a área que sobrou.
27    Client,
28    /// Ocupa o pai inteiro, ignorando o padding e os outros controles.
29    Contents,
30    /// Mantém o tamanho e centraliza na área que sobrou.
31    Center,
32    /// Centraliza na vertical e estica na horizontal.
33    VertCenter,
34    /// Centraliza na horizontal e estica na vertical.
35    HorzCenter,
36    /// Estica na horizontal; mantém `top` e `height`.
37    Horizontal,
38    /// Estica na vertical; mantém `left` e `width`.
39    Vertical,
40    /// Escala mantendo a proporção até caber, centralizado.
41    Fit,
42}
43
44impl Align {
45    pub const ALL: [Align; 17] = [
46        Align::None,
47        Align::Top,
48        Align::Bottom,
49        Align::Left,
50        Align::Right,
51        Align::MostTop,
52        Align::MostBottom,
53        Align::MostLeft,
54        Align::MostRight,
55        Align::Client,
56        Align::Contents,
57        Align::Center,
58        Align::VertCenter,
59        Align::HorzCenter,
60        Align::Horizontal,
61        Align::Vertical,
62        Align::Fit,
63    ];
64
65    /// Verdadeiro para os alinhamentos que consomem espaço da área livre.
66    pub fn is_dock(self) -> bool {
67        matches!(
68            self,
69            Align::Top
70                | Align::Bottom
71                | Align::Left
72                | Align::Right
73                | Align::MostTop
74                | Align::MostBottom
75                | Align::MostLeft
76                | Align::MostRight
77        )
78    }
79}
80
81impl PropEnum for Align {
82    const NAMES: &'static [&'static str] = &[
83        "none",
84        "top",
85        "bottom",
86        "left",
87        "right",
88        "most_top",
89        "most_bottom",
90        "most_left",
91        "most_right",
92        "client",
93        "contents",
94        "center",
95        "vert_center",
96        "horz_center",
97        "horizontal",
98        "vertical",
99        "fit",
100    ];
101
102    fn from_index(index: usize) -> Option<Self> {
103        Align::ALL.get(index).copied()
104    }
105
106    fn index(self) -> usize {
107        self as usize
108    }
109}
110
111/// Onde um controle encaixado fica no sentido em que o encaixe estica (como o `align-self`
112/// do CSS): em cima ou embaixo, na horizontal; à esquerda ou à direita, na vertical.
113///
114/// `Stretch` (o padrão) ocupa a faixa inteira (com a `max_width`, no meio). Os outros mantêm
115/// a própria `width` (ou `height`) e encostam no começo, no meio ou no fim: um botão ou um
116/// fundo do tamanho do conteúdo numa pilha de campos, sem conta de margem pela largura do pai.
117/// Com a `max_width` (ou `max_height`), ocupam a faixa até a máxima e encostam do mesmo
118/// jeito: uma coluna de leitura à esquerda numa tela larga.
119#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
120pub enum SelfAlign {
121    #[default]
122    Stretch,
123    Start,
124    Center,
125    End,
126}
127
128impl SelfAlign {
129    pub const ALL: [SelfAlign; 4] = [SelfAlign::Stretch, SelfAlign::Start, SelfAlign::Center, SelfAlign::End];
130}
131
132impl PropEnum for SelfAlign {
133    const NAMES: &'static [&'static str] = &["stretch", "start", "center", "end"];
134
135    fn from_index(index: usize) -> Option<Self> {
136        SelfAlign::ALL.get(index).copied()
137    }
138
139    fn index(self) -> usize {
140        self as usize
141    }
142}
143
144/// Lados do pai aos quais um controle com `Align::None` fica preso.
145///
146/// - esquerda + direita: a largura acompanha o pai;
147/// - só direita: o controle se move junto com a borda direita;
148/// - nenhum dos dois: o controle se move metade do quanto o pai cresceu.
149///
150/// O mesmo vale para cima/embaixo. O padrão é esquerda + cima.
151#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
152pub struct Anchors(u8);
153
154impl Anchors {
155    pub const NONE: Anchors = Anchors(0);
156    pub const LEFT: Anchors = Anchors(1);
157    pub const TOP: Anchors = Anchors(1 << 1);
158    pub const RIGHT: Anchors = Anchors(1 << 2);
159    pub const BOTTOM: Anchors = Anchors(1 << 3);
160    pub const ALL: Anchors = Anchors(0b1111);
161
162    /// Nomes na mesma ordem dos bits.
163    pub const NAMES: [&'static str; 4] = ["left", "top", "right", "bottom"];
164
165    pub const fn contains(self, other: Anchors) -> bool {
166        self.0 & other.0 == other.0
167    }
168
169    pub const fn union(self, other: Anchors) -> Anchors {
170        Anchors(self.0 | other.0)
171    }
172
173    pub fn names(self) -> Vec<String> {
174        Self::NAMES
175            .iter()
176            .enumerate()
177            .filter(|(i, _)| self.0 & (1 << i) != 0)
178            .map(|(_, n)| n.to_string())
179            .collect()
180    }
181
182    /// Monta a partir de nomes (`"left"`, `"right"`...). `None` se algum nome for inválido.
183    pub fn from_names<I, S>(names: I) -> Option<Anchors>
184    where
185        I: IntoIterator<Item = S>,
186        S: AsRef<str>,
187    {
188        let mut bits = 0u8;
189        for name in names {
190            let i = Self::NAMES.iter().position(|n| n.eq_ignore_ascii_case(name.as_ref()))?;
191            bits |= 1 << i;
192        }
193        Some(Anchors(bits))
194    }
195}
196
197impl Default for Anchors {
198    fn default() -> Self {
199        Anchors::LEFT | Anchors::TOP
200    }
201}
202
203impl BitOr for Anchors {
204    type Output = Anchors;
205    fn bitor(self, other: Anchors) -> Anchors {
206        self.union(other)
207    }
208}