bevy_ui_widgets 0.19.0

Unstyled common widgets for Bevy 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
use bevy_app::{App, Plugin, PostUpdate};
use bevy_camera::visibility::Visibility;
use bevy_ecs::{
    change_detection::DetectChangesMut,
    component::Component,
    entity::Entity,
    event::EntityEvent,
    hierarchy::{ChildOf, Children},
    observer::On,
    query::{With, Without},
    reflect::ReflectComponent,
    schedule::IntoScheduleConfigs,
    system::{Query, Res},
    template::FromTemplate,
};
use bevy_math::{Affine2, Vec2};
use bevy_picking::events::{Cancel, Drag, DragEnd, DragStart, Pointer, Press};
use bevy_reflect::{prelude::ReflectDefault, Reflect};
use bevy_ui::{
    prelude::BorderRect, ui_layout_system, BackgroundColor, BorderColor, BorderRadius,
    ComputedNode, ComputedUiRenderTargetInfo, ComputedUiTargetCamera, FocusPolicy, ScrollPosition,
    UiGlobalTransform, UiRect, UiScale, UiSystems, UiTransform, Val, ZIndex,
};

/// Used to select the orientation of a scrollbar, slider, or other oriented control.
// TODO: Move this to a more central place.
#[derive(Debug, Default, Clone, Copy, PartialEq, Reflect)]
#[reflect(PartialEq, Clone, Default)]
pub enum ControlOrientation {
    /// Horizontal orientation (stretching from left to right)
    Horizontal,
    /// Vertical orientation (stretching from top to bottom)
    #[default]
    Vertical,
}

/// An event which indicates that we want to scroll the specified item into view (adjusting
/// the scroll position of it's parent).
#[derive(Copy, Clone, Debug, PartialEq, EntityEvent)]
#[entity_event(propagate)]
pub struct ScrollIntoView {
    /// The activated entity.
    pub entity: Entity,
}

/// A headless scrollbar widget, which can be used to build custom scrollbars.
///
/// Scrollbars operate differently than the other UI widgets in a number of respects.
///
/// Unlike sliders, scrollbars don't have an [`AccessibilityNode`](bevy_a11y::AccessibilityNode)
/// component, nor can they have keyboard focus. This is because scrollbars are usually used in
/// conjunction with a scrollable container, which is itself accessible and focusable. This also
/// means that scrollbars don't accept keyboard events, which is also the responsibility of the
/// scrollable container.
///
/// Scrollbars don't emit notification events; instead they modify the scroll position of the target
/// entity directly.
///
/// A scrollbar can have any number of child entities, but one entity must be the scrollbar thumb,
/// which is marked with the [`ScrollbarThumb`] component. Other children are ignored. The core
/// scrollbar will directly update the position and size of this entity; the application is free to
/// set any other style properties as desired.
///
/// The application is free to position the scrollbars relative to the scrolling container however
/// it wants: it can overlay them on top of the scrolling content, or use a grid layout to displace
/// the content to make room for the scrollbars.
#[derive(Component, FromTemplate, Debug, Reflect, Clone, PartialEq)]
#[reflect(Component)]
pub struct Scrollbar {
    /// Entity being scrolled.
    pub target: Entity,
    /// Whether the scrollbar is vertical or horizontal.
    pub orientation: ControlOrientation,
    /// Minimum length of the scrollbar thumb, in pixel units, in the direction parallel to the main
    /// scrollbar axis. The scrollbar will resize the thumb entity based on the proportion of
    /// visible size to content size, but no smaller than this. This prevents the thumb from
    /// disappearing in cases where the ratio of content size to visible size is large.
    pub min_thumb_length: f32,
}

/// This component indicates that the entity is a scrollbar thumb (the moving, draggable part of
/// the scrollbar). This should be a child of the scrollbar entity.
///
/// A `ScrollbarThumb` UI node does not have a `Node` component. It only has `Border` and `BorderRadius` styling properties.
/// Its layout is handled after `ui_layout_system` in `update_scroll_thumb` so that its size and position can be set relative to the scrolling area's
/// size and scroll position.
#[derive(Component, Clone, Debug, Default)]
#[require(
    ScrollbarDragState,
    ComputedNode,
    ComputedUiTargetCamera,
    ComputedUiRenderTargetInfo,
    UiTransform,
    BackgroundColor,
    BorderColor,
    FocusPolicy::Block,
    Visibility,
    ZIndex
)]
#[derive(Reflect)]
#[reflect(Component)]
pub struct ScrollbarThumb {
    /// Border radius of the scrollbar thumb, used to update [`ComputedNode::border_radius`] in [`UiSystems::Layout`].
    pub border_radius: BorderRadius,
    /// Thickness of the thumb node's border.
    ///
    /// If the border is too large to fit inside the thumb node, the width of the border will be scaled to fit.
    pub border: UiRect,
}

impl Scrollbar {
    /// Construct a new scrollbar.
    ///
    /// # Arguments
    ///
    /// * `target` - The scrollable entity that this scrollbar will control.
    /// * `orientation` - The orientation of the scrollbar (horizontal or vertical).
    /// * `min_thumb_length` - The minimum size of the scrollbar's thumb, in pixels.
    pub fn new(target: Entity, orientation: ControlOrientation, min_thumb_length: f32) -> Self {
        Self {
            target,
            orientation,
            min_thumb_length,
        }
    }
}

/// Component used to manage the state of a scrollbar during dragging. This component is
/// inserted on the thumb entity.
#[derive(Component, Default, Reflect)]
#[reflect(Component, Default)]
pub struct ScrollbarDragState {
    /// Whether the scrollbar is currently being dragged.
    pub dragging: bool,
    /// The value of the scrollbar when dragging started.
    drag_origin: f32,
}

fn scrollbar_on_pointer_down(
    mut ev: On<Pointer<Press>>,
    q_thumb: Query<&ChildOf, With<ScrollbarThumb>>,
    mut q_scrollbar: Query<(
        &Scrollbar,
        &ComputedNode,
        &ComputedUiRenderTargetInfo,
        &UiGlobalTransform,
    )>,
    mut q_scroll_pos: Query<(&mut ScrollPosition, &ComputedNode), Without<Scrollbar>>,
    ui_scale: Res<UiScale>,
) {
    if q_thumb.contains(ev.entity) {
        // If they click on the thumb, do nothing. This will be handled by the drag event.
        ev.propagate(false);
    } else if let Ok((scrollbar, node, node_target, transform)) = q_scrollbar.get_mut(ev.entity) {
        // If they click on the scrollbar track, page up or down.
        ev.propagate(false);

        let Some(normalized_pos) = node.normalize_point(
            *transform,
            ev.event().pointer_location.position * node_target.scale_factor() / ui_scale.0,
        ) else {
            return;
        };

        // Bail if we don't find the target entity.
        let Ok((mut scroll_pos, scroll_content)) = q_scroll_pos.get_mut(scrollbar.target) else {
            return;
        };

        // Convert the click coordinates into a scroll position. If it's greater than the
        // current scroll position, scroll forward by one step (visible size) otherwise scroll
        // back.
        let visible_size = (scroll_content.size() - scroll_content.scrollbar_size)
            * scroll_content.inverse_scale_factor;
        let content_size = scroll_content.content_size() * scroll_content.inverse_scale_factor;
        let max_range = (content_size - visible_size).max(Vec2::ZERO);

        fn adjust_scroll_pos(scroll_pos: &mut f32, click_pos: f32, step: f32, range: f32) {
            *scroll_pos =
                (*scroll_pos + if click_pos > *scroll_pos { step } else { -step }).clamp(0., range);
        }

        match scrollbar.orientation {
            ControlOrientation::Horizontal => {
                let click_pos = (normalized_pos.x + 0.5) * content_size.x;
                adjust_scroll_pos(&mut scroll_pos.x, click_pos, visible_size.x, max_range.x);
            }
            ControlOrientation::Vertical => {
                let click_pos = (normalized_pos.y + 0.5) * content_size.y;
                adjust_scroll_pos(&mut scroll_pos.y, click_pos, visible_size.y, max_range.y);
            }
        }
    }
}

fn scrollbar_on_drag_start(
    mut ev: On<Pointer<DragStart>>,
    mut q_thumb: Query<(&ChildOf, &mut ScrollbarDragState), With<ScrollbarThumb>>,
    q_scrollbar: Query<&Scrollbar>,
    q_scroll_area: Query<&ScrollPosition>,
) {
    if let Ok((ChildOf(thumb_parent), mut drag)) = q_thumb.get_mut(ev.entity) {
        ev.propagate(false);
        if let Ok(scrollbar) = q_scrollbar.get(*thumb_parent)
            && let Ok(scroll_area) = q_scroll_area.get(scrollbar.target)
        {
            drag.dragging = true;
            drag.drag_origin = match scrollbar.orientation {
                ControlOrientation::Horizontal => scroll_area.x,
                ControlOrientation::Vertical => scroll_area.y,
            };
        }
    }
}

fn scrollbar_on_drag(
    mut ev: On<Pointer<Drag>>,
    mut q_thumb: Query<(&ChildOf, &mut ScrollbarDragState), With<ScrollbarThumb>>,
    mut q_scrollbar: Query<(&ComputedNode, &Scrollbar)>,
    mut q_scroll_pos: Query<(&mut ScrollPosition, &ComputedNode), Without<Scrollbar>>,
    ui_scale: Res<UiScale>,
) {
    if let Ok((ChildOf(thumb_parent), drag)) = q_thumb.get_mut(ev.entity)
        && let Ok((node, scrollbar)) = q_scrollbar.get_mut(*thumb_parent)
    {
        ev.propagate(false);
        let Ok((mut scroll_pos, scroll_content)) = q_scroll_pos.get_mut(scrollbar.target) else {
            return;
        };

        if drag.dragging {
            let distance = ev.event().distance / ui_scale.0;

            let visible_size = (scroll_content.size() - scroll_content.scrollbar_size)
                * scroll_content.inverse_scale_factor;
            let content_size = scroll_content.content_size() * scroll_content.inverse_scale_factor;

            let scrollbar_size = (node.size() * node.inverse_scale_factor).max(Vec2::ONE);

            match scrollbar.orientation {
                ControlOrientation::Horizontal => {
                    let range = (content_size.x - visible_size.x).max(0.);
                    scroll_pos.x = (drag.drag_origin
                        + (distance.x * content_size.x) / scrollbar_size.x)
                        .clamp(0., range);
                }
                ControlOrientation::Vertical => {
                    let range = (content_size.y - visible_size.y).max(0.);
                    scroll_pos.y = (drag.drag_origin
                        + (distance.y * content_size.y) / scrollbar_size.y)
                        .clamp(0., range);
                }
            };
        }
    }
}

fn scrollbar_on_drag_end(
    mut ev: On<Pointer<DragEnd>>,
    mut q_thumb: Query<&mut ScrollbarDragState, With<ScrollbarThumb>>,
) {
    if let Ok(mut drag) = q_thumb.get_mut(ev.entity) {
        ev.propagate(false);
        if drag.dragging {
            drag.dragging = false;
        }
    }
}

fn scrollbar_on_drag_cancel(
    mut ev: On<Pointer<Cancel>>,
    mut q_thumb: Query<&mut ScrollbarDragState, With<ScrollbarThumb>>,
) {
    if let Ok(mut drag) = q_thumb.get_mut(ev.entity) {
        ev.propagate(false);
        if drag.dragging {
            drag.dragging = false;
        }
    }
}

pub(crate) fn update_scrollbar_thumb(
    q_scroll_area: Query<(&ScrollPosition, &ComputedNode), Without<ScrollbarThumb>>,
    q_scrollbar: Query<
        (&Scrollbar, &ComputedNode, &UiGlobalTransform, &Children),
        Without<ScrollbarThumb>,
    >,
    mut q_thumb: Query<
        (
            &ScrollbarThumb,
            &UiTransform,
            &ComputedUiRenderTargetInfo,
            &mut ComputedNode,
            &mut UiGlobalTransform,
        ),
        With<ScrollbarThumb>,
    >,
) {
    for (scrollbar, scrollbar_node, scrollbar_transform, children) in q_scrollbar.iter() {
        let Ok(scroll_area) = q_scroll_area.get(scrollbar.target) else {
            continue;
        };

        // Size of the visible scrolling area.
        let visible_size = (scroll_area.1.size() - scroll_area.1.scrollbar_size)
            * scroll_area.1.inverse_scale_factor;

        // Size of the scrolling content.
        let content_size = scroll_area.1.content_size() * scroll_area.1.inverse_scale_factor;

        // Length of the scrollbar track.
        let track_length = scrollbar_node.size() * scrollbar_node.inverse_scale_factor;

        fn size_and_pos(
            content_size: f32,
            visible_size: f32,
            track_length: f32,
            min_size: f32,
            mut offset: f32,
        ) -> (f32, f32) {
            let thumb_size = if content_size > visible_size {
                (track_length * visible_size / content_size)
                    .max(min_size)
                    .min(track_length)
            } else {
                track_length
            };

            if content_size > visible_size {
                let max_offset = content_size - visible_size;

                // Clamp offset to prevent thumb from going out of bounds during inertial scroll
                offset = offset.clamp(0.0, max_offset);
            } else {
                offset = 0.0;
            }

            let thumb_pos = if content_size > visible_size {
                offset * (track_length - thumb_size) / (content_size - visible_size)
            } else {
                0.
            };

            (thumb_size, thumb_pos)
        }

        for child in children {
            let Ok((
                thumb,
                thumb_transform,
                target_info,
                mut thumb_node,
                mut thumb_global_transform,
            )) = q_thumb.get_mut(*child)
            else {
                continue;
            };

            let (thumb_logical_size, thumb_center) = match scrollbar.orientation {
                ControlOrientation::Horizontal => {
                    let (thumb_size, thumb_pos) = size_and_pos(
                        content_size.x,
                        visible_size.x,
                        track_length.x,
                        scrollbar.min_thumb_length,
                        scroll_area.0.x,
                    );
                    (
                        Vec2::new(thumb_size, track_length.y),
                        Vec2::new(thumb_pos + 0.5 * (thumb_size - track_length.x), 0.),
                    )
                }
                ControlOrientation::Vertical => {
                    let (thumb_size, thumb_pos) = size_and_pos(
                        content_size.y,
                        visible_size.y,
                        track_length.y,
                        scrollbar.min_thumb_length,
                        scroll_area.0.y,
                    );
                    (
                        Vec2::new(track_length.x, thumb_size),
                        Vec2::new(0., thumb_pos + 0.5 * (thumb_size - track_length.y)),
                    )
                }
            };

            let inverse_scale_factor = target_info.scale_factor().recip();
            let thumb_physical_size = thumb_logical_size * target_info.scale_factor();

            if thumb_node.size != thumb_physical_size
                || thumb_node.unrounded_size != thumb_physical_size
                || thumb_node.inverse_scale_factor != inverse_scale_factor
            {
                thumb_node.size = thumb_physical_size;
                thumb_node.unrounded_size = thumb_physical_size;
                thumb_node.inverse_scale_factor = inverse_scale_factor;
            }

            let border_radius = thumb.border_radius.resolve(
                target_info.scale_factor(),
                thumb_physical_size,
                target_info.physical_size().as_vec2(),
            );
            if thumb_node.border_radius != border_radius {
                thumb_node.border_radius = border_radius;
            }

            let resolve_border_val = |val: Val| {
                val.resolve(
                    target_info.scale_factor(),
                    thumb_physical_size.x,
                    target_info.physical_size().as_vec2(),
                )
                .unwrap_or(0.)
            };

            let mut resolved_border = BorderRect {
                min_inset: Vec2::new(
                    resolve_border_val(thumb.border.left),
                    resolve_border_val(thumb.border.top),
                ),
                max_inset: Vec2::new(
                    resolve_border_val(thumb.border.right),
                    resolve_border_val(thumb.border.bottom),
                ),
            };

            if thumb_node.size.x < resolved_border.min_inset.x + resolved_border.max_inset.x {
                let r =
                    thumb_node.size.x / (resolved_border.min_inset.x + resolved_border.max_inset.x);
                resolved_border.min_inset.x *= r;
                resolved_border.max_inset.x *= r;
            }

            if thumb_node.size.y < resolved_border.min_inset.y + resolved_border.max_inset.y {
                let r =
                    thumb_node.size.y / (resolved_border.min_inset.y + resolved_border.max_inset.y);
                resolved_border.min_inset.y *= r;
                resolved_border.max_inset.y *= r;
            }

            thumb_node.bypass_change_detection().border = resolved_border;

            let new_transform = scrollbar_transform.affine()
                * thumb_transform.compute_affine(
                    target_info.scale_factor(),
                    thumb_physical_size,
                    target_info.physical_size().as_vec2(),
                )
                * Affine2::from_translation(thumb_center * target_info.scale_factor());

            if thumb_global_transform.affine() != new_transform {
                *thumb_global_transform = new_transform.into();
            }
        }
    }
}

/// Plugin that adds the observers for the [`Scrollbar`] widget.
pub struct ScrollbarPlugin;

impl Plugin for ScrollbarPlugin {
    fn build(&self, app: &mut App) {
        app.add_observer(scrollbar_on_pointer_down)
            .add_observer(scrollbar_on_drag_start)
            .add_observer(scrollbar_on_drag_end)
            .add_observer(scrollbar_on_drag_cancel)
            .add_observer(scrollbar_on_drag)
            .add_systems(
                PostUpdate,
                update_scrollbar_thumb
                    .in_set(UiSystems::Layout)
                    .after(ui_layout_system),
            );
    }
}