bevy_pages 0.3.2

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
use crate::element::{ElementId, ElementProps};
use crate::events::ElementSet;
use crate::parser::color::parse_color;
use crate::parser::values::{parse_attribute, parse_float};
use crate::props::Properties;
use crate::systems::PageSystemSet;
use crate::widgets::Widget;
use bevy::asset::AssetServer;
use bevy::color::Color;
use bevy::ecs::system::EntityCommands;
use bevy::picking::hover::Hovered;
use bevy::prelude::*;
use bevy::ui::{BackgroundColor, BorderRadius, Display, FlexDirection, Node, PositionType, Val};
use bevy::ui_widgets::{
    Slider, SliderDragState, SliderRange, SliderThumb, SliderValue, TrackClick, observe,
    slider_self_update,
};
use roxmltree::Node as XmlNode;

fn sync_visuals(
    mut commands: Commands,
    mut slider_query: Query<
        (
            Entity,
            &Properties<SliderProps>,
            &SliderValue,
            &SliderRange,
            &mut SliderState,
            Option<&ElementId>,
        ),
        Or<(Changed<SliderValue>, Changed<SliderRange>)>,
    >,
    children_query: Query<&Children>,
    mut fill_query: Query<&mut Node, (With<SliderFill>, Without<SliderThumb>)>,
    mut thumb_query: Query<&mut Node, (With<SliderThumb>, Without<SliderFill>)>,
) {
    for (entity, props, value, range, mut state, id) in &mut slider_query {
        let mut val = value.0;

        if let Some(step) = props.default.step
            && step > 0.0
        {
            val = (val / step).round() * step;
        }

        let pct = range.thumb_position(val) * 100.0;

        if (state.0 - val).abs() > f32::EPSILON {
            let delta = val - state.0;
            state.0 = val;

            commands.trigger(ElementSet {
                entity,
                id: id.cloned(),
                value: val,
                delta: Some(delta),
            });
        }

        for descendant in children_query.iter_descendants(entity) {
            if let Ok(mut fill_node) = fill_query.get_mut(descendant) {
                fill_node.width = Val::Percent(pct);
            }

            if let Ok(mut thumb_node) = thumb_query.get_mut(descendant) {
                thumb_node.left = Val::Percent(pct);
            }
        }
    }
}

fn update_props(
    mut slider_query: Query<
        (Entity, &Properties<SliderProps>, &Hovered, &SliderDragState),
        Or<(
            Changed<Properties<SliderProps>>,
            Changed<Hovered>,
            Changed<SliderDragState>,
        )>,
    >,
    children_query: Query<&Children>,
    mut track_query: Query<
        (&mut Node, &mut BackgroundColor),
        (With<SliderTrack>, Without<SliderFill>, Without<SliderThumb>),
    >,
    mut fill_query: Query<
        (&mut Node, &mut BackgroundColor),
        (With<SliderFill>, Without<SliderTrack>, Without<SliderThumb>),
    >,
    mut thumb_query: Query<
        (&mut Node, &mut BackgroundColor),
        (With<SliderThumb>, Without<SliderTrack>, Without<SliderFill>),
    >,
) {
    for (entity, props, hovered, drag_state) in &mut slider_query {
        let active_props = if drag_state.dragging {
            &props.click
        } else if hovered.0 {
            &props.hover
        } else {
            &props.default
        };

        for descendant in children_query.iter_descendants(entity) {
            if let Ok((mut track_node, mut track_bg)) = track_query.get_mut(descendant) {
                crate::set_if_changed!(
                    track_node.height, Val::Px(active_props.track_height);
                    track_node.border_radius, BorderRadius::all(Val::Px(active_props.track_height / 2.0));
                    track_bg.0, active_props.track_color;
                );
            }

            if let Ok((mut fill_node, mut fill_bg)) = fill_query.get_mut(descendant) {
                crate::set_if_changed!(
                    fill_node.height, Val::Px(active_props.track_height);
                    fill_node.border_radius, BorderRadius::all(Val::Px(active_props.track_height / 2.0));
                    fill_bg.0, active_props.fill_color;
                );
            }

            if let Ok((mut thumb_node, mut thumb_bg)) = thumb_query.get_mut(descendant) {
                crate::set_if_changed!(
                    thumb_node.width, Val::Px(active_props.thumb_size);
                    thumb_node.height, Val::Px(active_props.thumb_size);
                    thumb_node.border_radius, BorderRadius::all(Val::Px(active_props.thumb_size / 2.0));
                    thumb_bg.0, active_props.thumb_color;
                );
            }
        }
    }
}

/// The internal state of the slider.
#[derive(Copy, Clone, Debug, Component)]
pub struct SliderState(pub f32);

/// Marker component for the track of a Slider.
#[derive(Component)]
pub struct SliderTrack;

/// Marker component for the fill of a Slider.
#[derive(Component)]
pub struct SliderFill;

/// A slider widget.
///
/// ## XML Usage
///
/// Build a slider widget using the `<Slider />` tag.
///
/// ### Attributes
/// - `min = "<float>"`: The minimum of the slider.
/// - `max = "<float>"`: The maximum of the slider.
/// - `step = "<float>"`: The step size for the slider.
/// - `value = "<float>"`: The value of the slider.
/// - `track-color = "<color>"`: The color of the slider track.
/// - `thumb-color = "<color>"`: The color of the slider thumb.
/// - `fill-color = "<color>"`: The color of the slider fill.
/// - `track-height = "<float>"`: The height of the slider track in pixels.
/// - `thumb-size = "<float>"`: The size of the slider thumb in pixels.
///
/// All the attributes, except `min` and `max`, support state overrides.
///
/// ## Logic
///
/// Use the [SliderProps] to control the slider.
/// Furthermore, the slider emits `ElementSet<f32>` events.
///
/// You may also use generic element events to implement custom behavior.
#[derive(Clone, Debug, Default)]
pub struct SliderWidget {
    props: Properties<SliderProps>,
}

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

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

    fn parse(&mut self, node: &XmlNode) -> Result<(), String>
    where
        Self: Sized,
    {
        let default = SliderProps::parse(node, None, &SliderProps::default())?;
        let hover = SliderProps::parse(node, Some("hover"), &default)?;
        let click = SliderProps::parse(node, Some("click"), &default)?;

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

        Ok(())
    }

    fn spawn(&self, commands: &mut EntityCommands, _: &AssetServer) -> Entity {
        let props = &self.props.default;

        commands.insert((
            self.props.clone(),
            SliderState(props.value),
            Slider {
                track_click: TrackClick::Snap,
                ..default()
            },
            SliderValue(props.value),
            SliderRange::new(props.min, props.max),
            Hovered::default(),
            SliderDragState::default(),
            observe(slider_self_update),
        ));

        commands.with_children(|parent| {
            // Background Track
            parent.spawn((
                SliderTrack,
                Node {
                    width: Val::Percent(100.0),
                    height: Val::Px(props.track_height),
                    border_radius: BorderRadius::all(Val::Px(props.track_height / 2.0)),
                    position_type: PositionType::Absolute,
                    ..default()
                },
                BackgroundColor(props.track_color),
            ));

            // Active Fill Bar
            parent.spawn((
                SliderFill,
                Node {
                    width: Val::Percent(0.0),
                    height: Val::Px(props.track_height),
                    border_radius: BorderRadius::all(Val::Px(props.track_height / 2.0)),
                    position_type: PositionType::Absolute,
                    ..default()
                },
                BackgroundColor(props.fill_color),
            ));

            // Slider Thumb
            parent
                .spawn(Node {
                    display: Display::Flex,
                    position_type: PositionType::Absolute,
                    left: Val::Px(0.0),
                    right: Val::Px(props.thumb_size),
                    top: Val::Px(0.0),
                    bottom: Val::Px(0.0),
                    align_items: AlignItems::Center,
                    ..default()
                })
                .with_children(|thumb_parent| {
                    thumb_parent.spawn((
                        SliderThumb,
                        Node {
                            display: Display::Flex,
                            width: Val::Px(props.thumb_size),
                            height: Val::Px(props.thumb_size),
                            position_type: PositionType::Absolute,
                            left: Val::Percent(0.0),
                            border_radius: BorderRadius::all(Val::Px(props.thumb_size / 2.0)),
                            ..default()
                        },
                        BackgroundColor(props.thumb_color),
                    ));
                });
        });

        commands.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,

            "height" => default.node.height = Val::Px(24.0),
            "hover.height" => hover.node.height = default.node.height,
            "click.height" => click.node.height = default.node.height,

            "display" => default.node.display = Display::Flex,
            "hover.display" => hover.node.display = default.node.display,
            "click.display" => click.node.display = default.node.display,

            "flex-direction" => default.node.flex_direction = FlexDirection::Column,
            "hover.flex-direction" => hover.node.flex_direction = default.node.flex_direction,
            "click.flex-direction" => click.node.flex_direction = default.node.flex_direction,

            "justify-content" => default.node.justify_content = JustifyContent::Center,
            "hover.justify-content" => hover.node.justify_content = default.node.justify_content,
            "click.justify-content" => click.node.justify_content = default.node.justify_content,

            "align-items" => default.node.align_items = AlignItems::Stretch,
            "hover.align-items" => hover.node.align_items = default.node.align_items,
            "click.align-items" => click.node.align_items = default.node.align_items,

            "position" => default.node.position_type = PositionType::Relative,
            "hover.position" => hover.node.position_type = default.node.position_type,
            "click.position" => click.node.position_type = default.node.position_type,
        );
    }

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

/// The properties of a [SliderWidget].
#[derive(Clone, Debug)]
pub struct SliderProps {
    /// The minimum slider value.
    pub min: f32,
    /// The maximum slider value.
    pub max: f32,
    /// The optional step size for the slider.
    pub step: Option<f32>,
    /// The value of the slider.
    pub value: f32,
    /// The slider track color.
    pub track_color: Color,
    /// The slider thumb color.
    pub thumb_color: Color,
    /// The slider fill color.
    pub fill_color: Color,
    /// The slider track height in pixels.
    ///
    /// TODO: Support bevy's [Val]
    pub track_height: f32,
    /// The slider thumb size in pixels.
    ///
    /// TODO: Support bevy's [Val]
    pub thumb_size: f32,
}

impl SliderProps {
    fn parse(
        node: &XmlNode,
        prefix: Option<&str>,
        base: &Self,
    ) -> std::result::Result<Self, String> {
        let min = parse_attribute(node, "min", prefix, parse_float)?.unwrap_or(base.min);

        let max = parse_attribute(node, "max", prefix, parse_float)?.unwrap_or(base.max);

        if min >= max {
            return Err(format!(
                "Slider 'min' ({}) must be strictly less than 'max' ({})",
                min, max
            ));
        }

        let step = parse_attribute(node, "step", prefix, parse_float)?.or(base.step);

        let mut value = parse_attribute(node, "value", prefix, parse_float)?.unwrap_or(base.value);

        if let Some(step_val) = step
            && step_val > 0.0
        {
            value = (value / step_val).round() * step_val;
        }

        value = value.clamp(min, max);

        let track_color =
            parse_attribute(node, "track-color", prefix, parse_color)?.unwrap_or(base.track_color);

        let thumb_color =
            parse_attribute(node, "thumb-color", prefix, parse_color)?.unwrap_or(base.thumb_color);

        let fill_color =
            parse_attribute(node, "fill-color", prefix, parse_color)?.unwrap_or(base.fill_color);

        let track_height = parse_attribute(node, "track-height", prefix, parse_float)?
            .unwrap_or(base.track_height);

        let thumb_size =
            parse_attribute(node, "thumb-size", prefix, parse_float)?.unwrap_or(base.thumb_size);

        Ok(Self {
            min,
            max,
            step,
            value,
            track_color,
            thumb_color,
            fill_color,
            track_height,
            thumb_size,
        })
    }
}

impl Default for SliderProps {
    #[inline(always)]
    fn default() -> Self {
        Self {
            min: 0.0,
            max: 1.0,
            step: None,
            value: 0.0,
            track_color: Color::srgb(0.16, 0.17, 0.20),
            thumb_color: Color::WHITE,
            fill_color: Color::srgb(0.38, 0.69, 0.94),
            track_height: 6.0,
            thumb_size: 16.0,
        }
    }
}