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
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
//! [`SingleChildScrollView`]: a vertically scrollable container.
//!
//! It occupies a fixed-size viewport; its single child is laid out at free height by
//! the driver, then clipped to the viewport and translated by the scroll offset, which
//! the runtime retains, keyed by identity.
use frus_core::{Insets, Rect, Scene};
use frus_layout::{Dimension, Style};
use crate::interaction::Status;
use crate::physics::ScrollPhysics;
use crate::theme::Theme;
use crate::widget::Widget;
/// A [`SingleChildScrollView`]'s scrolling axis, or axes.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum Axis {
/// Up and down.
Vertical,
/// Left and right.
Horizontal,
/// Both, which is a **convenience** rather than a third kind of area: a scrollable
/// elsewhere has one axis and one only, and two of them means one nested inside the
/// other. This is that pair collapsed into a single node, and a gesture reads it as
/// the pair: one drag moves one axis, decided by the direction the finger went in and
/// held to the end of the gesture. A page that scrolls down does not drift sideways
/// while it does it.
Both,
}
impl Axis {
pub(crate) fn free_x(self) -> bool {
matches!(self, Axis::Horizontal | Axis::Both)
}
pub(crate) fn free_y(self) -> bool {
matches!(self, Axis::Vertical | Axis::Both)
}
}
/// A scrollable container.
pub struct SingleChildScrollView<Msg = crate::callback::Callback> {
width: Dimension,
height: Dimension,
/// Was the width **set** explicitly? If not, in flex mode the width must not
/// serve as a basis; see [`SingleChildScrollView::style`].
width_explicit: bool,
/// Was the height **set** explicitly? The same question for the vertical axis.
height_explicit: bool,
flex_grow: f32,
axis: Axis,
/// Edge and fling behaviour, when this area wants one of its own; `None`
/// follows the application, which follows the platform.
physics: Option<ScrollPhysics>,
/// Whether this area draws a scrollbar, when it wants its own answer; `None`
/// follows the application, which follows the platform.
scrollbars: Option<crate::physics::Scrollbars>,
/// Whether the bar stays put instead of fading; `None` lets it fade.
thumb_visibility: Option<bool>,
reverse: bool,
/// Room around the content, inside the viewport; see [`SingleChildScrollView::padding`].
padding: Insets,
/// Told where this area is whenever it moves; see [`SingleChildScrollView::on_scroll`].
on_scroll: Option<Box<dyn Fn(crate::ScrollPosition) -> Msg>>,
/// How far it must move before it says so again; see
/// [`SingleChildScrollView::notify_every`].
grain: f32,
content: Vec<Box<dyn Widget<Msg>>>,
}
impl<Msg> SingleChildScrollView<Msg> {
/// Creates a scrollable area.
///
/// Unsized, it is sized as the reference's is (milestone 590): along the axis it
/// scrolls, **as big as its content, up to the room on offer**, and scrolling past
/// that; across it, all the room on offer. In a page's body that is the whole body;
/// in a column beside other children, whose length is not the viewport's to take, it
/// is as long as its content, and [`flex`](Self::flex) gives it the rest of the column.
pub fn new() -> Self {
Self {
width: Dimension::Auto,
height: Dimension::Auto,
width_explicit: false,
height_explicit: false,
flex_grow: 0.0,
axis: Axis::Vertical,
physics: None,
scrollbars: None,
thumb_visibility: None,
reverse: false,
padding: Insets::ZERO,
on_scroll: None,
grain: 0.0,
content: Vec::new(),
}
}
/// Chooses the scrolling axis or axes; vertical by default.
pub fn axis(mut self, axis: Axis) -> Self {
self.axis = axis;
self
}
/// Scrolls **from the far end**: the content is anchored to the bottom of a
/// vertical viewport (the right of a horizontal one) and the area starts there.
///
/// It is what a conversation wants. Two things follow from it that nothing else
/// gives you:
///
/// - content **shorter** than the viewport sits at the bottom rather than the top;
/// - the area **stays** at the end when content arrives, because offsets are
/// measured from the end. A view resting at the newest message goes on resting
/// there, however many messages are appended.
///
/// Nothing changes for the user's hand: a finger pushes the content the way it
/// moves, in either direction, and the scrollbar's thumb rests where the content is.
pub fn reverse(mut self) -> Self {
self.reverse = true;
self
}
/// Overrides how this area behaves at its edges and after a fling.
///
/// Left unset, it follows the application's choice, which itself defaults to
/// what the running platform does — so setting this is for the cases where the
/// content wants a particular feel, not for making an app feel native.
pub fn physics(mut self, physics: ScrollPhysics) -> Self {
self.physics = Some(physics);
self
}
/// **Whether this area draws a scrollbar**, over the application's answer.
///
/// Left unset it follows the application, which itself follows the platform — so
/// setting this is for the one area that wants a bar where the platform gives none,
/// or none where it gives one, not for making an app feel native.
pub fn scrollbars(mut self, scrollbars: crate::physics::Scrollbars) -> Self {
self.scrollbars = Some(scrollbars);
self
}
/// **Keeps the scrollbar on screen** rather than letting it fade out when this area
/// stops moving (`scrollbar.dart:214`).
///
/// A bar over content earns its place by going away again; pin it for an area whose
/// content does not look scrollable, or one a reader should be able to aim at
/// without scrolling first to make the bar appear.
pub fn thumb_visibility(mut self, visible: bool) -> Self {
self.thumb_visibility = Some(visible);
self
}
/// Sets the viewport width, in logical pixels.
pub fn width(mut self, width: f32) -> Self {
self.width = Dimension::Length(width);
self.width_explicit = true;
self
}
/// Sets the viewport height, in logical pixels.
pub fn height(mut self, height: f32) -> Self {
self.height = Dimension::Length(height);
self.height_explicit = true;
self
}
/// Flex growth factor along the parent's main axis.
pub fn flex(mut self, grow: f32) -> Self {
self.flex_grow = grow;
self
}
/// Insets the content, **inside** the viewport: the padding scrolls with what it
/// surrounds rather than shrinking the window onto it.
///
/// That is the whole distinction, and it is the reference's: a scroll area padded at
/// the bottom has that room *at the end of its content*, reachable only by scrolling
/// to it, which is what a floating button hovering over the last row needs. Room
/// taken out of the viewport instead would sit there permanently and the last row
/// would still slide under the button.
///
/// Along the cross axis it simply insets the content, which stays the width of the
/// viewport less the two sides.
///
/// ```
/// # use frus_widgets::SingleChildScrollView;
/// # let feed = frus_widgets::Container::<()>::new();
/// SingleChildScrollView::<()>::new().padding_each(0.0, 16.0, 88.0, 16.0).child(feed);
/// ```
pub fn padding(mut self, padding: f32) -> Self {
self.padding = Insets::uniform(padding);
self
}
/// The same, one side at a time.
pub fn padding_each(mut self, top: f32, right: f32, bottom: f32, left: f32) -> Self {
self.padding = Insets::new(top, right, bottom, left);
self
}
/// **Says where this area is** whenever it moves — a "back to top" button that
/// appears once the page has gone down, a rule that fills as it goes, a load-more
/// when the end comes into view.
///
/// The area has to be reachable by name for a request to come back the other way:
/// wrap it in `keyed(k, …)` and address `k`, exactly as a focus request does.
///
/// A message per frame while it moves, which is what a bar fading in needs and what
/// a load-more does not; [`SingleChildScrollView::notify_every`] is for the second.
pub fn on_scroll<R: crate::callback::IntoMsg<Msg>>(
mut self,
on_scroll: impl Fn(crate::ScrollPosition) -> R + 'static,
) -> Self {
self.on_scroll = Some(Box::new(crate::callback::handler1(on_scroll)));
self
}
/// Reports no more often than every `px` of movement — and **always** reports where
/// it comes to rest, however short the last step was.
pub fn notify_every(mut self, px: f32) -> Self {
self.grain = px.max(0.0);
self
}
/// Sets the scrollable content.
pub fn child(mut self, content: impl Widget<Msg> + 'static) -> Self {
self.content.clear();
self.content.push(Box::new(content));
self
}
}
impl<Msg> Default for SingleChildScrollView<Msg> {
fn default() -> Self {
Self::new()
}
}
impl<Msg: Clone> Widget<Msg> for SingleChildScrollView<Msg> {
fn style(&self) -> Style {
// In **flex** mode (fill then scroll), an axis dimension that was not set
// explicitly must not serve as a basis: the default height of 200 would
// otherwise stay a flexible basis and the viewport would not fill the parent's
// remaining space — it would take `+200` of free room to grow. So we set it to
// `Auto`, a basis of 0, and let `flex_grow` **fill**.
let filling = self.flex_grow > 0.0;
let height = if filling && !self.height_explicit && self.axis.free_y() {
Dimension::Auto
} else {
self.height
};
let width = if filling && !self.width_explicit && self.axis.free_x() {
Dimension::Auto
} else {
self.width
};
// **A size nobody asked for, on an axis that does not scroll, is not ours to
// invent.** The 200 is the default *viewport* — the height of a window onto
// something taller — and it belongs to the axis that scrolls. A horizontal strip
// took it too, and claimed two hundred pixels for a bar forty-eight tall (#65).
// `Auto` here is the signal the layout reads to size this axis from the content;
// see the scroll branch of `build_layout_scoped`.
let height = if !self.height_explicit && !self.axis.free_y() {
Dimension::Auto
} else {
height
};
let width = if !self.width_explicit && !self.axis.free_x() {
Dimension::Auto
} else {
width
};
Style {
width,
height,
flex_grow: self.flex_grow,
..Default::default()
}
}
fn children(&self) -> &[Box<dyn Widget<Msg>>] {
&self.content
}
fn paint(&self, _bounds: Rect, _status: Status, _theme: &Theme, _scene: &mut Scene) {
// The viewport itself is transparent: only the content is drawn.
}
fn on_click(&self) -> Option<Msg> {
None
}
fn scrollbars(&self) -> Option<crate::physics::Scrollbars> {
self.scrollbars
}
fn thumb_visibility(&self) -> Option<bool> {
self.thumb_visibility
}
fn scroll_content(&self) -> Option<&dyn Widget<Msg>> {
self.content.first().map(|child| child.as_ref())
}
/// **All the room on offer across the axis it scrolls**, when nobody sized that axis
/// and it was not told to grow (milestone 590). Along the axis it scrolls, the layout
/// measures it: its content, up to the room.
fn fill_axes(&self, _theme: &Theme) -> crate::widget::FillAxes {
if self.flex_grow > 0.0 {
return crate::widget::FillAxes::NONE;
}
crate::widget::FillAxes {
horizontal: !self.axis.free_x() && !self.width_explicit,
vertical: !self.axis.free_y() && !self.height_explicit,
}
}
fn scroll_axis(&self) -> Axis {
self.axis
}
fn scroll_physics(&self) -> Option<ScrollPhysics> {
self.physics
}
fn scroll_reverse(&self) -> bool {
self.reverse
}
fn scroll_padding(&self) -> Insets {
self.padding
}
fn on_scroll(&self, position: crate::ScrollPosition) -> Option<Msg> {
self.on_scroll.as_ref().map(|report| report(position))
}
fn scroll_grain(&self) -> f32 {
self.grain
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{build_ui, Container, Runtime, Size};
use frus_core::{Color, Primitive};
const MARK: Color = Color::rgb(1.0, 0.0, 0.0);
/// **A viewport is as big as its content on the axis it does not scroll.**
///
/// The two hundred pixel default is the height of a *window onto something taller*, and
/// it belongs to the axis that scrolls. A horizontal area took it as well, which is how
/// a tab bar forty-eight pixels tall came to claim two hundred and push its panel down
/// the page (#65).
///
/// It cannot be answered by this widget alone: a scroll host lays its content out
/// against the viewport on the axis that does not scroll, so an `Auto` here would hand
/// the content nothing and get nothing back. `Auto` is the *signal*; the measurement
/// happens in the layout, where the content can be laid out on its own first.
#[test]
fn a_viewport_takes_its_content_s_size_on_the_axis_it_does_not_scroll() {
let strip = SingleChildScrollView::<()>::new()
.axis(Axis::Horizontal)
.child(Container::new().width(900.0).height(48.0).color(MARK));
let ui = build_ui(
&strip,
Size::new(300.0, 400.0),
&Runtime::default(),
&Theme::default(),
);
let box_ = ui.scene().primitives().iter().find_map(|p| match p {
Primitive::Rect { rect, .. } => Some(*rect),
_ => None,
});
assert_eq!(
box_.map(|r| r.height),
Some(48.0),
"the strip is its content's height, not the vertical default"
);
// And a caller's own number is still a caller's own number.
let told = SingleChildScrollView::<()>::new()
.axis(Axis::Horizontal)
.height(120.0)
.child(Container::new().width(900.0).height(48.0).color(MARK));
assert_eq!(
Widget::<()>::style(&told).height,
Dimension::Length(120.0),
"an explicit height is not measured away"
);
}
/// The vertical case of the same rule: an area that scrolls **down** takes its width
/// from what is in it. In a row it used to come out nothing wide, a leaf's content
/// being nothing at all.
#[test]
fn a_vertical_area_is_as_wide_as_its_content() {
let row = crate::Flex::<()>::row().child(
SingleChildScrollView::<()>::new()
.height(100.0)
.child(Container::new().width(160.0).height(400.0).color(MARK)),
);
let ui = build_ui(
&row,
Size::new(400.0, 400.0),
&Runtime::default(),
&Theme::default(),
);
let drawn = ui.scene().primitives().iter().find_map(|p| match p {
Primitive::Rect { rect, .. } => Some(*rect),
_ => None,
});
assert_eq!(drawn.map(|r| r.width), Some(160.0));
}
/// A scroll 100 tall holding `content_h` of content, at `offset`; returns the
/// rectangle of the marker drawn at the very end of that content.
fn last_mark(scroll: SingleChildScrollView<()>, offset: f32) -> Rect {
let mut runtime = Runtime::default();
let ui = build_ui(
&scroll,
Size::new(100.0, 100.0),
&runtime,
&Theme::default(),
);
let id = ui.scroll_regions()[0].id;
runtime.scroll.insert(id, (0.0, offset));
let ui = build_ui(
&scroll,
Size::new(100.0, 100.0),
&runtime,
&Theme::default(),
);
ui.scene()
.primitives()
.iter()
.filter_map(|p| match p {
Primitive::Rect { color, rect, .. } if *color == MARK => Some(*rect),
_ => None,
})
.next_back()
.expect("the marker is painted")
}
/// A column of `n` 40 px rows, the last one marked.
fn content(n: usize) -> Container<()> {
let mut column = crate::Flex::<()>::column();
for i in 0..n {
let colour = if i + 1 == n {
MARK
} else {
Color::rgb(0.0, 0.0, 1.0)
};
column = column.child(Container::<()>::new().height(40.0).color(colour));
}
Container::<()>::new().child(column)
}
/// Content shorter than the viewport sits at the **top** normally and at the
/// **bottom** reversed — the first of the two things reversing is for.
#[test]
fn short_content_sits_at_the_end_when_reversed() {
let plain = SingleChildScrollView::<()>::new()
.width(100.0)
.height(100.0)
.child(content(1));
assert_eq!(last_mark(plain, 0.0).y, 0.0, "at the top");
let reversed = SingleChildScrollView::<()>::new()
.width(100.0)
.height(100.0)
.reverse()
.child(content(1));
let r = last_mark(reversed, 0.0);
assert_eq!(r.y + r.height, 100.0, "against the bottom: {r:?}");
}
/// Offset 0 is the **end** of the content when reversed, and it stays the end
/// however much content there is — which is what keeps a conversation resting on
/// its newest message as messages arrive.
#[test]
fn offset_zero_is_the_end_and_stays_there() {
for rows in [4, 10, 40] {
let reversed = SingleChildScrollView::<()>::new()
.width(100.0)
.height(100.0)
.reverse()
.child(content(rows));
let r = last_mark(reversed, 0.0);
assert_eq!(
r.y + r.height,
100.0,
"{rows} rows, still resting at the end: {r:?}"
);
}
}
/// Scrolling away from zero walks **back** through the content, which is up the
/// screen for the newest-last layout a reversed view has.
#[test]
fn a_positive_offset_moves_back_through_the_content() {
let scroll = || {
SingleChildScrollView::<()>::new()
.width(100.0)
.height(100.0)
.reverse()
.child(content(10))
};
let at_rest = last_mark(scroll(), 0.0);
let scrolled = last_mark(scroll(), 60.0);
assert_eq!(
scrolled.y - at_rest.y,
60.0,
"the end has moved down and out of view"
);
}
/// The end of the content is the end of the *axis*, so a refusal there glows at the
/// bottom of a reversed area rather than the top — where a conversation's oldest
/// message is, and where the user is actually pressing.
#[test]
fn the_glow_follows_the_axis_and_not_the_screen() {
use frus_core::Rect as R;
let area = |reverse: bool| crate::Scrollable {
id: crate::WidgetId::ROOT,
viewport: R::new(0.0, 0.0, 100.0, 100.0),
max_x: 0.0,
max_y: 300.0,
axis: crate::scroll::Axis::Vertical,
physics: crate::ScrollPhysics::CLAMPING,
overscroll: Some(crate::OverscrollIndicator::Glow),
fling: frus_core::VelocityStrategy::Regression,
refresh: None,
page: None,
reverse_x: false,
reverse_y: reverse,
host: None,
keep_visible: None,
};
// A refusal towards the axis's start (a negative offset).
assert_eq!(area(false).refused_edge(true, -1.0), crate::GlowEdge::Top);
assert_eq!(
area(true).refused_edge(true, -1.0),
crate::GlowEdge::Bottom,
"the start of a reversed axis is the bottom of the screen"
);
// And a pull-to-refresh listens at whichever of the two that is.
assert_eq!(area(true).start_edge(true), crate::GlowEdge::Bottom);
}
/// The one thing that is *not* reversed: what the user's hand does. A push in a
/// direction moves the content that way in both, and only the arithmetic between
/// the push and the number changes sign.
#[test]
fn a_push_moves_the_content_the_way_it_pushes() {
let region = |reverse: bool| {
let mut s = SingleChildScrollView::<()>::new()
.width(100.0)
.height(100.0);
if reverse {
s = s.reverse();
}
let s = s.child(content(10));
let ui = build_ui(
&s,
Size::new(100.0, 100.0),
&Runtime::default(),
&Theme::default(),
);
ui.scroll_regions()[0]
};
// A finger pushing the content **down** by 10 px.
assert_eq!(region(false).offset_delta((0.0, 10.0)).1, -10.0);
assert_eq!(region(true).offset_delta((0.0, 10.0)).1, 10.0);
// Opposite numbers, and in both cases "the content went down": one counts from
// the top and the other from the bottom.
}
}
#[cfg(test)]
mod padding_tests {
use super::*;
use crate::{build_ui, Container, Runtime, Size};
use frus_core::{Color, Primitive};
const MARK: Color = Color::rgb(1.0, 0.0, 0.0);
/// The box the content painted.
fn content_rect(scroll: &SingleChildScrollView<()>) -> Rect {
build_ui(
scroll,
Size::new(100.0, 100.0),
&Runtime::default(),
&Theme::default(),
)
.scene()
.primitives()
.iter()
.find_map(|p| match p {
Primitive::Rect { rect, color, .. } if *color == MARK => Some(*rect),
_ => None,
})
.expect("the content is painted")
}
fn area(height: f32) -> SingleChildScrollView<()> {
SingleChildScrollView::<()>::new()
.width(100.0)
.height(100.0)
.child(Container::<()>::new().height(height).color(MARK))
}
/// The leading insets move the content in; the sides come off its width, which is
/// otherwise the viewport's.
#[test]
fn the_content_starts_inside_the_insets() {
let bare = content_rect(&area(50.0));
assert_eq!((bare.x, bare.y, bare.width), (0.0, 0.0, 100.0));
let padded = content_rect(&area(50.0).padding_each(12.0, 8.0, 24.0, 8.0));
assert_eq!((padded.x, padded.y), (8.0, 12.0));
assert_eq!(padded.width, 84.0, "the sides come off the content");
}
/// The room is inside the viewport and scrolls with the content: it joins what there
/// is to scroll rather than being taken out of the window.
#[test]
fn the_far_inset_is_reachable_rather_than_lost() {
let region = |scroll: &SingleChildScrollView<()>| {
build_ui(
scroll,
Size::new(100.0, 100.0),
&Runtime::default(),
&Theme::default(),
)
.scroll_regions()[0]
.max_y
};
assert_eq!(
region(&area(100.0)),
0.0,
"exactly fills: nothing to scroll"
);
assert_eq!(
region(&area(100.0).padding_each(12.0, 0.0, 24.0, 0.0)),
36.0,
"both insets joined the content"
);
}
/// A reversed area rests at the end, and the end is one bottom inset up.
#[test]
fn a_reversed_area_rests_above_its_bottom_inset() {
let padded = content_rect(&area(50.0).reverse().padding_each(12.0, 0.0, 24.0, 0.0));
assert_eq!(
padded.y + padded.height,
76.0,
"the content ends one bottom inset above the viewport's edge"
);
}
}
/// Milestone 533: content that shrinks under an offset it no longer reaches. Seen on a
/// phone as a row of filters that overflowed at a large text size, was swiped to its end,
/// and stayed swiped — its first label cut at the left, empty room at the right — once the
/// text was small again and the row fitted.
#[cfg(test)]
mod shrunk_content_tests {
use super::*;
use crate::{build_ui, Container, ListView, PageView, Runtime, Size, Ui};
use frus_core::{Color, Primitive};
const MARK: Color = Color::rgb(1.0, 0.0, 0.0);
const FRAME: f32 = 1.0 / 60.0;
/// A strip 100 wide and 40 tall holding one marked box `width` wide: the demo's filter
/// row, reduced to its geometry.
fn strip(width: f32) -> SingleChildScrollView<()> {
SingleChildScrollView::<()>::new()
.axis(Axis::Horizontal)
.width(100.0)
.height(40.0)
.child(Container::<()>::new().width(width).height(40.0).color(MARK))
}
/// A list 200 tall of `count` marked rows, 40 each.
fn rows(count: usize) -> ListView<()> {
ListView::<()>::new(count, 40.0, |_| {
Container::<()>::new().height(40.0).color(MARK)
})
.width(100.0)
.height(200.0)
}
fn frame(widget: &dyn Widget<()>, runtime: &Runtime) -> Ui<()> {
build_ui(widget, Size::new(300.0, 400.0), runtime, &Theme::default())
}
/// Every rectangle painted in `color`, in paint order.
fn painted(ui: &Ui<()>, color: Color) -> Vec<Rect> {
ui.scene()
.primitives()
.iter()
.filter_map(|p| match p {
Primitive::Rect { rect, color: c, .. } if *c == color => Some(*rect),
_ => None,
})
.collect()
}
/// One turn of the shell's loop over `ui`'s regions.
fn step(runtime: &mut Runtime, ui: &Ui<()>) {
let regions = ui.scroll_regions().to_vec();
runtime.advance_scroll(®ions, FRAME);
}
/// The phone's report: the row fits again and is drawn from its start, in the frame it
/// fits — and the runtime keeps it there.
#[test]
fn a_row_that_fits_again_is_drawn_from_its_start() {
let mut runtime = Runtime::default();
let wide = strip(300.0);
let id = frame(&wide, &runtime).scroll_regions()[0].id;
// Swiped to the end, and the swipe has settled: nothing owns the offset now.
runtime.scroll.insert(id, (200.0, 0.0));
let ui = frame(&wide, &runtime);
assert_eq!(painted(&ui, MARK)[0].x, -200.0, "the end of the row shows");
step(&mut runtime, &ui);
let narrow = strip(80.0);
let ui = frame(&narrow, &runtime);
assert_eq!(ui.scroll_regions()[0].max_x, 0.0, "nothing left to scroll");
assert_eq!(
painted(&ui, MARK)[0].x,
0.0,
"drawn from its start in the very frame it fits"
);
step(&mut runtime, &ui);
assert_eq!(runtime.scroll.get(&id), Some(&(0.0, 0.0)));
assert_eq!(painted(&frame(&narrow, &runtime), MARK)[0].x, 0.0);
}
/// Shrunk, but still too wide: it rests at its new end, not at its start.
#[test]
fn a_row_that_still_overflows_rests_at_its_new_end() {
let mut runtime = Runtime::default();
let wide = strip(300.0);
let id = frame(&wide, &runtime).scroll_regions()[0].id;
runtime.scroll.insert(id, (200.0, 0.0));
// A few frames at the end first, so the scrollbar's fade has seen the offset.
for _ in 0..3 {
let ui = frame(&wide, &runtime);
step(&mut runtime, &ui);
}
let narrower = strip(150.0);
let ui = frame(&narrower, &runtime);
let mark = painted(&ui, MARK)[0];
assert_eq!(
(mark.x, mark.x + mark.width),
(-50.0, 100.0),
"its last pixel on the viewport's right edge"
);
for _ in 0..10 {
let ui = frame(&narrower, &runtime);
step(&mut runtime, &ui);
}
assert_eq!(runtime.scroll.get(&id), Some(&(50.0, 0.0)));
// Nothing scrolled: the content changed. A bar that arrived for it would say
// otherwise.
assert_eq!(
runtime.scrollbar_fade_of(id).opacity,
0.0,
"no bar summoned"
);
}
/// The same down the screen: a list scrolled to its bottom that loses rows.
#[test]
fn a_list_that_loses_rows_keeps_its_last_row_on_the_floor() {
let mut runtime = Runtime::default();
let id = frame(&rows(10), &runtime).scroll_regions()[0].id;
runtime.scroll.insert(id, (0.0, 200.0));
// Six rows, 240 of content: the bottom is 40 down.
let ui = frame(&rows(6), &runtime);
let last = painted(&ui, MARK)
.into_iter()
.max_by(|a, b| a.y.total_cmp(&b.y))
.expect("a row is painted");
assert_eq!(last.y + last.height, 200.0, "the last row on the floor");
step(&mut runtime, &ui);
assert_eq!(runtime.scroll.get(&id), Some(&(0.0, 40.0)));
// Three rows fit: back to the top.
let ui = frame(&rows(3), &runtime);
let first = painted(&ui, MARK)
.into_iter()
.min_by(|a, b| a.y.total_cmp(&b.y))
.expect("a row is painted");
assert_eq!(first.y, 0.0);
assert_eq!(painted(&ui, MARK).len(), 3, "every row shows");
step(&mut runtime, &ui);
assert_eq!(runtime.scroll.get(&id), Some(&(0.0, 0.0)));
}
/// A paged view that loses pages while on its last one shows its new last page.
#[test]
fn a_paged_view_that_loses_pages_shows_its_new_last_page() {
let shade = |index: usize| Color::rgb(0.0, 0.0, (index + 1) as f32 / 10.0);
let pages = |count: usize| {
PageView::<()>::new(count, move |index| {
Container::<()>::new().color(shade(index))
})
.width(300.0)
.height(400.0)
};
let mut runtime = Runtime::default();
let id = frame(&pages(5), &runtime).scroll_regions()[0].id;
runtime.scroll.insert(id, (1200.0, 0.0));
assert_eq!(painted(&frame(&pages(5), &runtime), shade(4))[0].x, 0.0);
let ui = frame(&pages(2), &runtime);
assert_eq!(
painted(&ui, shade(1)).first().map(|r| r.x),
Some(0.0),
"page 1 fills the viewport"
);
assert!(painted(&ui, shade(4)).is_empty(), "no page past the end");
step(&mut runtime, &ui);
assert_eq!(runtime.scroll.get(&id), Some(&(300.0, 0.0)));
}
/// A reversed strip counts its offset from the right. The range is the same, so the
/// correction is too — and the content lands against the left edge, not off to the right.
#[test]
fn a_reversed_row_is_brought_back_the_same_way() {
let mut runtime = Runtime::default();
let wide = strip(300.0).reverse();
let id = frame(&wide, &runtime).scroll_regions()[0].id;
runtime.scroll.insert(id, (200.0, 0.0));
assert_eq!(
painted(&frame(&wide, &runtime), MARK)[0].x,
0.0,
"its start shows"
);
let narrower = strip(150.0).reverse();
let ui = frame(&narrower, &runtime);
assert_eq!(
painted(&ui, MARK)[0].x,
0.0,
"its start against the left edge: {:?}",
painted(&ui, MARK)
);
step(&mut runtime, &ui);
assert_eq!(runtime.scroll.get(&id), Some(&(50.0, 0.0)));
}
/// A finger owns the offset: the content shrinking under it moves nothing, in the
/// picture or the runtime, until it lets go — and then the release brings it home.
#[test]
fn a_held_row_is_not_yanked_from_under_the_finger() {
let mut runtime = Runtime::default();
let wide = strip(300.0);
let id = frame(&wide, &runtime).scroll_regions()[0].id;
runtime.scroll.insert(id, (200.0, 0.0));
runtime.hold_scroll(id);
let narrower = strip(150.0);
for _ in 0..10 {
let ui = frame(&narrower, &runtime);
assert_eq!(painted(&ui, MARK)[0].x, -200.0, "where the finger left it");
step(&mut runtime, &ui);
}
assert_eq!(runtime.scroll.get(&id), Some(&(200.0, 0.0)));
runtime.release_scroll(id);
let area = frame(&narrower, &runtime).scroll_regions()[0];
assert!(
runtime.fling_scroll(area, ScrollPhysics::CLAMPING, (0.0, 0.0)),
"a release out of range springs"
);
for _ in 0..600 {
let ui = frame(&narrower, &runtime);
step(&mut runtime, &ui);
}
let rest = runtime.scroll.get(&id).copied().unwrap_or_default();
assert!((rest.0 - 50.0).abs() < 1.0, "home at the new end: {rest:?}");
}
}