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
use super::{
    ProviderChildPolicy, ProviderEffect, ProviderResolveContext, ProviderRules, UiProvider,
};
use crate::ExtendedUiConfiguration;
use crate::io::CssAsset;
use crate::styles::CssSource;
use bevy::asset::AssetId;
use bevy::prelude::*;
use once_cell::sync::Lazy;
use std::collections::{HashMap, HashSet};
use std::fs;
use std::sync::Mutex;

/// Defines the available `ThemeSwitchRequest` variants for this part of the UI runtime.
#[derive(Debug, Clone)]
enum ThemeSwitchRequest {
    /// Variant `ByName`.
    ByName(String),
    /// Variant `Next`.
    Next,
}

static THEME_SWITCH_REQUESTS: Lazy<Mutex<Vec<ThemeSwitchRequest>>> =
    Lazy::new(|| Mutex::new(Vec::new()));

/// Runtime state for ThemeProvider.
#[derive(Resource, Debug, Clone)]
pub struct ThemeProviderState {
    themes_fs_path: String,
    themes_asset_dir: String,
    themes: HashMap<String, Handle<CssAsset>>,
    theme_ids: HashSet<AssetId<CssAsset>>,
    default_theme: Option<String>,
    active_theme: Option<String>,
}

impl Default for ThemeProviderState {
    /// Handles `default` in the extended UI workflow.
    fn default() -> Self {
        Self {
            themes_fs_path: "assets/themes".to_string(),
            themes_asset_dir: "themes".to_string(),
            themes: HashMap::new(),
            theme_ids: HashSet::new(),
            default_theme: None,
            active_theme: None,
        }
    }
}

impl ThemeProviderState {
    /// Handles `themes_asset_dir` in the extended UI workflow.
    ///
    /// # Examples
    ///
    /// ```rust
    /// // Call `themes_asset_dir` with values from your app state and world context.
    /// ```
    pub fn themes_asset_dir(&self) -> &str {
        self.themes_asset_dir.as_str()
    }

    /// Handles `known_themes` in the extended UI workflow.
    ///
    /// # Examples
    ///
    /// ```rust
    /// // Call `known_themes` with values from your app state and world context.
    /// ```
    pub fn known_themes(&self) -> HashSet<String> {
        self.themes.keys().cloned().collect()
    }

    /// Handles `default_theme` in the extended UI workflow.
    ///
    /// # Examples
    ///
    /// ```rust
    /// // Call `default_theme` with values from your app state and world context.
    /// ```
    pub fn default_theme(&self) -> Option<&str> {
        self.default_theme.as_deref()
    }

    /// Handles `active_theme` in the extended UI workflow.
    ///
    /// # Examples
    ///
    /// ```rust
    /// // Call `active_theme` with values from your app state and world context.
    /// ```
    pub fn active_theme(&self) -> Option<&str> {
        self.active_theme.as_deref()
    }

    /// Handles `set_default_theme` in the extended UI workflow.
    ///
    /// # Examples
    ///
    /// ```rust
    /// // Call `set_default_theme` with values from your app state and world context.
    /// ```
    pub fn set_default_theme(&mut self, requested: &str) {
        let requested = requested.trim();
        if requested.is_empty() {
            return;
        }

        if self.themes.contains_key(requested) {
            self.default_theme = Some(requested.to_string());
        } else {
            warn!(
                "ThemeProvider default theme '{}' not found. Keeping current fallback.",
                requested
            );
            self.ensure_default_theme();
        }
    }

    /// Handles `ensure_default_theme` in the extended UI workflow.
    fn ensure_default_theme(&mut self) {
        if let Some(current) = self.default_theme.as_deref() {
            if self.themes.contains_key(current) {
                return;
            }
        }

        self.default_theme = self.themes.keys().min().cloned();
    }

    /// Handles `resolve_theme_or_default` in the extended UI workflow.
    fn resolve_theme_or_default(&self, requested: &str) -> Option<String> {
        let requested = requested.trim();
        if self.themes.contains_key(requested) {
            return Some(requested.to_string());
        }

        if let Some(default) = self.default_theme.as_deref() {
            if self.themes.contains_key(default) {
                return Some(default.to_string());
            }
        }

        self.themes.keys().min().cloned()
    }

    /// Handles `next_theme_name` in the extended UI workflow.
    fn next_theme_name(&self) -> Option<String> {
        let mut names: Vec<&String> = self.themes.keys().collect();
        names.sort();

        if names.is_empty() {
            return None;
        }

        if let Some(current) = self
            .active_theme
            .as_deref()
            .or(self.default_theme.as_deref())
            && let Some(index) = names.iter().position(|name| name.as_str() == current)
        {
            let next_index = (index + 1) % names.len();
            return Some(names[next_index].clone().to_string());
        }

        names.first().cloned().map(|name| name.to_string())
    }

    /// Handles `theme_handle` in the extended UI workflow.
    fn theme_handle(&self, name: &str) -> Option<Handle<CssAsset>> {
        self.themes.get(name).cloned()
    }
}

/// Default provider that maps `<theme-provider ...>` to a css file in the configured themes folder.
#[derive(Debug, Default, Clone, Copy)]
pub struct ThemeProvider;

impl ThemeProvider {
    /// Queues a global theme switch request.
    ///
    /// The request is applied by the provider system on the next frame.
    /// If the requested theme does not exist, the provider fallback/default theme is used.
    pub fn switch_theme(theme: &str) {
        let trimmed = theme.trim();
        if trimmed.is_empty() {
            warn!("ThemeProvider::switch_theme called with empty theme name.");
            return;
        }

        if let Ok(mut queue) = THEME_SWITCH_REQUESTS.lock() {
            queue.push(ThemeSwitchRequest::ByName(trimmed.to_string()));
        }
    }

    /// Queues a switch request to the next discovered theme (sorted by name).
    pub fn switch_next_theme() {
        if let Ok(mut queue) = THEME_SWITCH_REQUESTS.lock() {
            queue.push(ThemeSwitchRequest::Next);
        }
    }
}

impl UiProvider for ThemeProvider {
    /// Handles `tag` in the extended UI workflow.
    fn tag(&self) -> &'static str {
        "theme-provider"
    }

    /// Handles `rules` in the extended UI workflow.
    fn rules(&self) -> ProviderRules {
        ProviderRules {
            requires_body_child: true,
            child_policy: ProviderChildPolicy::Only(vec!["body".to_string()]),
            allow_in_head: false,
        }
    }

    /// Handles `resolve` in the extended UI workflow.
    fn resolve(&self, ctx: ProviderResolveContext<'_>) -> Result<ProviderEffect, String> {
        let requested = ctx
            .active_theme()
            .or_else(|| ctx.attr("default"))
            .or_else(|| ctx.attr("theme"))
            .unwrap_or("default")
            .trim();

        if requested.is_empty() {
            return Err("attribute 'default' must not be empty".to_string());
        }

        let is_valid_name = requested
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
        if !is_valid_name {
            return Err("theme name may only contain [A-Za-z0-9_-] characters".to_string());
        }

        let selected = if let Some(known) = ctx.known_themes() {
            if known.contains(requested) {
                requested.to_string()
            } else if let Some(fallback) = ctx
                .fallback_theme()
                .filter(|fallback| known.contains(*fallback))
            {
                warn!(
                    "Theme '{}' not found. Falling back to default theme '{}'.",
                    requested, fallback
                );
                fallback.to_string()
            } else if let Some(first) = known.iter().min() {
                warn!(
                    "Theme '{}' not found. Falling back to discovered theme '{}'.",
                    requested, first
                );
                first.to_string()
            } else {
                requested.to_string()
            }
        } else {
            requested.to_string()
        };

        let asset_dir = ctx
            .theme_asset_dir()
            .map(str::trim)
            .filter(|value| !value.is_empty())
            .unwrap_or("themes")
            .trim_matches('/');

        Ok(ProviderEffect {
            extra_css_paths: vec![format!("/{asset_dir}/{selected}.css")],
        })
    }
}

/// Handles `refresh_theme_provider_state` in the extended UI workflow.
///
/// # Examples
///
/// ```rust
/// // Call `refresh_theme_provider_state` with values from your app state and world context.
/// ```
pub(crate) fn refresh_theme_provider_state(
    mut state: ResMut<ThemeProviderState>,
    config: Res<ExtendedUiConfiguration>,
    asset_server: Res<AssetServer>,
) {
    let themes_fs_path = config.themes_path.trim();
    let themes_fs_path = if themes_fs_path.is_empty() {
        "assets/themes".to_string()
    } else {
        themes_fs_path.to_string()
    };
    let themes_asset_dir = normalize_themes_asset_dir(&themes_fs_path);

    let configured = normalize_theme_names(&config.theme_names);
    let discovered = if configured.is_empty() {
        discover_theme_names(&themes_fs_path)
    } else {
        configured
    };

    state.themes_fs_path = themes_fs_path.clone();
    state.themes_asset_dir = themes_asset_dir.clone();
    state.themes.clear();
    state.theme_ids.clear();

    for name in discovered {
        let asset_path = format!("{themes_asset_dir}/{name}.css");
        let handle: Handle<CssAsset> = asset_server.load(asset_path);
        state.theme_ids.insert(handle.id());
        state.themes.insert(name, handle);
    }

    if state.themes.is_empty() {
        warn!(
            "ThemeProvider found no themes in '{}'. Configure `ExtendedUiConfiguration.themes_path` or add theme files.",
            themes_fs_path
        );
    }

    state.ensure_default_theme();

    if let Some(active) = state.active_theme.as_deref() {
        if !state.themes.contains_key(active) {
            state.active_theme = None;
        }
    }
}

/// Handles `apply_theme_switch_requests` in the extended UI workflow.
///
/// # Examples
///
/// ```rust
/// // Call `apply_theme_switch_requests` with values from your app state and world context.
/// ```
pub(crate) fn apply_theme_switch_requests(
    mut state: ResMut<ThemeProviderState>,
    mut css_query: Query<&mut CssSource>,
) {
    let requests = if let Ok(mut queue) = THEME_SWITCH_REQUESTS.lock() {
        if queue.is_empty() {
            return;
        }
        std::mem::take(&mut *queue)
    } else {
        return;
    };

    for request in requests {
        let selected = match request {
            ThemeSwitchRequest::ByName(requested) => {
                let Some(selected) = state.resolve_theme_or_default(&requested) else {
                    warn!(
                        "ThemeProvider::switch_theme('{}') ignored: no themes are available.",
                        requested
                    );
                    continue;
                };

                if selected != requested {
                    warn!(
                        "ThemeProvider::switch_theme('{}') fallback to '{}'.",
                        requested, selected
                    );
                }
                selected
            }
            ThemeSwitchRequest::Next => {
                let Some(selected) = state.next_theme_name() else {
                    warn!("ThemeProvider::switch_next_theme ignored: no themes are available.");
                    continue;
                };
                selected
            }
        };

        let Some(handle) = state.theme_handle(&selected) else {
            continue;
        };
        state.active_theme = Some(selected);

        for mut css_source in &mut css_query {
            for source_handle in &mut css_source.0 {
                if state.theme_ids.contains(&source_handle.id()) {
                    *source_handle = handle.clone();
                }
            }
        }
    }
}

/// Handles `normalize_theme_names` in the extended UI workflow.
fn normalize_theme_names(names: &[String]) -> Vec<String> {
    let mut out = Vec::new();
    for name in names {
        let trimmed = name.trim();
        if trimmed.is_empty() {
            continue;
        }
        let is_valid_name = trimmed
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
        if !is_valid_name {
            warn!(
                "ThemeProvider ignored invalid theme name '{}' from ExtendedUiConfiguration.theme_names",
                trimmed
            );
            continue;
        }
        out.push(trimmed.to_string());
    }
    out.sort();
    out.dedup();
    out
}

/// Handles `discover_theme_names` in the extended UI workflow.
fn discover_theme_names(folder: &str) -> Vec<String> {
    let Ok(entries) = fs::read_dir(folder) else {
        return Vec::new();
    };

    let mut themes = Vec::new();
    for entry in entries.flatten() {
        let path = entry.path();
        let is_css = path
            .extension()
            .and_then(|ext| ext.to_str())
            .map(|ext| ext.eq_ignore_ascii_case("css"))
            .unwrap_or(false);
        if !is_css {
            continue;
        }

        let Some(stem) = path.file_stem().and_then(|stem| stem.to_str()) else {
            continue;
        };
        if stem.is_empty() {
            continue;
        }

        themes.push(stem.to_string());
    }

    themes.sort();
    themes.dedup();
    themes
}

/// Handles `normalize_themes_asset_dir` in the extended UI workflow.
fn normalize_themes_asset_dir(path: &str) -> String {
    let normalized = path.replace('\\', "/");
    let trimmed = normalized
        .trim()
        .trim_end_matches('/')
        .trim_start_matches("./");
    let trimmed = trimmed.trim_start_matches('/');

    if let Some(rest) = trimmed.strip_prefix("assets/") {
        if !rest.is_empty() {
            return rest.to_string();
        }
    }

    if let Some(index) = trimmed.rfind("/assets/") {
        let rest = &trimmed[index + "/assets/".len()..];
        if !rest.is_empty() {
            return rest.to_string();
        }
    }

    if trimmed.is_empty() {
        "themes".to_string()
    } else {
        trimmed.to_string()
    }
}