masonry 0.5.0

Traits and types of the Masonry toolkit.
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
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
// Copyright 2022 the Xilem Authors
// SPDX-License-Identifier: Apache-2.0

use std::any::TypeId;

use accesskit::{Node, Role};
use include_doc_path::include_doc_path;
use tracing::{Span, trace_span};

use crate::core::keyboard::{Key, KeyState, NamedKey};
use crate::core::{
    AccessCtx, AccessEvent, AllowRawMut, ChildrenIds, EventCtx, LayoutCtx, MeasureCtx, NoAction,
    PaintCtx, PointerButtonEvent, PointerEvent, PointerUpdate, PropertiesMut, PropertiesRef,
    Property, RegisterCtx, TextEvent, UpdateCtx, UsesProperty, Widget, WidgetId, WidgetMut,
};
use crate::imaging::{Composite, GroupRef, Painter};
use crate::kurbo::{Axis, Point, Rect, Size, Stroke};
use crate::layout::{AsUnit, LenReq, Length};
use crate::properties::Collapsible;
use crate::properties::types::AnimatedF32;
use crate::theme;

// TODO
// - Rename cursor to oval/rect/bar/grabber/grabbybar
// - Rename progress to something more descriptive
// - Document names
// - Document invariants

/// A scrollbar.
///
#[doc = concat!(
    "![Vertical scrollbar](",
    include_doc_path!("screenshots/scrollbar_default.png"),
    ")",
)]
/// This widget does not directly scroll any content. Instead, it exposes its position via
/// [`cursor_progress`](Self::cursor_progress) and sets `moved` to `true` whenever user input changes
/// that position. A parent scroll container (such as [`Portal`](crate::widgets::Portal)) is expected
/// to observe `moved` and update its viewport accordingly.
///
/// ## Keyboard and accessibility
///
/// Scrollbars are focusable and support basic keyboard navigation (arrow keys, PageUp/Down,
/// Home/End depending on axis), and expose scroll state in the accessibility tree.
pub struct ScrollBar {
    axis: Axis,
    pub(crate) cursor_progress: f64,
    pub(crate) moved: bool,
    pub(crate) portal_size: f64,
    pub(crate) content_size: f64,
    pub(crate) opacity: AnimatedF32,
    grab_anchor: Option<f64>,
}

// --- MARK: BUILDERS
impl ScrollBar {
    /// Creates a new scrollbar.
    ///
    /// - `portal_size`: Size of the scrolling container in the relevant axis.
    /// - `content_size`: Size of the child in the relevant axis. Usually exceeds `portal_size` in cases where the scrollbar is visible.
    pub fn new(axis: Axis, portal_size: f64, content_size: f64) -> Self {
        Self {
            axis,
            cursor_progress: 0.0,
            moved: false,
            portal_size,
            content_size,
            opacity: AnimatedF32::stable(1.),
            grab_anchor: None,
        }
    }
}

// --- MARK: METHODS
impl ScrollBar {
    /// Returns how far the scrollbar is from its initial point.
    ///
    /// Values range from 0.0 (beginning) to 1.0 (end).
    pub fn cursor_progress(&self) -> f64 {
        self.cursor_progress
    }

    /// Returns `(cursor_length, empty_space_length)`.
    ///
    /// `cursor_Length` is guaranteed to be at least `min_length`
    /// and the remainder of the layout length is `empty_space_length`.
    fn lengths(&self, layout_size: Size, min_length: f64) -> (f64, f64) {
        let size_ratio = if self.content_size != 0. {
            self.portal_size / self.content_size
        } else {
            1.
        };
        let size_ratio = size_ratio.clamp(0.0, 1.0);

        let cursor_length = (size_ratio * layout_size.get_coord(self.axis)).max(min_length);
        let empty_space_length = layout_size.get_coord(self.axis) - cursor_length;

        (cursor_length, empty_space_length)
    }

    fn cursor_rect(&self, layout_size: Size, min_length: f64) -> Rect {
        // TODO - handle invalid sizes
        let (cursor_length, empty_space_length) = self.lengths(layout_size, min_length);

        let cursor_pos_major = self.cursor_progress * empty_space_length;
        let cursor_pos = self.axis.pack_point(cursor_pos_major, 0.0);
        let cursor_size_minor = layout_size.get_coord(self.axis.cross());
        let cursor_size = self.axis.pack_size(cursor_length, cursor_size_minor);

        Rect::from_origin_size(cursor_pos, cursor_size)
    }

    fn progress_from_mouse_pos(
        &self,
        layout_size: Size,
        min_length: f64,
        anchor: f64,
        mouse_pos: Point,
    ) -> f64 {
        // TODO - handle invalid sizes
        let (cursor_length, empty_space_length) = self.lengths(layout_size, min_length);

        let new_cursor_pos_major = mouse_pos.get_coord(self.axis) - anchor * cursor_length;
        let new_cursor_progress = new_cursor_pos_major / empty_space_length;

        new_cursor_progress.clamp(0.0, 1.0)
    }

    fn scroll_range(&self) -> f64 {
        (self.content_size - self.portal_size).max(0.0)
    }

    fn set_cursor_progress(&mut self, new_progress: f64) -> bool {
        let new_progress = new_progress.clamp(0.0, 1.0);
        if (new_progress - self.cursor_progress).abs() > 1e-12 {
            self.cursor_progress = new_progress;
            self.moved = true;
            true
        } else {
            false
        }
    }

    fn adjust_by_pixels(&mut self, delta_pixels: f64) -> bool {
        let scroll_range = self.scroll_range();
        if scroll_range <= 1e-12 {
            return false;
        }
        // Translate from a pixel delta in content space to a normalized cursor progress delta.
        self.set_cursor_progress(self.cursor_progress + delta_pixels / scroll_range)
    }
}

// --- MARK: WIDGETMUT
impl ScrollBar {
    /// Updates the sizes of the widgets being represented by the scrollbar.
    /// - `portal_size`: Size of the scrolling container in the relevant axis.
    /// - `content_size`: Size of the child in the relevant axis. Usually exceeds `portal_size` in cases where the scrollbar is visible.
    // TODO - Remove?
    pub fn set_sizes(this: &mut WidgetMut<'_, Self>, portal_size: f64, content_size: f64) {
        this.widget.portal_size = portal_size;
        this.widget.content_size = content_size;
        this.ctx.request_render();
    }

    /// Updates the size of the child widget being represented by the scrollbar.
    // TODO - Remove?
    pub fn set_content_size(this: &mut WidgetMut<'_, Self>, content_size: f64) {
        // TODO - cursor_progress
        this.widget.content_size = content_size;
        this.ctx.request_render();
    }
}

impl UsesProperty<Collapsible> for ScrollBar {}

// --- MARK: IMPL WIDGET
impl Widget for ScrollBar {
    type Action = NoAction;

    fn on_pointer_event(
        &mut self,
        ctx: &mut EventCtx<'_>,
        _props: &mut PropertiesMut<'_>,
        event: &PointerEvent,
    ) {
        match event {
            PointerEvent::Down(PointerButtonEvent { state, .. }) => {
                ctx.capture_pointer();

                let size = ctx.content_box().size();
                let cursor_min_length = theme::SCROLLBAR_MIN_SIZE;
                let cursor_rect = self.cursor_rect(size, cursor_min_length);
                let mouse_pos = ctx.local_position(state.position);
                let mut changed = false;
                if cursor_rect.contains(mouse_pos) {
                    let (c0, c1) = cursor_rect.get_coords(self.axis);
                    let mouse_major = mouse_pos.get_coord(self.axis);
                    self.grab_anchor = Some((mouse_major - c0) / (c1 - c0));
                } else {
                    let progress =
                        self.progress_from_mouse_pos(size, cursor_min_length, 0.5, mouse_pos);
                    changed |= self.set_cursor_progress(progress);
                    self.grab_anchor = Some(0.5);
                };
                if changed {
                    ctx.request_render();
                }
            }
            PointerEvent::Move(PointerUpdate { current, .. }) => {
                if ctx.is_active()
                    && let Some(grab_anchor) = self.grab_anchor
                {
                    let size = ctx.content_box().size();
                    let cursor_min_length = theme::SCROLLBAR_MIN_SIZE;
                    let progress = self.progress_from_mouse_pos(
                        size,
                        cursor_min_length,
                        grab_anchor,
                        ctx.local_position(current.position),
                    );
                    if self.set_cursor_progress(progress) {
                        ctx.request_render();
                    }
                }
            }
            PointerEvent::Up(..) | PointerEvent::Cancel(..) => {
                self.grab_anchor = None;
            }
            _ => {}
        }
    }

    fn on_text_event(
        &mut self,
        ctx: &mut EventCtx<'_>,
        _props: &mut PropertiesMut<'_>,
        event: &TextEvent,
    ) {
        let TextEvent::Keyboard(event) = event else {
            return;
        };
        if event.state != KeyState::Down {
            return;
        }
        let line = 120.0;
        let page = self.portal_size;

        let mut changed = false;
        match (&event.key, self.axis) {
            (Key::Named(NamedKey::ArrowUp), Axis::Vertical) => {
                changed |= self.adjust_by_pixels(-line);
            }
            (Key::Named(NamedKey::ArrowDown), Axis::Vertical) => {
                changed |= self.adjust_by_pixels(line);
            }
            (Key::Named(NamedKey::PageUp), Axis::Vertical) => {
                changed |= self.adjust_by_pixels(-page);
            }
            (Key::Named(NamedKey::PageDown), Axis::Vertical) => {
                changed |= self.adjust_by_pixels(page);
            }
            (Key::Named(NamedKey::Home), Axis::Vertical) => {
                changed |= self.set_cursor_progress(0.0);
            }
            (Key::Named(NamedKey::End), Axis::Vertical) => changed |= self.set_cursor_progress(1.0),
            (Key::Named(NamedKey::ArrowLeft), Axis::Horizontal) => {
                changed |= self.adjust_by_pixels(-line);
            }
            (Key::Named(NamedKey::ArrowRight), Axis::Horizontal) => {
                changed |= self.adjust_by_pixels(line);
            }
            (Key::Named(NamedKey::Home), Axis::Horizontal) => {
                changed |= self.set_cursor_progress(0.0);
            }
            (Key::Named(NamedKey::End), Axis::Horizontal) => {
                changed |= self.set_cursor_progress(1.0);
            }
            _ => {}
        }

        if changed {
            ctx.request_render();
        }
    }

    fn on_access_event(
        &mut self,
        ctx: &mut EventCtx<'_>,
        _props: &mut PropertiesMut<'_>,
        event: &AccessEvent,
    ) {
        if !matches!(
            event.action,
            accesskit::Action::ScrollUp
                | accesskit::Action::ScrollDown
                | accesskit::Action::ScrollLeft
                | accesskit::Action::ScrollRight
        ) {
            return;
        }

        let action_matches_axis = matches!(
            (event.action, self.axis),
            (
                accesskit::Action::ScrollUp | accesskit::Action::ScrollDown,
                Axis::Vertical
            ) | (
                accesskit::Action::ScrollLeft | accesskit::Action::ScrollRight,
                Axis::Horizontal
            )
        );
        if !action_matches_axis {
            return;
        }
        let unit = if let Some(accesskit::ActionData::ScrollUnit(unit)) = &event.data {
            *unit
        } else {
            accesskit::ScrollUnit::Item
        };
        let line = 120.0;
        let page = self.portal_size;
        let amount = match unit {
            accesskit::ScrollUnit::Item => line,
            accesskit::ScrollUnit::Page => page,
        };
        let signed = match event.action {
            accesskit::Action::ScrollUp | accesskit::Action::ScrollLeft => -amount,
            accesskit::Action::ScrollDown | accesskit::Action::ScrollRight => amount,
            _ => 0.0,
        };

        if self.adjust_by_pixels(signed) {
            ctx.request_render();
        }
    }

    fn on_anim_frame(
        &mut self,
        ctx: &mut UpdateCtx<'_>,
        props: &mut PropertiesMut<'_>,
        interval: u64,
    ) {
        let cache = ctx.property_cache();
        let collapsible = props.get::<Collapsible>(cache).0;

        if !collapsible {
            self.opacity.move_to(1., 0.);
            ctx.request_paint_only();
            return;
        }

        let millis = (interval as f64 * 1e-6) as f32;
        let result = self.opacity.advance(millis);
        ctx.request_paint_only();

        if !result.is_completed() {
            ctx.request_anim_frame();
        }
    }

    fn register_children(&mut self, _ctx: &mut RegisterCtx<'_>) {}

    fn property_changed(&mut self, ctx: &mut UpdateCtx<'_>, property_type: TypeId) {
        if Collapsible::matches(property_type) {
            ctx.request_paint_only();
        }
    }

    fn measure(
        &mut self,
        _ctx: &mut MeasureCtx<'_>,
        _props: &PropertiesRef<'_>,
        axis: Axis,
        len_req: LenReq,
        _cross_length: Option<Length>,
    ) -> Length {
        if axis == self.axis {
            // TODO: Consider .max(theme::SCROLLBAR_MIN_SIZE)
            match len_req {
                LenReq::MinContent | LenReq::MaxContent => self.portal_size.px(),
                LenReq::FitContent(space) => space,
            }
        } else {
            let scrollbar_width = theme::SCROLLBAR_WIDTH;
            let cursor_padding = theme::SCROLLBAR_PAD;

            (scrollbar_width + cursor_padding * 2.0).px()
        }
    }

    fn layout(&mut self, _ctx: &mut LayoutCtx<'_>, _props: &PropertiesRef<'_>, _size: Size) {}

    fn paint(
        &mut self,
        ctx: &mut PaintCtx<'_>,
        props: &PropertiesRef<'_>,
        painter: &mut Painter<'_>,
    ) {
        let cache = ctx.property_cache();
        let collapsible = props.get::<Collapsible>(cache).0;

        if self.opacity.value() != 1. {
            painter.push_fill_clip(ctx.border_box());
            painter.push_group(GroupRef::new().with_composite(Composite::new(
                crate::peniko::BlendMode::default(),
                self.opacity.value(),
            )));
        }

        let radius = theme::SCROLLBAR_RADIUS;
        let edge_width = theme::SCROLLBAR_EDGE_WIDTH;
        let cursor_padding = theme::SCROLLBAR_PAD;
        let cursor_min_length = theme::SCROLLBAR_MIN_SIZE;
        let scrollbar_width = theme::SCROLLBAR_WIDTH;

        let size = ctx.content_box().size();
        let inset_start = if !collapsible || ctx.is_hovered() || self.grab_anchor.is_some() {
            cursor_padding
        } else {
            cursor_padding + scrollbar_width / 2.
        };
        let (inset_x0, inset_y0) = self.axis.pack_xy(0.0, inset_start);
        let (inset_x1, inset_y1) = self.axis.pack_xy(0.0, cursor_padding);
        let cursor_rect = self
            .cursor_rect(size, cursor_min_length)
            .inset((-inset_x0, -inset_y0, -inset_x1, -inset_y1))
            .to_rounded_rect(radius);

        painter.fill(cursor_rect, theme::SCROLLBAR_COLOR).draw();
        painter
            .stroke(
                cursor_rect,
                &Stroke::new(edge_width),
                theme::SCROLLBAR_BORDER_COLOR,
            )
            .draw();

        if self.opacity.value() != 1. {
            painter.pop_group();
            painter.pop_clip();
        }
    }

    fn accessibility_role(&self) -> Role {
        Role::ScrollBar
    }

    fn accessibility(
        &mut self,
        _ctx: &mut AccessCtx<'_>,
        _props: &PropertiesRef<'_>,
        node: &mut Node,
    ) {
        node.set_orientation(match self.axis {
            Axis::Horizontal => accesskit::Orientation::Horizontal,
            Axis::Vertical => accesskit::Orientation::Vertical,
        });

        let scroll_range = self.scroll_range();

        let value = (self.cursor_progress.clamp(0.0, 1.0)) * scroll_range;
        match self.axis {
            Axis::Horizontal => {
                node.set_scroll_x_min(0.0);
                node.set_scroll_x_max(scroll_range);
                node.set_scroll_x(value);
                if self.cursor_progress > 1e-12 {
                    node.add_action(accesskit::Action::ScrollLeft);
                }
                if self.cursor_progress + 1e-12 < 1.0 {
                    node.add_action(accesskit::Action::ScrollRight);
                }
            }
            Axis::Vertical => {
                node.set_scroll_y_min(0.0);
                node.set_scroll_y_max(scroll_range);
                node.set_scroll_y(value);
                if self.cursor_progress > 1e-12 {
                    node.add_action(accesskit::Action::ScrollUp);
                }
                if self.cursor_progress + 1e-12 < 1.0 {
                    node.add_action(accesskit::Action::ScrollDown);
                }
            }
        }
    }

    fn children_ids(&self) -> ChildrenIds {
        ChildrenIds::new()
    }

    fn make_trace_span(&self, id: WidgetId) -> Span {
        trace_span!("ScrollBar", id = id.trace())
    }

    fn accepts_focus(&self) -> bool {
        true
    }
}

impl AllowRawMut for ScrollBar {}

// --- MARK: TESTS
#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::keyboard::{Key, NamedKey};
    use crate::core::{NewWidget, TextEvent};
    use crate::properties::Dimensions;
    use crate::testing::{TestHarness, assert_render_snapshot};
    use crate::theme::test_property_set;

    #[test]
    fn simple_scrollbar() {
        let widget = NewWidget::new(ScrollBar::new(Axis::Vertical, 200.0, 600.0))
            .with_props(Dimensions::FIT);

        let mut harness = TestHarness::create_with_size(test_property_set(), widget, (50, 200));
        let scrollbar_tag = harness.root_tag();

        assert_render_snapshot!(harness, "scrollbar_default");

        assert!(harness.pop_action_erased().is_none());

        harness.mouse_click_on(scrollbar_tag, None);
        // TODO - Scroll action?
        assert!(harness.pop_action_erased().is_none());

        assert_render_snapshot!(harness, "scrollbar_middle");

        harness.mouse_button_press(None);
        harness.mouse_move(Point::new(30.0, 150.0));

        assert_render_snapshot!(harness, "scrollbar_down");

        harness.mouse_move(Point::new(30.0, 300.0));
        assert_render_snapshot!(harness, "scrollbar_bottom");
    }

    #[test]
    fn collapsible_scrollbar() {
        let widget = NewWidget::new(ScrollBar::new(Axis::Vertical, 200.0, 600.0))
            .with_props(Collapsible(true))
            .with_props(Dimensions::FIT);

        let mut harness = TestHarness::create_with_size(test_property_set(), widget, (20, 200));

        assert_render_snapshot!(harness, "scrollbar_collapsed");
    }

    #[test]
    fn horizontal_scrollbar() {
        let widget = NewWidget::new(ScrollBar::new(Axis::Horizontal, 200.0, 600.0))
            .with_props(Dimensions::FIT);

        let mut harness = TestHarness::create_with_size(test_property_set(), widget, (200, 50));
        let scrollbar_tag = harness.root_tag();

        assert_render_snapshot!(harness, "scrollbar_horizontal");

        assert!(harness.pop_action_erased().is_none());

        harness.mouse_click_on(scrollbar_tag, None);
        // TODO - Scroll action?
        assert!(harness.pop_action_erased().is_none());

        assert_render_snapshot!(harness, "scrollbar_horizontal_middle");
    }

    #[test]
    fn keyboard_scroll_updates_access_tree() {
        let widget = NewWidget::new(ScrollBar::new(Axis::Vertical, 200.0, 600.0))
            .with_props(Dimensions::FIT);
        let mut harness = TestHarness::create_with_size(test_property_set(), widget, (50, 200));
        let _ = harness.render();

        let scrollbar_tag = harness.root_tag();
        harness.focus_on(scrollbar_tag);

        harness.process_text_event(TextEvent::key_down(Key::Named(NamedKey::ArrowDown)));
        let _ = harness.render();

        let node = harness.access_node(scrollbar_tag).unwrap();
        assert!(node.data().scroll_y().unwrap_or(0.0) > 0.0);
    }

    // TODO - Add "portal larger than content" test

    // TODO - Add WidgetMut tests
}