bevy_material_ui 0.2.7

Material Design 3 UI components for Bevy game 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
//! Embedded icon system.
//!
//! By default, icons come from the `google-material-design-icons-bin` crate as ALPHA8.
//! For compatibility, icons are expanded to RGBA8 (white + alpha) when building UI images.
//! UI tinting is applied via `ImageNode.color`.

use bevy::asset::RenderAssetUsages;
use bevy::ecs::system::Command;
use bevy::prelude::*;
use bevy::render::render_resource::{Extent3d, TextureDimension, TextureFormat};
use bevy::ui::widget::ImageNode;
use std::collections::HashMap;

#[derive(Debug)]
struct InsertImageNodeIfExists {
    entity: Entity,
    image_node: ImageNode,
}

impl Command for InsertImageNodeIfExists {
    fn apply(self, world: &mut World) {
        if let Ok(mut entity) = world.get_entity_mut(self.entity) {
            entity.insert(self.image_node);
        }
    }
}

#[derive(Debug)]
struct InsertNodeIfExists {
    entity: Entity,
    node: Node,
}

impl Command for InsertNodeIfExists {
    fn apply(self, world: &mut World) {
        if let Ok(mut entity) = world.get_entity_mut(self.entity) {
            entity.insert(self.node);
        }
    }
}

fn icon_pixels_rgba8(id: material_icons::IconId) -> Vec<u8> {
    let alpha = id.alpha();
    let mut rgba = Vec::with_capacity(alpha.len() * 4);
    for a in alpha.iter().copied() {
        rgba.extend_from_slice(&[255, 255, 255, a]);
    }
    rgba
}

/// Generated icon table + embedded alpha-only bytes.
///
/// This mirrors the source folder layout as Rust modules (platform/category/icon).
pub use google_material_design_icons_bin::material_icons;

/// Lookup an embedded icon by its folder name (case-insensitive).
///
/// This is a small compatibility shim for older call sites that used an
/// `icon_by_name` helper.
pub use material_icons::by_name as icon_by_name;

// ---------------------------------------------------------------------------
// Common icon name constants
// ---------------------------------------------------------------------------
// These are folder names from the upstream icon repository.

pub const ICON_CLOSE: &str = "close";
pub const ICON_CHECK: &str = "check";
pub const ICON_REMOVE: &str = "remove";
pub const ICON_DELETE: &str = "delete";
pub const ICON_SEARCH: &str = "search";
pub const ICON_MENU: &str = "menu";
pub const ICON_HOME: &str = "home";
pub const ICON_SETTINGS: &str = "settings";
pub const ICON_FAVORITE: &str = "favorite";
pub const ICON_ADD: &str = "add";
pub const ICON_EDIT: &str = "edit";
pub const ICON_STAR: &str = "star";
pub const ICON_EMAIL: &str = "email";
pub const ICON_MORE_VERT: &str = "more_vert";
pub const ICON_NOTIFICATIONS: &str = "notifications";
pub const ICON_ARROW_BACK: &str = "arrow_back";
pub const ICON_EXPAND_MORE: &str = "expand_more";
pub const ICON_EXPAND_LESS: &str = "expand_less";

/// Backwards-compatible icon name constants.
///
/// Some widgets historically referenced Android-style resource identifiers.
/// These now map to embedded icon folder names.
pub mod material_icon_names {
    pub const IC_KEYBOARD_BLACK_24DP: &str = "keyboard";
    pub const IC_CLOCK_BLACK_24DP: &str = "schedule";

    pub const MATERIAL_IC_EDIT_BLACK_24DP: &str = "edit";
    pub const MATERIAL_IC_CALENDAR_BLACK_24DP: &str = "calendar_today";
    pub const MATERIAL_IC_MENU_ARROW_UP_BLACK_24DP: &str = "expand_less";
    pub const MATERIAL_IC_MENU_ARROW_DOWN_BLACK_24DP: &str = "expand_more";
    pub const MATERIAL_IC_KEYBOARD_ARROW_PREVIOUS_BLACK_24DP: &str = "chevron_left";
    pub const MATERIAL_IC_KEYBOARD_ARROW_NEXT_BLACK_24DP: &str = "chevron_right";
}

// ---------------------------------------------------------------------------
// Compatibility shims (style + svg)
// ---------------------------------------------------------------------------

/// Simple icon style component.
///
/// Older widgets in this crate used an `IconStyle` component to drive size and
/// color updates separately from the icon itself. In the embedded icon system,
/// the source-of-truth is `MaterialIcon { size, color }`, but we keep this
/// lightweight shim to avoid rewriting every widget at once.
#[derive(Component, Clone, Copy, Debug)]
pub struct IconStyle {
    pub size: f32,
    pub color: Color,
}

impl Default for IconStyle {
    fn default() -> Self {
        Self {
            size: 24.0,
            color: Color::WHITE,
        }
    }
}

impl IconStyle {
    pub fn outlined() -> Self {
        Self::default()
    }

    pub fn filled() -> Self {
        Self::default()
    }

    pub fn with_size(mut self, size: f32) -> Self {
        self.size = size;
        self
    }

    pub fn with_color(mut self, color: Color) -> Self {
        self.color = color;
        self
    }
}

/// Minimal stand-in for the old SVG icon component.
///
/// This does *not* load SVGs; it simply maps a name to an embedded bitmap icon.
pub mod svg {
    use super::{icon_by_name, MaterialIcon};
    use bevy::prelude::*;

    #[derive(Component, Clone, Debug)]
    pub struct SvgIcon {
        pub name: String,
        pub size: f32,
        pub color: Color,
    }

    impl SvgIcon {
        pub fn new(name: impl Into<String>) -> Self {
            Self {
                name: name.into(),
                size: 24.0,
                color: Color::WHITE,
            }
        }

        pub fn with_size(mut self, size: f32) -> Self {
            self.size = size;
            self
        }

        pub fn with_color(mut self, color: Color) -> Self {
            self.color = color;
            self
        }
    }

    pub(super) fn svg_icon_sync_system(
        mut commands: Commands,
        mut icons: Query<
            (
                Entity,
                &SvgIcon,
                Option<&mut MaterialIcon>,
                Option<&mut Visibility>,
            ),
            Or<(Added<SvgIcon>, Changed<SvgIcon>)>,
        >,
    ) {
        for (entity, svg, material_icon, visibility) in icons.iter_mut() {
            let Some(id) = icon_by_name(&svg.name) else {
                if let Some(mut visibility) = visibility {
                    *visibility = Visibility::Hidden;
                } else {
                    commands.entity(entity).insert(Visibility::Hidden);
                }
                continue;
            };

            if let Some(mut material_icon) = material_icon {
                material_icon.id = id;
                material_icon.size = svg.size;
                material_icon.color = svg.color;
            } else {
                commands.entity(entity).insert(
                    MaterialIcon::new(id)
                        .with_size(svg.size)
                        .with_color(svg.color),
                );
            }

            if let Some(mut visibility) = visibility {
                *visibility = Visibility::Inherited;
            } else {
                commands.entity(entity).insert(Visibility::Inherited);
            }
        }
    }
}

#[derive(Resource, Default)]
struct MaterialIconImageCache(HashMap<material_icons::IconId, Handle<Image>>);

/// Icon component for rendering an embedded icon via `ImageNode`.
#[derive(Component, Clone, Copy, Debug)]
pub struct MaterialIcon {
    pub id: material_icons::IconId,
    pub size: f32,
    pub color: Color,
}

impl MaterialIcon {
    pub fn new(id: material_icons::IconId) -> Self {
        Self {
            id,
            size: 20.0,
            color: Color::WHITE,
        }
    }

    pub fn from_name(name: &str) -> Option<Self> {
        material_icons::by_name(name).map(Self::new)
    }

    pub fn with_size(mut self, size: f32) -> Self {
        self.size = size;
        self
    }

    pub fn with_color(mut self, color: Color) -> Self {
        self.color = color;
        self
    }
}

/// Plugin that enables `MaterialIcon` rendering.
pub struct MaterialIconsPlugin;

impl Plugin for MaterialIconsPlugin {
    fn build(&self, app: &mut App) {
        app.init_resource::<MaterialIconImageCache>();
        app.add_systems(
            Update,
            (
                material_icon_system,
                material_icon_repair_system,
                icon_style_sync_system,
                svg::svg_icon_sync_system,
            ),
        );
    }
}

fn icon_style_sync_system(
    mut icons: Query<(&mut MaterialIcon, &IconStyle), Or<(Added<IconStyle>, Changed<IconStyle>)>>,
) {
    for (mut icon, style) in icons.iter_mut() {
        icon.size = style.size;
        icon.color = style.color;
    }
}

fn material_icon_system(
    mut commands: Commands,
    mut images: ResMut<Assets<Image>>,
    mut cache: ResMut<MaterialIconImageCache>,
    mut icons: Query<
        (
            Entity,
            &MaterialIcon,
            Option<&mut ImageNode>,
            Option<&mut Node>,
        ),
        Or<(Added<MaterialIcon>, Changed<MaterialIcon>)>,
    >,
) {
    for (entity, icon, image_node, node) in icons.iter_mut() {
        let handle = if let Some(handle) = cache.0.get(&icon.id) {
            handle.clone()
        } else {
            let extent = Extent3d {
                width: icon.id.width as u32,
                height: icon.id.height as u32,
                depth_or_array_layers: 1,
            };
            let image = Image::new(
                extent,
                TextureDimension::D2,
                icon_pixels_rgba8(icon.id),
                TextureFormat::Rgba8UnormSrgb,
                RenderAssetUsages::default(),
            );
            let handle = images.add(image);
            cache.0.insert(icon.id, handle.clone());
            handle
        };

        if let Some(mut image_node) = image_node {
            image_node.image = handle;
            image_node.color = icon.color;
        } else {
            commands.queue(InsertImageNodeIfExists {
                entity,
                image_node: ImageNode::new(handle).with_color(icon.color),
            });
        }

        if let Some(mut node) = node {
            node.width = Val::Px(icon.size);
            node.height = Val::Px(icon.size);
        } else {
            commands.queue(InsertNodeIfExists {
                entity,
                node: Node {
                    width: Val::Px(icon.size),
                    height: Val::Px(icon.size),
                    ..default()
                },
            });
        }
    }
}

fn material_icon_repair_system(
    mut commands: Commands,
    mut images: ResMut<Assets<Image>>,
    mut cache: ResMut<MaterialIconImageCache>,
    mut icons: Query<
        (
            Entity,
            &MaterialIcon,
            Option<&mut ImageNode>,
            Option<&mut Node>,
        ),
        Or<(Without<ImageNode>, Without<Node>)>,
    >,
) {
    for (entity, icon, image_node, node) in icons.iter_mut() {
        let handle = if let Some(handle) = cache.0.get(&icon.id) {
            handle.clone()
        } else {
            let extent = Extent3d {
                width: icon.id.width as u32,
                height: icon.id.height as u32,
                depth_or_array_layers: 1,
            };
            let image = Image::new(
                extent,
                TextureDimension::D2,
                icon_pixels_rgba8(icon.id),
                TextureFormat::Rgba8UnormSrgb,
                RenderAssetUsages::default(),
            );
            let handle = images.add(image);
            cache.0.insert(icon.id, handle.clone());
            handle
        };

        if let Some(mut image_node) = image_node {
            image_node.image = handle;
            image_node.color = icon.color;
        } else {
            commands.queue(InsertImageNodeIfExists {
                entity,
                image_node: ImageNode::new(handle).with_color(icon.color),
            });
        }

        if let Some(mut node) = node {
            node.width = Val::Px(icon.size);
            node.height = Val::Px(icon.size);
        } else {
            commands.queue(InsertNodeIfExists {
                entity,
                node: Node {
                    width: Val::Px(icon.size),
                    height: Val::Px(icon.size),
                    ..default()
                },
            });
        }
    }
}