bevy_feathers 0.19.0

A collection of UI widgets for building editors and utilities in 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
use core::f32::consts::PI;

use bevy_app::{Plugin, PreUpdate};
use bevy_asset::Handle;
use bevy_color::{Alpha, Color, Hsla};
use bevy_ecs::{
    bundle::Bundle,
    children,
    component::Component,
    entity::Entity,
    hierarchy::Children,
    query::{Changed, Or, With},
    reflect::ReflectComponent,
    schedule::IntoScheduleConfigs,
    system::Query,
};
use bevy_input_focus::tab_navigation::TabIndex;
use bevy_log::warn_once;
use bevy_picking::PickingSystems;
use bevy_reflect::std_traits::ReflectDefault;
use bevy_reflect::Reflect;
use bevy_scene::prelude::*;
use bevy_ui::{
    percent, px, AlignItems, BackgroundColor, BackgroundGradient, BorderColor, BorderRadius,
    ColorStop, Display, FlexDirection, Gradient, InterpolationColorSpace, LinearGradient, Node,
    Outline, PositionType, UiRect, UiTransform, Val2, ZIndex,
};
use bevy_ui_render::ui_material::MaterialNode;
use bevy_ui_widgets::{
    Slider, SliderOrientation, SliderRange, SliderThumb, SliderValue, TrackClick,
};

use crate::{
    alpha_pattern::{AlphaPattern, AlphaPatternMaterial},
    cursor::EntityCursor,
    focus::FocusIndicator,
    palette,
    rounded_corners::RoundedCorners,
};

const SLIDER_HEIGHT: f32 = 16.0;
const TRACK_PADDING: f32 = 3.0;
const TRACK_RADIUS: f32 = SLIDER_HEIGHT * 0.5 - TRACK_PADDING;
const THUMB_SIZE: f32 = SLIDER_HEIGHT - 2.0;

/// Indicates which color channel we want to edit.
#[derive(Component, Default, Copy, Clone, Reflect)]
#[reflect(Component, Default, Clone)]
pub enum ColorChannel {
    /// Editing the RGB red channel (0..=1)
    #[default]
    Red,
    /// Editing the RGB green channel (0..=1)
    Green,
    /// Editing the RGB blue channel (0..=1)
    Blue,
    /// Editing the hue channel (0..=360)
    HslHue,
    /// Editing the chroma / saturation channel (0..=1)
    HslSaturation,
    /// Editing the luminance channel (0..=1)
    HslLightness,
    /// Editing the alpha channel (0..=1)
    Alpha,
}

impl ColorChannel {
    /// Return the range of this color channel.
    pub fn range(&self) -> SliderRange {
        match self {
            ColorChannel::Red
            | ColorChannel::Green
            | ColorChannel::Blue
            | ColorChannel::Alpha
            | ColorChannel::HslSaturation
            | ColorChannel::HslLightness => SliderRange::new(0., 1.),
            ColorChannel::HslHue => SliderRange::new(0., 360.),
        }
    }

    /// Return the color endpoints and midpoint of the gradient. This is determined by both the
    /// channel being edited and the base color.
    pub fn gradient_ends(&self, base_color: Color) -> (Color, Color, Color) {
        match self {
            ColorChannel::Red => {
                let base_rgb = base_color.to_srgba();
                (
                    Color::srgb(0.0, base_rgb.green, base_rgb.blue),
                    Color::srgb(0.5, base_rgb.green, base_rgb.blue),
                    Color::srgb(1.0, base_rgb.green, base_rgb.blue),
                )
            }

            ColorChannel::Green => {
                let base_rgb = base_color.to_srgba();
                (
                    Color::srgb(base_rgb.red, 0.0, base_rgb.blue),
                    Color::srgb(base_rgb.red, 0.5, base_rgb.blue),
                    Color::srgb(base_rgb.red, 1.0, base_rgb.blue),
                )
            }

            ColorChannel::Blue => {
                let base_rgb = base_color.to_srgba();
                (
                    Color::srgb(base_rgb.red, base_rgb.green, 0.0),
                    Color::srgb(base_rgb.red, base_rgb.green, 0.5),
                    Color::srgb(base_rgb.red, base_rgb.green, 1.0),
                )
            }

            ColorChannel::HslHue => (
                Color::hsl(0.0 + 0.0001, 1.0, 0.5),
                Color::hsl(180.0, 1.0, 0.5),
                Color::hsl(360.0 - 0.0001, 1.0, 0.5),
            ),

            ColorChannel::HslSaturation => {
                let base_hsla: Hsla = base_color.into();
                (
                    Color::hsl(base_hsla.hue, 0.0, base_hsla.lightness),
                    Color::hsl(base_hsla.hue, 0.5, base_hsla.lightness),
                    Color::hsl(base_hsla.hue, 1.0, base_hsla.lightness),
                )
            }

            ColorChannel::HslLightness => {
                let base_hsla: Hsla = base_color.into();
                (
                    Color::hsl(base_hsla.hue, base_hsla.saturation, 0.0),
                    Color::hsl(base_hsla.hue, base_hsla.saturation, 0.5),
                    Color::hsl(base_hsla.hue, base_hsla.saturation, 1.0),
                )
            }

            ColorChannel::Alpha => (
                base_color.with_alpha(0.),
                base_color.with_alpha(0.5),
                base_color.with_alpha(1.),
            ),
        }
    }
}

/// Used to store the color channels that we are not editing: the components of the color
/// that are constant for this slider.
#[derive(Component, Default, Clone, Reflect)]
#[reflect(Component, Default, Clone)]
pub struct SliderBaseColor(pub Color);

/// A color slider widget.
///
/// This is spawnable by inheriting it as a "scene component" with optional [`FeathersColorSliderProps`].
///
/// # Emitted events
///
/// * [`bevy_ui_widgets::ValueChange<f32>`] when the slider value is changed.
///
///  These events can be disabled by adding an [`bevy_ui::InteractionDisabled`] component to the entity
#[derive(SceneComponent, Default, Clone)]
#[scene(FeathersColorSliderProps)]
#[derive(Reflect)]
#[reflect(Component, Default, Clone)]
pub struct FeathersColorSlider;

/// Props used to construct a [`FeathersColorSlider`] scene.
#[derive(Clone)]
pub struct FeathersColorSliderProps {
    /// Slider current value
    pub value: f32,
    /// Which color component we're editing
    pub channel: ColorChannel,
}

impl Default for FeathersColorSliderProps {
    fn default() -> Self {
        Self {
            value: 0.0,
            channel: ColorChannel::Alpha,
        }
    }
}

/// A color slider widget.
#[derive(Component, Default, Clone)]
#[require(Slider, SliderBaseColor(Color::WHITE))]
#[derive(Reflect)]
#[reflect(Component, Default, Clone)]
pub struct ColorSlider {
    /// Which channel is being edited by this slider.
    pub channel: ColorChannel,
}

/// Marker for the track
#[derive(Component, Default, Clone, Reflect)]
#[reflect(Component, Default, Clone)]
struct ColorSliderTrack;

/// Marker for the thumb
#[derive(Component, Default, Clone, Reflect)]
#[reflect(Component, Default, Clone)]
struct ColorSliderThumb;

impl FeathersColorSlider {
    fn scene(props: FeathersColorSliderProps) -> impl Scene {
        bsn! {
            Node {
                display: Display::Flex,
                flex_direction: FlexDirection::Row,
                height: px(SLIDER_HEIGHT),
                align_items: AlignItems::Stretch,
                flex_grow: 1.0,
            }
            Slider {
                track_click: TrackClick::Snap,
                orientation: SliderOrientation::Horizontal,
            }
            ColorSlider {
                channel: {props.channel},
            }
            SliderValue({props.value})
            template_value(props.channel.range())
            EntityCursor::System(bevy_window::SystemCursorIcon::Pointer)
            TabIndex(0)
            FocusIndicator
            Children [
                // track
                (
                    Node {
                        position_type: PositionType::Absolute,
                        left: px(0),
                        right: px(0),
                        top: px(TRACK_PADDING),
                        bottom: px(TRACK_PADDING),
                        border_radius: {RoundedCorners::All.to_border_radius(TRACK_RADIUS)},
                    }
                    ColorSliderTrack
                    AlphaPattern
                    MaterialNode::<AlphaPatternMaterial>
                    Children [
                        // Left endcap
                        (
                            Node {
                                width: px(THUMB_SIZE * 0.5),
                                border_radius: {RoundedCorners::Left.to_border_radius(TRACK_RADIUS)},
                            }
                            BackgroundColor(palette::X_AXIS)
                        ),
                        // Track with gradient
                        (
                            Node {
                                flex_grow: 1.0,
                            }
                            BackgroundGradient(vec![Gradient::Linear(LinearGradient {
                                angle: PI * 0.5,
                                stops: vec![
                                    ColorStop::new(Color::NONE, percent(0)),
                                    ColorStop::new(Color::NONE, percent(50)),
                                    ColorStop::new(Color::NONE, percent(100)),
                                ],
                                color_space: InterpolationColorSpace::Srgba,
                            })])
                            ZIndex(1)
                            Children [(
                                Node {
                                    position_type: PositionType::Absolute,
                                    left: percent(0),
                                    top: percent(50),
                                    width: px(THUMB_SIZE),
                                    height: px(THUMB_SIZE),
                                    border: px(2),
                                    border_radius: BorderRadius::MAX,
                                }
                                SliderThumb
                                ColorSliderThumb
                                BorderColor::all(palette::WHITE)
                                Outline {
                                    width: px(1),
                                    offset: px(0),
                                    color: palette::BLACK
                                }
                                UiTransform::from_translation(Val2::percent(-50., -50.))
                            )]
                        ),
                        // Right endcap
                        (
                            Node {
                                width: px(THUMB_SIZE * 0.5),
                                border_radius: {RoundedCorners::Right.to_border_radius(TRACK_RADIUS)},
                            }
                            BackgroundColor(palette::Z_AXIS)
                        )
                    ]
                )
            ]
        }
    }
}

/// Spawn a new slider widget.
///
/// # Arguments
///
/// * `props` - construction properties for the slider.
/// * `overrides` - a bundle of components that are merged in with the normal slider components.
///
/// # Emitted events
///
/// * [`bevy_ui_widgets::ValueChange<f32>`] when the slider value is changed.
///
///  These events can be disabled by adding an [`bevy_ui::InteractionDisabled`] component to the entity
#[deprecated(since = "0.19.0", note = "Use the color_slider() BSN function")]
pub fn color_slider_bundle<B: Bundle>(
    props: FeathersColorSliderProps,
    overrides: B,
) -> impl Bundle {
    (
        Node {
            display: Display::Flex,
            flex_direction: FlexDirection::Row,
            height: px(SLIDER_HEIGHT),
            align_items: AlignItems::Stretch,
            flex_grow: 1.0,
            ..Default::default()
        },
        Slider {
            track_click: TrackClick::Snap,
            orientation: SliderOrientation::Horizontal,
        },
        ColorSlider {
            channel: props.channel,
        },
        SliderValue(props.value),
        props.channel.range(),
        EntityCursor::System(bevy_window::SystemCursorIcon::Pointer),
        TabIndex(0),
        FocusIndicator,
        overrides,
        children![
            // track
            (
                Node {
                    position_type: PositionType::Absolute,
                    left: px(0),
                    right: px(0),
                    top: px(TRACK_PADDING),
                    bottom: px(TRACK_PADDING),
                    border_radius: RoundedCorners::All.to_border_radius(TRACK_RADIUS),
                    ..Default::default()
                },
                ColorSliderTrack,
                AlphaPattern,
                MaterialNode::<AlphaPatternMaterial>(Handle::default()),
                children![
                    // Left endcap
                    (
                        Node {
                            width: px(THUMB_SIZE * 0.5),
                            border_radius: RoundedCorners::Left.to_border_radius(TRACK_RADIUS),
                            ..Default::default()
                        },
                        BackgroundColor(palette::X_AXIS),
                    ),
                    // Track with gradient
                    (
                        Node {
                            flex_grow: 1.0,
                            ..Default::default()
                        },
                        BackgroundGradient(vec![Gradient::Linear(LinearGradient {
                            angle: PI * 0.5,
                            stops: vec![
                                ColorStop::new(Color::NONE, percent(0)),
                                ColorStop::new(Color::NONE, percent(50)),
                                ColorStop::new(Color::NONE, percent(100)),
                            ],
                            color_space: InterpolationColorSpace::Srgba,
                        })]),
                        ZIndex(1),
                        children![(
                            Node {
                                position_type: PositionType::Absolute,
                                left: percent(0),
                                top: percent(50),
                                width: px(THUMB_SIZE),
                                height: px(THUMB_SIZE),
                                border: UiRect::all(px(2)),
                                border_radius: BorderRadius::MAX,
                                ..Default::default()
                            },
                            SliderThumb,
                            ColorSliderThumb,
                            BorderColor::all(palette::WHITE),
                            Outline {
                                width: px(1),
                                offset: px(0),
                                color: palette::BLACK
                            },
                            UiTransform::from_translation(Val2::new(percent(-50), percent(-50),))
                        )]
                    ),
                    // Right endcap
                    (
                        Node {
                            width: px(THUMB_SIZE * 0.5),
                            border_radius: RoundedCorners::Right.to_border_radius(TRACK_RADIUS),
                            ..Default::default()
                        },
                        BackgroundColor(palette::Z_AXIS),
                    ),
                ]
            ),
        ],
    )
}

fn update_slider_pos(
    mut q_sliders: Query<
        (Entity, &SliderValue, &SliderRange),
        (
            With<ColorSlider>,
            Or<(Changed<SliderValue>, Changed<SliderRange>)>,
        ),
    >,
    q_children: Query<&Children>,
    mut q_slider_thumb: Query<&mut Node, With<ColorSliderThumb>>,
) {
    for (slider_ent, value, range) in q_sliders.iter_mut() {
        for child in q_children.iter_descendants(slider_ent) {
            if let Ok(mut thumb_node) = q_slider_thumb.get_mut(child) {
                thumb_node.left = percent(range.thumb_position(value.0) * 100.0);
            }
        }
    }
}

fn update_track_color(
    mut q_sliders: Query<(Entity, &ColorSlider, &SliderBaseColor), Changed<SliderBaseColor>>,
    q_children: Query<&Children>,
    q_track: Query<(), With<ColorSliderTrack>>,
    mut q_background: Query<&mut BackgroundColor>,
    mut q_gradient: Query<&mut BackgroundGradient>,
) {
    for (slider_ent, slider, SliderBaseColor(base_color)) in q_sliders.iter_mut() {
        let (start, middle, end) = slider.channel.gradient_ends(*base_color);
        if let Some(track_ent) = q_children
            .iter_descendants(slider_ent)
            .find(|ent| q_track.contains(*ent))
        {
            let Ok(track_children) = q_children.get(track_ent) else {
                continue;
            };

            if let Ok(mut cap_bg) = q_background.get_mut(track_children[0]) {
                cap_bg.0 = start;
            }

            if let Ok(mut gradient) = q_gradient.get_mut(track_children[1])
                && let [Gradient::Linear(linear_gradient)] = &mut gradient.0[..]
            {
                linear_gradient.stops[0].color = start;
                linear_gradient.stops[1].color = middle;
                linear_gradient.stops[2].color = end;
                linear_gradient.color_space = match slider.channel {
                    ColorChannel::Red | ColorChannel::Green | ColorChannel::Blue => {
                        InterpolationColorSpace::Srgba
                    }
                    ColorChannel::HslHue
                    | ColorChannel::HslLightness
                    | ColorChannel::HslSaturation => InterpolationColorSpace::Hsla,
                    ColorChannel::Alpha => match base_color {
                        Color::Srgba(_) => InterpolationColorSpace::Srgba,
                        Color::LinearRgba(_) => InterpolationColorSpace::LinearRgba,
                        Color::Oklaba(_) => InterpolationColorSpace::Oklaba,
                        Color::Oklcha(_) => InterpolationColorSpace::OklchaLong,
                        Color::Hsla(_) | Color::Hsva(_) => InterpolationColorSpace::Hsla,
                        _ => {
                            warn_once!("Unsupported color space for ColorSlider: {:?}", base_color);
                            InterpolationColorSpace::Srgba
                        }
                    },
                };
            }

            if let Ok(mut cap_bg) = q_background.get_mut(track_children[2]) {
                cap_bg.0 = end;
            }
        }
    }
}

/// Plugin which registers the systems for updating the slider styles.
pub struct ColorSliderPlugin;

impl Plugin for ColorSliderPlugin {
    fn build(&self, app: &mut bevy_app::App) {
        app.add_systems(
            PreUpdate,
            (update_slider_pos, update_track_color).in_set(PickingSystems::Last),
        );
    }
}