buoyant 0.7.0

SwiftUI-like UIs in Rust for embedded devices
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
use crate::{
    event::{EventContext, EventResult},
    focus::{DefaultFocus, FocusAction, FocusDirection},
    layout::ResolvedLayout,
    primitives::{Point, ProposedDimensions},
    render,
    transition::Opacity,
    view::{Event, ViewLayout, ViewMarker},
};

/// Helper macro to construct the last variant of a OneOfN enum with DefaultFocus
#[macro_export]
#[doc(hidden)]
macro_rules! last_variant_focus {
    // Base case: single variant left - this is the last one
    ($name:ident, $variant:ident) => {
        $name::$variant($variant::default_last())
    };
    // Recursive case: skip first variant, recurse with rest
    ($name:ident, $first:ident, $($rest:ident),+) => {
        $crate::last_variant_focus!($name, $($rest),+)
    };
}

pub use last_variant_focus;

/// A view that conditionally renders its arms based on a boolean expression.
///
/// If you need variable bindings, use the [`match_view!`] macro instead.
///
/// # Examples
///
/// ```
/// use buoyant::if_view;
/// use buoyant::font::CharacterBufferFont;
/// use buoyant::view::{shape::Rectangle, Text};
///
/// let font = CharacterBufferFont;
///
/// let view = |value: u32| {
///     if_view!((value % 2 == 0) {
///         Text::new("Even", &font)
///     } else {
///         Text::new("Odd", &font)
///     })
/// };
///
/// let view = |notification_count: u32| {
///     if_view!((notification_count > 0) {
///         Text::new("You have mail", &font)
///     })
/// };
/// ```
#[macro_export]
macro_rules! if_view {
    (
        ($value:expr) {
            $view0:expr
        }
    ) => {{ if $value { Some($view0) } else { None } }};

    (
        ($value:expr) {
            $view0:expr
        } else {
            $view1:expr
        }
    ) => {{
        if $value {
            $crate::view::match_view::OneOf2::V0($view0)
        } else {
            $crate::view::match_view::OneOf2::V1($view1)
        }
    }};
}

/// A view that can conditionally render one of N heterogeneous subtrees based on the enum variant.
/// Enum associated values can be unwrapped in the match arms.
///
/// # Examples
///
/// ```
/// use buoyant::match_view;
/// use buoyant::font::CharacterBufferFont;
/// use buoyant::view::prelude::*;
///
/// #[derive(Clone)]
/// enum State {
///     Message(&'static str),
///     Error,
///     Redacted,
/// }
///
/// let font = CharacterBufferFont;
///
/// let view = |state| {
///     match_view!(state, {
///         State::Message(msg) => Text::new(msg, &font),
///         State::Error => Text::new("Uh oh", &font),
///         State::Redacted => Rectangle,
///     })
/// };
/// ```
#[macro_export]
macro_rules! match_view {
    (
        $value:expr => {
            $pattern0:pat => $view0:expr,
            $($pattern:pat => $view:expr),* $(,)?
        }
    ) => {{
        compile_error!("Deprecated syntax. Use `match_view!(expr, { ... => ..., })` instead.");
    }};

    // Single branch just returns the inner view directly, for less compiler complaining
    (
        $value:expr, {
            $pattern0:pat => $view0:expr $(,)?
        }
    ) => {{
        match $value {
            $pattern0 => $view0,
        }
    }};

    (
        $value:expr, {
            $pattern0:pat => $view0:expr,
            $pattern1:pat => $view1:expr $(,)?
        }
    ) => {{
        match $value {
            $pattern0 => $crate::view::match_view::OneOf2::V0($view0),
            $pattern1 => $crate::view::match_view::OneOf2::V1($view1),
        }
    }};

    (
        $value:expr, {
            $pattern0:pat => $view0:expr,
            $pattern1:pat => $view1:expr,
            $pattern2:pat => $view2:expr $(,)?
        }
    ) => {{
        match $value {
            $pattern0 => $crate::view::match_view::OneOf3::V0($view0),
            $pattern1 => $crate::view::match_view::OneOf3::V1($view1),
            $pattern2 => $crate::view::match_view::OneOf3::V2($view2),
        }
    }};

    (
        $value:expr, {
            $pattern0:pat => $view0:expr,
            $pattern1:pat => $view1:expr,
            $pattern2:pat => $view2:expr,
            $pattern3:pat => $view3:expr $(,)?
        }
    ) => {{
        match $value {
            $pattern0 => $crate::view::match_view::OneOf4::V0($view0),
            $pattern1 => $crate::view::match_view::OneOf4::V1($view1),
            $pattern2 => $crate::view::match_view::OneOf4::V2($view2),
            $pattern3 => $crate::view::match_view::OneOf4::V3($view3),
        }
    }};

    (
        $value:expr, {
            $pattern0:pat => $view0:expr,
            $pattern1:pat => $view1:expr,
            $pattern2:pat => $view2:expr,
            $pattern3:pat => $view3:expr,
            $pattern4:pat => $view4:expr $(,)?
        }
    ) => {{
        match $value {
            $pattern0 => $crate::view::match_view::OneOf5::V0($view0),
            $pattern1 => $crate::view::match_view::OneOf5::V1($view1),
            $pattern2 => $crate::view::match_view::OneOf5::V2($view2),
            $pattern3 => $crate::view::match_view::OneOf5::V3($view3),
            $pattern4 => $crate::view::match_view::OneOf5::V4($view4),
        }
    }};

    (
        $value:expr, {
            $pattern0:pat => $view0:expr,
            $pattern1:pat => $view1:expr,
            $pattern2:pat => $view2:expr,
            $pattern3:pat => $view3:expr,
            $pattern4:pat => $view4:expr,
            $pattern5:pat => $view5:expr $(,)?
        }
    ) => {{
        match $value {
            $pattern0 => $crate::view::match_view::OneOf6::V0($view0),
            $pattern1 => $crate::view::match_view::OneOf6::V1($view1),
            $pattern2 => $crate::view::match_view::OneOf6::V2($view2),
            $pattern3 => $crate::view::match_view::OneOf6::V3($view3),
            $pattern4 => $crate::view::match_view::OneOf6::V4($view4),
            $pattern5 => $crate::view::match_view::OneOf6::V5($view5),
        }
    }};

    (
        $value:expr, {
            $pattern0:pat => $view0:expr,
            $pattern1:pat => $view1:expr,
            $pattern2:pat => $view2:expr,
            $pattern3:pat => $view3:expr,
            $pattern4:pat => $view4:expr,
            $pattern5:pat => $view5:expr,
            $pattern6:pat => $view6:expr $(,)?
        }
    ) => {{
        match $value {
            $pattern0 => $crate::view::match_view::OneOf7::V0($view0),
            $pattern1 => $crate::view::match_view::OneOf7::V1($view1),
            $pattern2 => $crate::view::match_view::OneOf7::V2($view2),
            $pattern3 => $crate::view::match_view::OneOf7::V3($view3),
            $pattern4 => $crate::view::match_view::OneOf7::V4($view4),
            $pattern5 => $crate::view::match_view::OneOf7::V5($view5),
            $pattern6 => $crate::view::match_view::OneOf7::V6($view6),
        }
    }};

    (
        $value:expr, {
            $pattern0:pat => $view0:expr,
            $pattern1:pat => $view1:expr,
            $pattern2:pat => $view2:expr,
            $pattern3:pat => $view3:expr,
            $($pattern:pat => $view:expr),*
        }
    ) => {{
        compile_error!("match_view! implements up to 7 branches.");
    }};
}

macro_rules! define_branch {
    ($name:ident, $($variant:ident),+) => {
        #[derive(Debug, Clone, PartialEq, Eq)]
        pub enum $name<$($variant),+> {
            $(
                $variant($variant),
            )+
        }

        impl <$($variant),+> $name<$($variant),+> {
            $(
                paste::paste! {
                    pub fn [<$variant:lower _or_init>] (&mut self, value: $variant) -> &mut $variant {
                        if let $name::$variant(inner) = self {
                            inner
                        } else {
                            *self = $name::$variant(value);
                            if let $name::$variant(inner) = self {
                                inner
                            } else {
                                unreachable!("Just set it to this variant")
                            }
                        }
                    }

                    pub fn [<$variant:lower _or_init_with>](&mut self, value_fn: impl FnOnce() -> $variant) -> &mut $variant {
                        if let $name::$variant(inner) = self {
                            inner
                        } else {
                            *self = $name::$variant(value_fn());
                            if let $name::$variant(inner) = self {
                                inner
                            } else {
                                unreachable!("Just set it to this variant")
                            }
                        }
                    }
                }
            )+
        }

        impl <$($variant),+> DefaultFocus for $name<$($variant),+>
        where
            $($variant: DefaultFocus,)+
        {
            fn default_first() -> Self {
                $name::V0(V0::default_first())
            }

            fn default_last() -> Self {
                // Use a helper to get the last variant
                last_variant_focus!($name, $($variant),+)
            }
        }

        impl<$($variant),+> ViewMarker for $name<$($variant),+>
            where $($variant: ViewMarker,)+
        {
            type Renderables = render::$name::<$($variant::Renderables),+>;
            type Transition = Opacity;
        }

        impl<Captures, $($variant),+> ViewLayout<Captures> for $name<$($variant),+>
            where
                Captures: ?Sized,
                $($variant: ViewLayout<Captures>,)+
        {
            type Sublayout = $name<$(ResolvedLayout<$variant::Sublayout>),+>;
            type State = $name<$( $variant::State ),+>;
            type FocusTree = $name<$($variant::FocusTree),+>;

            fn priority(&self) -> i8 {
                match self {
                    $( Self::$variant(v) => v.priority(),)+
                }
            }

            fn is_empty(&self) -> bool {
                match self {
                    $( Self::$variant(v) => v.is_empty(),)+
                }
            }

            fn transition(&self) -> Self::Transition {
                Opacity
            }

            fn build_state(&self, captures: &mut Captures) -> Self::State {
                match self {
                    $( Self::$variant(v) => $name::$variant(v.build_state(captures)),)+
                }
            }

            fn layout(
                &self,
                offer: &ProposedDimensions,
                env: &impl crate::environment::LayoutEnvironment,
                captures: &mut Captures,
                state: &mut Self::State,
            ) -> ResolvedLayout<Self::Sublayout> {
                match self {
                    $(
                        Self::$variant(v) => {
                            let s = if let $name::$variant(s) = state {
                                s
                            } else {
                                *state = $name::$variant(v.build_state(captures));
                                let $name::$variant(s) = state else {
                                    unreachable!("Guaranteed to not be any other variant")
                                };
                                s
                            };

                            let child_layout = v.layout(offer, env, captures, s);
                            let size = child_layout.resolved_size;
                            ResolvedLayout {
                                sublayouts: $name::$variant(child_layout),
                                resolved_size: size,
                            }
                        }
                    )+
                }
            }

            fn render_tree(
                &self,
                layout: &Self::Sublayout,
                origin: Point,
                env: &impl crate::environment::LayoutEnvironment,
                captures: &mut Captures,
                state: &mut Self::State,
            ) -> Self::Renderables {
                match (self, layout) {
                    $(
                    (Self::$variant(v), $name::$variant(l0)) => {
                        // apparently consumes a lot less stack than matching on state too
                        if let $name::$variant(s) = state {
                            render::$name::$variant(v.render_tree(&l0.sublayouts, origin, env, captures, s))
                        } else {
                            let mut s = v.build_state(captures);
                            let renderables =
                                render::$name::$variant(v.render_tree(&l0.sublayouts, origin, env, captures, &mut s));
                            *state = $name::$variant(s);
                            renderables
                        }
                    }
                    )+
                    // This is reachable if an old layout attempts to be reused
                    _ => panic!(
                        "Layout/state branch mismatch in conditional view. Layouts cannot be reused."
                    ),
                }
            }

            fn handle_event(
                &self,
                event: &Event,
                context: &EventContext,
                render_tree: &mut Self::Renderables,
                captures: &mut Captures,
                state: &mut Self::State,
                focus: &mut Self::FocusTree,
            ) -> EventResult {
                match (self, render_tree, state) {
                    $(
                    (Self::$variant(v), render::$name::$variant(t), $name::$variant(s)) => {
                        if let Event::Focus { action: focus_event, .. } = event {
                            let inner_focus = paste::paste! {
                                match focus_event {
                                    FocusAction::Focus(FocusDirection::Backward) | FocusAction::Previous => {
                                        focus.[< $variant:lower _or_init >](DefaultFocus::default_last())
                                    }
                                    _ => {
                                        focus.[< $variant:lower _or_init >](DefaultFocus::default_first())
                                    }
                                }
                            };
                            v.handle_event(event, context, t, captures, s, inner_focus)
                        } else {
                            let inner_focus = paste::paste! {
                                focus.[< $variant:lower _or_init >](DefaultFocus::default_first())
                            };
                            v.handle_event(event, context, t, captures, s, inner_focus)
                        }
                    }
                    )+
                    _ => {
                        assert!(
                            !cfg!(debug_assertions),
                            "State branch does not match view branch, likely due to improper reuse of layout."
                        );
                        EventResult::default()
                    }
                }
            }
        }
    };
}

// OneOf1 not implemented, just use the inner type directly instead
define_branch!(OneOf2, V0, V1);
define_branch!(OneOf3, V0, V1, V2);
define_branch!(OneOf4, V0, V1, V2, V3);
define_branch!(OneOf5, V0, V1, V2, V3, V4);
define_branch!(OneOf6, V0, V1, V2, V3, V4, V5);
define_branch!(OneOf7, V0, V1, V2, V3, V4, V5, V6);
define_branch!(OneOf8, V0, V1, V2, V3, V4, V5, V6, V7);
define_branch!(OneOf9, V0, V1, V2, V3, V4, V5, V6, V7, V8);
define_branch!(OneOf10, V0, V1, V2, V3, V4, V5, V6, V7, V8, V9);

#[cfg(test)]
mod tests {
    use super::OneOf2::{self, V0, V1};

    #[test]
    fn match_view_single_is_inner_type() {
        let view = match_view!(1, {
            _ => 0,
        });

        assert_eq!(view, 0);
    }

    #[test]
    fn match_view() {
        let view = match_view!(1, {
            0 => 0,
            _ => 1,
        });

        assert_eq!(view, OneOf2::<_, u8>::V1(1));
    }

    #[test]
    fn match_view_enum() {
        #[allow(unused)]
        enum MyEnum {
            A,
            B,
        }

        let view = match_view!(MyEnum::A, {
            MyEnum::A => 0,
            MyEnum::B => 1,
        });

        assert_eq!(view, V0(0));
    }

    #[test]
    fn match_view_variable_binding_enum() {
        #[allow(unused)]
        enum MyEnum {
            A(u8),
            B(f32),
        }

        let view = match_view!(MyEnum::B(3.0), {
            MyEnum::A(x) => x,
            MyEnum::B(y) => y,
        });
        assert_eq!(view, V1(3.0));
    }

    #[test]
    fn match_view_three_branches() {
        #[allow(unused)]
        enum ThreeState {
            First,
            Second,
            Third,
        }

        let view = match_view!(ThreeState::Second, {
            ThreeState::First => 1,
            ThreeState::Second => 2,
            ThreeState::Third => 3,
        });

        assert_eq!(view, super::OneOf3::V1(2));
    }
}