bevy_extended_ui 1.0.1-beta.2

Create simply ui's with css and html 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
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
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
use std::collections::HashMap;

use bevy::asset::AssetEvent;
use bevy::prelude::*;
use kuchiki::{NodeRef, traits::TendrilSink, Attributes};

use crate::html::{HtmlDirty, HtmlEventBindings, HtmlID, HtmlMeta, HtmlSource, HtmlStates, HtmlStructureMap, HtmlStyle, HtmlSystemSet, HtmlWidgetNode};
use crate::io::{CssAsset, DefaultCssHandle, HtmlAsset};
use crate::styles::IconPlace;
use crate::widgets::Button;
use crate::widgets::*;

pub const DEFAULT_UI_CSS: &str = "default/extended_ui.css";

pub struct HtmlConverterSystem;

impl Plugin for HtmlConverterSystem {
    fn build(&self, app: &mut App) {
        app.add_systems(Update, update_html_ui.in_set(HtmlSystemSet::Convert));
    }
}

/// Converts HtmlAsset content into HtmlStructureMap entries.
/// Also resolves <link rel="stylesheet" href="..."> into Handle<CssAsset>.
fn update_html_ui(
    mut structure_map: ResMut<HtmlStructureMap>,
    mut html_dirty: ResMut<HtmlDirty>,

    asset_server: Res<AssetServer>,
    html_assets: Res<Assets<HtmlAsset>>,
    mut html_asset_events: MessageReader<AssetEvent<HtmlAsset>>,
    default_css: Res<DefaultCssHandle>,

    query_added: Query<(Entity, &HtmlSource), Added<HtmlSource>>,
    query_all: Query<(Entity, &HtmlSource)>,
) {
    // Entities that need reparse (new HtmlSource or modified HtmlAsset).
    let mut dirty_entities: Vec<Entity> = query_added.iter().map(|(e, _)| e).collect();

    // If an HtmlAsset changed, find all entities referencing it.
    for ev in html_asset_events.read() {
        let id = match ev {
            AssetEvent::Modified { id } | AssetEvent::Removed { id } => *id,
            _ => continue,
        };

        for (entity, src) in query_all.iter() {
            if src.handle.id() == id {
                dirty_entities.push(entity);
            }
        }
    }

    dirty_entities.sort();
    dirty_entities.dedup();

    if dirty_entities.is_empty() {
        return;
    }

    for entity in dirty_entities {
        let Ok((_entity, html)) = query_all.get(entity) else {
            continue;
        };

        let Some(html_asset) = html_assets.get(&html.handle) else {
            // Asset isn't ready yet.
            continue;
        };

        let content = html_asset.html.clone();
        let document = kuchiki::parse_html().one(content);

        // Extract unique UI key from <meta name="...">
        let Some(meta_key) = document
            .select_first("head meta[name]")
            .ok()
            .and_then(|m| m.attributes.borrow().get("name").map(|s| s.to_string()))
        else {
            error!("Missing <meta name=...> tag in <head>");
            continue;
        };

        // Optional controller path from <meta controller="...">
        let meta_controller = document
            .select_first("head meta[controller]")
            .ok()
            .and_then(|m| {
                m.attributes
                    .borrow()
                    .get("controller")
                    .map(|s| s.to_string())
            })
            .unwrap_or_default();

        // Load all CSS handles from <link rel="stylesheet" href="...">
        let mut css_handles: Vec<Handle<CssAsset>> = document
            .select("head link[href]")
            .ok()
            .into_iter()
            .flatten()
            .filter_map(|node| {
                let attrs = node.attributes.borrow();

                let rel = attrs.get("rel")?.to_string();
                if rel != "stylesheet" {
                    return None;
                }

                let raw_href = attrs.get("href")?.to_string();
                drop(attrs);

                // Resolve href relative to the HTML file location inside assets/
                let resolved = resolve_relative_asset_path(&html.get_source_path(), &raw_href);

                Some(asset_server.load::<CssAsset>(resolved))
            })
            .collect();

        css_handles = with_default_css_first(&default_css, css_handles);

        // Mark this UI as active.
        structure_map.active = Some(meta_key.clone());

        // Parse body
        let Ok(body_node) = document.select_first("body") else {
            error!("Missing <body> tag!");
            continue;
        };

        debug!("Create UI for HTML with key [{:?}]", meta_key);
        if !meta_controller.is_empty() {
            debug!("UI controller [{:?}]", meta_controller);
        }

        let label_map = collect_labels_by_for(body_node.as_node());

        if let Some(body_widget) = parse_html_node(
            body_node.as_node(),
            &css_handles,
            &label_map,
            &meta_key,
            html,
        ) {
            structure_map.html_map.insert(meta_key, vec![body_widget]);

            // IMPORTANT: Explicitly mark UI as dirty so the builder rebuilds.
            html_dirty.0 = true;
        } else {
            error!("Failed to parse <body> node.");
        }
    }
}

/// Parses a DOM node into HtmlWidgetNode.
fn parse_html_node(
    node: &NodeRef,
    css_sources: &Vec<Handle<CssAsset>>,
    label_map: &HashMap<String, String>,
    key: &String,
    html: &HtmlSource,
) -> Option<HtmlWidgetNode> {
    let element = node.as_element()?;
    let tag = element.name.local.to_string();
    let attributes = element.attributes.borrow();

    let meta = HtmlMeta {
        css: css_sources.clone(),
        id: attributes.get("id").map(|s| s.to_string()),
        class: attributes
            .get("class")
            .map(|s| s.split_whitespace().map(str::to_string).collect()),
        style: attributes.get("style").map(HtmlStyle::from_str),
    };

    let states = HtmlStates {
        disabled: attributes.contains("disabled"),
        readonly: attributes.contains("readonly"),
        hidden: attributes.contains("hidden"),
    };

    let functions = bind_html_func(&attributes);

    let widget = Widget(html.controller.clone());

    match tag.as_str() {
        "body" => {
            let children = node
                .children()
                .filter_map(|child| parse_html_node(&child, css_sources, label_map, key, html))
                .collect();

            Some(HtmlWidgetNode::Body(
                Body {
                    html_key: Some(key.clone()),
                    ..default()
                },
                meta,
                states,
                children,
                functions,
                widget.clone(),
                HtmlID::default(),
            ))
        }

        "button" => {
            let (icon_path, icon_place) = parse_icon_and_text(node);
            let text = node.text_contents().trim().to_string();
            Some(HtmlWidgetNode::Button(
                Button {
                    text,
                    icon_path,
                    icon_place,
                    ..default()
                },
                meta,
                states,
                functions,
                widget.clone(),
                HtmlID::default(),
            ))
        }

        "checkbox" => {
            // Checkbox with label and optional icon
            let label = node.text_contents().trim().to_string();
            let icon_path = attributes
                .get("icon");
            let icon = icon_path.map(String::from);
            Some(HtmlWidgetNode::CheckBox(
                CheckBox {
                    label,
                    icon_path: icon,
                    ..default()
                },
                meta,
                states,
                functions,
                widget.clone(),
                HtmlID::default(),
            ))
        }

        "div" => {
            let mut children = Vec::new();
            for child in node.children() {
                if let Some(parsed) = parse_html_node(&child, css_sources, label_map, key, html) {
                    children.push(parsed);
                }
            }

            Some(HtmlWidgetNode::Div(
                Div::default(),
                meta,
                states,
                children,
                functions,
                widget.clone(),
                HtmlID::default(),
            ))
        }

        "divider" => {
            let alignment = attributes.get("alignment").unwrap_or("horizontal");
            Some(HtmlWidgetNode::Divider(
                Divider {
                    alignment: DividerAlignment::from_str(alignment).unwrap_or_default(),
                    ..default()
                },
                meta,
                states,
                functions,
                widget.clone(),
                HtmlID::default(),
            ))
        }

        "fieldset" => {
            let allow_none =
                attributes.get("allow-none").map(|s| s.to_string()) == Some("true".to_string());
            let mode = attributes.get("mode").unwrap_or("single").to_string();
            let mut children = Vec::new();

            let mut radio_nodes: Vec<(NodeRef, bool)> = Vec::new();
            for child in node.children() {
                if let Some(el) = child.as_element() {
                    if el.name.local.eq("radio") {
                        let selected_attr = el.attributes.borrow().contains("selected");
                        radio_nodes.push((child.clone(), selected_attr));
                        continue;
                    }
                }
                if let Some(parsed) = parse_html_node(&child, css_sources, label_map, key, html) {
                    children.push(parsed);
                }
            }

            let any_selected_attr = radio_nodes.iter().any(|(_, sel)| *sel);
            let mut selected_used = false;
            let mut first_radio_seen = false;

            for (radio_node, had_selected_attr) in radio_nodes {
                let element = radio_node.as_element().unwrap();
                let attrs = element.attributes.borrow();

                let value = attrs.get("value").unwrap_or("").to_string();
                let label = radio_node.text_contents().trim().to_string();

                let selected = if any_selected_attr {
                    if had_selected_attr && !selected_used {
                        selected_used = true;
                        true
                    } else {
                        false
                    }
                } else if !selected_used && !allow_none && !first_radio_seen {
                    selected_used = true;
                    true
                } else {
                    false
                };

                first_radio_seen = true;

                let child_meta = HtmlMeta {
                    css: meta.css.clone(),
                    id: attrs.get("id").map(|s| s.to_string()),
                    class: attrs
                        .get("class")
                        .map(|s| s.split_whitespace().map(str::to_string).collect()),
                    style: attrs.get("style").map(HtmlStyle::from_str),
                };

                let child_states = HtmlStates {
                    disabled: attrs.contains("disabled"),
                    readonly: attrs.contains("readonly"),
                    hidden: attrs.contains("hidden"),
                };

                let child_functions = bind_html_func(&attrs);

                children.push(HtmlWidgetNode::RadioButton(
                    RadioButton {
                        label,
                        value,
                        selected,
                        ..default()
                    },
                    child_meta,
                    child_states,
                    child_functions,
                    widget.clone(),
                    HtmlID::default(),
                ));
            }

            Some(HtmlWidgetNode::FieldSet(
                FieldSet {
                    allow_none,
                    field_mode: FieldMode::from_str(mode.as_str()).unwrap_or(FieldMode::Single),
                    ..default()
                },
                meta,
                states,
                children,
                functions,
                widget.clone(),
                HtmlID::default(),
            ))
        }

        "h1" | "h2" | "h3" | "h4" | "h5" | "h6" => {
            let h_type = match tag.as_str() {
                "h1" => HeadlineType::H1,
                "h2" => HeadlineType::H2,
                "h3" => HeadlineType::H3,
                "h4" => HeadlineType::H4,
                "h5" => HeadlineType::H5,
                "h6" => HeadlineType::H6,
                _ => HeadlineType::H3,
            };

            let text = node.text_contents().trim().to_string();

            Some(HtmlWidgetNode::Headline(
                Headline {
                    text,
                    h_type,
                    ..default()
                },
                meta,
                states,
                functions,
                widget.clone(),
                HtmlID::default(),
            ))
        }

        "img" => {
            let src_raw = attributes.get("src").unwrap_or("").to_string();
            let alt = attributes.get("alt").unwrap_or("").to_string();

            let src_resolved = if src_raw.trim().is_empty() {
                None
            } else {
                Some(resolve_relative_asset_path(
                    &html.get_source_path(),
                    &src_raw,
                ))
            };

            Some(HtmlWidgetNode::Img(
                Img {
                    src: src_resolved,
                    alt,
                    ..default()
                },
                meta,
                states,
                functions,
                widget.clone(),
                HtmlID::default(),
            ))
        }

        "input" => {
            let id = attributes.get("id").map(|s| s.to_string());
            let label = id
                .as_ref()
                .and_then(|id| label_map.get(id))
                .cloned()
                .unwrap_or_default();

            let text = attributes.get("value").unwrap_or("").to_string();
            let placeholder = attributes.get("placeholder").unwrap_or("").to_string();
            let input_type = attributes.get("type").unwrap_or("text").to_string();
            let icon_path = attributes.get("icon").unwrap_or("");
            let icon: Option<String> = if !icon_path.is_empty() {
                Some(String::from(icon_path))
            } else {
                None
            };
            let cap = match attributes.get("maxlength") {
                Some(value) if value.trim().eq_ignore_ascii_case("auto") => InputCap::CapAtNodeSize,
                Some(value) if value.trim().is_empty() => InputCap::NoCap,
                Some(value) => {
                    let length = value.trim().parse::<usize>().unwrap_or(0);
                    InputCap::CapAt(length)
                }
                None => InputCap::NoCap,
            };

            Some(HtmlWidgetNode::Input(
                InputField {
                    label,
                    placeholder,
                    text,
                    input_type: InputType::from_str(&input_type).unwrap_or_default(),
                    icon_path: icon,
                    cap_text_at: cap,
                    ..default()
                },
                meta,
                states,
                functions,
                widget.clone(),
                HtmlID::default(),
            ))
        }

        "p" => {
            let text = node.text_contents().trim().to_string();
            Some(HtmlWidgetNode::Paragraph(
                Paragraph { text, ..default() },
                meta,
                states,
                functions,
                widget.clone(),
                HtmlID::default(),
            ))
        }

        "progressbar" => {
            let min = attributes
                .get("min")
                .and_then(|v| v.parse::<f32>().ok())
                .unwrap_or(0.0);

            let max = attributes
                .get("max")
                .and_then(|v| v.parse::<f32>().ok())
                .unwrap_or(100.0);

            let value = attributes
                .get("value")
                .and_then(|v| v.parse::<f32>().ok())
                .unwrap_or(min);

            Some(HtmlWidgetNode::ProgressBar(
                ProgressBar {
                    value,
                    min,
                    max,
                    ..default()
                }, meta, states, functions, widget.clone(), HtmlID::default()))
        }

        "radio" => {
            let value = attributes.get("value").unwrap_or("").to_string();
            let label = node.text_contents().trim().to_string();
            let selected_attr = attributes.contains("selected");

            Some(HtmlWidgetNode::RadioButton(
                RadioButton {
                    label,
                    value,
                    selected: selected_attr,
                    ..default()
                },
                meta,
                states,
                functions,
                widget.clone(),
                HtmlID::default(),
            ))
        }

        "scroll" => {
            let alignment = attributes.get("alignment").unwrap_or("vertical");
            let mut vertical = true;
            if alignment.eq_ignore_ascii_case("horizontal") { vertical = false; }
            Some(HtmlWidgetNode::Scrollbar(
                Scrollbar {
                    vertical,
                    ..default()
                },
                meta,
                states,
                functions,
                widget.clone(),
                HtmlID::default(),
            ))
        }

        "select" => {
            // Parse dropdown options and selected value
            let mut options = Vec::new();
            let mut selected_value = None;

            for child in node.children() {
                if let Some(option_el) = child.as_element() {
                    if option_el.name.local.eq("option") {
                        let attrs = option_el.attributes.borrow();
                        let value = attrs.get("value").unwrap_or("").to_string();
                        let icon = attrs.get("icon").unwrap_or("").to_string();
                        let text = child.text_contents().trim().to_string();

                        let icon_path = if icon.trim().is_empty() {
                            None
                        } else {
                            Some(icon)
                        };

                        let option = ChoiceOption {
                            text: text.clone(),
                            internal_value: value.clone(),
                            icon_path,
                        };

                        if attrs.contains("selected") {
                            selected_value = Some(option.clone());
                        }

                        options.push(option);
                    }
                }
            }

            let value =
                selected_value.unwrap_or_else(|| options.first().cloned().unwrap_or_default());

            Some(HtmlWidgetNode::ChoiceBox(
                ChoiceBox {
                    value,
                    options,
                    ..default()
                },
                meta,
                states,
                functions,
                widget.clone(),
                HtmlID::default(),
            ))
        }

        "slider" => {
            // Parse slider attributes: min, max, value, step
            let min = attributes
                .get("min")
                .and_then(|v| v.parse::<f32>().ok())
                .unwrap_or(0.0);

            let max = attributes
                .get("max")
                .and_then(|v| v.parse::<f32>().ok())
                .unwrap_or(100.0);

            let value = attributes
                .get("value")
                .and_then(|v| v.parse::<f32>().ok())
                .unwrap_or(min);

            let step = attributes
                .get("step")
                .and_then(|v| v.parse::<f32>().ok())
                .unwrap_or(1.0);

            Some(HtmlWidgetNode::Slider(
                Slider {
                    value,
                    min,
                    max,
                    step,
                    ..default()
                },
                meta,
                states,
                functions,
                widget.clone(),
                HtmlID::default(),
            ))
        }

        "switch" => {
            let text = node.text_contents().trim().to_string();
            let icon_attr = attributes.get("icon").unwrap_or("");
            let icon = if icon_attr.is_empty() {
                None
            } else {
                Some(icon_attr.to_string())
            };

            Some(HtmlWidgetNode::SwitchButton(
                SwitchButton {
                    label: text,
                    icon,
                    ..default()
                },
                meta,
                states,
                functions,
                widget.clone(),
                HtmlID::default(),
            ))
        }

        "toggle" => {
            let value = attributes.get("value").unwrap_or("").to_string();
            let (icon_path, icon_place) = parse_icon_and_text(node);
            let text = node.text_contents().trim().to_string();
            let selected_attr = attributes.contains("selected");
            Some(HtmlWidgetNode::ToggleButton(
                ToggleButton {
                    label: text.clone(),
                    icon_path,
                    value,
                    icon_place,
                    selected: selected_attr,
                    ..default()
                },
                meta,
                states,
                functions,
                widget.clone(),
                HtmlID::default(),
            ))
        }
        _ => None,
    }
}

fn bind_html_func(attributes: &Attributes) -> HtmlEventBindings {
    let functions = HtmlEventBindings {
        onclick: attributes.get("onclick").map(|s| s.to_string()),
        onmouseover: attributes.get("onmouseenter").map(|s| s.to_string()),
        onmouseout: attributes.get("onmouseleave").map(|s| s.to_string()),
        onchange: attributes.get("onchange").map(|s| s.to_string()),
        oninit: attributes.get("oninit").map(|s| s.to_string()),
    };
    functions
}

/// Collects mappings from <label for="..."> to its label text.
fn collect_labels_by_for(node: &NodeRef) -> HashMap<String, String> {
    let mut map = HashMap::new();

    for label_node in node.select("label").unwrap() {
        let element = label_node.as_node().as_element().unwrap();
        if let Some(for_id) = element.attributes.borrow().get("for") {
            let label_text = label_node.text_contents().trim().to_string();
            map.insert(for_id.to_string(), label_text);
        }
    }

    map
}

/// Resolves a CSS href found inside an HTML document to a path that the AssetServer understands.
pub fn resolve_relative_asset_path(html_path: &str, href: &str) -> String {
    let mut href = href.replace('\\', "/");

    if let Some(rest) = href.strip_prefix("assets/") {
        href = rest.to_string();
    }

    if let Some(rest) = href.strip_prefix('/') {
        return rest.to_string();
    }

    let base = std::path::Path::new(html_path)
        .parent()
        .unwrap_or(std::path::Path::new(""));

    base.join(href).to_string_lossy().replace('\\', "/")
}

fn with_default_css_first(
    default_css: &DefaultCssHandle,
    mut css: Vec<Handle<CssAsset>>,
) -> Vec<Handle<CssAsset>> {
    let default_handle = default_css.0.clone();

    // Remove default if it already exists somewhere
    css.retain(|h| h.id() != default_handle.id());

    // Insert default at position 0
    css.insert(0, default_handle);

    css
}

fn parse_icon_and_text(node: &NodeRef) -> (Option<String>, IconPlace) {
    let mut icon_path = None;
    let mut icon_place = IconPlace::Left;
    let mut found_text = false;

    for child in node.children() {
        if let Some(el) = child.as_element() {
            if el.name.local.eq("icon") {
                if let Some(src) = el.attributes.borrow().get("src") {
                    icon_path = Some(src.to_string());
                    if found_text {
                        icon_place = IconPlace::Right;
                    }
                }
            }
        } else if child
            .as_text()
            .map(|t| !t.borrow().trim().is_empty())
            .unwrap_or(false)
        {
            found_text = true;
        }
    }

    (icon_path, icon_place)
}