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
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
//! Material Design 3 Icon Button component
//!
//! Icon buttons display actions using icons.
//! Reference: <https://m3.material.io/components/icon-buttons/overview>

use bevy::prelude::*;

use crate::{
    icons::MaterialIcon,
    ripple::RippleHost,
    theme::{blend_state_layer, MaterialTheme},
    tokens::CornerRadius,
};

/// Plugin for the icon button component
pub struct IconButtonPlugin;

impl Plugin for IconButtonPlugin {
    fn build(&self, app: &mut App) {
        app.add_message::<IconButtonClickEvent>().add_systems(
            Update,
            (
                icon_button_interaction_system,
                icon_button_style_system,
                icon_button_content_style_system,
                icon_button_theme_refresh_system,
            ),
        );
        if !app.is_plugin_added::<crate::MaterialUiCorePlugin>() {
            app.add_plugins(crate::MaterialUiCorePlugin);
        }
    }
}

/// Icon button variants
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum IconButtonVariant {
    /// Standard icon button
    #[default]
    Standard,
    /// Filled icon button
    Filled,
    /// Filled tonal icon button
    FilledTonal,
    /// Outlined icon button
    Outlined,
}

/// Material icon button component
#[derive(Component)]
pub struct MaterialIconButton {
    /// Button variant style
    pub variant: IconButtonVariant,
    /// Whether the button is disabled
    pub disabled: bool,
    /// Whether the button is selected/toggled
    pub selected: bool,
    /// Whether the button supports toggle behavior
    pub toggle: bool,
    /// Icon identifier
    pub icon: String,
    /// Whether this button is pressed
    pub pressed: bool,
    /// Whether this button is hovered
    pub hovered: bool,
}

impl MaterialIconButton {
    /// Create a new icon button
    pub fn new(icon: impl Into<String>) -> Self {
        Self {
            variant: IconButtonVariant::default(),
            disabled: false,
            selected: false,
            toggle: false,
            icon: icon.into(),
            pressed: false,
            hovered: false,
        }
    }

    /// Set the button variant
    pub fn with_variant(mut self, variant: IconButtonVariant) -> Self {
        self.variant = variant;
        self
    }

    /// Set whether the button is disabled
    pub fn disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }

    /// Enable toggle behavior
    pub fn toggleable(mut self) -> Self {
        self.toggle = true;
        self
    }

    /// Set initial selected state
    pub fn selected(mut self, selected: bool) -> Self {
        self.selected = selected;
        self
    }

    /// Get the background color with state layer applied
    pub fn background_color(&self, theme: &MaterialTheme) -> Color {
        if self.disabled {
            return match self.variant {
                IconButtonVariant::Standard => Color::NONE,
                IconButtonVariant::Filled | IconButtonVariant::FilledTonal => {
                    theme.on_surface.with_alpha(0.12)
                }
                IconButtonVariant::Outlined => Color::NONE,
            };
        }

        let base = match self.variant {
            IconButtonVariant::Standard => Color::NONE,
            IconButtonVariant::Filled => {
                if self.selected {
                    theme.primary
                } else {
                    theme.surface_container_highest
                }
            }
            IconButtonVariant::FilledTonal => {
                if self.selected {
                    theme.secondary_container
                } else {
                    theme.surface_container_highest
                }
            }
            IconButtonVariant::Outlined => {
                if self.selected {
                    theme.inverse_surface
                } else {
                    Color::NONE
                }
            }
        };

        // Apply state layer
        let state_opacity = self.state_layer_opacity();
        if state_opacity > 0.0 {
            let state_color = self.icon_color(theme);
            if base == Color::NONE {
                state_color.with_alpha(state_opacity)
            } else {
                blend_state_layer(base, state_color, state_opacity)
            }
        } else {
            base
        }
    }

    /// Get the state layer opacity
    fn state_layer_opacity(&self) -> f32 {
        if self.disabled {
            0.0
        } else if self.pressed {
            0.12
        } else if self.hovered {
            0.08
        } else {
            0.0
        }
    }

    /// Get the icon color
    pub fn icon_color(&self, theme: &MaterialTheme) -> Color {
        if self.disabled {
            return theme.on_surface.with_alpha(0.38);
        }

        match self.variant {
            IconButtonVariant::Standard => {
                if self.selected {
                    theme.primary
                } else {
                    theme.on_surface_variant
                }
            }
            IconButtonVariant::Filled => {
                if self.selected {
                    theme.on_primary
                } else {
                    theme.primary
                }
            }
            IconButtonVariant::FilledTonal => {
                if self.selected {
                    theme.on_secondary_container
                } else {
                    theme.on_surface_variant
                }
            }
            IconButtonVariant::Outlined => {
                if self.selected {
                    theme.inverse_on_surface
                } else {
                    theme.on_surface_variant
                }
            }
        }
    }

    /// Get the border color
    pub fn border_color(&self, theme: &MaterialTheme) -> Color {
        if self.variant != IconButtonVariant::Outlined {
            return Color::NONE;
        }

        if self.disabled {
            theme.on_surface.with_alpha(0.12)
        } else if self.selected {
            Color::NONE
        } else {
            theme.outline
        }
    }
}

/// Event fired when an icon button is clicked
#[derive(Event, bevy::prelude::Message)]
pub struct IconButtonClickEvent {
    /// The button entity
    pub entity: Entity,
    /// Whether the button is now selected (for toggle buttons)
    pub selected: bool,
}

/// System to handle icon button interactions
fn icon_button_interaction_system(
    mut interaction_query: Query<
        (Entity, &Interaction, &mut MaterialIconButton),
        (Changed<Interaction>, With<MaterialIconButton>),
    >,
    mut click_events: MessageWriter<IconButtonClickEvent>,
) {
    for (entity, interaction, mut button) in interaction_query.iter_mut() {
        if button.disabled {
            continue;
        }

        match *interaction {
            Interaction::Pressed => {
                button.pressed = true;
                button.hovered = false;

                if button.toggle {
                    button.selected = !button.selected;
                }

                click_events.write(IconButtonClickEvent {
                    entity,
                    selected: button.selected,
                });
            }
            Interaction::Hovered => {
                button.pressed = false;
                button.hovered = true;
            }
            Interaction::None => {
                button.pressed = false;
                button.hovered = false;
            }
        }
    }
}

/// System to update icon button styles
fn icon_button_style_system(
    theme: Option<Res<MaterialTheme>>,
    mut buttons: Query<
        (&MaterialIconButton, &mut BackgroundColor, &mut BorderColor),
        Changed<MaterialIconButton>,
    >,
) {
    let Some(theme) = theme else { return };

    for (button, mut bg_color, mut border_color) in buttons.iter_mut() {
        *bg_color = BackgroundColor(button.background_color(&theme));
        *border_color = BorderColor::all(button.border_color(&theme));
    }
}

/// System to update the child icon color when the icon button state changes.
fn icon_button_content_style_system(
    theme: Option<Res<MaterialTheme>>,
    buttons: Query<(Entity, &MaterialIconButton), Changed<MaterialIconButton>>,
    children_q: Query<&Children>,
    mut icons: Query<&mut MaterialIcon>,
) {
    let Some(theme) = theme else { return };

    for (entity, button) in buttons.iter() {
        let Ok(children) = children_q.get(entity) else {
            continue;
        };
        let icon_color = button.icon_color(&theme);
        for child in children.iter() {
            if let Ok(mut icon) = icons.get_mut(child) {
                icon.color = icon_color;
            }
        }
    }
}

/// Refresh icon button visuals when the theme resource changes.
fn icon_button_theme_refresh_system(
    theme: Option<Res<MaterialTheme>>,
    mut buttons: Query<(
        Entity,
        &MaterialIconButton,
        &mut BackgroundColor,
        &mut BorderColor,
    )>,
    children_q: Query<&Children>,
    mut icons: Query<&mut MaterialIcon>,
) {
    let Some(theme) = theme else { return };
    if !theme.is_changed() {
        return;
    }

    for (entity, button, mut bg_color, mut border_color) in buttons.iter_mut() {
        *bg_color = BackgroundColor(button.background_color(&theme));
        *border_color = BorderColor::all(button.border_color(&theme));

        let Ok(children) = children_q.get(entity) else {
            continue;
        };
        let icon_color = button.icon_color(&theme);
        for child in children.iter() {
            if let Ok(mut icon) = icons.get_mut(child) {
                icon.color = icon_color;
            }
        }
    }
}

/// Standard icon button size
pub const ICON_BUTTON_SIZE: f32 = 40.0;
/// Icon size within button
pub const ICON_SIZE: f32 = 24.0;

/// Builder for icon buttons
pub struct IconButtonBuilder {
    button: MaterialIconButton,
}

impl IconButtonBuilder {
    /// Create a new icon button builder
    pub fn new(icon: impl Into<String>) -> Self {
        Self {
            button: MaterialIconButton::new(icon),
        }
    }

    /// Set the variant
    pub fn variant(mut self, variant: IconButtonVariant) -> Self {
        self.button.variant = variant;
        self
    }

    /// Make standard variant
    pub fn standard(self) -> Self {
        self.variant(IconButtonVariant::Standard)
    }

    /// Make filled variant
    pub fn filled(self) -> Self {
        self.variant(IconButtonVariant::Filled)
    }

    /// Make filled tonal variant
    pub fn filled_tonal(self) -> Self {
        self.variant(IconButtonVariant::FilledTonal)
    }

    /// Make outlined variant
    pub fn outlined(self) -> Self {
        self.variant(IconButtonVariant::Outlined)
    }

    /// Set disabled state
    pub fn disabled(mut self, disabled: bool) -> Self {
        self.button.disabled = disabled;
        self
    }

    /// Enable toggle mode
    pub fn toggle(mut self) -> Self {
        self.button.toggle = true;
        self
    }

    /// Set selected state
    pub fn selected(mut self, selected: bool) -> Self {
        self.button.selected = selected;
        self
    }

    /// Build the button bundle
    pub fn build(self, theme: &MaterialTheme) -> impl Bundle {
        let bg_color = self.button.background_color(theme);
        let border_color = self.button.border_color(theme);
        let border_width = if self.button.variant == IconButtonVariant::Outlined {
            1.0
        } else {
            0.0
        };

        (
            self.button,
            Button,
            RippleHost::new(),
            Node {
                width: Val::Px(ICON_BUTTON_SIZE),
                height: Val::Px(ICON_BUTTON_SIZE),
                justify_content: JustifyContent::Center,
                align_items: AlignItems::Center,
                border: UiRect::all(Val::Px(border_width)),
                border_radius: BorderRadius::all(Val::Px(CornerRadius::FULL)),
                ..default()
            },
            BackgroundColor(bg_color),
            BorderColor::all(border_color),
        )
    }
}

// ============================================================================
// Spawn Traits for ChildSpawnerCommands
// ============================================================================

/// Extension trait to spawn Material icon buttons as children
///
/// This trait provides a clean API for spawning icon buttons within UI hierarchies.
///
/// ## Example:
/// ```no_run
/// use bevy::prelude::*;
/// use bevy_material_ui::icon_button::{IconButtonVariant, SpawnIconButtonChild};
/// use bevy_material_ui::theme::MaterialTheme;
///
/// fn setup(mut commands: Commands, theme: Res<MaterialTheme>) {
///     commands.spawn(Node::default()).with_children(|children| {
///         children.spawn_icon_button(&theme, "favorite", IconButtonVariant::Standard);
///         children.spawn_filled_icon_button(&theme, "add");
///     });
/// }
/// ```
pub trait SpawnIconButtonChild {
    /// Spawn an icon button with specified variant
    fn spawn_icon_button(
        &mut self,
        theme: &MaterialTheme,
        icon: impl Into<String>,
        variant: IconButtonVariant,
    );

    /// Spawn a standard icon button
    fn spawn_standard_icon_button(&mut self, theme: &MaterialTheme, icon: impl Into<String>);

    /// Spawn a filled icon button
    fn spawn_filled_icon_button(&mut self, theme: &MaterialTheme, icon: impl Into<String>);

    /// Spawn an outlined icon button
    fn spawn_outlined_icon_button(&mut self, theme: &MaterialTheme, icon: impl Into<String>);

    /// Spawn an icon button with full builder control
    fn spawn_icon_button_with(&mut self, theme: &MaterialTheme, button: MaterialIconButton);
}

impl SpawnIconButtonChild for ChildSpawnerCommands<'_> {
    fn spawn_icon_button(
        &mut self,
        theme: &MaterialTheme,
        icon: impl Into<String>,
        variant: IconButtonVariant,
    ) {
        let icon_name = icon.into();
        let builder = IconButtonBuilder::new(icon_name.clone()).variant(variant);
        let icon_color = builder.button.icon_color(theme);

        self.spawn(builder.build(theme)).with_children(|button| {
            if let Some(icon) = MaterialIcon::from_name(&icon_name) {
                button.spawn(icon.with_color(icon_color).with_size(ICON_SIZE));
            }
        });
    }

    fn spawn_standard_icon_button(&mut self, theme: &MaterialTheme, icon: impl Into<String>) {
        self.spawn_icon_button(theme, icon, IconButtonVariant::Standard);
    }

    fn spawn_filled_icon_button(&mut self, theme: &MaterialTheme, icon: impl Into<String>) {
        self.spawn_icon_button(theme, icon, IconButtonVariant::Filled);
    }

    fn spawn_outlined_icon_button(&mut self, theme: &MaterialTheme, icon: impl Into<String>) {
        self.spawn_icon_button(theme, icon, IconButtonVariant::Outlined);
    }

    fn spawn_icon_button_with(&mut self, theme: &MaterialTheme, button: MaterialIconButton) {
        let icon_color = button.icon_color(theme);
        let icon_name = button.icon.clone();
        let builder = IconButtonBuilder { button };

        self.spawn(builder.build(theme)).with_children(|btn| {
            if let Some(icon) = MaterialIcon::from_name(&icon_name) {
                btn.spawn(icon.with_color(icon_color).with_size(ICON_SIZE));
            }
        });
    }
}