haalka 0.7.1

ergonomic reactive Bevy UI library powered by FRP signals
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
//! Simple alignment semantics ported from [MoonZoon](https://github.com/MoonZoon/MoonZoon)'s [`align`](https://github.com/MoonZoon/MoonZoon/blob/main/crates/zoon/src/node/align.rs) and [`align_content`](https://github.com/MoonZoon/MoonZoon/blob/main/crates/zoon/src/node/align_content.rs).
//!
//! An [`Element`](`super::element::Element`) can be aligned in nine different areas in relation to
//! its parent: top left, top center, top right, center left, center, center right, bottom left,
//! bottom center, and bottom right. This provides a simple and clear to way to declare alignment as
//! a thin layer on top of bevy_ui's flexbox implementation.
//!
//! [`Align`]s can be specified on individual elements using [`.align`](`Alignable::align`) and
//! [`.align_signal`](`Alignable::align_signal`) or to all children using
//! [`.align_content`](`Alignable::align_content`) and
//! [`.align_content_signal`](`Alignable::align_content_signal`). See the [align](https://github.com/databasedav/haalka/blob/main/examples/align.rs)
//! example for how each [`Align`] behaves for each built-in alignable type: [`El`], [`Column`],
//! [`Row`], [`Stack`], and [`Grid`].
//!
//! # Notes
//! [`Stack`] and [`Grid`] children (read: children that are either a [`Stack`] or a [`Grid`], not
//! the children *of* [`Stack`]s or [`Grid`]s) do not behave as expected when aligned with a
//! parent's [`.align_content`](`Alignable::align_content`) or
//! [`.align_content_signal`](`Alignable::align_content_signal`); this is a known issue and one can
//! simply align the [`Stack`] or [`Grid`] themselves as workaround.

use std::{collections::BTreeSet, ops::Not};

use bevy_ecs::prelude::*;
use bevy_ui::prelude::*;
use futures_signals::signal::{BoxSignal, Signal, SignalExt};

use super::{
    column::Column,
    el::El,
    element::ElementWrapper,
    grid::Grid,
    raw::{RawElWrapper, RawHaalkaEl},
    row::Row,
    stack::Stack,
};

// TODO: replace moonzoon github links with docs.rs links once moonzoon crate published
// TODO: create and link issue for Stack and Grid content alignment behavior

/// Holder of composable [`Alignment`]s.
#[derive(Clone, Default)]
pub struct Align {
    alignments: BTreeSet<Alignment>,
}

#[allow(missing_docs)]
impl Align {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn center() -> Self {
        Self::default().center_x().center_y()
    }

    pub fn center_x(mut self) -> Self {
        self.alignments.insert(Alignment::CenterX);
        self.alignments.remove(&Alignment::Left);
        self.alignments.remove(&Alignment::Right);
        self
    }

    pub fn center_y(mut self) -> Self {
        self.alignments.insert(Alignment::CenterY);
        self.alignments.remove(&Alignment::Top);
        self.alignments.remove(&Alignment::Bottom);
        self
    }

    pub fn top(mut self) -> Self {
        self.alignments.insert(Alignment::Top);
        self.alignments.remove(&Alignment::CenterY);
        self.alignments.remove(&Alignment::Bottom);
        self
    }

    pub fn bottom(mut self) -> Self {
        self.alignments.insert(Alignment::Bottom);
        self.alignments.remove(&Alignment::CenterY);
        self.alignments.remove(&Alignment::Top);
        self
    }

    pub fn left(mut self) -> Self {
        self.alignments.insert(Alignment::Left);
        self.alignments.remove(&Alignment::CenterX);
        self.alignments.remove(&Alignment::Right);
        self
    }

    pub fn right(mut self) -> Self {
        self.alignments.insert(Alignment::Right);
        self.alignments.remove(&Alignment::CenterX);
        self.alignments.remove(&Alignment::Left);
        self
    }
}

/// Composable alignment variants. See [`Align`].
#[allow(missing_docs)]
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
pub enum Alignment {
    Top,
    Bottom,
    Left,
    Right,
    CenterX,
    CenterY,
}

/// Holder for [`Align`] data. See [`Alignable`] and [`ChildAlignable`].
pub enum AlignHolder {
    /// Static
    Align(Align),
    /// Reactive
    AlignSignal(BoxSignal<'static, Option<Align>>),
}

/// Whether to add or remove an [`Alignment`]. See [`Alignable`] and [`ChildAlignable`].
#[allow(missing_docs)]
pub enum AddRemove {
    Add,
    Remove,
}

fn register_align_signal<REW: RawElWrapper>(
    element: REW,
    align_signal: impl Signal<Item = Option<Vec<Alignment>>> + Send + 'static,
    apply_alignment: fn(&mut Node, Alignment, AddRemove),
) -> REW {
    let mut last_alignments_option: Option<Vec<Alignment>> = None;
    element.update_raw_el(|raw_el| {
        raw_el.on_signal_with_component::<Option<Vec<Alignment>>, Node>(align_signal, move |mut node, aligns_option| {
            if let Some(alignments) = aligns_option {
                // TODO: confirm that this last alignment removal strategy is working as intended
                if let Some(mut last_alignments) = last_alignments_option.take() {
                    last_alignments.retain(|align| !alignments.contains(align));
                    for alignment in last_alignments {
                        apply_alignment(&mut node, alignment, AddRemove::Remove)
                    }
                }
                for alignment in &alignments {
                    apply_alignment(&mut node, *alignment, AddRemove::Add)
                }
                last_alignments_option = alignments.is_empty().not().then_some(alignments);
            } else if let Some(last_aligns) = last_alignments_option.take() {
                for align in last_aligns {
                    apply_alignment(&mut node, align, AddRemove::Remove)
                }
            }
        })
    })
}

/// [`Alignable`] types can align themselves (although application of self alignment is managed by
/// [`ChildAlignable`]) and their children.
pub trait Alignable: RawElWrapper {
    /// The [`Aligner`] of this type. Used for indirection in [`AlignabilityFacade`].
    fn aligner(&mut self) -> Option<Aligner> {
        None
    }

    /// Mutable reference to the [`Align`] data of this type.
    fn align_mut(&mut self) -> &mut Option<AlignHolder>;

    /// Statically align this element, itself. See [`Align`].
    fn align(mut self, align_option: impl Into<Option<Align>>) -> Self
    where
        Self: Sized,
    {
        if let Some(align) = align_option.into() {
            *self.align_mut() = Some(AlignHolder::Align(align));
        }
        self
    }

    /// Reactively align this element, itself. See [`Align`].
    fn align_signal<S: Signal<Item = Option<Align>> + Send + Sync + 'static>(
        mut self,
        align_option_signal_option: impl Into<Option<S>>,
    ) -> Self
    where
        Self: Sized,
    {
        if let Some(align_option_signal) = align_option_signal_option.into() {
            *self.align_mut() = Some(AlignHolder::AlignSignal(align_option_signal.boxed()));
        }
        self
    }

    /// Allows implementor to override the content alignment processing function. The `&self` can
    /// be used to alter the alignment strategy based on data on the type itself. See
    /// [`AlignabilityFacade::apply_alignment_wrapper`] for an example.
    fn apply_content_alignment_wrapper(&self) -> fn(&mut Node, Alignment, AddRemove) {
        Self::apply_content_alignment
    }

    /// How to modify the [`Node`] of this element given a content alignment and whether to add or
    /// remove it.
    fn apply_content_alignment(node: &mut Node, alignment: Alignment, action: AddRemove);

    /// Statically align the children of this element. See [`Align`].
    ///
    /// # Notes
    /// [`Stack`] and [`Grid`] children (read: children that are either a [`Stack`] or a [`Grid`],
    /// not the children *of* [`Stack`]s or [`Grid`]s) do not behave as expected when aligned
    /// with a parent's [`.align_content`](`Alignable::align_content`) or
    /// [`.align_content_signal`](`Alignable::align_content_signal`); this is a known issue and one
    /// can simply align the [`Stack`] or [`Grid`] themselves as workaround.
    fn align_content(mut self, align_option: impl Into<Option<Align>>) -> Self {
        if let Some(align) = align_option.into() {
            let apply_content_alignment = self.apply_content_alignment_wrapper();
            self = self.update_raw_el(move |raw_el| {
                raw_el.with_component::<Node>(move |mut node| {
                    for alignment in align.alignments {
                        apply_content_alignment(&mut node, alignment, AddRemove::Add);
                    }
                })
            });
        }
        self
    }

    /// Reactively align the children of this element. See [`Align`].
    ///
    /// # Notes
    /// [`Stack`] and [`Grid`] children (read: children that are either a [`Stack`] or a [`Grid`],
    /// not the children *of* [`Stack`]s or [`Grid`]s) do not behave as expected when aligned
    /// with a parent's [`.align_content`](`Alignable::align_content`) or
    /// [`.align_content_signal`](`Alignable::align_content_signal`); this is a known issue and one
    /// can simply align the [`Stack`] or [`Grid`] themselves as workaround.
    fn align_content_signal<S: Signal<Item = Option<Align>> + Send + 'static>(
        mut self,
        align_option_signal_option: impl Into<Option<S>>,
    ) -> Self {
        if let Some(align_option_signal) = align_option_signal_option.into() {
            let apply_content_alignment = self.apply_content_alignment_wrapper();
            self = register_align_signal(
                self,
                align_option_signal
                    .map(|align_option| align_option.map(|align| align.alignments.into_iter().collect())),
                apply_content_alignment,
            );
        }
        self
    }
}

/// [`ChildAlignable`] types process and apply the [`Align`] data that their children specify to self align. This is an emulation of the [CSS child combinator](https://developer.mozilla.org/en-US/docs/Web/CSS/Child_combinator).
pub trait ChildAlignable
where
    Self: 'static,
{
    /// Static [`Node`] modifications for children of this type.
    fn update_node(_node: Mut<Node>) {} // only some require base updates

    /// Allows implementor to override the self alignment processing function. The `&self`
    /// can be used to alter the alignment strategy based on data on the type itself. See
    /// [`AlignabilityFacade::apply_alignment_wrapper`] for an example.
    fn apply_alignment_wrapper(&self) -> fn(&mut Node, Alignment, AddRemove) {
        Self::apply_alignment
    }

    /// How to modify the [`Node`] of children of this element given a self alignment and whether to
    /// add or remove it.
    fn apply_alignment(node: &mut Node, align: Alignment, action: AddRemove);

    /// Align child based on its [`Align`] data and processing defined by the type of its parent.
    fn align_child<Child: RawElWrapper + Alignable>(
        mut child: Child,
        apply_alignment: fn(&mut Node, Alignment, AddRemove),
    ) -> Child {
        child = child.update_raw_el(|raw_el| raw_el.with_component::<Node>(Self::update_node));
        // TODO: this .take means that child can't be passed around parents without losing align
        // info, but this can be easily added if desired
        if let Some(align) = child.align_mut().take() {
            match align {
                AlignHolder::Align(align) => {
                    child = child.update_raw_el(|raw_el| {
                        raw_el.with_component::<Node>(move |mut node| {
                            for align in align.alignments {
                                apply_alignment(&mut node, align, AddRemove::Add)
                            }
                        })
                    })
                }
                AlignHolder::AlignSignal(align_option_signal) => {
                    child = register_align_signal(
                        child,
                        {
                            align_option_signal
                                .map(|align_option| align_option.map(|align| align.alignments.into_iter().collect()))
                        },
                        apply_alignment,
                    )
                }
            }
        }
        child
    }
}

impl<EW: ElementWrapper> Alignable for EW {
    fn aligner(&mut self) -> Option<Aligner> {
        self.element_mut().aligner()
    }

    fn align_mut(&mut self) -> &mut Option<AlignHolder> {
        self.element_mut().align_mut()
    }

    fn apply_content_alignment(node: &mut Node, alignment: Alignment, action: AddRemove) {
        EW::EL::apply_content_alignment(node, alignment, action);
    }
}

impl<EW: ElementWrapper + 'static> ChildAlignable for EW {
    fn update_node(node: Mut<Node>) {
        EW::EL::update_node(node);
    }

    fn apply_alignment(node: &mut Node, align: Alignment, action: AddRemove) {
        EW::EL::apply_alignment(node, align, action);
    }
}

/// Exhaustive variants of alignable definitions; used for type indirection in
/// [`AlignabilityFacade`].
#[derive(Clone, Copy)]
pub enum Aligner {
    /// [`El`](`super::el::El`)
    El,
    /// [`Column`](`super::column::Column`)
    Column,
    /// [`Row`](`super::row::Row`)
    Row,
    /// [`Stack`](`super::stack::Stack`)
    Stack,
    /// [`Grid`](`super::grid::Grid`)
    Grid,
    // TODO: allow specifying custom alignment functions
}

/// Provides type indirection for built-in alignable types, enabling simple "type erasure" via
/// [`TypeEraseable::type_erase`](`super::element::TypeEraseable::type_erase`).
pub struct AlignabilityFacade {
    raw_el: RawHaalkaEl,
    align: Option<AlignHolder>,
    aligner: Aligner,
}

impl<NodeType: Bundle> From<NodeType> for AlignabilityFacade {
    fn from(node_bundle: NodeType) -> Self {
        AlignabilityFacade::new(RawHaalkaEl::from(node_bundle), None, Aligner::El)
    }
}

impl AlignabilityFacade {
    pub(crate) fn new(raw_el: RawHaalkaEl, align: Option<AlignHolder>, aligner: Aligner) -> Self {
        Self { raw_el, align, aligner }
    }
}

impl RawElWrapper for AlignabilityFacade {
    fn raw_el_mut(&mut self) -> &mut RawHaalkaEl {
        &mut self.raw_el
    }
}

impl Alignable for AlignabilityFacade {
    fn aligner(&mut self) -> Option<Aligner> {
        Some(self.aligner)
    }

    fn align_mut(&mut self) -> &mut Option<AlignHolder> {
        &mut self.align
    }

    fn apply_content_alignment_wrapper(&self) -> fn(&mut Node, Alignment, AddRemove) {
        match self.aligner {
            Aligner::El => El::<Node>::apply_content_alignment,
            Aligner::Column => Column::<Node>::apply_content_alignment,
            Aligner::Row => Row::<Node>::apply_content_alignment,
            Aligner::Stack => Stack::<Node>::apply_content_alignment,
            Aligner::Grid => Grid::<Node>::apply_content_alignment,
        }
    }

    fn apply_content_alignment(_node: &mut Node, _alignment: Alignment, _action: AddRemove) {}
}

impl ChildAlignable for AlignabilityFacade {
    fn apply_alignment_wrapper(&self) -> fn(&mut Node, Alignment, AddRemove) {
        match self.aligner {
            Aligner::El => El::<Node>::apply_alignment,
            Aligner::Column => Column::<Node>::apply_alignment,
            Aligner::Row => Row::<Node>::apply_alignment,
            Aligner::Stack => Stack::<Node>::apply_alignment,
            Aligner::Grid => Grid::<Node>::apply_alignment,
        }
    }

    fn apply_alignment(_node: &mut Node, _align: Alignment, _action: AddRemove) {}
}