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
use crate::services::image_service::get_or_load_image;
use crate::styles::paint::Colored;
use crate::styles::{CssID, CssSource, TagName};
use crate::widgets::{
    Img, InputField, InputType, InputValue, UIGenID, UIWidgetState, WidgetId, WidgetKind,
};
use crate::{CurrentWidgetState, ExtendedUiConfiguration, ImageCache};
use bevy::asset::LoadState;
use bevy::camera::visibility::RenderLayers;
use bevy::prelude::*;

/// Marker component for initialized image widgets.
#[derive(Component)]
struct ImageBase;

/// Marker component for the alt-text text node.
#[derive(Component)]
struct AltTextNode;

/// Stores the spawned alt-text child entity so we can update/remove it without scanning Children.
#[derive(Component, Copy, Clone)]
struct AltTextChild(Entity);

/// Tracks what we *last applied* so we don't spam updates/logs every frame.
#[derive(Component, Copy, Clone, Debug, PartialEq, Eq)]
enum ImgFallbackState {
    /// Variant `None`.
    None,
    /// Variant `AltShown`.
    AltShown,
}

/// Caches the last alt text we wrote into the child.
/// Prevents re-inserting Text every frame.
#[derive(Component, Debug, Clone, PartialEq, Eq)]
struct AltTextCached(String);

/// Plugin that registers image widget behavior.
pub struct ImageWidget;

impl Plugin for ImageWidget {
    /// Registers systems for image widget setup and updates.
    fn build(&self, app: &mut App) {
        app.add_systems(
            Update,
            (
                internal_node_creation_system,
                sync_preview_source_from_file_input,
                update_src,
                sync_alt_text_with_image_state, // needed for "missing file => alt text"
            )
                .chain(),
        );
    }
}

/// Syncs `<img preview="input-id">` sources from changed file inputs.
fn sync_preview_source_from_file_input(
    input_query: Query<(&CssID, &InputField, &InputValue), (With<InputField>, Changed<InputValue>)>,
    mut img_query: Query<&mut Img, With<Img>>,
) {
    for (input_id, input, input_value) in input_query.iter() {
        if input.input_type != InputType::File || input.folder {
            continue;
        }

        if !input_allows_image_preview(input) {
            continue;
        }

        let value = input_value.0.trim();
        if value.is_empty() || !is_supported_preview_source(value) {
            continue;
        }

        let normalized = value.replace('\\', "/");
        for mut img in img_query.iter_mut() {
            if img.preview.as_deref() == Some(input_id.0.as_str())
                && img.src.as_deref() != Some(normalized.as_str())
            {
                img.src = Some(normalized.clone());
            }
        }
    }
}

/// Initializes internal UI nodes for all [`Img`] components not yet marked with [`ImageBase`].
///
/// This system creates image-rendering UI nodes from `<img>` elements, applying
/// default styling, image loading via [`AssetServer`], and caches via [`ImageCache`].
///
/// It sets up:
/// - [`ImageNode`] with an optional image handle from `img.src`
/// - CSS styling components (`BackgroundColor`, `BorderColor`, `BoxShadow`, etc.)
/// - [`CssSource`] if provided
/// - [`RenderLayers`] for UI layer control
/// - [`TagName`] set to `"img"`
/// - [`Name`] using the image's internal counter (`w_count`)
///
/// Also attaches pointer event observers:
/// - [`on_internal_click`] → focuses the image widget
/// - [`on_internal_cursor_entered`] → sets hover state to true
/// - [`on_internal_cursor_leave`] → sets hover state to false
///
/// # Parameters
/// - `commands`: To insert components onto entities
/// - `query`: Finds [`Img`] entities missing [`ImageBase`]
/// - `config`: Provides render layer configuration
/// - `asset_server`: Loads assets if not already cached
/// - `image_cache`: Caches loaded image handles to avoid reloading
/// - `images`: Asset container for `Image` handles
fn internal_node_creation_system(
    mut commands: Commands,
    query: Query<(Entity, &Img, Option<&CssSource>), (With<Img>, Without<ImageBase>)>,
    config: Res<ExtendedUiConfiguration>,
    asset_server: Res<AssetServer>,
    mut image_cache: ResMut<ImageCache>,
    mut images: ResMut<Assets<Image>>,
) {
    let layer = config.render_layers.first().unwrap_or(&1);

    for (entity, img, source_opt) in query.iter() {
        let mut css_source = CssSource::default();
        if let Some(source) = source_opt {
            css_source = source.clone();
        }

        let mut image_node = ImageNode::default();

        assign_image_from_src(
            &mut image_node,
            img,
            &asset_server,
            &mut image_cache,
            &mut images,
        );

        commands
            .entity(entity)
            .insert((
                Name::new(format!("Img-{}", img.entry)),
                Node::default(),
                WidgetId {
                    id: img.entry,
                    kind: WidgetKind::Img,
                },
                image_node,
                BackgroundColor::default(),
                BorderColor::default(),
                BoxShadow::new(
                    Colored::TRANSPARENT,
                    Val::Px(0.),
                    Val::Px(0.),
                    Val::Px(0.),
                    Val::Px(0.),
                ),
                ZIndex::default(),
                Pickable::default(),
                css_source,
                TagName("img".to_string()),
                RenderLayers::layer(*layer),
                ImageBase,
            ))
            .insert(ImgFallbackState::None)
            .insert(AltTextCached(String::new()))
            .observe(on_internal_click)
            .observe(on_internal_cursor_entered)
            .observe(on_internal_cursor_leave);

        // If src is empty, show alt immediately (no need to wait for any load state).
        let src_empty = is_src_empty(img);
        if src_empty {
            let child = spawn_or_update_alt_text_child(&mut commands, entity, None, &img.alt);
            if let Some(child) = child {
                commands.entity(entity).insert(AltTextChild(child));
            }
            // Mark as applied so the sync system won't spam.
            commands.entity(entity).insert(ImgFallbackState::AltShown);
        }
    }
}

/// Updates the `ImageNode` texture for UI widgets when the associated `Img` component changes.
///
/// <p>
/// This system listens for changes to the `Img` component and updates the corresponding
/// `ImageNode` by loading the image from the specified `src` path. If the path is already
/// cached, the existing handle is reused. The `UIWidgetState` is also accessed to allow future
/// extensions (e.g., reacting to image changes).
/// </p>
///
/// # Parameters
/// - `query`: A query that retrieves all entities with mutable access to `ImageNode`,
///   `UIWidgetState`, and an `Img` component, filtered by the `Changed<Img>` condition.
/// - `asset_server`: A handle to Bevy's asset server for loading images from disk.
/// - `image_cache`: A mutable reference to an image cache used to avoid reloading assets.
/// - `images`: A mutable reference to the global asset collection of loaded `Image` assets.
///
/// # Behavior
/// For each changed `Img`:
/// - If the `src` field is `Some`, the image is loaded or reused from cache.
/// - The `ImageNode` is updated with the new image handle.
/// - The `UIWidgetState` is accessed (currently unchanged, but ready for future use).
///
/// # See Also
/// - [`get_or_load_image`]: Utility function to cache or load images from a path.
/// - [`ImageNode`]: Component that defines image appearance in the UI.
/// - [`Img`]: Component holding the `src` image path for UI image widgets.
fn update_src(
    mut commands: Commands,
    mut query: Query<
        (
            Entity,
            &mut ImageNode,
            &mut UIWidgetState,
            &Img,
            Option<&AltTextChild>,
            &mut ImgFallbackState,
            &mut AltTextCached,
        ),
        (With<Img>, Changed<Img>),
    >,
    asset_server: Res<AssetServer>,
    mut image_cache: ResMut<ImageCache>,
    mut images: ResMut<Assets<Image>>,
) {
    for (entity, mut image_node, _state, img, alt_child, mut fb_state, mut cached) in
        query.iter_mut()
    {
        let existing_child = alt_child.map(|c| c.0);

        // Always update the image handle if src is non-empty.
        assign_image_from_src(
            &mut image_node,
            img,
            &asset_server,
            &mut image_cache,
            &mut images,
        );

        // If src is empty -> show alt immediately (and mark state).
        if is_src_empty(img) {
            let child =
                spawn_or_update_alt_text_child(&mut commands, entity, existing_child, &img.alt);
            if let Some(child) = child {
                commands.entity(entity).insert(AltTextChild(child));
                set_cached_alt_if_changed(&mut commands, entity, &mut cached, &img.alt);
            }
            *fb_state = ImgFallbackState::AltShown;
        } else {
            // src changed to something non-empty:
            // don't remove alt *here* (async load). The sync system will remove it on Loaded.
            // But we should reset the fallback state so we can log on the next real transition.
            *fb_state = ImgFallbackState::None;
        }
    }
}

/// Keeps alt-text in sync with the actual load state.
/// This is required because asset loading is async and does NOT trigger Changed<Img>.
/// Shows or hides alt text based on image load state.
fn sync_alt_text_with_image_state(
    mut commands: Commands,
    asset_server: Res<AssetServer>,
    query: Query<
        (
            Entity,
            &Img,
            &ImageNode,
            Option<&AltTextChild>,
            &ImgFallbackState,
            &AltTextCached,
        ),
        With<Img>,
    >,
) {
    for (entity, img, image_node, alt_child, fb_state, cached) in query.iter() {
        let existing_child = alt_child.map(|c| c.0);

        // src empty -> alt is handled by creation/update_src already; avoid per-frame work.
        if is_src_empty(img) {
            continue;
        }

        // Decide based on the *actual* current load state.
        match asset_server.get_load_state(image_node.image.id()) {
            Some(LoadState::Loaded) => {
                // Only do work if alt is currently shown.
                if *fb_state == ImgFallbackState::AltShown {
                    remove_alt_text_children(&mut commands, entity, existing_child);
                    commands.entity(entity).insert(ImgFallbackState::None);
                    // Log only on transition/action.
                    debug!("Image loaded again, removing alt text: {:?}", entity);
                }
            }
            Some(LoadState::Failed(_)) => {
                // Only do work if alt is NOT currently shown.
                if *fb_state != ImgFallbackState::AltShown {
                    let child = spawn_or_update_alt_text_child(
                        &mut commands,
                        entity,
                        existing_child,
                        &img.alt,
                    );
                    if let Some(child) = child {
                        commands.entity(entity).insert(AltTextChild(child));
                        // Cache alt to avoid pointless text inserts later.
                        let mut cached_local = cached.clone();
                        set_cached_alt_if_changed(
                            &mut commands,
                            entity,
                            &mut cached_local,
                            &img.alt,
                        );
                    }
                    commands.entity(entity).insert(ImgFallbackState::AltShown);
                    // Log only on transition/action.
                    debug!("[WARN] Image failed to load, using alt text: {:?}", img.alt);
                } else {
                    // Alt already shown. Only update text if alt actually changed.
                    if cached.0 != img.alt.trim() {
                        if let Some(child) = existing_child {
                            commands
                                .entity(child)
                                .insert(Text::new(img.alt.trim().to_string()));
                            commands
                                .entity(entity)
                                .insert(AltTextCached(img.alt.trim().to_string()));
                            debug!("Alt text changed, updating child for Img: {:?}", entity);
                        }
                    }
                }
            }
            _ => {
                // Loading / NotLoaded / None -> do nothing to avoid flicker and spam.
            }
        }
    }
}

/// Loads an image handle from img.src if non-empty and assigns it to ImageNode.
/// This avoids duplicating the get_or_load_image logic.
/// Assigns an image handle from the `Img` source, if present.
fn assign_image_from_src(
    image_node: &mut ImageNode,
    img: &Img,
    asset_server: &Res<AssetServer>,
    image_cache: &mut ImageCache,
    images: &mut ResMut<Assets<Image>>,
) {
    if let Some(path) = img.src.clone().filter(|s| !s.trim().is_empty()) {
        let handle = get_or_load_image(path.as_str(), image_cache, images, asset_server);
        image_node.image = handle;
    }
}

/// Handles `input_allows_image_preview` in the extended UI workflow.
fn input_allows_image_preview(input: &InputField) -> bool {
    input.extensions.iter().any(|ext| {
        let ext = ext.trim().trim_start_matches('.').to_ascii_lowercase();
        matches!(ext.as_str(), "jpg" | "jpeg" | "png")
    })
}

/// Handles `path_is_supported_preview_image` in the extended UI workflow.
fn path_is_supported_preview_image(path: &str) -> bool {
    std::path::Path::new(path)
        .extension()
        .and_then(|ext| ext.to_str())
        .map(|ext| ext.to_ascii_lowercase())
        .is_some_and(|ext| matches!(ext.as_str(), "jpg" | "jpeg" | "png"))
}

/// Handles `is_supported_preview_source` in the extended UI workflow.
fn is_supported_preview_source(value: &str) -> bool {
    value.starts_with("data:") || path_is_supported_preview_image(value)
}

/// Returns true when the image source is empty or missing.
fn is_src_empty(img: &Img) -> bool {
    img.src
        .as_ref()
        .map(|s| s.trim().is_empty())
        .unwrap_or(true)
}

/// Updates the cached alt text when it changes.
fn set_cached_alt_if_changed(
    commands: &mut Commands,
    parent: Entity,
    cached: &mut AltTextCached,
    alt: &str,
) {
    let alt = alt.trim().to_string();
    if cached.0 != alt {
        cached.0 = alt.clone();
        commands.entity(parent).insert(AltTextCached(alt));
    }
}

/// Spawns or updates the alt-text child node.
fn spawn_or_update_alt_text_child(
    commands: &mut Commands,
    parent: Entity,
    existing_child: Option<Entity>,
    alt: &str,
) -> Option<Entity> {
    let alt = alt.trim();
    if alt.is_empty() {
        warn!("Alt text is empty for Img: {:?}", parent);
        return existing_child;
    }

    // Update instead of spawning duplicates.
    if let Some(child) = existing_child {
        // Don't spam inserts if it's the same text; we now gate updates elsewhere,
        // but keeping this safe is fine.
        commands.entity(child).insert(Text::new(alt.to_string()));
        return Some(child);
    }

    let child = commands
        .spawn((
            AltTextNode,
            Node::default(),
            Text::new(alt.to_string()),
            TextColor(Color::WHITE),
            TextFont::default(),
            TextLayout::default(),
        ))
        .id();

    commands.entity(parent).add_child(child);
    Some(child)
}

/// Removes any existing alt-text children from an image entity.
fn remove_alt_text_children(
    commands: &mut Commands,
    parent: Entity,
    existing_child: Option<Entity>,
) {
    let Some(child) = existing_child else { return };

    // Despawn alt child and clear tracking component.
    commands.entity(child).despawn();
    commands.entity(parent).remove::<AltTextChild>();
}

/// Handles pointer click on an [`Img`] element.
///
/// Sets the image's `UIWidgetState::focused` flag and updates the
/// `CurrentWidgetState` to track the selected widget ID.
///
/// # Triggered By:
/// - `Trigger<Pointer<Click>>`
///
/// # Affects:
/// - `UIWidgetState::focused`
/// - `CurrentWidgetState::widget_id`
/// Sets focus when an image widget is clicked.
fn on_internal_click(
    mut trigger: On<Pointer<Click>>,
    mut query: Query<(&mut UIWidgetState, &UIGenID), With<Img>>,
    mut current_widget_state: ResMut<CurrentWidgetState>,
) {
    if let Ok((mut state, gen_id)) = query.get_mut(trigger.entity) {
        state.focused = true;
        current_widget_state.widget_id = gen_id.0;
    }

    trigger.propagate(false);
}

/// Marks an [`Img`] node as hovered when the cursor enters.
///
/// # Triggered By:
/// - `Trigger<Pointer<Over>>`
///
/// # Affects:
/// - `UIWidgetState::hovered`
/// Sets hovered state when the cursor enters an image widget.
fn on_internal_cursor_entered(
    mut trigger: On<Pointer<Over>>,
    mut query: Query<&mut UIWidgetState, With<Img>>,
) {
    if let Ok(mut state) = query.get_mut(trigger.entity) {
        state.hovered = true;
    }

    trigger.propagate(false);
}

/// Unsets the hover state of an [`Img`] node when the cursor exits.
///
/// # Triggered By:
/// - `Trigger<Pointer<Out>>`
///
/// # Affects:
/// - `UIWidgetState::hovered`
/// Clears hovered state when the cursor leaves an image widget.
fn on_internal_cursor_leave(
    mut trigger: On<Pointer<Out>>,
    mut query: Query<&mut UIWidgetState, With<Img>>,
) {
    if let Ok(mut state) = query.get_mut(trigger.entity) {
        state.hovered = false;
    }

    trigger.propagate(false);
}