bevy_hui 0.7.0

pseudo Html templating ui crate for the bevy-engine.
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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
use crate::{
    animation::{ActiveAnimation, AnimationDirection},
    compile::CompileContextEvent,
    data::{AttrTokens, HtmlTemplate, NodeType, XNode},
    prelude::ComponentBindings,
    styles::{HoverTimer, HtmlStyle, PressedTimer},
    util::SlotId,
};
use bevy::{platform::collections::HashMap, prelude::*};

use std::time::Duration;

pub struct BuildPlugin;
impl Plugin for BuildPlugin {
    fn build(&self, app: &mut App) {
        app.add_systems(
            Update,
            (hotreload, spawn_ui, move_children_to_slot)
                .chain()
                .in_set(crate::HuiSystems::Build),
        )
            .register_type::<TemplatePropertySubscriber>()
            .register_type::<TemplateExpresions>()
            .register_type::<TemplateProperties>()
            .register_type::<TemplateScope>()
            .register_type::<Tags>()
            .register_type::<OnUiExit>()
            .register_type::<OnUiEnter>()
            .register_type::<OnUiPress>()
            .register_type::<OnUiSpawn>()
            .register_type::<OnUiChange>()
            .register_type::<UiTarget>()
            .register_type::<UiId>()
            .register_type::<SlotPlaceholder>()
            .register_type::<UnslotedChildren>()
            .register_type::<HtmlNode>()
            .register_type::<super::data::XNode>()
            .register_type::<super::data::HtmlTemplate>()
            .register_type::<super::data::StyleAttr>()
            .register_type::<super::data::Action>();
    }
}

/// Holds the reference to the template root entity,
/// which owns the template properties
#[derive(Component, Clone, Deref, Debug, DerefMut, Copy, Reflect)]
#[reflect]
pub struct TemplateScope(Entity);

/// The property definition of a template,
/// this component can be found on the template root
/// entity, use `TemplateScope` (exists on all nodes, part of a template)
/// to get access to the root.
#[derive(Component, Debug, Clone, Default, Reflect, Deref, DerefMut)]
#[reflect]
pub struct TemplateProperties(pub HashMap<String, String>);

impl TemplateProperties {
    pub fn with(mut self, key: &str, value: &str) -> Self {
        self.insert(key.to_string(), value.to_string());
        self
    }
    pub fn set(&mut self, key: &str, value: &str) -> &mut Self {
        self.insert(key.to_string(), value.to_string());
        self
    }
}

/// Entites that need to be notified, when the
/// template properties change.
#[derive(Component, Clone, Default, Debug, Deref, DerefMut, Reflect)]
#[reflect]
pub struct TemplatePropertySubscriber(pub Vec<Entity>);

#[derive(Component)]
pub struct InsideSlot {
    owner: Entity,
}

#[derive(Component, Reflect, Debug)]
#[reflect]
pub struct SlotPlaceholder {
    owner: Entity,
}

/// ref to unresolved nodes that
/// need to move to the `<slot/>`
/// when the template is loaded.
#[derive(Component, Reflect, Debug)]
#[reflect]
pub struct UnslotedChildren(Entity);

/// entities subscribed to the owners interaction
/// component
#[derive(Component, DerefMut, Debug, Deref)]
pub struct InteractionObverser(Vec<Entity>);

/// unresolved expresssions that can be compiled
/// to a solid attribute
#[derive(Component, Reflect, Deref, Debug, DerefMut)]
#[reflect]
pub struct TemplateExpresions(Vec<AttrTokens>);

/// Any attribute prefixed with `tag:my_tag="my_value"`
/// will be availble here.
#[derive(Component, Deref, DerefMut, Debug, Default, Reflect)]
#[reflect]
pub struct Tags(HashMap<String, String>);

impl Tags {
    pub fn tags(&self) -> &HashMap<String, String> {
        &self.0
    }
}

/// holds ref to the raw uncompiled text content
#[derive(Component, Deref, DerefMut)]
pub struct ContentId(SlotId);

/// the entities owned uid hashed as u64
#[derive(Component, Debug, Default, Hash, Deref, DerefMut, Reflect)]
#[reflect]
pub struct UiId(String);

impl UiId {
    pub fn id(&self) -> &String {
        &self.0
    }
}

/// the entity behind `id` in `target="id"`
#[derive(Component, Debug, DerefMut, Deref, Reflect)]
#[reflect]
pub struct UiTarget(pub Entity);

/// watch interaction of another entity
#[derive(Component, Debug, DerefMut, Deref, Reflect)]
#[reflect]
pub struct UiWatch(pub Entity);

#[derive(Component, Default)]
pub struct FullyBuild;

/// Eventlistener interaction transition to Hover
#[derive(Component, Debug, Deref, DerefMut, Reflect)]
#[reflect]
pub struct OnUiPress(pub Vec<String>);

/// Eventlistener on spawning node
#[derive(Component, Debug, DerefMut, Deref, Reflect)]
#[reflect]
pub struct OnUiSpawn(pub Vec<String>);

/// Eventlistener for interaction transition to Hover
#[derive(Component, Debug, DerefMut, Deref, Reflect)]
#[reflect]
pub struct OnUiEnter(pub Vec<String>);

/// Eventlistener for interaction transition to None
#[derive(Component, Debug, Deref, DerefMut, Reflect)]
#[reflect]
pub struct OnUiExit(pub Vec<String>);

/// Eventlistener for a user triggered Change Event
/// This can be when building a widgets
#[derive(Component, Debug, Deref, DerefMut, Reflect)]
#[reflect]
pub struct OnUiChange(pub Vec<String>);

/// Html Ui Node
/// pass it a handle, it will spawn an UI.
#[derive(Component, Debug, Default, Deref, DerefMut, Reflect)]
#[require(Node, TemplateProperties)]
#[reflect]
pub struct HtmlNode(pub Handle<HtmlTemplate>);

fn hotreload(
    mut cmd: Commands,
    mut events: MessageReader<AssetEvent<HtmlTemplate>>,
    templates: Query<(Entity, &HtmlNode)>,
    sloted_nodes: Query<(Entity, &InsideSlot)>,
) {
    events.read().for_each(|ev| {
        let id = match ev {
            AssetEvent::Modified { id } => id,
            _ => {
                return;
            }
        };

        templates
            .iter()
            .filter(|(_, html)| html.id() == *id)
            .for_each(|(entity, _)| {
                let slots = sloted_nodes
                    .iter()
                    .flat_map(|(slot_entity, slot)| (slot.owner == entity).then_some(slot_entity))
                    .collect::<Vec<_>>();

                if slots.len() > 0 {
                    let slot_holder = cmd.spawn_empty().add_children(&slots).id();
                    cmd.entity(entity).insert(UnslotedChildren(slot_holder));
                }

                cmd.entity(entity)
                    .despawn_related::<Children>()
                    .retain::<KeepComps>();
            });
    });
}

#[derive(Bundle)]
struct KeepComps {
    pub parent: ChildOf,
    pub children: Children,
    pub ui: HtmlNode,
    pub unsloed: UnslotedChildren,
    pub slot: SlotPlaceholder,
    pub inside: InsideSlot,
    pub scope: TemplateScope,
}

fn move_children_to_slot(
    mut cmd: Commands,
    unsloted_includes: Query<(Entity, &UnslotedChildren)>,
    children: Query<&Children>,
    slots: Query<(Entity, &SlotPlaceholder)>,
    parent: Query<&ChildOf>,
) {
    unsloted_includes
        .iter()
        .for_each(|(entity, UnslotedChildren(slot_holder))| {
            let Some(placeholder_entity) = slots
                .iter()
                .find_map(|(slot_ent, slot)| (slot.owner == entity).then_some(slot_ent))
            else {
                return;
            };

            let Ok(slot_parent) = parent.get(placeholder_entity).map(|p| p.parent()) else {
                error!("parentless slot, impossible");
                return;
            };

            _ = children.get(*slot_holder).map(|children| {
                children.iter().for_each(|child| {
                    if child != slot_parent {
                        cmd.entity(child).insert(InsideSlot { owner: entity });
                        cmd.entity(slot_parent).add_child(child);
                    }
                })
            });

            cmd.entity(entity).remove::<UnslotedChildren>();
            cmd.entity(placeholder_entity).despawn();
            cmd.entity(*slot_holder).despawn();
        });
}

fn spawn_ui(
    mut cmd: Commands,
    mut unbuild: Query<(Entity, &HtmlNode, &mut TemplateProperties), Without<FullyBuild>>,
    parents: Query<&ChildOf>,
    unsloted: Query<&UnslotedChildren>,
    assets: Res<Assets<HtmlTemplate>>,
    server: Res<AssetServer>,
    mut texture_atlases: ResMut<Assets<TextureAtlasLayout>>,
    custom_comps: Res<ComponentBindings>,
) {
    unbuild
        .iter_mut()
        .for_each(|(root_entity, handle, mut state)| {
            if parents.get(root_entity).is_ok_and(|parent| {
                unsloted
                    .iter()
                    .any(|children| children.0 == parent.parent())
            }) {
                return;
            }

            let Some(template) = assets.get(&**handle) else {
                return;
            };

            template.properties.iter().for_each(|(key, val)| {
                _ = state.try_insert(key.to_owned(), val.clone());
            });

            let mut builder = TemplateBuilder::new(
                root_entity,
                cmd.reborrow(),
                &server,
                &mut texture_atlases,
                &custom_comps,
                &template,
            );

            if let Some(node) = template.root.first() {
                builder.build_tree(node);
                builder.finalize_relations();
                cmd.trigger(CompileContextEvent {
                    entity: root_entity,
                });
            } else {
                warn!("template has no root node!");
            }

            if template.root.len() > 1 {
                warn!("templates currently only support one root node, ignoring the rest");
            }
        });
}

fn calculate_starting_frame(start: usize, end: usize, direction: &AnimationDirection) -> usize {
    match direction {
        AnimationDirection::Forward => start,
        AnimationDirection::Reverse => end,
        AnimationDirection::AlternateForward => start,
        AnimationDirection::AlternateReverse => end,
    }
}

fn build_animation(style: &HtmlStyle) -> Option<ActiveAnimation> {
    if style.computed.atlas.is_none() {
        return None;
    }

    let starting_frame = if !style.computed.frames.is_empty() {
        calculate_starting_frame(
            style.computed.frames[0] as usize,
            style.computed.frames[style.computed.frames.len() - 1] as usize,
            &style.computed.direction,
        )
    } else {
        let atlas = style.computed.atlas.as_ref().unwrap();

        calculate_starting_frame(
            0,
            (atlas.rows * atlas.columns) as usize - 1,
            &style.computed.direction,
        )
    };

    let starting_direction = match style.computed.direction {
        AnimationDirection::AlternateForward => AnimationDirection::Forward,
        AnimationDirection::AlternateReverse => AnimationDirection::Reverse,
        _ => style.computed.direction.clone(),
    };

    Some(ActiveAnimation {
        timer: Timer::new(
            Duration::from_secs_f32(1.0 / style.computed.fps as f32),
            TimerMode::Repeating,
        ),
        direction: starting_direction,
        frame: starting_frame,
        iterations: style.computed.iterations,
        duration: style.computed.duration / 1000.0,
    })
}

struct TemplateBuilder<'w, 's> {
    cmd: Commands<'w, 's>,
    server: &'w AssetServer,
    texture_atlases: &'w mut Assets<TextureAtlasLayout>,
    scope: Entity,
    comps: &'w ComponentBindings,
    subscriber: TemplatePropertySubscriber,
    ids: HashMap<String, Entity>,
    targets: HashMap<Entity, String>,
    watch: HashMap<String, Vec<Entity>>,
    template: &'w HtmlTemplate,
}

impl<'w, 's> TemplateBuilder<'w, 's> {
    pub fn new(
        scope: Entity,
        cmd: Commands<'w, 's>,
        server: &'w AssetServer,
        texture_atlases: &'w mut Assets<TextureAtlasLayout>,
        comps: &'w ComponentBindings,
        template: &'w HtmlTemplate,
    ) -> Self {
        Self {
            cmd,
            scope,
            server,
            texture_atlases,
            comps,
            template,
            subscriber: Default::default(),
            ids: Default::default(),
            targets: Default::default(),
            watch: Default::default(),
        }
    }

    pub fn finalize_relations(mut self) {
        self.ids.iter().for_each(|(id_string, entity)| {
            self.cmd.entity(*entity).insert(UiId(id_string.clone()));
        });

        self.targets
            .iter()
            .for_each(|(entity, target_id)| match self.ids.get(target_id) {
                Some(tar) => {
                    self.cmd.entity(*entity).insert(UiTarget(*tar));
                }
                None => warn!("target `{target_id}` not found for entity {entity}"),
            });

        self.watch
            .iter()
            .for_each(|(target_str, obs_list)| match self.ids.get(target_str) {
                Some(to_observe) => {
                    self.cmd
                        .entity(*to_observe)
                        .insert(InteractionObverser(obs_list.clone()));
                }
                None => warn!("undefined watch target `{target_str}`"),
            });

        self.cmd
            .entity(self.scope)
            .insert((std::mem::take(&mut self.subscriber), FullyBuild));
    }

    pub fn build_tree(&mut self, root: &XNode) {
        self.build_node(self.scope, root);
    }

    fn build_node(&mut self, entity: Entity, node: &XNode) {
        let styles = HtmlStyle::from(node.styles.clone());
        // ----------------------
        // timers
        self.cmd
            .entity(entity)
            .insert(PressedTimer::new(Duration::from_secs_f32(
                styles.computed.delay.max(0.01),
            )))
            .insert(HoverTimer::new(Duration::from_secs_f32(
                styles.computed.delay.max(0.01),
            )));

        // ---------------------
        // shadow
        if let Some(shadow) = styles.computed.shadow.as_ref() {
            self.cmd.entity(entity).insert(shadow.clone());
        }

        if let Some(shadow) = styles.computed.text_shadow.as_ref() {
            self.cmd.entity(entity).insert(shadow.clone());
        }

        // ---------------------
        // text_layout
        if let Some(text_layout) = styles.computed.text_layout.as_ref() {
            self.cmd.entity(entity).insert(text_layout.clone());
        }

        if entity != self.scope {
            self.cmd.entity(entity).insert(TemplateScope(self.scope));
        }

        // ----------------------
        //register prop listner
        if node.uncompiled.len() > 0 {
            self.cmd.entity(entity).insert(TemplateExpresions(
                node.uncompiled.iter().cloned().collect(),
            ));
            self.subscriber.push(entity);
        }

        // ----------------------
        //tags
        self.cmd.entity(entity).insert(Tags(node.tags.clone()));

        // ----------------------
        // connections
        if let Some(id) = &node.id {
            self.ids.insert(id.clone(), entity);
        }
        if let Some(target) = &node.target {
            self.targets.insert(entity, target.clone());
        }

        if let Some(watch) = &node.watch {
            match self.watch.get_mut(watch) {
                Some(list) => {
                    list.push(entity);
                }
                None => {
                    self.watch.insert(watch.clone(), vec![entity]);
                }
            };
        }

        // ----------------------
        // events
        node.event_listener.iter().for_each(|listener| {
            listener.clone().self_insert(self.cmd.entity(entity));
        });

        // ----------------------
        // dirty outline
        if let Some(outline) = styles.computed.outline.as_ref() {
            self.cmd.entity(entity).insert(outline.clone());
        }

        // ----------------------
        // pickable
        #[cfg(feature = "picking")]
        if let Some(pickable) = styles.computed.pickable.as_ref() {
            self.cmd.entity(entity).insert(pickable.clone());
        }

        match &node.node_type {
            // --------------------------------
            // div node
            NodeType::Node => {
                self.cmd.entity(entity).insert((Node::default(), styles));
            }
            // --------------------------------
            // spawn image
            NodeType::Image => {
                let mut img = self.cmd.entity(entity);

                let animation_option = build_animation(&styles);
                let mut starting_frame = 0;

                if animation_option.is_some() {
                    let animation = animation_option.unwrap();
                    starting_frame = animation.frame;

                    img.insert(animation);
                }

                img.insert((
                    ImageNode {
                        visual_box: VisualBox::BorderBox,
                        image: node
                            .src
                            .as_ref()
                            .map(|path| self.server.load(path))
                            .unwrap_or_default(),
                        image_mode: styles
                            .computed
                            .image_mode
                            .as_ref()
                            .cloned()
                            .unwrap_or_default(),
                        rect: styles.computed.image_region.clone(),
                        texture_atlas: styles.computed.atlas.as_ref().map(|atlas| {
                            let atlas_layout = TextureAtlasLayout::from_grid(
                                atlas.size,
                                atlas.columns,
                                atlas.rows,
                                atlas.padding,
                                atlas.offset,
                            );
                            let atlas_handle = self.texture_atlases.add(atlas_layout);

                            TextureAtlas {
                                layout: atlas_handle,
                                index: starting_frame,
                            }
                        }),
                        ..default()
                    },
                    styles,
                ));
            }
            // --------------------------------
            // spawn image
            NodeType::Text => {
                let content = self
                    .template
                    .content
                    .get(node.content_id)
                    .map(|t| t.trim().to_string())
                    .unwrap_or_default();

                if is_templated(&content) {
                    self.cmd.entity(entity).insert(ContentId(node.content_id));
                    self.subscriber.push(entity);
                }

                self.cmd.entity(entity).insert((Text(content), styles));
            }
            // --------------------------------
            // spawn button
            NodeType::Button => {
                self.cmd.entity(entity).insert((Button, styles));
            }
            NodeType::Custom(custom) => {
                // mark children
                self.comps.try_spawn(custom, entity, &mut self.cmd);
                if node.children.len() > 0 {
                    let slot_holder = self.cmd.spawn(Node::default()).id();
                    for child_node in node.children.iter() {
                        let child_entity = self.cmd.spawn_empty().id();
                        self.build_node(child_entity, child_node);
                        self.cmd.entity(slot_holder).add_child(child_entity);
                    }

                    self.cmd
                        .entity(entity)
                        .insert((UnslotedChildren(slot_holder),));
                }

                self.cmd
                    .entity(entity)
                    .insert(TemplateProperties(node.defs.clone()));

                if node.uncompiled.len() > 0 {
                    self.subscriber.push(entity);
                }

                return;
            }
            // --------------------------------
            // spawn slot
            NodeType::Slot => {
                self.cmd
                    .entity(entity)
                    .insert((Node::default(), SlotPlaceholder { owner: self.scope }));
            }
            // --------------------------------
            // don't render
            NodeType::Template | NodeType::Property => {
                return;
            }
        };

        for child in node.children.iter() {
            let child_entity = self.cmd.spawn_empty().id();
            self.build_node(child_entity, child);
            self.cmd.entity(entity).add_child(child_entity);
        }
    }
}

//@todo:dirty AF
pub fn is_templated(input: &str) -> bool {
    crate::compile::find_template_var(input).is_some()
}

#[cfg(test)]
mod tests {
    use super::*;
    use bevy::asset::AssetApp;

    #[test]
    fn component_build_waits_until_slot_projection() {
        let mut app = App::new();
        app.add_plugins((MinimalPlugins, AssetPlugin::default(), BuildPlugin))
            .init_asset::<HtmlTemplate>()
            .init_asset::<TextureAtlasLayout>()
            .init_resource::<ComponentBindings>();

        let template = app.world_mut().resource_mut::<Assets<HtmlTemplate>>().add(
            HtmlTemplate {
                name: None,
                properties: default(),
                root: vec![XNode::default()],
                content: default(),
            },
        );
        let holder = app.world_mut().spawn_empty().id();
        let component = app.world_mut().spawn(HtmlNode(template)).id();
        app.world_mut().entity_mut(holder).add_child(component);
        let owner = app.world_mut().spawn(UnslotedChildren(holder)).id();

        app.update();
        assert!(!app.world().entity(component).contains::<FullyBuild>());

        app.world_mut()
            .entity_mut(owner)
            .remove::<UnslotedChildren>();
        let parent = app.world_mut().spawn_empty().id();
        app.world_mut().entity_mut(parent).add_child(component);
        app.update();

        assert!(app.world().entity(component).contains::<FullyBuild>());
    }
}