aalo 0.3.0

aka bevy-inspector-haalka, a bevy_ui-native inspector for Bevy
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
use super::{defaults::*, globals::*, style::*, utils::*};
use crate::impl_syncers;
use bevy_asset::prelude::*;
use bevy_color::prelude::*;
use bevy_ecs::{prelude::*, system::SystemId};
use bevy_text::prelude::*;
use bevy_ui::prelude::*;
use haalka::futures_signals::{prelude::*, raw::utils::remove_system_holder_on_remove};
use std::{
    fmt::Display,
    sync::{Arc, OnceLock},
};

#[derive(Default)]
pub struct DynamicText {
    el: El<Text>,
    text: Mutable<String>,
    font: Mutable<Handle<Font>>,
    font_size: Mutable<f32>,
    color: Mutable<Color>,
}

impl ElementWrapper for DynamicText {
    type EL = El<Text>;
    fn element_mut(&mut self) -> &mut Self::EL {
        &mut self.el
    }
}

impl CursorOnHoverable for DynamicText {}
impl GlobalEventAware for DynamicText {}
impl PointerEventAware for DynamicText {}

impl DynamicText {
    pub fn new() -> Self {
        let text = Mutable::new(String::new());
        let font = Mutable::new(Default::default());
        let font_size = Mutable::new(DEFAULT_FONT_SIZE);
        let color = Mutable::new(DEFAULT_UNHIGHLIGHTED_COLOR);
        let el: El<Text> = El::<Text>::new()
            .text_font(
                TextFont::default()
                    .with_font(font.get_cloned())
                    .with_font_size(font_size.get()),
            )
            .text_color(TextColor(color.get()))
            .text(Text(text.get_cloned()))
            .text_signal(text.signal_cloned().dedupe_cloned().map(Text))
            .on_signal_with_text_font(font.signal_cloned(), |mut text_font, font| {
                text_font.font = font;
            })
            .apply(text_style(font_size.signal(), color.signal()));
        Self {
            el,
            text,
            font,
            font_size,
            color,
        }
    }

    impl_syncers! { text: String, font: Handle<Font>, font_size: f32, color: Color }
}

pub struct HighlightableText {
    pub text: DynamicText,
    highlighted_color: Mutable<Color>,
    unhighlighted_color: Mutable<Color>,
    highlighted: Mutable<bool>,
}

impl ElementWrapper for HighlightableText {
    type EL = DynamicText;
    fn element_mut(&mut self) -> &mut Self::EL {
        &mut self.text
    }
}

impl GlobalEventAware for HighlightableText {}
impl PointerEventAware for HighlightableText {}

impl HighlightableText {
    #[allow(clippy::new_without_default)]
    pub fn new() -> Self {
        let unhighlighted_color = Mutable::new(DEFAULT_UNHIGHLIGHTED_COLOR);
        let highlighted_color = Mutable::new(DEFAULT_HIGHLIGHTED_COLOR);
        let hovered = Mutable::new(false);
        let highlighted = Mutable::new(false);
        let dynamic_text = DynamicText::new()
            .color_signal(map_bool_signal(
                signal::or(hovered.signal(), highlighted.signal()),
                highlighted_color.clone(),
                unhighlighted_color.clone(),
            ))
            .hovered_sync(hovered);
        Self {
            text: dynamic_text,
            highlighted_color,
            unhighlighted_color,
            highlighted,
        }
    }

    pub fn with_text(mut self, f: impl FnOnce(DynamicText) -> DynamicText) -> Self {
        self.text = f(self.text);
        self
    }

    impl_syncers! {
        highlighted_color: Color,
        unhighlighted_color: Color,
        highlighted: bool
    }
}

pub struct Checkbox {
    el: El<Node>,
    size: Mutable<f32>,
    background_color: Mutable<Color>,
    highlighted_color: Mutable<Color>,
    unhighlighted_color: Mutable<Color>,
    border_radius: Mutable<f32>,
    hovered: Mutable<bool>,
    checked: Mutable<bool>,
}

impl ElementWrapper for Checkbox {
    type EL = El<Node>;
    fn element_mut(&mut self) -> &mut Self::EL {
        &mut self.el
    }
}

impl GlobalEventAware for Checkbox {}
impl PointerEventAware for Checkbox {}
impl Nameable for Checkbox {}

const CHECKBOX_BORDER_RADIUS_MODIFIER: f32 = 0.333;

impl Checkbox {
    #[allow(clippy::new_without_default)]
    pub fn new() -> Self {
        let size = GLOBAL_FONT_SIZE.clone();
        let background_color = GLOBAL_SECONDARY_BACKGROUND_COLOR.clone();
        let highlighted_color = GLOBAL_HIGHLIGHTED_COLOR.clone();
        let unhighlighted_color = GLOBAL_UNHIGHLIGHTED_COLOR.clone();
        let border_radius_base = GLOBAL_BORDER_RADIUS.get() * CHECKBOX_BORDER_RADIUS_MODIFIER;
        let border_width = GLOBAL_BORDER_WIDTH.clone();
        let border_radius = Mutable::new(border_radius_base);
        let hovered = Mutable::new(false);
        let checked = Mutable::new(false);
        let el = El::<Node>::new()
            .align_content(Align::center())
            .apply(square_style(size.signal()))
            .apply(border_radius_style(BoxCorner::ALL, border_radius.signal()))
            .apply(border_width_style(BoxEdge::ALL, border_width.signal()))
            .apply(border_color_style(hovered.signal().map_bool_signal(clone!((highlighted_color) move || highlighted_color.signal()), || GLOBAL_BORDER_COLOR.signal())))
            .hovered_sync(hovered.clone())
            .cursor(CursorIcon::System(SystemCursorIcon::Pointer))
            .apply(padding_style(BoxEdge::ALL, always(1.)))
            .child_signal(
                checked.signal()
                .map_true(clone!((hovered, highlighted_color, unhighlighted_color, border_radius) move ||
                    El::<Node>::new()
                        .apply(border_radius_style(BoxCorner::ALL, border_radius.signal().map(mul(0.5))))
                            .with_node(|mut node| {
                                node.width = Val::Percent(100.);
                                node.height = Val::Percent(100.);
                            })
                        .apply(background_style(hovered.signal().map_bool_signal(clone!((highlighted_color) move || highlighted_color.signal()), clone!((unhighlighted_color) move || unhighlighted_color.signal()))))
                ))
            );
        Self {
            el,
            size,
            background_color,
            highlighted_color,
            unhighlighted_color,
            border_radius,
            hovered,
            checked,
        }
    }

    impl_syncers! {
        size: f32,
        background_color: Color,
        highlighted_color: Color,
        unhighlighted_color: Color,
        border_radius: f32,
        hovered: bool,
        checked: bool,
    }
}

#[derive(Clone)]
pub struct OptionData<T> {
    pub option: T,
    pub blocked: bool,
    // TODO: just doing this with selected index instead, but this can be used
    // in the future to have a filter integrated into the dropdown
    filtered: Mutable<bool>,
}

impl<T> OptionData<T> {
    pub fn new(option: T, blocked: bool) -> Self {
        Self {
            option,
            blocked,
            filtered: Mutable::new(false),
        }
    }
}

// TODO: these should be horizontally resizable
pub struct Dropdown<T> {
    el: El<Node>,
    options: MutableVec<OptionData<T>>,
    option_handler_system: Arc<OnceLock<SystemId<In<usize>>>>,
    blocked_tooltip: Option<String>,
    selected: Mutable<Option<usize>>,
    show_dropdown: Mutable<bool>,
    font_size: Mutable<f32>,
    padding: Mutable<f32>,
    border_radius: Mutable<f32>,
    border_width: Mutable<f32>,
    background_color: Mutable<Color>,
    highlighted_color: Mutable<Color>,
    unhighlighted_color: Mutable<Color>,
    border_color: Mutable<Color>,
    error_color: Mutable<Color>,
}

impl<T: Clone + PartialEq + Display + Send + Sync + 'static> ElementWrapper for Dropdown<T> {
    type EL = El<Node>;
    fn element_mut(&mut self) -> &mut Self::EL {
        &mut self.el
    }

    fn into_el(self) -> Self::EL {
        let Self {
            el,
            options,
            option_handler_system,
            blocked_tooltip,
            selected,
            show_dropdown,
            font_size,
            padding,
            border_radius,
            border_width,
            background_color,
            highlighted_color,
            unhighlighted_color,
            border_color,
            error_color,
        } = self;
        let hovered = Mutable::new(false);
        // TODO: more intelligent way to get this height? waiting for node to reach "full size" is pretty
        // cringe TODO: where did this 3. come from ?
        let expected_tooltip_height = font_size.get() + padding.get() + border_width.get() * 2. + 3.;
        let blocked_tooltip = Arc::new(blocked_tooltip);
        // TODO: `Stack` does not play well with flex column, using an `El` allows us to avoid managing the
        // height entirely
        el
        .child(
            // TODO: should be able to DRY most of the display element for the dropdown option elements
            El::<Node>::new()
                .apply(border_color_style(signal::and(hovered.signal(), signal::not(show_dropdown.signal())).map_bool_signal(clone!((highlighted_color) move || highlighted_color.signal()), clone!((border_color) move || border_color.signal()))))
                .apply(border_width_style(BoxEdge::ALL, border_width.signal()))
                // .apply(border_width_style([BoxEdge::Top, BoxEdge::Left, BoxEdge::Right], border_width.signal()))
                // .apply(border_width_style([BoxEdge::Bottom], show_dropdown.signal().map_false_signal(clone!((border_width) move || border_width.signal())).map(Option::unwrap_or_default)))
                .apply(border_radius_style(BoxCorner::TOP, border_radius.signal()))
                .apply(border_radius_style(BoxCorner::BOTTOM, show_dropdown.signal().map_false_signal(clone!((border_radius) move || border_radius.signal())).map(Option::unwrap_or_default)))
                .with_node(|mut node| node.width = Val::Percent(100.))
                .apply(background_style(background_color.signal()))
                .cursor(CursorIcon::System(SystemCursorIcon::Pointer))
                .on_click(clone!((show_dropdown) move || flip(&show_dropdown)))
                .hovered_sync(hovered.clone())
                .child(
                    El::<Node>::new()
                    .with_node(|mut node| node.width = Val::Percent(100.))
                    .apply(border_radius_style(BoxCorner::ALL, border_radius.signal()))
                    .apply(border_style(border_width.signal(), signal::and(show_dropdown.signal(), hovered.signal()).map_bool_signal(clone!((highlighted_color) move || highlighted_color.signal()), clone!((background_color) move || background_color.signal()))))
                    .apply(padding_style(BoxEdge::ALL, padding.signal()))
                    .child(
                        El::<Text>::new()
                            .text_font_signal(font_size.signal().map(TextFont::from_font_size))
                            .text_color_signal(unhighlighted_color.signal().map(TextColor))
                            .text_signal(
                                selected.signal()
                                .map_some(clone!((options) move |i|
                                    options.signal_vec_cloned().to_signal_map(move |options| options.get(i).cloned())
                                ))
                                .map(signal::option).flatten().map(Option::flatten)
                                .map(|option_option| option_option.map(|option| option.option.to_string()).unwrap_or_default())
                                .map(Text)
                            )
                            .apply(text_style(font_size.signal(), hovered.signal().map_bool_signal(clone!((highlighted_color) move || highlighted_color.signal()), clone!((unhighlighted_color) move || unhighlighted_color.signal()))))
                    )
                )
        )
        .child_signal(show_dropdown.signal().map_true(
            clone!((options, selected, blocked_tooltip) move || {
                let option_handler_system = option_handler_system.get().copied();
                Column::<Node>::new()
                .global_z_index(GlobalZIndex(z_order("dropdown")))
                .apply(border_color_style(border_color.signal()))
                .with_node(|mut node| {
                    node.width = Val::Percent(100.);
                    node.position_type = PositionType::Absolute;
                })
                .update_raw_el(|raw_el| raw_el.on_spawn_with_system(|In(entity), child_ofs: Query<&ChildOf>, childrens: Query<&Children>, computed_nodes: Query<&ComputedNode>, mut nodes: Query<&mut Node>| {
                    if let Ok(child_of) = child_ofs.get(entity)
                        && let Ok(siblings) = childrens.get(child_of.parent())
                            && let Some(&sibling) = siblings.first()
                                && let Ok(sibling_node) = computed_nodes.get(sibling)
                                    && let Ok(mut node) = nodes.get_mut(entity) {
                                        // TODO: this is not robust to larger font sizes
                                        node.top = Val::Px(sibling_node.size().y + 1.);  // TODO: y do i need this 1. ?
                                    }
                }))
                .apply(border_width_style([BoxEdge::Left, BoxEdge::Right, BoxEdge::Bottom], border_width.signal()))
                .apply(border_radius_style([BoxCorner::BottomLeft, BoxCorner::BottomRight], border_radius.signal()))
                .apply(background_style(background_color.signal()))
                .align_content(Align::center())
                .items_signal_vec(
                    options.signal_vec_cloned()
                    .enumerate()
                    .sort_by_cloned(|(_, left), (_, right)| left.blocked.cmp(&right.blocked))
                    .filter_signal_cloned(clone!((selected) move |(i, OptionData { filtered, .. })| signal::and(signal::not(signal_eq(i.signal(), selected.signal())), signal::not(filtered.signal()))))
                    .map(clone!((
                        font_size,
                        unhighlighted_color,
                        background_color,
                        padding,
                        border_width,
                        border_radius,
                        highlighted_color,
                        error_color,
                        blocked_tooltip
                    ) move |(i, OptionData { option, blocked, .. })| {
                        let hovered = Mutable::new(false);
                        let mut el = El::<Node>::new()
                            .with_node(|mut node| node.width = Val::Percent(100.))
                            .apply(border_radius_style(BoxCorner::ALL, border_radius.signal()))
                            .apply(background_style(background_color.signal()))
                            .apply(padding_style(BoxEdge::ALL, padding.signal()))
                            .apply(border_width_style(BoxEdge::ALL, border_width.signal()))
                            .apply(
                                border_style(
                                    border_width.signal(),
                                    hovered.signal().map_bool_signal(
                                        clone!((error_color, highlighted_color) move || if blocked { error_color.signal() } else {  highlighted_color.signal() }),
                                        clone!((background_color) move || background_color.signal())
                                    )
                                )
                            )
                            .hovered_sync(hovered.clone())
                            .child(
                                El::<Text>::new()
                                .text_font(TextFont::from_font_size(font_size.get()))  // can see text shrink from larger font otherwise
                                .text_font_signal(font_size.signal().map(TextFont::from_font_size))
                                .text_color_signal(
                                    if blocked {
                                        error_color.signal().apply(SignalEither::Left)
                                    } else {
                                        hovered.signal().map_bool_signal(
                                            clone!((highlighted_color) move || highlighted_color.signal()),
                                            clone!((unhighlighted_color) move || unhighlighted_color.signal())
                                        )
                                        .apply(SignalEither::Right)
                                    }
                                    .map(TextColor)
                                )
                                .text(Text(option.to_string()))
                            );
                        if blocked {
                            if let Some(text) = &*blocked_tooltip.clone() {
                                el = el
                                .update_raw_el(|raw_el| {
                                    raw_el
                                    .apply(sync_tooltip_position(expected_tooltip_height))
                                    .on_signal_with_system(
                                        hovered.signal(),
                                        clone!((text) move |
                                            In((entity, hovered)),
                                            mut tooltip_cache: TooltipCache,
                                        | {
                                            if let Some(tooltip) = tooltip_cache.get(entity) {
                                                let data = Some(TooltipData::new(entity, text.clone()));
                                                let mut lock = tooltip.lock_mut();
                                                if hovered {
                                                    if *lock != data {
                                                        *lock = data;
                                                    }
                                                } else if *lock == data {
                                                    *lock = None;
                                                }
                                            }
                                        })
                                    )
                                });
                            }
                        } else {
                            el = el
                            .cursor(CursorIcon::System(SystemCursorIcon::Pointer));
                            if let Some(system) = option_handler_system {
                                el = el
                                .on_click_with_system(move |_: In<_>, mut commands: Commands| {
                                    if let Some(i) = i.get() {
                                        commands.run_system_with(system, i);
                                    }
                                });
                            }
                        }
                        el
                    }))
                )
            }),
        ))
    }
}

impl<T: Clone + PartialEq + Display + Send + Sync + 'static> GlobalEventAware for Dropdown<T> {}
impl<T: Clone + PartialEq + Display + Send + Sync + 'static> PointerEventAware for Dropdown<T> {}

impl<T> Dropdown<T> {
    pub fn new(options: MutableVec<OptionData<T>>) -> Self
    where
        T: Clone + PartialEq + Display + Send + Sync + 'static,
    {
        Self {
            el: El::<Node>::new(),
            options,
            option_handler_system: Arc::new(OnceLock::new()),
            blocked_tooltip: None,
            selected: Mutable::new(None),
            show_dropdown: Mutable::new(false),
            font_size: GLOBAL_FONT_SIZE.clone(),
            padding: Mutable::new(GLOBAL_PADDING.get() * 0.5),
            border_radius: GLOBAL_BORDER_RADIUS.clone(),
            // border_radius: Mutable::new(GLOBAL_BORDER_RADIUS.get() * 0.5),
            border_width: GLOBAL_BORDER_WIDTH.clone(),
            background_color: GLOBAL_PRIMARY_BACKGROUND_COLOR.clone(),
            highlighted_color: GLOBAL_HIGHLIGHTED_COLOR.clone(),
            unhighlighted_color: GLOBAL_UNHIGHLIGHTED_COLOR.clone(),
            border_color: GLOBAL_BORDER_COLOR.clone(),
            error_color: GLOBAL_ERROR_COLOR.clone(),
        }
    }

    impl_syncers! { selected: Option<usize>, show_dropdown: bool, font_size: f32, padding: f32, border_radius: f32, border_width: f32, background_color: Color, highlighted_color: Color, unhighlighted_color: Color, border_color: Color }

    pub fn with_show_dropdown(mut self, show_dropdown: Mutable<bool>) -> Self {
        self.show_dropdown = show_dropdown;
        self
    }

    pub fn sync_selected(self, selected: Mutable<Option<usize>>) -> Self
    where
        Self: ElementWrapper,
    {
        let syncer = spawn(sync_neq(selected.signal(), self.selected.clone()));
        self.update_raw_el(|raw_el| raw_el.hold_tasks([syncer]))
    }

    pub fn option_handler_system<Marker>(self, handler: impl IntoSystem<In<usize>, (), Marker> + Send + 'static) -> Self
    where
        Self: ElementWrapper,
    {
        let system_holder = self.option_handler_system.clone();
        self.update_raw_el(|raw_el| {
            raw_el
                .with_entity(clone!((system_holder) move |mut entity| {
                    let handler = entity.world_scope(|world| register_system(world, handler));
                    let _ = system_holder.set(handler);
                }))
                .apply(remove_system_holder_on_remove(system_holder))
        })
    }

    pub fn option_handler(self, mut option_handler: impl FnMut(usize) + Send + Sync + 'static) -> Self
    where
        Self: ElementWrapper,
    {
        self.option_handler_system(move |In(i)| option_handler(i))
    }

    pub fn basic_option_handler(self) -> Self
    where
        Self: ElementWrapper,
    {
        let f = clone!((self.selected => selected, self.show_dropdown => show_dropdown) move |i| {
            selected.set(Some(i));
            show_dropdown.set(false);
        });
        self.option_handler(f)
    }

    pub fn blocked_tooltip(mut self, text: String) -> Self {
        self.blocked_tooltip = Some(text);
        self
    }
}