bevy_extended_ui 1.7.0

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
use bevy::prelude::*;
use serde::Serialize;
use serde::de::DeserializeOwned;
use serde_json::Value as JsonValue;
use std::collections::{HashMap, HashSet};
use std::env;

#[cfg(any(feature = "fluent", feature = "properties-lang"))]
use std::fs;

#[cfg(any(feature = "fluent", feature = "properties-lang"))]
use std::path::{Path, PathBuf};

#[cfg(feature = "fluent")]
use i18n_fluent::{FluentBundle, FluentResource};

#[cfg(feature = "fluent")]
use unic_langid::LanguageIdentifier;

#[cfg(feature = "properties-lang")]
use i18n_properties::try_split;

#[cfg(any(feature = "fluent", feature = "properties-lang"))]
use once_cell::sync::Lazy;

#[cfg(any(feature = "fluent", feature = "properties-lang"))]
use regex::Regex;

/// Represents the source of the HTML `lang` setting after parsing.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HtmlLangSetting {
    /// Let the system and app selection decide the language.
    Auto,
    /// Force a specific language tag from the HTML attribute.
    Forced(String),
}

/// Global UI language selection.
///
/// Resolution order:
/// 1) `forced` (from `<html lang="...">`)
/// 2) `selected` (set by the app via the resource)
/// 3) `system` (detected from the OS environment)
#[derive(Resource, Debug, Clone)]
pub struct UILang {
    pub forced: Option<String>,
    pub selected: Option<String>,
    pub system: Option<String>,
}

impl Default for UILang {
    /// Creates a language state seeded with the detected system language.
    fn default() -> Self {
        Self {
            forced: None,
            selected: None,
            system: detect_system_language(),
        }
    }
}

impl Default for UiLangState {
    /// Creates a fresh language resolution cache state.
    fn default() -> Self {
        Self {
            last_resolved: None,
            last_language_path: None,
            last_vars_fingerprint: None,
            last_shared_fingerprint: None,
        }
    }
}

impl UILang {
    /// Returns the currently resolved language tag in priority order.
    pub fn resolved(&self) -> Option<&str> {
        self.forced
            .as_deref()
            .or(self.selected.as_deref())
            .or(self.system.as_deref())
    }

    /// Sets the selected language and returns whether it changed.
    pub fn set_selected(&mut self, lang: Option<&str>) -> bool {
        let normalized = normalize_lang_tag(lang);
        if self.selected == normalized {
            return false;
        }
        self.selected = normalized;
        true
    }

    /// Applies a `lang` value from HTML and returns whether it changed the forced state.
    pub fn apply_html_lang(&mut self, lang: Option<&str>) -> bool {
        let new_forced = match parse_html_lang(lang) {
            HtmlLangSetting::Auto => None,
            HtmlLangSetting::Forced(tag) => Some(tag),
        };

        if self.forced == new_forced {
            return false;
        }

        self.forced = new_forced;
        true
    }
}

/// Cached resolution information for language resources.
#[derive(Resource, Debug, Clone)]
pub struct UiLangState {
    pub last_resolved: Option<String>,
    pub last_language_path: Option<String>,
    pub last_vars_fingerprint: Option<u64>,
    pub last_shared_fingerprint: Option<u64>,
}

/// Runtime variables used for placeholder substitution during localization.
#[derive(Resource, Debug, Default, Clone)]
pub struct UiLangVariables {
    pub vars: HashMap<String, String>,
}

/// Shared typed values exposed to HTML templates.
#[derive(Resource, Debug, Default, Clone)]
pub struct UiSharedValues {
    /// Shared type name -> JSON value
    pub values: HashMap<String, JsonValue>,
    /// Auto alias (`#[html_use]`) -> shared type name
    pub auto_use_aliases: HashMap<String, String>,
    /// Registered shared type names (available via macros), even if no resource exists yet.
    pub known_types: HashSet<String>,
}

/// Registration entry produced by `#[html_shared]` / `#[html_use]`.
pub enum HtmlSharedRegistration {
    Shared {
        name: &'static str,
        path: &'static str,
        alias: &'static str,
        auto_use: bool,
        capture: fn(&World) -> Option<JsonValue>,
    },
}

inventory::collect!(HtmlSharedRegistration);
pub use inventory;
pub use serde_json;

impl UiLangVariables {
    /// Inserts or replaces a localization variable.
    pub fn set(&mut self, key: impl Into<String>, value: impl Into<String>) {
        self.vars.insert(key.into(), value.into());
    }

    /// Returns a variable value as `&str`.
    pub fn get(&self, key: &str) -> Option<&str> {
        self.vars.get(key).map(String::as_str)
    }

    /// Returns whether a key exists.
    pub fn contains_key(&self, key: &str) -> bool {
        self.vars.contains_key(key)
    }

    /// Sets a boolean variable as normalized `"true"` / `"false"`.
    pub fn set_bool(&mut self, key: impl Into<String>, value: bool) {
        self.set(key, if value { "true" } else { "false" });
    }

    /// Reads a boolean variable from common textual forms.
    pub fn get_bool(&self, key: &str) -> Option<bool> {
        let raw = self.get(key)?;
        parse_bool_var(raw)
    }

    /// Toggles a boolean variable and returns the new value.
    pub fn toggle_bool(&mut self, key: impl Into<String>, default: bool) -> bool {
        let key = key.into();
        let current = self.get_bool(&key).unwrap_or(default);
        let next = !current;
        self.set_bool(key, next);
        next
    }

    /// Stores any serializable value as JSON text.
    pub fn set_json<T: Serialize>(
        &mut self,
        key: impl Into<String>,
        value: &T,
    ) -> Result<(), serde_json::Error> {
        let encoded = serde_json::to_string(value)?;
        self.vars.insert(key.into(), encoded);
        Ok(())
    }

    /// Reads a JSON value into a typed model.
    pub fn get_json<T: DeserializeOwned>(&self, key: &str) -> Option<T> {
        let raw = self.get(key)?;
        serde_json::from_str(raw).ok()
    }
}

fn parse_bool_var(raw: &str) -> Option<bool> {
    match raw.trim().to_ascii_lowercase().as_str() {
        "true" | "1" | "yes" | "on" => Some(true),
        "false" | "0" | "no" | "off" => Some(false),
        _ => None,
    }
}

/// Parses an HTML `lang` attribute into a normalized setting.
fn parse_html_lang(lang: Option<&str>) -> HtmlLangSetting {
    let Some(tag) = normalize_lang_tag(lang) else {
        return HtmlLangSetting::Auto;
    };

    if tag == "auto" || tag == "default" {
        HtmlLangSetting::Auto
    } else {
        HtmlLangSetting::Forced(tag)
    }
}

/// Detects the system language from environment variables.
fn detect_system_language() -> Option<String> {
    const KEYS: [&str; 4] = ["LC_ALL", "LC_MESSAGES", "LANG", "LANGUAGE"];

    for key in KEYS {
        if let Ok(value) = env::var(key) {
            if let Some(tag) = normalize_env_lang(&value) {
                return Some(tag);
            }
        }
    }

    None
}

/// Normalizes an environment language string into a language tag.
fn normalize_env_lang(value: &str) -> Option<String> {
    let trimmed = value.trim();
    if trimmed.is_empty() {
        return None;
    }

    let first = trimmed
        .split(|c| c == ':' || c == ';' || c == ',')
        .next()
        .unwrap_or("");
    let first = first.split('.').next().unwrap_or("");

    normalize_lang_tag(Some(first))
}

/// Normalizes a raw language tag into lowercase hyphenated form.
fn normalize_lang_tag(raw: Option<&str>) -> Option<String> {
    let raw = raw?.trim();
    if raw.is_empty() {
        return None;
    }

    let normalized = raw.replace('_', "-").to_lowercase();
    if normalized == "c" || normalized == "posix" {
        return None;
    }

    Some(normalized)
}

#[cfg(any(feature = "fluent", feature = "properties-lang"))]
static PLACEHOLDER_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?s)\{\{\s*(.+?)\s*\}\}").unwrap());

/// Returns the input HTML unchanged when no localization backends are enabled.
#[cfg(not(any(feature = "fluent", feature = "properties-lang")))]
pub fn localize_html(
    html: &str,
    _lang: Option<&str>,
    _language_path: &str,
    _vars: &UiLangVariables,
) -> String {
    html.to_string()
}

/// Localizes HTML placeholders using the enabled backend(s).
#[cfg(any(feature = "fluent", feature = "properties-lang"))]
pub fn localize_html(
    html: &str,
    lang: Option<&str>,
    language_path: &str,
    vars: &UiLangVariables,
) -> String {
    if !PLACEHOLDER_RE.is_match(html) {
        return html.to_string();
    }

    let Some(normalized) = normalize_lang_tag(lang) else {
        return html.to_string();
    };

    let mut localized = html.to_string();

    #[cfg(feature = "fluent")]
    if let Some(out) = localize_html_fluent(&localized, &normalized, language_path, vars) {
        localized = out;
    }

    #[cfg(feature = "properties-lang")]
    if let Some(out) = localize_html_properties(&localized, &normalized, language_path, vars) {
        localized = out;
    }

    localized
}

/// Localizes HTML using Fluent files if available.
#[cfg(feature = "fluent")]
fn localize_html_fluent(
    html: &str,
    lang: &str,
    language_path: &str,
    vars: &UiLangVariables,
) -> Option<String> {
    let base = Path::new(language_path);
    let path = find_lang_file(base, lang, "ftl")?;
    let content = fs::read_to_string(path).ok()?;
    let resource = FluentResource::try_new(content).ok()?;
    let langid: LanguageIdentifier = lang.parse().unwrap_or_else(|_| {
        "en-US"
            .parse()
            .expect("Failed to parse fallback language identifier")
    });

    let mut bundle = FluentBundle::new(vec![langid]);
    if bundle.add_resource(resource).is_err() {
        return None;
    }

    let mut errors = Vec::new();
    let localized = PLACEHOLDER_RE
        .replace_all(html, |caps: &regex::Captures| {
            let inner = caps.get(1).map(|m| m.as_str()).unwrap_or_default();
            let resolved = resolve_placeholder(
                inner,
                |key| {
                    let message = bundle.get_message(key)?;
                    let pattern = message.value()?;
                    errors.clear();
                    let value = bundle.format_pattern(pattern, None, &mut errors);
                    if errors.is_empty() {
                        Some(value.to_string())
                    } else {
                        None
                    }
                },
                vars,
            );
            resolved.unwrap_or_else(|| {
                caps.get(0)
                    .map(|m| m.as_str())
                    .unwrap_or_default()
                    .to_string()
            })
        })
        .into_owned();

    Some(localized)
}

/// Localizes HTML using Java properties files if available.
#[cfg(feature = "properties-lang")]
fn localize_html_properties(
    html: &str,
    lang: &str,
    language_path: &str,
    vars: &UiLangVariables,
) -> Option<String> {
    let base = Path::new(language_path);
    let path = find_lang_file(base, lang, "properties")?;
    let content = fs::read_to_string(path).ok()?;
    let map = parse_properties(&content);

    let localized = PLACEHOLDER_RE
        .replace_all(html, |caps: &regex::Captures| {
            let inner = caps.get(1).map(|m| m.as_str()).unwrap_or_default();
            let resolved = resolve_placeholder(inner, |key| map.get(key).cloned(), vars);
            resolved.unwrap_or_else(|| {
                caps.get(0)
                    .map(|m| m.as_str())
                    .unwrap_or_default()
                    .to_string()
            })
        })
        .into_owned();

    Some(localized)
}

/// Parses a .properties file into a key/value map.
#[cfg(feature = "properties-lang")]
fn parse_properties(content: &str) -> HashMap<String, String> {
    let mut map = HashMap::new();

    for line in content.lines() {
        let trimmed = line.trim();
        if trimmed.is_empty() || trimmed.starts_with('#') || trimmed.starts_with('!') {
            continue;
        }

        let separator = if trimmed.contains('=') {
            Some('=')
        } else if trimmed.contains(':') {
            Some(':')
        } else {
            None
        };

        let prop = match separator {
            Some(sep) => try_split(trimmed, Some(sep), None),
            None => try_split(trimmed, None, None),
        };

        if let Some(prop) = prop {
            map.insert(prop.key(), prop.value());
        }
    }

    map
}

/// Finds the most suitable language file, falling back to English if needed.
#[cfg(any(feature = "fluent", feature = "properties-lang"))]
fn find_lang_file(base: &Path, lang: &str, extension: &str) -> Option<PathBuf> {
    let Some(primary) = find_lang_file_for(base, lang, extension) else {
        let fallback = "en";
        if normalize_lang_tag(Some(lang)) == normalize_lang_tag(Some(fallback)) {
            return None;
        }
        return find_lang_file_for(base, fallback, extension);
    };

    Some(primary)
}

/// Locates a language file by checking candidate filenames and directory entries.
#[cfg(any(feature = "fluent", feature = "properties-lang"))]
fn find_lang_file_for(base: &Path, lang: &str, extension: &str) -> Option<PathBuf> {
    if !base.exists() {
        return None;
    }

    let target = normalize_lang_tag(Some(lang))?;

    for candidate in build_lang_candidates(lang) {
        let path = base.join(format!("{candidate}.{extension}"));
        if path.is_file() {
            return Some(path);
        }
    }

    let entries = fs::read_dir(base).ok()?;
    for entry in entries.flatten() {
        let path = entry.path();
        let Some(ext) = path.extension().and_then(|s| s.to_str()) else {
            continue;
        };
        if ext.to_lowercase() != extension {
            continue;
        }
        let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else {
            continue;
        };
        let Some(normalized_stem) = normalize_lang_tag(Some(stem)) else {
            continue;
        };

        if normalized_stem == target
            || normalized_stem.starts_with(&format!("{target}-"))
            || normalized_stem.starts_with(&format!("{target}_"))
        {
            return Some(path);
        }
    }

    None
}

/// Builds a list of candidate language tags for lookup.
#[cfg(any(feature = "fluent", feature = "properties-lang"))]
fn build_lang_candidates(lang: &str) -> Vec<String> {
    let Some(normalized) = normalize_lang_tag(Some(lang)) else {
        return Vec::new();
    };

    let parts: Vec<&str> = normalized.split('-').filter(|p| !p.is_empty()).collect();
    if parts.is_empty() {
        return Vec::new();
    }

    let mut candidates = Vec::new();
    candidates.push(normalized.clone());
    candidates.push(normalized.replace('-', "_"));

    if parts.len() >= 2 {
        let region_upper = parts[1].to_uppercase();
        candidates.push(format!("{}_{}", parts[0], region_upper));
        candidates.push(format!("{}_{}", parts[0], parts[1]));
        candidates.push(format!("{}-{}", parts[0], parts[1]));
    }

    candidates.push(parts[0].to_string());

    let mut seen = HashSet::new();
    candidates.retain(|item| seen.insert(item.clone()));
    candidates
}

/// Computes a stable fingerprint for the current localization variables.
pub fn vars_fingerprint(vars: &UiLangVariables) -> u64 {
    use std::collections::hash_map::DefaultHasher;
    use std::hash::{Hash, Hasher};

    let mut items: Vec<_> = vars.vars.iter().collect();
    items.sort_by(|(a, _), (b, _)| a.cmp(b));

    let mut hasher = DefaultHasher::new();
    for (key, value) in items {
        key.hash(&mut hasher);
        value.hash(&mut hasher);
    }

    hasher.finish()
}

/// Computes a stable fingerprint for shared typed values.
pub fn shared_values_fingerprint(shared: &UiSharedValues) -> u64 {
    use std::collections::hash_map::DefaultHasher;
    use std::hash::{Hash, Hasher};

    let mut shared_entries: Vec<_> = shared.values.iter().collect();
    shared_entries.sort_by(|(a, _), (b, _)| a.cmp(b));

    let mut alias_entries: Vec<_> = shared.auto_use_aliases.iter().collect();
    alias_entries.sort_by(|(a, _), (b, _)| a.cmp(b));
    let mut known_types: Vec<_> = shared.known_types.iter().collect();
    known_types.sort();

    let mut hasher = DefaultHasher::new();
    for (key, value) in shared_entries {
        key.hash(&mut hasher);
        value.to_string().hash(&mut hasher);
    }
    for (alias, target) in alias_entries {
        alias.hash(&mut hasher);
        target.hash(&mut hasher);
    }
    for type_name in known_types {
        type_name.hash(&mut hasher);
    }

    hasher.finish()
}

/// Refreshes all shared typed values from macro-generated registrations.
pub fn refresh_shared_values(world: &mut World) {
    let mut values: HashMap<String, JsonValue> = HashMap::new();
    let mut aliases: HashMap<String, String> = HashMap::new();
    let mut known_types: HashSet<String> = HashSet::new();

    for registration in inventory::iter::<HtmlSharedRegistration> {
        let HtmlSharedRegistration::Shared {
            name,
            path,
            alias,
            auto_use,
            capture,
        } = registration;

        known_types.insert((*name).to_string());
        known_types.insert((*path).to_string());
        if *auto_use {
            if let Some(previous) = aliases.get(*alias) {
                if previous != name {
                    warn!(
                        "Duplicate #[html_use] alias '{}' for '{}' ignored (already used by '{}')",
                        alias, name, previous
                    );
                    continue;
                }
            }
            aliases.insert((*alias).to_string(), (*name).to_string());
        }

        if let Some(value) = (*capture)(&*world) {
            values.insert((*path).to_string(), value.clone());
            values.insert((*name).to_string(), value);
        }
    }

    let mut shared = world.resource_mut::<UiSharedValues>();
    if shared.values != values {
        shared.values = values;
    }
    if shared.auto_use_aliases != aliases {
        shared.auto_use_aliases = aliases;
    }
    if shared.known_types != known_types {
        shared.known_types = known_types;
    }
}

/// Resolves a placeholder token, returning `None` if unchanged.
#[cfg(any(feature = "fluent", feature = "properties-lang"))]
pub fn resolve_placeholder<F>(
    inner: &str,
    mut translate: F,
    vars: &UiLangVariables,
) -> Option<String>
where
    F: FnMut(&str) -> Option<String>,
{
    let resolved = resolve_inner_tokens(inner, &mut translate, vars);
    if resolved == inner {
        None
    } else {
        Some(resolved)
    }
}

/// Resolves variables and translation keys within a placeholder string.
#[cfg(any(feature = "fluent", feature = "properties-lang"))]
fn resolve_inner_tokens<F>(inner: &str, translate: &mut F, vars: &UiLangVariables) -> String
where
    F: FnMut(&str) -> Option<String>,
{
    let mut out = String::new();
    let mut chars = inner.chars().peekable();

    while let Some(ch) = chars.next() {
        if ch.is_whitespace() {
            out.push(ch);
            continue;
        }

        if ch == '%' {
            let mut name = String::new();
            let mut closed = false;
            let mut valid = true;

            while let Some(next) = chars.next() {
                if next == '%' {
                    closed = true;
                    break;
                }
                if !is_key_char(next) {
                    valid = false;
                }
                name.push(next);
            }

            if closed && valid && !name.is_empty() {
                if let Some(value) = vars.vars.get(&name) {
                    out.push_str(value);
                } else {
                    out.push('%');
                    out.push_str(&name);
                    out.push('%');
                }
            } else {
                out.push('%');
                out.push_str(&name);
                if closed {
                    out.push('%');
                }
            }

            continue;
        }

        if is_key_char(ch) {
            let mut key = String::new();
            key.push(ch);
            while let Some(next) = chars.peek().copied() {
                if is_key_char(next) {
                    chars.next();
                    key.push(next);
                } else {
                    break;
                }
            }

            if let Some(value) = translate(&key) {
                out.push_str(&value);
            } else {
                out.push_str(&key);
            }

            continue;
        }

        out.push(ch);
    }

    out
}

/// Returns true for characters that are valid in translation keys.
#[cfg(any(feature = "fluent", feature = "properties-lang"))]
fn is_key_char(ch: char) -> bool {
    ch.is_ascii_alphanumeric() || matches!(ch, '_' | '.' | ':' | '-')
}

#[cfg(any(feature = "fluent", feature = "properties-lang"))]
pub use i18n;

#[cfg(feature = "fluent")]
pub use i18n_fluent;

#[cfg(feature = "properties-lang")]
pub use i18n_properties;