bevy_pages 0.2.0

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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
use crate::element::{ElementProps, ElementWidget};
use crate::parser::color::parse_color;
use crate::parser::values::{parse_attribute, parse_bool, parse_float, parse_matches};
use crate::widgets::Widget;
use bevy::asset::AssetServer;
use bevy::color::Color;
use bevy::input::mouse::{MouseScrollUnit, MouseWheel};
use bevy::picking::hover::Hovered;
use bevy::prelude::*;
use bevy::ui_widgets::{ControlOrientation, Scrollbar, ScrollbarDragState, ScrollbarThumb};
use roxmltree::Node as XmlNode;

pub(crate) fn update_scroll_bounds(
    mut scroll_query: Query<(Entity, &Children, &mut ScrollViewState), With<ScrollViewArea>>,
    content_query: Query<&ComputedNode, With<ScrollViewContent>>,
    area_query: Query<&ComputedNode, With<ScrollViewArea>>,
) {
    for (area_entity, children, mut state) in &mut scroll_query {
        if let Ok(area_node) = area_query.get(area_entity) {
            state.viewport_size = area_node.size();
        }

        for child in children.iter() {
            if let Ok(content_node) = content_query.get(child) {
                state.content_size = content_node.size();
                break;
            }
        }
    }
}

pub(crate) fn scroll_view_mouse_wheel(
    mut mouse_wheel_events: MessageReader<MouseWheel>,
    mut scroll_query: Query<(Entity, &Interaction, &mut ScrollViewState), With<ScrollViewArea>>,
    parent_query: Query<(&ChildOf, Option<&Interaction>)>,
) {
    let mut total_delta = Vec2::ZERO;

    for event in mouse_wheel_events.read() {
        let delta = match event.unit {
            // Scales by typical line height in pixels ~24px
            MouseScrollUnit::Line => Vec2::new(event.x, event.y) * 24.0,
            MouseScrollUnit::Pixel => Vec2::new(event.x, event.y),
        };
        total_delta += delta;
    }

    if total_delta == Vec2::ZERO {
        return;
    }

    for (entity, interaction, mut state) in &mut scroll_query {
        // Check hover status on entire widget
        let is_hovered = *interaction == Interaction::Hovered
            || *interaction == Interaction::Pressed
            || parent_query
                .get(entity)
                .ok()
                .and_then(|(parent, _)| parent_query.get(parent.0).ok())
                .and_then(|(_, parent_interaction)| parent_interaction)
                .is_some_and(|i| *i == Interaction::Hovered || *i == Interaction::Pressed);

        if is_hovered {
            let max_scroll_x = (state.content_size.x - state.viewport_size.x).max(0.0);
            let max_scroll_y = (state.content_size.y - state.viewport_size.y).max(0.0);

            let scroll_step =
                Vec2::new(-total_delta.x, -total_delta.y) * (state.scroll_speed / 30.0);

            let new_x = state.target_offset.x + scroll_step.x;
            let new_y = state.target_offset.y + scroll_step.y;

            // Prevent clamping to zero if content size layout hasn't been computed yet
            state.target_offset.x = if max_scroll_x > 0.0 {
                new_x.clamp(0.0, max_scroll_x)
            } else {
                new_x.max(0.0)
            };

            state.target_offset.y = if max_scroll_y > 0.0 {
                new_y.clamp(0.0, max_scroll_y)
            } else {
                new_y.max(0.0)
            };
        }
    }
}

pub(crate) fn scroll_view_keyboard(
    keyboard_input: Res<ButtonInput<KeyCode>>,
    mut scroll_query: Query<(Entity, &Interaction, &mut ScrollViewState), With<ScrollViewArea>>,
    parent_query: Query<(&ChildOf, Option<&Interaction>)>,
) {
    for (entity, interaction, mut state) in &mut scroll_query {
        let is_hovered = *interaction == Interaction::Hovered
            || *interaction == Interaction::Pressed
            || parent_query
                .get(entity)
                .ok()
                .and_then(|(parent, _)| parent_query.get(parent.0).ok())
                .and_then(|(_, parent_interaction)| parent_interaction)
                .is_some_and(|i| *i == Interaction::Hovered || *i == Interaction::Pressed);

        if !is_hovered {
            continue;
        }

        let max_scroll_y = (state.content_size.y - state.viewport_size.y).max(0.0);

        let step = state.scroll_speed * 2.0;

        let page_step = if state.viewport_size.y > 0.0 {
            state.viewport_size.y * 0.8
        } else {
            100.0
        };

        let apply_clamp = |val: f32| -> f32 {
            if max_scroll_y > 0.0 {
                val.clamp(0.0, max_scroll_y)
            } else {
                val.max(0.0)
            }
        };

        if keyboard_input.just_pressed(KeyCode::ArrowUp) {
            state.target_offset.y = apply_clamp(state.target_offset.y - step);
        }

        if keyboard_input.just_pressed(KeyCode::ArrowDown) {
            state.target_offset.y = apply_clamp(state.target_offset.y + step);
        }

        if keyboard_input.just_pressed(KeyCode::PageUp) {
            state.target_offset.y = apply_clamp(state.target_offset.y - page_step);
        }

        if keyboard_input.just_pressed(KeyCode::PageDown) {
            state.target_offset.y = apply_clamp(state.target_offset.y + page_step);
        }

        if keyboard_input.just_pressed(KeyCode::Home) {
            state.target_offset.y = 0.0;
        }

        if keyboard_input.just_pressed(KeyCode::End) && max_scroll_y > 0.0 {
            state.target_offset.y = max_scroll_y;
        }
    }
}

pub(crate) fn apply_scroll_physics(
    time: Res<Time>,
    mut scroll_query: Query<(&mut ScrollViewState, &mut ScrollPosition), With<ScrollViewArea>>,
) {
    let delta_time = time.delta_secs();

    for (mut state, mut scroll_pos) in &mut scroll_query {
        let actual_pos = Vec2::new(scroll_pos.x, scroll_pos.y);

        // Detect direct updates from native scrollbar dragging
        if (actual_pos - state.current_offset).length_squared() > 0.001
            && (actual_pos - state.target_offset).length_squared() > 0.001
        {
            state.current_offset = actual_pos;
            state.target_offset = actual_pos;
        } else {
            // Apply LERP smoothing towards mouse/keyboard scroll target
            let decay = (1.0 - (-state.smoothing * delta_time).exp()).clamp(0.0, 1.0);
            state.current_offset = state.current_offset.lerp(state.target_offset, decay);

            if state.current_offset.distance(state.target_offset) < 0.05 {
                state.current_offset = state.target_offset;
            }

            scroll_pos.x = state.current_offset.x;
            scroll_pos.y = state.current_offset.y;
        }
    }
}

pub(crate) fn update_visuals(
    mut q_thumb: Query<
        (&mut BackgroundColor, &Hovered, Option<&ScrollbarDragState>),
        (
            With<ScrollViewThumb>,
            Or<(Changed<Hovered>, Changed<ScrollbarDragState>)>,
        ),
    >,
) {
    for (mut thumb_bg, Hovered(is_hovering), drag) in q_thumb.iter_mut() {
        let is_dragging = drag.is_some_and(|d| d.dragging);
        let color = if is_dragging {
            Color::srgb(0.9, 0.9, 0.9)
        } else if *is_hovering {
            Color::srgb(0.7, 0.7, 0.7)
        } else {
            Color::srgb(0.4, 0.4, 0.4)
        };

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

/// The direction of the scroll view.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
pub enum ScrollDirection {
    /// The view scrolls vertically.
    #[default]
    Vertical,
    /// The view scrolls horizontally.
    Horizontal,
    /// The view can be scrolled in both directions.
    Both,
}

impl ScrollDirection {
    /// Parses a scroll direction from a string.
    pub fn parse(s: &str) -> Result<Self, String> {
        parse_matches(
            s,
            &[
                ("vertical", || Ok(Self::Vertical)),
                ("horizontal", || Ok(Self::Horizontal)),
                ("both", || Ok(Self::Both)),
            ],
        )
    }

    /// Converts the scroll direction to bevy's [Overflow].
    pub fn to_overflow(self) -> Overflow {
        match self {
            Self::Vertical => Overflow {
                x: OverflowAxis::Clip,
                y: OverflowAxis::Scroll,
            },
            Self::Horizontal => Overflow {
                x: OverflowAxis::Scroll,
                y: OverflowAxis::Clip,
            },
            Self::Both => Overflow::scroll(),
        }
    }
}

/// Scroll view data attached to the scroll view root.
#[derive(Component, Debug, Clone, PartialEq)]
pub struct ScrollViewData {
    /// The scroll direction.
    pub direction: ScrollDirection,
    /// The scroll speed.
    pub scroll_speed: f32,
    /// Whether to use smooth scrolling.
    pub smooth: bool,
}

/// Scroll view state attached to [ScrollViewArea].
#[derive(Component, Debug, Clone, Reflect)]
#[reflect(Component)]
pub struct ScrollViewState {
    /// Current rendered scroll offset in pixels.
    pub current_offset: Vec2,
    /// Desired target offset (used for smooth LERP transitions).
    pub target_offset: Vec2,
    /// Viewport size in pixels.
    pub viewport_size: Vec2,
    /// Actual content size in pixels.
    pub content_size: Vec2,
    /// Scroll speed/sensitivity.
    pub scroll_speed: f32,
    /// Lerp factor for smooth scrolling (higher = snappier, lower = smoother).
    pub smoothing: f32,
}

impl Default for ScrollViewState {
    fn default() -> Self {
        Self {
            current_offset: Vec2::ZERO,
            target_offset: Vec2::ZERO,
            viewport_size: Vec2::ZERO,
            content_size: Vec2::ZERO,
            scroll_speed: 35.0,
            smoothing: 18.0,
        }
    }
}

/// A scroll view widget that allows users to scroll through overflowing content.
///
/// ## XML Usage
///
/// Build a scroll view using the `<ScrollView></ScrollView>` tag.
///
/// Insert as many children as you want.
///
/// ### Attributes
/// - `scroll-direction = "<vertical|horizontal|both>"`: The scroll direction. See [ScrollDirection].
/// - `scroll-speed = "<float>"`: The scroll speed.
/// - `color = "<color>"`: The background color of the scroll view container.
/// - `smooth = "<bool>"`: Whether to use smooth scrolling.
///
/// ## Logic
///
/// Use the [ScrollViewState] or the [ScrollViewData] components for custom logic.
/// You may also use element events to implement custom behavior.
#[derive(Clone, Debug, PartialEq)]
pub struct ScrollViewWidget {
    /// The direction of the scroll view.
    pub direction: ScrollDirection,
    /// The scroll speed.
    pub scroll_speed: f32,
    /// The background color of the scroll view container.
    pub bg_color: Option<Color>,
    /// Whether to use smooth scrolling.
    pub smooth: bool,
}

impl Default for ScrollViewWidget {
    fn default() -> Self {
        Self {
            direction: ScrollDirection::Vertical,
            scroll_speed: 30.0,
            bg_color: None,
            smooth: true,
        }
    }
}

impl Widget for ScrollViewWidget {
    fn spawn(&self, commands: &mut EntityCommands, _assets: &AssetServer) -> Entity {
        let direction = self.direction;
        let bg_color = self.bg_color.unwrap_or(Color::NONE);
        let scroll_speed = self.scroll_speed;

        commands.insert(ScrollViewData {
            direction: self.direction,
            scroll_speed: self.scroll_speed,
            smooth: self.smooth,
        });

        commands.insert(Node {
            display: Display::Grid,
            width: Val::Percent(100.0),
            height: Val::Percent(100.0),
            grid_template_columns: vec![
                RepeatedGridTrack::flex(1, 1.0),
                RepeatedGridTrack::auto(1),
            ],
            grid_template_rows: vec![RepeatedGridTrack::flex(1, 1.0), RepeatedGridTrack::auto(1)],
            row_gap: Val::Px(2.0),
            column_gap: Val::Px(2.0),
            ..default()
        });

        let mut content_entity = commands.id();

        commands.with_children(|parent| {
            // Spawn the clipping area container
            let scroll_area_id = parent
                .spawn((
                    Transform::default(),
                    GlobalTransform::default(),
                    ScrollViewArea,
                    Interaction::None, // Enables pointer hit testing on the viewport
                    ScrollViewState {
                        scroll_speed,
                        ..default()
                    },
                    Node {
                        display: Display::Flex,
                        flex_direction: FlexDirection::Column,
                        width: Val::Percent(100.0),
                        height: Val::Percent(100.0),
                        overflow: direction.to_overflow(),
                        grid_row: GridPlacement::start(1),
                        grid_column: GridPlacement::start(1),
                        ..default()
                    },
                    BackgroundColor(bg_color),
                    ScrollPosition::default(),
                ))
                .with_children(|area_parent| {
                    // Spawn internal content container and capture its ID
                    content_entity = area_parent
                        .spawn((
                            Transform::default(),
                            GlobalTransform::default(),
                            ScrollViewContent,
                            Node {
                                display: Display::Flex,
                                flex_direction: match direction {
                                    ScrollDirection::Horizontal => FlexDirection::Row,
                                    _ => FlexDirection::Column,
                                },
                                min_width: Val::Percent(100.0),
                                min_height: Val::Percent(100.0),
                                ..default()
                            },
                        ))
                        .id();
                })
                .id();

            if matches!(direction, ScrollDirection::Vertical | ScrollDirection::Both) {
                parent.spawn((
                    Transform::default(),
                    GlobalTransform::default(),
                    Node {
                        min_width: Val::Px(8.0),
                        grid_row: GridPlacement::start(1),
                        grid_column: GridPlacement::start(2),
                        ..default()
                    },
                    Scrollbar {
                        orientation: ControlOrientation::Vertical,
                        target: scroll_area_id,
                        min_thumb_length: 3.5,
                    },
                    Children::spawn(Spawn((
                        ScrollViewThumb,
                        Hovered::default(),
                        BackgroundColor(Color::srgb(0.4, 0.4, 0.4)),
                        BorderColor::all(Color::srgb(0.6, 0.6, 0.6)),
                        ScrollbarThumb {
                            border_radius: BorderRadius::all(Val::Px(4.0)),
                            border: UiRect::all(Val::Px(1.0)),
                        },
                    ))),
                ));
            }

            if matches!(
                direction,
                ScrollDirection::Horizontal | ScrollDirection::Both
            ) {
                parent.spawn((
                    Transform::default(),
                    GlobalTransform::default(),
                    Node {
                        min_height: Val::Px(8.0),
                        grid_row: GridPlacement::start(2),
                        grid_column: GridPlacement::start(1),
                        ..default()
                    },
                    Scrollbar {
                        orientation: ControlOrientation::Horizontal,
                        target: scroll_area_id,
                        min_thumb_length: 3.5,
                    },
                    Children::spawn(Spawn((
                        ScrollViewThumb,
                        Hovered::default(),
                        BackgroundColor(Color::srgb(0.4, 0.4, 0.4)),
                        BorderColor::all(Color::srgb(0.6, 0.6, 0.6)),
                        ScrollbarThumb {
                            border_radius: BorderRadius::all(Val::Px(4.0)),
                            border: UiRect::all(Val::Px(1.0)),
                        },
                    ))),
                ));
            }
        });

        content_entity
    }

    fn parse(
        node: &XmlNode,
        prefix: Option<&str>,
        base: Option<&ElementWidget>,
    ) -> Result<Self, String>
    where
        Self: Sized,
    {
        let base_sv = match base {
            Some(ElementWidget::ScrollView(sv)) => Some(sv),
            _ => None,
        };

        let direction = parse_attribute(node, "scroll-direction", prefix, ScrollDirection::parse)?
            .or_else(|| base_sv.map(|b| b.direction))
            .unwrap_or_default();

        let scroll_speed = parse_attribute(node, "scroll-speed", prefix, parse_float)?
            .or_else(|| base_sv.map(|b| b.scroll_speed))
            .unwrap_or(30.0);

        let bg_color = parse_attribute(node, "color", prefix, parse_color)?
            .or_else(|| base_sv.and_then(|b| b.bg_color));

        let smooth = parse_attribute(node, "smooth", prefix, parse_bool)?
            .or_else(|| base_sv.map(|b| b.smooth))
            .unwrap_or(true);

        Ok(Self {
            direction,
            scroll_speed,
            bg_color,
            smooth,
        })
    }

    fn apply_defaults(
        node: &XmlNode,
        default: &mut ElementProps,
        _: &mut ElementProps,
        _: &mut ElementProps,
    ) {
        if !node.has_attribute("width") {
            default.node.width = Val::Percent(100.0);
        }

        if !node.has_attribute("height") {
            default.node.height = Val::Px(200.0);
        }
    }
}

/// Marker component for the container holding the scrollable inner elements.
#[derive(Component, Debug, Default, Clone, Copy, Reflect)]
#[reflect(Component)]
pub struct ScrollViewContent;

/// Marker component for the scroll area container node.
#[derive(Component, Debug, Clone, Copy)]
pub struct ScrollViewArea;

/// Marker component identifying scrollbar thumb components.
#[derive(Component, Debug, Clone, Copy)]
pub struct ScrollViewThumb;