bevy_immediate 0.8.0

A simple, fast, and modular immediate mode UI library for 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
use bevy::color::Color;
use bevy::ecs::{
    component::Component,
    hierarchy::Children,
    lifecycle,
    observer::On,
    query::{Changed, Or, With},
    spawn::{Spawn, SpawnRelated},
    system::{Commands, Query, Res, SystemParam},
};
use bevy::input::{ButtonInput, keyboard::KeyCode};
use bevy::input_focus::InputDispatchPlugin;
use bevy::picking::{
    events::{Drag, DragStart, Pointer, Scroll},
    hover::Hovered,
};
use bevy::ui::{
    BackgroundColor, BorderRadius, ComputedNode, Display, FlexDirection, FlexWrap, GridPlacement,
    Node, Overflow, OverflowAxis, PositionType, RepeatedGridTrack, ScrollPosition, UiRect, UiScale,
    px,
};
use bevy::ui_widgets::{
    ControlOrientation, Scrollbar, ScrollbarDragState, ScrollbarPlugin, ScrollbarThumb,
};
use bevy::{math::Vec2, text::TextLayout, utils::default};
use bevy_immediate::{
    CapSet, Imm, ImmEntity,
    attach::{BevyImmediateAttachPlugin, ImmediateAttach},
    ui::text::ImmUiText,
};
use bevy_immediate_ui::{CapsUi, ImplCapsUi};

use crate::{bevy_scrollarea::colors::GRAY1, styles::title_text_style};

pub struct BevyScrollareaExamplePlugin;

impl bevy::app::Plugin for BevyScrollareaExamplePlugin {
    fn build(&self, app: &mut bevy::app::App) {
        // You will need bevy feature `experimental_bevy_ui_widgets`
        //
        // and bevy_immediate feature bevy_ui_widgets.
        //
        // As these plugins are added by other examples
        // additional checks are done to avoid bevy error about already added plugins
        //

        // For scrollbar support
        if !app.is_plugin_added::<ScrollbarPlugin>() {
            app.add_plugins(ScrollbarPlugin);
        }

        // For keyboard support
        if !app.is_plugin_added::<InputDispatchPlugin>() {
            app.add_plugins(InputDispatchPlugin);
        }

        // Initialize plugin with your root component
        app.add_plugins(BevyImmediateAttachPlugin::<CapsUi, BevyScrollareaExampleRoot>::new());

        app.add_systems(bevy::app::Update, update_scrollbar_style_on_drag);

        app.add_observer(
            |event: On<lifecycle::Add, MyScrollableNode>, mut commands: Commands| {
                commands
                    .entity(event.event().entity)
                    .insert(ScrollState::default())
                    .observe(scroll_on_mouse)
                    .observe(scroll_on_drag_start)
                    .observe(scroll_on_drag);
            },
        );
    }
}

// See bevy example `bevy/examples/ui/scrollbars.rs`
// https://github.com/bevyengine/bevy/tree/main/examples
// for more information

#[derive(Component)]
pub struct BevyScrollareaExampleRoot;

#[derive(SystemParam)]
pub struct Params {}

impl ImmediateAttach<CapsUi> for BevyScrollareaExampleRoot {
    type Params = Params;

    fn construct(ui: &mut Imm<CapsUi>, _params: &mut Params) {
        ui.ch()
            .on_spawn_insert(title_text_style)
            .on_spawn_text("Bevy scrollareas");
        ui.ch().on_spawn_text("Powered by bevy_ui_widgets");

        ui.ch().on_spawn_insert(|| Node {
            height: px(20.),
            ..default()
        });
        ui.ch()
            .on_spawn_insert(|| TextLayout {
                linebreak: bevy::text::LineBreak::WordBoundary,
                ..default()
            })
            .on_spawn_text(
                "Example showcases implementation of reusable scrollarea (scrollable, draggable):",
            );

        ui.ch()
            .on_spawn_insert(|| Node {
                display: Display::Grid,
                flex_wrap: FlexWrap::Wrap,
                grid_template_columns: vec![RepeatedGridTrack::fr(2, 1.)],
                grid_template_rows: vec![RepeatedGridTrack::fr(2, 1.)],
                column_gap: px(20.),
                row_gap: px(20.),

                min_height: px(200.),
                min_width: px(200.),

                max_height: px(600.),
                max_width: px(600.),

                ..default()
            })
            .add(|ui| {
                for (idx, overflow) in [
                    Overflow {
                        x: OverflowAxis::Scroll,
                        y: OverflowAxis::Scroll,
                    },
                    Overflow {
                        x: OverflowAxis::Scroll,
                        y: OverflowAxis::Clip,
                    },
                    Overflow {
                        x: OverflowAxis::Clip,
                        y: OverflowAxis::Scroll,
                    },
                    Overflow {
                        x: OverflowAxis::Clip,
                        y: OverflowAxis::Clip,
                    },
                ]
                .into_iter()
                .enumerate()
                {
                    ui.ch_id(("overflow", idx)).scrollarea(
                        Node {
                            min_height: px(50),
                            min_width: px(50),
                            // max_height: vh(20.),
                            // max_width: vw(20.),
                            ..default()
                        },
                        Node {
                            display: Display::Flex,
                            flex_direction: FlexDirection::Column,
                            padding: UiRect::all(px(4)),
                            overflow,
                            ..default()
                        },
                        |ui_entity| {
                            // Function gives partially initialized content entity
                            // Let's add background
                            ui_entity
                                .on_spawn_insert(|| BackgroundColor(GRAY1.into()))
                                .add(|ui| {
                                    let no_wrap = || TextLayout {
                                        linebreak: bevy::text::LineBreak::NoWrap,
                                        ..default()
                                    };

                                    ui.ch().on_spawn_text_fn(|| format!("{:?}", overflow));

                                    // And fill content
                                    for idx in 0..30 {
                                        ui.ch().on_spawn_insert(no_wrap).on_spawn_text_fn(|| {
                                            format!("{idx} Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.")
                                        });
                                    }
                                });
                        },
                    );
                }
            });
    }
}

pub trait ScrollBar<Caps: CapSet> {
    /// Content node must include overflow-axis logic
    ///
    /// Some node styles about how outer and content node will be placed will be overriden
    ///
    /// content node must set expected overflow axis
    fn scrollarea(
        self,
        outer_content_node: Node,
        content_node_style: Node,
        content: impl FnOnce(ImmEntity<'_, '_, '_, Caps>),
    ) -> Self;
}

impl<Caps> ScrollBar<Caps> for ImmEntity<'_, '_, '_, Caps>
where
    Caps: ImplCapsUi,
{
    fn scrollarea(
        self,
        outer_content_node: Node,
        content_node_style: Node,
        content: impl FnOnce(ImmEntity<'_, '_, '_, Caps>),
    ) -> Self {
        let grid_template = |scrollbar: bool| {
            if scrollbar {
                vec![RepeatedGridTrack::flex(1, 1.), RepeatedGridTrack::auto(1)]
            } else {
                vec![RepeatedGridTrack::flex(1, 1.)]
            }
        };

        let horizontal = content_node_style.overflow.x == OverflowAxis::Scroll;
        let vertical = content_node_style.overflow.y == OverflowAxis::Scroll;

        self.on_spawn_insert(|| {
            Node {
                display: Display::Grid,
                grid_template_columns: grid_template(horizontal),
                grid_template_rows: grid_template(vertical),

                // Use all remaining values from user provided style
                ..outer_content_node
            }
        })
        .add(|ui| {
            let scrollarea_content = ui.ch().on_spawn_insert(|| {
                (
                    content_node_style,
                    ScrollPosition(Vec2::ZERO),
                    // Currently logic to scroll content
                    // by dragging content or by scrolling needs custom implementation
                    MyScrollableNode,
                )
            });

            // Store entity for scrollable content area
            let scrollbar_target = scrollarea_content.entity();

            // Finalize construction of scrollarea entity
            content(scrollarea_content);

            if vertical {
                // Vertical scrollbar
                ui.ch().on_spawn_insert(|| {
                    (
                        Node {
                            width: px(8),
                            grid_row: GridPlacement::start(1),
                            grid_column: GridPlacement::start(2),
                            ..default()
                        },
                        Scrollbar {
                            orientation: ControlOrientation::Vertical,
                            target: scrollbar_target,
                            min_thumb_length: 8.0,
                        },
                        Children::spawn(Spawn((
                            Node {
                                position_type: PositionType::Absolute,
                                ..default()
                            },
                            Hovered::default(),
                            BackgroundColor(colors::GRAY2.into()),
                            ScrollbarThumb {
                                border_radius: BorderRadius::all(px(4)),
                                ..default()
                            },
                        ))),
                    )
                });
            }

            if horizontal {
                // Horizontal scrollbar
                ui.ch().on_spawn_insert(|| {
                    (
                        Node {
                            min_height: px(8),
                            grid_row: GridPlacement::start(2),
                            grid_column: GridPlacement::start(1),
                            ..default()
                        },
                        Scrollbar {
                            orientation: ControlOrientation::Horizontal,
                            target: scrollbar_target,
                            min_thumb_length: 8.0,
                        },
                        Children::spawn(Spawn((
                            Node {
                                position_type: PositionType::Absolute,
                                border_radius: BorderRadius::all(px(4)),
                                ..default()
                            },
                            Hovered::default(),
                            BackgroundColor(colors::GRAY2.into()),
                            ScrollbarThumb {
                                border_radius: BorderRadius::all(px(4)),
                                ..default()
                            },
                        ))),
                    )
                });
            }
        })
    }
}

#[derive(Component)]
struct MyScrollableNode;

#[derive(Component, Default)]
struct ScrollState {
    initial_pos: Vec2,
}

fn scroll_on_mouse(
    scroll: On<Pointer<Scroll>>,
    mut scroll_position_query: Query<(&mut ScrollPosition, &ComputedNode), With<MyScrollableNode>>,
    keyboard_input: Res<ButtonInput<KeyCode>>,
) {
    if let Ok((mut scroll_position, node)) = scroll_position_query.get_mut(scroll.entity) {
        let visible_size = node.size() * node.inverse_scale_factor;
        let content_size = node.content_size() * node.inverse_scale_factor;
        let max_range = (content_size - visible_size).max(Vec2::ZERO);

        let mut delta = Vec2::new(scroll.x, scroll.y);

        if keyboard_input.any_pressed([KeyCode::ControlLeft, KeyCode::ControlRight]) {
            std::mem::swap(&mut delta.x, &mut delta.y);
        }

        let inverse_scale_factor: f32 = node.inverse_scale_factor;

        match scroll.unit {
            bevy::input::mouse::MouseScrollUnit::Line => {
                delta *= 28.;
            }
            bevy::input::mouse::MouseScrollUnit::Pixel => {
                delta *= 1.0 / inverse_scale_factor;
            }
        }

        scroll_position.0 = (scroll_position.0 - delta).min(max_range).max(Vec2::ZERO);
    }
}

fn scroll_on_drag_start(
    mut drag_start: On<Pointer<DragStart>>,
    mut scroll_position_query: Query<(&ComputedNode, &mut ScrollState), With<MyScrollableNode>>,
) {
    if let Ok((computed_node, mut state)) = scroll_position_query.get_mut(drag_start.entity) {
        drag_start.propagate(false);
        state.initial_pos = computed_node.scroll_position;
    }
}

fn scroll_on_drag(
    mut drag: On<Pointer<Drag>>,
    ui_scale: Res<UiScale>,
    mut scroll_position_query: Query<
        (&mut ScrollPosition, &ComputedNode, &ScrollState),
        With<MyScrollableNode>,
    >,
) {
    if let Ok((mut scroll_position, comp_node, state)) = scroll_position_query.get_mut(drag.entity)
    {
        let visible_size = comp_node.size();
        let content_size = comp_node.content_size();

        drag.propagate(false);

        let max_range = (content_size - visible_size).max(Vec2::ZERO);

        // Convert from screen coordinates to UI coordinates then back to physical coordinates
        let distance = drag.distance / (comp_node.inverse_scale_factor * ui_scale.0);

        scroll_position.0 = ((state.initial_pos - distance)
            .min(max_range)
            .max(Vec2::ZERO))
            * comp_node.inverse_scale_factor;
    }
}

// Update the color of the scrollbar thumb.
#[allow(clippy::type_complexity)]
fn update_scrollbar_style_on_drag(
    mut q_thumb: Query<
        (&mut BackgroundColor, &Hovered, &ScrollbarDragState),
        (
            With<ScrollbarThumb>,
            Or<(Changed<Hovered>, Changed<ScrollbarDragState>)>,
        ),
    >,
) {
    for (mut thumb_bg, Hovered(is_hovering), drag) in q_thumb.iter_mut() {
        let color: Color = if *is_hovering || drag.dragging {
            colors::GRAY3
        } else {
            colors::GRAY2
        }
        .into();

        if thumb_bg.0 != color {
            thumb_bg.0 = color;
        }
    }
}

mod colors {
    use bevy::color::Srgba;

    pub const GRAY1: Srgba = Srgba::new(0.224, 0.224, 0.243, 1.0);
    pub const GRAY2: Srgba = Srgba::new(0.486, 0.486, 0.529, 1.0);
    pub const GRAY3: Srgba = Srgba::new(1.0, 1.0, 1.0, 1.0);
}