bevy_pages 0.3.4

A lightweight and elegant framework to upgrade your Bevy UI experience.
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
use crate::element::{ElementId, ElementProps};
use crate::events::ElementSet;
use crate::parser::AttributeMap;
use crate::parser::color::parse_color;
use crate::parser::values::parse_attribute;
use crate::props::Properties;
use crate::systems::PageSystemSet;
use crate::widgets::Widget;
use bevy::color::Color;
use bevy::prelude::*;
use roxmltree::Node as XmlNode;

fn trigger_menu(
    mut trigger_query: Query<
        (&Interaction, &ChildOf),
        (With<DropdownTrigger>, Changed<Interaction>),
    >,
    mut root_query: Query<&mut DropdownState>,
) {
    for (interaction, child_of) in &mut trigger_query {
        if *interaction == Interaction::Pressed
            && let Ok(mut state) = root_query.get_mut(child_of.0)
        {
            state.is_open = !state.is_open;
        }
    }
}

fn option_select(
    mut commands: Commands,
    interaction_query: Query<(Entity, &Interaction), Changed<Interaction>>,
    child_of_query: Query<&ChildOf>,
    menu_query: Query<&ChildOf, With<DropdownMenu>>,
    mut root_query: Query<(Entity, &mut DropdownState, &Children, Option<&ElementId>)>,
    trigger_query: Query<&Children, With<DropdownTrigger>>,
    label_query: Query<Entity, With<DropdownLabelText>>,
    mut text_query: Query<&mut Text>,
    children_query: Query<&Children>,
) {
    for (clicked_entity, interaction) in &interaction_query {
        if *interaction != Interaction::Pressed {
            continue;
        }

        if let Some(root_entity) = find_dropdown_root(clicked_entity, &child_of_query, &menu_query)
            && let Ok((entity, mut state, root_children, element_id)) =
                root_query.get_mut(root_entity)
        {
            // Extract label text from the clicked entity or its child subtree
            let extracted_label =
                extract_text_from_entity(clicked_entity, &text_query, &children_query)
                    .unwrap_or_else(|| "Selected Option".to_string());

            state.selected_value = extracted_label.clone();
            state.selected_label = extracted_label.clone();
            state.is_open = false; // Auto-close menu on selection

            commands.trigger(ElementSet {
                entity,
                id: element_id.cloned(),
                value: extracted_label.clone(),
                delta: None,
            });

            // Sync the trigger header label text
            for child in root_children.iter() {
                if let Ok(trigger_children) = trigger_query.get(child) {
                    for trigger_child in trigger_children.iter() {
                        if label_query.contains(trigger_child)
                            && let Ok(mut text) = text_query.get_mut(trigger_child)
                        {
                            **text = extracted_label.clone();
                        }
                    }
                }
            }
        }
    }
}

fn visibility(
    root_query: Query<(&DropdownState, &Children), Changed<DropdownState>>,
    mut menu_query: Query<(&mut Node, &mut ZIndex), With<DropdownMenu>>,
) {
    for (state, children) in &root_query {
        for child in children.iter() {
            if let Ok((mut node, mut z_index)) = menu_query.get_mut(child) {
                if state.is_open {
                    node.display = Display::Flex;
                    *z_index = ZIndex(100);
                } else {
                    node.display = Display::None;
                    *z_index = ZIndex(0);
                }
            }
        }
    }
}

fn close_on_outside_click(
    mouse_button: Res<ButtonInput<MouseButton>>,
    mut root_query: Query<(Entity, &mut DropdownState)>,
    interaction_query: Query<&Interaction>,
    children_query: Query<&Children>,
) {
    if !mouse_button.just_pressed(MouseButton::Left) {
        return;
    }

    for (root_entity, mut state) in &mut root_query {
        if !state.is_open {
            continue;
        }

        // Check if any entity within this specific dropdown's tree is hovered or pressed
        let is_interacting =
            is_hierarchy_interacting(root_entity, &interaction_query, &children_query);

        if !is_interacting {
            state.is_open = false;
        }
    }
}

fn update_props(
    root_query: Query<(&Properties<DropdownProps>, &DropdownState, &Children)>,
    mut trigger_query: Query<
        (&Interaction, &Children, &mut BackgroundColor),
        With<DropdownTrigger>,
    >,
    mut menu_query: Query<&mut BackgroundColor, (With<DropdownMenu>, Without<DropdownTrigger>)>,
    mut label_query: Query<&mut Text, With<DropdownLabelText>>,
    changed_roots: Query<Entity, Or<(Changed<Properties<DropdownProps>>, Changed<DropdownState>)>>,
    changed_triggers: Query<&ChildOf, (With<DropdownTrigger>, Changed<Interaction>)>,
) {
    let mut roots_to_update = std::collections::HashSet::new();

    for entity in &changed_roots {
        roots_to_update.insert(entity);
    }

    for child_of in &changed_triggers {
        roots_to_update.insert(child_of.0);
    }

    for root_entity in roots_to_update {
        let Ok((props, state, root_children)) = root_query.get(root_entity) else {
            continue;
        };

        let mut active_interaction = Interaction::None;
        for child in root_children.iter() {
            if let Ok((interaction, _, _)) = trigger_query.get(child) {
                active_interaction = *interaction;
                break;
            }
        }

        let active_props = match active_interaction {
            Interaction::Pressed => &props.click,
            Interaction::Hovered => &props.hover,
            Interaction::None => &props.default,
        };

        for child in root_children.iter() {
            if let Ok((_, trigger_children, mut trigger_bg)) = trigger_query.get_mut(child) {
                crate::set_if_changed!(trigger_bg.0, active_props.bg_color);

                if state.selected_index.is_none() && state.selected_value.is_empty() {
                    for trigger_child in trigger_children.iter() {
                        if let Ok(mut text) = label_query.get_mut(trigger_child) {
                            crate::set_if_changed!(text.0, active_props.placeholder => active_props.placeholder.clone());
                        }
                    }
                }
            }

            if let Ok(mut menu_bg) = menu_query.get_mut(child) {
                crate::set_if_changed!(menu_bg.0, active_props.menu_bg_color);
            }
        }
    }
}

#[inline]
fn find_dropdown_root(
    start_entity: Entity,
    child_of_query: &Query<&ChildOf>,
    menu_query: &Query<&ChildOf, With<DropdownMenu>>,
) -> Option<Entity> {
    let mut current = start_entity;

    loop {
        // Check if current entity is the DropdownMenu container
        if let Ok(menu_child_of) = menu_query.get(current) {
            return Some(menu_child_of.0); // Returns root Dropdown entity
        }

        // Ascend to parent
        if let Ok(parent) = child_of_query.get(current) {
            current = parent.0;
        } else {
            return None;
        }
    }
}

#[inline]
fn extract_text_from_entity(
    entity: Entity,
    text_query: &Query<&mut Text>,
    children_query: &Query<&Children>,
) -> Option<String> {
    if let Ok(text) = text_query.get(entity)
        && !text.0.is_empty()
    {
        return Some(text.0.clone());
    }

    if let Ok(children) = children_query.get(entity) {
        for child in children.iter() {
            if let Some(found) = extract_text_from_entity(child, text_query, children_query) {
                return Some(found);
            }
        }
    }

    None
}

#[inline]
fn is_hierarchy_interacting(
    entity: Entity,
    interaction_query: &Query<&Interaction>,
    children_query: &Query<&Children>,
) -> bool {
    if let Ok(interaction) = interaction_query.get(entity)
        && matches!(interaction, Interaction::Hovered | Interaction::Pressed)
    {
        return true;
    }

    if let Ok(children) = children_query.get(entity) {
        for child in children.iter() {
            if is_hierarchy_interacting(child, interaction_query, children_query) {
                return true;
            }
        }
    }

    false
}

/// The internal state of a dropdown widget.
#[derive(Component, Debug, Clone)]
pub struct DropdownState {
    /// If the dropdown menu is open.
    pub is_open: bool,
    /// The selected item index.
    pub selected_index: Option<usize>,
    /// The selected value.
    pub selected_value: String,
    /// The selected label.
    pub selected_label: String,
}

impl Default for DropdownState {
    #[inline(always)]
    fn default() -> Self {
        Self {
            is_open: false,
            selected_index: None,
            selected_value: String::new(),
            selected_label: "Select an option...".to_string(),
        }
    }
}

/// Marker component for the header button.
#[derive(Component, Debug, Clone, Copy)]
pub struct DropdownTrigger;

/// Marker component for the overlay container holding the dropdown items.
#[derive(Component, Debug, Clone, Copy)]
pub struct DropdownMenu;

/// Marker for the dropdown label text.
#[derive(Component, Debug, Clone, Copy)]
pub struct DropdownLabelText;

/// A dropdown widget with a list of options.
///
/// ## XML Usage
///
/// Build a dropdown widget using the `<Dropdown></Dropdown>` tag.
///
/// Every "root" children of the dropdown is considered a new option.
///
/// ### Attributes
/// - `placeholder = "<string>"`: The placeholder text to display when no option is selected.
/// - `dropdown-bg-color = "<color>"`: The background color of the dropdown.
/// - `menu-bg-color = "<color>"`: The background color of the dropdown menu.
///
/// All the attributes listed support state overrides.
///
/// ## Logic
///
/// Use the [DropdownProps] to control the dropdown.
/// Furthermore, the dropdown widget triggers `ElementSet<String>` when an option is selected.
///
/// You can also use generic element events to implement custom behavior.
#[derive(Clone, Debug, Default)]
pub struct DropdownWidget {
    props: Properties<DropdownProps>,
}

impl Widget for DropdownWidget {
    fn name() -> &'static str
    where
        Self: Sized,
    {
        "Dropdown"
    }

    fn setup(&self, app: &mut App) {
        app.add_systems(
            Update,
            (
                update_props,
                option_select,
                trigger_menu,
                visibility,
                close_on_outside_click,
            )
                .in_set(PageSystemSet),
        );
    }

    fn parse(&mut self, _: &XmlNode, attrs: AttributeMap) -> Result<(), String> {
        let default = DropdownProps::parse(&attrs, None, &DropdownProps::default())?;
        let hover = DropdownProps::parse(&attrs, Some("hover"), &default)?;
        let click = DropdownProps::parse(&attrs, Some("click"), &default)?;

        self.props = Properties {
            default,
            hover,
            click,
        };

        Ok(())
    }

    fn spawn(&self, entity: Entity, world: &mut World) -> Entity {
        let props = &self.props.default;

        world.entity_mut(entity).insert((
            self.props.clone(),
            DropdownState {
                selected_label: props.placeholder.clone(),
                ..default()
            },
        ));

        let trigger_entity = world
            .spawn((
                ChildOf(entity),
                Transform::default(),
                GlobalTransform::default(),
                DropdownTrigger,
                Interaction::None,
                Node {
                    width: Val::Percent(100.0),
                    height: Val::Px(36.0),
                    padding: UiRect::axes(Val::Px(12.0), Val::Px(8.0)),
                    justify_content: JustifyContent::SpaceBetween,
                    align_items: AlignItems::Center,
                    border: UiRect::all(Val::Px(1.0)),
                    border_radius: BorderRadius::all(Val::Px(4.0)),
                    ..default()
                },
                BackgroundColor(props.bg_color),
                BorderColor::all(Color::srgb(0.4, 0.4, 0.4)),
            ))
            .id();

        world.spawn((
            ChildOf(trigger_entity),
            Transform::default(),
            GlobalTransform::default(),
            DropdownLabelText,
            Text::new(&props.placeholder),
            TextFont {
                font_size: FontSize::Px(14.0),
                ..default()
            },
            TextColor(Color::srgb(0.9, 0.9, 0.9)),
        ));

        world.spawn((
            ChildOf(trigger_entity),
            Transform::default(),
            GlobalTransform::default(),
            Text::new(">"),
            TextFont {
                font_size: FontSize::Px(10.0),
                ..default()
            },
            TextColor(Color::srgb(0.6, 0.6, 0.6)),
        ));

        world
            .spawn((
                ChildOf(entity),
                Transform::default(),
                GlobalTransform::default(),
                DropdownMenu,
                Node {
                    display: Display::None,
                    position_type: PositionType::Absolute,
                    top: Val::Percent(100.0),
                    left: Val::Px(0.0),
                    width: Val::Percent(100.0),
                    max_height: Val::Px(200.0),
                    flex_direction: FlexDirection::Column,
                    overflow: Overflow::clip_y(),
                    margin: UiRect::top(Val::Px(4.0)),
                    border: UiRect::all(Val::Px(1.0)),
                    border_radius: BorderRadius::all(Val::Px(4.0)),
                    ..default()
                },
                ZIndex(100),
                BackgroundColor(props.menu_bg_color),
                BorderColor::all(Color::srgb(0.3, 0.3, 0.3)),
            ))
            .id()
    }

    fn apply_defaults(
        &self,
        node: &XmlNode,
        default: &mut ElementProps,
        hover: &mut ElementProps,
        click: &mut ElementProps,
    ) {
        crate::set_missing_attrs!(
            node,
            "width" => default.node.width = Val::Px(200.0),
            "hover.width" => hover.node.width = default.node.width,
            "click.width" => click.node.width = default.node.width,
        );
    }

    fn dyn_clone(&self) -> Box<dyn Widget> {
        Box::new(self.clone())
    }
}

/// The properties of a [DropdownWidget].
#[derive(Clone, Debug)]
pub struct DropdownProps {
    /// The placeholder text to display when no option is selected.
    pub placeholder: String,
    /// The dropdown background color.
    pub bg_color: Color,
    /// The dropdown menu background color.
    pub menu_bg_color: Color,
}

impl DropdownProps {
    fn parse(attrs: &AttributeMap, prefix: Option<&str>, base: &Self) -> Result<Self, String> {
        let placeholder = parse_attribute(attrs, "placeholder", prefix, |s| Ok(s.to_string()))?
            .unwrap_or_else(|| base.placeholder.clone());

        let bg_color = parse_attribute(attrs, "dropdown-bg-color", prefix, parse_color)?
            .unwrap_or(base.bg_color);

        let menu_bg_color = parse_attribute(attrs, "menu-bg-color", prefix, parse_color)?
            .unwrap_or(base.menu_bg_color);

        Ok(Self {
            placeholder,
            bg_color,
            menu_bg_color,
        })
    }
}

impl Default for DropdownProps {
    #[inline(always)]
    fn default() -> Self {
        Self {
            placeholder: String::default(),
            bg_color: Color::srgb(0.2, 0.2, 0.2),
            menu_bg_color: Color::srgb(0.15, 0.15, 0.15),
        }
    }
}